hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
73b17a94db8e98090e8472d125a66922f9fac2f0
594
cpp
C++
3 - Branches/3.10 - Character operations/isdigit/isdigit.cpp
aTonyXiao/Zybook
36cd05a436c6ca007cdd14638cf5ee2a7724b889
[ "MIT" ]
11
2017-11-17T07:31:44.000Z
2020-12-05T14:46:56.000Z
3 - Branches/3.10 - Character operations/isdigit/isdigit.cpp
aTonyXiao/Zybook
36cd05a436c6ca007cdd14638cf5ee2a7724b889
[ "MIT" ]
null
null
null
3 - Branches/3.10 - Character operations/isdigit/isdigit.cpp
aTonyXiao/Zybook
36cd05a436c6ca007cdd14638cf5ee2a7724b889
[ "MIT" ]
1
2019-10-15T20:58:51.000Z
2019-10-15T20:58:51.000Z
#include <iostream> #include <string> #include <cctype> using namespace std; // true if digit: 0-9. /* isdigit('x') // false isdigit('6') // true */ int main(){ string myString_1 = "?"; bool hasDigit = 0; //ask for username cout << "Enter name: "; getline(cin, myString_1); //check username for numbers for(unsigned int i = 0; i < myString_1.length(); i++){ hasDigit = hasDigit + isdigit(myString_1.at(i)); } //display output if(hasDigit){ cout << "Error: use only letters." << endl; } else{ cout << "Welcome, " << myString_1 << endl; } cout << endl; return 0; }
15.631579
55
0.616162
aTonyXiao
73b34e6e36e7449a7906958971fc50d36f7bcb94
4,685
cpp
C++
tests/dummy.cpp
KPO-2020-2021/zad3-Ploneczka
37f6db13449d1a0d3efe652ff1e9b92f8a9166bf
[ "Unlicense" ]
null
null
null
tests/dummy.cpp
KPO-2020-2021/zad3-Ploneczka
37f6db13449d1a0d3efe652ff1e9b92f8a9166bf
[ "Unlicense" ]
null
null
null
tests/dummy.cpp
KPO-2020-2021/zad3-Ploneczka
37f6db13449d1a0d3efe652ff1e9b92f8a9166bf
[ "Unlicense" ]
null
null
null
#include "../tests/doctest/doctest.h" #include "example.h" #include "vector.hh" #include <sstream> #include "rectangle.hh" // Tests that don't naturally fit in the headers/.cpp files directly // can be placed in a tests/*.cpp file. Integration tests are a good example. TEST_CASE("konskruktor domyslny") { Vector v1,v2; v2[0]=0; v2[1]=0; CHECK_EQ(v1, v2); } TEST_CASE("konskruktor parametryczny") { double a[2] = {1,1}; Vector v1(a),v2; v2[0]=1; v2[1]=1; CHECK_EQ(v1, v2); } TEST_CASE("dodawanie") { Vector v1,v2,v3; v1[0]=3; v1[1]=2; v2[0]=6; v2[1]=4; v3[0]=9; v3[1]=6; CHECK_EQ(v1+v2, v3); } TEST_CASE("mnozenie") { Vector v1,v2; v1[0]=1; v1[1]=5; v2[0]=2; v2[1]=10; CHECK_EQ(v1*2, v2); } TEST_CASE("dzielenie") { Vector v1,v2; v1[0]=6; v1[1]=4; v2[0]=3; v2[1]=2; CHECK_EQ(v1/2, v2); } TEST_CASE("odejmowanie") { Vector v1,v2,v3; v1[0]=3; v1[1]=2; v2[0]=1; v2[1]=4; v3[0]=2; v3[1]=-2; CHECK_EQ(v1-v2, v3); } TEST_CASE("miejsca po przecinku") { Vector v1,v2; v1[0]=3; v1[1]=2.7548945; v2[0]=3; v2[1]=2.7548945; CHECK_EQ(v1, v2); } TEST_CASE("<<") { std::stringstream ss; Vector a1; ss << a1; CHECK_EQ(ss.str(), "0 0 "); } TEST_CASE(">>") { std::stringstream ss; Vector a1, a2; ss<<"1 1 "; ss >> a1; a2[0]= 1; a2[1] = 1; CHECK_EQ(a1, a2); } TEST_CASE("indeks") { Vector a1; a1[0] = 0; a1[1] = 3; CHECK_EQ(a1[1], 3); } TEST_CASE("poza indeks") { Vector a1; a1[0] = 0; a1[1] = 3; WARN_THROWS(a1[2]); } TEST_CASE("indeks z consta") { Vector a1; const double b = a1[0]; CHECK_EQ(b, 0); } TEST_CASE("Macierz domyslny") { Matrix m1,m2; m2(0,0) = 0; m2(0,1) = 0; m2(1,0) = 0; m2(1,1) = 0; CHECK_EQ(m1, m2); } TEST_CASE("Macierz parametryczna") { double dwu[2][2]; dwu[0][0] = 0; dwu[0][1] = 0; dwu[1][0] = 0; dwu[1][1] = 0; Matrix m1,m2(dwu); CHECK_EQ(m1, m2); } TEST_CASE("Macierz x Wektor") { Matrix m1; Vector a1, wynik; wynik[0] = 7; wynik[1] = 9; a1[0] = 1; a1[1] = 3; m1(0,0) = 1; m1(0,1) = 2; m1(1,0) = 3; m1(1,1) = 2; CHECK_EQ(m1*a1, wynik); } TEST_CASE("Macierz indeks bez const") { Matrix m1; m1(0,0) = 1; m1(0,1) = 2; m1(1,0) = 3; m1(1,1) = 2; CHECK_EQ(m1(1,0), 3); } TEST_CASE("Macierz indeks z consta") { Matrix m1; const double b = m1(0,0); CHECK_EQ(b, 0); } TEST_CASE("Macierz obrotu") { Vector a1,a2; a1[0]=1; a1[1]=1; a1 = a1.rotacja(180); a2[0]=-1; a2[1]=-1; CHECK_EQ(a1, a2); } TEST_CASE("Prostokat bez parametryczny") { rectangle rec1, rec2; CHECK_EQ(rec1, rec2); } TEST_CASE("Prostokat parametryczny") { Vector ve1,ve2,ve3,ve4; rectangle rec1, rec2(ve1,ve2,ve3,ve4); CHECK_EQ(rec1, rec2); } TEST_CASE("Prostokat translacja") { Vector ve1,ve2,ve3,ve4, vek1, vek2, vek3, vek4, przesun; przesun[0]= 1; przesun[1]= 1; ve1[0] = 0; ve1[1] = 0; ve2[0] = 3; ve2[1] = 0; ve3[0] = 3; ve3[1] = 2; ve4[0] = 0; ve4[1] = 2; vek1[0] = 1; vek1[1] = 1; vek2[0] = 4; vek2[1] = 1; vek3[0] = 4; vek3[1] = 3; vek4[0] = 1; vek4[1] = 3; rectangle rec1(vek1,vek2,vek3,vek4), rec2(ve1+przesun, ve2+przesun, ve3+przesun, ve4+przesun); CHECK_EQ(rec1, rec2); } TEST_CASE("prostokat rotacja") { Vector ve1,ve2,ve3,ve4, vek1, vek2, vek3, vek4; double kat = 180; ve1[0] = 0; ve1[1] = 0; ve2[0] = 3; ve2[1] = 0; ve3[0] = 3; ve3[1] = 3; ve4[0] = 0; ve4[1] = 3; vek1[0] = 0; vek1[1] = 0; vek2[0] = -3; vek2[1] = 0; vek3[0] = -3; vek3[1] = -3; vek4[0] = 0; vek4[1] = -3; rectangle rec(ve1,ve2,ve3,ve4), rec7(vek1, vek2, vek3, vek4); CHECK_EQ(rec.rotacja(kat), rec7); } TEST_CASE("prostokat rotacja, kat ujemny") { Vector ve1,ve2,ve3,ve4, vek1, vek2, vek3, vek4; double kat = -90; ve1[0] = 0; ve1[1] = 0; ve2[0] = 3; ve2[1] = 0; ve3[0] = 3; ve3[1] = 3; ve4[0] = 0; ve4[1] = 3; vek1[0] = 0; vek1[1] = 0; vek2[0] = 0; vek2[1] = -3; vek3[0] = 3; vek3[1] = -3; vek4[0] = 3; vek4[1] = 0; rectangle rec(ve1,ve2,ve3,ve4), rec7(vek1, vek2, vek3, vek4); CHECK_EQ(rec.rotacja(kat), rec7); } TEST_CASE("nierowne boki prostokata") { Vector vek1, vek2, vek3, vek4; vek1[0] = 0; vek1[1] = 0; vek2[0] = 2; vek2[1] = -3; vek3[0] =26; vek3[1] = -3; vek4[0] = 992; vek4[1] = 7; rectangle rec(vek1, vek2, vek3, vek4); CHECK_FALSE(rec.sprawdz_boki()); } TEST_CASE("rowne boki prostokata") { Vector vek1, vek2, vek3, vek4; vek1[0] = 0; vek1[1] = 0; vek2[0] = 3; vek2[1] = 0; vek3[0] = 3; vek3[1] = 2; vek4[0] = 0; vek4[1] = 2; rectangle rec(vek1, vek2, vek3, vek4); CHECK_FALSE(!rec.sprawdz_boki()); }
16.044521
96
0.553042
KPO-2020-2021
73b7a24324dafbb415cc3222773c61fc33256d44
10,307
cpp
C++
runtime/file.cpp
JessicaGabriela/PROYECTO
f02c784174e028cc935b2d924309afbb690e9308
[ "Apache-2.0" ]
1
2022-01-06T15:44:48.000Z
2022-01-06T15:44:48.000Z
runtime/file.cpp
JessicaGabriela/PROYECTO
f02c784174e028cc935b2d924309afbb690e9308
[ "Apache-2.0" ]
2
2019-06-27T00:36:28.000Z
2021-06-29T20:05:03.000Z
runtime/file.cpp
JessicaGabriela/PROYECTO
f02c784174e028cc935b2d924309afbb690e9308
[ "Apache-2.0" ]
null
null
null
//===-- runtime/file.cpp ----------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "file.h" #include "magic-numbers.h" #include "memory.h" #include <algorithm> #include <cerrno> #include <cstring> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #ifdef _WIN32 #define NOMINMAX #include <io.h> #include <windows.h> #else #include <unistd.h> #endif namespace Fortran::runtime::io { void OpenFile::set_path(OwningPtr<char> &&path, std::size_t bytes) { path_ = std::move(path); pathLength_ = bytes; } static int openfile_mkstemp(IoErrorHandler &handler) { #ifdef _WIN32 const unsigned int uUnique{0}; // GetTempFileNameA needs a directory name < MAX_PATH-14 characters in length. // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamea char tempDirName[MAX_PATH - 14]; char tempFileName[MAX_PATH]; unsigned long nBufferLength{sizeof(tempDirName)}; nBufferLength = ::GetTempPathA(nBufferLength, tempDirName); if (nBufferLength > sizeof(tempDirName) || nBufferLength == 0) { return -1; } if (::GetTempFileNameA(tempDirName, "Fortran", uUnique, tempFileName) == 0) { return -1; } int fd{::_open(tempFileName, _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE)}; #else char path[]{"/tmp/Fortran-Scratch-XXXXXX"}; int fd{::mkstemp(path)}; #endif if (fd < 0) { handler.SignalErrno(); } #ifndef _WIN32 ::unlink(path); #endif return fd; } void OpenFile::Open(OpenStatus status, std::optional<Action> action, Position position, IoErrorHandler &handler) { if (fd_ >= 0 && (status == OpenStatus::Old || status == OpenStatus::Unknown)) { return; } if (fd_ >= 0) { if (fd_ <= 2) { // don't actually close a standard file descriptor, we might need it } else { if (::close(fd_) != 0) { handler.SignalErrno(); } } fd_ = -1; } if (status == OpenStatus::Scratch) { if (path_.get()) { handler.SignalError("FILE= must not appear with STATUS='SCRATCH'"); path_.reset(); } if (!action) { action = Action::ReadWrite; } fd_ = openfile_mkstemp(handler); } else { if (!path_.get()) { handler.SignalError("FILE= is required"); return; } int flags{0}; if (status != OpenStatus::Old) { flags |= O_CREAT; } if (status == OpenStatus::New) { flags |= O_EXCL; } else if (status == OpenStatus::Replace) { flags |= O_TRUNC; } if (!action) { // Try to open read/write, back off to read-only on failure fd_ = ::open(path_.get(), flags | O_RDWR, 0600); if (fd_ >= 0) { action = Action::ReadWrite; } else { action = Action::Read; } } if (fd_ < 0) { switch (*action) { case Action::Read: flags |= O_RDONLY; break; case Action::Write: flags |= O_WRONLY; break; case Action::ReadWrite: flags |= O_RDWR; break; } fd_ = ::open(path_.get(), flags, 0600); if (fd_ < 0) { handler.SignalErrno(); } } } RUNTIME_CHECK(handler, action.has_value()); pending_.reset(); if (position == Position::Append && !RawSeekToEnd()) { handler.SignalErrno(); } isTerminal_ = ::isatty(fd_) == 1; mayRead_ = *action != Action::Write; mayWrite_ = *action != Action::Read; if (status == OpenStatus::Old || status == OpenStatus::Unknown) { knownSize_.reset(); #ifndef _WIN32 struct stat buf; if (::fstat(fd_, &buf) == 0) { mayPosition_ = S_ISREG(buf.st_mode); knownSize_ = buf.st_size; } #else // TODO: _WIN32 mayPosition_ = true; #endif } else { knownSize_ = 0; mayPosition_ = true; } } void OpenFile::Predefine(int fd) { fd_ = fd; path_.reset(); pathLength_ = 0; position_ = 0; knownSize_.reset(); nextId_ = 0; pending_.reset(); mayRead_ = fd == 0; mayWrite_ = fd != 0; mayPosition_ = false; } void OpenFile::Close(CloseStatus status, IoErrorHandler &handler) { CheckOpen(handler); pending_.reset(); knownSize_.reset(); switch (status) { case CloseStatus::Keep: break; case CloseStatus::Delete: if (path_.get()) { ::unlink(path_.get()); } break; } path_.reset(); if (fd_ >= 0) { if (::close(fd_) != 0) { handler.SignalErrno(); } fd_ = -1; } } std::size_t OpenFile::Read(FileOffset at, char *buffer, std::size_t minBytes, std::size_t maxBytes, IoErrorHandler &handler) { if (maxBytes == 0) { return 0; } CheckOpen(handler); if (!Seek(at, handler)) { return 0; } minBytes = std::min(minBytes, maxBytes); std::size_t got{0}; while (got < minBytes) { auto chunk{::read(fd_, buffer + got, maxBytes - got)}; if (chunk == 0) { handler.SignalEnd(); break; } else if (chunk < 0) { auto err{errno}; if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { handler.SignalError(err); break; } } else { position_ += chunk; got += chunk; } } return got; } std::size_t OpenFile::Write(FileOffset at, const char *buffer, std::size_t bytes, IoErrorHandler &handler) { if (bytes == 0) { return 0; } CheckOpen(handler); if (!Seek(at, handler)) { return 0; } std::size_t put{0}; while (put < bytes) { auto chunk{::write(fd_, buffer + put, bytes - put)}; if (chunk >= 0) { position_ += chunk; put += chunk; } else { auto err{errno}; if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { handler.SignalError(err); break; } } } if (knownSize_ && position_ > *knownSize_) { knownSize_ = position_; } return put; } inline static int openfile_ftruncate(int fd, OpenFile::FileOffset at) { #ifdef _WIN32 return !::_chsize(fd, at); #else return ::ftruncate(fd, at); #endif } void OpenFile::Truncate(FileOffset at, IoErrorHandler &handler) { CheckOpen(handler); if (!knownSize_ || *knownSize_ != at) { if (openfile_ftruncate(fd_, at) != 0) { handler.SignalErrno(); } knownSize_ = at; } } // The operation is performed immediately; the results are saved // to be claimed by a later WAIT statement. // TODO: True asynchronicity int OpenFile::ReadAsynchronously( FileOffset at, char *buffer, std::size_t bytes, IoErrorHandler &handler) { CheckOpen(handler); int iostat{0}; for (std::size_t got{0}; got < bytes;) { #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L auto chunk{::pread(fd_, buffer + got, bytes - got, at)}; #else auto chunk{Seek(at, handler) ? ::read(fd_, buffer + got, bytes - got) : -1}; #endif if (chunk == 0) { iostat = FORTRAN_RUNTIME_IOSTAT_END; break; } if (chunk < 0) { auto err{errno}; if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { iostat = err; break; } } else { at += chunk; got += chunk; } } return PendingResult(handler, iostat); } // TODO: True asynchronicity int OpenFile::WriteAsynchronously(FileOffset at, const char *buffer, std::size_t bytes, IoErrorHandler &handler) { CheckOpen(handler); int iostat{0}; for (std::size_t put{0}; put < bytes;) { #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L auto chunk{::pwrite(fd_, buffer + put, bytes - put, at)}; #else auto chunk{ Seek(at, handler) ? ::write(fd_, buffer + put, bytes - put) : -1}; #endif if (chunk >= 0) { at += chunk; put += chunk; } else { auto err{errno}; if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { iostat = err; break; } } } return PendingResult(handler, iostat); } void OpenFile::Wait(int id, IoErrorHandler &handler) { std::optional<int> ioStat; Pending *prev{nullptr}; for (Pending *p{pending_.get()}; p; p = (prev = p)->next.get()) { if (p->id == id) { ioStat = p->ioStat; if (prev) { prev->next.reset(p->next.release()); } else { pending_.reset(p->next.release()); } break; } } if (ioStat) { handler.SignalError(*ioStat); } } void OpenFile::WaitAll(IoErrorHandler &handler) { while (true) { int ioStat; if (pending_) { ioStat = pending_->ioStat; pending_.reset(pending_->next.release()); } else { return; } handler.SignalError(ioStat); } } void OpenFile::CheckOpen(const Terminator &terminator) { RUNTIME_CHECK(terminator, fd_ >= 0); } bool OpenFile::Seek(FileOffset at, IoErrorHandler &handler) { if (at == position_) { return true; } else if (RawSeek(at)) { position_ = at; return true; } else { handler.SignalErrno(); return false; } } bool OpenFile::RawSeek(FileOffset at) { #ifdef _LARGEFILE64_SOURCE return ::lseek64(fd_, at, SEEK_SET) == at; #else return ::lseek(fd_, at, SEEK_SET) == at; #endif } bool OpenFile::RawSeekToEnd() { #ifdef _LARGEFILE64_SOURCE std::int64_t at{::lseek64(fd_, 0, SEEK_END)}; #else std::int64_t at{::lseek(fd_, 0, SEEK_END)}; #endif if (at >= 0) { knownSize_ = at; return true; } else { return false; } } int OpenFile::PendingResult(const Terminator &terminator, int iostat) { int id{nextId_++}; pending_ = New<Pending>{terminator}(id, iostat, std::move(pending_)); return id; } bool IsATerminal(int fd) { return ::isatty(fd); } #ifdef WIN32 // Access flags are normally defined in unistd.h, which unavailable under // Windows. Instead, define the flags as documented at // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/access-waccess #define F_OK 00 #define W_OK 02 #define R_OK 04 #endif bool IsExtant(const char *path) { return ::access(path, F_OK) == 0; } bool MayRead(const char *path) { return ::access(path, R_OK) == 0; } bool MayWrite(const char *path) { return ::access(path, W_OK) == 0; } bool MayReadAndWrite(const char *path) { return ::access(path, R_OK | W_OK) == 0; } } // namespace Fortran::runtime::io
24.776442
91
0.601242
JessicaGabriela
73bd1bd881cd6bddf3aea5261316570f8a5ef5fe
9,811
cpp
C++
src/Magnum/Trade/PbrClearCoatMaterialData.cpp
RyanSamlalsingh/magnum
f80b238e2776b7c1fb60541b0d26b08ee488b735
[ "MIT" ]
null
null
null
src/Magnum/Trade/PbrClearCoatMaterialData.cpp
RyanSamlalsingh/magnum
f80b238e2776b7c1fb60541b0d26b08ee488b735
[ "MIT" ]
null
null
null
src/Magnum/Trade/PbrClearCoatMaterialData.cpp
RyanSamlalsingh/magnum
f80b238e2776b7c1fb60541b0d26b08ee488b735
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Vladimír Vondruš <mosra@centrum.cz> 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 "PbrClearCoatMaterialData.h" namespace Magnum { namespace Trade { bool PbrClearCoatMaterialData::hasLayerFactorRoughnessTexture() const { return hasAttribute(MaterialAttribute::LayerFactorTexture) && hasAttribute(MaterialAttribute::RoughnessTexture) && attribute<UnsignedInt>(MaterialAttribute::LayerFactorTexture) == attribute<UnsignedInt>(MaterialAttribute::RoughnessTexture) && layerFactorTextureSwizzle() == MaterialTextureSwizzle::R && roughnessTextureSwizzle() == MaterialTextureSwizzle::G && layerFactorTextureMatrix() == roughnessTextureMatrix() && layerFactorTextureCoordinates() == roughnessTextureCoordinates(); } bool PbrClearCoatMaterialData::hasTextureTransformation() const { return hasAttribute(MaterialAttribute::LayerFactorTextureMatrix) || hasAttribute(MaterialAttribute::RoughnessTextureMatrix) || hasAttribute(MaterialAttribute::NormalTextureMatrix) || hasAttribute(MaterialAttribute::TextureMatrix) || hasAttribute(0, MaterialAttribute::TextureMatrix); } bool PbrClearCoatMaterialData::hasCommonTextureTransformation() const { auto check = [](Containers::Optional<Matrix3>& transformation, Matrix3 current) { if(!transformation) { transformation = current; return true; } return transformation == current; }; Containers::Optional<Matrix3> transformation; /* First one can't fail */ if(hasAttribute(MaterialAttribute::LayerFactorTexture) && !check(transformation, layerFactorTextureMatrix())) CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ if(hasAttribute(MaterialAttribute::RoughnessTexture) && !check(transformation, roughnessTextureMatrix())) return false; if(hasAttribute(MaterialAttribute::NormalTexture) && !check(transformation, normalTextureMatrix())) return false; return true; } bool PbrClearCoatMaterialData::hasTextureCoordinates() const { return hasAttribute(MaterialAttribute::LayerFactorTextureCoordinates) || hasAttribute(MaterialAttribute::RoughnessTextureCoordinates) || hasAttribute(MaterialAttribute::NormalTextureCoordinates) || hasAttribute(MaterialAttribute::TextureCoordinates) || hasAttribute(0, MaterialAttribute::TextureCoordinates); } bool PbrClearCoatMaterialData::hasCommonTextureCoordinates() const { auto check = [](Containers::Optional<UnsignedInt>& coordinates, UnsignedInt current) { if(!coordinates) { coordinates = current; return true; } return coordinates == current; }; Containers::Optional<UnsignedInt> coordinates; /* First one can't fail */ if(hasAttribute(MaterialAttribute::LayerFactorTexture) && !check(coordinates, layerFactorTextureCoordinates())) CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ if(hasAttribute(MaterialAttribute::RoughnessTexture) && !check(coordinates, roughnessTextureCoordinates())) return false; if(hasAttribute(MaterialAttribute::NormalTexture) && !check(coordinates, normalTextureCoordinates())) return false; return true; } Float PbrClearCoatMaterialData::roughness() const { return attributeOr(MaterialAttribute::Roughness, 0.0f); } UnsignedInt PbrClearCoatMaterialData::roughnessTexture() const { return attribute<UnsignedInt>(MaterialAttribute::RoughnessTexture); } MaterialTextureSwizzle PbrClearCoatMaterialData::roughnessTextureSwizzle() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::RoughnessTexture), "Trade::PbrClearCoatMaterialData::roughnessTextureSwizzle(): the layer doesn't have a roughness texture", {}); return attributeOr(MaterialAttribute::RoughnessTextureSwizzle, MaterialTextureSwizzle::R); } Matrix3 PbrClearCoatMaterialData::roughnessTextureMatrix() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::RoughnessTexture), "Trade::PbrClearCoatMaterialData::roughnessTextureMatrix(): the layer doesn't have a roughness texture", {}); if(Containers::Optional<Matrix3> value = tryAttribute<Matrix3>(MaterialAttribute::RoughnessTextureMatrix)) return *value; if(Containers::Optional<Matrix3> value = tryAttribute<Matrix3>(MaterialAttribute::TextureMatrix)) return *value; return attributeOr(0, MaterialAttribute::TextureMatrix, Matrix3{}); } UnsignedInt PbrClearCoatMaterialData::roughnessTextureCoordinates() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::RoughnessTexture), "Trade::PbrClearCoatMaterialData::roughnessTextureCoordinates(): the layer doesn't have a roughness texture", {}); if(Containers::Optional<UnsignedInt> value = tryAttribute<UnsignedInt>(MaterialAttribute::RoughnessTextureCoordinates)) return *value; if(Containers::Optional<UnsignedInt> value = tryAttribute<UnsignedInt>(MaterialAttribute::TextureCoordinates)) return *value; return attributeOr(0, MaterialAttribute::TextureCoordinates, 0u); } UnsignedInt PbrClearCoatMaterialData::normalTexture() const { return attribute<UnsignedInt>(MaterialAttribute::NormalTexture); } Float PbrClearCoatMaterialData::normalTextureScale() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::NormalTexture), "Trade::PbrClearCoatMaterialData::normalTextureScale(): the layer doesn't have a normal texture", {}); return attributeOr(MaterialAttribute::NormalTextureScale, 1.0f); } MaterialTextureSwizzle PbrClearCoatMaterialData::normalTextureSwizzle() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::NormalTexture), "Trade::PbrClearCoatMaterialData::normalTextureSwizzle(): the layer doesn't have a normal texture", {}); return attributeOr(MaterialAttribute::NormalTextureSwizzle, MaterialTextureSwizzle::RGB); } Matrix3 PbrClearCoatMaterialData::normalTextureMatrix() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::NormalTexture), "Trade::PbrClearCoatMaterialData::normalTextureMatrix(): the layer doesn't have a normal texture", {}); if(Containers::Optional<Matrix3> value = tryAttribute<Matrix3>(MaterialAttribute::NormalTextureMatrix)) return *value; if(Containers::Optional<Matrix3> value = tryAttribute<Matrix3>(MaterialAttribute::TextureMatrix)) return *value; return attributeOr(0, MaterialAttribute::TextureMatrix, Matrix3{}); } UnsignedInt PbrClearCoatMaterialData::normalTextureCoordinates() const { CORRADE_ASSERT(hasAttribute(MaterialAttribute::NormalTexture), "Trade::PbrClearCoatMaterialData::normalTextureCoordinates(): the layer doesn't have a normal texture", {}); if(Containers::Optional<UnsignedInt> value = tryAttribute<UnsignedInt>(MaterialAttribute::NormalTextureCoordinates)) return *value; if(Containers::Optional<UnsignedInt> value = tryAttribute<UnsignedInt>(MaterialAttribute::TextureCoordinates)) return *value; return attributeOr(0, MaterialAttribute::TextureCoordinates, 0u); } Matrix3 PbrClearCoatMaterialData::commonTextureMatrix() const { CORRADE_ASSERT(hasCommonTextureTransformation(), "Trade::PbrClearCoatMaterialData::commonTextureMatrix(): the layer doesn't have a common texture coordinate transformation", {}); if(hasAttribute(MaterialAttribute::LayerFactorTexture)) return layerFactorTextureMatrix(); if(hasAttribute(MaterialAttribute::RoughnessTexture)) return roughnessTextureMatrix(); if(hasAttribute(MaterialAttribute::NormalTexture)) return normalTextureMatrix(); if(Containers::Optional<Matrix3> value = tryAttribute<Matrix3>(MaterialAttribute::TextureMatrix)) return *value; return attributeOr(0, MaterialAttribute::TextureMatrix, Matrix3{}); } UnsignedInt PbrClearCoatMaterialData::commonTextureCoordinates() const { CORRADE_ASSERT(hasCommonTextureCoordinates(), "Trade::PbrClearCoatMaterialData::commonTextureCoordinates(): the layer doesn't have a common texture coordinate set", {}); if(hasAttribute(MaterialAttribute::LayerFactorTexture)) return layerFactorTextureCoordinates(); if(hasAttribute(MaterialAttribute::RoughnessTexture)) return roughnessTextureCoordinates(); if(hasAttribute(MaterialAttribute::NormalTexture)) return normalTextureCoordinates(); if(Containers::Optional<UnsignedInt> value = tryAttribute<UnsignedInt>(MaterialAttribute::TextureCoordinates)) return *value; return attributeOr(0, MaterialAttribute::TextureCoordinates, 0u); } }}
49.80203
137
0.758536
RyanSamlalsingh
73bf7c62e91d08862bdefcfa14c1d2663d43b47c
440
cpp
C++
chat/stress-test/src/savelist.cpp
Shiny-Man/MCR
fa3cf2f7e00065011c14f472f985de04d2c8fa7d
[ "MIT" ]
3
2019-05-16T13:11:52.000Z
2019-08-02T09:09:28.000Z
chat/stress-test/src/savelist.cpp
Shiny-Man/MCR
fa3cf2f7e00065011c14f472f985de04d2c8fa7d
[ "MIT" ]
null
null
null
chat/stress-test/src/savelist.cpp
Shiny-Man/MCR
fa3cf2f7e00065011c14f472f985de04d2c8fa7d
[ "MIT" ]
4
2019-05-16T13:11:55.000Z
2022-02-26T02:35:09.000Z
#include "savelist.h" SaveList::SaveList() { pthread_mutex_init(&m_packmutex, NULL); } char* SaveList::pack_pop() { SaveMutex mutex_lock(&m_packmutex); char *p = m_package.front(); m_package.pop_front(); m_packcount--; return p; } int SaveList::getPackSize() { return m_packcount; } void SaveList::pack_push(char *p) { SaveMutex mutex_lock(&m_packmutex); m_package.push_back(p); m_packcount++; }
15.714286
43
0.670455
Shiny-Man
73c01d5082aa63acb2b3aa60711240c09390f555
25,860
cpp
C++
kizunano/node/telemetry.cpp
kizunanocoin/node
c6013e7e992ab75432db58da05054b381f821566
[ "BSD-3-Clause" ]
1
2021-08-16T06:41:05.000Z
2021-08-16T06:41:05.000Z
kizunano/node/telemetry.cpp
kizunanocoin/node
c6013e7e992ab75432db58da05054b381f821566
[ "BSD-3-Clause" ]
null
null
null
kizunano/node/telemetry.cpp
kizunanocoin/node
c6013e7e992ab75432db58da05054b381f821566
[ "BSD-3-Clause" ]
null
null
null
#include <kizunano/lib/alarm.hpp> #include <kizunano/lib/stats.hpp> #include <kizunano/lib/worker.hpp> #include <kizunano/node/network.hpp> #include <kizunano/node/nodeconfig.hpp> #include <kizunano/node/telemetry.hpp> #include <kizunano/node/transport/transport.hpp> #include <kizunano/secure/buffer.hpp> #include <boost/algorithm/string.hpp> #include <algorithm> #include <cstdint> #include <future> #include <numeric> #include <set> using namespace std::chrono_literals; nano::telemetry::telemetry (nano::network & network_a, nano::alarm & alarm_a, nano::worker & worker_a, nano::observer_set<nano::telemetry_data const &, nano::endpoint const &> & observers_a, nano::stat & stats_a, nano::network_params & network_params_a, bool disable_ongoing_requests_a) : network (network_a), alarm (alarm_a), worker (worker_a), observers (observers_a), stats (stats_a), network_params (network_params_a), disable_ongoing_requests (disable_ongoing_requests_a) { } void nano::telemetry::start () { // Cannot be done in the constructor as a shared_from_this () call is made in ongoing_req_all_peers if (!disable_ongoing_requests) { ongoing_req_all_peers (std::chrono::milliseconds (0)); } } void nano::telemetry::stop () { stopped = true; } void nano::telemetry::set (nano::telemetry_ack const & message_a, nano::transport::channel const & channel_a) { if (!stopped) { nano::unique_lock<std::mutex> lk (mutex); nano::endpoint endpoint = channel_a.get_endpoint (); auto it = recent_or_initial_request_telemetry_data.find (endpoint); if (it == recent_or_initial_request_telemetry_data.cend () || !it->undergoing_request) { // Not requesting telemetry data from this peer so ignore it stats.inc (nano::stat::type::telemetry, nano::stat::detail::unsolicited_telemetry_ack); return; } recent_or_initial_request_telemetry_data.modify (it, [&message_a](nano::telemetry_info & telemetry_info_a) { telemetry_info_a.data = message_a.data; }); // This can also remove the peer auto error = verify_message (message_a, channel_a); if (!error) { // Received telemetry data from a peer which hasn't disabled providing telemetry metrics and there's no errors with the data lk.unlock (); observers.notify (message_a.data, endpoint); lk.lock (); } channel_processed (endpoint, error); } } bool nano::telemetry::verify_message (nano::telemetry_ack const & message_a, nano::transport::channel const & channel_a) { if (message_a.is_empty_payload ()) { return true; } auto remove_channel = false; // We want to ensure that the node_id of the channel matches that in the message before attempting to // use the data to remove any peers. auto node_id_mismatch = (channel_a.get_node_id () != message_a.data.node_id); if (!node_id_mismatch) { // The data could be correctly signed but for a different node id remove_channel = message_a.data.validate_signature (message_a.size ()); if (!remove_channel) { // Check for different genesis blocks remove_channel = (message_a.data.genesis_block != network_params.ledger.genesis_hash); if (remove_channel) { stats.inc (nano::stat::type::telemetry, nano::stat::detail::different_genesis_hash); } } else { stats.inc (nano::stat::type::telemetry, nano::stat::detail::invalid_signature); } } else { stats.inc (nano::stat::type::telemetry, nano::stat::detail::node_id_mismatch); } if (remove_channel) { // Add to peer exclusion list network.excluded_peers.add (channel_a.get_tcp_endpoint (), network.size ()); // Disconnect from peer with incorrect telemetry data network.erase (channel_a); } return remove_channel || node_id_mismatch; } std::chrono::milliseconds nano::telemetry::cache_plus_buffer_cutoff_time () const { // This include the waiting time for the response as well as a buffer (1 second) waiting for the alarm operation to be scheduled and completed return cache_cutoff + response_time_cutoff + 1s; } bool nano::telemetry::within_cache_plus_buffer_cutoff (telemetry_info const & telemetry_info) const { auto is_within = (telemetry_info.last_response + cache_plus_buffer_cutoff_time ()) >= std::chrono::steady_clock::now (); return !telemetry_info.awaiting_first_response () && is_within; } bool nano::telemetry::within_cache_cutoff (telemetry_info const & telemetry_info) const { auto is_within = (telemetry_info.last_response + cache_cutoff) >= std::chrono::steady_clock::now (); return !telemetry_info.awaiting_first_response () && is_within; } void nano::telemetry::ongoing_req_all_peers (std::chrono::milliseconds next_request_interval) { alarm.add (std::chrono::steady_clock::now () + next_request_interval, [this_w = std::weak_ptr<telemetry> (shared_from_this ())]() { if (auto this_l = this_w.lock ()) { // Check if there are any peers which are in the peers list which haven't been request, or any which are below or equal to the cache cutoff time if (!this_l->stopped) { class tag_channel { }; struct channel_wrapper { std::shared_ptr<nano::transport::channel> channel; channel_wrapper (std::shared_ptr<nano::transport::channel> const & channel_a) : channel (channel_a) { } nano::endpoint endpoint () const { return channel->get_endpoint (); } }; // clang-format off namespace mi = boost::multi_index; boost::multi_index_container<channel_wrapper, mi::indexed_by< mi::hashed_unique<mi::tag<tag_endpoint>, mi::const_mem_fun<channel_wrapper, nano::endpoint, &channel_wrapper::endpoint>>, mi::hashed_unique<mi::tag<tag_channel>, mi::member<channel_wrapper, std::shared_ptr<nano::transport::channel>, &channel_wrapper::channel>>>> peers; // clang-format on { // Copy peers to the multi index container so can get better asymptotic complexity in future operations auto temp_peers = this_l->network.list (std::numeric_limits<size_t>::max (), this_l->network_params.protocol.telemetry_protocol_version_min); peers.insert (temp_peers.begin (), temp_peers.end ()); } { // Cleanup any stale saved telemetry data for non-existent peers nano::lock_guard<std::mutex> guard (this_l->mutex); for (auto it = this_l->recent_or_initial_request_telemetry_data.begin (); it != this_l->recent_or_initial_request_telemetry_data.end ();) { if (!it->undergoing_request && !this_l->within_cache_cutoff (*it) && peers.count (it->endpoint) == 0) { it = this_l->recent_or_initial_request_telemetry_data.erase (it); } else { ++it; } } // Remove from peers list if it exists and is within the cache cutoff for (auto peers_it = peers.begin (); peers_it != peers.end ();) { auto it = this_l->recent_or_initial_request_telemetry_data.find (peers_it->endpoint ()); if (it != this_l->recent_or_initial_request_telemetry_data.cend () && this_l->within_cache_cutoff (*it)) { peers_it = peers.erase (peers_it); } else { ++peers_it; } } } // Request data from new peers, or ones which are out of date for (auto const & peer : boost::make_iterator_range (peers)) { this_l->get_metrics_single_peer_async (peer.channel, [](auto const &) { // Intentionally empty, just using to refresh the cache }); } // Schedule the next request; Use the default request time unless a telemetry request cache expires sooner nano::lock_guard<std::mutex> guard (this_l->mutex); long long next_round = std::chrono::duration_cast<std::chrono::milliseconds> (this_l->cache_cutoff + this_l->response_time_cutoff).count (); if (!this_l->recent_or_initial_request_telemetry_data.empty ()) { auto range = boost::make_iterator_range (this_l->recent_or_initial_request_telemetry_data.get<tag_last_updated> ()); for (auto telemetry_info : range) { if (!telemetry_info.undergoing_request && peers.count (telemetry_info.endpoint) == 0) { auto const last_response = telemetry_info.last_response; auto now = std::chrono::steady_clock::now (); if (now > last_response + this_l->cache_cutoff) { next_round = std::min<long long> (next_round, std::chrono::duration_cast<std::chrono::milliseconds> (now - (last_response + this_l->cache_cutoff)).count ()); } // We are iterating in sorted order from last_updated, so can break once we have found the first valid one. break; } } } this_l->ongoing_req_all_peers (std::chrono::milliseconds (next_round)); } } }); } std::unordered_map<nano::endpoint, nano::telemetry_data> nano::telemetry::get_metrics () { std::unordered_map<nano::endpoint, nano::telemetry_data> telemetry_data; nano::lock_guard<std::mutex> guard (mutex); auto range = boost::make_iterator_range (recent_or_initial_request_telemetry_data); // clang-format off nano::transform_if (range.begin (), range.end (), std::inserter (telemetry_data, telemetry_data.end ()), [this](auto const & telemetry_info) { return this->within_cache_plus_buffer_cutoff (telemetry_info); }, [](auto const & telemetry_info) { return std::pair<const nano::endpoint, nano::telemetry_data>{ telemetry_info.endpoint, telemetry_info.data }; }); // clang-format on return telemetry_data; } void nano::telemetry::get_metrics_single_peer_async (std::shared_ptr<nano::transport::channel> const & channel_a, std::function<void(telemetry_data_response const &)> const & callback_a) { auto invoke_callback_with_error = [&callback_a, &worker = this->worker, channel_a]() { nano::endpoint endpoint; if (channel_a) { endpoint = channel_a->get_endpoint (); } worker.push_task ([callback_a, endpoint]() { auto const error = true; callback_a ({ nano::telemetry_data{}, endpoint, error }); }); }; if (!stopped) { if (channel_a && (channel_a->get_network_version () >= network_params.protocol.telemetry_protocol_version_min)) { auto add_callback_async = [& worker = this->worker, &callback_a](telemetry_data const & telemetry_data_a, nano::endpoint const & endpoint_a) { telemetry_data_response telemetry_data_response_l{ telemetry_data_a, endpoint_a, false }; worker.push_task ([telemetry_data_response_l, callback_a]() { callback_a (telemetry_data_response_l); }); }; // Check if this is within the cache nano::lock_guard<std::mutex> guard (mutex); auto it = recent_or_initial_request_telemetry_data.find (channel_a->get_endpoint ()); if (it != recent_or_initial_request_telemetry_data.cend () && within_cache_cutoff (*it)) { add_callback_async (it->data, it->endpoint); } else { if (it != recent_or_initial_request_telemetry_data.cend () && it->undergoing_request) { // A request is currently undergoing, add the callback debug_assert (callbacks.count (it->endpoint) > 0); callbacks[it->endpoint].push_back (callback_a); } else { if (it == recent_or_initial_request_telemetry_data.cend ()) { // Insert dummy values, it's important not to use "last_response" time here without first checking that awaiting_first_response () returns false. recent_or_initial_request_telemetry_data.emplace (channel_a->get_endpoint (), nano::telemetry_data (), std::chrono::steady_clock::now (), true); it = recent_or_initial_request_telemetry_data.find (channel_a->get_endpoint ()); } else { recent_or_initial_request_telemetry_data.modify (it, [](nano::telemetry_info & telemetry_info_a) { telemetry_info_a.undergoing_request = true; }); } callbacks[it->endpoint].push_back (callback_a); fire_request_message (channel_a); } } } else { invoke_callback_with_error (); } } else { invoke_callback_with_error (); } } nano::telemetry_data_response nano::telemetry::get_metrics_single_peer (std::shared_ptr<nano::transport::channel> const & channel_a) { std::promise<telemetry_data_response> promise; get_metrics_single_peer_async (channel_a, [&promise](telemetry_data_response const & single_metric_data_a) { promise.set_value (single_metric_data_a); }); return promise.get_future ().get (); } void nano::telemetry::fire_request_message (std::shared_ptr<nano::transport::channel> const & channel_a) { // Fire off a telemetry request to all passed in channels debug_assert (channel_a->get_network_version () >= network_params.protocol.telemetry_protocol_version_min); uint64_t round_l; { auto it = recent_or_initial_request_telemetry_data.find (channel_a->get_endpoint ()); recent_or_initial_request_telemetry_data.modify (it, [](nano::telemetry_info & telemetry_info_a) { ++telemetry_info_a.round; }); round_l = it->round; } std::weak_ptr<nano::telemetry> this_w (shared_from_this ()); nano::telemetry_req message; // clang-format off channel_a->send (message, [this_w, endpoint = channel_a->get_endpoint (), round_l](boost::system::error_code const & ec, size_t size_a) { if (auto this_l = this_w.lock ()) { if (ec) { // Error sending the telemetry_req message this_l->stats.inc (nano::stat::type::telemetry, nano::stat::detail::failed_send_telemetry_req); nano::lock_guard<std::mutex> guard (this_l->mutex); this_l->channel_processed (endpoint, true); } else { // If no response is seen after a certain period of time remove it this_l->alarm.add (std::chrono::steady_clock::now () + this_l->response_time_cutoff, [round_l, this_w, endpoint]() { if (auto this_l = this_w.lock ()) { nano::lock_guard<std::mutex> guard (this_l->mutex); auto it = this_l->recent_or_initial_request_telemetry_data.find (endpoint); if (it != this_l->recent_or_initial_request_telemetry_data.cend () && it->undergoing_request && round_l == it->round) { this_l->stats.inc (nano::stat::type::telemetry, nano::stat::detail::no_response_received); this_l->channel_processed (endpoint, true); } } }); } } }, nano::buffer_drop_policy::no_socket_drop); // clang-format on } void nano::telemetry::channel_processed (nano::endpoint const & endpoint_a, bool error_a) { auto it = recent_or_initial_request_telemetry_data.find (endpoint_a); if (it != recent_or_initial_request_telemetry_data.end ()) { if (!error_a) { recent_or_initial_request_telemetry_data.modify (it, [](nano::telemetry_info & telemetry_info_a) { telemetry_info_a.last_response = std::chrono::steady_clock::now (); telemetry_info_a.undergoing_request = false; }); } else { recent_or_initial_request_telemetry_data.erase (endpoint_a); } flush_callbacks_async (endpoint_a, error_a); } } void nano::telemetry::flush_callbacks_async (nano::endpoint const & endpoint_a, bool error_a) { // Post to worker so that it's truly async and not on the calling thread (same problem as std::async otherwise) worker.push_task ([endpoint_a, error_a, this_w = std::weak_ptr<nano::telemetry> (shared_from_this ())]() { if (auto this_l = this_w.lock ()) { nano::unique_lock<std::mutex> lk (this_l->mutex); while (!this_l->callbacks[endpoint_a].empty ()) { lk.unlock (); this_l->invoke_callbacks (endpoint_a, error_a); lk.lock (); } } }); } void nano::telemetry::invoke_callbacks (nano::endpoint const & endpoint_a, bool error_a) { std::vector<std::function<void(telemetry_data_response const &)>> callbacks_l; telemetry_data_response response_data{ nano::telemetry_data (), endpoint_a, error_a }; { // Copy data so that it can be used outside of holding the lock nano::lock_guard<std::mutex> guard (mutex); callbacks_l = callbacks[endpoint_a]; auto it = recent_or_initial_request_telemetry_data.find (endpoint_a); if (it != recent_or_initial_request_telemetry_data.end ()) { response_data.telemetry_data = it->data; } callbacks.erase (endpoint_a); } // Need to account for nodes which disable telemetry data in responses for (auto & callback : callbacks_l) { callback (response_data); } } size_t nano::telemetry::telemetry_data_size () { nano::lock_guard<std::mutex> guard (mutex); return recent_or_initial_request_telemetry_data.size (); } nano::telemetry_info::telemetry_info (nano::endpoint const & endpoint_a, nano::telemetry_data const & data_a, std::chrono::steady_clock::time_point last_response_a, bool undergoing_request_a) : endpoint (endpoint_a), data (data_a), last_response (last_response_a), undergoing_request (undergoing_request_a) { } bool nano::telemetry_info::awaiting_first_response () const { return data == nano::telemetry_data (); } std::unique_ptr<nano::container_info_component> nano::collect_container_info (telemetry & telemetry, const std::string & name) { auto composite = std::make_unique<container_info_composite> (name); size_t callbacks_count; { nano::lock_guard<std::mutex> guard (telemetry.mutex); std::unordered_map<nano::endpoint, std::vector<std::function<void(telemetry_data_response const &)>>> callbacks; callbacks_count = std::accumulate (callbacks.begin (), callbacks.end (), static_cast<size_t> (0), [](auto total, auto const & callback_a) { return total += callback_a.second.size (); }); } composite->add_component (std::make_unique<container_info_leaf> (container_info{ "recent_or_initial_request_telemetry_data", telemetry.telemetry_data_size (), sizeof (decltype (telemetry.recent_or_initial_request_telemetry_data)::value_type) })); composite->add_component (std::make_unique<container_info_leaf> (container_info{ "callbacks", callbacks_count, sizeof (decltype (telemetry.callbacks)::value_type::second_type) })); return composite; } nano::telemetry_data nano::consolidate_telemetry_data (std::vector<nano::telemetry_data> const & telemetry_datas) { if (telemetry_datas.empty ()) { return {}; } else if (telemetry_datas.size () == 1) { // Only 1 element in the collection, so just return it. return telemetry_datas.front (); } std::unordered_map<uint8_t, int> protocol_versions; std::unordered_map<std::string, int> vendor_versions; std::unordered_map<uint64_t, int> bandwidth_caps; std::unordered_map<nano::block_hash, int> genesis_blocks; // Use a trimmed average which excludes the upper and lower 10% of the results std::multiset<uint64_t> account_counts; std::multiset<uint64_t> block_counts; std::multiset<uint64_t> cemented_counts; std::multiset<uint32_t> peer_counts; std::multiset<uint64_t> unchecked_counts; std::multiset<uint64_t> uptimes; std::multiset<uint64_t> bandwidths; std::multiset<uint64_t> timestamps; std::multiset<uint64_t> active_difficulties; for (auto const & telemetry_data : telemetry_datas) { account_counts.insert (telemetry_data.account_count); block_counts.insert (telemetry_data.block_count); cemented_counts.insert (telemetry_data.cemented_count); std::ostringstream ss; ss << telemetry_data.major_version << "." << telemetry_data.minor_version << "." << telemetry_data.patch_version << "." << telemetry_data.pre_release_version << "." << telemetry_data.maker; ++vendor_versions[ss.str ()]; timestamps.insert (std::chrono::duration_cast<std::chrono::milliseconds> (telemetry_data.timestamp.time_since_epoch ()).count ()); ++protocol_versions[telemetry_data.protocol_version]; peer_counts.insert (telemetry_data.peer_count); unchecked_counts.insert (telemetry_data.unchecked_count); uptimes.insert (telemetry_data.uptime); // 0 has a special meaning (unlimited), don't include it in the average as it will be heavily skewed if (telemetry_data.bandwidth_cap != 0) { bandwidths.insert (telemetry_data.bandwidth_cap); } ++bandwidth_caps[telemetry_data.bandwidth_cap]; ++genesis_blocks[telemetry_data.genesis_block]; active_difficulties.insert (telemetry_data.active_difficulty); } // Remove 10% of the results from the lower and upper bounds to catch any outliers. Need at least 10 responses before any are removed. auto num_either_side_to_remove = telemetry_datas.size () / 10; auto strip_outliers_and_sum = [num_either_side_to_remove](auto & counts) { counts.erase (counts.begin (), std::next (counts.begin (), num_either_side_to_remove)); counts.erase (std::next (counts.rbegin (), num_either_side_to_remove).base (), counts.end ()); return std::accumulate (counts.begin (), counts.end (), nano::uint128_t (0), [](nano::uint128_t total, auto count) { return total += count; }); }; auto account_sum = strip_outliers_and_sum (account_counts); auto block_sum = strip_outliers_and_sum (block_counts); auto cemented_sum = strip_outliers_and_sum (cemented_counts); auto peer_sum = strip_outliers_and_sum (peer_counts); auto unchecked_sum = strip_outliers_and_sum (unchecked_counts); auto uptime_sum = strip_outliers_and_sum (uptimes); auto bandwidth_sum = strip_outliers_and_sum (bandwidths); auto active_difficulty_sum = strip_outliers_and_sum (active_difficulties); nano::telemetry_data consolidated_data; auto size = telemetry_datas.size () - num_either_side_to_remove * 2; consolidated_data.account_count = boost::numeric_cast<decltype (consolidated_data.account_count)> (account_sum / size); consolidated_data.block_count = boost::numeric_cast<decltype (consolidated_data.block_count)> (block_sum / size); consolidated_data.cemented_count = boost::numeric_cast<decltype (consolidated_data.cemented_count)> (cemented_sum / size); consolidated_data.peer_count = boost::numeric_cast<decltype (consolidated_data.peer_count)> (peer_sum / size); consolidated_data.uptime = boost::numeric_cast<decltype (consolidated_data.uptime)> (uptime_sum / size); consolidated_data.unchecked_count = boost::numeric_cast<decltype (consolidated_data.unchecked_count)> (unchecked_sum / size); consolidated_data.active_difficulty = boost::numeric_cast<decltype (consolidated_data.unchecked_count)> (active_difficulty_sum / size); if (!timestamps.empty ()) { auto timestamp_sum = strip_outliers_and_sum (timestamps); consolidated_data.timestamp = std::chrono::system_clock::time_point (std::chrono::milliseconds (boost::numeric_cast<uint64_t> (timestamp_sum / timestamps.size ()))); } auto set_mode_or_average = [](auto const & collection, auto & var, auto const & sum, size_t size) { auto max = std::max_element (collection.begin (), collection.end (), [](auto const & lhs, auto const & rhs) { return lhs.second < rhs.second; }); if (max->second > 1) { var = max->first; } else { var = (sum / size).template convert_to<std::remove_reference_t<decltype (var)>> (); } }; auto set_mode = [](auto const & collection, auto & var, size_t size) { auto max = std::max_element (collection.begin (), collection.end (), [](auto const & lhs, auto const & rhs) { return lhs.second < rhs.second; }); if (max->second > 1) { var = max->first; } else { // Just pick the first one var = collection.begin ()->first; } }; // Use the mode of protocol version and vendor version. Also use it for bandwidth cap if there is 2 or more of the same cap. set_mode_or_average (bandwidth_caps, consolidated_data.bandwidth_cap, bandwidth_sum, size); set_mode (protocol_versions, consolidated_data.protocol_version, size); set_mode (genesis_blocks, consolidated_data.genesis_block, size); // Vendor version, needs to be parsed out of the string std::string version; set_mode (vendor_versions, version, size); // May only have major version, but check for optional parameters as well, only output if all are used std::vector<std::string> version_fragments; boost::split (version_fragments, version, boost::is_any_of (".")); debug_assert (version_fragments.size () == 5); consolidated_data.major_version = boost::lexical_cast<uint8_t> (version_fragments.front ()); consolidated_data.minor_version = boost::lexical_cast<uint8_t> (version_fragments[1]); consolidated_data.patch_version = boost::lexical_cast<uint8_t> (version_fragments[2]); consolidated_data.pre_release_version = boost::lexical_cast<uint8_t> (version_fragments[3]); consolidated_data.maker = boost::lexical_cast<uint8_t> (version_fragments[4]); return consolidated_data; } nano::telemetry_data nano::local_telemetry_data (nano::ledger_cache const & ledger_cache_a, nano::network & network_a, uint64_t bandwidth_limit_a, nano::network_params const & network_params_a, std::chrono::steady_clock::time_point statup_time_a, uint64_t active_difficulty_a, nano::keypair const & node_id_a) { nano::telemetry_data telemetry_data; telemetry_data.node_id = node_id_a.pub; telemetry_data.block_count = ledger_cache_a.block_count; telemetry_data.cemented_count = ledger_cache_a.cemented_count; telemetry_data.bandwidth_cap = bandwidth_limit_a; telemetry_data.protocol_version = network_params_a.protocol.protocol_version; telemetry_data.uptime = std::chrono::duration_cast<std::chrono::seconds> (std::chrono::steady_clock::now () - statup_time_a).count (); telemetry_data.unchecked_count = ledger_cache_a.unchecked_count; telemetry_data.genesis_block = network_params_a.ledger.genesis_hash; telemetry_data.peer_count = nano::narrow_cast<decltype (telemetry_data.peer_count)> (network_a.size ()); telemetry_data.account_count = ledger_cache_a.account_count; telemetry_data.major_version = nano::get_major_node_version (); telemetry_data.minor_version = nano::get_minor_node_version (); telemetry_data.patch_version = nano::get_patch_node_version (); telemetry_data.pre_release_version = nano::get_pre_release_node_version (); telemetry_data.maker = 0; // 0 Indicates it originated from the NF telemetry_data.timestamp = std::chrono::system_clock::now (); telemetry_data.active_difficulty = active_difficulty_a; // Make sure this is the final operation! telemetry_data.sign (node_id_a); return telemetry_data; }
39.541284
309
0.735576
kizunanocoin
73c10a3dbde87d2d64eb42a17cd565783794313b
778
cpp
C++
src/cbcSolver.cpp
yenyi/PcbDecompaction
5b783308e008c3b6119afde94d86f000d28e55ef
[ "BSD-3-Clause" ]
2
2020-05-06T10:43:42.000Z
2020-07-02T05:13:51.000Z
src/cbcSolver.cpp
yenyi/PcbDecompaction
5b783308e008c3b6119afde94d86f000d28e55ef
[ "BSD-3-Clause" ]
null
null
null
src/cbcSolver.cpp
yenyi/PcbDecompaction
5b783308e008c3b6119afde94d86f000d28e55ef
[ "BSD-3-Clause" ]
4
2020-10-16T23:59:01.000Z
2021-12-21T13:17:29.000Z
#include "cbcSolver.h" bool CbcSolver::solver(std::string lpFileName, std::string solFileName) { Cbc_Model *model = Cbc_newModel(); int status; status = Cbc_readLp(model, lpFileName.c_str()); Cbc_solve(model); const double *sol = Cbc_getColSolution(model); int n = Cbc_getNumCols(model); size_t length = Cbc_maxNameLength(model); std::ofstream file; file.open(solFileName); for (int i = 0; i < n; ++i) { char *name = (char *)malloc(length); Cbc_getColName(model, i, name, length); printf("Column %d, val %g, name %s\n", i, sol[i], name); file << name << " " << sol[i] << std::endl; //std::cout << name; //std::cout << " " << sol[i] << std::endl; } Cbc_deleteModel(model); }
27.785714
71
0.582262
yenyi
73c4658cccd007ef3225c3e09c8ea936e609e327
1,688
cpp
C++
gearoenix/gles2/pipeline/gx-gles2-pip-unlit-resource-set.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/gles2/pipeline/gx-gles2-pip-unlit-resource-set.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/gles2/pipeline/gx-gles2-pip-unlit-resource-set.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#include "gx-gles2-pip-unlit-resource-set.hpp" #ifdef GX_USE_OPENGL_ES2 #include "../../gl/gx-gl-loader.hpp" #include "../../render/buffer/gx-rnd-buf-uniform.hpp" #include "../../render/camera/gx-rnd-cmr-uniform.hpp" #include "../../render/graph/node/gx-rnd-gr-nd-unlit.hpp" #include "../../render/material/gx-rnd-mat-unlit.hpp" #include "../../render/mesh/gx-rnd-msh-mesh.hpp" #include "../buffer/gx-gles2-buf-index.hpp" #include "../buffer/gx-gles2-buf-vertex.hpp" #include "../shader/gx-gles2-shd-unlit.hpp" #include "../texture/gx-gles2-txt-2d.hpp" #include "gx-gles2-pip-resource-set.hpp" #include "gx-gles2-pip-unlit.hpp" gearoenix::gles2::pipeline::UnlitResourceSet::UnlitResourceSet(const std::shared_ptr<shader::Unlit>& shd, std::shared_ptr<Unlit const> pip) noexcept : render::pipeline::UnlitResourceSet(std::move(pip)) , base(new gles2::pipeline::ResourceSet(shd)) { } gearoenix::gles2::pipeline::UnlitResourceSet::~UnlitResourceSet() noexcept = default; void gearoenix::gles2::pipeline::UnlitResourceSet::bind_final(gl::uint& bound_shader_program) const noexcept { GX_GLES2_PIP_RES_START_DRAWING_MESH GX_GLES2_PIP_RES_START_SHADER(Unlit, shd) const auto* const material = material_uniform_buffer->get_ptr<render::material::Unlit::Uniform>(); GX_GLES2_PIP_RES_SET_UNIFORM(material_alpha, material->alpha) GX_GLES2_PIP_RES_SET_UNIFORM(material_alpha_cutoff, material->alpha_cutoff) GX_GLES2_PIP_RES_SET_TXT_2D(material_color, color) const auto* const node = node_uniform_buffer->get_ptr<render::graph::node::UnlitUniform>(); GX_GLES2_PIP_RES_SET_UNIFORM(effect_mvp, node->mvp.data[0][0]) GX_GLES2_PIP_RES_END_DRAWING_MESH } #endif
45.621622
148
0.755332
Hossein-Noroozpour
73c4e13f4ec330b201ff538afe5a38696a0f13a8
14,926
hpp
C++
buffer.hpp
kmchan2018/piper
0b8a37511963f900d9476ec55b300dba72577660
[ "MIT" ]
null
null
null
buffer.hpp
kmchan2018/piper
0b8a37511963f900d9476ec55b300dba72577660
[ "MIT" ]
null
null
null
buffer.hpp
kmchan2018/piper
0b8a37511963f900d9476ec55b300dba72577660
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstddef> #include <cstring> #include <exception> #include <memory> #include <stdexcept> #include <type_traits> #include <utility> #include "exception.hpp" #ifndef BUFFER_HPP_ #define BUFFER_HPP_ namespace Piper { using Support::Exception::start; /** * Buffer is a value class that references a memory region. A buffer consists * of two components, including the pointer to the start of the region, and * the size of the region in bytes. * * Note the following points about the class: * * Buffer does not assume ownership to the memory region and therefore is not * responsible for freeing the memory region. Also, it is possible that * multiple buffer instance to refer to a single region. * * Const buffers are considered a read only view to the given memory region. * A onst buffer will only return pointers to const data; moreover, the * `head`, `tail` and `slice` operations will only return const buffers. */ class Buffer { public: /** * Construct a new buffer from its components. Throws invalid argument * exception when start and/or size is invalid. */ explicit Buffer(char* start, std::size_t size) : m_start(start), m_size(size) { if (start == nullptr) { Support::Exception::start(std::invalid_argument("[Piper::Buffer::Buffer] start should not be null"), "buffer.hpp", __LINE__); } else if (size == 0) { Support::Exception::start(std::invalid_argument("[Piper::Buffer::Buffer] length should not be 0"), "buffer.hpp", __LINE__); } } /** * Construct a new buffer backed by the given pointer to struct. */ template<typename T, typename std::conditional<std::is_base_of<Buffer,T>::value, void, bool>::type = false> explicit Buffer(T* start) : m_start(reinterpret_cast<char*>(start)), m_size(sizeof(T)) { if (start == nullptr) { Support::Exception::start(std::invalid_argument("[Piper::Buffer::Buffer] start should not be null"), "buffer.hpp", __LINE__); } } /** * Construct a new buffer backed by the given reference to struct. */ template<typename T, typename std::conditional<std::is_base_of<Buffer,T>::value, void, bool>::type = false> explicit Buffer(T& start) : m_start(reinterpret_cast<char*>(std::addressof(start))), m_size(sizeof(T)) { // empty } /** * Returns the size of this buffer. */ std::size_t size() const noexcept { return m_size; } /** * Returns a pointer to the start of this buffer. */ const char* start() const noexcept { return m_start; } /** * Returns a pointer to the start of this buffer. */ char* start() noexcept { return m_start; } /** * Cast the buffer as a pointer to struct. */ template<typename T> const T* to_struct_pointer() const { void* start = m_start; std::size_t size = m_size; if (std::align(alignof(T), sizeof(T), start, size) == nullptr) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else if (start != m_start) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else if (size != m_size) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else { return reinterpret_cast<T*>(m_start); } } /** * Cast the buffer as a pointer to struct. */ template<typename T> T* to_struct_pointer() { void* start = m_start; std::size_t size = m_size; if (std::align(alignof(T), sizeof(T), start, size) == nullptr) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else if (start != m_start) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else if (size != m_size) { Support::Exception::start(std::logic_error("[Piper::Buffer::to_struct_pointer] Cannot cast buffer to struct due to misalignment"), "buffer.hpp", __LINE__); } else { return reinterpret_cast<T*>(m_start); } } /** * Cast the buffer as a reference to struct. */ template<typename T> const T& to_struct_reference() const { return *(to_struct_pointer<T>()); } /** * Cast the buffer as a reference to struct. */ template<typename T> T& to_struct_reference() { return *(to_struct_pointer<T>()); } /** * Returns a pointer to a specific offset of the memory region. Throws * invalid argument exception when the offset extends past the end of * this buffer. */ const char* at(std::size_t offset) const { if (offset < m_size) { return m_start + offset; } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::at] offset should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a pointer to a specific offset of the memory region. Throws * invalid argument exception when the offset extends past the end of * this buffer. */ char* at(std::size_t offset) { if (offset < m_size) { return m_start + offset; } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::at] offset should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a buffer representing the first n bytes of this buffer. Throws * exception when n is larger than the size of this buffer. */ const Buffer head(std::size_t size) const { if (size <= m_size) { return Buffer(m_start, size); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::head] size should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a buffer representing the first n bytes of this buffer. Throws * exception when n is larger than the size of this buffer. */ Buffer head(std::size_t size) { if (size <= m_size) { return Buffer(m_start, size); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::head] size should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a buffer representing the last n bytes of this buffer. Throws * exception when n is larger than the size of this buffer. */ const Buffer tail(std::size_t size) const { if (size <= m_size) { return Buffer(m_start + (m_size - size), size); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::tail] size should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a buffer representing the last n bytes of this buffer. Throws * exception when n is larger than the size of this buffer. */ Buffer tail(std::size_t size) { if (size <= m_size) { return Buffer(m_start + (m_size - size), size); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::tail] size should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Returns a buffer that starts from the specific offset of this buffer * and with the given size. Throws exception when the slice extends * past the end of this buffer. */ const Buffer slice(std::size_t offset, std::size_t size) const { if (offset >= m_size) { Support::Exception::start(std::out_of_range("[Piper::Buffer::slice] offset should not exceed buffer size"), "buffer.hpp", __LINE__); } else if (size > m_size - offset) { Support::Exception::start(std::out_of_range("[Piper::Buffer::slice] size should not exceed available space in the buffer after the given offset"), "buffer.hpp", __LINE__); } else { return Buffer(m_start + offset, size); } } /** * Returns a buffer that starts from the specific offset of this buffer * and with the given size. Throws exception when the slice extends * past the end of this buffer. */ Buffer slice(std::size_t offset, std::size_t size) { if (offset >= m_size) { Support::Exception::start(std::out_of_range("[Piper::Buffer::slice] offset should not exceed buffer size"), "buffer.hpp", __LINE__); } else if (size > m_size - offset) { Support::Exception::start(std::out_of_range("[Piper::Buffer::slice] size should not exceed available space in the buffer after the given offset"), "buffer.hpp", __LINE__); } else { return Buffer(m_start + offset, size); } } /** * Index operation. */ const char& operator[](std::size_t index) const { if (index < m_size) { return *(m_start + index); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::operator[]] index should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Index operation. */ char& operator[](std::size_t index) { if (index < m_size) { return *(m_start + index); } else { Support::Exception::start(std::out_of_range("[Piper::Buffer::operator[]] index should not exceed buffer size"), "buffer.hpp", __LINE__); } } /** * Swap the content of this buffer instance with another buffer instance. * This method is used to support std::swap operation over buffer * instances. */ void swap(Buffer& other) noexcept { std::swap(m_start, other.m_start); std::swap(m_size, other.m_size); } private: char* m_start; std::size_t m_size; }; /** * Source implements a buffer wrapper that represents a source where data * can be read from. * * Essentially, a source contains 2 components. It includes a buffer where * data can be found, and a counter indicating the amount of pending data. */ class Source { public: /** * Construct a new source. */ explicit Source(const Buffer& buffer) : m_buffer(buffer), m_remainder(buffer.size()) { // do nothing } /** * Return the buffer where the source reads from. */ const Buffer& buffer() const noexcept { return m_buffer; } /** * Return the number of bytes that are available for reading. */ std::size_t total() const noexcept { return m_buffer.size(); } /** * Return the number of bytes that are already read. */ std::size_t read() const noexcept { return m_buffer.size() - m_remainder; } /** * Return the number of bytes in the buffer to be read. */ std::size_t remainder() const noexcept { return m_remainder; } /** * Return a buffer containing the unread data. Throws exception when * there are no data left. */ const Buffer data() { return m_buffer.tail(m_remainder); } /** * Consume the given amount of data as processed. */ void consume(std::size_t consumed) { if (consumed <= m_remainder) { m_remainder -= consumed; } else { Support::Exception::start(std::out_of_range("[Piper::Source::consume] consumed should not exceed remainder size"), "buffer.hpp", __LINE__); } } private: const Buffer& m_buffer; std::size_t m_remainder; }; /** * Destination implements a buffer wrapper that represents a destination * where data can be written to. * * Essentially, a destination contains 2 components. It includes a buffer * where data can be stored, and a counter indicating the amount of unused * space. */ class Destination { public: /** * Construct a new destination. */ explicit Destination(Buffer& buffer) : m_buffer(buffer), m_remainder(buffer.size()) { // do nothing } /** * Return the buffer where the transfer processes. */ Buffer& buffer() const noexcept { return m_buffer; } /** * Return the number of bytes that are available for processing. */ std::size_t total() const noexcept { return m_buffer.size(); } /** * Return the number of bytes that are already written. */ std::size_t written() const noexcept { return m_buffer.size() - m_remainder; } /** * Return the number of bytes in the buffer to be written. */ std::size_t remainder() const noexcept { return m_remainder; } /** * Return the slice to the buffer where the data awaits processing. * Throws exception when there are no data left. */ Buffer data() { return m_buffer.tail(m_remainder); } /** * Consume the given amount of data as processed. */ void consume(std::size_t consumed) { if (consumed <= m_remainder) { m_remainder -= consumed; } else { Support::Exception::start(std::out_of_range("[Piper::Destination::consume] consumed should not exceed remainder size"), "buffer.hpp", __LINE__); } } private: Buffer& m_buffer; std::size_t m_remainder; }; /** * Copy data from the source buffer into the destination buffer. */ inline void copy(Buffer& destination, const Buffer& source) { if (destination.size() >= source.size()) { std::memcpy(destination.start(), source.start(), source.size()); } else { Support::Exception::start(std::invalid_argument("[Piper::copy] source too large"), "buffer.hpp", __LINE__); } } /** * Copy data from the source variable into the destination buffer. */ template<typename T> inline void copy(Buffer& destination, const T& source) { if (destination.size() >= sizeof(T)) { std::memcpy(destination.start(), &source, sizeof(T)); } else { Support::Exception::start(std::invalid_argument("[Piper::copy] source too large"), "buffer.hpp", __LINE__); } } /** * Copy data from the source variable into the destination buffer. */ template<typename T> inline void copy(Buffer& destination, const T* source) { if (destination.size() >= sizeof(T)) { std::memcpy(destination.start(), reinterpret_cast<void*>(source), sizeof(T)); } else { Support::Exception::start(std::invalid_argument("[Piper::copy] source too large"), "buffer.hpp", __LINE__); } } /** * Copy data from the source buffer into the destination variable. */ template<typename T> inline void copy(T* destination, const Buffer& source) { if (sizeof(T) >= source.size()) { std::memcpy(reinterpret_cast<void*>(destination), source.start(), source.size()); } else { Support::Exception::start(std::invalid_argument("[Piper::copy] source too large"), "buffer.hpp", __LINE__); } } /** * Specialize the swap call for buffer instances. */ inline void swap(Buffer &a, Buffer &b) noexcept { return a.swap(b); } } #endif
28.056391
176
0.647595
kmchan2018
73c78764ed0b39fe3d45febfdb05e87f3600ea1d
13,212
cxx
C++
arrows/ffmpeg/ffmpeg_video_output.cxx
hdefazio/kwiver
0e04c3727bfb6f55c9da439fff77d054f32a575c
[ "BSD-3-Clause" ]
null
null
null
arrows/ffmpeg/ffmpeg_video_output.cxx
hdefazio/kwiver
0e04c3727bfb6f55c9da439fff77d054f32a575c
[ "BSD-3-Clause" ]
null
null
null
arrows/ffmpeg/ffmpeg_video_output.cxx
hdefazio/kwiver
0e04c3727bfb6f55c9da439fff77d054f32a575c
[ "BSD-3-Clause" ]
null
null
null
// This file is part of KWIVER, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/kwiver/blob/master/LICENSE for details. /// \file /// \brief Implementation of FFmpeg video writer. #include "arrows/ffmpeg/ffmpeg_init.h" #include "arrows/ffmpeg/ffmpeg_video_output.h" #include "arrows/ffmpeg/ffmpeg_video_settings.h" extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> } namespace kv = kwiver::vital; namespace kwiver { namespace arrows { namespace ffmpeg { class ffmpeg_video_output::impl { public: impl(); ~impl(); bool write_next_packet(); void write_remaining_packets(); private: friend class ffmpeg_video_output; AVFormatContext* format_context; AVOutputFormat* output_format; AVStream* video_stream; AVStream* metadata_stream; AVCodecContext* codec_context; AVCodec* codec; SwsContext* image_conversion_context; kv::logger_handle_t logger; size_t frame_count; AVRational frame_rate; }; ffmpeg_video_output::impl ::impl() : format_context{ nullptr }, output_format{ nullptr }, video_stream{ nullptr }, metadata_stream{ nullptr }, codec_context{ nullptr }, codec{ nullptr }, image_conversion_context{ nullptr }, logger{}, frame_count{ 0 }, frame_rate{ 0, 1 } { ffmpeg_init(); } ffmpeg_video_output::impl::~impl() {} bool ffmpeg_video_output::impl ::write_next_packet() { AVPacket packet = {}; av_init_packet( &packet ); // Attempt to read next encoded packet auto const success = avcodec_receive_packet( codec_context, &packet ); if( success == AVERROR( EAGAIN ) || success == AVERROR_EOF ) { // Failed expectedly: no packet to read av_packet_unref( &packet ); return false; } if( success < 0 ) { // Failed unexpectedly av_packet_unref( &packet ); VITAL_THROW( kv::video_runtime_exception, "Failed to receive packet" ); } // Succeeded; write to file if( av_interleaved_write_frame( format_context, &packet ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to write packet" ); } return true; } void ffmpeg_video_output::impl ::write_remaining_packets() { // Enter "draining mode" - i.e. signal end of file avcodec_send_frame( codec_context, nullptr ); while( write_next_packet() ) {} } ffmpeg_video_output ::ffmpeg_video_output() : d{ new impl{} } { attach_logger( "ffmpeg_video_output" ); d->logger = logger(); set_capability( kv::algo::video_output::SUPPORTS_FRAME_RATE, true ); set_capability( kv::algo::video_output::SUPPORTS_FRAME_TIME, true ); set_capability( kv::algo::video_output::SUPPORTS_METADATA, true ); } ffmpeg_video_output::~ffmpeg_video_output() { close(); } vital::config_block_sptr ffmpeg_video_output ::get_configuration() const { // TODO auto config = vital::algorithm::get_configuration(); return config; } void ffmpeg_video_output ::set_configuration( kv::config_block_sptr config ) { // TODO auto existing_config = vital::algorithm::get_configuration(); existing_config->merge_config( config ); } bool ffmpeg_video_output ::check_configuration( kv::config_block_sptr config ) const { // TODO return true; } void ffmpeg_video_output ::open( std::string video_name, vital::video_settings const* generic_settings ) { // Ensure we start from a blank slate close(); auto const settings = generic_settings ? dynamic_cast< ffmpeg_video_settings const* >( generic_settings ) : nullptr; if( !settings ) { VITAL_THROW( kv::invalid_value, "Must provide ffmpeg_video_settings to open()" ); } d->output_format = av_guess_format( nullptr, video_name.c_str(), nullptr ); // Allocate output format context avformat_alloc_output_context2( &d->format_context, d->output_format, nullptr, nullptr ); if( !d->format_context ) { LOG_DEBUG( logger(), "Could not deduce output format for filename `" << video_name << "`; defaulting to MPEG" ); avformat_alloc_output_context2( &d->format_context, nullptr, "mpeg", nullptr ); } if( !d->format_context ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate format context" ); } // Configure video codec d->codec = avcodec_find_encoder( d->output_format->video_codec ); if( !d->codec ) { VITAL_THROW( kv::video_runtime_exception, "Failed to find codec" ); } // Find best pixel format auto pixel_format = static_cast< AVPixelFormat >( -1 ); for( auto ptr = d->codec->pix_fmts; ptr && *ptr != -1; ++ptr ) { if( *ptr == settings->pixel_format ) { pixel_format = settings->pixel_format; break; } } if( pixel_format == -1 ) { pixel_format = avcodec_find_best_pix_fmt_of_list( d->codec->pix_fmts, AV_PIX_FMT_RGB24, false, nullptr ); } // Create and configure codec context d->codec_context = avcodec_alloc_context3( d->codec ); if( !d->codec_context ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate codec context" ); } d->codec_context->time_base = av_inv_q( settings->frame_rate ); d->codec_context->pix_fmt = pixel_format; d->codec_context->width = settings->width; d->codec_context->height = settings->height; d->codec_context->framerate = settings->frame_rate; d->codec_context->sample_aspect_ratio = settings->sample_aspect_ratio; if( d->codec_context->bit_rate > 0 ) { d->codec_context->bit_rate = settings->bit_rate; d->codec_context->bit_rate_tolerance = settings->bit_rate_tolerance; } if( d->codec->id == settings->codec_id ) { d->codec_context->gop_size = settings->gop_size; d->codec_context->level = settings->level; d->codec_context->profile = settings->profile; } // Create video stream if( d->output_format->video_codec == AV_CODEC_ID_NONE ) { VITAL_THROW( kv::invalid_value, std::string{} + "Specified format `" + d->output_format->long_name + "` does not support video" ); } d->video_stream = avformat_new_stream( d->format_context, nullptr ); if( !d->video_stream ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate video stream" ); } d->video_stream->time_base = d->codec_context->time_base; d->video_stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; d->video_stream->codecpar->codec_id = d->output_format->video_codec; d->video_stream->codecpar->width = d->codec_context->width; d->video_stream->codecpar->height = d->codec_context->height; d->video_stream->codecpar->format = d->codec_context->pix_fmt; if( avcodec_open2( d->codec_context, d->codec, nullptr ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to open codec" ); } av_dump_format( d->format_context, d->video_stream->index, video_name.c_str(), 1 ); // Open streams if( avio_open( &d->format_context->pb, video_name.c_str(), AVIO_FLAG_WRITE ) < 0 ) { VITAL_THROW( kv::file_write_exception, video_name, std::string{} + "Failed to open video file for writing" ); } auto const output_status = avformat_init_output( d->format_context, nullptr ); if( output_status == AVSTREAM_INIT_IN_WRITE_HEADER ) { if( avformat_write_header( d->format_context, nullptr ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to write video header" ); } } if( output_status != AVSTREAM_INIT_IN_INIT_OUTPUT ) { VITAL_THROW( kv::video_runtime_exception, "Failed to initialize output stream" ); } d->frame_rate = settings->frame_rate; } void ffmpeg_video_output ::close() { if( d->format_context ) { d->write_remaining_packets(); // Write closing bytes of video format if( av_write_trailer( d->format_context ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to write trailer" ); } // Close video file if( d->format_context->pb ) { if( avio_closep( &d->format_context->pb ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to close video file" ); } } // Destroy video context avcodec_free_context( &d->codec_context ); // Destroy video encoder avformat_free_context( d->format_context ); d->format_context = nullptr; } // Destroy image converter if( d->image_conversion_context ) { sws_freeContext( d->image_conversion_context ); d->image_conversion_context = nullptr; } d->frame_count = 0; d->frame_rate = { 0, 1 }; } bool ffmpeg_video_output ::good() const { return d->format_context; } void ffmpeg_video_output ::add_image( kv::image_container_sptr const& image, VITAL_UNUSED kv::timestamp const& ts ) { // These structs ensure no memory leaks even when an exception is thrown. // Could use std::unique_ptr, but the syntax is a bit less clean struct frame_autodeleter { ~frame_autodeleter() { av_frame_free( &ptr ); } AVFrame* ptr; }; struct image_autodeleter { ~image_autodeleter() { av_freep( &ptr->data[ 0 ] ); } AVFrame* ptr; }; // Create frame object to represent incoming image auto const frame = av_frame_alloc(); if( !frame ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate frame" ); } frame_autodeleter const frame_deleter{ frame }; // Fill in a few mandatory fields frame->width = image->width(); frame->height = image->height(); frame->format = AV_PIX_FMT_RGB24; // Allocate storage based on those fields if( av_frame_get_buffer( frame, 0 ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate frame data" ); } // Give the frame the raw pixel data auto const image_ptr = static_cast< uint8_t* >( image->get_image().memory()->data() ); if( av_image_fill_arrays( frame->data, frame->linesize, image_ptr, AV_PIX_FMT_RGB24, image->width(), image->height(), 1 ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to fill frame image" ); } // Create frame object to hold the image after conversion to the required // pixel format auto const converted_frame = av_frame_alloc(); if( !converted_frame ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate frame" ); } frame_autodeleter const converted_frame_deleter{ converted_frame }; // Fill in a few mandatory fields converted_frame->width = image->width(); converted_frame->height = image->height(); converted_frame->format = d->codec_context->pix_fmt; // Allocate storage based on those fields if( av_frame_get_buffer( converted_frame, 0 ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate frame data" ); } // Allocate a buffer to store the converted pixel data if( av_image_alloc( converted_frame->data, converted_frame->linesize, image->width(), image->height(), d->codec_context->pix_fmt, 1 ) < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to allocate frame image" ); } image_autodeleter const converted_image_deleter{ converted_frame }; // Specify which conversion to perform d->image_conversion_context = sws_getCachedContext( d->image_conversion_context, image->width(), image->height(), AV_PIX_FMT_RGB24, image->width(), image->height(), d->codec_context->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr ); if( !d->image_conversion_context ) { VITAL_THROW( kv::video_runtime_exception, "Failed to create image conversion context" ); } // Convert the pixel format if( sws_scale( d->image_conversion_context, frame->data, frame->linesize, 0, image->height(), converted_frame->data, converted_frame->linesize ) != static_cast< int >( image->height() ) ) { VITAL_THROW( kv::video_runtime_exception, "Failed to convert frame image pixel format" ); } // Try to send image to video encoder converted_frame->pts = static_cast< int64_t >( static_cast< double >( d->frame_count ) * d->video_stream->time_base.den / d->video_stream->time_base.num / d->frame_rate.num * d->frame_rate.den + 0.5 ); auto frame_success = avcodec_send_frame( d->codec_context, converted_frame ); // If the video encoder's buffers are full, we have to process some output // packets before we can send a new image while( frame_success == AVERROR( EAGAIN ) ) { if( !d->write_next_packet() ) { throw std::logic_error{ "Frame provided after EOF" }; } frame_success = avcodec_send_frame( d->codec_context, converted_frame ); } if( frame_success < 0 ) { VITAL_THROW( kv::video_runtime_exception, "Failed to send frame to encoder" ); } ++d->frame_count; } void ffmpeg_video_output ::add_metadata( kwiver::vital::metadata_sptr const& md ) { // TODO } } // namespace ffmpeg } // namespace arrows } // namespace kwiver
26.424
79
0.676658
hdefazio
73cab025818ff7d28ac012a99fe94a13bd603c9a
30,620
cpp
C++
sources/Renderer/Vulkan/VKRenderSystem.cpp
Krypton-Dev/LLGL
b1817bea26b81d26246a6e840caaecf839ace573
[ "BSD-3-Clause" ]
null
null
null
sources/Renderer/Vulkan/VKRenderSystem.cpp
Krypton-Dev/LLGL
b1817bea26b81d26246a6e840caaecf839ace573
[ "BSD-3-Clause" ]
null
null
null
sources/Renderer/Vulkan/VKRenderSystem.cpp
Krypton-Dev/LLGL
b1817bea26b81d26246a6e840caaecf839ace573
[ "BSD-3-Clause" ]
null
null
null
/* * VKRenderSystem.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include <LLGL/Platform/Platform.h> #include "VKRenderSystem.h" #include "Ext/VKExtensionLoader.h" #include "Ext/VKExtensions.h" #include "Memory/VKDeviceMemory.h" #include "../RenderSystemUtils.h" #include "../TextureUtils.h" #include "../CheckedCast.h" #include "../../Core/Helper.h" #include "../../Core/Vendor.h" #include "VKCore.h" #include "VKTypes.h" #include "VKInitializers.h" #include <LLGL/Log.h> #include <LLGL/ImageFlags.h> namespace LLGL { /* ----- Internal functions ----- */ static VkResult CreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* createInfo, const VkAllocationCallbacks* allocator, VkDebugReportCallbackEXT* callback) { auto func = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT")); if (func != nullptr) return func(instance, createInfo, allocator, callback); else return VK_ERROR_EXTENSION_NOT_PRESENT; } static void DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* allocator) { auto func = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT")); if (func != nullptr) func(instance, callback, allocator); } static VkBufferUsageFlags GetStagingVkBufferUsageFlags(long cpuAccessFlags) { if ((cpuAccessFlags & CPUAccessFlags::Write) != 0) return VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; else return VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } /* ----- Common ----- */ VKRenderSystem::VKRenderSystem(const RenderSystemDescriptor& renderSystemDesc) : instance_ { vkDestroyInstance }, debugReportCallback_ { instance_, DestroyDebugReportCallbackEXT } { /* Extract optional renderer configuartion */ auto rendererConfigVK = GetRendererConfiguration<RendererConfigurationVulkan>(renderSystemDesc); #ifdef LLGL_DEBUG debugLayerEnabled_ = true; #endif /* Create Vulkan instance and device objects */ CreateInstance(rendererConfigVK); PickPhysicalDevice(); CreateLogicalDevice(); /* Create default resources */ CreateDefaultPipelineLayout(); /* Create device memory manager */ deviceMemoryMngr_ = MakeUnique<VKDeviceMemoryManager>( device_, physicalDevice_.GetMemoryProperties(), (rendererConfigVK != nullptr ? rendererConfigVK->minDeviceMemoryAllocationSize : 1024*1024), (rendererConfigVK != nullptr ? rendererConfigVK->reduceDeviceMemoryFragmentation : false) ); } VKRenderSystem::~VKRenderSystem() { device_.WaitIdle(); } /* ----- Render Context ----- */ RenderContext* VKRenderSystem::CreateRenderContext(const RenderContextDescriptor& desc, const std::shared_ptr<Surface>& surface) { return TakeOwnership( renderContexts_, MakeUnique<VKRenderContext>(instance_, physicalDevice_, device_, *deviceMemoryMngr_, desc, surface) ); } void VKRenderSystem::Release(RenderContext& renderContext) { RemoveFromUniqueSet(renderContexts_, &renderContext); } /* ----- Command queues ----- */ CommandQueue* VKRenderSystem::GetCommandQueue() { return commandQueue_.get(); } /* ----- Command buffers ----- */ CommandBuffer* VKRenderSystem::CreateCommandBuffer(const CommandBufferDescriptor& desc) { return TakeOwnership( commandBuffers_, MakeUnique<VKCommandBuffer>(physicalDevice_, device_, device_.GetVkQueue(), device_.GetQueueFamilyIndices(), desc) ); } void VKRenderSystem::Release(CommandBuffer& commandBuffer) { RemoveFromUniqueSet(commandBuffers_, &commandBuffer); } /* ----- Buffers ------ */ Buffer* VKRenderSystem::CreateBuffer(const BufferDescriptor& desc, const void* initialData) { AssertCreateBuffer(desc, static_cast<uint64_t>(std::numeric_limits<VkDeviceSize>::max())); /* Create staging buffer */ VkBufferCreateInfo stagingCreateInfo; BuildVkBufferCreateInfo( stagingCreateInfo, static_cast<VkDeviceSize>(desc.size), GetStagingVkBufferUsageFlags(desc.cpuAccessFlags) ); auto stagingBuffer = CreateStagingBuffer(stagingCreateInfo, initialData, desc.size); /* Create primary buffer object */ auto buffer = TakeOwnership(buffers_, MakeUnique<VKBuffer>(device_, desc)); /* Allocate device memory */ auto memoryRegion = deviceMemoryMngr_->Allocate( buffer->GetDeviceBuffer().GetRequirements(), VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ); buffer->BindMemoryRegion(device_, memoryRegion); /* Copy staging buffer into hardware buffer */ device_.CopyBuffer(stagingBuffer.GetVkBuffer(), buffer->GetVkBuffer(), static_cast<VkDeviceSize>(desc.size)); if (desc.cpuAccessFlags != 0 || (desc.miscFlags & MiscFlags::DynamicUsage) != 0) { /* Store ownership of staging buffer */ buffer->TakeStagingBuffer(std::move(stagingBuffer)); } else { /* Release staging buffer */ stagingBuffer.ReleaseMemoryRegion(*deviceMemoryMngr_); } return buffer; } BufferArray* VKRenderSystem::CreateBufferArray(std::uint32_t numBuffers, Buffer* const * bufferArray) { AssertCreateBufferArray(numBuffers, bufferArray); auto refBindFlags = bufferArray[0]->GetBindFlags(); return TakeOwnership(bufferArrays_, MakeUnique<VKBufferArray>(refBindFlags, numBuffers, bufferArray)); } void VKRenderSystem::Release(Buffer& buffer) { /* Release device memory regions for primary buffer and internal staging buffer, then release buffer object */ auto& bufferVK = LLGL_CAST(VKBuffer&, buffer); bufferVK.GetDeviceBuffer().ReleaseMemoryRegion(*deviceMemoryMngr_); bufferVK.GetStagingDeviceBuffer().ReleaseMemoryRegion(*deviceMemoryMngr_); RemoveFromUniqueSet(buffers_, &buffer); } void VKRenderSystem::Release(BufferArray& bufferArray) { RemoveFromUniqueSet(bufferArrays_, &bufferArray); } void VKRenderSystem::WriteBuffer(Buffer& dstBuffer, std::uint64_t dstOffset, const void* data, std::uint64_t dataSize) { auto& bufferVK = LLGL_CAST(VKBuffer&, dstBuffer); if (bufferVK.GetStagingVkBuffer() != VK_NULL_HANDLE) { /* Copy data to staging buffer memory */ device_.WriteBuffer(bufferVK.GetStagingDeviceBuffer(), data, dataSize, dstOffset); /* Copy staging buffer into hardware buffer */ device_.CopyBuffer(bufferVK.GetStagingVkBuffer(), bufferVK.GetVkBuffer(), dataSize, dstOffset, dstOffset); } else { /* Create staging buffer */ VkBufferCreateInfo stagingCreateInfo; BuildVkBufferCreateInfo( stagingCreateInfo, dataSize, (VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT) ); auto stagingBuffer = CreateStagingBuffer(stagingCreateInfo, data, dataSize); /* Copy staging buffer into hardware buffer */ device_.CopyBuffer(stagingBuffer.GetVkBuffer(), bufferVK.GetVkBuffer(), dataSize, 0, dstOffset); /* Release device memory region of staging buffer */ stagingBuffer.ReleaseMemoryRegion(*deviceMemoryMngr_); } } void* VKRenderSystem::MapBuffer(Buffer& buffer, const CPUAccess access) { auto& bufferVK = LLGL_CAST(VKBuffer&, buffer); if (auto stagingBuffer = bufferVK.GetStagingVkBuffer()) { /* Copy GPU local buffer into staging buffer for read accces */ if (access != CPUAccess::WriteOnly && access != CPUAccess::WriteDiscard) device_.CopyBuffer(bufferVK.GetVkBuffer(), stagingBuffer, bufferVK.GetSize()); /* Map staging buffer */ return bufferVK.Map(device_, access); } return nullptr; } void VKRenderSystem::UnmapBuffer(Buffer& buffer) { auto& bufferVK = LLGL_CAST(VKBuffer&, buffer); if (auto stagingBuffer = bufferVK.GetStagingVkBuffer()) { /* Unmap staging buffer */ bufferVK.Unmap(device_); /* Copy staging buffer into GPU local buffer for write access */ if (bufferVK.GetMappedCPUAccess() != CPUAccess::ReadOnly) device_.CopyBuffer(stagingBuffer, bufferVK.GetVkBuffer(), bufferVK.GetSize()); } } /* ----- Textures ----- */ // Returns the extent for the specified texture dimensionality (used for the dimension of 'VK_IMAGE_TYPE_1D/ 2D/ 3D') static VkExtent3D GetTextureVkExtent(const TextureDescriptor& desc) { switch (desc.type) { case TextureType::Texture1D: /*pass*/ case TextureType::Texture1DArray: return { desc.extent.width, 1u, 1u }; case TextureType::Texture2D: /*pass*/ case TextureType::Texture2DArray: /*pass*/ case TextureType::TextureCube: /*pass*/ case TextureType::TextureCubeArray: /*pass*/ case TextureType::Texture2DMS: /*pass*/ case TextureType::Texture2DMSArray: return { desc.extent.width, desc.extent.height, 1u }; case TextureType::Texture3D: return { desc.extent.width, desc.extent.height, desc.extent.depth }; } throw std::invalid_argument("cannot determine texture extent for unknown texture type"); } static std::uint32_t GetTextureLayertCount(const TextureDescriptor& desc) { if (IsArrayTexture(desc.type)) return desc.arrayLayers; else return 1; } Texture* VKRenderSystem::CreateTexture(const TextureDescriptor& textureDesc, const SrcImageDescriptor* imageDesc) { const auto& cfg = GetConfiguration(); /* Determine size of image for staging buffer */ const auto imageSize = TextureSize(textureDesc); const auto initialDataSize = static_cast<VkDeviceSize>(TextureBufferSize(textureDesc.format, imageSize)); /* Set up initial image data */ const void* initialData = nullptr; ByteBuffer intermediateData; if (imageDesc) { /* Check if image data must be converted */ const auto& formatAttribs = GetFormatAttribs(textureDesc.format); if (formatAttribs.bitSize > 0 && (formatAttribs.flags & FormatFlags::IsCompressed) == 0) { /* Convert image format (will be null if no conversion is necessary) */ intermediateData = ConvertImageBuffer(*imageDesc, formatAttribs.format, formatAttribs.dataType, cfg.threadCount); } if (intermediateData) { /* Validate that source image data was large enough so conversion is valid, then use temporary image buffer as source for initial data */ const auto srcImageDataSize = imageSize * ImageFormatSize(imageDesc->format) * DataTypeSize(imageDesc->dataType); AssertImageDataSize(imageDesc->dataSize, static_cast<std::size_t>(srcImageDataSize)); initialData = intermediateData.get(); } else { /* Validate that image data is large enough, then use input data as source for initial data */ AssertImageDataSize(imageDesc->dataSize, static_cast<std::size_t>(initialDataSize)); initialData = imageDesc->data; } } else if ((textureDesc.miscFlags & MiscFlags::NoInitialData) == 0) { /* Allocate default image data */ const auto& formatAttribs = GetFormatAttribs(textureDesc.format); if (formatAttribs.bitSize > 0 && (formatAttribs.flags & FormatFlags::IsCompressed) == 0) { const ColorRGBAd fillColor{ textureDesc.clearValue.color.Cast<double>() }; intermediateData = GenerateImageBuffer(formatAttribs.format, formatAttribs.dataType, imageSize, fillColor); } else intermediateData = GenerateEmptyByteBuffer(static_cast<std::size_t>(initialDataSize)); initialData = intermediateData.get(); } /* Create staging buffer */ VkBufferCreateInfo stagingCreateInfo; BuildVkBufferCreateInfo( stagingCreateInfo, initialDataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT // <-- TODO: support read/write mapping //GetStagingVkBufferUsageFlags(desc.cpuAccessFlags) ); auto stagingBuffer = CreateStagingBuffer(stagingCreateInfo, initialData, initialDataSize); /* Create device texture */ auto textureVK = MakeUnique<VKTexture>(device_, *deviceMemoryMngr_, textureDesc); auto image = textureVK->GetVkImage(); auto mipLevels = textureVK->GetNumMipLevels(); auto arrayLayers = textureVK->GetNumArrayLayers(); /* Copy staging buffer into hardware texture, then transfer image into sampling-ready state */ auto formatVK = VKTypes::Map(textureDesc.format); auto cmdBuffer = device_.AllocCommandBuffer(); { const TextureSubresource subresource{ 0, arrayLayers, 0, mipLevels }; device_.TransitionImageLayout( cmdBuffer, image, formatVK, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource ); device_.CopyBufferToImage( cmdBuffer, stagingBuffer.GetVkBuffer(), image, VkOffset3D{ 0, 0, 0 }, GetTextureVkExtent(textureDesc), 0, GetTextureLayertCount(textureDesc) ); device_.TransitionImageLayout( cmdBuffer, image, formatVK, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource ); /* Generate MIP-maps if enabled */ if (imageDesc != nullptr && MustGenerateMipsOnCreate(textureDesc)) { device_.GenerateMips( cmdBuffer, textureVK->GetVkImage(), textureVK->GetVkExtent(), subresource ); } } device_.FlushCommandBuffer(cmdBuffer); /* Release staging buffer */ stagingBuffer.ReleaseMemoryRegion(*deviceMemoryMngr_); /* Create image view for texture */ textureVK->CreateInternalImageView(device_); return TakeOwnership(textures_, std::move(textureVK)); } void VKRenderSystem::Release(Texture& texture) { /* Release device memory region, then release texture object */ auto& textureVK = LLGL_CAST(VKTexture&, texture); deviceMemoryMngr_->Release(textureVK.GetMemoryRegion()); RemoveFromUniqueSet(textures_, &texture); } void VKRenderSystem::WriteTexture(Texture& texture, const TextureRegion& textureRegion, const SrcImageDescriptor& imageDesc) { auto& textureVK = LLGL_CAST(VKTexture&, texture); const auto& cfg = GetConfiguration(); /* Determine size of image for staging buffer */ const auto& offset = textureRegion.offset; const auto& extent = textureRegion.extent; const auto& subresource = textureRegion.subresource; const auto format = VKTypes::Unmap(textureVK.GetVkFormat()); auto image = textureVK.GetVkImage(); const auto imageSize = extent.width * extent.height * extent.depth; const void* imageData = nullptr; const auto imageDataSize = static_cast<VkDeviceSize>(TextureBufferSize(format, imageSize)); /* Check if image data must be converted */ ByteBuffer intermediateData; const auto& formatAttribs = GetFormatAttribs(format); if (formatAttribs.bitSize > 0 && (formatAttribs.flags & FormatFlags::IsCompressed) == 0) { /* Convert image format (will be null if no conversion is necessary) */ intermediateData = ConvertImageBuffer(imageDesc, formatAttribs.format, formatAttribs.dataType, cfg.threadCount); } if (intermediateData) { /* Validate that source image data was large enough so conversion is valid, then use temporary image buffer as source for initial data */ const auto srcImageDataSize = imageSize * ImageFormatSize(imageDesc.format) * DataTypeSize(imageDesc.dataType); AssertImageDataSize(imageDesc.dataSize, static_cast<std::size_t>(srcImageDataSize)); imageData = intermediateData.get(); } else { /* Validate that image data is large enough, then use input data as source for initial data */ AssertImageDataSize(imageDesc.dataSize, static_cast<std::size_t>(imageDataSize)); imageData = imageDesc.data; } /* Create staging buffer */ VkBufferCreateInfo stagingCreateInfo; BuildVkBufferCreateInfo( stagingCreateInfo, imageDataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT // <-- TODO: support read/write mapping //GetStagingVkBufferUsageFlags(desc.cpuAccessFlags) ); auto stagingBuffer = CreateStagingBuffer(stagingCreateInfo, imageData, imageDataSize); /* Copy staging buffer into hardware texture, then transfer image into sampling-ready state */ auto cmdBuffer = device_.AllocCommandBuffer(); { device_.TransitionImageLayout( cmdBuffer, image, textureVK.GetVkFormat(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource ); device_.CopyBufferToImage( cmdBuffer, stagingBuffer.GetVkBuffer(), image, VkOffset3D{ offset.x, offset.y, offset.z }, VkExtent3D{ extent.width, extent.height, extent.depth }, subresource.baseArrayLayer, subresource.numArrayLayers, subresource.baseMipLevel ); device_.TransitionImageLayout( cmdBuffer, image, textureVK.GetVkFormat(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource ); } device_.FlushCommandBuffer(cmdBuffer); /* Release staging buffer */ stagingBuffer.ReleaseMemoryRegion(*deviceMemoryMngr_); } void VKRenderSystem::ReadTexture(const Texture& texture, std::uint32_t mipLevel, const DstImageDescriptor& imageDesc) { //todo } /* ----- Sampler States ---- */ Sampler* VKRenderSystem::CreateSampler(const SamplerDescriptor& desc) { return TakeOwnership(samplers_, MakeUnique<VKSampler>(device_, desc)); } void VKRenderSystem::Release(Sampler& sampler) { RemoveFromUniqueSet(samplers_, &sampler); } /* ----- Resource Heaps ----- */ ResourceHeap* VKRenderSystem::CreateResourceHeap(const ResourceHeapDescriptor& desc) { return TakeOwnership(resourceHeaps_, MakeUnique<VKResourceHeap>(device_, desc)); } void VKRenderSystem::Release(ResourceHeap& resourceHeap) { RemoveFromUniqueSet(resourceHeaps_, &resourceHeap); } /* ----- Render Passes ----- */ RenderPass* VKRenderSystem::CreateRenderPass(const RenderPassDescriptor& desc) { AssertCreateRenderPass(desc); return TakeOwnership(renderPasses_, MakeUnique<VKRenderPass>(device_, desc)); } void VKRenderSystem::Release(RenderPass& renderPass) { RemoveFromUniqueSet(renderPasses_, &renderPass); } /* ----- Render Targets ----- */ RenderTarget* VKRenderSystem::CreateRenderTarget(const RenderTargetDescriptor& desc) { AssertCreateRenderTarget(desc); return TakeOwnership(renderTargets_, MakeUnique<VKRenderTarget>(device_, *deviceMemoryMngr_, desc)); } void VKRenderSystem::Release(RenderTarget& renderTarget) { /* Release device memory region, then release texture object */ auto& renderTargetVL = LLGL_CAST(VKRenderTarget&, renderTarget); renderTargetVL.ReleaseDeviceMemoryResources(*deviceMemoryMngr_); RemoveFromUniqueSet(renderTargets_, &renderTarget); } /* ----- Shader ----- */ Shader* VKRenderSystem::CreateShader(const ShaderDescriptor& desc) { AssertCreateShader(desc); return TakeOwnership(shaders_, MakeUnique<VKShader>(device_, desc)); } ShaderProgram* VKRenderSystem::CreateShaderProgram(const ShaderProgramDescriptor& desc) { AssertCreateShaderProgram(desc); return TakeOwnership(shaderPrograms_, MakeUnique<VKShaderProgram>(desc)); } void VKRenderSystem::Release(Shader& shader) { RemoveFromUniqueSet(shaders_, &shader); } void VKRenderSystem::Release(ShaderProgram& shaderProgram) { RemoveFromUniqueSet(shaderPrograms_, &shaderProgram); } /* ----- Pipeline Layouts ----- */ PipelineLayout* VKRenderSystem::CreatePipelineLayout(const PipelineLayoutDescriptor& desc) { return TakeOwnership(pipelineLayouts_, MakeUnique<VKPipelineLayout>(device_, desc)); } void VKRenderSystem::Release(PipelineLayout& pipelineLayout) { RemoveFromUniqueSet(pipelineLayouts_, &pipelineLayout); } /* ----- Pipeline States ----- */ GraphicsPipeline* VKRenderSystem::CreateGraphicsPipeline(const GraphicsPipelineDescriptor& desc) { return TakeOwnership( graphicsPipelines_, MakeUnique<VKGraphicsPipeline>( device_, defaultPipelineLayout_, (!renderContexts_.empty() ? (*renderContexts_.begin())->GetRenderPass() : nullptr), desc, gfxPipelineLimits_ ) ); } ComputePipeline* VKRenderSystem::CreateComputePipeline(const ComputePipelineDescriptor& desc) { return TakeOwnership(computePipelines_, MakeUnique<VKComputePipeline>(device_, desc, defaultPipelineLayout_)); } void VKRenderSystem::Release(GraphicsPipeline& graphicsPipeline) { RemoveFromUniqueSet(graphicsPipelines_, &graphicsPipeline); } void VKRenderSystem::Release(ComputePipeline& computePipeline) { RemoveFromUniqueSet(computePipelines_, &computePipeline); } /* ----- Queries ----- */ QueryHeap* VKRenderSystem::CreateQueryHeap(const QueryHeapDescriptor& desc) { return TakeOwnership(queryHeaps_, MakeUnique<VKQueryHeap>(device_, desc)); } void VKRenderSystem::Release(QueryHeap& queryHeap) { RemoveFromUniqueSet(queryHeaps_, &queryHeap); } /* ----- Fences ----- */ Fence* VKRenderSystem::CreateFence() { return TakeOwnership(fences_, MakeUnique<VKFence>(device_)); } void VKRenderSystem::Release(Fence& fence) { RemoveFromUniqueSet(fences_, &fence); } /* * ======= Private: ======= */ #ifndef VK_LAYER_KHRONOS_VALIDATION_NAME #define VK_LAYER_KHRONOS_VALIDATION_NAME "VK_LAYER_KHRONOS_validation" #endif void VKRenderSystem::CreateInstance(const RendererConfigurationVulkan* config) { /* Query instance layer properties */ auto layerProperties = VKQueryInstanceLayerProperties(); std::vector<const char*> layerNames; for (const auto& prop : layerProperties) { if (IsLayerRequired(prop.layerName, config)) layerNames.push_back(prop.layerName); } /* Query instance extension properties */ auto extensionProperties = VKQueryInstanceExtensionProperties(); std::vector<const char*> extensionNames; for (const auto& prop : extensionProperties) { if (IsExtensionRequired(prop.extensionName)) extensionNames.push_back(prop.extensionName); } /* Setup Vulkan instance descriptor */ VkInstanceCreateInfo instanceInfo; VkApplicationInfo appInfo; instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceInfo.pNext = nullptr; instanceInfo.flags = 0; /* Specify application descriptor */ if (config != nullptr) { /* Initialize application information struct */ { appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; appInfo.pApplicationName = config->application.applicationName.c_str(); appInfo.applicationVersion = config->application.applicationVersion; appInfo.pEngineName = config->application.engineName.c_str(); appInfo.engineVersion = config->application.engineVersion; appInfo.apiVersion = VK_API_VERSION_1_0; } instanceInfo.pApplicationInfo = (&appInfo); } else instanceInfo.pApplicationInfo = nullptr; /* Specify layers to enable */ if (layerNames.empty()) { instanceInfo.enabledLayerCount = 0; instanceInfo.ppEnabledLayerNames = nullptr; } else { instanceInfo.enabledLayerCount = static_cast<std::uint32_t>(layerNames.size()); instanceInfo.ppEnabledLayerNames = layerNames.data(); } /* Specify extensions to enable */ if (extensionNames.empty()) { instanceInfo.enabledExtensionCount = 0; instanceInfo.ppEnabledExtensionNames = nullptr; } else { instanceInfo.enabledExtensionCount = static_cast<std::uint32_t>(extensionNames.size()); instanceInfo.ppEnabledExtensionNames = extensionNames.data(); } /* Create Vulkan instance */ VkResult result = vkCreateInstance(&instanceInfo, nullptr, instance_.ReleaseAndGetAddressOf()); VKThrowIfFailed(result, "failed to create Vulkan instance"); if (debugLayerEnabled_) CreateDebugReportCallback(); /* Load Vulkan instance extensions */ VKLoadInstanceExtensions(instance_); } static Log::ReportType ToReportType(VkDebugReportFlagsEXT flags) { if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0) return Log::ReportType::Error; if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0) return Log::ReportType::Warning; if ((flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) != 0) return Log::ReportType::Performance; return Log::ReportType::Information; } static VKAPI_ATTR VkBool32 VKAPI_CALL VKDebugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* layerPrefix, const char* message, void* userData) { //auto renderSystemVK = reinterpret_cast<VKRenderSystem*>(userData); Log::PostReport(ToReportType(flags), message, "vkDebugReportCallback"); return VK_FALSE; } void VKRenderSystem::CreateDebugReportCallback() { /* Initialize flags */ VkDebugReportFlagsEXT flags = 0; //flags |= VK_DEBUG_REPORT_INFORMATION_BIT_EXT; flags |= VK_DEBUG_REPORT_WARNING_BIT_EXT; //flags |= VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; flags |= VK_DEBUG_REPORT_ERROR_BIT_EXT; //flags |= VK_DEBUG_REPORT_DEBUG_BIT_EXT; /* Create report callback */ VkDebugReportCallbackCreateInfoEXT createInfo; { createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; createInfo.pNext = nullptr; createInfo.flags = flags; createInfo.pfnCallback = VKDebugCallback; createInfo.pUserData = reinterpret_cast<void*>(this); } auto result = CreateDebugReportCallbackEXT(instance_, &createInfo, nullptr, debugReportCallback_.ReleaseAndGetAddressOf()); VKThrowIfFailed(result, "failed to create Vulkan debug report callback"); } void VKRenderSystem::PickPhysicalDevice() { /* Pick physical device with Vulkan support */ if (!physicalDevice_.PickPhysicalDevice(instance_)) throw std::runtime_error("failed to find suitable Vulkan device"); /* Query and store rendering capabilities */ RendererInfo info; RenderingCapabilities caps; physicalDevice_.QueryDeviceProperties(info, caps, gfxPipelineLimits_); /* Store Vulkan extension names */ const auto& extensions = physicalDevice_.GetExtensionNames(); info.extensionNames = std::vector<std::string>(extensions.begin(), extensions.end()); SetRendererInfo(info); SetRenderingCaps(caps); } void VKRenderSystem::CreateLogicalDevice() { /* Create logical device with all supported physical device feature */ device_ = physicalDevice_.CreateLogicalDevice(); /* Create command queue interface */ commandQueue_ = MakeUnique<VKCommandQueue>(device_, device_.GetVkQueue()); /* Load Vulkan device extensions */ VKLoadDeviceExtensions(device_, physicalDevice_.GetExtensionNames()); } void VKRenderSystem::CreateDefaultPipelineLayout() { VkPipelineLayoutCreateInfo layoutCreateInfo = {}; { layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; } auto result = vkCreatePipelineLayout(device_, &layoutCreateInfo, nullptr, defaultPipelineLayout_.ReleaseAndGetAddressOf()); VKThrowIfFailed(result, "failed to create Vulkan default pipeline layout"); } bool VKRenderSystem::IsLayerRequired(const char* name, const RendererConfigurationVulkan* config) const { if (config != nullptr) { for (const auto& layer : config->enabledLayers) { if (std::strcmp(layer.c_str(), name) == 0) return true; } } if (debugLayerEnabled_) { if (std::strcmp(name, VK_LAYER_KHRONOS_VALIDATION_NAME) == 0) return true; } return false; } bool VKRenderSystem::IsExtensionRequired(const std::string& name) const { return ( name == VK_KHR_SURFACE_EXTENSION_NAME #ifdef LLGL_OS_WIN32 || name == VK_KHR_WIN32_SURFACE_EXTENSION_NAME #endif #ifdef LLGL_OS_LINUX || name == VK_KHR_XLIB_SURFACE_EXTENSION_NAME #endif || (debugLayerEnabled_ && name == VK_EXT_DEBUG_REPORT_EXTENSION_NAME) ); } VKDeviceBuffer VKRenderSystem::CreateStagingBuffer(const VkBufferCreateInfo& createInfo) { return VKDeviceBuffer { device_, createInfo, *deviceMemoryMngr_, (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) }; } VKDeviceBuffer VKRenderSystem::CreateStagingBuffer( const VkBufferCreateInfo& createInfo, const void* data, VkDeviceSize dataSize) { /* Allocate staging buffer */ auto stagingBuffer = CreateStagingBuffer(createInfo); /* Copy initial data to buffer memory */ if (data != nullptr && dataSize > 0) device_.WriteBuffer(stagingBuffer, data, dataSize); return stagingBuffer; } } // /namespace LLGL // ================================================================================
33.35512
195
0.686022
Krypton-Dev
73d0b6a7bf3b74b9f32bda054da69bd9333ae7b8
530
hpp
C++
libs/common/result_fwd.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
libs/common/result_fwd.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
libs/common/result_fwd.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_RESULT_FWD_HPP #define IROHA_RESULT_FWD_HPP namespace iroha { namespace expected { struct ValueBase; template <typename T> struct Value; struct ErrorBase; template <typename E> struct Error; class ResultException; struct ResultBase; template <typename V, typename E> class Result; } // namespace expected } // namespace iroha #endif // IROHA_RESULT_FWD_HPP
16.060606
53
0.692453
akshatkarani
73d100c00fc7c810da2fc583bf38aec05b12007c
21,026
cxx
C++
source/OOSQL/Evaluator/oosql_Eval_DS.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
6
2016-08-29T08:03:21.000Z
2022-03-25T09:56:23.000Z
source/OOSQL/Evaluator/oosql_Eval_DS.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
source/OOSQL/Evaluator/oosql_Eval_DS.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************/ /* */ /* Copyright (c) 1990-2016, KAIST */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* 3. Neither the name of the copyright holder nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /******************************************************************************/ /******************************************************************************/ /* */ /* ODYSSEUS/OOSQL DB-IR-Spatial Tightly-Integrated DBMS */ /* Version 5.0 */ /* */ /* Developed by Professor Kyu-Young Whang et al. */ /* */ /* Advanced Information Technology Research Center (AITrc) */ /* Korea Advanced Institute of Science and Technology (KAIST) */ /* */ /* e-mail: odysseus.oosql@gmail.com */ /* */ /* Bibliography: */ /* [1] Whang, K., Lee, J., Lee, M., Han, W., Kim, M., and Kim, J., "DB-IR */ /* Integration Using Tight-Coupling in the Odysseus DBMS," World Wide */ /* Web, Vol. 18, No. 3, pp. 491-520, May 2015. */ /* [2] Whang, K., Lee, M., Lee, J., Kim, M., and Han, W., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with IR Features," In Proc. */ /* IEEE 21st Int'l Conf. on Data Engineering (ICDE), pp. 1104-1105 */ /* (demo), Tokyo, Japan, April 5-8, 2005. This paper received the Best */ /* Demonstration Award. */ /* [3] Whang, K., Park, B., Han, W., and Lee, Y., "An Inverted Index */ /* Storage Structure Using Subindexes and Large Objects for Tight */ /* Coupling of Information Retrieval with Database Management */ /* Systems," U.S. Patent No.6,349,308 (2002) (Appl. No. 09/250,487 */ /* (1999)). */ /* [4] Whang, K., Lee, J., Kim, M., Lee, M., Lee, K., Han, W., and Kim, */ /* J., "Tightly-Coupled Spatial Database Features in the */ /* Odysseus/OpenGIS DBMS for High-Performance," GeoInformatica, */ /* Vol. 14, No. 4, pp. 425-446, Oct. 2010. */ /* [5] Whang, K., Lee, J., Kim, M., Lee, M., and Lee, K., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with Spatial Database */ /* Features," In Proc. 23rd IEEE Int'l Conf. on Data Engineering */ /* (ICDE), pp. 1493-1494 (demo), Istanbul, Turkey, Apr. 16-20, 2007. */ /* */ /******************************************************************************/ /* MODULE: OOSQL_EvalDS.C DESCRIPTION: This module implements the data structures used for query evaluation module. IMPORTS: EXPORTS: */ #include "OOSQL_Eval_DS.hxx" OOSQL_EvalBuffer::OOSQL_EvalBuffer() { nCols = 0; nGrpByCols = 0; nAggrFuncResults = 0; nFuncMatchResults = 0; strBufSize = 0; isDualBuf = SM_FALSE; clist = NULL; prevColList = NULL; methodResult = NULL; grpByColList = NULL; aggrFuncResults = NULL; funcMatchResults = NULL; nTuplesForSumAndAvg = NULL; strBuf = NULL; } Four OOSQL_EvalBuffer::init( Four numCols, /* IN: evaluation buffer size (the # of columns) */ Four nGrpByKeys, /* IN: */ Four nAggrFunc, /* IN: */ Four nFuncMatch, /* IN: # of MATCH function result */ Four stringSize, /* IN: memory size for string and variable string */ Boolean isDualBuffer /* IN: flag indicating */ ) { char *pCurrBufSlot; if (numCols < 0) { OOSQL_PRTERR(eBADPARAMETER_OOSQL); numCols = 0; } if (nGrpByKeys < 0) { OOSQL_PRTERR(eBADPARAMETER_OOSQL); nGrpByKeys = 0; } if (nAggrFunc < 0) { OOSQL_PRTERR(eBADPARAMETER_OOSQL); nAggrFunc = 0; } if (nFuncMatch < 0) { OOSQL_PRTERR(eBADPARAMETER_OOSQL); nFuncMatch = 0; } if (stringSize < 0) { OOSQL_PRTERR(eBADPARAMETER_OOSQL); stringSize = 0; } this->isDualBuf = isDualBuffer; this->nCols = numCols; this->clist = (EVAL_EvalBufferSlot*)pMemoryManager->Alloc(sizeof(EVAL_EvalBufferSlot) * (numCols + nGrpByKeys + nAggrFunc + nFuncMatch)); if(this->isDualBuf == SM_TRUE) this->prevColList = (EVAL_EvalBufferSlot*)pMemoryManager->Alloc(sizeof(EVAL_EvalBufferSlot) * (numCols + nGrpByKeys + nAggrFunc + nFuncMatch)); else this->prevColList = NULL; this->nGrpByCols = nGrpByKeys; this->grpByColList = (EVAL_EvalBufferSlot*) pMemoryManager->Alloc(sizeof(EVAL_EvalBufferSlot) * nGrpByKeys); this->nAggrFuncResults = nAggrFunc; this->aggrFuncResults = (EVAL_EvalBufferSlot*) pMemoryManager->Alloc(sizeof(EVAL_EvalBufferSlot) * nAggrFunc); this->aggrFuncResults->nullFlag = SM_FALSE; this->nTuplesForSumAndAvg = (Four*) pMemoryManager->Alloc(sizeof(Four) * nAggrFunc); this->nFuncMatchResults = nFuncMatch; this->funcMatchResults = (EVAL_EvalBufferSlot*) pMemoryManager->Alloc(sizeof(EVAL_EvalBufferSlot) * nFuncMatch); this->strBufSize = stringSize; if(isDualBuffer == SM_TRUE) this->strBuf = (char*) pMemoryManager->Alloc(sizeof(char) * stringSize * 2); else this->strBuf = (char*) pMemoryManager->Alloc(sizeof(char) * stringSize); return eNOERROR; } OOSQL_EvalBuffer::~OOSQL_EvalBuffer() { pMemoryManager->Free(clist); if(prevColList) pMemoryManager->Free(prevColList); pMemoryManager->Free(grpByColList); pMemoryManager->Free(aggrFuncResults); pMemoryManager->Free(nTuplesForSumAndAvg); pMemoryManager->Free(funcMatchResults); pMemoryManager->Free(strBuf); } Four OOSQL_EvalBuffer::getLogicalID() /* Function: Side effect: Referenced member variables: Return value: */ { return logicalID; } EVAL_EvalBufferSlot* OOSQL_EvalBuffer::getColSlotPtr( Four colSlotIndex // IN: ) /* Function: Side effect: Referenced member variables: Return value: */ { /* check input paramter */ if (colSlotIndex < 0 || nCols <= colSlotIndex) { return NULL; } /* return pointer to the buffer slot */ return &clist[colSlotIndex]; } EVAL_EvalBufferSlot* OOSQL_EvalBuffer::getGrpBySlotPtr( Four grpBySlotIndex // IN: ) /* Function: Side effect: Referenced member variables: Return value: */ { /* check input paramter */ if (grpBySlotIndex < 0 || nGrpByCols <= grpBySlotIndex) { return NULL; } /* return pointer to the buffer slot */ return &grpByColList[grpBySlotIndex]; } EVAL_EvalBufferSlot* OOSQL_EvalBuffer::getAggrFuncResSlotPtr( Four aggrFuncIndex // IN: ) /* Function: Side effect: Referenced member variables: Return value: */ { /* check input paramter */ if (aggrFuncIndex < 0 || nAggrFuncResults <= aggrFuncIndex) { return NULL; } /* return pointer to the buffer slot */ return &aggrFuncResults[aggrFuncIndex]; } EVAL_EvalBufferSlot* OOSQL_EvalBuffer::getFnMatchSlotPtr( Four matchFuncNum // IN: ) /* Function: Side effect: Referenced member variables: Return value: */ { /* check input parameter */ if (matchFuncNum < 0 || nFuncMatchResults <= matchFuncNum) { return NULL; } /* return pointer to the buffer slot */ return &funcMatchResults[matchFuncNum]; } OOSQL_ScanInfoTable::OOSQL_ScanInfoTable( Four numElem // IN: ) /* Function: Side effect: Referenced member variables: Return value: */ { /* check input parameters */ if (numElem < 0) return; /* allocate memory */ tableSize = (numElem > 0)? numElem: 0; if(tableSize > 0) { OOSQL_ARRAYNEW(scanInfos, pMemoryManager, OOSQL_ScanInfo, tableSize); } else { scanInfos = NULL; } } OOSQL_ScanInfoTable::~OOSQL_ScanInfoTable() { if(scanInfos) { for(int i = 0; i < tableSize; i++) { if(scanInfos[i].boolExprs) pMemoryManager->Free(scanInfos[i].boolExprs); } OOSQL_ARRAYDELETE(OOSQL_ScanInfo, scanInfos); } } Four OOSQL_ScanInfoTable::prepareBoolExpression(int index, int nBools) { if(scanInfos[index].boolExprs) pMemoryManager->Free(scanInfos[index].boolExprs); scanInfos[index].boolExprs = (OOSQL_StorageManager::BoolExp*)pMemoryManager->Alloc(sizeof(OOSQL_StorageManager::BoolExp) * nBools); scanInfos[index].nBoolExprs = nBools; return eNOERROR; } Four OOSQL_ScanInfoTable::resetBoolExpression(int index) { if(scanInfos[index].boolExprs) pMemoryManager->Free(scanInfos[index].boolExprs); scanInfos[index].boolExprs = NULL; scanInfos[index].nBoolExprs = 0; return eNOERROR; } OOSQL_AccessElement::OOSQL_AccessElement() /* Function: Side effect: Referenced member variables: Return value: */ { /* initialize member variables */ classId = -1; ocn = -1; osn = -1; } OOSQL_AccessList::OOSQL_AccessList() /* Function: Constructor Side effect: Initialize members. Return value: */ { // do minimal initialization numClasses = 0; accessList = NULL; endOfCurrAccess = SM_FALSE; accessDirection = ACCESSDIRECTION_FORWARD; currAccessIndex = 0; writeOcn = -1; writeColList = NULL; } Four OOSQL_AccessList::init( Four num_scans // IN: the # of scans ) /* Function: Constructor Side effect: Initialize members. Return value: */ { int i; /* * initialze member variables */ numClasses = (num_scans > 0)? num_scans: 0; if(numClasses > 0) { OOSQL_ARRAYNEW(accessList, pMemoryManager, OOSQL_AccessElement, numClasses); } else accessList = NULL; endOfCurrAccess = SM_FALSE; /* initialized accessDirection */ accessDirection = ACCESSDIRECTION_FORWARD; currAccessIndex = 0; writeOcn = -1; writeColList = NULL; return eNOERROR; } OOSQL_AccessList::~OOSQL_AccessList() { if(accessList) OOSQL_ARRAYDELETE(OOSQL_AccessElement, accessList); } Four OOSQL_AccessList::isEndOfCurrAccess() /* Function: Check if the current scan reached to the end. Side effect: Return value: SM_TRUE if end of scan SM_FALSE otherwise */ { if (endOfCurrAccess == SM_TRUE) return SM_TRUE; else return SM_FALSE; } Four OOSQL_AccessList::isEndOfAllAccess() /* Function: Check if all of the scans reached to the end. Side effect: Return value: SM_TRUE if end of all scans SM_FALSE otherwise */ { if (isEndOfCurrAccess()) { switch (accessDirection) { case ACCESSDIRECTION_FORWARD: if (currAccessIndex == (numClasses-1)) return SM_TRUE; break; case ACCESSDIRECTION_BACKWARD: if (currAccessIndex == 0) return SM_TRUE; break; default: OOSQL_ERR(eINVALID_CASE_OOSQL); } } return SM_FALSE; } Four OOSQL_AccessList::setEndOfAllAccess() /* Function: Side effect: Referenced member variables: Return value: */ { endOfCurrAccess = SM_TRUE; switch (accessDirection) { case ACCESSDIRECTION_FORWARD: currAccessIndex = numClasses-1; break; case ACCESSDIRECTION_BACKWARD: currAccessIndex = 0; break; default: OOSQL_ERR(eINVALID_CASE_OOSQL); } return(eNOERROR); } Four OOSQL_AccessList::getCurrClassID() /* Function: Return class ID of the current class. Side effect: Return value: class ID */ { return accessList[currAccessIndex].classId; } Four OOSQL_AccessList::getCurrOcn() /* Function: Return open class number of the current class. Side effect: Return value: >= 0 open class number */ { return accessList[currAccessIndex].ocn; } Four OOSQL_AccessList::getCurrScanID() /* Function: Return scan ID of the current scan. Side effect: Return value: >= 0 scan ID */ { return accessList[currAccessIndex].osn; } Four OOSQL_AccessList::moveToNextAccessElem() /* Function: Prepare the next scan. Side effect: Return value: */ { #ifdef OOSQL_DEBUG if (currAccessIndex < 0 || (numClasses-1) <= currAccessIndex) OOSQL_ERR(eINTERNAL_INCORRECTEXECSEQUENCE_OOSQL); #endif /* distinguished the direction of accessing classes (for class hierarchy search) */ switch (accessDirection) { case ACCESSDIRECTION_FORWARD: if (currAccessIndex < (numClasses-1)) { currAccessIndex ++; endOfCurrAccess = SM_FALSE; } break; case ACCESSDIRECTION_BACKWARD: if (currAccessIndex > 0) { currAccessIndex --; endOfCurrAccess = SM_FALSE; } break; default: OOSQL_ERR(eINVALID_CASE_OOSQL); } return(eNOERROR); } Four OOSQL_AccessList::reverseAccessDirection() /* Function: Close all scans and reopen them for the current scan list. Side effect: All scans previously opened are closed and then reopened. Return value: eNOERROR if no error < eNOERROR error code */ { /* re-initialize scan list control variable */ endOfCurrAccess = SM_FALSE; /* reverses the direction of accessing access elements */ switch (accessDirection) { case ACCESSDIRECTION_FORWARD: accessDirection = ACCESSDIRECTION_BACKWARD; break; case ACCESSDIRECTION_BACKWARD: accessDirection = ACCESSDIRECTION_FORWARD; break; default: OOSQL_ERR(eINVALID_CASE_OOSQL); } /* do not reinitialize currAccessIndex here because * the order of accesses go and return. currAccessIndex = 0; */ return(eNOERROR); } TempFileSavingInfo::TempFileSavingInfo() /* Function: Side effect: Return value: */ { savingPlanNo = -1; } OOSQL_TempFileInfoTable::OOSQL_TempFileInfoTable( Four numTempFiles // the # of temporary files ) /* Function: Constructor. Side effect: Initialize member variables. Return value: */ { nTempFiles = ((numTempFiles > 0)? numTempFiles: 0); tempFileInfo = (OOSQL_TempFileInfo**)pMemoryManager->Alloc(sizeof(OOSQL_TempFileInfo*) * nTempFiles); } OOSQL_TempFileInfoTable::~OOSQL_TempFileInfoTable() { pMemoryManager->Free(tempFileInfo); } Four OOSQL_TempFileInfo::isNotCreated() /* Function: Check if temp. file for 'tempFileNum' is not yet created. Side effect: Return value: SM_TRUE if temp. file is not yet created SM_FALSE otherwise */ { if ( name[0] == NULL ) return SM_TRUE; else return SM_FALSE; } Four OOSQL_TempFileInfo::getOcn() /* Function: Get open class number for 'tempFileNum'. Side effect: Return value: > 0 if temp. file is created and opened < eNOERROR error code */ { if(sortStream) { return NIL; } else if(name[0] == NULL) { OOSQL_ERR(eINVALID_TEMPFILENUM_OOSQL); } return ocn; } Four OOSQL_TempFileInfo::getOsn() /* Function: Get open scan number for 'tempFileNum'. Side effect: Return value: > 0 if temp. file is created and opened < eNOERROR error code */ { if ( name[0] == NULL ) { OOSQL_ERR( eINVALID_TEMPFILENUM_OOSQL); } return osn; } OOSQL_TempFileInfo::OOSQL_TempFileInfo( Four numCols, Four stringBufSize, Boolean isDualBuffer ) /* Function: Side effect: Return value: */ { Four strBufSizeToAlloc; name[0] = NULL; ocn = -1; osn = -1; sortStream = NULL; indexName[0] = NULL; nCols = (numCols > 0)? numCols: 0; isDualBuf = isDualBuffer; strBufSize = (stringBufSize > 0)? stringBufSize: 0; clist = (OOSQL_StorageManager::ColListStruct*)pMemoryManager->Alloc(sizeof(OOSQL_StorageManager::ColListStruct) * nCols); if (isDualBuf == SM_TRUE) { prevColList = (OOSQL_StorageManager::ColListStruct*)pMemoryManager->Alloc(sizeof(OOSQL_StorageManager::ColListStruct) * nCols); strBufSizeToAlloc = (stringBufSize > 0)? (stringBufSize * 2): 0; } else { prevColList = NULL; strBufSizeToAlloc = (stringBufSize > 0)? stringBufSize: 0; } strBuf = (char*)pMemoryManager->Alloc(strBufSizeToAlloc); attrInfo = (OOSQL_StorageManager::AttrInfo*)pMemoryManager->Alloc(sizeof(OOSQL_StorageManager::AttrInfo) * nCols); isTextAttrExist = NIL; useFastEncoding = NIL; firstFastEncodedNextScan = SM_TRUE; } OOSQL_TempFileInfo::~OOSQL_TempFileInfo() { pMemoryManager->Free(clist); if(prevColList) pMemoryManager->Free(prevColList); pMemoryManager->Free(strBuf); pMemoryManager->Free(attrInfo); } Four OOSQL_TempFileInfo::saveCurrTuple() /* Function: Save the current data stored in OOSQL_StorageManager::ColListStruct by exchanging two pointers for OOSQL_StorageManager::ColListStruct. Side effect: Return value: */ { OOSQL_StorageManager::ColListStruct *temp; // temp = clist; // clist = prevColList; *prevColList = *clist; return eNOERROR; } OOSQL_EvalIndexBuffer::OOSQL_EvalIndexBuffer() { } OOSQL_EvalIndexBuffer::~OOSQL_EvalIndexBuffer() { }
24.971496
133
0.56744
odysseus-oosql
73d123bd0a92bd1dce91c3d5410c13cea3ccb50b
2,191
cpp
C++
Libraries/LibCore/GetPassword.cpp
galileoDesk/serenity
602a830428986463e63b8cf2fdd4fbb621280d06
[ "BSD-2-Clause" ]
2
2021-06-09T01:33:00.000Z
2021-06-09T01:33:06.000Z
Libraries/LibCore/GetPassword.cpp
galileoDesk/serenity
602a830428986463e63b8cf2fdd4fbb621280d06
[ "BSD-2-Clause" ]
null
null
null
Libraries/LibCore/GetPassword.cpp
galileoDesk/serenity
602a830428986463e63b8cf2fdd4fbb621280d06
[ "BSD-2-Clause" ]
1
2021-06-25T06:30:52.000Z
2021-06-25T06:30:52.000Z
/* * Copyright (c) 2020, Peter Elliott <pelliott@ualberta.ca> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <LibCore/GetPassword.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> namespace Core { Result<String, int> get_password(const StringView& prompt) { fwrite(prompt.characters_without_null_termination(), sizeof(char), prompt.length(), stdout); fflush(stdout); struct termios original; tcgetattr(STDIN_FILENO, &original); struct termios no_echo = original; no_echo.c_lflag &= ~ECHO; if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &no_echo) < 0) { return errno; } char* password = nullptr; size_t n = 0; int ret = getline(&password, &n, stdin); tcsetattr(STDIN_FILENO, TCSAFLUSH, &original); putchar('\n'); if (ret < 0) { return errno; } String s(password); free(password); return s; } }
34.234375
96
0.724327
galileoDesk
73d3c0bb8fcba84c94f6e0bc8abff24ee7f93529
910
hpp
C++
src/Module/Codec/RSC/Codec_RSC.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Codec/RSC/Codec_RSC.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Codec/RSC/Codec_RSC.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
#ifndef CODEC_RSC_HPP_ #define CODEC_RSC_HPP_ #include "Factory/Module/Encoder/RSC/Encoder_RSC.hpp" #include "Factory/Module/Decoder/RSC/Decoder_RSC.hpp" #include "../Codec_SISO_SIHO.hpp" namespace aff3ct { namespace module { template <typename B = int, typename Q = float> class Codec_RSC : public Codec_SISO_SIHO<B,Q> { protected: const bool buffered_encoding; std::vector<std::vector<int>> trellis; public: Codec_RSC(const factory::Encoder_RSC::parameters &enc_params, const factory::Decoder_RSC::parameters &dec_params); virtual ~Codec_RSC(); protected: void _extract_sys_par(const Q *Y_N, Q *sys, Q *par, const int frame_id); void _extract_sys_llr(const Q *Y_N, Q *sys, const int frame_id); void _add_sys_ext (const Q *ext, Q *Y_N, const int frame_id); void _extract_sys_bit(const Q *Y_N, B *V_K, const int frame_id); }; } } #endif /* CODEC_RSC_HPP_ */
26
73
0.723077
codechecker123
73d582f4675ce156f6f801d97e4af6e555e94ceb
3,432
cpp
C++
test/single_phase_pressuer_solver_test.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
test/single_phase_pressuer_solver_test.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
test/single_phase_pressuer_solver_test.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "../src/fluid_solvers/single_phase_pressure_solver.hpp" void ___PrintArray3(const Array3<double>& input) { const auto& size = input.GetSize(); std::cout << std::setprecision(2) << std::fixed; std::cout << "Size: (" << size.x << ", " << size.y << ", " << size.z << ")\n"; for(size_t j = size.y ; j > 0; j--) { for(size_t k = 0; k < size.z; k++) { for(size_t i = 0; i < size.x; i++) { std::cout << input(i, j - 1, k) << " "; } std::cout << " "; } std::cout << "\n"; } std::cout << "\n"; } TEST(SinglePhasePressureSolverTest, Solve_test) { const Vector3<size_t> size(6, 6, 3); FaceCenteredGrid3D input(size, 0, 1, 1); ScalarGrid3D sdf(size, 1, Vector3<double>(0, 0, 0)); SinglePhasePressureSolver solver; auto& xData = input.GetDataXRef(); auto& yData = input.GetDataYRef(); auto& zData = input.GetDataZRef(); xData(2, 2, 1) = yData(2, 2, 1) = zData(2, 2, 1) = 3; xData(3, 2, 1) = yData(3, 2, 1) = zData(3, 2, 1) = 3; xData(2, 3, 1) = yData(2, 3, 1) = zData(2, 3, 1) = 5; xData(3, 3, 1) = yData(3, 3, 1) = zData(3, 3, 1) = 5; sdf(2, 2, 1) = -1; sdf(3, 2, 1) = -1; sdf(2, 3, 1) = -1; sdf(3, 3, 1) = -1; sdf(2, 2, 2) = -1; sdf(3, 2, 2) = -1; sdf(2, 3, 2) = -1; sdf(3, 3, 2) = -1; //___PrintArray3(input.GetDataXRef()); FaceCenteredGrid3D output; solver.Solve(input, sdf, 1, 0.1, &output); //___PrintArray3(output.GetDataXRef()); // __PrintArray3(output.GetDataYRef()); // __PrintArray3(output.GetDataZRef()); } TEST(SinglePhasePressureSolverTest, SolveSinglePhase) { std::cout << "Solve Single Phase\n"; Vector3<size_t> size(4, 4, 4); FaceCenteredGrid3D vel(size); ScalarGrid3D sdf(size, -1, Vector3<double>(0, 0, 0)); vel.Fill(0, 0, 0); for (size_t k = 0; k < 4; ++k) { for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 4; ++i) { if (j == 0 || j == 3) { vel.y(i, j, k) = 0.0; } else { vel.y(i, j, k) = 1.0; } } } } SinglePhasePressureSolver solver; solver.Solve(vel, sdf, 1, 1, &vel); for (size_t k = 0; k < 3; ++k) { for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.x(i, j, k), 1e-6); } } } for (size_t k = 0; k < 3; ++k) { for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.y(i, j, k), 1e-6); } } } for (size_t k = 0; k < 4; ++k) { for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.z(i, j, k), 1e-6); } } } const auto& pressure = solver.GetPressure(); for (size_t k = 0; k < 3; ++k) { for (size_t j = 0; j < 2; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(pressure(i, j + 1, k) - pressure(i, j, k), -1.0, 1e-6); } } } }
26.198473
82
0.42366
AleksanderSiwek
73d6346d5d5310e7b5975120063223636f1a328c
606
cpp
C++
RealmLib/Packets/Client/Buy.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
10
2018-11-25T21:59:43.000Z
2022-01-09T22:41:52.000Z
RealmLib/Packets/Client/Buy.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
1
2018-11-28T12:59:59.000Z
2018-11-28T12:59:59.000Z
RealmLib/Packets/Client/Buy.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
6
2018-12-28T22:34:13.000Z
2021-10-16T10:17:17.000Z
#include "stdafx.h" #include <GameData/Constants.h> #include <GameData/TypeManager.h> #include "Packets/PacketWriter.h" #include "Packets/PacketReader.h" #include <Packets/Buy.h> Buy::Buy(int objectId, int quantity) : objectId(objectId), quantity(quantity) { } Buy::Buy(byte* data) { PacketReader r(data); r.read(objectId); r.read(quantity); } void Buy::emplace(byte* buffer) const { PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::Buy]); w.write(objectId); w.write(quantity); } int Buy::size() const { return 13; } String Buy::toString() const { return String("BUY"); }
15.15
72
0.70462
SometimesRain
73d7203da0e077e884be43a8969520d8a38cb0aa
639
hpp
C++
library/ATF/_qry_case_unmandtrader_log_in_proc_update_complete.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_qry_case_unmandtrader_log_in_proc_update_complete.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_qry_case_unmandtrader_log_in_proc_update_complete.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _qry_case_unmandtrader_log_in_proc_update_complete { struct __list { char byProcRet; char byProcUpdate; unsigned int dwBuyer; unsigned int dwRegistSerial; char byUpdateState; }; unsigned __int16 wInx; unsigned int dwSeller; bool bAllSuccess; char byType; unsigned __int16 wNum; __list List[20]; }; END_ATF_NAMESPACE
24.576923
108
0.629108
lemkova
73d84e4bcbb64a8f59d21dd726d03f1b51848e7a
7,017
hpp
C++
simulator/include/marlin/simulator/transport/SimulatedTransportFactory.hpp
WhiteWalker608/ActionsTest
41e3c3cf6d5a2094d90fd4c004ad0cd3856d42cd
[ "MIT" ]
null
null
null
simulator/include/marlin/simulator/transport/SimulatedTransportFactory.hpp
WhiteWalker608/ActionsTest
41e3c3cf6d5a2094d90fd4c004ad0cd3856d42cd
[ "MIT" ]
null
null
null
simulator/include/marlin/simulator/transport/SimulatedTransportFactory.hpp
WhiteWalker608/ActionsTest
41e3c3cf6d5a2094d90fd4c004ad0cd3856d42cd
[ "MIT" ]
1
2020-10-28T07:38:49.000Z
2020-10-28T07:38:49.000Z
#ifndef MARLIN_SIMULATOR_UDP_SIMULATEDTRANSPORTFACTORY_HPP #define MARLIN_SIMULATOR_UDP_SIMULATEDTRANSPORTFACTORY_HPP #include "marlin/simulator/transport/SimulatedTransport.hpp" #include <marlin/core/Buffer.hpp> #include <marlin/core/SocketAddress.hpp> #include <marlin/core/TransportManager.hpp> #include <spdlog/spdlog.h> namespace marlin { namespace simulator { template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > class SimulatedTransportFactory : public NetworkListener<NetworkInterfaceType> { public: using SelfType = SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >; using TransportType = SimulatedTransport< EventManager, NetworkInterfaceType, TransportDelegateType >; private: NetworkInterfaceType& interface; core::TransportManager<TransportType> transport_manager; EventManager& manager; ListenDelegateType* delegate; bool is_listening = false; std::pair<TransportType*, int> dial_impl(core::SocketAddress const& addr, ListenDelegateType& delegate); public: core::SocketAddress addr; SimulatedTransportFactory( NetworkInterfaceType& interface, EventManager& manager ); int bind(core::SocketAddress const& addr); int listen(ListenDelegateType& delegate); int dial(core::SocketAddress const& addr, ListenDelegateType& delegate); template<typename MetadataType> int dial(core::SocketAddress const& addr, ListenDelegateType& delegate, MetadataType* metadata); template<typename MetadataType> int dial(core::SocketAddress const& addr, ListenDelegateType& delegate, MetadataType&& metadata); TransportType* get_transport(core::SocketAddress const& addr); void did_recv( NetworkInterfaceType& interface, uint16_t port, core::SocketAddress const& addr, core::Buffer&& message ) override; void did_close() override {} }; //Impl template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::SimulatedTransportFactory( NetworkInterfaceType& interface, EventManager& manager ) : interface(interface), manager(manager) {} template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > int SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::bind(core::SocketAddress const& addr) { this->addr = addr; return 0; } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > int SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::listen(ListenDelegateType& delegate) { this->delegate = &delegate; is_listening = true; return interface.bind(*this, addr.get_port()); } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > std::pair< SimulatedTransport< EventManager, NetworkInterfaceType, TransportDelegateType >*, int > SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::dial_impl(core::SocketAddress const& addr, ListenDelegateType& delegate) { if(!is_listening) { auto status = listen(delegate); if(status < 0) { SPDLOG_ERROR("SimulatedTransportFactory {}: Listen failure: {}", this->addr.to_string()); return {nullptr, status}; } } auto [transport, res] = this->transport_manager.get_or_create( addr, this->addr, addr, this->interface, this->transport_manager, this->manager ); return {transport, res ? 1 : 0}; } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > int SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::dial(core::SocketAddress const& addr, ListenDelegateType& delegate) { auto [transport, status] = dial_impl(addr, delegate); if(status < 0) { return status; } else if(status == 1) { delegate.did_create_transport(*transport); } transport->delegate->did_dial(*transport); return status; } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > template<typename MetadataType> int SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::dial( core::SocketAddress const& addr, ListenDelegateType& delegate, MetadataType* metadata ) { auto [transport, status] = dial_impl(addr, delegate); if(status < 0) { return status; } else if(status == 1) { delegate.did_create_transport(*transport, metadata); } transport->delegate->did_dial(*transport); return status; } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > template<typename MetadataType> int SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::dial( core::SocketAddress const& addr, ListenDelegateType& delegate, MetadataType&& metadata ) { auto [transport, status] = dial_impl(addr, delegate); if(status < 0) { return status; } else if(status == 1) { delegate.did_create_transport(*transport, std::move(metadata)); } transport->delegate->did_dial(*transport); return status; } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > SimulatedTransport< EventManager, NetworkInterfaceType, TransportDelegateType >* SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::get_transport(core::SocketAddress const& addr) { return transport_manager.get(addr); } template< typename EventManager, typename NetworkInterfaceType, typename ListenDelegateType, typename TransportDelegateType > void SimulatedTransportFactory< EventManager, NetworkInterfaceType, ListenDelegateType, TransportDelegateType >::did_recv( NetworkInterfaceType&, uint16_t, core::SocketAddress const& addr, core::Buffer&& message ) { if(message.size() == 0) { return; } auto* transport = this->transport_manager.get(addr); if(transport == nullptr) { // Create new transport if permitted if(delegate->should_accept(addr)) { transport = this->transport_manager.get_or_create( addr, this->addr, addr, this->interface, this->transport_manager, this->manager ).first; delegate->did_create_transport(*transport); } else { return; } } transport->did_recv( addr, std::move(message) ); } } // namespace simulator } // namespace marlin #endif // MARLIN_SIMULATOR_UDP_SIMULATEDTRANSPORTFACTORY_HPP
21.996865
105
0.782671
WhiteWalker608
73e1c00cd0391544c32320d45aaddcb5195d91eb
1,640
cpp
C++
src/UOJ_1195 - (1180313) Accepted.cpp
miguelarauj1o/UOJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
80
2015-01-07T01:18:40.000Z
2021-05-04T15:23:18.000Z
src/UOJ_1195 - (1180313) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
1
2019-01-07T01:13:32.000Z
2019-01-07T01:13:32.000Z
src/UOJ_1195 - (1180313) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
28
2015-03-05T11:53:23.000Z
2020-07-05T15:50:42.000Z
#include <cstdio> using namespace std; struct Node { int data; Node* left; Node* right; }; Node* GetNewroot(int data) { Node* newroot = new Node(); newroot -> data = data; newroot -> left = NULL; newroot -> right = NULL; return newroot; } Node* Insert(Node* root, int data) { if(root == NULL){ //empty tree root = GetNewroot(data); return root; }else if(data <= root -> data){ root -> left = Insert(root -> left, data); }else{ root -> right = Insert(root -> right, data); } return root; } void printPreOrder(struct Node* root) { if (root == NULL) return; printf(" %i", root -> data); printPreOrder (root -> left); printPreOrder (root -> right); } void printInOrder(struct Node* root) { if (root == NULL) return; printInOrder (root -> left); printf(" %i", root -> data); printInOrder (root -> right); } void printPosOrder(struct Node* root) { if (root == NULL) return; printPosOrder (root -> left); printPosOrder (root -> right); printf(" %i", root -> data); } int main() { int c, n, x, count = 1; scanf("%i", &c); for (int i = 0; i < c; ++i) { Node* root = NULL; scanf("%i", &n); for (int j = 0; j < n; ++j) { scanf("%i", &x); root = Insert(root, x); } printf("Case %i:\n", count); printf("Pre.:"); printPreOrder(root); printf("\n"); printf("In..:"); printInOrder(root); printf("\n"); printf("Post:"); printPosOrder(root); printf("\n"); count++; //if(i != (c - 1)) printf("\n"); } return 0; }
16.907216
47
0.52439
miguelarauj1o
73e39a33fd3fb36dbc1e004b870de6468eeeeb19
6,330
cpp
C++
firmware/Parser.cpp
bespokegear/Power_Meter_Display_EA_LED_Matrix
61d538c21fefdf566b1cc10c8d4f824bfcbe6d80
[ "MIT" ]
null
null
null
firmware/Parser.cpp
bespokegear/Power_Meter_Display_EA_LED_Matrix
61d538c21fefdf566b1cc10c8d4f824bfcbe6d80
[ "MIT" ]
null
null
null
firmware/Parser.cpp
bespokegear/Power_Meter_Display_EA_LED_Matrix
61d538c21fefdf566b1cc10c8d4f824bfcbe6d80
[ "MIT" ]
null
null
null
#include <string.h> #include <Arduino.h> #include <MutilaDebug.h> #include "Matrix.h" #include "Parser.h" #include "Config.h" #include "SmallTextMode.h" #include "TextMode.h" #include "TextControlMode.h" #include "ClearMode.h" #include "CountdownMode.h" #include "TimerMode.h" #include "VoltageAndCurrentMode.h" #include "WinnerMode.h" #include "PowerMode.h" #include "SetMaxPowerMode.h" #include "SetIDMode.h" #include "DumpConfigMode.h" #include "Settings.h" RIDisplayCommandParser Parser; RIDisplayCommandMapper::RIDisplayCommandMapper() : _count(0) { } void RIDisplayCommandMapper::add(const char* id, RIDisplayCommand cmd, uint8_t maxData, DisplayMode* mode) { if (_count < RIDCP_MAX_IDS) { DB(F("RIDisplayCommandMapper::add ")); DBLN(id); strncpy(_id[_count], id, 2); _cmd[_count] = cmd; _maxData[_count] = maxData; _modes[_count] = mode; _count++; } else { DBLN(F("RIDisplayCommandMapper::add FULL")); } } RIDisplayCommand RIDisplayCommandMapper::getCmd(const char* id) { for (uint8_t i=0; i<_count; i++) { if (strncmp(id, _id[i], 2) == 0) { return _cmd[i]; } } return None; } uint8_t RIDisplayCommandMapper::getMaxData(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _maxData[i]; } } return 0; } DisplayMode* RIDisplayCommandMapper::getMode(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _modes[i]; } } return NULL; } RIDisplayCommandParser::RIDisplayCommandParser() { } void RIDisplayCommandParser::begin() { // Do this here rather than the constructor so that // we can expect Serial to be initialized for debugging // output... setID(DisplayID0.get(), DisplayID1.get()); _mapper.add("CD", Countdown, 1, &CountdownMode); _mapper.add("CL", Clear, 0, &ClearMode); _mapper.add("DC", DumpConfig, 0, &DumpConfigMode); _mapper.add("ID", SetID, 2, &SetIDMode); _mapper.add("MP", MaxGraphPower, 4, &SetMaxPowerMode); _mapper.add("P", Power, 5, &PowerMode); _mapper.add("ST", String, RIDCP_BUFFER_LEN-6, &SmallTextMode); _mapper.add("TC", TextControl, 2, &TextControlMode); _mapper.add("TE", Text, RIDCP_BUFFER_LEN-6, &TextMode); _mapper.add("TI", Timer, 4, &TimerMode); _mapper.add("V", VoltageAndCurrent, 8, &VoltageAndCurrentMode); _mapper.add("WN", Winner, 1, &WinnerMode); // Make sure the buffer is reset reset(); } void RIDisplayCommandParser::update() { if (millis() > _timeout && _ptr > 0) { DBLN(F("TIMEOUT")); reset(); } bool fire = false; if (Serial.available() > 0) { int c = Serial.read(); if (c == '\n' || c == '\r') { fire = true; } else { _buf[_ptr] = c; DB('+'); DB(_buf[_ptr]); switch(_ptr++) { case 0: if (_buf[0] != 'a') { DBLN(F("RST HDR0")); reset(); } else { _last = millis(); _timeout = _last + CMD_TIMEOUT_MS; } break; case 1: if (_buf[1] != _id0 && _id0 != '*') { DBLN(F("RST HDR1")); reset(); } break; case 2: if (_buf[2] != _id1 && _id1 != '*') { DBLN(F("RST HDR2")); reset(); } break; case 3: _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("1-byte cmd=#")); DBLN(_cmd); _dataOffset = 4; } break; case 4: if (_cmd == None) { _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("2-byte cmd=#")); DBLN(_cmd); _dataOffset = 5; } else { DB(F("RST CMD")); reset(); } } break; default: break; } DB(F("_buf now=")); DBLN(_buf); } // Double check we didn't exceed the buffer size. Shouldn't ever // trigger cos we have set the mapper data lengths to be small // enough that we never do this, but just in case... if (_ptr >= RIDCP_BUFFER_LEN) { fire = true; } // Test to see if we've had enough data for the current command... if (_cmd != None) { DB(F("we have command id=#")); DB(_cmd); DB(F(" data we have: ")); DB(_ptr-_dataOffset); DB('/'); DBLN(_mapper.getMaxData(_cmd)); if (_ptr-_dataOffset >= _mapper.getMaxData(_cmd)) { fire = true; } } if (fire) { DB(F("READY! AIM! ")); DisplayMode* mode = _mapper.getMode(_cmd); if (mode != NULL) { DBLN(F("FIRE!")); Matrix.startMode(mode, _buf+_dataOffset); } else { DBLN(F("[click]")); } reset(); } } } bool RIDisplayCommandParser::valid() { return false; } bool RIDisplayCommandParser::complete() { return false; } void RIDisplayCommandParser::reset() { _last = 0; memset(_buf, 0, RIDCP_BUFFER_LEN); _ptr = 0; _dataOffset = 0; _cmd = None; _timeout = 0; } void RIDisplayCommandParser::setID(uint8_t id0, uint8_t id1) { _id0 = id0; _id1 = id1; if ((_id0 < 'A' || id0 > 'Z') && id0 != '*') _id0 = '*'; if ((_id1 < 'A' || id1 > 'Z') && id1 != '*') _id1 = '*'; } void RIDisplayCommandParser::dumpID() { Serial.print(F("Display ID is: ")); Serial.print((char)_id0); Serial.println((char)_id1); }
26.822034
106
0.481675
bespokegear
73e635eed25043d735c37ae0c21474034685c122
2,920
cpp
C++
Engine/script/script_engine.cpp
monkey0506/ags
2f96ddf47e944efea2534386a4004849eb71372b
[ "Artistic-2.0" ]
null
null
null
Engine/script/script_engine.cpp
monkey0506/ags
2f96ddf47e944efea2534386a4004849eb71372b
[ "Artistic-2.0" ]
null
null
null
Engine/script/script_engine.cpp
monkey0506/ags
2f96ddf47e944efea2534386a4004849eb71372b
[ "Artistic-2.0" ]
null
null
null
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= // // Script Editor run-time engine component (c) 1998 Chris Jones // script chunk format: // 00h 1 dword version - should be 2 // 04h 1 dword sizeof(scriptblock) // 08h 1 dword number of ScriptBlocks // 0Ch n STRUCTs ScriptBlocks // //============================================================================= #include <stdio.h> #include <stdlib.h> #include "ac/roomstruct.h" #include "util/filestream.h" #include "script/cc_instance.h" #include "script/cc_error.h" using namespace AGS::Common; char *scripteditruntimecopr = "Script Editor v1.2 run-time component. (c) 1998 Chris Jones"; #define SCRIPT_CONFIG_VERSION 1 extern void quit(const char *); extern int currentline; // in script/script_common void cc_error_at_line(char *buffer, const char *error_msg) { if (ccInstance::GetCurrentInstance() == NULL) { sprintf(ccErrorString, "Error (line %d): %s", currentline, error_msg); } else { sprintf(ccErrorString, "Error: %s\n", error_msg); ccInstance::GetCurrentInstance()->GetCallStack(ccErrorCallStack, 5); } } void cc_error_without_line(char *buffer, const char *error_msg) { sprintf(ccErrorString, "Runtime error: %s", error_msg); } void save_script_configuration(Stream *out) { quit("ScriptEdit: run-time version can't save"); } void load_script_configuration(Stream *in) { int aa; if (in->ReadInt32() != SCRIPT_CONFIG_VERSION) quit("ScriptEdit: invalid config version"); int numvarnames = in->ReadInt32(); for (aa = 0; aa < numvarnames; aa++) { int lenoft = in->ReadByte(); in->Seek(lenoft); } } void save_graphical_scripts(Stream *out, RoomStruct * rss) { quit("ScriptEdit: run-time version can't save"); } char *scripttempn = "~acsc%d.tmp"; void load_graphical_scripts(Stream *in, RoomStruct * rst) { int32_t ct; while (1) { ct = in->ReadInt32(); if ((ct == -1) | (in->EOS() != 0)) break; int32_t lee; lee = in->ReadInt32(); char thisscn[20]; sprintf(thisscn, scripttempn, ct); Stream *te = Common::File::CreateFile(thisscn); char *scnf = (char *)malloc(lee); // MACPORT FIX: swap size and nmemb in->Read(scnf, lee); te->Write(scnf, lee); delete te; free(scnf); } }
27.809524
92
0.603082
monkey0506
73e9b45bf7446b8516bbc0007b20ce5c9c8a2eb4
8,892
cc
C++
cbplusui/apps/settings/SettingWifiPasswordActivity.cc
Iorest/mg-demos
8375a84d6e5dfbd659a53f6dc17ea00e7b117ef9
[ "Apache-2.0" ]
11
2019-05-27T04:15:46.000Z
2022-03-18T05:16:52.000Z
cbplusui/apps/settings/SettingWifiPasswordActivity.cc
Iorest/mg-demos
8375a84d6e5dfbd659a53f6dc17ea00e7b117ef9
[ "Apache-2.0" ]
2
2019-08-17T11:54:12.000Z
2020-08-14T01:34:35.000Z
cbplusui/apps/settings/SettingWifiPasswordActivity.cc
Iorest/mg-demos
8375a84d6e5dfbd659a53f6dc17ea00e7b117ef9
[ "Apache-2.0" ]
11
2019-08-19T04:48:27.000Z
2022-01-27T09:25:05.000Z
/////////////////////////////////////////////////////////////////////////////// // // IMPORTANT NOTICE // // The following open source license statement does not apply to any // entity in the Exception List published by FMSoft. // // For more information, please visit: // // https://www.fmsoft.cn/exception-list // ////////////////////////////////////////////////////////////////////////////// /* ** This file is a part of mg-demos package. ** ** Copyright (C) 2019 FMSoft (http://www.fmsoft.cn). ** Copyright (C) 2018 Beijing Joobot Technologies Co., Ltd. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /*!============================================================================ * @file SettingWifiPasswordActivity.cc * @Synopsis The activity for WiFi password. * @author Vincent Wei * @version 1.0 * @date 23/05/2018 */ #include "global.h" #include "utilities.h" #include "misc.h" #include "Activity.hh" #include "ActivityStack.hh" #include "NCSActivity.hh" #define _HAVE_SUBTITLE #include "resource.h" #include "SettingWifiPasswordActivity.hh" #define IDC_WIFI 101 REGISTER_ACTIVITY(SettingWifiPasswordActivity); static BOOL mymain_onCreate (mMainWnd* self, DWORD dwAddData) { return TRUE; } static LRESULT mymain_onIntent (mMainWnd* self, UINT msg, DWORD wparam, DWORD lparam) { Intent* intent = (Intent*)wparam; const char* ssid = intent->getString ("SSID").c_str(); mWidget* ctrl = (mWidget*)(_c(self)->getChild (self, IDC_SUBTITLE)); SetWindowText (ctrl->hwnd, ssid); Intent::deleteIntent (intent); return 0; } #define RES_WIFI_LOGO "images/select-wifi/wifi-logo.png" static RES_NODE _myres_list [] = { {RES_WIFI_LOGO, RES_TYPE_IMAGE, 16, 0}, {NULL} }; static BOOL mymain_onClose (mWidget* self, int message) { _MG_PRINTF ("SettingWifiPasswordActivity: mymain_onClose called.\n"); unloadResByTag (_myres_list, 0); //DestroyMainWindow (self->hwnd); return TRUE; } static BOOL mymain_onCreated (struct _NCS_CREATE_NOTIFY_INFO* info, mComponent* self, DWORD special_id) { unsigned cnt = loadResByTag (_myres_list, 0); if (cnt < (TABLESIZE (_myres_list) - 1)) { _ERR_PRINTF ("SettingWifiPasswordActivity: failed to load resource.\n"); return FALSE; } mWidget* ctrl; ctrl = (mWidget*)(_c(self)->getChild (self, IDC_TITLE)); ncsSetElement (ctrl, NCS_FGC_WINDOW, COLOR_TITLE); ncsSetFont (ctrl->hwnd, FONT_TITLE); SetWindowText (ctrl->hwnd, _("Input Password")); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_SUBTITLE)); _c(ctrl)->setProperty (ctrl, NCSP_STATIC_VALIGN, (DWORD)NCS_VALIGN_TOP); ncsSetElement (ctrl, NCS_FGC_WINDOW, COLOR_SUBTITLE); ncsSetFont (ctrl->hwnd, FONT_SUBTITLE); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_WIFI)); _c(ctrl)->setProperty (ctrl, NCSP_IMAGE_IMAGE, (DWORD)GetResource (Str2Key (RES_WIFI_LOGO))); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_CONTENT)); SetWindowText (ctrl->hwnd, _("Tap WiFi logo to input password")); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_LEFT_BUTTON)); //_c(ctrl)->setProperty (ctrl, NCSP_STATIC_ALIGN, (DWORD)NCS_ALIGN_LEFT); //ncsSetElement (ctrl, NCS_FGC_WINDOW, COLOR_TEXT_BUTTON); //ncsSetFont (ctrl->hwnd, GLOBAL_FONT_SM); SetWindowText (ctrl->hwnd, _("Cancel")); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_RIGHT_BUTTON)); //_c(ctrl)->setProperty (ctrl, NCSP_STATIC_ALIGN, (DWORD)NCS_ALIGN_RIGHT); //ncsSetElement (ctrl, NCS_FGC_WINDOW, COLOR_TEXT_BUTTON); //ncsSetFont (ctrl->hwnd, GLOBAL_FONT_SM); SetWindowText (ctrl->hwnd, _("Join")); return TRUE; } static BOOL mymain_onCommand (mMainWnd* self, int id, int nc, HWND hCtrl) { if (nc == NCSN_WIDGET_CLICKED) { switch (id) { case IDC_WIFI: case IDC_CONTENT: { char buff [256]; memset(buff, 0, 256); statusBar_enableScreenLock(FALSE); softKeyboard (self->hwnd, buff, 8, 255); statusBar_enableScreenLock(TRUE); if (strlen (buff) > 0) { mWidget* ctrl = (mWidget*)(_c(self)->getChild (self, IDC_CONTENT)); SetWindowText (ctrl->hwnd, buff); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_RIGHT_BUTTON)); EnableWindow (ctrl->hwnd, TRUE); } break; } case IDC_LEFT_BUTTON: { ACTIVITYSTACK->pop(); break; } case IDC_RIGHT_BUTTON: { /* the caller is responsible to free the info */ WIFI_PASSWORD_INFO* info = (WIFI_PASSWORD_INFO*)calloc (sizeof (WIFI_PASSWORD_INFO), 1); mWidget* ctrl = (mWidget*)(_c(self)->getChild (self, IDC_SUBTITLE)); info->ssid = strdup (GetWindowCaption (ctrl->hwnd)); ctrl = (mWidget*)(_c(self)->getChild (self, IDC_CONTENT)); info->password = strdup (GetWindowCaption (ctrl->hwnd)); ACTIVITYSTACK->pop ((DWORD)info); break; } default: break; } } return TRUE; } static NCS_CREATE_NOTIFY_INFO create_notify_info = { onCreated: mymain_onCreated, }; static NCS_WND_TEMPLATE _ctrl_templ[] = { { class_name: NCSCTRL_STATIC, id: IDC_TITLE, x: ACTIVITY_TITLE_X, y: ACTIVITY_TITLE_Y, w: ACTIVITY_TITLE_W, h: ACTIVITY_TITLE_H, style: WS_VISIBLE, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_STATIC, id: IDC_SUBTITLE, x: ACTIVITY_SUBTITLE_X, y: ACTIVITY_SUBTITLE_Y - 3, w: ACTIVITY_SUBTITLE_W, h: ACTIVITY_SUBTITLE_H, style: WS_VISIBLE, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_SEPARATOR, id: IDC_STATIC, x: ACTIVITY_SEPARATOR_X, y: ACTIVITY_SEPARATOR_Y, w: ACTIVITY_SEPARATOR_W, h: ACTIVITY_SEPARATOR_H, style: WS_VISIBLE, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_IMAGE, id: IDC_WIFI, x: ACTIVITY_CONTENT_X + ACTIVITY_CONTENT_MARGIN_H, y: ACTIVITY_CONTENT_Y + ACTIVITY_CONTENT_MARGIN_V, w: ACTIVITY_CONTENT_ITEM_W - ACTIVITY_CONTENT_MARGIN_H - ACTIVITY_CONTENT_MARGIN_H, h: ACTIVITY_CONTENT_ITEM_H * 2, style: WS_VISIBLE | NCSS_NOTIFY, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_STATIC, id: IDC_CONTENT, x: ACTIVITY_CONTENT_X + ACTIVITY_CONTENT_MARGIN_H, y: ACTIVITY_LEFT_BUTTON_Y - ACTIVITY_CONTENT_ITEM_H - ACTIVITY_CONTENT_MARGIN_V, w: ACTIVITY_CONTENT_ITEM_W - ACTIVITY_CONTENT_MARGIN_H - ACTIVITY_CONTENT_MARGIN_H, h: ACTIVITY_CONTENT_ITEM_H, style: WS_VISIBLE | NCSS_NOTIFY, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_BUTTON, id: IDC_LEFT_BUTTON, x: ACTIVITY_LEFT_BUTTON_X, y: ACTIVITY_LEFT_BUTTON_Y, w: ACTIVITY_LEFT_BUTTON_W, h: ACTIVITY_LEFT_BUTTON_H, style: WS_VISIBLE | NCSS_NOTIFY, ex_style: WS_EX_NONE, caption: "", }, { class_name: NCSCTRL_BUTTON, id: IDC_RIGHT_BUTTON, x: ACTIVITY_RIGHT_BUTTON_X, y: ACTIVITY_RIGHT_BUTTON_Y, w: ACTIVITY_RIGHT_BUTTON_W, h: ACTIVITY_RIGHT_BUTTON_H, style: WS_VISIBLE | WS_DISABLED | NCSS_NOTIFY, ex_style: WS_EX_NONE, caption: "", }, }; static NCS_EVENT_HANDLER mymain_handlers [] = { {MSG_CREATE, reinterpret_cast<void*>(mymain_onCreate)}, {MSG_USER_APP_DATA, reinterpret_cast<void*>(mymain_onIntent)}, {MSG_COMMAND, reinterpret_cast<void*>(mymain_onCommand)}, {MSG_CLOSE, reinterpret_cast<void*>(mymain_onClose)}, {0, NULL} }; static NCS_MNWND_TEMPLATE mymain_templ = { NCSCTRL_DIALOGBOX, 1, ACTIVITY_X, ACTIVITY_Y, ACTIVITY_W, ACTIVITY_H, WS_NONE, WS_EX_NONE, N_("WiFi Pasword"), NULL, NULL, mymain_handlers, _ctrl_templ, TABLESIZE(_ctrl_templ), 0, 0, NULL, 0, 0, &create_notify_info, 0 }; SettingWifiPasswordActivity::SettingWifiPasswordActivity () : NCSActivity (&mymain_templ) { m_style = STYLE_PUSH; }
30.662069
103
0.62978
Iorest
73eabfe1965cefc9c0961efa616bffa0ef3fd175
1,395
hpp
C++
Engine/video/Video.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
32
2015-07-04T02:47:22.000Z
2022-01-19T00:07:51.000Z
Engine/video/Video.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
null
null
null
Engine/video/Video.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
11
2016-11-14T15:53:15.000Z
2020-05-29T12:12:54.000Z
// Copyright (c) 2013 Juan Delgado (JuDelCo) // License: zlib/libpng License // zlib/libpng License web page: http://opensource.org/licenses/Zlib #pragma once #ifndef VIDEO_HPP #define VIDEO_HPP #include <SFML/Graphics.hpp> #include <memory> typedef std::shared_ptr<sf::RenderWindow> RenderWindowPtr; class Video { public: typedef std::shared_ptr<Video> Ptr; Video(); ~Video(); bool init(); void swapBuffers(); RenderWindowPtr getWindow(); const sf::Vector2i getCameraPosition(); float getFpsLimit(); void setFpsLimit(float fpsLimit); void changeTitle(std::string title); const sf::Vector2u getResolution(); void changeResolution(sf::Vector2u resolution); void setCameraPosition(sf::Vector2i position); void moveCameraPosition(sf::Vector2i offset); void viewReset(sf::FloatRect rect); void viewResetToCamera(); void clear(sf::Color color); void draw(sf::Drawable& drawable); void draw(sf::Drawable& drawable, sf::RenderStates& renderStates); void drawPoint(const float positionX, const float positionY, const sf::Color color); void drawRectangle(const sf::Vector2f position, const sf::Vector2f size, const sf::Color color); protected: sf::Vector2u m_resolution; RenderWindowPtr m_window; sf::Vector2i m_cameraPosition; std::string m_title; float m_fpsLimit; private: void initWindow(); void endWindow(); }; #endif // VIDEO_HPP
25.833333
98
0.741935
JuDelCo
73eb71a165d827ab9b324eb581a9393adf51a045
7,039
hpp
C++
unit/atf-src/atf-c++/macros.hpp
Reverier-Xu/bind-EDNS-client-subnet-patched
c02debb6d48736db4601659107a358b3c445ba75
[ "MIT", "BSD-3-Clause" ]
7
2015-04-19T12:14:32.000Z
2021-08-11T21:43:00.000Z
unit/atf-src/atf-c++/macros.hpp
Reverier-Xu/bind-EDNS-client-subnet-patched
c02debb6d48736db4601659107a358b3c445ba75
[ "MIT", "BSD-3-Clause" ]
2
2020-02-04T01:58:46.000Z
2020-02-04T02:25:08.000Z
unit/atf-src/atf-c++/macros.hpp
Reverier-Xu/bind-EDNS-client-subnet-patched
c02debb6d48736db4601659107a358b3c445ba75
[ "MIT", "BSD-3-Clause" ]
5
2015-12-03T15:11:19.000Z
2019-09-06T16:53:22.000Z
// // Automated Testing Framework (atf) // // Copyright (c) 2007, 2008, 2010 The NetBSD Foundation, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. // #if !defined(_ATF_CXX_MACROS_HPP_) #define _ATF_CXX_MACROS_HPP_ #include <sstream> #include <stdexcept> #include <vector> #include <atf-c++/tests.hpp> #define ATF_TEST_CASE_WITHOUT_HEAD(name) \ class atfu_tc_ ## name : public atf::tests::tc { \ void body(void) const; \ public: \ atfu_tc_ ## name(void) : atf::tests::tc(#name, false) {} \ }; #define ATF_TEST_CASE(name) \ class atfu_tc_ ## name : public atf::tests::tc { \ void head(void); \ void body(void) const; \ public: \ atfu_tc_ ## name(void) : atf::tests::tc(#name, false) {} \ }; #define ATF_TEST_CASE_WITH_CLEANUP(name) \ class atfu_tc_ ## name : public atf::tests::tc { \ void head(void); \ void body(void) const; \ void cleanup(void) const; \ public: \ atfu_tc_ ## name(void) : atf::tests::tc(#name, true) {} \ }; #define ATF_TEST_CASE_NAME(name) atfu_tc_ ## name #define ATF_TEST_CASE_HEAD(name) \ void \ atfu_tc_ ## name::head(void) #define ATF_TEST_CASE_BODY(name) \ void \ atfu_tc_ ## name::body(void) \ const #define ATF_TEST_CASE_CLEANUP(name) \ void \ atfu_tc_ ## name::cleanup(void) \ const #define ATF_FAIL(reason) atf::tests::tc::fail(reason) #define ATF_SKIP(reason) atf::tests::tc::skip(reason) #define ATF_PASS() atf::tests::tc::pass() #define ATF_REQUIRE(x) \ do { \ if (!(x)) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " << #x << " not met"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } while (false) #define ATF_REQUIRE_EQ(x, y) \ do { \ if ((x) != (y)) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " << #x << " != " << #y \ << " (" << (x) << " != " << (y) << ")"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } while (false) #define ATF_REQUIRE_MATCH(regexp, string) \ do { \ if (!atf::tests::detail::match(regexp, string)) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": '" << string << "' does not " \ << "match regexp '" << regexp << "'"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } while (false) #define ATF_REQUIRE_THROW(e, x) \ do { \ try { \ x; \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " did not throw " \ #e " as expected"; \ atf::tests::tc::fail(atfu_ss.str()); \ } catch (const e&) { \ } catch (const std::exception& atfu_e) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " threw an " \ "unexpected error (not " #e "): " << atfu_e.what(); \ atf::tests::tc::fail(atfu_ss.str()); \ } catch (...) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " threw an " \ "unexpected error (not " #e ")"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } while (false) #define ATF_REQUIRE_THROW_RE(type, regexp, x) \ do { \ try { \ x; \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " did not throw " \ #type " as expected"; \ atf::tests::tc::fail(atfu_ss.str()); \ } catch (const type& e) { \ if (!atf::tests::detail::match(regexp, e.what())) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " threw " #type "(" \ << e.what() << "), but does not match '" << regexp \ << "'"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } catch (const std::exception& atfu_e) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " threw an " \ "unexpected error (not " #type "): " << atfu_e.what(); \ atf::tests::tc::fail(atfu_ss.str()); \ } catch (...) { \ std::ostringstream atfu_ss; \ atfu_ss << "Line " << __LINE__ << ": " #x " threw an " \ "unexpected error (not " #type ")"; \ atf::tests::tc::fail(atfu_ss.str()); \ } \ } while (false) #define ATF_CHECK_ERRNO(exp_errno, bool_expr) \ atf::tests::tc::check_errno(__FILE__, __LINE__, exp_errno, #bool_expr, \ bool_expr) #define ATF_REQUIRE_ERRNO(exp_errno, bool_expr) \ atf::tests::tc::require_errno(__FILE__, __LINE__, exp_errno, #bool_expr, \ bool_expr) #define ATF_INIT_TEST_CASES(tcs) \ namespace atf { \ namespace tests { \ int run_tp(int, char* const*, \ void (*)(std::vector< atf::tests::tc * >&)); \ } \ } \ \ static void atfu_init_tcs(std::vector< atf::tests::tc * >&); \ \ int \ main(int argc, char* const* argv) \ { \ return atf::tests::run_tp(argc, argv, atfu_init_tcs); \ } \ \ static \ void \ atfu_init_tcs(std::vector< atf::tests::tc * >& tcs) #define ATF_ADD_TEST_CASE(tcs, tcname) \ do { \ atf::tests::tc* tcptr = new atfu_tc_ ## tcname(); \ (tcs).push_back(tcptr); \ } while (0); #endif // !defined(_ATF_CXX_MACROS_HPP_)
35.195
80
0.542691
Reverier-Xu
73edc91a98330ddc9af2c5b4421e992698d1b4f4
522
cpp
C++
src/LG/lg-P5132.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/LG/lg-P5132.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/LG/lg-P5132.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> typedef long long ll; int a[1050]; int main() { std::ios::sync_with_stdio(false); int n; std::cin >> n; ll ans = 0; for (int i = 1; i <= n; i++) { std::cin >> a[i]; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int x; std::cin >> x; if (i > j) { ans += 1ll * x * std::min(a[i], a[j]); } } } std::cout << ans << '\n'; return 0; }
15.352941
54
0.371648
krishukr
73ef45ff7d7c6c526e0900f1bfcd59501ff46550
631
cpp
C++
labs/lab2/lab2ex3.cpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
null
null
null
labs/lab2/lab2ex3.cpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
null
null
null
labs/lab2/lab2ex3.cpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
2
2020-10-01T14:16:56.000Z
2021-07-06T16:31:33.000Z
/* UQAM / Département d'informatique INF3105 Laboratoire 2 - Type de passage de paramètres */ #include <iostream> using namespace std; void test(int a, int* b, int* c, int& d, int*& e) { a = 11; // effet local b++; // change l'adresse locale de b *c = 13; // change la valeur pointée par c d = 14; // change la valeur référée par d e = c; // change la valeur du pointeur (adresse) pour celle de c } int main() { int v1 = 1; int v2 = 2; int v3 = 3; int v4 = 4; int* p5 = &v1; test(v1, &v2, &v3, v4, p5); cout << v1 << " " << v2 << " " << v3 << " " << v4 << " " << *p5 << " " << endl; return 0; }
21.758621
81
0.549921
MFarradji
73f10ba5b260e9287542d12ad5072bb629900394
746
cpp
C++
URI/Beginner/Experiments.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Experiments.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Experiments.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; char type; int total = 0; int T = 0, t = 0; double rats = 0, rabbits = 0, frogs = 0; int main () { cin >> T; while ( T-- ){ cin >> t >> type; total += t; if (type == 'C') rabbits+= t; else if (type == 'R') rats+= t; else if (type == 'S') frogs+=t; } printf("Total: %d cobaias\n", total); printf("Total de coelhos: %.0f\n", rabbits); printf("Total de ratos: %.0f\n", rats); printf("Total de sapos: %.0f\n", frogs); printf("Percentual de coelhos: %.2f %%\n", (rabbits/total)*100); printf("Percentual de ratos: %.2f %%\n", (rats/total)*100); printf("Percentual de sapos: %.2f %%\n", (frogs/total)*100); return 0; } /* input:- ----------- output:- ----------- Problem: */
17.761905
65
0.552279
Mhmd-Hisham
73f1513f26ef5ad89a2d969229677e2bfdd9e6fb
1,923
hh
C++
libview/toolTip.hh
libview/libview
3d9b8bd63589e8bdc43638331bf6061127690cd3
[ "MIT" ]
2
2020-10-22T22:02:52.000Z
2021-12-13T18:07:16.000Z
libview/toolTip.hh
libview/libview
3d9b8bd63589e8bdc43638331bf6061127690cd3
[ "MIT" ]
null
null
null
libview/toolTip.hh
libview/libview
3d9b8bd63589e8bdc43638331bf6061127690cd3
[ "MIT" ]
null
null
null
/* ************************************************************************* * Copyright (c) 2005 VMware, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * *************************************************************************/ /* * toolTip.hh -- * * A tooltip look-alike widget that can be shown on demand. */ #ifndef LIBVIEW_TOOLTIP_HH #define LIBVIEW_TOOLTIP_HH #include <gtkmm/window.h> #include <libview/motionTracker.hh> namespace view { class ToolTip : public Gtk::Window { public: ToolTip(Gtk::Widget &target, const Glib::ustring &markup); protected: bool on_button_press_event(GdkEventButton *event); bool on_expose_event(GdkEventExpose *event); void on_show(void); private: bool OnTimeout(void); void UpdatePosition(void); Gtk::Widget &mTarget; MotionTracker mTracker; }; } // namespace view #endif // LIBVIEW_TOOLTIP_HH
29.136364
77
0.683307
libview
73f2d8777738af49152d925531e53867642cb0b1
49,565
hpp
C++
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/function_internal.hpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
29
2020-05-11T16:59:10.000Z
2022-02-24T11:30:16.000Z
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/function_internal.hpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
1
2021-02-04T04:20:55.000Z
2021-02-28T20:47:02.000Z
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/function_internal.hpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
10
2020-06-22T22:41:32.000Z
2021-12-15T12:26:13.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi 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 3 of the License, or (at your option) any later version. * * CasADi 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 CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef CASADI_FUNCTION_INTERNAL_HPP #define CASADI_FUNCTION_INTERNAL_HPP #include "function.hpp" #include <set> #include <stack> #include "code_generator.hpp" #include "importer.hpp" #include "sparse_storage.hpp" #include "options.hpp" #include "shared_object_internal.hpp" #include "timing.hpp" #ifdef CASADI_WITH_THREAD #ifdef CASADI_WITH_THREAD_MINGW #include <mingw.mutex.h> #else // CASADI_WITH_THREAD_MINGW #include <mutex> #endif // CASADI_WITH_THREAD_MINGW #endif //CASADI_WITH_THREAD // This macro is for documentation purposes #define INPUTSCHEME(name) // This macro is for documentation purposes #define OUTPUTSCHEME(name) /// \cond INTERNAL namespace casadi { template<typename T> std::vector<std::pair<std::string, T>> zip(const std::vector<std::string>& id, const std::vector<T>& mat) { casadi_assert_dev(id.size()==mat.size()); std::vector<std::pair<std::string, T>> r(id.size()); for (casadi_uint i=0; i<r.size(); ++i) r[i] = make_pair(id[i], mat[i]); return r; } /** \brief Function memory with temporary work vectors */ struct CASADI_EXPORT ProtoFunctionMemory { // Function specific statistics std::map<std::string, FStats> fstats; // Short-hand for "total" fstats FStats* t_total; // Add a statistic void add_stat(const std::string& s) { bool added = fstats.insert(std::make_pair(s, FStats())).second; casadi_assert(added, "Duplicate stat: '" + s + "'"); } }; /** \brief Function memory with temporary work vectors */ struct CASADI_EXPORT FunctionMemory : public ProtoFunctionMemory { }; /** \brief Base class for FunctionInternal and LinsolInternal \author Joel Andersson \date 2017 */ class CASADI_EXPORT ProtoFunction : public SharedObjectInternal { public: /** \brief Constructor */ ProtoFunction(const std::string& name); /** \brief Destructor */ ~ProtoFunction() override = 0; /** \brief Construct Prepares the function for evaluation */ void construct(const Dict& opts); ///@{ /** \brief Options */ static const Options options_; virtual const Options& get_options() const { return options_;} ///@} /// Reconstruct options dict virtual Dict generate_options(bool is_temp=false) const; /** \brief Initialize Initialize and make the object ready for setting arguments and evaluation. This method is typically called after setting options but before evaluating. If passed to another class (in the constructor), this class should invoke this function when initialized. */ virtual void init(const Dict& opts); /** \brief Finalize the object creation This function, which visits the class hierarchy in reverse order is run after init() has been completed. */ virtual void finalize(); /// Checkout a memory object int checkout() const; /// Release a memory object void release(int mem) const; /// Memory objects void* memory(int ind) const; /** \brief Create memory block */ virtual void* alloc_mem() const { return new ProtoFunctionMemory(); } /** \brief Initalize memory block */ virtual int init_mem(void* mem) const; /** \brief Free memory block */ virtual void free_mem(void *mem) const { delete static_cast<ProtoFunctionMemory*>(mem); } /// Get all statistics virtual Dict get_stats(void* mem) const; /** \brief Clear all memory (called from destructor) */ void clear_mem(); /** \brief C-style formatted printing during evaluation */ void print(const char* fmt, ...) const; /** \brief C-style formatted printing to string */ void sprint(char* buf, size_t buf_sz, const char* fmt, ...) const; /** \brief Format time in a fixed width 8 format */ void format_time(char* buffer, double time) const; /** \brief Print timing statistics */ void print_time(const std::map<std::string, FStats>& fstats) const; /** \brief Serialize an object */ void serialize(SerializingStream &s) const; /** \brief Serialize an object without type information */ virtual void serialize_body(SerializingStream &s) const; /** \brief Serialize type information */ virtual void serialize_type(SerializingStream &s) const {} /** \brief String used to identify the immediate FunctionInternal subclass */ virtual std::string serialize_base_function() const { return class_name(); } protected: /** \brief Deserializing constructor */ explicit ProtoFunction(DeserializingStream& s); /// Name std::string name_; /// Verbose printout bool verbose_; // Print timing statistics bool print_time_; // Print timing statistics bool record_time_; #ifdef CASADI_WITH_THREAD /// Mutex for thread safety mutable std::mutex mtx_; #endif // CASADI_WITH_THREAD private: /// Memory objects mutable std::vector<void*> mem_; /// Unused memory objects mutable std::stack<casadi_int> unused_; }; /** \brief Internal class for Function \author Joel Andersson \date 2010-2015 */ class CASADI_EXPORT FunctionInternal : public ProtoFunction { friend class Function; public: /** \brief Constructor */ FunctionInternal(const std::string& name); /** \brief Destructor */ ~FunctionInternal() override = 0; /** \brief Obtain solver name from Adaptor */ virtual std::string getAdaptorSolverName() const { return ""; } ///@{ /** \brief Options */ static const Options options_; const Options& get_options() const override { return options_;} ///@} /// Reconstruct options dict Dict generate_options(bool is_temp=false) const override; /** \brief Initialize */ void init(const Dict& opts) override; /** \brief Finalize the object creation */ void finalize() override; /** \brief Get a public class instance */ Function self() const { return shared_from_this<Function>();} // Factory virtual Function factory(const std::string& name, const std::vector<std::string>& s_in, const std::vector<std::string>& s_out, const Function::AuxOut& aux, const Dict& opts) const; // Get list of dependency functions virtual std::vector<std::string> get_function() const; // Get a dependency function virtual const Function& get_function(const std::string &name) const; // Check if a particular dependency exists virtual bool has_function(const std::string& fname) const {return false;} /** \brief Which variables enter with some order * \param[in] s_in Input name * \param[in] s_out Output name(s) * \param[in] order Only 1 (linear) and 2 (nonlinear) allowed * \param[in] tr Flip the relationship. Return which expressions contain the variables */ virtual std::vector<bool> which_depends(const std::string& s_in, const std::vector<std::string>& s_out, casadi_int order, bool tr=false) const; ///@{ /** \brief Is the class able to propagate seeds through the algorithm? */ virtual bool has_spfwd() const { return false;} virtual bool has_sprev() const { return false;} ///@} ///@{ /** \brief Evaluate numerically */ int eval_gen(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const; virtual int eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const; ///@} /** \brief Evaluate with symbolic scalars */ virtual int eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w, void* mem) const; /** \brief Evaluate with symbolic matrices */ virtual void eval_mx(const MXVector& arg, MXVector& res, bool always_inline, bool never_inline) const; ///@{ /** \brief Evaluate with DM matrices */ virtual std::vector<DM> eval_dm(const std::vector<DM>& arg) const; virtual bool has_eval_dm() const { return false;} ///@} ///@{ /** \brief Evaluate a function, overloaded */ int eval_gen(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w, void* mem) const { return eval_sx(arg, res, iw, w, mem); } int eval_gen(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w, void* mem) const { return sp_forward(arg, res, iw, w, mem); } ///@} ///@{ /** \brief Call a function, overloaded */ void call_gen(const MXVector& arg, MXVector& res, casadi_int npar, bool always_inline, bool never_inline) const; template<typename D> void call_gen(const std::vector<Matrix<D> >& arg, std::vector<Matrix<D> >& res, casadi_int npar, bool always_inline, bool never_inline) const; ///@} /** \brief Call a function, templated */ template<typename M> void call(const std::vector<M>& arg, std::vector<M>& res, bool always_inline, bool never_inline) const; ///@{ /** Helper function * * \param npar[in] normal usage: 1, disallow pararallel calls: -1 * \param npar[out] required number of parallel calls (or -1) */ static bool check_mat(const Sparsity& arg, const Sparsity& inp, casadi_int& npar); ///@} ///@{ /** \brief Check if input arguments have correct length and dimensions * * Raises errors. * * \param npar[in] normal usage: 1, disallow pararallel calls: -1 * \param[out] npar: max number of horizontal repetitions across all arguments (or -1) */ template<typename M> void check_arg(const std::vector<M>& arg, casadi_int& npar) const; ///@} ///@{ /** \brief Check if output arguments have correct length and dimensions * * Raises errors. * * \param npar[in] normal usage: 1, disallow pararallel calls: -1 * \param[out] npar: max number of horizontal repetitions across all arguments (or -1) */ template<typename M> void check_res(const std::vector<M>& res, casadi_int& npar) const; ///@} /** \brief Check if input arguments that needs to be replaced * * Raises errors * * \param npar[in] normal usage: 1, disallow pararallel calls: -1 * \param[out] npar: max number of horizontal repetitions across all arguments (or -1) */ template<typename M> bool matching_arg(const std::vector<M>& arg, casadi_int& npar) const; /** \brief Check if output arguments that needs to be replaced * * Raises errors * * \param npar[in] normal usage: 1, disallow pararallel calls: -1 * \param[out] npar: max number of horizontal repetitions across all arguments (or -1) */ template<typename M> bool matching_res(const std::vector<M>& arg, casadi_int& npar) const; /** \brief Replace 0-by-0 inputs */ template<typename M> std::vector<M> replace_arg(const std::vector<M>& arg, casadi_int npar) const; /** \brief Project sparsities * */ template<typename M> std::vector<M> project_arg(const std::vector<M>& arg, casadi_int npar) const; /** \brief Project sparsities * */ template<typename M> std::vector<M> project_res(const std::vector<M>& arg, casadi_int npar) const; /** \brief Replace 0-by-0 outputs */ template<typename M> std::vector<M> replace_res(const std::vector<M>& res, casadi_int npar) const; /** \brief Replace 0-by-0 forward seeds */ template<typename M> std::vector<std::vector<M>> replace_fseed(const std::vector<std::vector<M>>& fseed, casadi_int npar) const; /** \brief Replace 0-by-0 reverse seeds */ template<typename M> std::vector<std::vector<M>> replace_aseed(const std::vector<std::vector<M>>& aseed, casadi_int npar) const; /** \brief Convert from/to input/output lists/map */ /// @{ template<typename M> std::map<std::string, M> convert_arg(const std::vector<M>& arg) const; template<typename M> std::vector<M> convert_arg(const std::map<std::string, M>& arg) const; template<typename M> std::map<std::string, M> convert_res(const std::vector<M>& res) const; template<typename M> std::vector<M> convert_res(const std::map<std::string, M>& res) const; /// @} /** \brief Convert from/to flat vector of input/output nonzeros */ /// @{ std::vector<double> nz_in(const std::vector<DM>& arg) const; std::vector<double> nz_out(const std::vector<DM>& res) const; std::vector<DM> nz_in(const std::vector<double>& arg) const; std::vector<DM> nz_out(const std::vector<double>& res) const; ///@} virtual bool is_diff_out(casadi_int i) { return true; } virtual bool is_diff_in(casadi_int i) { return true; } ///@{ /** \brief Forward mode AD, virtual functions overloaded in derived classes */ virtual void call_forward(const std::vector<MX>& arg, const std::vector<MX>& res, const std::vector<std::vector<MX> >& fseed, std::vector<std::vector<MX> >& fsens, bool always_inline, bool never_inline) const; virtual void call_forward(const std::vector<SX>& arg, const std::vector<SX>& res, const std::vector<std::vector<SX> >& fseed, std::vector<std::vector<SX> >& fsens, bool always_inline, bool never_inline) const; ///@} ///@{ /** \brief Reverse mode, virtual functions overloaded in derived classes */ virtual void call_reverse(const std::vector<MX>& arg, const std::vector<MX>& res, const std::vector<std::vector<MX> >& aseed, std::vector<std::vector<MX> >& asens, bool always_inline, bool never_inline) const; virtual void call_reverse(const std::vector<SX>& arg, const std::vector<SX>& res, const std::vector<std::vector<SX> >& aseed, std::vector<std::vector<SX> >& asens, bool always_inline, bool never_inline) const; ///@} /** \brief Parallel evaluation */ std::vector<MX> mapsum_mx(const std::vector<MX > &arg, const std::string& parallelization); /** \brief Do the derivative functions need nondifferentiated outputs? */ virtual bool uses_output() const {return false;} ///@{ /** \brief Return Jacobian of all input elements with respect to all output elements */ Function jacobian() const; virtual bool has_jacobian() const { return false;} virtual Function get_jacobian(const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const; ///@} ///@{ /** \brief Return Jacobian of all input elements with respect to all output elements */ Function jac() const; virtual bool has_jac() const { return false;} virtual Function get_jac(const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const; ///@} ///@{ /** \brief Return function that calculates forward derivatives * forward(nfwd) returns a cached instance if available, * and calls <tt>Function get_forward(casadi_int nfwd)</tt> * if no cached version is available. */ Function forward(casadi_int nfwd) const; virtual bool has_forward(casadi_int nfwd) const { return false;} virtual Function get_forward(casadi_int nfwd, const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const; ///@} ///@{ /** \brief Return function that calculates adjoint derivatives * reverse(nadj) returns a cached instance if available, * and calls <tt>Function get_reverse(casadi_int nadj)</tt> * if no cached version is available. */ Function reverse(casadi_int nadj) const; virtual bool has_reverse(casadi_int nadj) const { return false;} virtual Function get_reverse(casadi_int nadj, const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const; ///@} /** \brief returns a new function with a selection of inputs/outputs of the original */ virtual Function slice(const std::string& name, const std::vector<casadi_int>& order_in, const std::vector<casadi_int>& order_out, const Dict& opts) const; /** \brief Get oracle */ virtual const Function& oracle() const; /** \brief Can derivatives be calculated in any way? */ bool has_derivative() const; /** \brief Weighting factor for chosing forward/reverse mode */ virtual double ad_weight() const; /** \brief Weighting factor for chosing forward/reverse mode, sparsity propagation */ virtual double sp_weight() const; /** \brief Get Jacobian sparsity */ virtual Sparsity get_jacobian_sparsity() const; ///@{ /** \brief Get function input(s) and output(s) */ virtual const SX sx_in(casadi_int ind) const; virtual const SX sx_out(casadi_int ind) const; virtual const std::vector<SX> sx_in() const; virtual const std::vector<SX> sx_out() const; virtual const MX mx_in(casadi_int ind) const; virtual const MX mx_out(casadi_int ind) const; virtual const std::vector<MX> mx_in() const; virtual const std::vector<MX> mx_out() const; const DM dm_in(casadi_int ind) const; const DM dm_out(casadi_int ind) const; const std::vector<DM> dm_in() const; const std::vector<DM> dm_out() const; ///@} /// Get free variables (MX) virtual std::vector<MX> free_mx() const; /// Get free variables (SX) virtual std::vector<SX> free_sx() const; /** \brief Does the function have free variables */ virtual bool has_free() const { return false;} /** \brief Extract the functions needed for the Lifted Newton method */ virtual void generate_lifted(Function& vdef_fcn, Function& vinit_fcn) const; /** \brief Get the number of atomic operations */ virtual casadi_int n_instructions() const; /** \brief Get an atomic operation operator index */ virtual casadi_int instruction_id(casadi_int k) const; /** \brief Get the (integer) input arguments of an atomic operation */ virtual std::vector<casadi_int> instruction_input(casadi_int k) const; /** \brief Get the floating point output argument of an atomic operation */ virtual double instruction_constant(casadi_int k) const; /** \brief Get the (integer) output argument of an atomic operation */ virtual std::vector<casadi_int> instruction_output(casadi_int k) const; /** \brief Number of nodes in the algorithm */ virtual casadi_int n_nodes() const; /** *\brief get MX expression associated with instruction */ virtual MX instruction_MX(casadi_int k) const; /** *\brief get SX expression associated with instructions */ virtual SX instructions_sx() const; /** \brief Wrap in an Function instance consisting of only one MX call */ Function wrap() const; /** \brief Wrap in an Function instance consisting of only one MX call */ Function wrap_as_needed(const Dict& opts) const; /** \brief Get function in cache */ bool incache(const std::string& fname, Function& f, const std::string& suffix="") const; /** \brief Save function to cache */ void tocache(const Function& f, const std::string& suffix="") const; /** \brief Generate code the function */ void codegen(CodeGenerator& g, const std::string& fname) const; /** \brief Generate meta-information allowing a user to evaluate a generated function */ void codegen_meta(CodeGenerator& g) const; /** \brief Codegen sparsities */ void codegen_sparsities(CodeGenerator& g) const; /** \brief Get name in codegen */ virtual std::string codegen_name(const CodeGenerator& g, bool ns=true) const; /** \brief Get thread-local memory object */ std::string codegen_mem(CodeGenerator& g, const std::string& index="mem") const; /** \brief Codegen incref for dependencies */ virtual void codegen_incref(CodeGenerator& g) const {} /** \brief Codegen decref for dependencies */ virtual void codegen_decref(CodeGenerator& g) const {} /** \brief Codegen decref for alloc_mem */ virtual void codegen_alloc_mem(CodeGenerator& g) const; /** \brief Codegen decref for init_mem */ virtual void codegen_init_mem(CodeGenerator& g) const; /** \brief Codegen for free_mem */ virtual void codegen_free_mem(CodeGenerator& g) const {} /** \brief Code generate the function */ std::string signature(const std::string& fname) const; /** \brief Generate code for the declarations of the C function */ virtual void codegen_declarations(CodeGenerator& g) const; /** \brief Generate code for the function body */ virtual void codegen_body(CodeGenerator& g) const; /** \brief Thread-local memory object type */ virtual std::string codegen_mem_type() const { return ""; } /** \brief Export / Generate C code for the dependency function */ virtual std::string generate_dependencies(const std::string& fname, const Dict& opts) const; /** \brief Is codegen supported? */ virtual bool has_codegen() const { return false;} /** \brief Jit dependencies */ virtual void jit_dependencies(const std::string& fname) {} /** \brief Export function in a specific language */ virtual void export_code(const std::string& lang, std::ostream &stream, const Dict& options) const; /** \brief Serialize type information */ void serialize_type(SerializingStream &s) const override; /** \brief Serialize an object without type information */ void serialize_body(SerializingStream &s) const override; /** \brief Display object */ void disp(std::ostream& stream, bool more) const override; /** \brief Print more */ virtual void disp_more(std::ostream& stream) const {} /** \brief Get function signature: name:(inputs)->(outputs) */ std::string definition() const; /** \brief Print dimensions of inputs and outputs */ void print_dimensions(std::ostream &stream) const; /** \brief Print list of options */ void print_options(std::ostream &stream) const; /** \brief Print all information there is to know about a certain option */ void print_option(const std::string &name, std::ostream &stream) const; /** \brief Print free variables */ virtual std::vector<std::string> get_free() const; /** \brief Get the unidirectional or bidirectional partition */ void get_partition(casadi_int iind, casadi_int oind, Sparsity& D1, Sparsity& D2, bool compact, bool symmetric, bool allow_forward, bool allow_reverse) const; ///@{ /** \brief Number of input/output nonzeros */ casadi_int nnz_in() const; casadi_int nnz_in(casadi_int ind) const { return sparsity_in(ind).nnz(); } casadi_int nnz_out() const; casadi_int nnz_out(casadi_int ind) const { return sparsity_out(ind).nnz(); } ///@} ///@{ /** \brief Number of input/output elements */ casadi_int numel_in() const; casadi_int numel_in(casadi_int ind) const { return sparsity_in(ind).numel(); } casadi_int numel_out(casadi_int ind) const { return sparsity_out(ind).numel(); } casadi_int numel_out() const; ///@} ///@{ /** \brief Input/output dimensions */ casadi_int size1_in(casadi_int ind) const { return sparsity_in(ind).size1(); } casadi_int size2_in(casadi_int ind) const { return sparsity_in(ind).size2(); } casadi_int size1_out(casadi_int ind) const { return sparsity_out(ind).size1(); } casadi_int size2_out(casadi_int ind) const { return sparsity_out(ind).size2(); } std::pair<casadi_int, casadi_int> size_in(casadi_int ind) const { return sparsity_in(ind).size(); } std::pair<casadi_int, casadi_int> size_out(casadi_int ind) const { return sparsity_out(ind).size(); } ///@} ///@{ /** \brief Input/output sparsity */ const Sparsity& sparsity_in(casadi_int ind) const { return sparsity_in_.at(ind); } const Sparsity& sparsity_out(casadi_int ind) const { return sparsity_out_.at(ind); } ///@} ///@{ /** \brief Are all inputs and outputs scalar */ bool all_scalar() const; /// Generate the sparsity of a Jacobian block virtual Sparsity getJacSparsity(casadi_int iind, casadi_int oind, bool symmetric) const; /// Get the sparsity pattern, forward mode template<bool fwd> Sparsity getJacSparsityGen(casadi_int iind, casadi_int oind, bool symmetric, casadi_int gr_i=1, casadi_int gr_o=1) const; /// A flavor of getJacSparsity that does hierarchical block structure recognition Sparsity getJacSparsityHierarchical(casadi_int iind, casadi_int oind) const; /** A flavor of getJacSparsity that does hierarchical block * structure recognition for symmetric Jacobians */ Sparsity getJacSparsityHierarchicalSymm(casadi_int iind, casadi_int oind) const; /// Get, if necessary generate, the sparsity of a Jacobian block Sparsity& sparsity_jac(casadi_int iind, casadi_int oind, bool compact, bool symmetric) const; /// Filter out nonzeros in the full sparsity jacobian according to is_diff_in/out Sparsity jacobian_sparsity_filter(const Sparsity& sp) const; /// Get a vector of symbolic variables corresponding to the outputs virtual std::vector<MX> symbolic_output(const std::vector<MX>& arg) const; ///@{ /** \brief Number of function inputs and outputs */ virtual size_t get_n_in(); virtual size_t get_n_out(); ///@} ///@{ /** \brief Names of function input and outputs */ virtual std::string get_name_in(casadi_int i); virtual std::string get_name_out(casadi_int i); ///@} /** \brief Get default input value */ virtual double get_default_in(casadi_int ind) const { return 0; } /** \brief Get largest input value */ virtual double get_max_in(casadi_int ind) const { return inf; } /** \brief Get smallest input value */ virtual double get_min_in(casadi_int ind) const { return -inf; } /** \brief Get relative tolerance */ virtual double get_reltol() const { return eps; } /** \brief Get absolute tolerance */ virtual double get_abstol() const { return eps; } /** \brief Get sparsity of a given input */ virtual Sparsity get_sparsity_in(casadi_int i); /** \brief Get sparsity of a given output */ virtual Sparsity get_sparsity_out(casadi_int i); /** \brief Get input scheme index by name */ casadi_int index_in(const std::string &name) const { for (casadi_int i=0; i<name_in_.size(); ++i) { if (name_in_[i]==name) return i; } casadi_error("FunctionInternal::index_in: could not find entry \"" + name + "\". Available names are: " + str(name_in_) + "."); return -1; } /** \brief Get output scheme index by name */ casadi_int index_out(const std::string &name) const { for (casadi_int i=0; i<name_out_.size(); ++i) { if (name_out_[i]==name) return i; } casadi_error("FunctionInternal::index_out: could not find entry \"" + name + "\". Available names are: " + str(name_out_) + "."); return -1; } /** \brief Propagate sparsity forward */ virtual int sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w, void* mem) const; /** \brief Propagate sparsity backwards */ virtual int sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w, void* mem) const; /** \brief Get number of temporary variables needed */ void sz_work(size_t& sz_arg, size_t& sz_res, size_t& sz_iw, size_t& sz_w) const; /** \brief Get required length of arg field */ size_t sz_arg() const { return sz_arg_per_ + sz_arg_tmp_;} /** \brief Get required length of res field */ size_t sz_res() const { return sz_res_per_ + sz_res_tmp_;} /** \brief Get required length of iw field */ size_t sz_iw() const { return sz_iw_per_ + sz_iw_tmp_;} /** \brief Get required length of w field */ size_t sz_w() const { return sz_w_per_ + sz_w_tmp_;} /** \brief Ensure required length of arg field */ void alloc_arg(size_t sz_arg, bool persistent=false); /** \brief Ensure required length of res field */ void alloc_res(size_t sz_res, bool persistent=false); /** \brief Ensure required length of iw field */ void alloc_iw(size_t sz_iw, bool persistent=false); /** \brief Ensure required length of w field */ void alloc_w(size_t sz_w, bool persistent=false); /** \brief Ensure work vectors long enough to evaluate function */ void alloc(const Function& f, bool persistent=false); /** \brief Set the (persistent) work vectors */ virtual void set_work(void* mem, const double**& arg, double**& res, casadi_int*& iw, double*& w) const {} /** \brief Set the (temporary) work vectors */ virtual void set_temp(void* mem, const double** arg, double** res, casadi_int* iw, double* w) const {} /** \brief Set the (persistent and temporary) work vectors */ void setup(void* mem, const double** arg, double** res, casadi_int* iw, double* w) const; ///@{ /** \brief Calculate derivatives by multiplying the full Jacobian and multiplying */ virtual bool fwdViaJac(casadi_int nfwd) const; virtual bool adjViaJac(casadi_int nadj) const; ///@} /** Obtain information about function */ virtual Dict info() const; /** \brief Generate/retrieve cached serial map */ Function map(casadi_int n, const std::string& parallelization) const; /** \brief Export an input file that can be passed to generate C code with a main */ void generate_in(const std::string& fname, const double** arg) const; void generate_out(const std::string& fname, double** res) const; bool always_inline_, never_inline_; /// Number of inputs and outputs size_t n_in_, n_out_; /// Are inputs and outputs differentiable? std::vector<bool> is_diff_in_, is_diff_out_; /// Input and output sparsity std::vector<Sparsity> sparsity_in_, sparsity_out_; /// Input and output scheme std::vector<std::string> name_in_, name_out_; /** \brief Use just-in-time compiler */ bool jit_; /** \brief Cleanup jit source file */ bool jit_cleanup_; /** \brief Name if jit source file */ std::string jit_name_; std::string jit_base_name_; /** \brief Use a temporary name */ bool jit_temp_suffix_; /** \brief Numerical evaluation redirected to a C function */ eval_t eval_; /** \brief Checkout redirected to a C function */ casadi_checkout_t checkout_; /** \brief Release redirected to a C function */ casadi_release_t release_; /** \brief Dict of statistics (resulting from evaluate) */ Dict stats_; /** \brief Reference counting in codegen? */ bool has_refcount_; /// Function cache mutable std::map<std::string, WeakRef> cache_; /// Cache for full Jacobian mutable WeakRef jacobian_; /// Cache for sparsities of the Jacobian blocks mutable SparseStorage<Sparsity> jac_sparsity_, jac_sparsity_compact_; /// If the function is the derivative of another function Function derivative_of_; /// User-set field void* user_data_; /// Just-in-time compiler std::string compiler_plugin_; Importer compiler_; Dict jit_options_; /// Penalty factor for using a complete Jacobian to calculate directional derivatives double jac_penalty_; // Types of derivative calculation permitted bool enable_forward_, enable_reverse_, enable_jacobian_, enable_fd_; bool enable_forward_op_, enable_reverse_op_, enable_jacobian_op_, enable_fd_op_; /// Weighting factor for derivative calculation and sparsity pattern calculation double ad_weight_, ad_weight_sp_; /// Maximum number of sensitivity directions casadi_int max_num_dir_; /// Errors are thrown when NaN is produced bool regularity_check_; /// Errors are thrown if numerical values of inputs look bad bool inputs_check_; // Finite difference step Dict fd_options_; // Finite difference step size double fd_step_; // Finite difference method std::string fd_method_; // Print input/output bool print_in_; bool print_out_; // Dump input/output bool dump_in_, dump_out_, dump_; // Directory to dump to std::string dump_dir_; // Format to dump with std::string dump_format_; // Forward/reverse options Dict forward_options_, reverse_options_; // Store a reference to a custom Jacobian Function custom_jacobian_; // Counter for unique names for dumping inputs and output mutable casadi_int dump_count_ = 0; #ifdef CASADI_WITH_THREAD mutable std::mutex dump_count_mtx_; #endif // CASADI_WITH_THREAD /** \brief Check if the function is of a particular type */ virtual bool is_a(const std::string& type, bool recursive) const; /** \brief Can a derivative direction be skipped */ template<typename MatType> static bool purgable(const std::vector<MatType>& seed); /** \brief Symbolic expressions for the forward seeds */ template<typename MatType> std::vector<std::vector<MatType> > fwd_seed(casadi_int nfwd) const; /** \brief Symbolic expressions for the adjoint seeds */ template<typename MatType> std::vector<std::vector<MatType> > symbolicAdjSeed(casadi_int nadj, const std::vector<MatType>& v) const; /** Unified return status for solvers */ enum UnifiedReturnStatus { SOLVER_RET_UNKNOWN, SOLVER_RET_SUCCESS, SOLVER_RET_LIMITED, // Out of time SOLVER_RET_NAN }; static std::string string_from_UnifiedReturnStatus(UnifiedReturnStatus status); /** \brief Deserializing constructor */ explicit FunctionInternal(DeserializingStream& e); /** \brief Deserialize with type disambiguation */ static Function deserialize(DeserializingStream& s); static std::map<std::string, ProtoFunction* (*)(DeserializingStream&)> deserialize_map; protected: /** \brief Populate jac_sparsity_ and jac_sparsity_compact_ during initialization */ void set_jac_sparsity(const Sparsity& sp); private: // @{ /// Dumping functionality casadi_int get_dump_id() const; void dump_in(casadi_int id, const double** arg) const; void dump_out(casadi_int id, double** res) const; void dump() const; // @} /** \brief Memory that is persistent during a call (but not between calls) */ size_t sz_arg_per_, sz_res_per_, sz_iw_per_, sz_w_per_; /** \brief Temporary memory inside a function */ size_t sz_arg_tmp_, sz_res_tmp_, sz_iw_tmp_, sz_w_tmp_; }; // Template implementations template<typename MatType> bool FunctionInternal::purgable(const std::vector<MatType>& v) { for (auto i=v.begin(); i!=v.end(); ++i) { if (!i->is_zero()) return false; } return true; } template<typename MatType> std::vector<std::vector<MatType> > FunctionInternal:: fwd_seed(casadi_int nfwd) const { std::vector<std::vector<MatType>> fseed(nfwd); for (casadi_int dir=0; dir<nfwd; ++dir) { fseed[dir].resize(n_in_); for (casadi_int iind=0; iind<n_in_; ++iind) { std::string n = "f" + str(dir) + "_" + name_in_[iind]; Sparsity sp = is_diff_in_[iind] ? sparsity_in(iind) : Sparsity(size_in(iind)); fseed[dir][iind] = MatType::sym(n, sp); } } return fseed; } template<typename MatType> std::vector<std::vector<MatType> > FunctionInternal:: symbolicAdjSeed(casadi_int nadj, const std::vector<MatType>& v) const { std::vector<std::vector<MatType> > aseed(nadj, v); for (casadi_int dir=0; dir<nadj; ++dir) { // Replace symbolic inputs casadi_int oind=0; for (typename std::vector<MatType>::iterator i=aseed[dir].begin(); i!=aseed[dir].end(); ++i, ++oind) { // Name of the adjoint seed std::stringstream ss; ss << "a"; if (nadj>1) ss << dir << "_"; ss << oind; // Save to matrix *i = MatType::sym(ss.str(), is_diff_out_[oind] ? i->sparsity() : Sparsity(i->size())); } } return aseed; } template<typename M> void FunctionInternal::call(const std::vector<M>& arg, std::vector<M>& res, bool always_inline, bool never_inline) const { // If all inputs are scalar ... if (all_scalar()) { // ... and some arguments are matrix-valued with matching dimensions ... bool matrix_call = false; std::pair<casadi_int, casadi_int> sz; for (auto&& a : arg) { if (!a.is_scalar() && !a.is_empty()) { if (!matrix_call) { // Matrix call matrix_call = true; sz = a.size(); } else if (a.size()!=sz) { // Not same dimensions matrix_call = false; break; } } } // ... then, call multiple times if (matrix_call) { // Start with zeros res.resize(n_out_); M z = M::zeros(sz); for (auto&& a : res) a = z; // Call multiple times std::vector<M> arg1 = arg, res1; for (casadi_int c=0; c<sz.second; ++c) { for (casadi_int r=0; r<sz.first; ++r) { // Get scalar arguments for (casadi_int i=0; i<arg.size(); ++i) { if (arg[i].size()==sz) arg1[i] = arg[i](r, c); } // Call recursively with scalar arguments call(arg1, res1, always_inline, never_inline); // Get results casadi_assert_dev(res.size() == res1.size()); for (casadi_int i=0; i<res.size(); ++i) res[i](r, c) = res1[i]; } } // All elements assigned return; } } // Check if inputs need to be replaced casadi_int npar = 1; if (!matching_arg(arg, npar)) { return call(replace_arg(arg, npar), res, always_inline, never_inline); } // Call the type-specific method call_gen(arg, res, npar, always_inline, never_inline); } template<typename M> std::vector<M> FunctionInternal:: project_arg(const std::vector<M>& arg, casadi_int npar) const { casadi_assert_dev(arg.size()==n_in_); // Which arguments require mapped evaluation std::vector<bool> mapped(n_in_); for (casadi_int i=0; i<n_in_; ++i) { mapped[i] = arg[i].size2()!=size2_in(i); } // Check if matching input sparsity std::vector<bool> matching(n_in_); bool any_mismatch = false; for (casadi_int i=0; i<n_in_; ++i) { if (mapped[i]) { matching[i] = arg[i].sparsity().is_stacked(sparsity_in(i), npar); } else { matching[i] = arg[i].sparsity()==sparsity_in(i); } any_mismatch = any_mismatch || !matching[i]; } // Correct input sparsity if (any_mismatch) { std::vector<M> arg2(arg); for (casadi_int i=0; i<n_in_; ++i) { if (!matching[i]) { if (mapped[i]) { arg2[i] = project(arg2[i], repmat(sparsity_in(i), 1, npar)); } else { arg2[i] = project(arg2[i], sparsity_in(i)); } } } return arg2; } return arg; } template<typename M> std::vector<M> FunctionInternal:: project_res(const std::vector<M>& arg, casadi_int npar) const { return arg; } template<typename D> void FunctionInternal:: call_gen(const std::vector<Matrix<D> >& arg, std::vector<Matrix<D> >& res, casadi_int npar, bool always_inline, bool never_inline) const { casadi_assert(!never_inline, "Call-nodes only possible in MX expressions"); std::vector< Matrix<D> > arg2 = project_arg(arg, npar); // Which arguments require mapped evaluation std::vector<bool> mapped(n_in_); for (casadi_int i=0; i<n_in_; ++i) { mapped[i] = arg[i].size2()!=size2_in(i); } // Allocate results res.resize(n_out_); for (casadi_int i=0; i<n_out_; ++i) { if (!res[i].sparsity().is_stacked(sparsity_out(i), npar)) { res[i] = Matrix<D>::zeros(repmat(sparsity_out(i), 1, npar)); } } // Allocate temporary memory if needed std::vector<casadi_int> iw_tmp(sz_iw()); std::vector<D> w_tmp(sz_w()); // Get pointers to input arguments std::vector<const D*> argp(sz_arg()); for (casadi_int i=0; i<n_in_; ++i) argp[i]=get_ptr(arg2[i]); // Get pointers to output arguments std::vector<D*> resp(sz_res()); for (casadi_int i=0; i<n_out_; ++i) resp[i]=get_ptr(res[i]); // For all parallel calls for (casadi_int p=0; p<npar; ++p) { // Call memory-less if (eval_gen(get_ptr(argp), get_ptr(resp), get_ptr(iw_tmp), get_ptr(w_tmp), memory(0))) { casadi_error("Evaluation failed"); } // Update offsets if (p==npar-1) break; for (casadi_int i=0; i<n_in_; ++i) if (mapped[i]) argp[i] += nnz_in(i); for (casadi_int i=0; i<n_out_; ++i) resp[i] += nnz_out(i); } } template<typename M> void FunctionInternal::check_arg(const std::vector<M>& arg, casadi_int& npar) const { casadi_assert(arg.size()==n_in_, "Incorrect number of inputs: Expected " + str(n_in_) + ", got " + str(arg.size())); for (casadi_int i=0; i<n_in_; ++i) { if (!check_mat(arg[i].sparsity(), sparsity_in(i), npar)) { // Dimensions std::string d_arg = str(arg[i].size1()) + "-by-" + str(arg[i].size2()); std::string d_in = str(size1_in(i)) + "-by-" + str(size2_in(i)); std::string e = "Input " + str(i) + " (" + name_in_[i] + ") has mismatching shape. " "Got " + d_arg + ". Allowed dimensions, in general, are:\n" " - The input dimension N-by-M (here " + d_in + ")\n" " - A scalar, i.e. 1-by-1\n" " - M-by-N if N=1 or M=1 (i.e. a transposed vector)\n" " - N-by-M1 if K*M1=M for some K (argument repeated horizontally)\n"; if (npar!=-1) { e += " - N-by-P*M, indicating evaluation with multiple arguments (P must be a " "multiple of " + str(npar) + " for consistency with previous inputs)"; } casadi_error(e); } } } template<typename M> void FunctionInternal::check_res(const std::vector<M>& res, casadi_int& npar) const { casadi_assert(res.size()==n_out_, "Incorrect number of outputs: Expected " + str(n_out_) + ", got " + str(res.size())); for (casadi_int i=0; i<n_out_; ++i) { casadi_assert(check_mat(res[i].sparsity(), sparsity_out(i), npar), "Output " + str(i) + " (" + name_out_[i] + ") has mismatching shape. " "Expected " + str(size_out(i)) + ", got " + str(res[i].size())); } } template<typename M> bool FunctionInternal::matching_arg(const std::vector<M>& arg, casadi_int& npar) const { check_arg(arg, npar); for (casadi_int i=0; i<n_in_; ++i) { if (arg.at(i).size1()!=size1_in(i)) return false; if (arg.at(i).size2()!=size2_in(i) && arg.at(i).size2()!=npar*size2_in(i)) return false; } return true; } template<typename M> bool FunctionInternal::matching_res(const std::vector<M>& res, casadi_int& npar) const { check_res(res, npar); for (casadi_int i=0; i<n_out_; ++i) { if (res.at(i).size1()!=size1_out(i)) return false; if (res.at(i).size2()!=size2_out(i) && res.at(i).size2()!=npar*size2_out(i)) return false; } return true; } template<typename M> M replace_mat(const M& arg, const Sparsity& inp, casadi_int npar) { if (arg.size()==inp.size()) { // Matching dimensions already return arg; } else if (arg.is_empty()) { // Empty matrix means set zero return M(inp.size()); } else if (arg.is_scalar()) { // Scalar assign means set all return M(inp, arg); } else if (arg.is_vector() && inp.size()==std::make_pair(arg.size2(), arg.size1())) { // Transpose vector return arg.T(); } else if (arg.size1()==inp.size1() && arg.size2()>0 && inp.size2()>0 && inp.size2()%arg.size2()==0) { // Horizontal repmat return repmat(arg, 1, inp.size2()/arg.size2()); } else { casadi_assert_dev(npar!=-1); // Multiple evaluation return repmat(arg, 1, (npar*inp.size2())/arg.size2()); } } template<typename M> std::vector<M> FunctionInternal:: replace_arg(const std::vector<M>& arg, casadi_int npar) const { std::vector<M> r(arg.size()); for (casadi_int i=0; i<r.size(); ++i) r[i] = replace_mat(arg[i], sparsity_in(i), npar); return r; } template<typename M> std::vector<M> FunctionInternal:: replace_res(const std::vector<M>& res, casadi_int npar) const { std::vector<M> r(res.size()); for (casadi_int i=0; i<r.size(); ++i) r[i] = replace_mat(res[i], sparsity_out(i), npar); return r; } template<typename M> std::vector<std::vector<M> > FunctionInternal:: replace_fseed(const std::vector<std::vector<M> >& fseed, casadi_int npar) const { std::vector<std::vector<M> > r(fseed.size()); for (casadi_int d=0; d<r.size(); ++d) r[d] = replace_arg(fseed[d], npar); return r; } template<typename M> std::vector<std::vector<M> > FunctionInternal:: replace_aseed(const std::vector<std::vector<M> >& aseed, casadi_int npar) const { std::vector<std::vector<M> > r(aseed.size()); for (casadi_int d=0; d<r.size(); ++d) r[d] = replace_res(aseed[d], npar); return r; } template<typename M> std::map<std::string, M> FunctionInternal:: convert_arg(const std::vector<M>& arg) const { casadi_assert(arg.size()==n_in_, "Incorrect number of inputs: Expected " + str(n_in_) + ", got " + str(arg.size())); std::map<std::string, M> ret; for (casadi_int i=0;i<n_in_;++i) { ret[name_in_[i]] = arg[i]; } return ret; } template<typename M> std::vector<M> FunctionInternal:: convert_arg(const std::map<std::string, M>& arg) const { // Get default inputs std::vector<M> arg_v(n_in_); for (casadi_int i=0; i<arg_v.size(); ++i) { arg_v[i] = get_default_in(i); } // Assign provided inputs for (auto&& e : arg) { arg_v.at(index_in(e.first)) = e.second; } return arg_v; } template<typename M> std::map<std::string, M> FunctionInternal:: convert_res(const std::vector<M>& res) const { casadi_assert(res.size()==n_out_, "Incorrect number of outputs: Expected " + str(n_out_) + ", got " + str(res.size())); std::map<std::string, M> ret; for (casadi_int i=0;i<n_out_;++i) { ret[name_out_[i]] = res[i]; } return ret; } template<typename M> std::vector<M> FunctionInternal:: convert_res(const std::map<std::string, M>& res) const { // Get default inputs std::vector<M> res_v(n_out_); for (casadi_int i=0; i<res_v.size(); ++i) { res_v[i] = std::numeric_limits<double>::quiet_NaN(); } // Assign provided inputs for (auto&& e : res) { M a = e.second; res_v.at(index_out(e.first)) = a; } return res_v; } } // namespace casadi /// \endcond #endif // CASADI_FUNCTION_INTERNAL_HPP
35.327869
99
0.632664
pymBRT
73f5e63507d40ef432fc8611de96bd944670a229
7,374
cpp
C++
extensions/Particle3D/PU/CCPUSphereCollider.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
null
null
null
extensions/Particle3D/PU/CCPUSphereCollider.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
4
2020-10-22T05:45:37.000Z
2020-10-23T12:11:44.000Z
extensions/Particle3D/PU/CCPUSphereCollider.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
1
2020-10-22T03:17:28.000Z
2020-10-22T03:17:28.000Z
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. https://adxeproject.github.io/ 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 "CCPUSphereCollider.h" #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h" NS_CC_BEGIN // Constants const float PUSphereCollider::DEFAULT_RADIUS = 100.0f; //----------------------------------------------------------------------- PUSphereCollider::PUSphereCollider() : PUBaseCollider(), _radius(DEFAULT_RADIUS), _innerCollision(false) {} PUSphereCollider::~PUSphereCollider(void) {} //----------------------------------------------------------------------- float PUSphereCollider::getRadius() const { return _radius; } //----------------------------------------------------------------------- void PUSphereCollider::setRadius(const float radius) { _radius = radius; _sphere.setRadius(_radius); } //----------------------------------------------------------------------- bool PUSphereCollider::isInnerCollision() const { return _innerCollision; } //----------------------------------------------------------------------- void PUSphereCollider::setInnerCollision(bool innerCollision) { _innerCollision = innerCollision; } //----------------------------------------------------------------------- void PUSphereCollider::calculateDirectionAfterCollision(PUParticle3D* particle, Vec3 distance, float distanceLength) { switch (_collisionType) { case PUBaseCollider::CT_BOUNCE: { /** If the particle is on the surface (or just inside the sphere); bounce it Make use of formula R = 2 * (-I dot N) * N + I, where R = the new direction vector I = the old (unit) direction vector before the collision N = the Normal at the collision point */ float directionLength = particle->direction.length(); particle->direction.normalize(); distance.normalize(); particle->direction = 2 * (-particle->direction.dot(distance)) * distance + particle->direction; // Adjust to original speed particle->direction *= directionLength; // Accelerate/slow down, using the bounce value particle->direction *= _bouncyness; } break; case PUBaseCollider::CT_FLOW: { /** Reset the position (on the sphere), but keep the direction. This doesn't really work good for box-type collisions, because it doesn't take the particle dimensions into account. */ float scaledRadius = 0.3333f * (_affectorScale.x + _affectorScale.y + _affectorScale.z) * _radius; particle->position = _derivedPosition + distance * (scaledRadius / distanceLength); } break; default: break; } } void PUSphereCollider::updatePUAffector(PUParticle3D* particle, float /*deltaTime*/) { // for (auto iter : _particleSystem->getParticles()) { // PUParticle3D *particle = iter; _predictedPosition = particle->position + _velocityScale * particle->direction; bool collision = false; Vec3 distance = particle->position - _derivedPosition; float distanceLength = distance.length(); float scaledRadius = 0.3333f * (_affectorScale.x + _affectorScale.y + _affectorScale.z) * _radius; // Scaling changed in V 1.3.1 switch (_intersectionType) { case PUBaseCollider::IT_POINT: { // Validate for a point-sphere intersection if (_innerCollision == (distanceLength > scaledRadius)) { // Collision detected (re-position the particle) particle->position -= _velocityScale * particle->direction; collision = true; } else { distance = _predictedPosition - _derivedPosition; distanceLength = distance.length(); if (_innerCollision == (distanceLength > scaledRadius)) { // Collision detected collision = true; } } } break; case PUBaseCollider::IT_BOX: { //// Validate for a box-sphere intersection // if (particle->particleType != Particle::PT_VISUAL) // break; AABB box; populateAlignedBox(box, particle->position, particle->width, particle->height, particle->depth); // FIXME // if (_innerCollision != box.intersects(_sphere)) //{ // // Collision detected (re-position the particle) // particle->position -= _velocityScale * particle->direction; // collision = true; // } // else //{ // AABB box; // populateAlignedBox(box, // _predictedPosition, // particle->width, // particle->height, // particle->depth); // if (_innerCollision != box.intersects(_sphere)) // { // // Collision detected // collision = true; // } // } } break; } if (collision) { calculateDirectionAfterCollision(particle, distance, distanceLength); calculateRotationSpeedAfterCollision(particle); particle->addEventFlags(PUParticle3D::PEF_COLLIDED); } } } void PUSphereCollider::preUpdateAffector(float /*deltaTime*/) { // Calculate the affectors' center position. _sphere.setCenter(getDerivedPosition()); } PUSphereCollider* PUSphereCollider::create() { auto psc = new PUSphereCollider(); psc->autorelease(); return psc; } void PUSphereCollider::copyAttributesTo(PUAffector* affector) { PUAffector::copyAttributesTo(affector); PUSphereCollider* sphereCollider = static_cast<PUSphereCollider*>(affector); sphereCollider->_radius = _radius; sphereCollider->_sphere = _sphere; sphereCollider->_innerCollision = _innerCollision; } NS_CC_END
36.50495
120
0.587469
DelinWorks
73f7790c7dcf98e5569d469d6aff2de8e5ecd2cb
3,963
cpp
C++
engine/liveupdate/src/liveupdate_private.cpp
Epitaph128/defold
554625a6438c38014b8f701c4a6e0ca684478618
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-19T15:47:07.000Z
2020-05-19T15:47:07.000Z
engine/liveupdate/src/liveupdate_private.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
engine/liveupdate/src/liveupdate_private.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Defold Foundation // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // // You may obtain a copy of the License, together with FAQs at // https://www.defold.com/license // // 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 "liveupdate.h" #include "liveupdate_private.h" #include <resource/resource.h> #include <resource/resource_archive.h> #include <dlib/log.h> #include <dlib/crypt.h> namespace dmLiveUpdate { uint32_t HexDigestLength(dmLiveUpdateDDF::HashAlgorithm algorithm) { return dmResource::HashLength(algorithm) * 2U; } HResourceEntry FindResourceEntry(const dmResource::Manifest* manifest, const dmhash_t urlHash) { HResourceEntry entries = manifest->m_DDFData->m_Resources.m_Data; int first = 0; int last = manifest->m_DDFData->m_Resources.m_Count - 1; while (first <= last) { int mid = first + (last - first) / 2; uint64_t currentHash = entries[mid].m_UrlHash; if (currentHash == urlHash) { return &entries[mid]; } else if (currentHash > urlHash) { last = mid - 1; } else if (currentHash < urlHash) { first = mid + 1; } } return NULL; } uint32_t MissingResources(dmResource::Manifest* manifest, const dmhash_t urlHash, uint8_t* entries[], uint32_t entries_size) { uint32_t resources = 0; if (manifest == 0x0) { return 0; } HResourceEntry entry = FindResourceEntry(manifest, urlHash); if (entry != NULL) { for (uint32_t i = 0; i < entry->m_Dependants.m_Count; ++i) { uint8_t* resourceHash = entry->m_Dependants.m_Data[i].m_Data.m_Data; dmResourceArchive::Result result = dmResourceArchive::FindEntry(manifest->m_ArchiveIndex, resourceHash, NULL); if (result != dmResourceArchive::RESULT_OK) { if (entries != NULL && resources < entries_size) { entries[resources] = resourceHash; } resources += 1; } } } return resources; } void CreateResourceHash(dmLiveUpdateDDF::HashAlgorithm algorithm, const char* buf, size_t buflen, uint8_t* digest) { if (algorithm == dmLiveUpdateDDF::HASH_MD5) { dmCrypt::HashMd5((const uint8_t*)buf, buflen, digest); } else if (algorithm == dmLiveUpdateDDF::HASH_SHA1) { dmCrypt::HashSha1((const uint8_t*)buf, buflen, digest); } else { dmLogError("The algorithm specified for manifest verification hashing is not supported (%i)", algorithm); } } void CreateManifestHash(dmLiveUpdateDDF::HashAlgorithm algorithm, const uint8_t* buf, size_t buflen, uint8_t* digest) { if (algorithm == dmLiveUpdateDDF::HASH_SHA1) { dmCrypt::HashSha1(buf, buflen, digest); } else if (algorithm == dmLiveUpdateDDF::HASH_SHA256) { dmCrypt::HashSha256(buf, buflen, digest); } else if (algorithm == dmLiveUpdateDDF::HASH_SHA512) { dmCrypt::HashSha512(buf, buflen, digest); } else { dmLogError("The algorithm specified for manifest verification hashing is not supported (%i)", algorithm); } } };
32.219512
128
0.587938
Epitaph128
73f8f3b6e4bf30367aff43d0951294b23415e79b
1,947
cc
C++
source/server/config/network/tcp_proxy.cc
georgi-d/envoy
3e6e4a73d5c1804842948088dd23b6f2f95ca377
[ "Apache-2.0" ]
null
null
null
source/server/config/network/tcp_proxy.cc
georgi-d/envoy
3e6e4a73d5c1804842948088dd23b6f2f95ca377
[ "Apache-2.0" ]
1
2017-11-22T09:35:42.000Z
2017-11-22T09:35:42.000Z
source/server/config/network/tcp_proxy.cc
georgi-d/envoy
3e6e4a73d5c1804842948088dd23b6f2f95ca377
[ "Apache-2.0" ]
null
null
null
#include "server/config/network/tcp_proxy.h" #include <string> #include "envoy/network/connection.h" #include "envoy/registry/registry.h" #include "common/config/filter_json.h" #include "common/filter/tcp_proxy.h" namespace Envoy { namespace Server { namespace Configuration { NetworkFilterFactoryCb TcpProxyConfigFactory::createFactory(const envoy::api::v2::filter::network::TcpProxy& config, FactoryContext& context) { Filter::TcpProxyConfigSharedPtr filter_config(new Filter::TcpProxyConfig(config, context)); return [filter_config, &context](Network::FilterManager& filter_manager) -> void { filter_manager.addReadFilter(Network::ReadFilterSharedPtr{ new Filter::TcpProxy(filter_config, context.clusterManager())}); }; } NetworkFilterFactoryCb TcpProxyConfigFactory::createFilterFactoryFromProto(const Protobuf::Message& config, FactoryContext& context) { return createFactory(dynamic_cast<const envoy::api::v2::filter::network::TcpProxy&>(config), context); } NetworkFilterFactoryCb TcpProxyConfigFactory::createFilterFactory(const Json::Object& json_config, FactoryContext& context) { envoy::api::v2::filter::network::TcpProxy tcp_proxy_config; Config::FilterJson::translateTcpProxy(json_config, tcp_proxy_config); return createFactory(tcp_proxy_config, context); } ProtobufTypes::MessagePtr TcpProxyConfigFactory::createEmptyConfigProto() { return std::unique_ptr<envoy::api::v2::filter::network::TcpProxy>( new envoy::api::v2::filter::network::TcpProxy()); } /** * Static registration for the tcp_proxy filter. @see RegisterFactory. */ static Registry::RegisterFactory<TcpProxyConfigFactory, NamedNetworkFilterConfigFactory> registered_; } // namespace Configuration } // namespace Server } // namespace Envoy
36.055556
98
0.713919
georgi-d
73fa0df29d0bfc6c6ef21ca4a78445d954ac3077
23,102
cpp
C++
src/DX/d3dfont.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
1
2018-04-01T16:47:52.000Z
2018-04-01T16:47:52.000Z
src/DX/d3dfont.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
null
null
null
src/DX/d3dfont.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
null
null
null
//----------------------------------------------------------------------------- // File: D3DFont.cpp // // Desc: Texture-based font class // // Copyright (c) 1999-2000 Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #define STRICT #include "stdafx.h" #include <stdio.h> #include <tchar.h> #include "dx.h" #include "D3DFont.h" //----------------------------------------------------------------------------- // Custom vertex types for rendering text //----------------------------------------------------------------------------- #define MAX_NUM_VERTICES 50*6 struct FONT2DVERTEX { D3DXVECTOR4 p; DWORD color; FLOAT tu, tv; }; struct FONT3DVERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; FLOAT tu, tv; }; #define D3DFVF_FONT2DVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) #define D3DFVF_FONT3DVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1) inline FONT2DVERTEX InitFont2DVertex( const D3DXVECTOR4& p, D3DCOLOR color, FLOAT tu, FLOAT tv ) { FONT2DVERTEX v; v.p = p; v.color = color; v.tu = tu; v.tv = tv; return v; } inline FONT3DVERTEX InitFont3DVertex( const D3DXVECTOR3& p, const D3DXVECTOR3& n, FLOAT tu, FLOAT tv ) { FONT3DVERTEX v; v.p = p; v.n = n; v.tu = tu; v.tv = tv; return v; } //----------------------------------------------------------------------------- // Name: CD3DFont() // Desc: Font class constructor //----------------------------------------------------------------------------- CD3DFont::CD3DFont( TCHAR* strFontName, DWORD dwHeight, DWORD dwFlags ) { _tcscpy( m_strFontName, strFontName ); m_dwFontHeight = dwHeight; m_dwFontFlags = dwFlags; m_pd3dDevice = NULL; m_pTexture = NULL; m_pVB = NULL; m_dwSavedStateBlock = 0L; m_dwDrawTextStateBlock = 0L; } //----------------------------------------------------------------------------- // Name: ~CD3DFont() // Desc: Font class destructor //----------------------------------------------------------------------------- CD3DFont::~CD3DFont() { InvalidateDeviceObjects(); DeleteDeviceObjects(); } //----------------------------------------------------------------------------- // Name: InitDeviceObjects() // Desc: Initializes device-dependent objects, including the vertex buffer used // for rendering text and the texture map which stores the font image. //----------------------------------------------------------------------------- HRESULT CD3DFont::InitDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice ) { HRESULT hr; // Keep a local copy of the device m_pd3dDevice = pd3dDevice; // Establish the font and texture size m_fTextScale = 1.0f; // Draw fonts into texture without scaling // Large fonts need larger textures if( m_dwFontHeight > 40 ) m_dwTexWidth = m_dwTexHeight = 1024; else if( m_dwFontHeight > 20 ) m_dwTexWidth = m_dwTexHeight = 512; else m_dwTexWidth = m_dwTexHeight = 256; // If requested texture is too big, use a smaller texture and smaller font, // and scale up when rendering. D3DCAPS8 d3dCaps; m_pd3dDevice->GetDeviceCaps( &d3dCaps ); if( m_dwTexWidth > d3dCaps.MaxTextureWidth ) { m_fTextScale = (FLOAT)d3dCaps.MaxTextureWidth / (FLOAT)m_dwTexWidth; m_dwTexWidth = m_dwTexHeight = d3dCaps.MaxTextureWidth; } // Create a new texture for the font hr = m_pd3dDevice->CreateTexture( m_dwTexWidth, m_dwTexHeight, 1, 0, D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, &m_pTexture ); if( FAILED(hr) ) return hr; // Prepare to create a bitmap DWORD* pBitmapBits; BITMAPINFO bmi; ZeroMemory( &bmi.bmiHeader, sizeof(BITMAPINFOHEADER) ); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = (int)m_dwTexWidth; bmi.bmiHeader.biHeight = -(int)m_dwTexHeight; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biBitCount = 32; // Create a DC and a bitmap for the font HDC hDC = CreateCompatibleDC( NULL ); HBITMAP hbmBitmap = CreateDIBSection( hDC, &bmi, DIB_RGB_COLORS, (VOID**)&pBitmapBits, NULL, 0 ); SetMapMode( hDC, MM_TEXT ); // Create a font. By specifying ANTIALIASED_QUALITY, we might get an // antialiased font, but this is not guaranteed. INT nHeight = -MulDiv( m_dwFontHeight, (INT)(GetDeviceCaps(hDC, LOGPIXELSY) * m_fTextScale), 72 ); DWORD dwBold = (m_dwFontFlags&D3DFONT_BOLD) ? FW_BOLD : FW_NORMAL; DWORD dwItalic = (m_dwFontFlags&D3DFONT_ITALIC) ? TRUE : FALSE; HFONT hFont = CreateFont( nHeight, 0, 0, 0, dwBold, dwItalic, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, m_strFontName ); if( NULL==hFont ) return E_FAIL; SelectObject( hDC, hbmBitmap ); SelectObject( hDC, hFont ); // Set text properties SetTextColor( hDC, RGB(255,255,255) ); SetBkColor( hDC, 0x00000000 ); SetTextAlign( hDC, TA_TOP ); // Loop through all printable character and output them to the bitmap.. // Meanwhile, keep track of the corresponding tex coords for each character. DWORD x = 0; DWORD y = 0; TCHAR str[2] = _T("x"); SIZE size; for( TCHAR c=32; c<127; c++ ) { str[0] = c; GetTextExtentPoint32( hDC, str, 1, &size ); if( (DWORD)(x+size.cx+1) > m_dwTexWidth ) { x = 0; y += size.cy+1; } ExtTextOut( hDC, x+0, y+0, ETO_OPAQUE, NULL, str, 1, NULL ); m_fTexCoords[c-32][0] = ((FLOAT)(x+0))/m_dwTexWidth; m_fTexCoords[c-32][1] = ((FLOAT)(y+0))/m_dwTexHeight; m_fTexCoords[c-32][2] = ((FLOAT)(x+0+size.cx))/m_dwTexWidth; m_fTexCoords[c-32][3] = ((FLOAT)(y+0+size.cy))/m_dwTexHeight; x += size.cx+1; } // Lock the surface and write the alpha values for the set pixels D3DLOCKED_RECT d3dlr; m_pTexture->LockRect( 0, &d3dlr, 0, 0 ); WORD* pDst16 = (WORD*)d3dlr.pBits; BYTE bAlpha; // 4-bit measure of pixel intensity for( y=0; y < m_dwTexHeight; y++ ) { for( x=0; x < m_dwTexWidth; x++ ) { bAlpha = (BYTE)((pBitmapBits[m_dwTexWidth*y + x] & 0xff) >> 4); if (bAlpha > 0) { *pDst16++ = (bAlpha << 12) | 0x0fff; } else { *pDst16++ = 0x0000; } } } // Done updating texture, so clean up used objects m_pTexture->UnlockRect(0); DeleteObject( hbmBitmap ); DeleteDC( hDC ); DeleteObject( hFont ); return S_OK; } //----------------------------------------------------------------------------- // Name: RestoreDeviceObjects() // Desc: //----------------------------------------------------------------------------- HRESULT CD3DFont::RestoreDeviceObjects() { HRESULT hr; // Create vertex buffer for the letters if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer( MAX_NUM_VERTICES*sizeof(FONT2DVERTEX), D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, 0, D3DPOOL_DEFAULT, &m_pVB ) ) ) { return hr; } // Create the state blocks for rendering text for( UINT which=0; which<2; which++ ) { m_pd3dDevice->BeginStateBlock(); m_pd3dDevice->SetTexture( 0, m_pTexture ); m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ); m_pd3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x08 ); m_pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL ); m_pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_CLIPPING, TRUE ); m_pd3dDevice->SetRenderState( D3DRS_EDGEANTIALIAS, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_VERTEXBLEND, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE ); m_pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_POINT ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_POINT ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_NONE ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); if( which==0 ) m_pd3dDevice->EndStateBlock( &m_dwSavedStateBlock ); else m_pd3dDevice->EndStateBlock( &m_dwDrawTextStateBlock ); } return S_OK; } //----------------------------------------------------------------------------- // Name: InvalidateDeviceObjects() // Desc: Destroys all device-dependent objects //----------------------------------------------------------------------------- HRESULT CD3DFont::InvalidateDeviceObjects() { SAFE_RELEASE( m_pVB ); // Delete the state blocks if( m_pd3dDevice ) { if( m_dwSavedStateBlock ) m_pd3dDevice->DeleteStateBlock( m_dwSavedStateBlock ); if( m_dwDrawTextStateBlock ) m_pd3dDevice->DeleteStateBlock( m_dwDrawTextStateBlock ); } m_dwSavedStateBlock = 0L; m_dwDrawTextStateBlock = 0L; return S_OK; } //----------------------------------------------------------------------------- // Name: DeleteDeviceObjects() // Desc: Destroys all device-dependent objects //----------------------------------------------------------------------------- HRESULT CD3DFont::DeleteDeviceObjects() { SAFE_RELEASE( m_pTexture ); m_pd3dDevice = NULL; return S_OK; } //----------------------------------------------------------------------------- // Name: GetTextExtent() // Desc: Get the dimensions of a text string //----------------------------------------------------------------------------- HRESULT CD3DFont::GetTextExtent( TCHAR* strText, SIZE* pSize ) { if( NULL==strText || NULL==pSize ) return E_FAIL; FLOAT fRowWidth = 0.0f; FLOAT fRowHeight = (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight; FLOAT fWidth = 0.0f; FLOAT fHeight = fRowHeight; while( *strText ) { TCHAR c = *strText++; if( c == _T('\n') ) { fRowWidth = 0.0f; fHeight += fRowHeight; } if( c < _T(' ') ) continue; FLOAT tx1 = m_fTexCoords[c-32][0]; FLOAT tx2 = m_fTexCoords[c-32][2]; fRowWidth += (tx2-tx1)*m_dwTexWidth; if( fRowWidth > fWidth ) fWidth = fRowWidth; } pSize->cx = (int)fWidth; pSize->cy = (int)fHeight; return S_OK; } //----------------------------------------------------------------------------- // Name: DrawTextScaled() // Desc: Draws scaled 2D text. Note that x and y are in viewport coordinates // (ranging from -1 to +1). fXScale and fYScale are the size fraction // relative to the entire viewport. For example, a fXScale of 0.25 is // 1/8th of the screen width. This allows you to output text at a fixed // fraction of the viewport, even if the screen or window size changes. //----------------------------------------------------------------------------- HRESULT CD3DFont::DrawTextScaled( FLOAT x, FLOAT y, FLOAT z, FLOAT fXScale, FLOAT fYScale, DWORD dwColor, TCHAR* strText, DWORD dwFlags ) { if( m_pd3dDevice == NULL ) return E_FAIL; // Set up renderstate m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock ); m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock ); m_pd3dDevice->SetVertexShader( D3DFVF_FONT2DVERTEX ); m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT2DVERTEX) ); // Set filter states if( dwFlags & D3DFONT_FILTERED ) { m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); } D3DVIEWPORT8 vp; m_pd3dDevice->GetViewport( &vp ); FLOAT sx = (x+1.0f)*vp.Width/2; FLOAT sy = (y-1.0f)*vp.Height/2; FLOAT sz = z; FLOAT rhw = 1.0f; FLOAT fStartX = sx; FLOAT fLineHeight = ( m_fTexCoords[0][3] - m_fTexCoords[0][1] ) * m_dwTexHeight; // Fill vertex buffer FONT2DVERTEX* pVertices; DWORD dwNumTriangles = 0L; m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); while( *strText ) { TCHAR c = *strText++; if( c == _T('\n') ) { sx = fStartX; sy += fYScale*vp.Height; } if( c < _T(' ') ) continue; FLOAT tx1 = m_fTexCoords[c-32][0]; FLOAT ty1 = m_fTexCoords[c-32][1]; FLOAT tx2 = m_fTexCoords[c-32][2]; FLOAT ty2 = m_fTexCoords[c-32][3]; FLOAT w = (tx2-tx1)*m_dwTexWidth; FLOAT h = (ty2-ty1)*m_dwTexHeight; w *= (fXScale*vp.Height)/fLineHeight; h *= (fYScale*vp.Height)/fLineHeight; *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx1, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx1, ty1 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx2, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx2, ty1 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx2, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx1, ty1 ); dwNumTriangles += 2; if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) ) { // Unlock, render, and relock the vertex buffer m_pVB->Unlock(); m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); dwNumTriangles = 0L; } sx += w; } // Unlock and render the vertex buffer m_pVB->Unlock(); if( dwNumTriangles > 0 ) m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); // Restore the modified renderstates m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock ); return S_OK; } //----------------------------------------------------------------------------- // Name: DrawText() // Desc: Draws 2D text //----------------------------------------------------------------------------- HRESULT CD3DFont::DrawText( FLOAT sx, FLOAT sy, DWORD dwColor, TCHAR* strText, DWORD dwFlags ) { if( m_pd3dDevice == NULL ) return E_FAIL; // Setup renderstate m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock ); m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock ); m_pd3dDevice->SetVertexShader( D3DFVF_FONT2DVERTEX ); m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT2DVERTEX) ); // Set filter states if( dwFlags & D3DFONT_FILTERED ) { m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); } FLOAT fStartX = sx; // Fill vertex buffer FONT2DVERTEX* pVertices = NULL; DWORD dwNumTriangles = 0; m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); while( *strText ) { TCHAR c = *strText++; if( c == _T('\n') ) { sx = fStartX; sy += (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight; } if( c < _T(' ') ) continue; FLOAT tx1 = m_fTexCoords[c-32][0]; FLOAT ty1 = m_fTexCoords[c-32][1]; FLOAT tx2 = m_fTexCoords[c-32][2]; FLOAT ty2 = m_fTexCoords[c-32][3]; FLOAT w = (tx2-tx1) * m_dwTexWidth / m_fTextScale; FLOAT h = (ty2-ty1) * m_dwTexHeight / m_fTextScale; *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx1, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx2, ty1 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 ); *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 ); dwNumTriangles += 2; if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) ) { // Unlock, render, and relock the vertex buffer m_pVB->Unlock(); m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); pVertices = NULL; m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); dwNumTriangles = 0L; } sx += w; } // Unlock and render the vertex buffer m_pVB->Unlock(); if( dwNumTriangles > 0 ) m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); // Restore the modified renderstates m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock ); return S_OK; } //----------------------------------------------------------------------------- // Name: Render3DText() // Desc: Renders 3D text //----------------------------------------------------------------------------- HRESULT CD3DFont::Render3DText( TCHAR* strText, DWORD dwFlags ) { if( m_pd3dDevice == NULL ) return E_FAIL; // Setup renderstate m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock ); m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock ); m_pd3dDevice->SetVertexShader( D3DFVF_FONT3DVERTEX ); m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT3DVERTEX) ); // Set filter states if( dwFlags & D3DFONT_FILTERED ) { m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); } // Position for each text element FLOAT x = 0.0f; FLOAT y = 0.0f; // Center the text block at the origin if( dwFlags & D3DFONT_CENTERED ) { SIZE sz; GetTextExtent( strText, &sz ); x = -(((FLOAT)sz.cx)/10.0f)/2.0f; y = -(((FLOAT)sz.cy)/10.0f)/2.0f; } // Turn off culling for two-sided text if( dwFlags & D3DFONT_TWOSIDED ) m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); FLOAT fStartX = x; TCHAR c; // Fill vertex buffer FONT3DVERTEX* pVertices; DWORD dwVertex = 0L; DWORD dwNumTriangles = 0L; m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); while( c = *strText++ ) { if( c == '\n' ) { x = fStartX; y -= (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight/10.0f; } if( c < 32 ) continue; FLOAT tx1 = m_fTexCoords[c-32][0]; FLOAT ty1 = m_fTexCoords[c-32][1]; FLOAT tx2 = m_fTexCoords[c-32][2]; FLOAT ty2 = m_fTexCoords[c-32][3]; FLOAT w = (tx2-tx1) * m_dwTexWidth / ( 10.0f * m_fTextScale ); FLOAT h = (ty2-ty1) * m_dwTexHeight / ( 10.0f * m_fTextScale ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+0,0), D3DXVECTOR3(0,0,-1), tx1, ty2 ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+h,0), D3DXVECTOR3(0,0,-1), tx1, ty1 ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+0,0), D3DXVECTOR3(0,0,-1), tx2, ty2 ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+h,0), D3DXVECTOR3(0,0,-1), tx2, ty1 ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+0,0), D3DXVECTOR3(0,0,-1), tx2, ty2 ); *pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+h,0), D3DXVECTOR3(0,0,-1), tx1, ty1 ); dwNumTriangles += 2; if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) ) { // Unlock, render, and relock the vertex buffer m_pVB->Unlock(); m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD ); dwNumTriangles = 0L; } x += w; } // Unlock and render the vertex buffer m_pVB->Unlock(); if( dwNumTriangles > 0 ) m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles ); // Restore the modified renderstates m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock ); return S_OK; }
35.109422
106
0.54636
HonzaMD
bab71693892dc7b0edbbbf181f173dcb6ed26ca5
545
cpp
C++
src/mge/core/memory.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/mge/core/memory.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/mge/core/memory.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. #include "mge/core/memory.hpp" #include "mge/core/stdexceptions.hpp" namespace mge { void* mge::malloc(size_t size) { void* ptr = ::malloc(size); if (ptr == nullptr) { MGE_THROW(out_of_memory) << "Cannot allocate " << size << " bytes"; } return ptr; } void free(void* ptr) { if (ptr == nullptr) { return; } ::free(ptr); } } // namespace mge
20.961538
79
0.537615
mge-engine
babb0f31f384c06114789059edc72a0acc8dd312
653
hpp
C++
src/interpreter/headers/TokenFactory.hpp
Rishirai7/cpp_interpreter
77756cba2c426db70be562c6e0119bad45346eb6
[ "MIT" ]
1
2022-02-02T05:44:20.000Z
2022-02-02T05:44:20.000Z
src/interpreter/headers/TokenFactory.hpp
Rishirai7/cpp_interpreter
77756cba2c426db70be562c6e0119bad45346eb6
[ "MIT" ]
6
2022-01-16T21:04:02.000Z
2022-01-16T21:17:52.000Z
src/interpreter/headers/TokenFactory.hpp
Rishirai7/cpp_interpreter
77756cba2c426db70be562c6e0119bad45346eb6
[ "MIT" ]
1
2022-01-22T19:10:23.000Z
2022-01-22T19:10:23.000Z
/* Author: R. Baltrusch */ #pragma once #ifndef TOKENFACTORY_H #define TOKENFACTORY_H #include <any> #include <map> #include <regex> #include <string> #include <memory> #include "Token.hpp" #include "Value.hpp" class TokenFactory { ConstructorMap tokens, regexTokens; std::map<std::string, std::regex> compiledRegexPatterns; int lineNumber; public: TokenFactory(ConstructorMap tokens, ConstructorMap regexTokens); std::shared_ptr<Token> createToken(const std::string& string); static std::shared_ptr<Value> createVariable(const std::string &name); static std::shared_ptr<Value> createValue(std::any &value); }; #endif
19.787879
74
0.732006
Rishirai7
babbc2ec47bd228e431312083880830470369af5
24,748
hpp
C++
src/roles/client.hpp
lfranchi/websocketpp
85b9ed7cef7280f9889b08053f45feb6d1ff3204
[ "BSD-3-Clause" ]
2
2016-07-31T10:50:43.000Z
2017-01-03T21:00:50.000Z
src/roles/client.hpp
lfranchi/websocketpp
85b9ed7cef7280f9889b08053f45feb6d1ff3204
[ "BSD-3-Clause" ]
null
null
null
src/roles/client.hpp
lfranchi/websocketpp
85b9ed7cef7280f9889b08053f45feb6d1ff3204
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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. * */ #ifndef WEBSOCKETPP_ROLE_CLIENT_HPP #define WEBSOCKETPP_ROLE_CLIENT_HPP #include <limits> #include <iostream> #include <boost/cstdint.hpp> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/random.hpp> #include <boost/random/random_device.hpp> #include "../endpoint.hpp" #include "../uri.hpp" #include "../shared_const_buffer.hpp" #ifdef _MSC_VER // Disable "warning C4355: 'this' : used in base member initializer list". # pragma warning(push) # pragma warning(disable:4355) #endif using boost::asio::ip::tcp; namespace websocketpp { namespace role { template <class endpoint> class client { public: // Connection specific details template <typename connection_type> class connection { public: typedef connection<connection_type> type; typedef endpoint endpoint_type; // client connections are friends with their respective client endpoint friend class client<endpoint>; // Valid always int get_version() const { return m_version; } std::string get_origin() const { return m_origin; } // not sure when valid std::string get_request_header(const std::string& key) const { return m_request.header(key); } std::string get_response_header(const std::string& key) const { return m_response.header(key); } // Valid before connect is called void add_request_header(const std::string& key, const std::string& value) { m_request.add_header(key,value); } void replace_request_header(const std::string& key, const std::string& value) { m_request.replace_header(key,value); } void remove_request_header(const std::string& key) { m_request.remove_header(key); } void add_subprotocol(const std::string& value) { m_requested_subprotocols.push_back(value); } void set_origin(const std::string& value) { m_origin = value; } // Information about the requested URI // valid only after URIs are loaded // TODO: check m_uri for NULLness bool get_secure() const { return m_uri->get_secure(); } std::string get_host() const { return m_uri->get_host(); } std::string get_resource() const { return m_uri->get_resource(); } uint16_t get_port() const { return m_uri->get_port(); } std::string get_uri() const { return m_uri->str(); } int32_t rand() { return m_endpoint.rand(); } bool is_server() const { return false; } // should this exist? boost::asio::io_service& get_io_service() { return m_endpoint.get_io_service(); } protected: connection(endpoint& e) : m_endpoint(e), m_connection(static_cast< connection_type& >(*this)), // TODO: version shouldn't be hardcoded m_version(13) {} void set_uri(uri_ptr u) { m_uri = u; } void async_init() { m_connection.m_processor = processor::ptr(new processor::hybi<connection_type>(m_connection)); m_connection.get_handler()->on_handshake_init(m_connection.shared_from_this()); write_request(); } void write_request(); void handle_write_request(const boost::system::error_code& error); void read_response(); void handle_read_response(const boost::system::error_code& error, std::size_t bytes_transferred); void log_open_result(); private: endpoint& m_endpoint; connection_type& m_connection; int m_version; uri_ptr m_uri; std::string m_origin; std::vector<std::string> m_requested_subprotocols; std::vector<std::string> m_requested_extensions; std::string m_subprotocol; std::vector<std::string> m_extensions; std::string m_handshake_key; http::parser::request m_request; http::parser::response m_response; }; // types typedef client<endpoint> type; typedef endpoint endpoint_type; typedef typename endpoint_traits<endpoint>::connection_type connection_type; typedef typename endpoint_traits<endpoint>::connection_ptr connection_ptr; typedef typename endpoint_traits<endpoint>::handler_ptr handler_ptr; // handler interface callback class class handler_interface { public: // Required virtual void on_open(connection_ptr con) {} virtual void on_close(connection_ptr con) {} virtual void on_fail(connection_ptr con) {} virtual void on_message(connection_ptr con,message::data_ptr) {} // Optional virtual void on_handshake_init(connection_ptr con) {} virtual bool on_ping(connection_ptr con,std::string) {return true;} virtual void on_pong(connection_ptr con,std::string) {} virtual void on_pong_timeout(connection_ptr con,std::string) {} }; client (boost::asio::io_service& m) : m_endpoint(static_cast< endpoint_type& >(*this)), m_io_service(m), m_gen(m_rng, boost::random::uniform_int_distribution<>( std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::max() )) {} connection_ptr get_connection(const std::string& u); connection_ptr connect(const std::string& u); connection_ptr connect(connection_ptr con); void run(bool perpetual = false); void end_perpetual(); void reset(); protected: bool is_server() const {return false;} int32_t rand() {return m_gen();} private: void handle_connect(connection_ptr con, const boost::system::error_code& error); endpoint_type& m_endpoint; boost::asio::io_service& m_io_service; boost::random::random_device m_rng; boost::random::variate_generator< boost::random::random_device&, boost::random::uniform_int_distribution<> > m_gen; boost::shared_ptr<boost::asio::io_service::work> m_idle_worker; }; // client implimentation /// Start the client ASIO loop /** * Calls run on the endpoint's io_service. This method will block until the io_service * run method returns. This method may only be called when the endpoint is in the IDLE * state. Endpoints start in the idle state and can be returned to the IDLE state by * calling reset. `run` has a perpetual flag (default is false) that indicates whether * or not it should return after all connections have been made. * * <b>Important note:</b> Calling run with perpetual = false on a client endpoint will return * immediately unless you have already called connect() at least once. To get around * this either queue up all connections you want to make before calling run or call * run with perpetual in another thread. * * Visibility: public * State: Valid from IDLE, an exception is thrown otherwise * Concurrency: callable from any thread * * @param perpetual whether or not to run the endpoint in perpetual mode * @exception websocketpp::exception with code error::INVALID_STATE if called from a state other than IDLE */ template <class endpoint> void client<endpoint>::run(bool perpetual) { { boost::lock_guard<boost::recursive_mutex> lock(m_endpoint.m_lock); if (m_endpoint.m_state != endpoint::IDLE) { throw exception("client::run called from invalid state",error::INVALID_STATE); } if (perpetual) { m_idle_worker = boost::shared_ptr<boost::asio::io_service::work>( new boost::asio::io_service::work(m_io_service) ); } m_endpoint.m_state = endpoint::RUNNING; } // TODO: preliminary support for multi-threaded clients. Finish external // interface once better tested size_t num_threads = 1; if (num_threads == 1) { m_io_service.run(); } else if (num_threads > 1 && num_threads <= MAX_THREAD_POOL_SIZE) { std::vector< boost::shared_ptr<boost::thread> > threads; for (std::size_t i = 0; i < num_threads; ++i) { boost::shared_ptr<boost::thread> thread( new boost::thread(boost::bind( &boost::asio::io_service::run, &m_io_service )) ); threads.push_back(thread); } for (std::size_t i = 0; i < threads.size(); ++i) { threads[i]->join(); } } else { throw exception("listen called with invalid num_threads value"); } m_endpoint.m_state = endpoint::STOPPED; } /// End the idle work loop that keeps the io_service active /** * Calling end_perpetual on a client endpoint that was started in perpetual mode (via * run(true), will stop the idle work object that prevents the run method from * returning even when there is no work for it to do. Use if you want to gracefully * stop the endpoint. Use stop() to forcibly stop the endpoint. * * Visibility: public * State: Valid from RUNNING, ignored otherwise * Concurrency: callable from any thread */ template <class endpoint> void client<endpoint>::end_perpetual() { if (m_idle_worker) { m_idle_worker.reset(); } } /// Reset a stopped endpoint. /** * Resets an endpoint that was stopped by stop() or whose run() method exited due to * running out of work. reset() should not be called while the endpoint is running. * Use stop() and/or end_perpetual() first and then reset once one of those methods * has fully stopped the endpoint. * * Visibility: public * State: Valid from STOPPED, an exception is thrown otherwise * Concurrency: callable from any thread */ template <class endpoint> void client<endpoint>::reset() { boost::lock_guard<boost::recursive_mutex> lock(m_endpoint.m_lock); if (m_endpoint.m_state != endpoint::STOPPED) { throw exception("client::reset called from invalid state",error::INVALID_STATE); } m_io_service.reset(); m_endpoint.m_state = endpoint::IDLE; } /// Returns a new connection /** * Creates and returns a pointer to a new connection to the given URI suitable for passing * to connect(). This method allows applying connection specific settings before * performing the connection. * * Visibility: public * State: Valid from IDLE or RUNNING, an exception is thrown otherwise * Concurrency: callable from any thread * * @param u The URI that this connection will connect to. * @return The pointer to the new connection */ template <class endpoint> typename endpoint_traits<endpoint>::connection_ptr client<endpoint>::get_connection(const std::string& u) { try { uri_ptr location(new uri(u)); if (location->get_secure() && !m_endpoint.is_secure()) { throw websocketpp::exception("Endpoint doesn't support secure connections.", websocketpp::error::ENDPOINT_UNSECURE); } connection_ptr con = m_endpoint.create_connection(); if (!con) { throw websocketpp::exception("get_connection called from invalid state", websocketpp::error::INVALID_STATE); } con->set_uri(location); return con; } catch (uri_exception& e) { throw websocketpp::exception(e.what(),websocketpp::error::INVALID_URI); } } /// Begin the connect process for the given connection. /** * Initiates the async connect request for connection con. * * Visibility: public * State: Valid from IDLE or RUNNING, an exception is thrown otherwise * Concurrency: callable from any thread * * @param con A pointer to the connection to connect * @return The pointer to con */ template <class endpoint> typename endpoint_traits<endpoint>::connection_ptr client<endpoint>::connect(connection_ptr con) { tcp::resolver resolver(m_io_service); std::stringstream p; p << con->get_port(); tcp::resolver::query query(con->get_host(),p.str()); tcp::resolver::iterator iterator = resolver.resolve(query); boost::asio::async_connect( con->get_raw_socket(), iterator, boost::bind( &endpoint_type::handle_connect, this, // shared from this? con, boost::asio::placeholders::error ) ); return con; } /// Convenience method, equivalent to connect(get_connection(u)) template <class endpoint> typename endpoint_traits<endpoint>::connection_ptr client<endpoint>::connect(const std::string& u) { return connect(get_connection(u)); } template <class endpoint> void client<endpoint>::handle_connect(connection_ptr con, const boost::system::error_code& error) { if (!error) { m_endpoint.m_alog->at(log::alevel::CONNECT) << "Successful connection" << log::endl; con->start(); } else { con->m_fail_code = fail::status::SYSTEM; con->m_fail_system = error; if (error == boost::system::errc::connection_refused) { con->m_fail_reason = "Connection refused"; } else if (error == boost::system::errc::operation_canceled) { con->m_fail_reason = "Operation canceled"; } else if (error == boost::system::errc::connection_reset) { con->m_fail_reason = "Connection Reset"; } else if (error == boost::system::errc::timed_out) { con->m_fail_reason = "Operation timed out"; } else if (error == boost::system::errc::broken_pipe) { con->m_fail_reason = "Broken pipe"; } else { con->m_fail_reason = "Unknown"; } m_endpoint.m_elog->at(log::elevel::RERROR) << "An error occurred while establishing a connection: " << error << " (" << con->m_fail_reason << ")" << log::endl; con->terminate(false); } } // client connection implimentation template <class endpoint> template <class connection_type> void client<endpoint>::connection<connection_type>::write_request() { boost::lock_guard<boost::recursive_mutex> lock(m_connection.m_lock); // async write to handle_write m_request.set_method("GET"); m_request.set_uri(m_uri->get_resource()); m_request.set_version("HTTP/1.1"); m_request.add_header("Upgrade","websocket"); m_request.add_header("Connection","Upgrade"); m_request.replace_header("Sec-WebSocket-Version","13"); m_request.replace_header("Host",m_uri->get_host_port()); if (m_origin != "") { m_request.replace_header("Origin",m_origin); } if (m_requested_subprotocols.size() > 0) { std::string vals; std::string sep = ""; std::vector<std::string>::iterator it; for (it = m_requested_subprotocols.begin(); it != m_requested_subprotocols.end(); ++it) { vals += sep + *it; sep = ","; } m_request.replace_header("Sec-WebSocket-Protocol",vals); } // Generate client key int32_t raw_key[4]; for (int i = 0; i < 4; i++) { raw_key[i] = this->rand(); } m_handshake_key = base64_encode(reinterpret_cast<unsigned char const*>(raw_key), 16); m_request.replace_header("Sec-WebSocket-Key",m_handshake_key); // Unless the user has overridden the user agent, send generic WS++ if (m_request.header("User-Agent") == "") { m_request.replace_header("User-Agent",USER_AGENT); } // TODO: generating this raw request involves way too much copying in cases // without string/vector move semantics. shared_const_buffer buffer(m_request.raw()); //std::string raw = m_request.raw(); //m_endpoint.m_alog->at(log::alevel::DEBUG_HANDSHAKE) << raw << log::endl; boost::asio::async_write( m_connection.get_socket(), //boost::asio::buffer(raw), buffer, m_connection.get_strand().wrap(boost::bind( &type::handle_write_request, m_connection.shared_from_this(), boost::asio::placeholders::error )) ); } template <class endpoint> template <class connection_type> void client<endpoint>::connection<connection_type>::handle_write_request( const boost::system::error_code& error) { if (error) { // TODO: detached state? m_endpoint.m_elog->at(log::elevel::RERROR) << "Error writing WebSocket request. code: " << error << log::endl; m_connection.terminate(false); return; } read_response(); } template <class endpoint> template <class connection_type> void client<endpoint>::connection<connection_type>::read_response() { boost::asio::async_read_until( m_connection.get_socket(), m_connection.buffer(), "\r\n\r\n", m_connection.get_strand().wrap(boost::bind( &type::handle_read_response, m_connection.shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred )) ); } template <class endpoint> template <class connection_type> void client<endpoint>::connection<connection_type>::handle_read_response ( const boost::system::error_code& error, std::size_t bytes_transferred) { boost::lock_guard<boost::recursive_mutex> lock(m_connection.m_lock); // detached check? if (error) { m_endpoint.m_elog->at(log::elevel::RERROR) << "Error reading HTTP request. code: " << error << log::endl; m_connection.terminate(false); return; } try { std::istream request(&m_connection.buffer()); if (!m_response.parse_complete(request)) { // not a valid HTTP response // TODO: this should be a client error throw http::exception("Could not parse server response.", http::status_code::BAD_REQUEST); } m_endpoint.m_alog->at(log::alevel::DEBUG_HANDSHAKE) << m_response.raw() << log::endl; // error checking if (m_response.get_status_code() != http::status_code::SWITCHING_PROTOCOLS) { throw http::exception("Server failed to upgrade connection.", m_response.get_status_code(), m_response.get_status_msg()); } std::string h = m_response.header("Upgrade"); if (!boost::ifind_first(h,"websocket")) { throw http::exception("Token `websocket` missing from Upgrade header.", m_response.get_status_code(), m_response.get_status_msg()); } h = m_response.header("Connection"); if (!boost::ifind_first(h,"upgrade")) { throw http::exception("Token `upgrade` missing from Connection header.", m_response.get_status_code(), m_response.get_status_msg()); } h = m_response.header("Sec-WebSocket-Accept"); if (h == "") { throw http::exception("Required Sec-WebSocket-Accept header is missing.", m_response.get_status_code(), m_response.get_status_msg()); } else { std::string server_key = m_handshake_key; server_key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; SHA1 sha; uint32_t message_digest[5]; sha.Reset(); sha << server_key.c_str(); if (!sha.Result(message_digest)) { m_endpoint.m_elog->at(log::elevel::RERROR) << "Error computing handshake sha1 hash." << log::endl; // TODO: close behavior return; } // convert sha1 hash bytes to network byte order because this sha1 // library works on ints rather than bytes for (int i = 0; i < 5; i++) { message_digest[i] = htonl(message_digest[i]); } server_key = base64_encode( reinterpret_cast<const unsigned char*>(message_digest),20); if (server_key != h) { m_endpoint.m_elog->at(log::elevel::RERROR) << "Server returned incorrect handshake key." << log::endl; // TODO: close behavior return; } } log_open_result(); m_connection.m_state = session::state::OPEN; m_connection.get_handler()->on_open(m_connection.shared_from_this()); get_io_service().post( m_connection.m_strand.wrap(boost::bind( &connection_type::handle_read_frame, m_connection.shared_from_this(), boost::system::error_code() )) ); //m_connection.handle_read_frame(boost::system::error_code()); } catch (const http::exception& e) { m_endpoint.m_elog->at(log::elevel::RERROR) << "Error processing server handshake. Server HTTP response: " << e.m_error_msg << " (" << e.m_error_code << ") Local error: " << e.what() << log::endl; return; } // start session loop } template <class endpoint> template <class connection_type> void client<endpoint>::connection<connection_type>::log_open_result() { std::stringstream version; version << "v" << m_version << " "; m_endpoint.m_alog->at(log::alevel::CONNECT) << (m_version == -1 ? "HTTP" : "WebSocket") << " Connection " << m_connection.get_raw_socket().remote_endpoint() << " " << (m_version == -1 ? "" : version.str()) << (get_request_header("Server") == "" ? "NULL" : get_request_header("Server")) << " " << m_uri->get_resource() << " " << m_response.get_status_code() << log::endl; } } // namespace role } // namespace websocketpp #ifdef _MSC_VER # pragma warning(pop) #endif #endif // WEBSOCKETPP_ROLE_CLIENT_HPP
34.709677
106
0.608211
lfranchi
bacbb2da043bdfff60ef9dc61b345ea75fdcd07c
6,248
cc
C++
modules/guardian/guardian_component.cc
aaaaliyun/apollo
5d4bb57a253327434c829ab5b6936916f5b229da
[ "Apache-2.0" ]
null
null
null
modules/guardian/guardian_component.cc
aaaaliyun/apollo
5d4bb57a253327434c829ab5b6936916f5b229da
[ "Apache-2.0" ]
null
null
null
modules/guardian/guardian_component.cc
aaaaliyun/apollo
5d4bb57a253327434c829ab5b6936916f5b229da
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/guardian/guardian_component.h" #include "cyber/common/log.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/message_util.h" namespace apollo { namespace guardian { using apollo::canbus::Chassis; using apollo::control::ControlCommand; using apollo::monitor::SystemStatus; bool GuardianComponent::Init() { if (!GetProtoConfig(&guardian_conf_)) { AERROR << "Unable to load canbus conf file: " << ConfigFilePath(); return false; } chassis_reader_ = node_->CreateReader<Chassis>(FLAGS_chassis_topic, [this](const std::shared_ptr<Chassis>& chassis) { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); chassis_.CopyFrom(*chassis); }); control_cmd_reader_ = node_->CreateReader<ControlCommand>(FLAGS_control_command_topic, [this](const std::shared_ptr<ControlCommand>& cmd) { ADEBUG << "Received control data: run control callback."; std::lock_guard<std::mutex> lock(mutex_); control_cmd_.CopyFrom(*cmd); }); system_status_reader_ = node_->CreateReader<SystemStatus>(FLAGS_system_status_topic, [this](const std::shared_ptr<SystemStatus>& status) { ADEBUG << "Received system status data: run system status callback."; std::lock_guard<std::mutex> lock(mutex_); last_status_received_s_ = cyber::Time::Now().ToSecond(); system_status_.CopyFrom(*status); }); guardian_writer_ = node_->CreateWriter<GuardianCommand>(FLAGS_guardian_topic); return true; } bool GuardianComponent::Proc() { ADEBUG << "Timer is triggered: publish GuardianComponent result"; bool safety_mode_triggered = false; if (guardian_conf_.guardian_enable()) { std::lock_guard<std::mutex> lock(mutex_); static constexpr double kSecondsTillTimeout(2.5); if (cyber::Time::Now().ToSecond() - last_status_received_s_ > kSecondsTillTimeout) { safety_mode_triggered = true; } safety_mode_triggered = safety_mode_triggered || system_status_.has_safety_mode_trigger_time(); } if (safety_mode_triggered) { ADEBUG << "Safety mode triggered, enable safety mode"; TriggerSafetyMode(); } else { ADEBUG << "Safety mode not triggered, bypass control command"; PassThroughControlCommand(); } common::util::FillHeader(node_->Name(), &guardian_cmd_); guardian_writer_->Write(guardian_cmd_); return true; } void GuardianComponent::PassThroughControlCommand() { std::lock_guard<std::mutex> lock(mutex_); guardian_cmd_.mutable_control_command()->CopyFrom(control_cmd_); } void GuardianComponent::TriggerSafetyMode() { AINFO << "Safety state triggered, with system safety mode trigger time : " << system_status_.safety_mode_trigger_time(); std::lock_guard<std::mutex> lock(mutex_); bool sensor_malfunction = false, obstacle_detected = false; if (!chassis_.surround().sonar_enabled() || chassis_.surround().sonar_fault()) { AINFO << "Ultrasonic sensor not enabled for faulted, will do emergency stop!"; sensor_malfunction = true; } else { // TODO(QiL) : Load for config for (int i = 0; i < chassis_.surround().sonar_range_size(); ++i) { if ((chassis_.surround().sonar_range(i) > 0.0 && chassis_.surround().sonar_range(i) < 2.5) || chassis_.surround().sonar_range(i) > 30) { AINFO << "Object detected or ultrasonic sensor fault output, will do emergency stop!"; obstacle_detected = true; } } } guardian_cmd_.mutable_control_command()->set_throttle(0.0); guardian_cmd_.mutable_control_command()->set_steering_target(0.0); guardian_cmd_.mutable_control_command()->set_steering_rate(25.0); guardian_cmd_.mutable_control_command()->set_is_in_safe_mode(true); // TODO(QiL) : Remove this one once hardware re-alignment is done. sensor_malfunction = false; obstacle_detected = false; AINFO << "Temporarily ignore the ultrasonic sensor output during hardware re-alignment!"; if (system_status_.require_emergency_stop() || sensor_malfunction || obstacle_detected) { AINFO << "Emergency stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake(guardian_conf_.guardian_cmd_emergency_stop_percentage()); } else { AINFO << "Soft stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake(guardian_conf_.guardian_cmd_soft_stop_percentage()); } } } // namespace guardian } // namespace apollo
41.653333
146
0.609955
aaaaliyun
bacdff80c95820123d28565c22915eaa1f575ce4
1,070
hh
C++
src/game/units/Car.hh
zermingore/warevolved
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
[ "MIT" ]
1
2019-09-23T18:16:27.000Z
2019-09-23T18:16:27.000Z
src/game/units/Car.hh
zermingore/warevolved
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
[ "MIT" ]
2
2018-11-12T18:48:03.000Z
2018-11-15T21:10:02.000Z
src/game/units/Car.hh
zermingore/warevolved
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
[ "MIT" ]
null
null
null
/** * \file * \date June 2, 2019 * \author Zermingore * \brief Car (specific Unit) class declaration */ #ifndef CAR_HH_ # define CAR_HH_ # include <string> # include <game/units/Vehicle.hh> /** * \class Car * \brief Specialization of Unit class */ class Car: public Vehicle { public: /** * \brief Default Constructor. Initializes characteristics motion, hp, ... */ Car(); /** * \brief Can open fire depending on the presence of a co-pilot */ bool canOpenFire() const override final; /** * \brief Add the given unit to the Car if its role allows it * \param unit Unit getting in the car (adding it to the crew) * \param role role to give to the Unit getting in the car * \note If the role is left empty: The driver will be added; then the copilot */ bool addToCrew( std::shared_ptr<Unit> unit, e_unit_role role = e_unit_role::NONE) override final; /** * Update the Sprite, depending on the crew * \todo Clean manual pixel offsets */ void updateSprite() override final; }; #endif /* !CAR_HH_ */
20.980392
80
0.661682
zermingore
bad39e8fdca14d39e241f3cb6f2c4b057e3e8b15
2,103
cc
C++
src/utils/ambry_bitset_test.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
1
2021-01-11T14:19:51.000Z
2021-01-11T14:19:51.000Z
src/utils/ambry_bitset_test.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
src/utils/ambry_bitset_test.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2016 LinkedIn Corp. 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. */ // ambry/ambry-utils/src/test/java/com.github.ambry.utils/OpenBitSetTest.java #include "utils/ambry_bitset.h" #include "platform/base_error.h" /** * OpenBitSet Test */ namespace bubblefs { namespace myambry { namespace utils { class OpenBitSetTest { //@Test public: void testOpenBitSetTest() { OpenBitSet bitSet(1000); bitSet.set(0); bitSet.set(100); PRINTF_CHECK_TRUE(bitSet.get(0)); PRINTF_CHECK_TRUE(bitSet.get(100)); PRINTF_CHECK_FALSE(bitSet.get(1)); bitSet.clear(0); PRINTF_CHECK_FALSE(bitSet.get(0)); PRINTF_CHECK_EQ(bitSet.capacity(), 1024); PRINTF_CHECK_EQ(bitSet.size(), 1024); PRINTF_CHECK_EQ(bitSet.length(), 1024); PRINTF_CHECK_EQ(bitSet.isEmpty(), false); PRINTF_CHECK_EQ(bitSet.cardinality(), 1); OpenBitSet bitSet2(1000); bitSet2.set(100); bitSet2.set(1); bitSet2.andWith(bitSet); PRINTF_CHECK_TRUE(bitSet2.get(100)); PRINTF_CHECK_FALSE(bitSet2.get(1)); bitSet2.intersect(bitSet); PRINTF_CHECK_TRUE(bitSet2.get(100)); OpenBitSet bitSet3(1000); bitSet3.set(100); PRINTF_CHECK_TRUE(bitSet2.equals(&bitSet3)); bitSet3.set(101); bitSet3.set(102); bitSet3.set(103); bitSet3.clear(100, 104); PRINTF_CHECK_FALSE(bitSet3.get(100)); PRINTF_CHECK_FALSE(bitSet3.get(101)); PRINTF_CHECK_FALSE(bitSet3.get(102)); PRINTF_CHECK_FALSE(bitSet3.get(103)); } }; } // namespace utils } // namespace myambry } // namespace bubblefs int main(int argc, char* argv[]) { bubblefs::myambry::utils::OpenBitSetTest t; t.testOpenBitSetTest(); return 0; }
28.418919
77
0.705183
pengdu
bad4c56593b298d9f0302a0d673da1458535c2c9
3,704
cpp
C++
isis/src/base/objs/PvlTokenizer/unitTest.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/base/objs/PvlTokenizer/unitTest.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/base/objs/PvlTokenizer/unitTest.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include <sstream> #include "PvlToken.h" #include "PvlTokenizer.h" #include "IException.h" #include "Preference.h" using namespace Isis; using namespace std; int main(void) { Preference::Preferences(true); //***************************************************************************** // Create Instances of the Tokenizer //***************************************************************************** PvlTokenizer tizer; //***************************************************************************** // Create a stream and load it //***************************************************************************** stringstream os; os << "DOG=POODLE " << "CAT=\"TABBY\" " << "BIRD=(PARROT) \0" << "REPTILE={SNAKE,LIZARD} \t" << "-VEGGIE \n" << " " << " BOVINE = ( COW , CAMEL ) \n " << "TREE = { \"MAPLE\" ,\n \"ELM\" \n, \"PINE\" }" << "FLOWER = \"DAISY & \nTULIP \"" << "# This is a comment\n" << "/* This is another comment\n" << "BIG = (\" NOT \",\"REALLY LARGE\")\n" << "SEQUENCE = ((a,b,c), (d,e,f))" << "QUOTED_STRING=\"A QUOTED STRING\"" << "QuotedNewLine=\"abcd\nefgh \nijk\n lmn\"" << "ApostNewLine=\'abcd\nefgh \nijk\n lmn\'"; try { tizer.Load(os); } catch(IException &e) { e.print(); } vector<PvlToken> t = tizer.GetTokenList(); cout << "TESTING TOKENIZER" << endl; int i, j; for(i = 0; i < (int)t.size(); i++) { cout << t[i].key() << " is "; for(j = 0; j < t[i].valueSize(); j++) { cout << t[i].value(j) << " "; } cout << endl; } cout << endl; cout << "TESTING TOKENIZER CLEAR" << endl; tizer.Clear(); vector<PvlToken> t2 = tizer.GetTokenList(); cout << t2.size() << endl << endl; stringstream os2; os2 << "PHRASE = \"The quick brown fox jumped over the lazy dog"; cout << "TESTING TOKEN ERROR [" << os2.str() << "]" << endl; try { tizer.Load(os2); } catch(IException &e) { e.print(); } cout << endl; stringstream os3; os3 << "PHRASE = {To Be or Not To Be That is the Question"; cout << "TESTING TOKEN ERROR [" << os3.str() << "]" << endl; try { tizer.Load(os3); } catch(IException &e) { e.print(); } cout << endl; stringstream os4; os4 << "PHRASE = (I came, I saw, I conquered"; cout << "TESTING TOKEN ERROR [" << os4.str() << "]" << endl; try { tizer.Load(os4); } catch(IException &e) { e.print(); } cout << endl; stringstream os5; os5 << "FOOD = (\"french\",\"fries,\"good\") "; cout << "TESTING TOKEN ERROR [" << os5.str() << "]" << endl; try { tizer.Load(os5); } catch(IException &e) { e.print(); } cout << endl; stringstream os6; os6 << "FOOD = (\"burgers\",\"hotdogs,\"good\")"; cout << "TESTING TOKEN ERROR [" << os6.str() << "]" << endl; try { tizer.Load(os6); } catch(IException &e) { e.print(); } cout << endl; stringstream os7; os7 << "FOOD = (\"pickels,pizza\")"; cout << "TESTING TOKEN ERROR [" << os7.str() << "]" << endl; try { tizer.Load(os7); } catch(IException &e) { e.print(); } cout << endl; stringstream os8; os8 << "FISH = (\"trout\",\"pizz\"a)"; cout << "TESTING TOKEN ERROR [" << os8.str() << "]" << endl; try { tizer.Load(os8); } catch(IException &e) { e.print(); } cout << endl; return 0; }
24.529801
79
0.49784
kdl222
bade0ae118df2427739823a2ca52c6c9120a42ec
8,647
cc
C++
Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/sslidentity.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/sslidentity.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/sslidentity.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Handling of certificates and keypairs for SSLStreamAdapter's peer mode. #include BOSS_WEBRTC_U_rtc_base__sslidentity_h //original-code:"rtc_base/sslidentity.h" #include <ctime> #include <string> #include <utility> #include BOSS_ABSEILCPP_U_absl__memory__memory_h //original-code:"absl/memory/memory.h" #include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" #include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" #include BOSS_WEBRTC_U_rtc_base__opensslidentity_h //original-code:"rtc_base/opensslidentity.h" #include BOSS_WEBRTC_U_rtc_base__sslfingerprint_h //original-code:"rtc_base/sslfingerprint.h" #include BOSS_WEBRTC_U_rtc_base__third_party__base64__base64_h //original-code:"rtc_base/third_party/base64/base64.h" namespace rtc { ////////////////////////////////////////////////////////////////////// // KeyParams ////////////////////////////////////////////////////////////////////// const char kPemTypeCertificate[] = "CERTIFICATE"; const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY"; const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY"; KeyParams::KeyParams(KeyType key_type) { if (key_type == KT_ECDSA) { type_ = KT_ECDSA; params_.curve = EC_NIST_P256; } else if (key_type == KT_RSA) { type_ = KT_RSA; params_.rsa.mod_size = kRsaDefaultModSize; params_.rsa.pub_exp = kRsaDefaultExponent; } else { RTC_NOTREACHED(); } } // static KeyParams KeyParams::RSA(int mod_size, int pub_exp) { KeyParams kt(KT_RSA); kt.params_.rsa.mod_size = mod_size; kt.params_.rsa.pub_exp = pub_exp; return kt; } // static KeyParams KeyParams::ECDSA(ECCurve curve) { KeyParams kt(KT_ECDSA); kt.params_.curve = curve; return kt; } bool KeyParams::IsValid() const { if (type_ == KT_RSA) { return (params_.rsa.mod_size >= kRsaMinModSize && params_.rsa.mod_size <= kRsaMaxModSize && params_.rsa.pub_exp > params_.rsa.mod_size); } else if (type_ == KT_ECDSA) { return (params_.curve == EC_NIST_P256); } return false; } RSAParams KeyParams::rsa_params() const { RTC_DCHECK(type_ == KT_RSA); return params_.rsa; } ECCurve KeyParams::ec_curve() const { RTC_DCHECK(type_ == KT_ECDSA); return params_.curve; } KeyType IntKeyTypeFamilyToKeyType(int key_type_family) { return static_cast<KeyType>(key_type_family); } ////////////////////////////////////////////////////////////////////// // SSLIdentity ////////////////////////////////////////////////////////////////////// bool SSLIdentity::PemToDer(const std::string& pem_type, const std::string& pem_string, std::string* der) { // Find the inner body. We need this to fulfill the contract of // returning pem_length. size_t header = pem_string.find("-----BEGIN " + pem_type + "-----"); if (header == std::string::npos) return false; size_t body = pem_string.find("\n", header); if (body == std::string::npos) return false; size_t trailer = pem_string.find("-----END " + pem_type + "-----"); if (trailer == std::string::npos) return false; std::string inner = pem_string.substr(body + 1, trailer - (body + 1)); *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE | Base64::DO_PAD_ANY | Base64::DO_TERM_BUFFER); return true; } std::string SSLIdentity::DerToPem(const std::string& pem_type, const unsigned char* data, size_t length) { std::stringstream result; result << "-----BEGIN " << pem_type << "-----\n"; std::string b64_encoded; Base64::EncodeFromArray(data, length, &b64_encoded); // Divide the Base-64 encoded data into 64-character chunks, as per // 4.3.2.4 of RFC 1421. static const size_t kChunkSize = 64; size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize; for (size_t i = 0, chunk_offset = 0; i < chunks; ++i, chunk_offset += kChunkSize) { result << b64_encoded.substr(chunk_offset, kChunkSize); result << "\n"; } result << "-----END " << pem_type << "-----\n"; return result.str(); } // static SSLIdentity* SSLIdentity::GenerateWithExpiration(const std::string& common_name, const KeyParams& key_params, time_t certificate_lifetime) { return OpenSSLIdentity::GenerateWithExpiration(common_name, key_params, certificate_lifetime); } // static SSLIdentity* SSLIdentity::Generate(const std::string& common_name, const KeyParams& key_params) { return OpenSSLIdentity::GenerateWithExpiration( common_name, key_params, kDefaultCertificateLifetimeInSeconds); } // static SSLIdentity* SSLIdentity::Generate(const std::string& common_name, KeyType key_type) { return OpenSSLIdentity::GenerateWithExpiration( common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds); } SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) { return OpenSSLIdentity::GenerateForTest(params); } // static SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key, const std::string& certificate) { return OpenSSLIdentity::FromPEMStrings(private_key, certificate); } // static SSLIdentity* SSLIdentity::FromPEMChainStrings( const std::string& private_key, const std::string& certificate_chain) { return OpenSSLIdentity::FromPEMChainStrings(private_key, certificate_chain); } bool operator==(const SSLIdentity& a, const SSLIdentity& b) { return static_cast<const OpenSSLIdentity&>(a) == static_cast<const OpenSSLIdentity&>(b); } bool operator!=(const SSLIdentity& a, const SSLIdentity& b) { return !(a == b); } ////////////////////////////////////////////////////////////////////// // Helper Functions ////////////////////////////////////////////////////////////////////// // Read |n| bytes from ASN1 number string at *|pp| and return the numeric value. // Update *|pp| and *|np| to reflect number of read bytes. static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) { const unsigned char* p = *pp; int x = 0; for (size_t i = 0; i < n; i++) x = 10 * x + p[i] - '0'; *pp = p + n; *np = *np - n; return x; } int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) { size_t bytes_left = length; // Make sure the string ends with Z. Doing it here protects the strspn call // from running off the end of the string in Z's absense. if (length == 0 || s[length - 1] != 'Z') return -1; // Make sure we only have ASCII digits so that we don't need to clutter the // code below and ASN1ReadInt with error checking. size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789"); if (n + 1 != length) return -1; int year; // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME" // format. Both format use UTC in this context. if (long_format) { // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ. if (bytes_left < 11) return -1; year = ASN1ReadInt(&s, &bytes_left, 4); year -= 1900; } else { // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280 // requires us to only support exactly yymmddhhmmssZ. if (bytes_left < 9) return -1; year = ASN1ReadInt(&s, &bytes_left, 2); if (year < 50) // Per RFC 5280 4.1.2.5.1 year += 100; } std::tm tm; tm.tm_year = year; // Read out remaining ASN1 time data and store it in |tm| in documented // std::tm format. tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1; tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2); tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2); tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2); tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2); if (bytes_left != 1) { // Now just Z should remain. Its existence was asserted above. return -1; } return TmToSeconds(tm); } } // namespace rtc
32.878327
117
0.634555
Yash-Wasalwar-07
bae186b86e8137b246bc0265b48e5aee040e6de8
4,838
hpp
C++
FlexEngine/include/Types.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
762
2017-11-07T23:40:58.000Z
2022-03-31T16:03:22.000Z
FlexEngine/include/Types.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
5
2018-03-13T14:41:06.000Z
2020-11-01T12:02:29.000Z
FlexEngine/include/Types.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
43
2017-11-17T11:22:37.000Z
2022-03-14T01:51:19.000Z
#pragma once #include <cstdint> #include <limits> #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) #define ARRAY_LENGTH(a) ARRAY_SIZE(a) namespace flex { class GameObject; using u8 = uint8_t; using u16 = uint16_t; using u32 = uint32_t; using u64 = uint64_t; using i8 = int8_t; using i16 = int16_t; using i32 = int32_t; using i64 = int64_t; using real = float; using deg = real; using rad = real; using sec = real; // Seconds using ms = real; // Milliseconds 1x10^-3 seconds using us = real; // Microseconds 1x10^-6 seconds using ns = real; // Nanoseconds 1x10^-9 seconds using VertexAttributes = u32; using RenderID = u32; using ShaderID = u32; using MaterialID = u32; using TextureID = u32; using FrameBufferAttachmentID = u32; using GraphicsPipelineID = u32; using PointLightID = u32; using SpotLightID = u32; using AreaLightID = u32; using AudioSourceID = u32; using TrackID = u32; using CartID = u32; using CartChainID = u32; using VariableID = u32; using ParticleSystemID = u32; using GameObjectStackID = u32; using StringID = u64; using ThreadHandle = u64; using SpecializationConstantID = u32; static constexpr auto u8_min = std::numeric_limits<u8>::min(); static constexpr auto u8_max = std::numeric_limits<u8>::max(); static constexpr auto u16_min = std::numeric_limits<u16>::min(); static constexpr auto u16_max = std::numeric_limits<u16>::max(); static constexpr auto u32_min = std::numeric_limits<u32>::min(); static constexpr auto u32_max = std::numeric_limits<u32>::max(); static constexpr auto u64_min = std::numeric_limits<u64>::min(); static constexpr auto u64_max = std::numeric_limits<u64>::max(); static constexpr auto i8_min = std::numeric_limits<i8>::min(); static constexpr auto i8_max = std::numeric_limits<i8>::max(); static constexpr auto i16_min = std::numeric_limits<i16>::min(); static constexpr auto i16_max = std::numeric_limits<i16>::max(); static constexpr auto i32_min = std::numeric_limits<i32>::min(); static constexpr auto i32_max = std::numeric_limits<i32>::max(); static constexpr auto i64_min = std::numeric_limits<i64>::min(); static constexpr auto i64_max = std::numeric_limits<i64>::max(); static constexpr auto real_min = std::numeric_limits<real>::min(); static constexpr auto real_max = std::numeric_limits<real>::max(); static constexpr auto InvalidRenderID = ((RenderID)u32_max); static constexpr auto InvalidShaderID = ((ShaderID)u32_max); static constexpr auto InvalidMaterialID = ((MaterialID)u32_max); static constexpr auto InvalidTextureID = ((TextureID)u32_max); static constexpr auto InvalidFrameBufferAttachmentID = ((FrameBufferAttachmentID)u32_max); static constexpr auto InvalidGraphicsPipelineID = ((GraphicsPipelineID)u32_max); static constexpr auto InvalidPointLightID = ((PointLightID)u32_max); static constexpr auto InvalidSpotLightID = ((SpotLightID)u32_max); static constexpr auto InvalidAreaLightID = ((AreaLightID)u32_max); static constexpr auto InvalidAudioSourceID = ((AudioSourceID)u32_max); static constexpr auto InvalidTrackID = ((TrackID)u32_max); static constexpr auto InvalidCartID = ((CartChainID)u32_max); static constexpr auto InvalidCartChainID = ((CartChainID)u32_max); static constexpr auto InvalidVariableID = ((VariableID)u32_max); static constexpr auto InvalidParticleSystemID = ((ParticleSystemID)u32_max); static constexpr auto InvalidThreadHandle = ((ThreadHandle)u64_max); static constexpr auto InvalidBufferID = u64_max; static constexpr auto InvalidSpecializationConstantID = (SpecializationConstantID)u32_max; static constexpr auto InvalidStringID = (StringID)u64_max; static constexpr auto InvalidID = u32_max; //template<bool> struct StaticAssert; //template<> struct StaticAssert<true> {}; // Screen-space anchors enum class AnchorPoint { CENTER, TOP_LEFT, TOP, TOP_RIGHT, RIGHT, BOTTOM_RIGHT, BOTTOM, BOTTOM_LEFT, LEFT, WHOLE, // Covers the whole screen _NONE }; enum class EventReply { CONSUMED, UNCONSUMED }; // TODO: Move enums to their own header enum class SamplingType { CONSTANT, // All samples are equally-weighted LINEAR, // Latest sample is weighted N times higher than Nth sample CUBIC, // Latest samples contribute much more than old samples }; enum class TurningDir { LEFT, NONE, RIGHT }; enum class TransformState { TRANSLATE, ROTATE, SCALE, _NONE }; enum class TrackState { FACING_FORWARD, FACING_BACKWARD, _NONE }; static const char* TrackStateStrs[] = { "Facing forward", "Facing backward", "NONE", }; static_assert(ARRAY_LENGTH(TrackStateStrs) == (u32)TrackState::_NONE + 1, "Length of TrackStateStrs must match length of TrackState enum"); enum class LookDirection { LEFT, CENTER, RIGHT, _NONE }; } // namespace flex
27.804598
140
0.740389
ajweeks
bae40de52fdcf5a60576133398cae77b19f95b66
65,658
cpp
C++
src/condor_startd.V6/claim.cpp
krowenrao/htcondor
9cd7983fe4318849b9a133ee28c56cbfa2773de7
[ "Apache-2.0" ]
null
null
null
src/condor_startd.V6/claim.cpp
krowenrao/htcondor
9cd7983fe4318849b9a133ee28c56cbfa2773de7
[ "Apache-2.0" ]
null
null
null
src/condor_startd.V6/claim.cpp
krowenrao/htcondor
9cd7983fe4318849b9a133ee28c56cbfa2773de7
[ "Apache-2.0" ]
null
null
null
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* This file implements the classes defined in claim.h. See that file for comments and documentation on what it's about. Originally written 9/29/97 by Derek Wright <wright@cs.wisc.edu> Decided the Match object should really be called "Claim" (the files were renamed in cvs from Match.[Ch] to claim.[Ch], and renamed everything on 1/10/03 - Derek Wright */ #include "condor_common.h" #include "startd.h" #include "condor_crypt.h" #include "dc_schedd.h" // for startdClaimIdFile #include "misc_utils.h" // for starter exit codes #include "exit.h" /////////////////////////////////////////////////////////////////////////// // Claim /////////////////////////////////////////////////////////////////////////// Claim::Claim( Resource* res_ip, ClaimType claim_type, int lease_duration ) : c_rip(res_ip) , c_client(NULL) , c_id(0) , c_type(claim_type) , c_jobad(NULL) , c_starter_pid(0) , c_rank(0) , c_oldrank(0) , c_universe(-1) , c_cluster(-1) , c_proc(-1) , c_global_job_id(NULL) , c_job_start(-1) , c_last_pckpt(-1) , c_claim_started(0) , c_entered_state(0) , c_job_total_run_time(0) , c_job_total_suspend_time(0) , c_claim_total_run_time(0) , c_claim_total_suspend_time(0) , c_activation_count(0) , c_request_stream(NULL) , c_match_tid(-1) , c_lease_tid(-1) , c_sendalive_tid(-1) , c_alive_inprogress_sock(NULL) , c_lease_duration(lease_duration) , c_aliveint(-1) , c_starter_handles_alives(false) , c_startd_sends_alives(false) , c_cod_keyword(NULL) , c_has_job_ad(false) , c_state(CLAIM_IDLE) , c_last_state(CLAIM_UNCLAIMED) , c_pending_cmd(-1) , c_wants_remove(false) , c_may_unretire(true) , c_retire_peacefully(false) , c_preempt_was_true(false) , c_badput_caused_by_draining(false) , c_badput_caused_by_preemption(false) , c_schedd_closed_claim(false) , c_pledged_machine_max_vacate_time(0) , c_cpus_usage(0) , c_image_size(0) { //dprintf(D_ALWAYS | D_BACKTRACE, "constructing claim %p on resource %p\n", this, res_ip); c_client = new Client; c_id = new ClaimId( claim_type, res_ip->r_id_str ); if( claim_type == CLAIM_OPPORTUNISTIC ) { c_id->dropFile( res_ip->r_id ); } // to make purify happy, we want to initialize this to // something. however, we immediately set it to UNCLAIMED // (which is what it should really be) by using changeState() // so we get all the nice functionality that method provides. c_state = CLAIM_IDLE; changeState( CLAIM_UNCLAIMED ); c_last_state = CLAIM_UNCLAIMED; } Claim::~Claim() { if( c_type == CLAIM_COD ) { dprintf( D_FULLDEBUG, "Deleted claim %s (owner '%s')\n", c_id->id(), c_client->owner() ? c_client->owner() : "unknown" ); } // The resources assigned to this claim must have been freed by now. if( c_rip != NULL && c_rip->r_classad != NULL ) { resmgr->adlist_unset_monitors( c_rip->r_id, c_rip->r_classad ); } else { dprintf( D_ALWAYS, "Unable to unset monitors in claim destructor. The StartOfJob* attributes will be stale. (%p, %p)\n", c_rip, c_rip == NULL ? NULL : c_rip->r_classad ); } // Cancel any daemonCore events associated with this claim this->cancel_match_timer(); this->cancelLeaseTimer(); if ( c_alive_inprogress_sock ) { daemonCore->Cancel_Socket(c_alive_inprogress_sock); c_alive_inprogress_sock = NULL; } // if we were associated with a starter, then we need to check to see if that starter was reaped // before we can delete the job ad. if (c_starter_pid && c_jobad) { Starter * starter = findStarterByPid(c_starter_pid); if (starter && starter->notYetReaped()) { dprintf(D_ALWAYS, "Deleting claim while starter is still alive. The STARTD history for job %d.%d may be incomplete\n", c_cluster, c_proc); // update stat for JobBusyTime if (c_job_start > 0) { double busyTime = condor_gettimestamp_double() - c_job_start; resmgr->startd_stats.job_busy_time += busyTime; } // Transfer ownership of our jobad to the starter so it can write a correct history entry. starter->setOrphanedJob(c_jobad); c_jobad = NULL; } } // Free up memory that's been allocated if (c_jobad) { delete(c_jobad); c_jobad = NULL; } delete( c_id ); if( c_client ) { delete( c_client ); } // delete the request stream and do any necessary related cleanup setRequestStream( NULL ); if( c_global_job_id ) { free( c_global_job_id ); } if( c_cod_keyword ) { free( c_cod_keyword ); } } void Claim::scheddClosedClaim() { // This tells us that there is no need to send RELEASE_CLAIM // to the schedd, because it was the schedd that told _us_ // to close the claim. c_schedd_closed_claim = true; } void Claim::vacate() { ASSERT( c_id ); // warn the client of this claim that it's being vacated if( c_client && c_client->addr() && !c_schedd_closed_claim ) { c_client->vacate( c_id->id() ); } #if HAVE_JOB_HOOKS if ((c_type == CLAIM_FETCH) && c_has_job_ad) { resmgr->m_hook_mgr->hookEvictClaim(c_rip); } #endif /* HAVE_JOB_HOOKS */ } void Claim::publish( ClassAd* cad, amask_t how_much ) { MyString line; char* tmp; char *remoteUser; /* NOTE: currently, we publish all of the following regardless of the mask (e.g. UPDATE vs. TIMEOUT). Given the bug with ImageSize being recomputed but not used due to UPDATE vs. TIMEOUT confusion when publishing it, I'm inclined to ignore the performance cost of publishing the same stuff every timeout. If, for some crazy reason, this becomes a problem, we can always seperate these into UPDATE + TIMEOUT attributes and only publish accordingly... Derek <wright@cs.wisc.edu> 2005-08-11 */ line.formatstr( "%s = %f", ATTR_CURRENT_RANK, c_rank ); cad->Insert( line.Value() ); if( c_client ) { remoteUser = c_client->user(); if( remoteUser ) { line.formatstr( "%s=\"%s\"", ATTR_REMOTE_USER, remoteUser ); cad->Insert( line.Value() ); } tmp = c_client->owner(); if( tmp ) { line.formatstr( "%s=\"%s\"", ATTR_REMOTE_OWNER, tmp ); cad->Insert( line.Value() ); } tmp = c_client->accountingGroup(); if( tmp ) { char *uidDom = NULL; // The accountant wants to see ATTR_ACCOUNTING_GROUP // fully qualified if ( remoteUser ) { uidDom = strchr(remoteUser,'@'); } if ( uidDom ) { line.formatstr("%s=\"%s%s\"",ATTR_ACCOUNTING_GROUP,tmp,uidDom); } else { line.formatstr("%s=\"%s\"", ATTR_ACCOUNTING_GROUP, tmp ); } cad->Insert( line.Value() ); } tmp = c_client->host(); if( tmp ) { line.formatstr( "%s=\"%s\"", ATTR_CLIENT_MACHINE, tmp ); cad->Insert( line.Value() ); } tmp = c_client->getConcurrencyLimits(); if (tmp) { cad->Assign(ATTR_CONCURRENCY_LIMITS, tmp); } int numJobPids = c_client->numPids(); //In standard universe, numJobPids should be 1 if(c_universe == CONDOR_UNIVERSE_STANDARD) { numJobPids = 1; } line.formatstr("%s=%d", ATTR_NUM_PIDS, numJobPids); cad->Insert( line.Value() ); if ((tmp = c_client->rmtgrp())) { cad->Assign(ATTR_REMOTE_GROUP, tmp); } if ((tmp = c_client->neggrp())) { cad->Assign(ATTR_REMOTE_NEGOTIATING_GROUP, tmp); cad->Assign(ATTR_REMOTE_AUTOREGROUP, c_client->autorg()); } } if( (c_cluster > 0) && (c_proc >= 0) ) { line.formatstr( "%s=\"%d.%d\"", ATTR_JOB_ID, c_cluster, c_proc ); cad->Insert( line.Value() ); } if( c_global_job_id ) { line.formatstr( "%s=\"%s\"", ATTR_GLOBAL_JOB_ID, c_global_job_id ); cad->Insert( line.Value() ); } if( c_job_start > 0 ) { // The "JobStart" attribute is traditionally an integer, so we truncate the time to an int for this assignment. cad->Assign(ATTR_JOB_START, (time_t)c_job_start); } if( c_last_pckpt > 0 ) { line.formatstr( "%s=%d", ATTR_LAST_PERIODIC_CHECKPOINT, c_last_pckpt ); cad->Insert( line.Value() ); } // update ImageSize attribute from procInfo (this is // only for the opportunistic job, not COD) if( isActive() ) { // put the image size value from the last call to updateUsage into the ad. cad->Assign(ATTR_IMAGE_SIZE, c_image_size); // also the CpusUsage value cad->Assign("CPUsUsage", c_cpus_usage); //PRAGMA_REMIND("put CpusUsage into the standard attributes header file.") } // If this claim is for vm universe, update some info about VM if (c_starter_pid > 0) { resmgr->m_vmuniverse_mgr.publishVMInfo(c_starter_pid, cad, how_much); } publishStateTimes( cad ); } void Claim::publishPreemptingClaim( ClassAd* cad, amask_t /*how_much*/ /*UNUSED*/ ) { MyString line; char* tmp; char *remoteUser; if( c_client && c_client->user() ) { line.formatstr( "%s = %f", ATTR_PREEMPTING_RANK, c_rank ); cad->Insert( line.Value() ); remoteUser = c_client->user(); if( remoteUser ) { line.formatstr( "%s=\"%s\"", ATTR_PREEMPTING_USER, remoteUser ); cad->Insert( line.Value() ); } tmp = c_client->owner(); if( tmp ) { line.formatstr( "%s=\"%s\"", ATTR_PREEMPTING_OWNER, tmp ); cad->Insert( line.Value() ); } tmp = c_client->accountingGroup(); if( tmp ) { char *uidDom = NULL; // The accountant wants to see ATTR_ACCOUNTING_GROUP // fully qualified if ( remoteUser ) { uidDom = strchr(remoteUser,'@'); } if ( uidDom ) { line.formatstr("%s=\"%s%s\"",ATTR_PREEMPTING_ACCOUNTING_GROUP,tmp,uidDom); } else { line.formatstr("%s=\"%s\"", ATTR_PREEMPTING_ACCOUNTING_GROUP, tmp ); } cad->Insert( line.Value() ); } tmp = c_client->getConcurrencyLimits(); if (tmp) { line.formatstr("%s=\"%s\"", ATTR_PREEMPTING_CONCURRENCY_LIMITS, tmp); cad->Insert(line.Value()); } } else { cad->Delete(ATTR_PREEMPTING_RANK); cad->Delete(ATTR_PREEMPTING_OWNER); cad->Delete(ATTR_PREEMPTING_USER); cad->Delete(ATTR_PREEMPTING_ACCOUNTING_GROUP); } } void Claim::publishCOD( ClassAd* cad ) { MyString line; char* tmp; line = codId(); line += '_'; line += ATTR_CLAIM_ID; line += "=\""; line += id(); line += '"'; cad->Insert( line.Value() ); line = codId(); line += '_'; line += ATTR_CLAIM_STATE; line += "=\""; line += getClaimStateString( c_state ); line += '"'; cad->Insert( line.Value() ); line = codId(); line += '_'; line += ATTR_ENTERED_CURRENT_STATE; line += '='; line += IntToStr( (int)c_entered_state ); cad->Insert( line.Value() ); if( c_client ) { tmp = c_client->user(); if( tmp ) { line = codId(); line += '_'; line += ATTR_REMOTE_USER; line += "=\""; line += tmp; line += '"'; cad->Insert( line.Value() ); } tmp = c_client->accountingGroup(); if( tmp ) { line = codId(); line += '_'; line += ATTR_ACCOUNTING_GROUP; line += "=\""; line += tmp; line += '"'; cad->Insert( line.Value() ); } tmp = c_client->host(); if( tmp ) { line = codId(); line += '_'; line += ATTR_CLIENT_MACHINE; line += "=\""; line += tmp; line += '"'; cad->Insert( line.Value() ); } } if( c_starter_pid ) { if( c_cod_keyword ) { line = codId(); line += '_'; line += ATTR_JOB_KEYWORD; line += "=\""; line += c_cod_keyword; line += '"'; cad->Insert( line.Value() ); } char buf[128]; if( (c_cluster > 0) && (c_proc >= 0) ) { snprintf( buf, 128, "%d.%d", c_cluster, c_proc ); } else { strcpy( buf, "1.0" ); } line = codId(); line += '_'; line += ATTR_JOB_ID; line += "=\""; line += buf; line += '"'; cad->Insert( line.Value() ); if( c_job_start > 0 ) { line = codId(); line += '_'; line += ATTR_JOB_START; cad->Assign( line.Value(), (time_t)c_job_start ); } } } time_t Claim::getJobTotalRunTime() { time_t my_job_run = c_job_total_run_time; time_t now; if( c_state == CLAIM_RUNNING ) { now = time(NULL); my_job_run += now - c_entered_state; } return my_job_run; } void Claim::publishStateTimes( ClassAd* cad ) { MyString line; time_t now, time_dif = 0; time_t my_job_run = c_job_total_run_time; time_t my_job_sus = c_job_total_suspend_time; time_t my_claim_run = c_claim_total_run_time; time_t my_claim_sus = c_claim_total_suspend_time; // If we're currently claimed or suspended, add on the time // we've spent in the current state, since we only increment // the private data members on state changes... if( c_state == CLAIM_RUNNING || c_state == CLAIM_SUSPENDED ) { now = time( NULL ); time_dif = now - c_entered_state; } if( c_state == CLAIM_RUNNING ) { my_job_run += time_dif; my_claim_run += time_dif; } if( c_state == CLAIM_SUSPENDED ) { my_job_sus += time_dif; my_claim_sus += time_dif; } // Now that we have all the right values, publish them. if( my_job_run > 0 ) { line.formatstr( "%s=%ld", ATTR_TOTAL_JOB_RUN_TIME, (long)my_job_run ); cad->Insert( line.Value() ); } if( my_job_sus > 0 ) { line.formatstr( "%s=%ld", ATTR_TOTAL_JOB_SUSPEND_TIME, (long)my_job_sus ); cad->Insert( line.Value() ); } if( my_claim_run > 0 ) { line.formatstr( "%s=%ld", ATTR_TOTAL_CLAIM_RUN_TIME, (long)my_claim_run ); cad->Insert( line.Value() ); } if( my_claim_sus > 0 ) { line.formatstr( "%s=%ld", ATTR_TOTAL_CLAIM_SUSPEND_TIME, (long)my_claim_sus ); cad->Insert( line.Value() ); } } void Claim::dprintf( int flags, const char* fmt, ... ) { va_list args; va_start( args, fmt ); if (c_rip) { c_rip->dprintf_va( flags, fmt, args ); } else { const DPF_IDENT ident = 0; // REMIND: maybe something useful here?? ::_condor_dprintf_va( flags, ident, fmt, args ); } va_end( args ); } void Claim::refuseClaimRequest() { if( !c_request_stream ) { return; } dprintf( D_ALWAYS, "Refusing request to claim Resource\n" ); c_request_stream->encode(); c_request_stream->put(NOT_OK); c_request_stream->end_of_message(); } void Claim::start_match_timer() { if( c_match_tid != -1 ) { /* We got matched twice for the same ClaimId. This must be because we got matched, we sent an update that said we're unavailable, but the collector dropped that update, and we got matched again. This shouldn't be a fatal error, b/c UDP gets dropped all the time. We just need to cancel the old timer, print a warning, and then continue. */ dprintf( D_FAILURE|D_ALWAYS, "Warning: got matched twice for same ClaimId." " Canceling old match timer (%d)\n", c_match_tid ); if( daemonCore->Cancel_Timer(c_match_tid) < 0 ) { dprintf( D_ALWAYS, "Failed to cancel old match timer (%d): " "daemonCore error\n", c_match_tid ); } else { dprintf( D_FULLDEBUG, "Cancelled old match timer (%d)\n", c_match_tid ); } c_match_tid = -1; } c_match_tid = daemonCore->Register_Timer( match_timeout, 0, (TimerHandlercpp) &Claim::match_timed_out, "match_timed_out", this ); if( c_match_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } dprintf( D_FULLDEBUG, "Started match timer (%d) for %d seconds.\n", c_match_tid, match_timeout ); } void Claim::cancel_match_timer() { int rval; if( c_match_tid != -1 ) { rval = daemonCore->Cancel_Timer( c_match_tid ); if( rval < 0 ) { dprintf( D_ALWAYS, "Failed to cancel match timer (%d): " "daemonCore error\n", c_match_tid ); } else { dprintf( D_FULLDEBUG, "Canceled match timer (%d)\n", c_match_tid ); } c_match_tid = -1; } } void Claim::match_timed_out() { char* my_id = id(); if( !my_id ) { // We're all confused. // Don't use our dprintf(), use the "real" version, since // if we're this confused, our rip pointer might be messed // up, too, and we don't want to seg fault. ::dprintf( D_FAILURE|D_ALWAYS, "ERROR: Match timed out but there's no ClaimId\n" ); return; } Resource* res_ip = resmgr->get_by_any_id( my_id ); if( !res_ip ) { ::dprintf( D_FAILURE|D_ALWAYS, "ERROR: Can't find resource of expired match\n" ); return; } if( res_ip->r_cur->idMatches( id() ) ) { #if HAVE_BACKFILL if( res_ip->state() == backfill_state ) { /* If the resource is in the backfill state when the match timed out, it means that the backfill job is taking longer to exit than the match timeout, which should be an extremely rare case. However, if it happens, we need to handle it. Luckily, all we have to do is change our destination state and return, since the ResState code will deal with resetting the claim objects once we hit the owner state... */ dprintf( D_FAILURE|D_ALWAYS, "WARNING: Match timed out " "while still in the %s state. This might mean " "your MATCH_TIMEOUT setting (%d) is too small, " "or that there's a problem with how quickly your " "backfill jobs can evict themselves.\n", state_to_string(res_ip->state()), match_timeout ); res_ip->set_destination_state( owner_state ); return; } #endif /* HAVE_BACKFILL */ if( res_ip->state() != matched_state ) { /* This used to be an EXCEPT(), since it really shouldn't ever happen. However, it kept happening, and we couldn't figure out why. For now, just log it and silently ignore it, since there's no real harm done, anyway. We use D_FULLDEBUG, since we don't want people to worry about it if they see it in D_ALWAYS in the 6.2.X stable series. However, in the 6.3 series, we should probably try to figure out what's going on with this, for example, by sending email at this point with the last 300 lines of the log file or something. -Derek 10/9/00 */ dprintf( D_FAILURE|D_FULLDEBUG, "WARNING: Current match timed out but in %s state.\n", state_to_string(res_ip->state()) ); return; } delete res_ip->r_cur; // once we've done this delete, the this pointer is now in // a weird, invalid state. don't rely on using any member // functions or data until we return. res_ip->r_cur = new Claim( res_ip ); res_ip->dprintf( D_FAILURE|D_ALWAYS, "State change: match timed out\n" ); res_ip->change_state( owner_state ); } else { // The match that timed out was the preempting claim. Claim *c = NULL; if( res_ip->r_pre && res_ip->r_pre->idMatches( id() ) ) { c = res_ip->r_pre; } else if( res_ip->r_pre_pre && res_ip->r_pre_pre->idMatches( id() ) ) { c = res_ip->r_pre_pre; } else { EXCEPT("Unexpected timeout of claim id: %s",id()); } // We need to generate a new preempting claim object, // restore our reqexp, and update the CM. res_ip->removeClaim( c ); res_ip->r_reqexp->restore(); res_ip->update(); } return; } void Claim::beginClaim( void ) { ASSERT( c_state == CLAIM_UNCLAIMED ); changeState( CLAIM_IDLE ); startLeaseTimer(); } void Claim::loadAccountingInfo() { // Get a bunch of info out of the request ad that is now // relevant, and store it in this Claim object // See if the classad we got includes an ATTR_USER field, // so we know who to charge for our services. If not, we use // the same user that claimed us. char* tmp = NULL; if( ! c_jobad->LookupString(ATTR_USER, &tmp) ) { if( c_type != CLAIM_COD ) { c_rip->dprintf( D_FULLDEBUG, "WARNING: %s not defined in " "request classad! Using old value (%s)\n", ATTR_USER, c_client->user() ); } } else { c_rip->dprintf( D_FULLDEBUG, "Got RemoteUser (%s) from request classad\n", tmp ); c_client->setuser( tmp ); free( tmp ); tmp = NULL; } // Only stash this if it's in the ad, but don't print anything // if it's not. if( c_jobad->LookupString(ATTR_ACCOUNTING_GROUP, &tmp) ) { c_client->setAccountingGroup( tmp ); free( tmp ); tmp = NULL; } if(!c_client->owner()) { // Only if Owner has never been initialized, load it now. if(c_jobad->LookupString(ATTR_OWNER, &tmp)) { c_client->setowner( tmp ); free( tmp ); tmp = NULL; } } } void Claim::loadRequestInfo() { // Stash the ATTR_CONCURRENCY_LIMITS, necessary to advertise // them if they exist std::string limits; EvalString(ATTR_CONCURRENCY_LIMITS, c_jobad, c_rip->r_classad, limits); if (!limits.empty()) { c_client->setConcurrencyLimits(limits.c_str()); } // stash information about what accounting group match was negotiated under string strval; if (c_jobad->LookupString(ATTR_REMOTE_GROUP, strval)) { c_client->setrmtgrp(strval.c_str()); } if (c_jobad->LookupString(ATTR_REMOTE_NEGOTIATING_GROUP, strval)) { c_client->setneggrp(strval.c_str()); } bool boolval=false; if (c_jobad->LookupBool(ATTR_REMOTE_AUTOREGROUP, boolval)) { c_client->setautorg(boolval); } } void Claim::loadStatistics() { // Stash the ATTR_NUM_PIDS, necessary to advertise // them if they exist if ( c_client ) { int numJobPids = 0; c_jobad->LookupInteger(ATTR_NUM_PIDS, numJobPids); c_client->setNumPids(numJobPids); } } void Claim::beginActivation( double now ) { loadAccountingInfo(); c_activation_count += 1; c_job_start = now; c_pledged_machine_max_vacate_time = 0; if(c_rip->r_classad->LookupExpr(ATTR_MACHINE_MAX_VACATE_TIME)) { if( !EvalInteger( ATTR_MACHINE_MAX_VACATE_TIME, c_rip->r_classad, c_jobad, c_pledged_machine_max_vacate_time)) { dprintf(D_ALWAYS,"Failed to evaluate %s as an integer.\n",ATTR_MACHINE_MAX_VACATE_TIME); c_pledged_machine_max_vacate_time = 0; } } dprintf(D_FULLDEBUG,"pledged MachineMaxVacateTime = %d\n",c_pledged_machine_max_vacate_time); // Everything else is only going to be valid if we're not a // COD job. So, if we *are* cod, just return now, since we've // got everything we need... if( c_type == CLAIM_COD ) { return; } int univ; if( c_jobad->LookupInteger(ATTR_JOB_UNIVERSE, univ) == 0 ) { univ = CONDOR_UNIVERSE_STANDARD; c_rip->dprintf( D_ALWAYS, "Default universe \"%s\" (%d) " "since not in classad\n", CondorUniverseName(univ), univ ); } else { c_rip->dprintf( D_ALWAYS, "Got universe \"%s\" (%d) " "from request classad\n", CondorUniverseName(univ), univ ); } c_universe = univ; bool wantCheckpoint = false; switch( univ ) { case CONDOR_UNIVERSE_VANILLA: c_jobad->LookupBool( ATTR_WANT_CHECKPOINT_SIGNAL, wantCheckpoint ); if( ! wantCheckpoint ) { break; } //@fallthrough@ case CONDOR_UNIVERSE_VM: case CONDOR_UNIVERSE_STANDARD: c_last_pckpt = (int)now; default: break; } c_rip->setAcceptedWhileDraining(); resmgr->adlist_reset_monitors( c_rip->r_id, c_rip->r_classad ); resmgr->startd_stats.total_job_starts += 1; } void Claim::setaliveint( int new_alive ) { c_aliveint = new_alive; // for now, set our lease_duration, too, just so it's // initalized to something reasonable. once we get the job ad // we'll reset it to the real value if it's defined. c_lease_duration = max_claim_alives_missed * new_alive; } void Claim::cacheJobInfo( ClassAd* job ) { job->LookupInteger( ATTR_CLUSTER_ID, c_cluster ); job->LookupInteger( ATTR_PROC_ID, c_proc ); if( c_cluster >= 0 ) { // if the cluster is set and the proc isn't, use 0. if( c_proc < 0 ) { c_proc = 0; } // only print this if the request specified it... c_rip->dprintf( D_ALWAYS, "Remote job ID is %d.%d\n", c_cluster, c_proc ); } job->LookupString( ATTR_GLOBAL_JOB_ID, &c_global_job_id ); if( c_global_job_id ) { // only print this if the request specified it... c_rip->dprintf( D_FULLDEBUG, "Remote global job ID is %s\n", c_global_job_id ); } // check for an explicit job lease duration. if it's not // there, we have to use the old default of 3 * aliveint. :( if( job->LookupInteger(ATTR_JOB_LEASE_DURATION, c_lease_duration) ) { dprintf( D_FULLDEBUG, "%s defined in job ClassAd: %d\n", ATTR_JOB_LEASE_DURATION, c_lease_duration ); dprintf( D_FULLDEBUG, "Resetting ClaimLease timer (%d) with new duration\n", c_lease_tid ); } else if( c_type == CLAIM_OPPORTUNISTIC ) { c_lease_duration = max_claim_alives_missed * c_aliveint; dprintf( D_FULLDEBUG, "%s not defined: using %d (" "alive_interval [%d] * max_missed [%d]\n", ATTR_JOB_LEASE_DURATION, c_lease_duration, c_aliveint, max_claim_alives_missed ); } } #if 0 // no-one uses this void Claim::saveJobInfo( ClassAd* request_ad ) { // This does not make a copy, so we assume we have control // over the ClassAd once this method has been called. // However, don't clobber our ad if the caller passes NULL. if (request_ad) { setjobad(request_ad); } ASSERT(c_ad); cacheJobInfo(c_ad); /* This resets the timers for us, and also, we should consider a request to activate a claim (which is what just happened if we're in this function) as another keep-alive... */ alive(); } #endif void Claim::startLeaseTimer() { if( c_lease_duration < 0 ) { if( c_type == CLAIM_COD ) { // COD claims have no lease by default. return; } dprintf( D_ALWAYS, "Warning: starting ClaimLease timer before " "lease duration set.\n" ); c_lease_duration = 1200; } if( c_lease_tid != -1 ) { EXCEPT( "Claim::startLeaseTimer() called w/ c_lease_tid = %d", c_lease_tid ); } c_lease_tid = daemonCore->Register_Timer( c_lease_duration, 0, (TimerHandlercpp)&Claim::leaseExpired, "Claim::leaseExpired", this ); if( c_lease_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } // Figure out who should sending keep alives // note that the job-ad lookups MUST be here rather than in cacheJobInfo // because the job ad we get from the shadow at activation time doesn't have // the necessary attributes - they are only in the job ad we get from the schedd at claim time // see #6568 for more details. std::string value; param( value, "STARTD_SENDS_ALIVES", "peer" ); if ( c_jobad && c_jobad->LookupBool( ATTR_STARTD_SENDS_ALIVES, c_startd_sends_alives ) ) { // Use value from ad } else if ( strcasecmp( value.c_str(), "false" ) == 0 ) { c_startd_sends_alives = false; } else if ( strcasecmp( value.c_str(), "true" ) == 0 ) { c_startd_sends_alives = true; } else { // No direction from the schedd or config file. c_startd_sends_alives = false; } // If startd is sending the alives, look to see if the schedd is requesting // that we let only send alives when there is no starter present (i.e. when // the claim is idle). c_starter_handles_alives = false; // default to false unless schedd tells us if (c_jobad) { c_jobad->LookupBool( ATTR_STARTER_HANDLES_ALIVES, c_starter_handles_alives ); } if ( c_startd_sends_alives && c_type != CLAIM_COD && c_lease_duration > 0 ) // prevent divide by zero { if ( c_sendalive_tid != -1 ) { daemonCore->Cancel_Timer(c_sendalive_tid); } c_sendalive_tid = daemonCore->Register_Timer( c_lease_duration / 3, c_lease_duration / 3, (TimerHandlercpp)&Claim::sendAlive, "Claim::sendAlive", this ); } dprintf( D_FULLDEBUG, "Started ClaimLease timer (%d) w/ %d second " "lease duration\n", c_lease_tid, c_lease_duration ); } void Claim::cancelLeaseTimer() { int rval; if( c_lease_tid != -1 ) { rval = daemonCore->Cancel_Timer( c_lease_tid ); if( rval < 0 ) { dprintf( D_ALWAYS, "Failed to cancel ClaimLease timer (%d): " "daemonCore error\n", c_lease_tid ); } else { dprintf( D_FULLDEBUG, "Canceled ClaimLease timer (%d)\n", c_lease_tid ); } c_lease_tid = -1; } // Anytime we cancel the lease, we should also cancel // the timer to renew the lease. So do that now. if ( c_sendalive_tid != -1 ) { daemonCore->Cancel_Timer(c_sendalive_tid); c_sendalive_tid = -1; } } void Claim::sendAlive() { const char* c_addr = NULL; if ( c_starter_handles_alives && isActive() ) { // If the starter is dealing with the alive protocol, // then we only need to send alives when claimed/idle. // In this instance, the claim is active and thus // there is a starter... so just push forward the lease // without making any connections. alive(); // this will push forward the lease & alive expiration timer return; } if ( c_client ) { c_addr = c_client->addr(); } if( !c_addr ) { // Client not really set, nothing to do. return; } if ( c_alive_inprogress_sock ) { // already did it return; } DCSchedd matched_schedd ( c_addr, NULL ); Sock* sock = NULL; dprintf( D_PROTOCOL, "Sending alive to schedd %s...\n", c_addr); int connect_timeout = MAX(20, ((c_lease_duration / 3)-3) ); if (!(sock = matched_schedd.reliSock( connect_timeout, 0, NULL, true ))) { dprintf( D_FAILURE|D_ALWAYS, "Alive failed - couldn't initiate connection to %s\n", c_addr ); return; } char to_schedd[256]; snprintf ( to_schedd, 256, "Alive to schedd %s", c_addr ); int reg_rc = daemonCore-> Register_Socket( sock, "<Alive Contact Socket>", (SocketHandlercpp)&Claim::sendAliveConnectHandler, to_schedd, this, ALLOW ); if(reg_rc < 0) { dprintf( D_ALWAYS, "Failed to register socket for alive to schedd at %s. " "Register_Socket returned %d.\n", c_addr,reg_rc); delete sock; return; } c_alive_inprogress_sock = sock; } /* ALIVE_BAILOUT def: before each bad return we reset the alive timer to try again soon, since the heartbeat failed */ #define ALIVE_BAILOUT \ daemonCore->Reset_Timer(c_sendalive_tid, 5, 5 ); \ c_alive_inprogress_sock = NULL; \ return FALSE; int Claim::sendAliveConnectHandler(Stream *s) { const char* c_addr = "(unknown)"; if ( c_client ) { c_addr = c_client->addr(); } char *claimId = id(); if ( !claimId ) { dprintf( D_ALWAYS, "ERROR In Claim::sendAliveConnectHandler, id unknown\n"); ALIVE_BAILOUT; } Sock *sock = (Sock *)s; DCSchedd matched_schedd( c_addr, NULL ); dprintf( D_PROTOCOL, "In Claim::sendAliveConnectHandler id %s\n", publicClaimId()); if (!sock) { dprintf( D_FAILURE|D_ALWAYS, "NULL sock when connecting to schedd %s\n", c_addr ); ALIVE_BAILOUT; // note daemonCore will close sock for us } ASSERT(c_alive_inprogress_sock == sock); if (!sock->is_connected()) { dprintf( D_FAILURE|D_ALWAYS, "Failed to connect to schedd %s\n", c_addr ); ALIVE_BAILOUT; // note daemonCore will close sock for us } // Protocl of sending an alive to the schedd: we send // the claim id, and schedd responds with an int ack. if (!matched_schedd.startCommand(ALIVE, sock, 20, NULL, NULL, false, secSessionId() )) { dprintf( D_FAILURE|D_ALWAYS, "Couldn't send ALIVE to schedd at %s\n", c_addr ); ALIVE_BAILOUT; // note daemonCore will close sock for us } sock->encode(); if ( !sock->put_secret( claimId ) || !sock->end_of_message() ) { dprintf( D_FAILURE|D_ALWAYS, "Failed to send Alive to schedd %s for job %d.%d id %s\n", c_addr, c_cluster, c_proc, publicClaimId() ); ALIVE_BAILOUT; // note daemonCore will close sock for us } daemonCore->Cancel_Socket( sock ); //Allow us to re-register this socket. char to_schedd[256]; snprintf ( to_schedd, 256, "Alive to schedd %s", c_addr ); int reg_rc = daemonCore-> Register_Socket( sock, "<Alive Contact Socket>", (SocketHandlercpp)&Claim::sendAliveResponseHandler, to_schedd, this, ALLOW ); if(reg_rc < 0) { dprintf( D_ALWAYS, "Failed to register socket for alive to schedd at %s. " "Register_Socket returned %d.\n", c_addr,reg_rc); ALIVE_BAILOUT; // note daemonCore will close sock for us } dprintf( D_PROTOCOL, "Leaving Claim::sendAliveConnectHandler success id %s\n",publicClaimId()); // The stream will be closed when we get a callback // in sendAliveResponseHandler. Keep it open for now. c_alive_inprogress_sock = sock; return KEEP_STREAM; } int Claim::sendAliveResponseHandler( Stream *sock ) { int reply; const char* c_addr = "(unknown)"; if ( c_client ) { c_addr = c_client->addr(); } // Now, we set the timeout on the socket to 1 second. Since we // were called by as a Register_Socket callback, this should not // block if things are working as expected. sock->timeout(1); if( !sock->rcv_int(reply, TRUE) ) { dprintf( D_ALWAYS, "Response problem from schedd %s on ALIVE job %d.%d.\n", c_addr, c_cluster, c_proc ); ALIVE_BAILOUT; // note daemonCore will close sock for us } // So here we got a response from the schedd. dprintf(D_PROTOCOL, "Received Alive response of %d from schedd %s job %d.%d\n", reply, c_addr, c_cluster, c_proc); // If the response is -1, that means the schedd knows nothing // about this claim, so relinquish it. if ( reply == -1 ) { dprintf(D_FAILURE|D_ALWAYS,"State change: claim no longer recognized " "by the schedd - removing claim\n" ); c_alive_inprogress_sock = NULL; finishKillClaim(); // get rid of the claim return FALSE; } alive(); // this will push forward the lease & alive expiration timer // and now clear c_alive_inprogress_sock since this alive is done. c_alive_inprogress_sock = NULL; return TRUE; } void Claim::leaseExpired() { cancelLeaseTimer(); // cancel timer(s) in case we are being called directly if( c_type == CLAIM_COD ) { dprintf( D_FAILURE|D_ALWAYS, "COD claim %s lease expired " "(client must not have called 'condor_cod renew' within %d seconds)\n", id(), c_lease_duration ); if( removeClaim(false) ) { // There is no starter, so remove immediately. // Otherwise, we will be removed when starter exits. CODMgr* pCODMgr = getCODMgr(); if (pCODMgr) pCODMgr->removeClaim(this); } return; } dprintf( D_FAILURE|D_ALWAYS, "State change: claim lease expired " "(condor_schedd gone?), evicting claim\n" ); // Kill the claim. finishKillClaim(); return; } int Claim::finishKillClaim() { Resource* res_ip = resmgr->get_by_cur_id( id() ); if( !res_ip ) { EXCEPT( "Can't find resource of expired claim" ); } // Note that this claim either (a) timed out, or (b) is unknown // by the schedd, so we don't try to send a // command to our client. if( c_client ) { delete c_client; c_client = NULL; } // Kill the claim. res_ip->kill_claim(); return TRUE; } void Claim::alive( bool alive_from_schedd ) { dprintf( D_PROTOCOL, "Keep alive for ClaimId %s job %d.%d%s\n", publicClaimId(), c_cluster, c_proc, c_starter_handles_alives && isActive() ? " auto refreshed because starter running" : alive_from_schedd ? ", received from schedd" : " sent to schedd" ); // Process an alive command. This is called whenever we // "heard" from the schedd since a claim was created, // for instance: // 1 - an alive send from the schedd // 2 - an acknowledgement from the schedd to an alive // sent by the startd. // 3 - a claim activation. // 4 - a starter is still running and c_starter_handles_alives==True // First push forward our lease timer. if( c_lease_tid == -1 ) { startLeaseTimer(); } else { daemonCore->Reset_Timer( c_lease_tid, c_lease_duration, 0 ); } // And now push forward our send alives timer. Plus, // it is possible that c_lease_duration changed on activation // of a claim, so our timer reset here will handle that case // as well since alive() is called upon claim activation. // If we got an alive message from the schedd, send our own // alive message soon, since that should cause the schedd to // stop sending them (since we're supposed to be sending them). if ( c_sendalive_tid != -1 ) { if ( alive_from_schedd ) { daemonCore->Reset_Timer(c_sendalive_tid, 10, c_lease_duration / 3); } else { daemonCore->Reset_Timer(c_sendalive_tid, c_lease_duration / 3, c_lease_duration / 3); } } } bool Claim::hasJobAd() { bool has_it = false; if (c_has_job_ad) { has_it = true; } #if HAVE_JOB_HOOKS else if (c_type == CLAIM_FETCH && c_jobad != NULL) { has_it = true; } #endif /* HAVE_JOB_HOOKS */ return has_it; } // Set our ad to the given pointer void Claim::setjobad(ClassAd *cad) { if (c_jobad && (c_jobad != cad)) { delete c_jobad; } c_jobad = cad; } void Claim::setRequestStream(Stream* stream) { if( c_request_stream ) { daemonCore->Cancel_Socket( c_request_stream ); delete( c_request_stream ); } c_request_stream = stream; if( c_request_stream ) { MyString desc; desc.formatstr("request claim %s", publicClaimId() ); int register_rc = daemonCore->Register_Socket( c_request_stream, desc.Value(), (SocketHandlercpp)&Claim::requestClaimSockClosed, "requestClaimSockClosed", this ); if( register_rc < 0 ) { dprintf(D_ALWAYS, "Failed to register claim request socket " " to detect premature closure for claim %s.\n", publicClaimId() ); } } } int Claim::requestClaimSockClosed(Stream *s) { dprintf( D_ALWAYS, "Request claim socket closed prematurely for claim %s. " "This probably means the schedd gave up.\n", publicClaimId() ); ASSERT( s == c_request_stream ); c_request_stream = NULL; // socket will be closed when we return c_rip->removeClaim( this ); return FALSE; } char* Claim::id( void ) { if( c_id ) { return c_id->id(); } else { return NULL; } } char const* Claim::publicClaimId( void ) { if( c_id ) { return c_id->publicClaimId(); } else { return "<unknown>"; } } char const* Claim::secSessionId( void ) { if( c_id ) { return c_id->secSessionId(); } return NULL; } bool Claim::idMatches( const char* req_id ) { if( c_id ) { return c_id->matches( req_id ); } return false; } void Claim::updateUsage(double & percentCpuUsage, long long & imageSize) { percentCpuUsage = 0.0; imageSize = 0; if (c_starter_pid) { Starter *starter = findStarterByPid(c_starter_pid); if ( ! starter) { EXCEPT( "Claim::updateUsage(): Could not find starter object for pid %d", c_starter_pid ); } const ProcFamilyUsage & usage = starter->updateUsage(); percentCpuUsage = usage.percent_cpu; imageSize = usage.total_image_size; } // save off the last values so we can use them in the ::publish method c_cpus_usage = percentCpuUsage / 100; c_image_size = imageSize; } CODMgr* Claim::getCODMgr( void ) { if( ! c_rip ) { return NULL; } return c_rip->r_cod_mgr; } // spawn a starter in the given starter object. // on successful spawn, the claim will take ownership of the job classad. // job can be NULL in the case where we are doing a delayed spawn because of preemption // or when doing fetchwork. when job is NULL, the c_ad member of this class must not be. int Claim::spawnStarter( Starter* starter, ClassAd * job, Stream* s) { if( ! starter ) { // Big error! dprintf( D_ALWAYS, "ERROR! Claim::spawnStarter() called " "w/o a Starter object! Returning failure\n" ); return FALSE; } // the starter had better not already have an active process. ASSERT ( ! starter->pid()); double now = condor_gettimestamp_double(); // grab job id, etc out of the job ad and write it into the claim. if ( ! job) { // refresh cached values from the ad that we already own. // this happends when the spawn of the starter was delayed // because of preemption ASSERT(c_jobad); cacheJobInfo(c_jobad); } else { // this also caches other values from the ad // but does NOT take ownership of the job ad (we do that after we spawn) cacheJobInfo(job); } MyString prefix; formatstr(prefix, "%s[%d.%d]", c_rip->r_id_str, c_cluster, c_proc); starter->set_dprintf_prefix(prefix.c_str()); // HACK!! Starter::spawn reaches back into the claim object to grab values out of the c_ad member // so we have to temporarily set it, even though we have not yet decided to take ownership of the // passed in job (we will only own it if the spawn succeeds) // when job is NULL and c_ad has already been set, then this HACK does nothing. // the code should probably be refactored so that the job ad is an explicit argument to Starter::spawn. ClassAd * old_c_ad = c_jobad; if (job) { c_jobad = job; } c_starter_pid = starter->spawn( this, (time_t)now, s ); c_jobad = old_c_ad; if (c_starter_pid) { if (job) { setjobad(job); } // transfer ownership of the job ad to the claim. alive(); } else { resetClaim(); return FALSE; } changeState( CLAIM_RUNNING ); // Do other bookkeeping so this claim knows it started an activation. beginActivation(now); // WE USED TO.... // // Fake ourselves out so we take another snapshot in 15 // seconds, once the starter has had a chance to spawn the // user job and the job as (hopefully) done any initial // forking it's going to do. If we're planning to check more // often that 15 seconds, anyway, don't bother with this. // // TODO: should we set a timer here to tell the procd // explicitly to take a snapshot in 15 seconds??? return TRUE; } void Claim::starterExited( Starter* starter, int status) { // Now that the starter is gone, we need to change our state changeState( CLAIM_IDLE ); // Notify our starter object that its starter exited, so it // can cancel timers any pending timers, cleanup the starter's // execute directory, and do any other cleanup. // note: null pointer check here is to make coverity happy, not because we think it possible for starter to be null. if (starter) { starter->exited(this, status); delete starter; starter = NULL; } // update stat for JobBusyTime if (c_job_start > 0) { double busyTime = condor_gettimestamp_double() - c_job_start; resmgr->startd_stats.job_busy_time += busyTime; } if( c_badput_caused_by_draining ) { int badput = (int)getJobTotalRunTime() * c_rip->r_attr->num_cpus(); dprintf(D_ALWAYS,"Adding to badput caused by draining: %d cpu-seconds\n",badput); resmgr->addToDrainingBadput( badput ); } // Now, clear out this claim with all the starter-specific // info, including the starter object itself. resetClaim(); // If exit code of starter is 0, it is a normal exit. // If exit code of starter is 1, starter failed to startup // If exit code of starter is 2, it lost connection to the shadow if ( WIFEXITED(status) && WEXITSTATUS(status) == STARTER_EXIT_LOST_SHADOW_CONNECTION ) { // Starter lost connection to shadow, treat it as if the // lease on the slot expired. // We do not just directly call leaseExpired() here, since // that will remove some state in the Resource object that // the call to starterExited() below will want to inspect. // So instead, just set a zero second timer to call leaseExpired(). // This way, starterExited() below gets to do the right thing, including // perhaps giving the resource away to a preempting claim... and // yet if this claim object still exists after starterExited() does its thing, // when the timer goes off we will be sure to destroy this claim and // put the resource back to Unclaimed. See gt#4807. Todd Tannenbaum 1/15 if( c_lease_tid == -1 ) { startLeaseTimer(); } daemonCore->Reset_Timer( c_lease_tid, 0 ); } // Finally, let our resource know that our starter exited, so // it can do the right thing. // This should be done as the last thing in this method; it // is possible that starterExited may destroy this object. c_rip->starterExited( this ); // Think twice about doing anything after returning from starterExited(), // as perhaps this claim object has now been destroyed. } bool Claim::starterPidMatches( pid_t starter_pid ) { if (c_starter_pid && starter_pid == c_starter_pid) { return true; } return false; } bool Claim::isDeactivating( void ) { if( c_state == CLAIM_VACATING || c_state == CLAIM_KILLING ) { return true; } return false; } bool Claim::isActive( void ) { switch( c_state ) { case CLAIM_RUNNING: case CLAIM_SUSPENDED: case CLAIM_VACATING: case CLAIM_KILLING: return true; break; case CLAIM_IDLE: case CLAIM_UNCLAIMED: return false; break; } return false; } bool Claim::isRunning( void ) { switch( c_state ) { case CLAIM_RUNNING: case CLAIM_VACATING: case CLAIM_KILLING: return true; break; case CLAIM_SUSPENDED: case CLAIM_IDLE: case CLAIM_UNCLAIMED: return false; break; } return false; } bool Claim::deactivateClaim( bool graceful ) { if( isActive() ) { if( graceful ) { return starterKillSoft(); } else { return starterKillHard(); } } // not active, so nothing to do return true; } bool Claim::removeClaim( bool graceful ) { if( isActive() ) { c_wants_remove = true; if( graceful ) { starterKillSoft(); } else { starterKillHard(); } dprintf( D_FULLDEBUG, "Removing active claim %s " "(waiting for starter pid %d to exit)\n", id(), c_starter_pid); return false; } dprintf( D_FULLDEBUG, "Removing inactive claim %s\n", id() ); return true; } bool Claim::suspendClaim( void ) { changeState( CLAIM_SUSPENDED ); Starter* starter = findStarterByPid(c_starter_pid); if (starter) { return (bool)starter->suspend(); } // if there's no starter, we don't need to do anything, so // it worked... return true; } bool Claim::resumeClaim( void ) { Starter* starter = findStarterByPid(c_starter_pid); if (starter) { changeState( CLAIM_RUNNING ); return starter->resume(); } // if there's no starter, we don't need to do anything, so // it worked... changeState( CLAIM_IDLE ); return true; } bool Claim::starterKill( int sig ) { // don't need to work about the state, since we don't use this // method to send any signals that change the claim state... Starter* starter = findStarterByPid(c_starter_pid); if (starter) { return starter->kill( sig ); } // if there's no starter, we don't need to kill anything, so // it worked... return true; } bool Claim::starterKillPg( int sig ) { Starter* starter = findStarterByPid(c_starter_pid); if (starter) { // if we're using KillPg, we're trying to hard-kill the // starter and all its children changeState( CLAIM_KILLING ); return starter->killpg( sig ); } // if there's no starter, we don't need to kill anything, so // it worked... return true; } bool Claim::starterKillSoft( bool state_change ) { Starter* starter = findStarterByPid(c_starter_pid); if (starter) { changeState( CLAIM_VACATING ); int timeout = c_rip ? c_rip->evalMaxVacateTime() : 0; return starter->killSoft( timeout, state_change ); } // if there's no starter, we don't need to kill anything, so // it worked... return true; } bool Claim::starterKillHard( void ) { Starter* starter = findStarterByPid(c_starter_pid); if (starter) { changeState( CLAIM_KILLING ); int timeout = (universe() == CONDOR_UNIVERSE_VM) ? vm_killing_timeout : killing_timeout; return starter->killHard(timeout); } // if there's no starter, we don't need to kill anything, so // it worked... return true; } void Claim::starterHoldJob( char const *hold_reason,int hold_code,int hold_subcode,bool soft ) { Starter* starter = findStarterByPid(c_starter_pid); if (starter) { int timeout; if (soft) { timeout = c_rip ? c_rip->evalMaxVacateTime() : 0; } else { timeout = (universe() == CONDOR_UNIVERSE_VM) ? vm_killing_timeout : killing_timeout; } if( starter->holdJob(hold_reason,hold_code,hold_subcode,soft,timeout) ) { return; } dprintf(D_ALWAYS,"Starter unable to hold job, so evicting job instead.\n"); } if( soft ) { starterKillSoft(); } else { starterKillHard(); } } void Claim::makeStarterArgs( ArgList &args ) { switch (c_type) { case CLAIM_COD: makeCODStarterArgs(args); break; #if HAVE_JOB_HOOKS case CLAIM_FETCH: makeFetchStarterArgs(args); break; #endif /* HAVE_JOB_HOOKS */ default: EXCEPT("Impossible: makeStarterArgs() called with unsupported claim type"); } } #if HAVE_JOB_HOOKS void Claim::makeFetchStarterArgs( ArgList &args ) { args.AppendArg("condor_starter"); args.AppendArg("-f"); if ( resmgr->is_smp() ) { args.AppendArg("-a"); args.AppendArg(rip()->r_id_str); } args.AppendArg("-job-input-ad"); args.AppendArg("-"); } #endif /* HAVE_JOB_HOOKS */ void Claim::makeCODStarterArgs( ArgList &args ) { // first deal with everthing that's shared, no matter what. args.AppendArg("condor_starter"); args.AppendArg("-f"); args.AppendArg("-append"); args.AppendArg("cod"); args.AppendArg("-header"); MyString cod_id_arg; cod_id_arg += "("; if( resmgr->is_smp() ) { cod_id_arg += c_rip->r_id_str; cod_id_arg += ':'; } cod_id_arg += codId(); cod_id_arg += ")"; args.AppendArg(cod_id_arg.Value()); // if we've got a cluster and proc for the job, append those if( c_cluster >= 0 ) { args.AppendArg("-job-cluster"); args.AppendArg(c_cluster); } if( c_proc >= 0 ) { args.AppendArg("-job-proc"); args.AppendArg(c_proc); } // finally, specify how the job should get its ClassAd if( c_cod_keyword ) { args.AppendArg("-job-keyword"); args.AppendArg(c_cod_keyword); } if( c_has_job_ad ) { args.AppendArg("-job-input-ad"); args.AppendArg("-"); } } bool Claim::verifyCODAttrs( ClassAd* req ) { if( c_cod_keyword ) { EXCEPT( "Trying to activate a COD claim that has a keyword" ); } req->LookupString( ATTR_JOB_KEYWORD, &c_cod_keyword ); req->LookupBool( ATTR_HAS_JOB_AD, c_has_job_ad ); if( c_cod_keyword || c_has_job_ad ) { return true; } return false; } bool Claim::publishStarterAd(ClassAd *cad) { Starter * starter = NULL; if (c_starter_pid) { starter = findStarterByPid(c_starter_pid); } if ( ! starter) { return false; } char const* ip_addr = starter->getIpAddr(); if (ip_addr) { cad->Assign(ATTR_STARTER_IP_ADDR, ip_addr); } // stuff in starter-specific attributes, if we have them. StringList ability_list; starter->publish(cad, A_STATIC | A_PUBLIC, &ability_list); char* ability_str = ability_list.print_to_string(); if (ability_str) { cad->Assign(ATTR_STARTER_ABILITY_LIST, ability_str); free(ability_str); } // TODO add more goodness to this ClassAd?? return true; } bool Claim::periodicCheckpoint( void ) { Starter * starter = findStarterByPid(c_starter_pid); if (starter) { if( ! starter->kill(DC_SIGPCKPT) ) { return false; } } c_last_pckpt = (int)time(NULL); return true; } bool Claim::ownerMatches( const char* owner ) { if( ! strcmp(c_client->owner(), owner) ) { return true; } // TODO: handle COD_SUPER_USERS return false; } bool Claim::globalJobIdMatches( const char* req_id ) { if( c_global_job_id && !strcmp(c_global_job_id, req_id) ) { return true; } return false; } bool Claim::setPendingCmd( int cmd ) { // TODO: we might want to check what our currently pending // command is and do something special... c_pending_cmd = cmd; // also, keep track of what state we were in when we got this // request, since we might want that in the reply classad. c_last_state = c_state; return true; } int Claim::finishPendingCmd( void ) { switch( c_pending_cmd ) { case -1: return FALSE; break; case CA_RELEASE_CLAIM: return finishReleaseCmd(); break; case CA_DEACTIVATE_CLAIM: return finishDeactivateCmd(); break; default: EXCEPT( "Claim::finishPendingCmd called with unknown cmd: %s (%d)", getCommandString(c_pending_cmd), c_pending_cmd ); break; } return TRUE; } int Claim::finishReleaseCmd( void ) { ClassAd reply; int rval; reply.Assign(ATTR_RESULT, getCAResultString(CA_SUCCESS)); reply.Assign(ATTR_LAST_CLAIM_STATE, getClaimStateString(c_last_state)); // TODO: hopefully we can put the final job update ad in here, // too. rval = sendCAReply( c_request_stream, "CA_RELEASE_CLAIM", &reply ); // now that we're done replying, we need to delete this stream // so we don't leak memory, since DaemonCore's not going to do // that for us in this case setRequestStream(NULL); c_pending_cmd = -1; dprintf( D_ALWAYS, "Finished releasing claim %s (owner: '%s')\n", id(), client()->owner() ); c_rip->removeClaim( this ); // THIS OBJECT IS NOW DELETED, WE CAN *ONLY* RETURN NOW!!! return rval; } int Claim::finishDeactivateCmd( void ) { ClassAd reply; int rval; reply.Assign(ATTR_RESULT, getCAResultString(CA_SUCCESS)); reply.Assign(ATTR_LAST_CLAIM_STATE, getClaimStateString(c_last_state)); // TODO: hopefully we can put the final job update ad in here, // too. rval = sendCAReply( c_request_stream, "CA_DEACTIVATE_CLAIM", &reply ); // now that we're done replying, we need to delete this stream // so we don't leak memory, since DaemonCore's not going to do // that for us in this case setRequestStream(NULL); c_pending_cmd = -1; dprintf( D_ALWAYS, "Finished deactivating claim %s (owner: '%s')\n", id(), client()->owner() ); // also, we must reset all the attributes we're storing in // this Claim object that are specific to a given activation. resetClaim(); return rval; } void Claim::resetClaim( void ) { c_starter_pid = 0; c_image_size = 0; c_cpus_usage = 0; if( c_jobad && c_type == CLAIM_COD ) { delete( c_jobad ); c_jobad = NULL; } c_universe = -1; c_cluster = -1; c_proc = -1; c_job_start = -1; c_last_pckpt = -1; if( c_global_job_id ) { free( c_global_job_id ); c_global_job_id = NULL; } if( c_cod_keyword ) { free( c_cod_keyword ); c_cod_keyword = NULL; } c_has_job_ad = false; c_job_total_run_time = 0; c_job_total_suspend_time = 0; c_may_unretire = true; c_preempt_was_true = false; c_badput_caused_by_draining = false; } void Claim::changeState( ClaimState s ) { if( c_state == s ) { return; } time_t now = time(NULL); if( c_state == CLAIM_RUNNING || c_state == CLAIM_SUSPENDED ) { // the state we're leaving is one of the ones we're // keeping track of total times for, so we've got to // update some things. time_t time_dif = now - c_entered_state; if( c_state == CLAIM_RUNNING ) { c_job_total_run_time += time_dif; c_claim_total_run_time += time_dif; } if( c_state == CLAIM_SUSPENDED ) { c_job_total_suspend_time += time_dif; c_claim_total_suspend_time += time_dif; } } if( c_state == CLAIM_UNCLAIMED && c_claim_started == 0 ) { c_claim_started = time(NULL); } // now that all the appropriate time values are updated, we // can actually do the deed. c_state = s; c_entered_state = now; // everytime a COD claim changes state, we want to update the // collector. if( c_type == CLAIM_COD ) { c_rip->update(); } } time_t Claim::getClaimAge() { time_t now = time(NULL); if(c_claim_started) { return now - c_claim_started; } return 0; } bool Claim::writeJobAd( int pipe_end ) { // pipe_end is a DaemonCore pipe, so we must use // DC::Write_Pipe for writing to it MyString ad_str; sPrintAd(ad_str, *c_jobad); const char* ptr = ad_str.Value(); int len = ad_str.Length(); while (len) { int bytes_written = daemonCore->Write_Pipe(pipe_end, ptr, len); if (bytes_written == -1) { dprintf(D_ALWAYS, "writeJobAd: Write_Pipe failed\n"); return false; } ptr += bytes_written; len -= bytes_written; } return true; } bool Claim::writeMachAd( Stream* stream ) { if (IsDebugLevel(D_MACHINE)) { std::string adbuf; dprintf(D_MACHINE, "Sending Machine Ad to Starter :\n%s", formatAd(adbuf, *c_rip->r_classad, "\t")); } else { dprintf(D_FULLDEBUG, "Sending Machine Ad to Starter\n"); } if (!putClassAd(stream, *c_rip->r_classad) || !stream->end_of_message()) { dprintf(D_ALWAYS, "writeMachAd: Failed to write machine ClassAd to stream\n"); return false; } return true; } /////////////////////////////////////////////////////////////////////////// // Client /////////////////////////////////////////////////////////////////////////// Client::Client() { c_user = NULL; c_owner = NULL; c_acctgrp = NULL; c_addr = NULL; c_host = NULL; c_proxyfile = NULL; c_concurrencyLimits = NULL; c_rmtgrp = NULL; c_neggrp = NULL; c_autorg = false; c_numPids = 0; } Client::~Client() { if( c_user) free( c_user ); if( c_owner) free( c_owner ); if( c_acctgrp) free( c_acctgrp ); if( c_addr) free( c_addr ); if( c_host) free( c_host ); if (c_rmtgrp) free(c_rmtgrp); if (c_neggrp) free(c_neggrp); if (c_concurrencyLimits) free(c_concurrencyLimits); } void Client::setuser( const char* updated_user ) { if( c_user ) { free( c_user); } if( updated_user ) { c_user = strdup( updated_user ); } else { c_user = NULL; } } void Client::setowner( const char* updated_owner ) { if( c_owner ) { free( c_owner); } if( updated_owner ) { c_owner = strdup( updated_owner ); } else { c_owner = NULL; } } void Client::setAccountingGroup( const char* grp ) { if( c_acctgrp ) { free( c_acctgrp); } if( grp ) { c_acctgrp = strdup( grp ); } else { c_acctgrp = NULL; } } void Client::setrmtgrp(const char* rmtgrp_) { if (c_rmtgrp) { free(c_rmtgrp); c_rmtgrp = NULL; } if (rmtgrp_) c_rmtgrp = strdup(rmtgrp_); } void Client::setneggrp(const char* neggrp_) { if (c_neggrp) { free(c_neggrp); c_neggrp = NULL; } if (neggrp_) c_neggrp = strdup(neggrp_); } void Client::setautorg(const bool autorg_) { c_autorg = autorg_; } void Client::setaddr( const char* updated_addr ) { if( c_addr ) { free( c_addr); } if( updated_addr ) { c_addr = strdup( updated_addr ); } else { c_addr = NULL; } } void Client::sethost( const char* updated_host ) { if( c_host ) { free( c_host); } if( updated_host ) { c_host = strdup( updated_host ); } else { c_host = NULL; } } void Client::setProxyFile( const char* pf ) { if( c_proxyfile ) { free( c_proxyfile ); } if ( pf ) { c_proxyfile = strdup( pf ); } else { c_proxyfile = NULL; } } void Client::setConcurrencyLimits( const char* limits ) { if( c_concurrencyLimits ) { free( c_concurrencyLimits ); } if ( limits ) { c_concurrencyLimits = strdup( limits ); } else { c_concurrencyLimits = NULL; } } void Client::setNumPids( int numJobPids ) { c_numPids = numJobPids; } void Client::vacate(char* id) { ReliSock* sock; if( ! (c_addr || c_host || c_owner ) ) { // Client not really set, nothing to do. return; } dprintf(D_FULLDEBUG, "Entered vacate_client %s %s...\n", c_addr, c_host); ClaimIdParser cid(id); Daemon my_schedd( DT_SCHEDD, c_addr, NULL); sock = (ReliSock*)my_schedd.startCommand( RELEASE_CLAIM, Stream::reli_sock, 20, NULL, NULL, false, cid.secSessionId()); if( ! sock ) { dprintf(D_FAILURE|D_ALWAYS, "Can't connect to schedd (%s)\n", c_addr); return; } if( !sock->put_secret( id ) ) { dprintf(D_ALWAYS, "Can't send ClaimId to client\n"); } else if( !sock->end_of_message() ) { dprintf(D_ALWAYS, "Can't send EOM to client\n"); } sock->close(); delete sock; } /////////////////////////////////////////////////////////////////////////// // ClaimId /////////////////////////////////////////////////////////////////////////// static int newIdString( char** id_str_ptr ) { // ClaimId string is of the form: // (keep this in sync with condor_claimid_parser) // "<ip:port>#startd_bday#sequence_num#cookie" static int sequence_num = 0; sequence_num++; MyString id; // Keeping with tradition, we insert the startd's address in // the claim id. As of condor 7.2, nothing relies on this. // Starting in 8.9, we use the full sinful string, which can // contain '#'. Parsers should look for the first '>' in the // string to reliably extract the startd's sinful. formatstr( id, "%s#%d#%d#", daemonCore->publicNetworkIpAddr(), (int)startd_startup, sequence_num ); // keylen is 20 in order to avoid generating claim ids that // overflow the 80 byte buffer in pre-7.1.3 negotiators // Note: Claim id strings have been longer than 80 characters // ever since we started putting a security session ad in them. const size_t keylen = 20; char *keybuf = Condor_Crypt_Base::randomHexKey(keylen); id += keybuf; free( keybuf ); *id_str_ptr = strdup( id.Value() ); return sequence_num; } ClaimId::ClaimId( ClaimType claim_type, char const * /*slotname*/ /*UNUSED*/ ) { int num = newIdString( &c_id ); claimid_parser.setClaimId(c_id); if( claim_type == CLAIM_COD ) { char buf[64]; snprintf( buf, 64, "COD%d", num ); buf[COUNTOF(buf)-1] = 0; // snprintf doesn't necessarly null terminate. c_cod_id = strdup( buf ); } else { c_cod_id = NULL; } if( claim_type == CLAIM_OPPORTUNISTIC && param_boolean("SEC_ENABLE_MATCH_PASSWORD_AUTHENTICATION",false) ) { MyString session_id; MyString session_key; MyString session_info; // there is no sec session info yet in the claim id, so // we call secSessionId with ignore_session_info=true to // force it to give us the session id session_id = claimid_parser.secSessionId(/*ignore_session_info=*/true); session_key = claimid_parser.secSessionKey(); bool rc = daemonCore->getSecMan()->CreateNonNegotiatedSecuritySession( DAEMON, session_id.Value(), session_key.Value(), NULL, SUBMIT_SIDE_MATCHSESSION_FQU, NULL, 0, nullptr ); if( !rc ) { dprintf(D_ALWAYS, "SEC_ENABLE_MATCH_PASSWORD_AUTHENTICATION: failed to create " "security session for claim id %s\n", session_id.Value()); } else { // fill in session_info so that schedd will have // enough info to create a pre-built security session // compatible with the one we just created. rc = daemonCore->getSecMan()->ExportSecSessionInfo( session_id.Value(), session_info ); if( !rc ) { dprintf(D_ALWAYS, "SEC_ENABLE_MATCH_PASSWORD_AUTHENTICATION: failed to get " "session info for claim id %s\n",session_id.Value()); } else { claimid_parser.setSecSessionInfo( session_info.Value() ); free( c_id ); c_id = strdup(claimid_parser.claimId()); // after rewriting session info, verify that session id // and session key are the same that we used when we // created the session ASSERT( session_id == claimid_parser.secSessionId() ); ASSERT( session_key == claimid_parser.secSessionKey() ); ASSERT( session_info == claimid_parser.secSessionInfo() ); } } } } ClaimId::~ClaimId() { if( claimid_parser.secSessionId() ) { // Expire the session after enough time to let the final // RELEASE_CLAIM command finish, in case it is still in // progress. This also allows us to more gracefully // handle any final communication from the schedd that may // still be in flight. daemonCore->getSecMan()->SetSessionExpiration(claimid_parser.secSessionId(),time(NULL)+600); } free( c_id ); if( c_cod_id ) { free( c_cod_id ); } } bool ClaimId::matches( const char* req_id ) { if( !req_id ) { return false; } return( strcmp(c_id, req_id) == 0 ); } void ClaimId::dropFile( int slot_id ) { if( ! param_boolean("STARTD_SHOULD_WRITE_CLAIM_ID_FILE", true) ) { return; } char* filename = startdClaimIdFile( slot_id ); if( ! filename ) { dprintf( D_ALWAYS, "Error getting claim id filename, not writing\n" ); return; } MyString filename_final = filename; MyString filename_tmp = filename; free( filename ); filename = NULL; filename_tmp += ".new"; FILE* NEW_FILE = safe_fopen_wrapper_follow( filename_tmp.Value(), "w", 0600 ); if( ! NEW_FILE ) { dprintf( D_ALWAYS, "ERROR: can't open claim id file: %s: %s (errno: %d)\n", filename_tmp.Value(), strerror(errno), errno ); return; } fprintf( NEW_FILE, "%s\n", c_id ); fclose( NEW_FILE ); if( rotate_file(filename_tmp.Value(), filename_final.Value()) < 0 ) { dprintf( D_ALWAYS, "ERROR: failed to move %s into place, removing\n", filename_tmp.Value() ); if (unlink(filename_tmp.Value()) < 0) { dprintf( D_ALWAYS, "ERROR: failed to remove %s\n", filename_tmp.Value() ); } } } void Claim::receiveJobClassAdUpdate( ClassAd &update_ad, bool final_update ) { ASSERT( c_jobad ); const char *name; ExprTree *expr; for ( auto itr = update_ad.begin(); itr != update_ad.end(); itr++ ) { name = itr->first.c_str(); expr = itr->second; ASSERT( name ); if( !strcmp(name,ATTR_MY_TYPE) || !strcmp(name,ATTR_TARGET_TYPE) ) { // ignore MyType and TargetType continue; } // replace expression in current ad with expression from update ad ExprTree *new_expr = expr->Copy(); ASSERT( new_expr ); if ( ! c_jobad->Insert(name, new_expr)) { delete new_expr; } } loadStatistics(); if( IsDebugVerbose(D_JOB) ) { std::string adbuf; dprintf(D_JOB | D_VERBOSE,"Updated job ClassAd:\n%s", formatAd(adbuf, *c_jobad, "\t")); } if (final_update) { double duration = 0.0; if ( ! c_jobad->LookupFloat(ATTR_JOB_DURATION, duration)) { duration = 0.0; } resmgr->startd_stats.job_duration += duration; } } bool Claim::waitingForActivation() { time_t maxDrainingActivationDelay = param_integer( "MAX_DRAINING_ACTIVATION_DELAY", 20 ); return getClaimAge() < maxDrainingActivationDelay; } void Claim::invalidateID() { delete c_id; c_id = new ClaimId( type(), c_rip->r_id_str ); }
25.340795
174
0.668829
krowenrao
bae4f8a8b44e2debe1febe913da4b3938bdbddb4
298
cpp
C++
Necromancer/Logger.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
Necromancer/Logger.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
Necromancer/Logger.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Logger.h" #include "Necromancer.h" namespace Necromancer{ Logger::~Logger(){ } void Log(const String& str){ Necromancer* nec = Necromancer::get_instance(); Logger* logger = nec->logger(); logger->Log(str); } void Logger::Log(const String& str){ } }
13.545455
49
0.661074
myffx36
bae5513a3ea4821dee9cc3868b850df7efa848d8
13,007
cpp
C++
sdk/physx/2.8.3/Samples/SampleTerrain/src/NxSampleTerrain.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
1
2018-09-20T10:01:30.000Z
2018-09-20T10:01:30.000Z
sdk/physx/2.8.3/Samples/SampleTerrain/src/NxSampleTerrain.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
sdk/physx/2.8.3/Samples/SampleTerrain/src/NxSampleTerrain.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
// =============================================================================== // // NVIDIA PhysX SDK Sample Program // // Title: Terrain Sample // Description: This sample program builds a terrain and shows some of the debug // information that you can receive from the SDK. // // =============================================================================== #include <stdio.h> #include <GL/glut.h> // Physics code #undef random #include "NxPhysics.h" #include "UserAllocator.h" #include "Terrain.h" #include "TerrainRender.h" #include "Stream.h" #include "ErrorStream.h" #include "cooking.h" #include "Utilities.h" #include "SamplesVRDSettings.h" #ifdef __PPCGEKKO__ #include "GLFontRenderer.h" #endif static ErrorStream gMyErrorStream; static UserAllocator* gMyAllocator = NULL; static bool gPause = false; static NxPhysicsSDK* gPhysicsSDK = NULL; static NxScene* gScene = NULL; static NxVec3 gDefaultGravity(0.0f, -9.81f, 0.0f); #define TERRAIN_SIZE 33 #define TERRAIN_CHAOS 300.0f #define TERRAIN_OFFSET -20.0f #define TERRAIN_WIDTH 20.0f static TerrainData* gTerrainData = NULL; // Render code static NxVec3 Eye(50.0f, 50.0f, 50.0f); static NxVec3 Dir(-0.6,-0.2,-0.7); static NxVec3 N; static int mx = 0; static int my = 0; static NxArray<NxU32> gTouchedTris; static NxActor* gTerrain = NULL; static NxTriangleMesh* terrainMesh = NULL; class MyContactReport : public NxUserContactReport { public: virtual void onContactNotify(NxContactPair& pair, NxU32 events) { // Iterate through contact points NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here if(i.getSeparation()<0.0f) { const NxVec3& contactPoint = i.getPoint(); NxU32 faceIndex = i.getFeatureIndex0(); if(faceIndex==0xffffffff) faceIndex = i.getFeatureIndex1(); if(faceIndex!=0xffffffff) { gTouchedTris.pushBack(faceIndex); } } } } } } }gMyContactReport; static void CreatePhysicsTerrain() { if(gTerrainData!=NULL) { delete gTerrainData; gTerrainData=NULL; } gTerrainData = new TerrainData; gTerrainData->init(TERRAIN_SIZE, TERRAIN_OFFSET, TERRAIN_WIDTH, TERRAIN_CHAOS); // Build physical model NxTriangleMeshDesc terrainDesc; terrainDesc.numVertices = gTerrainData->nbVerts; terrainDesc.numTriangles = gTerrainData->nbFaces; terrainDesc.pointStrideBytes = sizeof(NxVec3); terrainDesc.triangleStrideBytes = 3*sizeof(NxU32); terrainDesc.points = gTerrainData->verts; terrainDesc.triangles = gTerrainData->faces; terrainDesc.flags = 0; terrainDesc.heightFieldVerticalAxis = NX_Y; terrainDesc.heightFieldVerticalExtent = -1000.0f; bool status = InitCooking(gMyAllocator, &gMyErrorStream); if (!status) { printf("Unable to initialize the cooking library. Please make sure that you have correctly installed the latest version of the NVIDIA PhysX SDK."); exit(1); } MemoryWriteBuffer buf; status = CookTriangleMesh(terrainDesc, buf); if (!status) { printf("Unable to cook a triangle mesh."); exit(1); } MemoryReadBuffer readBuffer(buf.data); terrainMesh = gPhysicsSDK->createTriangleMesh(readBuffer); // // Please note about the created Triangle Mesh, user needs to release it when no one uses it to save memory. It can be detected // by API "meshData->getReferenceCount() == 0". And, the release API is "gPhysicsSDK->releaseTriangleMesh(*meshData);" // NxTriangleMeshShapeDesc terrainShapeDesc; terrainShapeDesc.meshData = terrainMesh; terrainShapeDesc.shapeFlags = NX_SF_FEATURE_INDICES; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&terrainShapeDesc); gTerrain = gScene->createActor(ActorDesc); gTerrain->userData = (void*)0; CloseCooking(); } static void RenderTerrain() { if(gTerrainData) { #if _XBOX renderTerrain(*gTerrainData); renderTerrainTriangles(*gTerrainData, gTouchedTris.size(), &gTouchedTris[0]); #else renderTerrainTriangles(*gTerrainData, gTouchedTris.size(), &gTouchedTris[0]); renderTerrain(*gTerrainData); #endif } } static void CreateCube(const NxVec3& pos, int size=2, const NxVec3* initial_velocity=NULL) { // Create body NxBodyDesc BodyDesc; BodyDesc.angularDamping = 0.5f; if(initial_velocity) BodyDesc.linearVelocity = *initial_velocity; NxBoxShapeDesc BoxDesc; BoxDesc.dimensions = NxVec3(float(size), float(size), float(size)); NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&BoxDesc); ActorDesc.body = &BodyDesc; ActorDesc.density = 10.0f; ActorDesc.globalPose.t = pos; NxActor* newActor = gScene->createActor(ActorDesc); newActor->userData = (void*)size; gScene->setActorPairFlags(*gTerrain, *newActor, NX_NOTIFY_ON_TOUCH); } static void CreateStack(int size) { float CubeSize = 2.0f; float Spacing = 0.0001f; NxVec3 Pos(0.0f, CubeSize, 0.0f); float Offset = -size * (CubeSize * 2.0f + Spacing) * 0.5f; while(size) { for(int i=0;i<size;i++) { Pos.x = Offset + float(i) * (CubeSize * 2.0f + Spacing); CreateCube(Pos, (int)CubeSize); } Offset += CubeSize; Pos.y += (CubeSize * 2.0f + Spacing); size--; } } static void CreateTower(int size) { float CubeSize = 2.0f; float Spacing = 0.01f; NxVec3 Pos(0.0f, CubeSize, 0.0f); while(size) { CreateCube(Pos, (int)CubeSize); Pos.y += (CubeSize * 2.0f + Spacing); size--; } } static bool InitNx() { if (!gMyAllocator) gMyAllocator = new UserAllocator(); // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gMyAllocator, &gMyErrorStream, desc, &errorCode); if(gPhysicsSDK == NULL) { printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode)); return false; } #if SAMPLES_USE_VRD // The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK); #endif gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.userContactReport = &gMyContactReport; gScene = gPhysicsSDK->createScene(sceneDesc); if(gScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } NxMaterial * defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); CreatePhysicsTerrain(); return true; } static void ExitCallback() { #ifdef __PPCGEKKO__ gTouchedTris.clear(); gTouchedTris.~NxArray<NxU32>(); #endif if(gTerrainData!=NULL) { delete gTerrainData; gTerrainData=NULL; } if(gPhysicsSDK != NULL) { if(gScene != NULL) gPhysicsSDK->releaseScene(*gScene); gScene = NULL; NxReleasePhysicsSDK(gPhysicsSDK); gPhysicsSDK = NULL; } if(gMyAllocator!=NULL) { delete gMyAllocator; gMyAllocator=NULL; } } static void ResetScene() { if(gPhysicsSDK != NULL) { if(gScene != NULL) gPhysicsSDK->releaseScene(*gScene); gScene = NULL; #ifdef RESET_SDK NxReleasePhysicsSDK(gPhysicsSDK); gPhysicsSDK = NULL; #endif } ExitCallback(); if (!InitNx()) exit(0); } static void KeyboardCallback(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; case 'r': case 'R': ResetScene(); break; case ' ': CreateCube(NxVec3(0.0f, 20.0f, 0.0f), 1+(rand()&3)); break; case 's': case 'S': CreateStack(10); break; case 'b': case 'B': CreateStack(30); break; case 't': case 'T': CreateTower(30); break; case 'p': case 'P': gPause = !gPause; break; case 101: case '8': Eye += Dir * 2.0f; break; case 103: case '2': Eye -= Dir * 2.0f; break; case 100: case '4': Eye -= N * 2.0f; break; case 102: case '6': Eye += N * 2.0f; break; case 'w': case 'W': { NxVec3 t = Eye; NxVec3 Vel = Dir; Vel.normalize(); Vel*=200.0f; CreateCube(t, 8, &Vel); } break; } } static void ArrowKeyCallback(int key, int x, int y) { KeyboardCallback(key,x,y); } static void MouseCallback(int button, int state, int x, int y) { mx = x; my = y; } static void MotionCallback(int x, int y) { int dx = mx - x; int dy = my - y; Dir.normalize(); N.cross(Dir,NxVec3(0,1,0)); NxQuat qx(NxPiF32 * dx * 20/ 180.0f, NxVec3(0,1,0)); qx.rotate(Dir); NxQuat qy(NxPiF32 * dy * 20/ 180.0f, N); qy.rotate(Dir); mx = x; my = y; } static void RenderCallback() { if(gScene == NULL) return; // Physics code if(!gPause) { gTouchedTris.clear(); gScene->simulate(1.0f/60.0f); //Note: a real application would compute and pass the elapsed time here. gScene->flushStream(); gScene->fetchResults(NX_RIGID_BODY_FINISHED, true); } // ~Physics code // Clear buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup camera glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 10000.0f); gluLookAt(Eye.x, Eye.y, Eye.z, Eye.x + Dir.x, Eye.y + Dir.y, Eye.z + Dir.z, 0.0f, 1.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Keep physics & graphics in sync glColor4f(1.0f, 1.0f, 1.0f, 1.0f); { int nbActors = gScene->getNbActors(); NxActor** actors = gScene->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(!int(actor->userData)) continue; glPushMatrix(); float glmat[16]; actor->getGlobalPose().getColumnMajor44(glmat); glMultMatrixf(glmat); glutSolidCube(float(int(actor->userData))*2.0f); glPopMatrix(); } } RenderTerrain(); #ifdef __PPCGEKKO__ char buf[256]; sprintf(buf,"FPS: %d\nRender time:%d ms \nPhysic time:%d ms \nTotal time:%d ms\n" "Use the arrow keys to move the camera.\n" "Press the keys b,HOME,1 and 2 to create various things.\n" "Press a to reset the scene.\n"); GLFontRenderer::setScreenResolution(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); GLFontRenderer::setColor(0.9f, 1.0f, 0.0f, 1.0f); GLFontRenderer::print(0.01, 0.9, 0.036, buf, false, 11, true); #endif glutSwapBuffers(); } static void ReshapeCallback(int width, int height) { glViewport(0, 0, width, height); } static void IdleCallback() { glutPostRedisplay(); } int main(int argc, char** argv) { #ifdef __PPCGEKKO__ printf("Use the arrow keys to move the camera.\n"); printf("Press the keys b,HOME,1 and 2 to create various things.\n"); printf("Press a to reset the scene.\n"); #else printf("Use the arrow keys or 2, 4, 6 and 8 to move the camera.\n"); printf("Use the mouse to rotate the camera.\n"); printf("Press p to pause the simulation.\n"); printf("Press the keys w,space,s,b, and t to create various things.\n"); printf("Press r to reset the scene.\n"); #endif // Initialize Glut glutInit(&argc, argv); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); int mainHandle = glutCreateWindow("SampleTerrain"); glutSetWindow(mainHandle); glutDisplayFunc(RenderCallback); glutReshapeFunc(ReshapeCallback); glutIdleFunc(IdleCallback); glutKeyboardFunc(KeyboardCallback); glutSpecialFunc(ArrowKeyCallback); glutMouseFunc(MouseCallback); glutMotionFunc(MotionCallback); MotionCallback(0,0); atexit(ExitCallback); #ifdef __PPCGEKKO__ glutRemapButtonExt('a','r'); glutRemapButtonExt('b','w'); glutRemapButtonExt('1','s'); glutRemapButtonExt('2','b'); glutRemapButtonExt(GLUT_KEY_HOME,'t'); glutRemapButtonExt(GLUT_KEY_UP,101); glutRemapButtonExt(GLUT_KEY_DOWN,103); glutRemapButtonExt(GLUT_KEY_LEFT,100); glutRemapButtonExt(GLUT_KEY_RIGHT,102); #endif // Setup default render states glClearColor(0.3f, 0.4f, 0.5f, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); #ifndef __PPCGEKKO__ glEnable(GL_CULL_FACE); #endif // Setup lighting glEnable(GL_LIGHTING); float AmbientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor); float DiffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor); float SpecularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor); float Position[] = { -10.0f, 100.0f, -4.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, Position); glEnable(GL_LIGHT0); // Initialize physics scene and start the application main loop if scene was created if (InitNx()) glutMainLoop(); return 0; }
25.158607
149
0.700238
daher-alfawares
bae7ae1c11b6c787b7a287606c0a567b6e22e14c
22,959
cpp
C++
PVSNES/PVSNES/SNES/SNESCore/fxdbg.cpp
DaddyCal/Provenance
cda9464b4bef6dd48f9977047c4af90aca80c5a7
[ "BSD-3-Clause" ]
2
2015-10-03T18:38:58.000Z
2022-03-02T17:05:42.000Z
PVSNES/PVSNES/SNES/SNESCore/fxdbg.cpp
DaddyCal/Provenance
cda9464b4bef6dd48f9977047c4af90aca80c5a7
[ "BSD-3-Clause" ]
2
2015-05-13T10:06:29.000Z
2016-04-18T12:09:59.000Z
PVSNES/PVSNES/SNES/SNESCore/fxdbg.cpp
DaddyCal/Provenance
cda9464b4bef6dd48f9977047c4af90aca80c5a7
[ "BSD-3-Clause" ]
null
null
null
/*********************************************************************************** Snes9x - Portable Super Nintendo Entertainment System (TM) emulator. (c) Copyright 1996 - 2002 Gary Henderson (gary.henderson@ntlworld.com), Jerremy Koot (jkoot@snes9x.com) (c) Copyright 2002 - 2004 Matthew Kendora (c) Copyright 2002 - 2005 Peter Bortas (peter@bortas.org) (c) Copyright 2004 - 2005 Joel Yliluoma (http://iki.fi/bisqwit/) (c) Copyright 2001 - 2006 John Weidman (jweidman@slip.net) (c) Copyright 2002 - 2006 funkyass (funkyass@spam.shaw.ca), Kris Bleakley (codeviolation@hotmail.com) (c) Copyright 2002 - 2010 Brad Jorsch (anomie@users.sourceforge.net), Nach (n-a-c-h@users.sourceforge.net), (c) Copyright 2002 - 2011 zones (kasumitokoduck@yahoo.com) (c) Copyright 2006 - 2007 nitsuja (c) Copyright 2009 - 2011 BearOso, OV2 BS-X C emulator code (c) Copyright 2005 - 2006 Dreamer Nom, zones C4 x86 assembler and some C emulation code (c) Copyright 2000 - 2003 _Demo_ (_demo_@zsnes.com), Nach, zsKnight (zsknight@zsnes.com) C4 C++ code (c) Copyright 2003 - 2006 Brad Jorsch, Nach DSP-1 emulator code (c) Copyright 1998 - 2006 _Demo_, Andreas Naive (andreasnaive@gmail.com), Gary Henderson, Ivar (ivar@snes9x.com), John Weidman, Kris Bleakley, Matthew Kendora, Nach, neviksti (neviksti@hotmail.com) DSP-2 emulator code (c) Copyright 2003 John Weidman, Kris Bleakley, Lord Nightmare (lord_nightmare@users.sourceforge.net), Matthew Kendora, neviksti DSP-3 emulator code (c) Copyright 2003 - 2006 John Weidman, Kris Bleakley, Lancer, z80 gaiden DSP-4 emulator code (c) Copyright 2004 - 2006 Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden OBC1 emulator code (c) Copyright 2001 - 2004 zsKnight, pagefault (pagefault@zsnes.com), Kris Bleakley Ported from x86 assembler to C by sanmaiwashi SPC7110 and RTC C++ emulator code used in 1.39-1.51 (c) Copyright 2002 Matthew Kendora with research by zsKnight, John Weidman, Dark Force SPC7110 and RTC C++ emulator code used in 1.52+ (c) Copyright 2009 byuu, neviksti S-DD1 C emulator code (c) Copyright 2003 Brad Jorsch with research by Andreas Naive, John Weidman S-RTC C emulator code (c) Copyright 2001 - 2006 byuu, John Weidman ST010 C++ emulator code (c) Copyright 2003 Feather, John Weidman, Kris Bleakley, Matthew Kendora Super FX x86 assembler emulator code (c) Copyright 1998 - 2003 _Demo_, pagefault, zsKnight Super FX C emulator code (c) Copyright 1997 - 1999 Ivar, Gary Henderson, John Weidman Sound emulator code used in 1.5-1.51 (c) Copyright 1998 - 2003 Brad Martin (c) Copyright 1998 - 2006 Charles Bilyue' Sound emulator code used in 1.52+ (c) Copyright 2004 - 2007 Shay Green (gblargg@gmail.com) SH assembler code partly based on x86 assembler code (c) Copyright 2002 - 2004 Marcus Comstedt (marcus@mc.pp.se) 2xSaI filter (c) Copyright 1999 - 2001 Derek Liauw Kie Fa HQ2x, HQ3x, HQ4x filters (c) Copyright 2003 Maxim Stepin (maxim@hiend3d.com) NTSC filter (c) Copyright 2006 - 2007 Shay Green GTK+ GUI code (c) Copyright 2004 - 2011 BearOso Win32 GUI code (c) Copyright 2003 - 2006 blip, funkyass, Matthew Kendora, Nach, nitsuja (c) Copyright 2009 - 2011 OV2 Mac OS GUI code (c) Copyright 1998 - 2001 John Stiles (c) Copyright 2001 - 2011 zones Specific ports contains the works of other authors. See headers in individual files. Snes9x homepage: http://www.snes9x.com/ Permission to use, copy, modify and/or distribute Snes9x in both binary and source form, for non-commercial purposes, is hereby granted without fee, providing that this license information and copyright notice appear with all copies and any derived work. This software is provided 'as-is', without any express or implied warranty. In no event shall the authors be held liable for any damages arising from the use of this software or it's derivatives. Snes9x is freeware for PERSONAL USE only. Commercial users should seek permission of the copyright holders first. Commercial use includes, but is not limited to, charging money for Snes9x or software derived from Snes9x, including Snes9x or derivatives in commercial game bundles, and/or using Snes9x as a promotion for your commercial product. The copyright holders request that bug fixes and improvements to the code should be forwarded to them so everyone can benefit from the modifications in future versions. Super NES and Super Nintendo Entertainment System are trademarks of Nintendo Co., Limited and its subsidiary companies. ***********************************************************************************/ #ifdef DEBUGGER #include "snes9x.h" #include "fxinst.h" #include "fxemu.h" /* When printing a line from the pipe, it could look like this: 01:8006 f4 fb 86 iwt r4, #$86fb The values are: program bank : 01 adress : 8006 values at memory address 8006 : f4 fb 86 instruction in the pipe : iwt r4, #$86fb Note! If the instruction has more than one byte (like in 'iwt') and the instruction is in a delay slot, the second and third byte displayed will not be the same as those used. Since the instrction is in a delay slot, the first byte of the instruction will be taken from the pipe at the address after the branch instruction, and the next one or two bytes will be taken from the address that the branch points to. This is a bit complicated, but I've taken this into account, in this debug function. (See the diffrence of how the values vPipe1 and vPipe2 are read, compared to the values vByte1 and vByte2) */ /* static const char *fx_apvMnemonicTable[] = { // ALT0 Table // 00 - 0f "stop", "nop", "cache", "lsr", "rol", "bra $%04x", "blt $%04x", "bge $%04x", "bne $%04x", "beq $%04x", "bpl $%04x", "bmi $%04x", "bcc $%04x", "bcs $%04x", "bvc $%04x", "bvs $%04x", // 10 - 1f "to r0", "to r1", "to r2", "to r3", "to r4", "to r5", "to r6", "to r7", "to r8", "to r9", "to r10", "to r11", "to r12", "to r13", "to r14", "to r15", // 20 - 2f "with r0", "with r1", "with r2", "with r3", "with r4", "with r5", "with r6", "with r7", "with r8", "with r9", "with r10", "with r11", "with r12", "with r13", "with r14", "with r15", // 30 - 3f "stw (r0)", "stw (r1)", "stw (r2)", "stw (r3)", "stw (r4)", "stw (r5)", "stw (r6)", "stw (r7)", "stw (r8)", "stw (r9)", "stw (r10)", "stw (r11)", "loop", "alt1", "alt2", "alt3", // 40 - 4f "ldw (r0)", "ldw (r1)", "ldw (r2)", "ldw (r3)", "ldw (r4)", "ldw (r5)", "ldw (r6)", "ldw (r7)", "ldw (r8)", "ldw (r9)", "ldw (r10)", "ldw (r11)", "plot", "swap", "color", "not", // 50 - 5f "add r0", "add r1", "add r2", "add r3", "add r4", "add r5", "add r6", "add r7", "add r8", "add r9", "add r10", "add r11", "add r12", "add r13", "add r14", "add r15", // 60 - 6f "sub r0", "sub r1", "sub r2", "sub r3", "sub r4", "sub r5", "sub r6", "sub r7", "sub r8", "sub r9", "sub r10", "sub r11", "sub r12", "sub r13", "sub r14", "sub r15", // 70 - 7f "merge", "and r1", "and r2", "and r3", "and r4", "and r5", "and r6", "and r7", "and r8", "and r9", "and r10", "and r11", "and r12", "and r13", "and r14", "and r15", // 80 - 8f "mult r0", "mult r1", "mult r2", "mult r3", "mult r4", "mult r5", "mult r6", "mult r7", "mult r8", "mult r9", "mult r10", "mult r11", "mult r12", "mult r13", "mult r14", "mult r15", // 90 - 9f "sbk", "link #1", "link #2", "link #3", "link #4", "sex", "asr", "ror", "jmp (r8)", "jmp (r9)", "jmp (r10)", "jmp (r11)", "jmp (r12)", "jmp (r13)", "lob", "fmult", // a0 - af "ibt r0, #$%02x", "ibt r1, #$%02x", "ibt r2, #$%02x", "ibt r3, #$%02x", "ibt r4, #$%02x", "ibt r5, #$%02x", "ibt r6, #$%02x", "ibt r7, #$%02x", "ibt r8, #$%02x", "ibt r9, #$%02x", "ibt r10, #$%02x", "ibt r11, #$%02x", "ibt r12, #$%02x", "ibt r13, #$%02x", "ibt r14, #$%02x", "ibt r15, #$%02x", // b0 - bf "from r0", "from r1", "from r2", "from r3", "from r4", "from r5", "from r6", "from r7", "from r8", "from r9", "from r10", "from r11", "from r12", "from r13", "from r14", "from r15", // c0 - cf "hib", "or r1", "or r2", "or r3", "or r4", "or r5", "or r6", "or r7", "or r8", "or r9", "or r10", "or r11", "or r12", "or r13", "or r14", "or r15", // d0 - df "inc r0", "inc r1", "inc r2", "inc r3", "inc r4", "inc r5", "inc r6", "inc r7", "inc r8", "inc r9", "inc r10", "inc r11", "inc r12", "inc r13", "inc r14", "getc", // e0 - ef "dec r0", "dec r1", "dec r2", "dec r3", "dec r4", "dec r5", "dec r6", "dec r7", "dec r8", "dec r9", "dec r10", "dec r11", "dec r12", "dec r13", "dec r14", "getb", // f0 - ff "iwt r0, #$%04x", "iwt r1, #$%04x", "iwt r2, #$%04x", "iwt r3, #$%04x", "iwt r4, #$%04x", "iwt r5, #$%04x", "iwt r6, #$%04x", "iwt r7, #$%04x", "iwt r8, #$%04x", "iwt r9, #$%04x", "iwt r10, #$%04x", "iwt r11, #$%04x", "iwt r12, #$%04x", "iwt r13, #$%04x", "iwt r14, #$%04x", "iwt r15, #$%04x", // ALT1 Table // 00 - 0f "stop", "nop", "cache", "lsr", "rol", "bra $%04x", "blt $%04x", "bge $%04x", "bne $%04x", "beq $%04x", "bpl $%04x", "bmi $%04x", "bcc $%04x", "bcs $%04x", "bvc $%04x", "bvs $%04x", // 10 - 1f "to r0", "to r1", "to r2", "to r3", "to r4", "to r5", "to r6", "to r7", "to r8", "to r9", "to r10", "to r11", "to r12", "to r13", "to r14", "to r15", // 20 - 2f "with r0", "with r1", "with r2", "with r3", "with r4", "with r5", "with r6", "with r7", "with r8", "with r9", "with r10", "with r11", "with r12", "with r13", "with r14", "with r15", // 30 - 3f "stb (r0)", "stb (r1)", "stb (r2)", "stb (r3)", "stb (r4)", "stb (r5)", "stb (r6)", "stb (r7)", "stb (r8)", "stb (r9)", "stb (r10)", "stb (r11)", "loop", "alt1", "alt2", "alt3", // 40 - 4f "ldb (r0)", "ldb (r1)", "ldb (r2)", "ldb (r3)", "ldb (r4)", "ldb (r5)", "ldb (r6)", "ldb (r7)", "ldb (r8)", "ldb (r9)", "ldb (r10)", "ldb (r11)", "rpix", "swap", "cmode", "not", // 50 - 5f "adc r0", "adc r1", "adc r2", "adc r3", "adc r4", "adc r5", "adc r6", "adc r7", "adc r8", "adc r9", "adc r10", "adc r11", "adc r12", "adc r13", "adc r14", "adc r15", // 60 - 6f "sbc r0", "sbc r1", "sbc r2", "sbc r3", "sbc r4", "sbc r5", "sbc r6", "sbc r7", "sbc r8", "sbc r9", "sbc r10", "sbc r11", "sbc r12", "sbc r13", "sbc r14", "sbc r15", // 70 - 7f "merge", "bic r1", "bic r2", "bic r3", "bic r4", "bic r5", "bic r6", "bic r7", "bic r8", "bic r9", "bic r10", "bic r11", "bic r12", "bic r13", "bic r14", "bic r15", // 80 - 8f "umult r0", "umult r1", "umult r2", "umult r3", "umult r4", "umult r5", "umult r6", "umult r7", "umult r8", "umult r9", "umult r10", "umult r11", "umult r12", "umult r13", "umult r14", "umult r15", // 90 - 9f "sbk", "link #1", "link #2", "link #3", "link #4", "sex", "div2", "ror", "ljmp (r8)", "ljmp (r9)", "ljmp (r10)", "ljmp (r11)", "ljmp (r12)", "ljmp (r13)", "lob", "lmult", // a0 - af "lms r0, ($%04x)", "lms r1, ($%04x)", "lms r2, ($%04x)", "lms r3, ($%04x)", "lms r4, ($%04x)", "lms r5, ($%04x)", "lms r6, ($%04x)", "lms r7, ($%04x)", "lms r8, ($%04x)", "lms r9, ($%04x)", "lms r10, ($%04x)", "lms r11, ($%04x)", "lms r12, ($%04x)", "lms r13, ($%04x)", "lms r14, ($%04x)", "lms r15, ($%04x)", // b0 - bf "from r0", "from r1", "from r2", "from r3", "from r4", "from r5", "from r6", "from r7", "from r8", "from r9", "from r10", "from r11", "from r12", "from r13", "from r14", "from r15", // c0 - cf "hib", "xor r1", "xor r2", "xor r3", "xor r4", "xor r5", "xor r6", "xor r7", "xor r8", "xor r9", "xor r10", "xor r11", "xor r12", "xor r13", "xor r14", "xor r15", // d0 - df "inc r0", "inc r1", "inc r2", "inc r3", "inc r4", "inc r5", "inc r6", "inc r7", "inc r8", "inc r9", "inc r10", "inc r11", "inc r12", "inc r13", "inc r14", "getc", // e0 - ef "dec r0", "dec r1", "dec r2", "dec r3", "dec r4", "dec r5", "dec r6", "dec r7", "dec r8", "dec r9", "dec r10", "dec r11", "dec r12", "dec r13", "dec r14", "getbh", // f0 - ff "lm r0, ($%04x)", "lm r1, ($%04x)", "lm r2, ($%04x)", "lm r3, ($%04x)", "lm r4, ($%04x)", "lm r5, ($%04x)", "lm r6, ($%04x)", "lm r7, ($%04x)", "lm r8, ($%04x)", "lm r9, ($%04x)", "lm r10, ($%04x)", "lm r11, ($%04x)", "lm r12, ($%04x)", "lm r13, ($%04x)", "lm r14, ($%04x)", "lm r15, ($%04x)", // ALT2 Table // 00 - 0f "stop", "nop", "cache", "lsr", "rol", "bra $%04x", "blt $%04x", "bge $%04x", "bne $%04x", "beq $%04x", "bpl $%04x", "bmi $%04x", "bcc $%04x", "bcs $%04x", "bvc $%04x", "bvs $%04x", // 10 - 1f "to r0", "to r1", "to r2", "to r3", "to r4", "to r5", "to r6", "to r7", "to r8", "to r9", "to r10", "to r11", "to r12", "to r13", "to r14", "to r15", // 20 - 2f "with r0", "with r1", "with r2", "with r3", "with r4", "with r5", "with r6", "with r7", "with r8", "with r9", "with r10", "with r11", "with r12", "with r13", "with r14", "with r15", // 30 - 3f "stw (r0)", "stw (r1)", "stw (r2)", "stw (r3)", "stw (r4)", "stw (r5)", "stw (r6)", "stw (r7)", "stw (r8)", "stw (r9)", "stw (r10)", "stw (r11)", "loop", "alt1", "alt2", "alt3", // 40 - 4f "ldw (r0)", "ldw (r1)", "ldw (r2)", "ldw (r3)", "ldw (r4)", "ldw (r5)", "ldw (r6)", "ldw (r7)", "ldw (r8)", "ldw (r9)", "ldw (r10)", "ldw (r11)", "plot", "swap", "color", "not", // 50 - 5f "add #0", "add #1", "add #2", "add #3", "add #4", "add #5", "add #6", "add #7", "add #8", "add #9", "add #10", "add #11", "add #12", "add #13", "add #14", "add #15", // 60 - 6f "sub #0", "sub #1", "sub #2", "sub #3", "sub #4", "sub #5", "sub #6", "sub #7", "sub #8", "sub #9", "sub #10", "sub #11", "sub #12", "sub #13", "sub #14", "sub #15", // 70 - 7f "merge", "and #1", "and #2", "and #3", "and #4", "and #5", "and #6", "and #7", "and #8", "and #9", "and #10", "and #11", "and #12", "and #13", "and #14", "and #15", // 80 - 8f "mult #0", "mult #1", "mult #2", "mult #3", "mult #4", "mult #5", "mult #6", "mult #7", "mult #8", "mult #9", "mult #10", "mult #11", "mult #12", "mult #13", "mult #14", "mult #15", // 90 - 9f "sbk", "link #1", "link #2", "link #3", "link #4", "sex", "asr", "ror", "jmp (r8)", "jmp (r9)", "jmp (r10)", "jmp (r11)", "jmp (r12)", "jmp (r13)", "lob", "fmult", // a0 - af "sms ($%04x), r0", "sms ($%04x), r1", "sms ($%04x), r2", "sms ($%04x), r3", "sms ($%04x), r4", "sms ($%04x), r5", "sms ($%04x), r6", "sms ($%04x), r7", "sms ($%04x), r8", "sms ($%04x), r9", "sms ($%04x), r10", "sms ($%04x), r11", "sms ($%04x), r12", "sms ($%04x), r13", "sms ($%04x), r14", "sms ($%04x), r15", // b0 - bf "from r0", "from r1", "from r2", "from r3", "from r4", "from r5", "from r6", "from r7", "from r8", "from r9", "from r10", "from r11", "from r12", "from r13", "from r14", "from r15", // c0 - cf "hib", "or #1", "or #2", "or #3", "or #4", "or #5", "or #6", "or #7", "or #8", "or #9", "or #10", "or #11", "or #12", "or #13", "or #14", "or #15", // d0 - df "inc r0", "inc r1", "inc r2", "inc r3", "inc r4", "inc r5", "inc r6", "inc r7", "inc r8", "inc r9", "inc r10", "inc r11", "inc r12", "inc r13", "inc r14", "ramb", // e0 - ef "dec r0", "dec r1", "dec r2", "dec r3", "dec r4", "dec r5", "dec r6", "dec r7", "dec r8", "dec r9", "dec r10", "dec r11", "dec r12", "dec r13", "dec r14", "getbl", // f0 - ff "sm ($%04x), r0", "sm ($%04x), r1", "sm ($%04x), r2", "sm ($%04x), r3", "sm ($%04x), r4", "sm ($%04x), r5", "sm ($%04x), r6", "sm ($%04x), r7", "sm ($%04x), r8", "sm ($%04x), r9", "sm ($%04x), r10", "sm ($%04x), r11", "sm ($%04x), r12", "sm ($%04x), r13", "sm ($%04x), r14", "sm ($%04x), r15", // ALT3 Table // 00 - 0f "stop", "nop", "cache", "lsr", "rol", "bra $%04x", "blt $%04x", "bge $%04x", "bne $%04x", "beq $%04x", "bpl $%04x", "bmi $%04x", "bcc $%04x", "bcs $%04x", "bvc $%04x", "bvs $%04x", // 10 - 1f "to r0", "to r1", "to r2", "to r3", "to r4", "to r5", "to r6", "to r7", "to r8", "to r9", "to r10", "to r11", "to r12", "to r13", "to r14", "to r15", // 20 - 2f "with r0", "with r1", "with r2", "with r3", "with r4", "with r5", "with r6", "with r7", "with r8", "with r9", "with r10", "with r11", "with r12", "with r13", "with r14", "with r15", // 30 - 3f "stb (r0)", "stb (r1)", "stb (r2)", "stb (r3)", "stb (r4)", "stb (r5)", "stb (r6)", "stb (r7)", "stb (r8)", "stb (r9)", "stb (r10)", "stb (r11)", "loop", "alt1", "alt2", "alt3", // 40 - 4f "ldb (r0)", "ldb (r1)", "ldb (r2)", "ldb (r3)", "ldb (r4)", "ldb (r5)", "ldb (r6)", "ldb (r7)", "ldb (r8)", "ldb (r9)", "ldb (r10)", "ldb (r11)", "rpix", "swap", "cmode", "not", // 50 - 5f "adc #0", "adc #1", "adc #2", "adc #3", "adc #4", "adc #5", "adc #6", "adc #7", "adc #8", "adc #9", "adc #10", "adc #11", "adc #12", "adc #13", "adc #14", "adc #15", // 60 - 6f "cmp r0", "cmp r1", "cmp r2", "cmp r3", "cmp r4", "cmp r5", "cmp r6", "cmp r7", "cmp r8", "cmp r9", "cmp r10", "cmp r11", "cmp r12", "cmp r13", "cmp r14", "cmp r15", // 70 - 7f "merge", "bic #1", "bic #2", "bic #3", "bic #4", "bic #5", "bic #6", "bic #7", "bic #8", "bic #9", "bic #10", "bic #11", "bic #12", "bic #13", "bic #14", "bic #15", // 80 - 8f "umult #0", "umult #1", "umult #2", "umult #3", "umult #4", "umult #5", "umult #6", "umult #7", "umult #8", "umult #9", "umult #10", "umult #11", "umult #12", "umult #13", "umult #14", "umult #15", // 90 - 9f "sbk", "link #1", "link #2", "link #3", "link #4", "sex", "div2", "ror", "ljmp (r8)", "ljmp (r9)", "ljmp (r10)", "ljmp (r11)", "ljmp (r12)", "ljmp (r13)", "lob", "lmult", // a0 - af "lms r0, ($%04x)", "lms r1, ($%04x)", "lms r2, ($%04x)", "lms r3, ($%04x)", "lms r4, ($%04x)", "lms r5, ($%04x)", "lms r6, ($%04x)", "lms r7, ($%04x)", "lms r8, ($%04x)", "lms r9, ($%04x)", "lms r10, ($%04x)", "lms r11, ($%04x)", "lms r12, ($%04x)", "lms r13, ($%04x)", "lms r14, ($%04x)", "lms r15, ($%04x)", // b0 - bf "from r0", "from r1", "from r2", "from r3", "from r4", "from r5", "from r6", "from r7", "from r8", "from r9", "from r10", "from r11", "from r12", "from r13", "from r14", "from r15", // c0 - cf "hib", "xor #1", "xor #2", "xor #3", "xor #4", "xor #5", "xor #6", "xor #7", "xor #8", "xor #9", "xor #10", "xor #11", "xor #12", "xor #13", "xor #14", "xor #15", // d0 - df "inc r0", "inc r1", "inc r2", "inc r3", "inc r4", "inc r5", "inc r6", "inc r7", "inc r8", "inc r9", "inc r10", "inc r11", "inc r12", "inc r13", "inc r14", "romb", // e0 - ef "dec r0", "dec r1", "dec r2", "dec r3", "dec r4", "dec r5", "dec r6", "dec r7", "dec r8", "dec r9", "dec r10", "dec r11", "dec r12", "dec r13", "dec r14", "getbs", // f0 - ff "lm r0, ($%04x)", "lm r1, ($%04x)", "lm r2, ($%04x)", "lm r3, ($%04x)", "lm r4, ($%04x)", "lm r5, ($%04x)", "lm r6, ($%04x)", "lm r7, ($%04x)", "lm r8, ($%04x)", "lm r9, ($%04x)", "lm r10, ($%04x)", "lm r11, ($%04x)", "lm r12, ($%04x)", "lm r13, ($%04x)", "lm r14, ($%04x)", "lm r15, ($%04x)" }; */ /* static void FxPipeString (char *pvString) { uint32 vOpcode = (GSU.vStatusReg & 0x300) | ((uint32) PIPE); const char *m = fx_apvMnemonicTable[vOpcode]; uint8 vPipe1, vPipe2, vByte1, vByte2; uint8 vPipeBank = GSU.vPipeAdr >> 16; char *p; // The next two bytes after the pipe's address vPipe1 = GSU.apvRomBank[vPipeBank][USEX16(GSU.vPipeAdr + 1)]; vPipe2 = GSU.apvRomBank[vPipeBank][USEX16(GSU.vPipeAdr + 2)]; // The actual next two bytes to be read vByte1 = PRGBANK(USEX16(R15)); vByte2 = PRGBANK(USEX16(R15 + 1)); // Print ROM address of the pipe sprintf(pvString, "%02x:%04x %02x ", USEX8(vPipeBank), USEX16(GSU.vPipeAdr), USEX8(PIPE)); p = &pvString[strlen(pvString)]; if (PIPE >= 0x05 && PIPE <= 0x0f) // Check if it's a branch instruction { sprintf(&pvString[11], "%02x ", USEX8(vPipe1)); #ifdef BRANCH_DELAY_RELATIVE sprintf(p, m, USEX16(R15 + SEX8(vByte1) + 1)); #else sprintf(p, m, USEX16(R15 + SEX8(vByte1) - 1)); #endif } else if (PIPE >= 0x10 && PIPE <= 0x1f && TF(B)) // Check for 'move' instruction sprintf(p, "move r%d, r%d", USEX8(PIPE & 0x0f), (uint32) (GSU.pvSreg - GSU.avReg)); else if (PIPE >= 0xa0 && PIPE <= 0xaf) // Check for 'ibt', 'lms' or 'sms' { sprintf(&pvString[11], "%02x ", USEX8(vPipe1)); if ((GSU.vStatusReg & 0x300) == 0x100 || (GSU.vStatusReg & 0x300) == 0x200) sprintf(p, m, USEX16(vByte1) << 1); else sprintf(p, m, USEX16(vByte1)); } else if (PIPE >= 0xb0 && PIPE <= 0xbf && TF(B)) // Check for 'moves' sprintf(p, "moves r%d, r%d", (uint32) (GSU.pvDreg - GSU.avReg), USEX8(PIPE & 0x0f)); else if (PIPE >= 0xf0) // Check for 'iwt', 'lm' or 'sm' { sprintf(&pvString[11], "%02x %02x ", USEX8(vPipe1), USEX8(vPipe2)); sprintf(p, m, USEX8(vByte1) | (USEX16(vByte2) << 8)); } else // Normal instruction strcpy(p, m); } */ #endif
16.088998
108
0.490135
DaddyCal
bae827acd8db57d0f8481d75cda715e43792dc3d
6,351
cpp
C++
hphp/compiler/expression/modifier_expression.cpp
radford/hhvm
a7cd6754d14742b40528c847b607a1608cfcfe98
[ "PHP-3.01", "Zend-2.0" ]
1
2015-02-12T07:24:28.000Z
2015-02-12T07:24:28.000Z
hphp/compiler/expression/modifier_expression.cpp
radford/hhvm
a7cd6754d14742b40528c847b607a1608cfcfe98
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/compiler/expression/modifier_expression.cpp
radford/hhvm
a7cd6754d14742b40528c847b607a1608cfcfe98
[ "PHP-3.01", "Zend-2.0" ]
1
2015-06-16T05:47:12.000Z
2015-06-16T05:47:12.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/compiler/expression/modifier_expression.h" #include "hphp/parser/hphp.tab.hpp" using namespace HPHP; /////////////////////////////////////////////////////////////////////////////// // constructors/destructors ModifierExpression::ModifierExpression (EXPRESSION_CONSTRUCTOR_PARAMETERS) : Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ModifierExpression)), m_hasPrivacy(true) { } ExpressionPtr ModifierExpression::clone() { ModifierExpressionPtr exp(new ModifierExpression(*this)); Expression::deepCopy(exp); return exp; } /////////////////////////////////////////////////////////////////////////////// // parser functions void ModifierExpression::add(int modifier) { m_modifiers.push_back(modifier); } void ModifierExpression::remove(int modifier) { m_modifiers.erase( std::remove(m_modifiers.begin(), m_modifiers.end(), modifier), m_modifiers.end()); } int ModifierExpression::operator[](int index) { assert(index >= 0 && index < getCount()); return m_modifiers[index]; } bool ModifierExpression::isPublic() const { if (!m_hasPrivacy) { return false; } for (unsigned int i = 0; i < m_modifiers.size(); i++) { switch (m_modifiers[i]) { case T_PUBLIC: return true; case T_PROTECTED: case T_PRIVATE: return false; default: break; } } return true; } bool ModifierExpression::hasModifier(int modifier) const { for (unsigned int i = 0; i < m_modifiers.size(); i++) { if (m_modifiers[i] == modifier) { return true; } } return false; } bool ModifierExpression::hasDuplicates() const { std::set<int> seen; for (unsigned int i = 0; i < m_modifiers.size(); i++) { if (seen.find(m_modifiers[i]) != seen.end()) { return true; } seen.insert(m_modifiers[i]); } return false; } bool ModifierExpression::isExplicitlyPublic() const { return hasModifier(T_PUBLIC); } bool ModifierExpression::isProtected() const { return hasModifier(T_PROTECTED); } bool ModifierExpression::isPrivate() const { return hasModifier(T_PRIVATE); } bool ModifierExpression::isStatic() const { return hasModifier(T_STATIC); } bool ModifierExpression::isAbstract() const { return hasModifier(T_ABSTRACT); } bool ModifierExpression::isFinal() const { return hasModifier(T_FINAL); } bool ModifierExpression::isAsync() const { return hasModifier(T_ASYNC); } bool ModifierExpression::validForFunction() const { for (auto i = m_modifiers.begin(); i != m_modifiers.end(); ++i) { if (*i != T_ASYNC) { return false; } } return true; } bool ModifierExpression::validForClosure() const { for (auto i = m_modifiers.begin(); i != m_modifiers.end(); ++i) { if (*i != T_ASYNC && *i != T_STATIC) { return false; } } return true; } /** * In the context of a trait alias rule, only method access and visibility * modifiers are allowed */ bool ModifierExpression::validForTraitAliasRule() const { for (auto const& mod: m_modifiers) { if (mod != T_PUBLIC && mod != T_PRIVATE && mod != T_PROTECTED && mod != T_FINAL) { return false; } } return true; } /////////////////////////////////////////////////////////////////////////////// // static analysis functions void ModifierExpression::analyzeProgram(AnalysisResultPtr ar) { // do nothing } /////////////////////////////////////////////////////////////////////////////// void ModifierExpression::outputCodeModel(CodeGenerator &cg) { cg.printf("V:9:\"HH\\Vector\":%d:{", (int)m_modifiers.size()); for (unsigned int i = 0; i < m_modifiers.size(); i++) { cg.printObjectHeader("Modifier", 1); cg.printPropertyHeader("name"); switch (m_modifiers[i]) { case T_PUBLIC: cg.printValue("public"); break; case T_PROTECTED: cg.printValue("protected"); break; case T_PRIVATE: cg.printValue("private"); break; case T_STATIC: cg.printValue("static"); break; case T_ABSTRACT: cg.printValue("abstract"); break; case T_FINAL: cg.printValue("final"); break; case T_ASYNC: cg.printValue("async"); break; default: assert(false); } cg.printObjectFooter(); } cg.printf("}"); } /////////////////////////////////////////////////////////////////////////////// // code generation functions void ModifierExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) { if (m_hasPrivacy) { if (m_modifiers.empty()) { cg_printf("public "); return; } bool printed = false; for (unsigned int i = 0; i < m_modifiers.size(); i++) { switch (m_modifiers[i]) { case T_PUBLIC: cg_printf("public "); printed = true; break; case T_PROTECTED: cg_printf("protected "); printed = true; break; case T_PRIVATE: cg_printf("private "); printed = true; break; } } if (!printed) { cg_printf("public "); } } for (unsigned int i = 0; i < m_modifiers.size(); i++) { switch (m_modifiers[i]) { case T_PUBLIC: break; case T_PROTECTED: break; case T_PRIVATE: break; case T_STATIC: cg_printf("static "); break; case T_ABSTRACT: cg_printf("abstract "); break; case T_FINAL: cg_printf("final "); break; case T_ASYNC: cg_printf("async "); break; default: assert(false); } } }
28.737557
79
0.568414
radford
baeca18c4b053d28c486e82663baac829ceca969
1,838
cpp
C++
C++/082_Remove_Duplicates_From_Sorted_Lists_II.cpp
stephenkid/LeetCode-Sol
8cb429652e0741ca4078b6de5f9eeaddcb8607a8
[ "MIT" ]
1,958
2015-01-30T01:19:03.000Z
2022-03-17T03:34:47.000Z
src/main/cpp/082_Remove_Duplicates_From_Sorted_Lists_II.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
135
2016-03-03T04:53:10.000Z
2022-03-03T21:14:37.000Z
src/main/cpp/082_Remove_Duplicates_From_Sorted_Lists_II.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
914
2015-01-27T22:27:22.000Z
2022-03-05T04:25:10.000Z
// 82 Remove Duplicates from Sorted List II /** * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. * * For example, * Given 1->2->3->3->4->4->5, return 1->2->5. * Given 1->1->1->2->3, return 2->3. * * Tag: Linked List * * Author: Yanbin Lu */ #include <stddef.h> #include <vector> #include <string.h> #include <stdio.h> #include <algorithm> #include <iostream> #include <map> #include <queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { // check empty or single node list if(!head || !head->next) return head; // if the first element is not a duplicate, recursive start from the next one if(head->val != head->next->val){ head->next = deleteDuplicates(head->next); return head; } // if the first element is duplicate, go along untill a different value else{ int val = head->val; ListNode* node = head; while(node && node->val == val) node = node->next; return deleteDuplicates(node); } } }; int main() { // creat a duplicate list ListNode* list = new ListNode(0); list->next = new ListNode(0); list->next->next = new ListNode(1); list->next->next->next = new ListNode(1); list->next->next->next->next = new ListNode(2); list->next->next->next->next->next = new ListNode(3); Solution* sol = new Solution(); ListNode* test = sol->deleteDuplicates(list); ListNode* node = test; while(node){ cout<<node->val<<endl; node = node->next; } char c; std::cin>>c; return 0; }
23.564103
129
0.59086
stephenkid
baf1b2695f834fccfc4abdb4cdcb1e2a43408277
368
cpp
C++
C++programlecurer.cpp
Mohamed742/C-AIMS-SA-2018
a59ba718872dfae0f8ee216b10dbb66db3e8a921
[ "Apache-2.0" ]
null
null
null
C++programlecurer.cpp
Mohamed742/C-AIMS-SA-2018
a59ba718872dfae0f8ee216b10dbb66db3e8a921
[ "Apache-2.0" ]
null
null
null
C++programlecurer.cpp
Mohamed742/C-AIMS-SA-2018
a59ba718872dfae0f8ee216b10dbb66db3e8a921
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int pow_itreative(int q, int n){ int out = 1 ; for( int i = 0 ; i < n;i++) out *= q; return out; } int main() { int x; int y; cout<< " Enter value for x" ; cin >> x; cout << "enter value of y" ; cin >> y ; cout<< x<< "^" << y << "=" << pow_itreative(x,y)<< endl; return 0; }
17.52381
60
0.480978
Mohamed742
baf2dd7de6fb3239434b1bc0ba6a7d66f5e49b51
4,347
cpp
C++
src/lnGPIO.cpp
mean00/Arduino_gd32_freeRTOS
de1828faaa5df79ee244c93ad45cf1dd63986f9f
[ "MIT" ]
4
2021-09-06T14:38:23.000Z
2022-03-13T01:15:48.000Z
src/lnGPIO.cpp
mean00/Arduino_gd32_freeRTOS
de1828faaa5df79ee244c93ad45cf1dd63986f9f
[ "MIT" ]
1
2021-10-14T09:38:56.000Z
2021-10-14T10:11:21.000Z
src/lnGPIO.cpp
mean00/lnArduino
de1828faaa5df79ee244c93ad45cf1dd63986f9f
[ "MIT" ]
null
null
null
/* * (C) 2021 MEAN00 fixounet@free.fr * See license file */ #include "lnArduino.h" #include "lnGPIO.h" #include "lnGPIO_priv.h" #include "lnAFIO_priv.h" #include "lnPeripheral_priv.h" #include "lnPinMapping.h" #include "lnTimer.h" static LN_GPIO *gpio[5]={(LN_GPIO *)LN_GPIOA_ADR,(LN_GPIO *)LN_GPIOB_ADR,(LN_GPIO *)LN_GPIOC_ADR,(LN_GPIO *)LN_GPIOD_ADR,(LN_GPIO *)LN_GPIOE_ADR}; static LN_GPIO *gpioA=(LN_GPIO *)LN_GPIOA_ADR; static LN_GPIO *gpioB=(LN_GPIO *)LN_GPIOB_ADR; static LN_GPIO *gpioC=(LN_GPIO *)LN_GPIOC_ADR; static LN_GPIO *gpios[3]={gpioA,gpioB,gpioC}; LN_AFIO *aAfio=(LN_AFIO *)LN_AFIO_ADR; /** * * @param pin * @param mode */ void lnPinMode(const lnPin xpin, const GpioMode mode) { LN_GPIO *port=gpio[xpin>>4]; const LN_PIN_MAPPING *lnPin=pinMappings+xpin; xAssert(lnPin->pin==xpin); int pin=xpin&0xf; volatile uint32_t *CTL; uint32_t value; switch(mode) { case lnDAC_MODE: value=LNGPIOSET(LN_CTL_MD_INPUT,LN_CTL_INPUT_ANALOG); break; case lnADC_MODE: value=LNGPIOSET(LN_CTL_MD_INPUT,LN_CTL_INPUT_ANALOG); break; case lnFLOATING: value=LNGPIOSET(LN_CTL_MD_INPUT,LN_CTL_INPUT_FLOATING); break; case lnINPUT_PULLUP: port->BOP=1<<pin; value=LNGPIOSET(LN_CTL_MD_INPUT,LN_CTL_INPUT_PULLUPPULLDOWN); break; case lnINPUT_PULLDOWN: port->BOP=1<<(16+pin); value=LNGPIOSET(LN_CTL_MD_INPUT,LN_CTL_INPUT_PULLUPPULLDOWN); break; case lnOUTPUT: value=LNGPIOSET (LN_CTL_MD_OUTPUT,LN_CTL_OUTPUT_PP); break; case lnOUTPUT_OPEN_DRAIN:value=LNGPIOSET(LN_CTL_MD_OUTPUT,LN_CTL_OUTPUT_OD); break; case lnPWM: xAssert(lnPin->timer!=-1); //lnTimer::setPwmMode(lnPin->timer, lnPin->timerChannel); case lnALTERNATE_PP: value=LNGPIOSET (LN_CTL_MD_OUTPUT,LN_CTL_OUTPUT_ALTERNAT_PP); break; case lnALTERNATE_OD: value=LNGPIOSET (LN_CTL_MD_OUTPUT,LN_CTL_OUTPUT_ALTERNAT_OD); break; default: xAssert(0); break; } if(pin>7) { CTL=&(port->CTL1); pin&=7; }else { CTL=&(port->CTL0); } uint32_t ref=*CTL; ref&=~(0Xf<<(pin*4)); ref|=value<<(pin*4); *CTL=ref; } /** * \brief Hardcoded switch PB10/PB11 * @param timer */ void lnRemapTimerPin(int timer) { switch(timer) { case 1: { uint32_t v= aAfio->PCF0; v&=LN_GPIO_TIMER1_MASK; v|=LN_GPIO_TIMER1_REMAP; aAfio->PCF0=v; } break; default: xAssert(0); } } /** * * @param pin * @param value */ void lnDigitalWrite(const lnPin pin, bool value) { LN_GPIO *port=gpio[pin>>4]; int xpin=pin&0xf; uint32_t mask,radix; if(value) { radix=1; }else { radix=(1<<16); } port->BOP=radix<<xpin; } void lnDigitalToggle(const lnPin pin) { LN_GPIO *port=gpio[pin>>4]; int xpin=pin&0xf; uint32_t val=port->OCTL; val^=1<<xpin; port->OCTL=val; } /** * * @param port * @return */ volatile uint32_t *lnGetGpioToggleRegister(int port) { return &(gpios[port]->BOP); } /** * * @param port * @return */ volatile uint32_t *lnGetGpioDirectionRegister(int port) { return &(gpios[port]->CTL0); } /** * * @param port * @return */ volatile uint32_t *lnGetGpioValueRegister(int port) { return &(gpios[port]->OCTL); } /** * * @param pin * @return */ bool lnDigitalRead(const lnPin pin) { LN_GPIO *port=gpio[pin>>4]; int xpin=pin&0xf; uint32_t v=port->ISTAT; return !!(v&(1<<xpin)); } /** * * @param port * @return */ uint32_t lnReadPort(int port) { return (gpios[port]->ISTAT); } /** * * @param p */ lnFastIO::lnFastIO(lnPin pin) { lnPinMode(pin,lnOUTPUT); LN_GPIO *port=gpio[pin>>4]; _onoff=(uint32_t *)&port->BOP; int bit=1<<(pin&0xf); _offbit=bit<<16; _onbit=bit; } // EOF
22.06599
147
0.564297
mean00
bafe00bdce5f834f8f9dd136258d6e2798e5ad01
10,254
hpp
C++
include/nudb/_experimental/test/test_store.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
279
2016-08-24T18:50:33.000Z
2022-01-17T22:28:17.000Z
include/nudb/_experimental/test/test_store.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
61
2016-08-23T23:26:00.000Z
2019-04-04T22:26:26.000Z
include/nudb/_experimental/test/test_store.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
44
2016-08-25T19:17:03.000Z
2021-09-10T08:14:00.000Z
// // Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef NUDB_TEST_TEST_STORE_HPP #define NUDB_TEST_TEST_STORE_HPP #include <nudb/_experimental/util.hpp> #include <nudb/_experimental/test/temp_dir.hpp> #include <nudb/_experimental/test/xor_shift_engine.hpp> #include <nudb/create.hpp> #include <nudb/native_file.hpp> #include <nudb/store.hpp> #include <nudb/verify.hpp> #include <nudb/xxhasher.hpp> #include <iomanip> #include <iostream> namespace nudb { namespace test { template<class = void> class Buffer_t { std::size_t size_ = 0; std::size_t capacity_ = 0; std::unique_ptr<std::uint8_t[]> p_; public: Buffer_t() = default; Buffer_t(Buffer_t&& other); Buffer_t(Buffer_t const& other); Buffer_t& operator=(Buffer_t&& other); Buffer_t& operator=(Buffer_t const& other); bool empty() const { return size_ == 0; } std::size_t size() const { return size_; } std::uint8_t* data() { return p_.get(); } std::uint8_t const* data() const { return p_.get(); } void clear(); void shrink_to_fit(); std::uint8_t* resize(std::size_t size); std::uint8_t* operator()(void const* data, std::size_t size); }; template<class _> Buffer_t<_>:: Buffer_t(Buffer_t&& other) : size_(other.size_) , capacity_(other.capacity_) , p_(std::move(other.p_)) { other.size_ = 0; other.capacity_ = 0; } template<class _> Buffer_t<_>:: Buffer_t(Buffer_t const& other) { if(! other.empty()) std::memcpy(resize(other.size()), other.data(), other.size()); } template<class _> auto Buffer_t<_>:: operator=(Buffer_t&& other) -> Buffer_t& { if(&other != this) { size_ = other.size_; capacity_ = other.capacity_; p_ = std::move(other.p_); other.size_ = 0; other.capacity_ = 0; } return *this; } template<class _> auto Buffer_t<_>:: operator=(Buffer_t const& other) -> Buffer_t& { if(&other != this) { if(other.empty()) size_ = 0; else std::memcpy(resize(other.size()), other.data(), other.size()); } return *this; } template<class _> void Buffer_t<_>:: clear() { size_ = 0; capacity_ = 0; p_.reset(); } template<class _> void Buffer_t<_>:: shrink_to_fit() { if(empty() || size_ == capacity_) return; std::unique_ptr<std::uint8_t[]> p{ new std::uint8_t[size_]}; capacity_ = size_; std::memcpy(p.get(), p_.get(), size_); std::swap(p, p_); } template<class _> std::uint8_t* Buffer_t<_>:: resize(std::size_t size) { if(capacity_ < size) { p_.reset(new std::uint8_t[size]); capacity_ = size; } size_ = size; return p_.get(); } template<class _> std::uint8_t* Buffer_t<_>:: operator()(void const* data, std::size_t size) { if(data == nullptr || size == 0) return resize(0); return reinterpret_cast<std::uint8_t*>( std::memcpy(resize(size), data, size)); } using Buffer = Buffer_t<>; //------------------------------------------------------------------------------ /// Describes a test generated key/value pair struct item_type { std::uint8_t* key; std::uint8_t* data; std::size_t size; }; /// Interface to facilitate tests template<class File> class basic_test_store { using Hasher = xxhasher; temp_dir td_; std::uniform_int_distribution<std::size_t> sizef_; std::function<void(error_code&)> createf_; std::function<void(error_code&)> openf_; Buffer buf_; public: path_type const dp; path_type const kp; path_type const lp; std::size_t const keySize; std::size_t const blockSize; float const loadFactor; static std::uint64_t constexpr appnum = 1; static std::uint64_t constexpr salt = 42; basic_store<xxhasher, File> db; template<class... Args> basic_test_store(std::size_t keySize, std::size_t blockSize, float loadFactor, Args&&... args); template<class... Args> basic_test_store( boost::filesystem::path const& temp_dir, std::size_t keySize, std::size_t blockSize, float loadFactor, Args&&... args); ~basic_test_store(); item_type operator[](std::uint64_t i); void create(error_code& ec); void open(error_code& ec); void close(error_code& ec) { db.close(ec); } void erase(); private: template<class Generator> static void rngfill( void* dest, std::size_t size, Generator& g); }; template <class File> template <class... Args> basic_test_store<File>::basic_test_store( boost::filesystem::path const& temp_dir, std::size_t keySize_, std::size_t blockSize_, float loadFactor_, Args&&... args) : td_(temp_dir) , sizef_(250, 750) , createf_( [this, args...](error_code& ec) { nudb::create<Hasher, File>( dp, kp, lp, appnum, salt, keySize, blockSize, loadFactor, ec, args...); }) , openf_( [this, args...](error_code& ec) { db.open(dp, kp, lp, ec, args...); }) , dp(td_.file("nudb.dat")) , kp(td_.file("nudb.key")) , lp(td_.file("nudb.log")) , keySize(keySize_) , blockSize(blockSize_) , loadFactor(loadFactor_) { } template <class File> template <class... Args> basic_test_store<File>::basic_test_store(std::size_t keySize_, std::size_t blockSize_, float loadFactor_, Args&&... args) : basic_test_store(boost::filesystem::path{}, keySize_, blockSize_, loadFactor_, std::forward<Args>(args)...) { } template<class File> basic_test_store<File>:: ~basic_test_store() { erase(); } template<class File> auto basic_test_store<File>:: operator[](std::uint64_t i) -> item_type { xor_shift_engine g{i + 1}; item_type item; item.size = sizef_(g); auto const needed = keySize + item.size; rngfill(buf_.resize(needed), needed, g); // put key last so we can get some unaligned // keys, this increases coverage of xxhash. item.data = buf_.data(); item.key = buf_.data() + item.size; return item; } template<class File> void basic_test_store<File>:: create(error_code& ec) { createf_(ec); } template<class File> void basic_test_store<File>:: open(error_code& ec) { openf_(ec); if(ec) return; if(db.key_size() != keySize) ec = error::invalid_key_size; else if(db.block_size() != blockSize) ec = error::invalid_block_size; } template<class File> void basic_test_store<File>:: erase() { erase_file(dp); erase_file(kp); erase_file(lp); } template<class File> template<class Generator> void basic_test_store<File>:: rngfill( void* dest, std::size_t size, Generator& g) { using result_type = typename Generator::result_type; while(size >= sizeof(result_type)) { auto const v = g(); std::memcpy(dest, &v, sizeof(v)); dest = reinterpret_cast< std::uint8_t*>(dest) + sizeof(v); size -= sizeof(v); } if(size > 0) { auto const v = g(); std::memcpy(dest, &v, size); } } using test_store = basic_test_store<native_file>; //------------------------------------------------------------------------------ template<class T> static std::string num (T t) { std::string s = std::to_string(t); std::reverse(s.begin(), s.end()); std::string s2; s2.reserve(s.size() + (s.size()+2)/3); int n = 0; for (auto c : s) { if (n == 3) { n = 0; s2.insert (s2.begin(), ','); } ++n; s2.insert(s2.begin(), c); } return s2; } template<class = void> std::ostream& operator<<(std::ostream& os, verify_info const& info) { os << "avg_fetch: " << std::fixed << std::setprecision(3) << info.avg_fetch << "\n" << "waste: " << std::fixed << std::setprecision(3) << info.waste * 100 << "%" << "\n" << "overhead: " << std::fixed << std::setprecision(1) << info.overhead * 100 << "%" << "\n" << "actual_load: " << std::fixed << std::setprecision(0) << info.actual_load * 100 << "%" << "\n" << "version: " << num(info.version) << "\n" << "uid: " << fhex(info.uid) << "\n" << "appnum: " << info.appnum << "\n" << "key_size: " << num(info.key_size) << "\n" << "salt: " << fhex(info.salt) << "\n" << "pepper: " << fhex(info.pepper) << "\n" << "block_size: " << num(info.block_size) << "\n" << "bucket_size: " << num(info.bucket_size) << "\n" << "load_factor: " << std::fixed << std::setprecision(0) << info.load_factor * 100 << "%" << "\n" << "capacity: " << num(info.capacity) << "\n" << "buckets: " << num(info.buckets) << "\n" << "key_count: " << num(info.key_count) << "\n" << "value_count: " << num(info.value_count) << "\n" << "value_bytes: " << num(info.value_bytes) << "\n" << "spill_count: " << num(info.spill_count) << "\n" << "spill_count_tot: " << num(info.spill_count_tot) << "\n" << "spill_bytes: " << num(info.spill_bytes) << "\n" << "spill_bytes_tot: " << num(info.spill_bytes_tot) << "\n" << "key_file_size: " << num(info.key_file_size) << "\n" << "dat_file_size: " << num(info.dat_file_size) << std::endl; std::string s; for (size_t i = 0; i < info.hist.size(); ++i) s += (i==0) ? std::to_string(info.hist[i]) : (", " + std::to_string(info.hist[i])); os << "hist: " << s << std::endl; return os; } } // test } // nudb #endif
22.685841
109
0.552662
movitto
bafe6156613104f06687342cfa1d16ab3b1d699b
530
cpp
C++
KeepCryingEngine/Canvas.cpp
KeepCryingEngine/KeepCryingEngine
c2e3f89eb5c3d70916f97b7a04cfbab033553b04
[ "MIT" ]
1
2018-01-11T20:05:29.000Z
2018-01-11T20:05:29.000Z
KeepCryingEngine/Canvas.cpp
KeepCryingEngine/KeepCryingEngine
c2e3f89eb5c3d70916f97b7a04cfbab033553b04
[ "MIT" ]
28
2018-01-17T21:04:33.000Z
2018-03-02T13:26:17.000Z
KeepCryingEngine/Canvas.cpp
PereViader/KeepCryingEngine
c2e3f89eb5c3d70916f97b7a04cfbab033553b04
[ "MIT" ]
1
2020-01-12T02:28:04.000Z
2020-01-12T02:28:04.000Z
#include "Canvas.h" #include "GameObject.h" Canvas::Canvas():Component(Canvas::TYPE) {} Canvas::~Canvas() {} std::vector<Component::Type> Canvas::GetNeededComponents() const { return { Component::Type::Transform2D }; } void Canvas::DrawUI() { if(ImGui::CollapsingHeader("Canvas")) { ImGui::PushID(gameObject->GetId()); if(ImGui::Checkbox("Active", &enabled)) { SetEnable(enabled); } ImGui::SameLine(); ImGui::PopID(); if(ImGui::Button("Delete Component")) { gameObject->RemoveComponent(this); } } }
17.096774
64
0.664151
KeepCryingEngine
baff0f44401f87c170aa9b379ea8ff3a675f7304
47,087
cpp
C++
GameServer/Event.cpp
millerp/IGC.GameServer
0f67ec22d747a84d5934493939cada88a4e067db
[ "MIT" ]
2
2017-03-09T09:42:59.000Z
2020-11-18T07:58:58.000Z
GameServer/Event.cpp
millerp/IGC.GameServer
0f67ec22d747a84d5934493939cada88a4e067db
[ "MIT" ]
8
2017-03-08T13:26:53.000Z
2017-03-09T13:37:43.000Z
GameServer/Event.cpp
millerp/IGC.GameServer
0f67ec22d747a84d5934493939cada88a4e067db
[ "MIT" ]
5
2017-11-21T13:22:52.000Z
2022-02-17T07:41:34.000Z
#include "stdafx.h" #include "Event.h" #include "TLog.h" #include "DSProtocol.h" #include "GameServer.h" #include "GameMain.h" #include "winutil.h" #include "BagManager.h" #include "configread.h" // GS-N 0.99.60T 0x00460DF0 // GS-N 1.00.18 JPN 0x00470700 - Completed void EventChipEventProtocolCore(BYTE protoNum, LPBYTE aRecv, int aLen) { #if (TRACE_PROTOCOL == 1) LogAddHeadHex("EVENT_SERVER", aRecv, aLen); #endif switch (protoNum) { case 0x01: EGRecvEventChipInfo((PMSG_ANS_VIEW_EC_MN *) aRecv); break; case 0x02: EGResultRegEventChip((PMSG_ANS_REGISTER_EVENTCHIP *) aRecv); break; case 0x03: EGRecvRegMutoNum((PMSG_ANS_REGISTER_MUTONUM *) aRecv); break; case 0x04: EGRecvChangeRena((PMSG_ANS_RESET_EVENTCHIP *) aRecv); break; case 0x05: EGRecvStoneInfo((PMSG_ANS_VIEW_STONES *) aRecv); break; case 0x06: EGRecvRegStone((PMSG_ANS_REGISTER_STONES *) aRecv); break; case 0x07: EGRecvDeleteStone((PMSG_ANS_DELETE_STONES *) aRecv); break; case 0x09: EGRecvChangeStones((PMSG_ANS_RESET_EVENTCHIP *) aRecv); break; case 0x08: EGRecv2AnvRegSerial((PMSG_ANS_2ANIV_SERIAL *) aRecv); break; case 0x10: EGRecvRegRingGift((PMSG_ANS_REG_RINGGIFT *) aRecv); break; case 0x15: EGAnsRegCCOfflineGift((PMSG_ANS_REG_CC_OFFLINE_GIFT *) aRecv); break; case 0x16: EGAnsRegDLOfflineGift((PMSG_ANS_REG_DL_OFFLINE_GIFT *) aRecv); break; case 0x17: EGAnsRegHTOfflineGift((PMSG_ANS_REG_HT_OFFLINE_GIFT *) aRecv); break; case 0x18: EGAnsRegLuckyCoin((PMSG_ANS_REG_LUCKYCOIN *) aRecv); break; case 0x19: EGAnsLuckyCoinInfo((PMSG_ANS_LUCKYCOIN *) aRecv); break; case 0x20: EGAnsSantaCheck(reinterpret_cast<PMSG_ANS_SANTACHECK *>(aRecv)); break; case 0x21: EGAnsSantaGift(reinterpret_cast<PMSG_ANS_SANTAGIFT *>(aRecv)); break; } } void FireworksOpenEven(LPOBJ lpObj) { PMSG_SERVERCMD ServerCmd; PHeadSubSetB((LPBYTE) & ServerCmd, 0xF3, 0x40, sizeof(ServerCmd)); ServerCmd.CmdType = 0; ServerCmd.X = lpObj->X; ServerCmd.Y = lpObj->Y; GSProtocol.MsgSendV2(lpObj, (LPBYTE) & ServerCmd, sizeof(ServerCmd)); IOCP.DataSend(lpObj->m_Index, (LPBYTE) & ServerCmd, sizeof(ServerCmd)); } void ChristmasFireCrackDrop(LPOBJ lpObj) //season 4.5 add-on { PMSG_SERVERCMD ServerCmd; PHeadSubSetB((LPBYTE) & ServerCmd, 0xF3, 0x40, sizeof(ServerCmd)); ServerCmd.CmdType = 59; ServerCmd.X = lpObj->X; ServerCmd.Y = lpObj->Y; GSProtocol.MsgSendV2(lpObj, (LPBYTE) & ServerCmd, sizeof(ServerCmd)); IOCP.DataSend(lpObj->m_Index, (LPBYTE) & ServerCmd, sizeof(ServerCmd)); } #pragma warning ( disable : 4101 ) void EGRecvEventChipInfo(PMSG_ANS_VIEW_EC_MN *aRecv) { LPOBJ lpObj = &gObj[aRecv->iINDEX]; PMSG_EVENTCHIPINFO eventchipeventinfo; char msg[255]; PHeadSetB((LPBYTE) & eventchipeventinfo, 0x94, sizeof(eventchipeventinfo)); eventchipeventinfo.Type = 0; eventchipeventinfo.ChipCount = aRecv->nEVENT_CHIPS; lpObj->EventChipCount = aRecv->nEVENT_CHIPS; lpObj->MutoNumber = aRecv->iMUTO_NUM; IOCP.DataSend(lpObj->m_Index, (LPBYTE) & eventchipeventinfo, eventchipeventinfo.h.size); lpObj->UseEventServer = FALSE; } #pragma warning ( default : 4101 ) void EGResultRegEventChip(PMSG_ANS_REGISTER_EVENTCHIP *aRecv) { PMSG_REGEVENTCHIP_RESULT Result; LPOBJ lpObj; int aIndex; PHeadSetB((LPBYTE) & Result, 0x95, sizeof(Result)); lpObj = &gObj[aRecv->iINDEX]; aIndex = aRecv->iINDEX; if (aRecv->bSUCCESS == FALSE) { Result.ChipCount = -1; g_Log.Add("[EventChip] [%s][%s] RegEventServer Fail (RegEventchip) %d", lpObj->AccountID, lpObj->Name, aRecv->Pos); } else { Result.ChipCount = aRecv->nEVENT_CHIPS; gObjInventoryDeleteItem(aIndex, aRecv->Pos); GSProtocol.GCInventoryItemDeleteSend(aIndex, aRecv->Pos, 1); g_Log.Add("[EventChip] [%s][%s] Delete EventChip (%d)", lpObj->AccountID, lpObj->Name, aRecv->Pos); } Result.Type = 0; IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; } void EGRecvRegMutoNum(PMSG_ANS_REGISTER_MUTONUM *aRecv) { LPOBJ lpObj; int aIndex; lpObj = &gObj[aRecv->iINDEX]; aIndex = aRecv->iINDEX; PMSG_GETMUTONUMBER_RESULT Result; PHeadSetB((LPBYTE) & Result, 0x96, sizeof(Result)); if (gObjFind10EventChip(aIndex) == FALSE) { Result.MutoNum[0] = -1; Result.MutoNum[1] = 0; Result.MutoNum[2] = 0; IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; return; } gObjDelete10EventChip(aIndex); Result.MutoNum[0] = aRecv->iMUTO_NUM / 1000000; Result.MutoNum[1] = aRecv->iMUTO_NUM / 1000 - aRecv->iMUTO_NUM / 1000000 * 1000; Result.MutoNum[2] = aRecv->iMUTO_NUM % 1000; lpObj->MutoNumber = aRecv->iMUTO_NUM; g_Log.Add("[EventChip] [%s][%s] Make MutoNumber %d,%d,%d", lpObj->AccountID, lpObj->Name, Result.MutoNum[0], Result.MutoNum[1], Result.MutoNum[2]); IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; } void EGRecvChangeRena(PMSG_ANS_RESET_EVENTCHIP *aRecv) { PMSG_REGEVENTCHIP_RESULT Result; LPOBJ lpObj; int aIndex; PHeadSetB((LPBYTE) & Result, 0x95, sizeof(Result)); lpObj = &gObj[aRecv->iINDEX]; aIndex = aRecv->iINDEX; if (aRecv->bSUCCESS != FALSE) { lpObj->m_PlayerData->Money += lpObj->EventChipCount * 3000; GSProtocol.GCMoneySend(aIndex, lpObj->m_PlayerData->Money); g_Log.Add("[EventChip] [%s][%s] ChangeRena AddMoney(%d)", lpObj->AccountID, lpObj->Name, lpObj->EventChipCount * 3000); } else { g_Log.Add("[EventChip] [%s][%s] ChangeRena Fail", lpObj->AccountID, lpObj->Name); } Result.ChipCount = 0; lpObj->EventChipCount = 0; IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; } LPOBJ pEventObj; void EGRecvStoneInfo(PMSG_ANS_VIEW_STONES *aRecv) { LPOBJ lpObj = &gObj[aRecv->iINDEX]; PMSG_EVENTCHIPINFO Result; PHeadSetB((LPBYTE) & Result, 0x94, sizeof(Result)); if (aRecv->bSUCCESS) lpObj->iStoneCount = aRecv->iStoneCount; else lpObj->iStoneCount = 0; lpObj->MutoNumber = 0; Result.Type = 3; Result.ChipCount = aRecv->iStoneCount; IOCP.DataSend(lpObj->m_Index, (LPBYTE) & Result, Result.h.size); char msg[128]; wsprintf(msg, Lang.GetText(0, 78), Result.ChipCount); GSProtocol.ChatTargetSend(pEventObj, msg, lpObj->m_Index); } void EGRecvRegStone(PMSG_ANS_REGISTER_STONES *aRecv) { PMSG_REGEVENTCHIP_RESULT Result; LPOBJ lpObj; int aIndex; PHeadSetB((LPBYTE) & Result, 0x95, sizeof(Result)); lpObj = &gObj[aRecv->iINDEX]; aIndex = aRecv->iINDEX; if (aRecv->bSUCCESS != FALSE) { Result.ChipCount = aRecv->iStoneCount; gObjInventoryDeleteItem(aIndex, aRecv->iPosition); GSProtocol.GCInventoryItemDeleteSend(aIndex, aRecv->iPosition, 1); g_Log.Add("[Stone] [%s][%s] Delete Stones", lpObj->AccountID, lpObj->Name); } else { Result.ChipCount = -1; g_Log.Add("[Stone] [%s][%s] RegEventServer Fail (Stones : %d)", lpObj->AccountID, lpObj->Name, aRecv->iStoneCount); } IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; } void EGRecvDeleteStone(PMSG_ANS_DELETE_STONES *aRecv) { return; } void EGRecvChangeStones(PMSG_ANS_RESET_EVENTCHIP *aRecv) { PMSG_REGEVENTCHIP_RESULT Result; LPOBJ lpObj; int aIndex; PHeadSetB((LPBYTE) & Result, 0x95, sizeof(Result)); lpObj = &gObj[aRecv->iINDEX]; aIndex = aRecv->iINDEX; if (aRecv->bSUCCESS != FALSE) { lpObj->m_PlayerData->Money += lpObj->iStoneCount * 3000; GSProtocol.GCMoneySend(aIndex, lpObj->m_PlayerData->Money); g_Log.Add("[Stones] [%s][%s] ChangeRena AddMoney(%d)", lpObj->AccountID, lpObj->Name, lpObj->iStoneCount * 3000); } else { g_Log.Add("[Stones] [%s][%s] ChangeRena Fail", lpObj->AccountID, lpObj->Name); } Result.ChipCount = 0; lpObj->iStoneCount = 0; IOCP.DataSend(aIndex, (LPBYTE) & Result, Result.h.size); lpObj->UseEventServer = FALSE; } struct PMSG_ANS_2ANV_LOTTO_EVENT { PBMSG_HEAD h; // C1:9D BYTE btIsRegistered; // 3 char szGIFT_NAME[64]; // 4 }; #define GIFT_2ANV_MAP 235 #define MAX_GIFT_2ANV 50 #define GIFT_2ANV_RANGE(x) ( (((x))<0)?FALSE:(((x))>MAX_GIFT_2ANV-1)?FALSE:TRUE ) BOOL g_bRingEventItemTextLoad = FALSE; char g_sz2ANV_GIFT_NAME[MAX_GIFT_2ANV][64]; void EGRecv2AnvRegSerial(PMSG_ANS_2ANIV_SERIAL *aRecv) { PMSG_ANS_2ANV_LOTTO_EVENT Result; PHeadSetB((LPBYTE) & Result, 0x9D, sizeof(Result)); if (!ObjectMaxRange(aRecv->iINDEX)) { g_Log.Add("[Mu_2Anv_Event] Error : Index is out of bound [%d]", aRecv->iINDEX); return; } if (gObj[aRecv->iINDEX].Connected <= PLAYER_LOGGED) { g_Log.Add("[Mu_2Anv_Event] Error : Index is out of bound [%d]", aRecv->iINDEX); return; } Result.szGIFT_NAME[0] = 0; if (aRecv->btIsRegistered == FALSE) { Result.btIsRegistered = FALSE; if (!GIFT_2ANV_RANGE(aRecv->iGiftNumber - 1)) { g_Log.Add("[Mu_2Anv_Event] Error : Gift Index is out of bound [%d]", aRecv->iGiftNumber); Result.btIsRegistered = 2; } if (gObj[aRecv->iINDEX].Connected > PLAYER_LOGGED) { PMSG_SERVERCMD ServerCmd; PHeadSubSetB((LPBYTE) & ServerCmd, 0xF3, 0x40, sizeof(ServerCmd)); ServerCmd.CmdType = 0; ServerCmd.X = gObj[aRecv->iINDEX].X; ServerCmd.Y = gObj[aRecv->iINDEX].Y; GSProtocol.MsgSendV2(&gObj[aRecv->iINDEX], (LPBYTE) & ServerCmd, sizeof(ServerCmd)); IOCP.DataSend(aRecv->iINDEX, (LPBYTE) & ServerCmd, sizeof(ServerCmd)); } if (g_bRingEventItemTextLoad) { strcpy(Result.szGIFT_NAME, g_sz2ANV_GIFT_NAME[aRecv->iGiftNumber - 1]); } switch (aRecv->iGiftNumber) { case 1: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 13), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 13)].Name); } break; case 2: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 14), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 14)].Name); } break; case 3: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 15), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 15)].Name); } break; case 4: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 5: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 3, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, "Heart of Love"); } break; case 6: gObj[aRecv->iINDEX].m_PlayerData->Money += 500000; GSProtocol.GCMoneySend(aRecv->iINDEX, gObj[aRecv->iINDEX].m_PlayerData->Money); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, "500,000 Zen"); } break; case 7: gObj[aRecv->iINDEX].m_PlayerData->Money += 50000; GSProtocol.GCMoneySend(aRecv->iINDEX, gObj[aRecv->iINDEX].m_PlayerData->Money); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, "50,000 Zen"); } break; case 8: case 9: case 10: gObj[aRecv->iINDEX].m_PlayerData->Money += 30000; GSProtocol.GCMoneySend(aRecv->iINDEX, gObj[aRecv->iINDEX].m_PlayerData->Money); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, "30,000 Zen"); } break; case 11: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 19), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 11)].Name); // #error Change 11 to 19 } break; case 12: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 18), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 18)].Name); } break; case 13: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 17), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 17)].Name); } break; case 14: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 16), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 16)].Name); } break; case 15: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 14), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 14)].Name); } break; case 16: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 13), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 13)].Name); } break; case 17: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(12, 12), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(12, 12)].Name); } break; case 18: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(13, 2), 0, 255, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(13, 2)].Name); } break; case 19: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(13, 3), 0, 255, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(13, 3)].Name); // #error Change 2 to 3 } break; case 20: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 16), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 16)].Name); } break; case 21: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(13, 0), 0, 255, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(13, 0)].Name); } break; case 22: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(13, 1), 0, 255, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(13, 1)].Name); } break; case 23: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 1, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 24: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 9, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 25: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 10, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 26: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 19), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 19)].Name); } break; case 27: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 19), 1, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 19)].Name); } break; case 28: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 19), 2, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 19)].Name); } break; case 29: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 19), 3, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 19)].Name); } break; case 30: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 19), 4, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 19)].Name); } break; case 31: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 2, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 32: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 20), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 20)].Name); } break; case 33: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 22), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 22)].Name); } break; case 34: case 35: case 36: case 37: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(13, 15), aRecv->iGiftNumber - 34, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(13, 15)].Name); } break; case 38: case 39: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), aRecv->iGiftNumber - 27, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 40: case 41: case 42: case 43: case 44: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 20), aRecv->iGiftNumber - 39, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 20)].Name); } break; case 45: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 11), 8, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 11)].Name); } break; case 46: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 41), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 41)].Name); } break; case 47: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 42), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 42)].Name); } break; case 48: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 44), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 44)].Name); } break; case 49: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 43), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 43)].Name); } break; case 50: ItemSerialCreateSend(gObj[aRecv->iINDEX].m_Index, GIFT_2ANV_MAP, gObj[aRecv->iINDEX].X, gObj[aRecv->iINDEX].Y, ItemGetNumberMake(14, 31), 0, 0, 0, 0, 0, aRecv->iINDEX, 0, 0, 0, 0, 0); if (g_bRingEventItemTextLoad == FALSE) { strcpy(Result.szGIFT_NAME, ItemAttribute[ITEMGET(14, 31)].Name); } break; default: g_Log.Add("[Mu_2Anv_Event] Error : iGiftNumber is Out of Boud [%d]", aRecv->iGiftNumber); break; } } else if (aRecv->btIsRegistered == 1 || aRecv->btIsRegistered == 2 || aRecv->btIsRegistered == 3 || aRecv->btIsRegistered == 4 || aRecv->btIsRegistered == 5) { Result.btIsRegistered = aRecv->btIsRegistered; } else { Result.btIsRegistered = 4; g_Log.Add("[Mu_2Anv_Event] Error : Result Value is Wrong [%d]", aRecv->btIsRegistered); } g_Log.Add("[Mu_2Anv_Event] Register Serial Result : %d [%s][%s]", aRecv->btIsRegistered, gObj[aRecv->iINDEX].AccountID, gObj[aRecv->iINDEX].Name); IOCP.DataSend(aRecv->iINDEX, (LPBYTE) & Result, Result.h.size); gObj[aRecv->iINDEX].UseEventServer = FALSE; } static const char g_szRingEventOfflineGift[4][32] = {"100�� �¹���", "10�� �¹���", "5�� �¹���", "2�� �¹���"}; void EGRecvRegRingGift(PMSG_ANS_REG_RINGGIFT *aRecv) { gObj[aRecv->iINDEX].UseEventServer = FALSE; if (gObjIsConnected(aRecv->iINDEX) == FALSE) return; if (strcmp(aRecv->szUID, gObj[aRecv->iINDEX].AccountID)) return; if (aRecv->btIsRegistered == 1) { if (CHECK_LIMIT(aRecv->btGiftKind - 1, 4)) { char szTemp[256]; wsprintf(szTemp, "%s�� ���� %s�� ��÷�Ǽ̽��ϴ�.", gObj[aRecv->iINDEX].Name, g_szRingEventOfflineGift[aRecv->btGiftKind - 1]); GSProtocol.AllSendServerMsg(szTemp); g_Log.Add("[Ring Event] [%s][%s] Register Succeeded Result:%d, Gift:%d", gObj[aRecv->iINDEX].AccountID, gObj[aRecv->iINDEX].Name, aRecv->btIsRegistered, aRecv->btGiftKind); } else { g_Log.Add("[Ring Event] [%s][%s] Register Failed Result:%d, Gift:%d (out of bound, 1~4)", gObj[aRecv->iINDEX].AccountID, gObj[aRecv->iINDEX].Name, aRecv->btIsRegistered, aRecv->btGiftKind); } return; } g_Log.Add("[Ring Event] [%s][%s] Register Failed Result : %d", gObj[aRecv->iINDEX].AccountID, gObj[aRecv->iINDEX].Name, aRecv->btIsRegistered); if (gObjIsConnected(aRecv->iINDEX) == TRUE) { MapC[gObj[aRecv->iINDEX].MapNumber].MoneyItemDrop(100000, (BYTE) gObj[aRecv->iINDEX].X, (BYTE) gObj[aRecv->iINDEX].Y); } } struct PMSG_REQ_BLOODCASTLE_ENTERCOUNT { PBMSG_HEAD2 h; // C1:0B char AccountID[10]; // 3 char GameID[10]; // D int ServerCode; // 18 int iObjIndex; // 1C }; void EGReqBloodCastleEnterCount(int iIndex) { if (!gObjIsConnected(iIndex)) return; PMSG_REQ_BLOODCASTLE_ENTERCOUNT pMsg; pMsg.h.c = 0xC1; pMsg.h.headcode = 0xBD; pMsg.h.subcode = 0x02; pMsg.h.size = sizeof(pMsg); memcpy(pMsg.AccountID, gObj[iIndex].AccountID, 10); memcpy(pMsg.GameID, gObj[iIndex].Name, 10); pMsg.ServerCode = g_ConfigRead.server.GetGameServerCode() / 20; pMsg.iObjIndex = iIndex; wsDataCli.DataSend(reinterpret_cast<char *>(&pMsg), pMsg.h.size); } struct PMSG_ANS_CL_ENTERCOUNT { PBMSG_HEAD h; // C1:9F BYTE btEventType; // 3 BYTE btLeftEnterCount; // 4 }; void EGAnsBloodCastleEnterCount(PMSG_ANS_BLOODCASTLE_ENTERCOUNT *lpMsg) { if (!lpMsg) return; if (!gObjIsConnected(lpMsg->iObjIndex)) return; char szAccountID[11] = {0}; char szName[11] = {0}; memcpy(szAccountID, lpMsg->AccountID, 10); memcpy(szName, lpMsg->GameID, 10); if (strcmp(gObj[lpMsg->iObjIndex].AccountID, szAccountID) || strcmp(gObj[lpMsg->iObjIndex].Name, szName)) return; PMSG_ANS_CL_ENTERCOUNT pMsgSend; pMsgSend.h.c = 0xC1; pMsgSend.h.headcode = 0x9F; pMsgSend.h.size = sizeof(pMsgSend); pMsgSend.btEventType = 2; pMsgSend.btLeftEnterCount = lpMsg->iLeftCount; IOCP.DataSend(lpMsg->iObjIndex, (LPBYTE) & pMsgSend, sizeof(pMsgSend)); } struct PMSG_REQ_REG_CC_OFFLINE_GIFT { PBMSG_HEAD2 h; // C1:15 int iINDEX; // 4 char szUID[11]; // 8 WORD wServerCode; // 14 char szNAME[11]; // 16 }; void EGReqRegCCOfflineGift(int iIndex) { if (!gObjIsConnected(iIndex)) return; PMSG_REQ_REG_CC_OFFLINE_GIFT pMsg; pMsg.h.c = 0xC1; pMsg.h.headcode = 0xBE; pMsg.h.subcode = 0x15; pMsg.h.size = sizeof(pMsg); memcpy(pMsg.szUID, gObj[iIndex].AccountID, 11); memcpy(pMsg.szNAME, gObj[iIndex].Name, 11); pMsg.wServerCode = g_ConfigRead.server.GetGameServerCode() / 20; pMsg.iINDEX = iIndex; pMsg.szUID[10] = 0; pMsg.szNAME[10] = 0; wsDataCli.DataSend((PCHAR) & pMsg, sizeof(pMsg)); } void EGAnsRegCCOfflineGift(PMSG_ANS_REG_CC_OFFLINE_GIFT *lpMsg) { if (!lpMsg) return; if (!lpMsg->iResultCode) return; char szAccountID[11] = {0}; char szName[11] = {0}; char szGIFT_NAME[50] = {0}; memset(szAccountID, 0, sizeof(szAccountID)); memset(szName, 0, sizeof(szName)); memset(szGIFT_NAME, 0, sizeof(szGIFT_NAME)); memcpy(szAccountID, lpMsg->szUID, sizeof(szAccountID)); memcpy(szName, lpMsg->szNAME, sizeof(szName)); memcpy(szGIFT_NAME, lpMsg->szGIFT_NAME, sizeof(szGIFT_NAME)); szAccountID[10] = 0; szName[10] = 0; szGIFT_NAME[49] = 0; char szText[256] = {0}; wsprintf(szText, Lang.GetText(0, 156), szName, szGIFT_NAME); GSProtocol.AllSendServerMsg(szText); g_Log.Add("[Chaos Castle] [%s][%s] Success to Register OffLine Gift (GIFT:%s)", szAccountID, szName, szGIFT_NAME); } struct PMSG_REQ_REG_DL_OFFLINE_GIFT { PBMSG_HEAD2 h; // C1:16 int iINDEX; // 4 char szUID[11]; // 8 WORD wServerCode; // 14 char szNAME[11]; // 16 }; void EGReqRegDLOfflineGift(int iIndex) { if (!gObjIsConnected(iIndex)) return; PMSG_REQ_REG_DL_OFFLINE_GIFT pMsg; pMsg.h.c = 0xC1; pMsg.h.headcode = 0xBE; pMsg.h.subcode = 0x16; pMsg.h.size = sizeof(pMsg); memcpy(pMsg.szUID, gObj[iIndex].AccountID, 11); memcpy(pMsg.szNAME, gObj[iIndex].Name, 11); pMsg.wServerCode = g_ConfigRead.server.GetGameServerCode() / 20; pMsg.iINDEX = iIndex; pMsg.szUID[10] = 0; pMsg.szNAME[10] = 0; wsDataCli.DataSend((PCHAR) & pMsg, sizeof(pMsg)); } void EGAnsRegDLOfflineGift(PMSG_ANS_REG_DL_OFFLINE_GIFT *lpMsg) { if (!lpMsg) return; if (!lpMsg->iResultCode) return; char szAccountID[11] = {0}; char szName[11] = {0}; char szGIFT_NAME[50] = {0}; memset(szAccountID, 0, sizeof(szAccountID)); memset(szName, 0, sizeof(szName)); memset(szGIFT_NAME, 0, sizeof(szGIFT_NAME)); memcpy(szAccountID, lpMsg->szUID, sizeof(szAccountID)); memcpy(szName, lpMsg->szNAME, sizeof(szName)); memcpy(szGIFT_NAME, lpMsg->szGIFT_NAME, sizeof(szGIFT_NAME)); szAccountID[10] = 0; szName[10] = 0; szGIFT_NAME[49] = 0; char szText[256] = {0}; wsprintf(szText, "[��ũ�ε� ��� �̺�Ʈ] %s �Բ��� %s ��ǰ�� ��÷�Ǽ̽��ϴ�.", szName, szGIFT_NAME); GSProtocol.AllSendServerMsg(szText); g_Log.Add("[DarkLord Heart Event] [%s][%s] Success to Register OffLine Gift (GIFT:%s)", szAccountID, szName, szGIFT_NAME); } struct PMSG_REQ_REG_HT_OFFLINE_GIFT { PBMSG_HEAD2 h; // C1:17 int iINDEX; // 4 char szUID[11]; // 8 WORD wServerCode; // 14 char szNAME[11]; // 16 }; void EGReqRegHTOfflineGift(int iIndex) { if (!gObjIsConnected(iIndex)) return; PMSG_REQ_REG_HT_OFFLINE_GIFT pMsg; pMsg.h.c = 0xC1; pMsg.h.headcode = 0xBE; pMsg.h.subcode = 0x17; pMsg.h.size = sizeof(pMsg); memcpy(pMsg.szUID, gObj[iIndex].AccountID, 11); memcpy(pMsg.szNAME, gObj[iIndex].Name, 11); pMsg.wServerCode = g_ConfigRead.server.GetGameServerCode() / 20; pMsg.iINDEX = iIndex; pMsg.szUID[10] = 0; pMsg.szNAME[10] = 0; wsDataCli.DataSend((PCHAR) & pMsg, sizeof(pMsg)); } void EGAnsRegHTOfflineGift(PMSG_ANS_REG_HT_OFFLINE_GIFT *lpMsg) { if (!lpMsg) return; if (!lpMsg->iResultCode) { if (gObjIsConnected(lpMsg->iINDEX)) { LPOBJ lpObj = &gObj[lpMsg->iINDEX]; MapC[lpObj->MapNumber].MoneyItemDrop(1000000, lpObj->X, lpObj->Y); } return; } char szAccountID[11] = {0}; char szName[11] = {0}; char szGIFT_NAME[50] = {0}; memset(szAccountID, 0, sizeof(szAccountID)); memset(szName, 0, sizeof(szName)); memset(szGIFT_NAME, 0, sizeof(szGIFT_NAME)); memcpy(szAccountID, lpMsg->szUID, sizeof(szAccountID)); memcpy(szName, lpMsg->szNAME, sizeof(szName)); memcpy(szGIFT_NAME, lpMsg->szGIFT_NAME, sizeof(szGIFT_NAME)); szAccountID[10] = 0; szName[10] = 0; szGIFT_NAME[49] = 0; char szText[256] = {0}; wsprintf(szText, "[������ �������� �̺�Ʈ] %s �Բ��� %s ��ǰ�� ��÷�Ǽ̽��ϴ�.", szName, szGIFT_NAME); GSProtocol.AllSendServerMsg(szText); g_Log.Add("[Hidden TreasureBox Event] [%s][%s] Success to Register OffLine Gift (GIFT:%s)", szAccountID, szName, szGIFT_NAME); } void EGAnsRegLuckyCoin(PMSG_ANS_REG_LUCKYCOIN *lpMsg) { if (!lpMsg) return; PMSG_ANS_LUCKYCOIN_REGISTER pMsg = {0}; PHeadSubSetB((LPBYTE) & pMsg, 0xBF, 0x0C, sizeof(pMsg)); LPOBJ lpObj = &gObj[lpMsg->iIndex]; pMsg.btResult = lpMsg->Result; if (pMsg.btResult == 1) { if (lpObj->pInventory[lpMsg->Pos].IsItem() == TRUE && lpObj->pInventory[lpMsg->Pos].m_Type == ITEMGET(14, 100)) { if (lpObj->pInventory[lpMsg->Pos].m_Durability > 1.0) { lpObj->pInventory[lpMsg->Pos].m_Durability -= 1.0f; GSProtocol.GCItemDurSend2(lpObj->m_Index, lpMsg->Pos, lpObj->pInventory[lpMsg->Pos].m_Durability, 0); } else { gObjInventoryDeleteItem(lpObj->m_Index, lpMsg->Pos); GSProtocol.GCInventoryItemDeleteSend(lpObj->m_Index, lpMsg->Pos, 1); } pMsg.iLuckyCoin = lpMsg->LuckyCoins; lpObj->LuckyCoinCount = lpMsg->LuckyCoins; } else { pMsg.btResult = 0; pMsg.iLuckyCoin = lpMsg->LuckyCoins; } } IOCP.DataSend(lpObj->m_Index, (LPBYTE) & pMsg, pMsg.h.size); lpObj->UseEventServer = FALSE; } void EGAnsLuckyCoinInfo(PMSG_ANS_LUCKYCOIN *lpMsg) { if (!lpMsg) return; PMSG_ANS_LUCKYCOININFO pMsg; PHeadSubSetB((LPBYTE) & pMsg, 0xBF, 0x0B, sizeof(pMsg)); LPOBJ lpObj = &gObj[lpMsg->iIndex]; pMsg.iLuckyCoin = lpMsg->LuckyCoins; lpObj->LuckyCoinCount = lpMsg->LuckyCoins; IOCP.DataSend(lpObj->m_Index, (LPBYTE) & pMsg, pMsg.h.size); lpObj->UseEventServer = FALSE; } void EGAnsSantaCheck(PMSG_ANS_SANTACHECK *lpMsg) { if (!lpMsg) return; LPOBJ lpObj = &gObj[lpMsg->aIndex]; switch (lpMsg->Result) { case 0: if (!lpMsg->UseCount) GSProtocol.GCServerCmd(lpObj->m_Index, 16, 0, 0); else GSProtocol.GCServerCmd(lpObj->m_Index, 16, 1, 0); break; case 1: case 3: GSProtocol.GCServerCmd(lpObj->m_Index, 16, 3, 0); break; case 2: GSProtocol.GCServerCmd(lpObj->m_Index, 16, 2, 0); break; } } void EGReqSantaGift(int aIndex) { if (gObjIsConnected(aIndex) == false) return; PMSG_REQ_SANTAGIFT pMsg; PHeadSubSetB((LPBYTE) & pMsg, 0xBE, 0x21, sizeof(pMsg)); memcpy(pMsg.AccountID, gObj[aIndex].AccountID, 11); pMsg.gGameServerCode = g_ConfigRead.server.GetGameServerCode(); pMsg.aIndex = aIndex; wsDataCli.DataSend((char *) &pMsg, pMsg.h.size); } void EGAnsSantaGift(PMSG_ANS_SANTAGIFT *lpMsg) { if (!lpMsg) return; LPOBJ lpObj = &gObj[lpMsg->aIndex]; switch (lpMsg->Result) { case 0: if (lpObj->m_PlayerData->SantaCount < g_ConfigRead.data.common.XMasSantaFirstPrizeMaxCount) { g_BagManager.SearchAndUseBag(lpObj->m_Index, BAG_EVENT, EVENTBAG_SANTAFIRST, lpObj->m_Index); } else if (lpObj->m_PlayerData->SantaCount < g_ConfigRead.data.common.XMasSantaSecondPrizeMaxCount) { g_BagManager.SearchAndUseBag(lpObj->m_Index, BAG_EVENT, EVENTBAG_SANTASECOND, lpObj->m_Index); } else { g_BagManager.SearchAndUseBag(lpObj->m_Index, BAG_EVENT, EVENTBAG_SANTATHIRD, lpObj->m_Index); } lpObj->m_PlayerData->SantaCount++; g_Log.Add("[X-MAS Event] [AccountID]: %s, [VISITCOUNT]:%d", lpObj->AccountID, lpObj->m_PlayerData->SantaCount); break; case 2: GSProtocol.GCServerCmd(lpObj->m_Index, 16, 2, 0); break; case 1: case 3: GSProtocol.GCServerCmd(lpObj->m_Index, 16, 3, 0); break; } }
37.018082
117
0.499777
millerp
baff6468bd0fdf32c26af1f8bd4ffe5240c1900e
1,254
cpp
C++
src/Compiler/Parsing/parsers/assignment_parser.cpp
joakimthun/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
16
2015-10-12T14:24:45.000Z
2021-07-20T01:56:04.000Z
src/Compiler/Parsing/parsers/assignment_parser.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
null
null
null
src/Compiler/Parsing/parsers/assignment_parser.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
2
2017-11-12T01:39:09.000Z
2021-07-20T01:56:09.000Z
#include "assignment_parser.h" namespace elsa { namespace compiler { std::unique_ptr<Expression> AssignmentParser::parse(ElsaParser* parser, std::unique_ptr<Expression> left) { parser->consume(TokenType::Equals); auto exp = std::make_unique<AssignmentExpression>(); exp->set_left(std::move(left)); assert_valid_assignment(parser, exp->get_left()); exp->set_right(std::move(parser->parse_expression(precedence()))); auto left_type = std::unique_ptr<ElsaType>(parser->type_checker().get_expression_type(exp->get_left())); if(!parser->type_checker().valid_assignment(exp.get())) throw ParsingException(L"Invalid assignment. The right hand side of the expression must be of type '" + left_type->get_name() + L"'", parser->current_token()); if(parser->current_token()->get_type() == TokenType::Semicolon) parser->consume(TokenType::Semicolon); return std::move(exp); } int AssignmentParser::precedence() { return Precedence::Assignment; } void AssignmentParser::assert_valid_assignment(ElsaParser* parser, Expression* left) { if (!parser->type_checker().is_assignable(left)) throw ParsingException(L"Values can only be assigned to local variables", parser->current_token()); } } }
29.857143
163
0.722488
joakimthun
2401252dda1aa447ec8e9897e398065311f960f7
4,931
cpp
C++
examples/01_trafficlight/01_trafficlight.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
10
2021-03-17T17:26:50.000Z
2022-03-30T17:33:23.000Z
examples/01_trafficlight/01_trafficlight.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
1
2022-03-30T16:29:01.000Z
2022-03-30T16:29:01.000Z
examples/01_trafficlight/01_trafficlight.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
null
null
null
// NOTE: For internal testing and will be removed later #include "hsmcpp/hsm.hpp" #include <thread> #include "hsmcpp/logging.hpp" #include "hsmcpp/HsmEventDispatcherGLibmm.hpp" #undef __HSM_TRACE_CLASS__ #define __HSM_TRACE_CLASS__ "01_trafficlight" __HSM_TRACE_PREINIT__(); using namespace std::chrono_literals; using namespace hsmcpp; enum class TrafficLightState { OFF, STARTING, RED, YELLOW, GREEN }; enum class TrafficLightEvent { TURN_ON, TURN_OFF, NEXT_STATE }; class TrafficLight: public HierarchicalStateMachine<TrafficLightState, TrafficLightEvent> { public: TrafficLight() : HierarchicalStateMachine(TrafficLightState::OFF) { registerState<TrafficLight>(TrafficLightState::OFF, this, &TrafficLight::onOff, nullptr, nullptr); registerState<TrafficLight>(TrafficLightState::STARTING, this, &TrafficLight::onStarting, nullptr, nullptr); registerState<TrafficLight>(TrafficLightState::RED, this, &TrafficLight::onRed, nullptr, nullptr); registerState<TrafficLight>(TrafficLightState::YELLOW, this, &TrafficLight::onYellow, nullptr, nullptr); registerState<TrafficLight>(TrafficLightState::GREEN, this, &TrafficLight::onGreen, nullptr, nullptr); registerTransition(TrafficLightState::OFF, TrafficLightState::STARTING, TrafficLightEvent::TURN_ON, nullptr, nullptr); registerTransition(TrafficLightState::STARTING, TrafficLightState::RED, TrafficLightEvent::NEXT_STATE, this, &TrafficLight::onNextStateTransition); registerTransition(TrafficLightState::RED, TrafficLightState::YELLOW, TrafficLightEvent::NEXT_STATE, this, &TrafficLight::onNextStateTransition); registerTransition(TrafficLightState::YELLOW, TrafficLightState::GREEN, TrafficLightEvent::NEXT_STATE, this, &TrafficLight::onNextStateTransition); registerTransition(TrafficLightState::GREEN, TrafficLightState::RED, TrafficLightEvent::NEXT_STATE, this, &TrafficLight::onNextStateTransition); initialize(std::make_shared<HsmEventDispatcherGLibmm>()); } void onNextStateTransition(const VariantVector_t& args) { if (args.size() == 2) { printf("----> onNextStateTransition (args=%d, thread=%d, index=%d)\n", (int)args.size(), (int)args[0].toInt64(), (int)args[1].toInt64()); } else { printf("----> onNextStateTransition (no args)\n"); } std::this_thread::sleep_for(1000ms); } void onOff(const VariantVector_t& args){ printf("----> OFF\n"); } void onStarting(const VariantVector_t& args){ printf("----> onStarting\n"); } void onRed(const VariantVector_t& args){ printf("----> onRed\n"); } void onYellow(const VariantVector_t& args){ printf("----> onYellow\n"); } void onGreen(const VariantVector_t& args){ printf("----> onGreen\n"); } }; Glib::RefPtr<Glib::MainLoop> mMainLoop; TrafficLight* tl = nullptr; void simulate() { int index = 0; printf("[T0] wait 2000 ms...\n"); std::this_thread::sleep_for(2000ms); printf("[T0] starting work...\n"); tl->transition(TrafficLightEvent::TURN_ON); std::this_thread::sleep_for(2000ms); while(true) { tl->transition(TrafficLightEvent::NEXT_STATE); index++; std::this_thread::sleep_for(1000ms); } } void simulateSync1() { int index = 0; printf("[T1] wait 2000 ms...\n"); std::this_thread::sleep_for(2000ms); printf("[T1] starting work...\n"); tl->transition(TrafficLightEvent::TURN_ON); std::this_thread::sleep_for(2000ms); while(true) { bool status; printf("[T1] BEFORE transition\n"); status = tl->transitionEx(TrafficLightEvent::NEXT_STATE, true, true, HSM_WAIT_INDEFINITELY, 1, index); printf("[T1] AFTER transition: %d\n", (int)status); index++; std::this_thread::sleep_for(3000ms); } } void simulateSync2() { int index = 0; printf("[T2] wait 2000 ms...\n"); std::this_thread::sleep_for(2000ms); printf("[T2] starting work...\n"); tl->transition(TrafficLightEvent::TURN_ON); std::this_thread::sleep_for(2000ms); while(true) { bool status; printf("[T2] BEFORE transition\n"); status = tl->transitionEx(TrafficLightEvent::NEXT_STATE, true, true, HSM_WAIT_INDEFINITELY, 2, index); printf("[T2] AFTER transition: %d\n", (int)status); index++; std::this_thread::sleep_for(3000ms); } } int main(const int argc, const char**argv) { __HSM_TRACE_INIT__(); __HSM_TRACE_CALL_ARGS__("01_trafficlight"); Glib::init(); mMainLoop = Glib::MainLoop::create(); tl = new TrafficLight(); std::thread threadSimulate0(simulate); std::thread threadSimulate1(simulateSync1); std::thread threadSimulate2(simulateSync2); mMainLoop->run(); delete tl; tl = nullptr; return 0; }
30.81875
155
0.674914
igor-krechetov
2401acd8c54761bf44155a20c465b48f8a17ca8f
75,347
cpp
C++
isis/src/cassini/apps/cisscal/main.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
1
2022-02-17T01:07:03.000Z
2022-02-17T01:07:03.000Z
isis/src/cassini/apps/cisscal/main.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
isis/src/cassini/apps/cisscal/main.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "Isis.h" #include <algorithm>// sort, unique #include <cmath> #include <cstdlib> #include <iterator>//unique #include <iostream> // unique #include <QString> #include <sstream> #include <vector> #include "Brick.h" #include "Buffer.h" #include "Camera.h" #include "CisscalFile.h" #include "CissLabels.h" #include "Cube.h" #include "DarkCurrent.h" #include "FileName.h" #include "LeastSquares.h" #include "NumericalApproximation.h" #include "Pixel.h" #include "PolynomialUnivariate.h" #include "ProcessByLine.h" #include "Preference.h" #include "PvlGroup.h" #include "SpecialPixel.h" #include "Stretch.h" #include "Table.h" #include "UserInterface.h" #include "IException.h" #include "IString.h" #include <QDir> using namespace Isis; using namespace std; // Working functions and parameters namespace gbl { //global methods void BitweightCorrect(Buffer &in); void Calibrate(vector<Buffer *> &in, vector<Buffer *> &out); void ComputeBias(); void CopyInput(Buffer &in); void CreateBitweightStretch(FileName bitweightTable); FileName FindBitweightFile(); vector<double> OverclockFit(); void Linearize(); void FindDustRingParameters(); FileName FindFlatFile(); void FindCorrectionFactors(); void FindSensitivityCorrection(); void DNtoElectrons(); void FindShutterOffset(); void DivideByAreaPixel(); void FindEfficiencyFactor(QString fluxunits); QString GetCalibrationDirectory(QString calibrationType); //global variables CissLabels *cissLab; Cube *incube; PvlGroup calgrp; Stretch stretch; int numberOfOverclocks; vector <double> bias; vector <vector <double> > bitweightCorrected; //dark subtraction variables vector <vector <double> > dark_DN; // flatfield variables FileName dustFile; FileName dustFile2; FileName mottleFile; double strengthFactor; bool dustCorrection, mottleCorrection, flatCorrection; //DN to Flux variables double trueGain; bool divideByExposure; Brick *offset; double solidAngle; double opticsArea; double sumFactor; double efficiencyFactor; //correction factor variables double correctionFactor; bool sensCorrection; double sensVsTimeCorr; } void IsisMain() { // Initialize Globals UserInterface &ui = Application::GetUserInterface(); gbl::cissLab = new CissLabels(ui.GetCubeName("FROM")); gbl::incube = NULL; gbl::stretch.ClearPairs(); gbl::numberOfOverclocks = 0; gbl::bias.clear(); gbl::dustFile = ""; gbl::mottleFile = ""; gbl::strengthFactor = 1.0; gbl::dustCorrection = false; gbl::mottleCorrection = false; gbl::flatCorrection = false; gbl::trueGain = 1.0; gbl::divideByExposure = false; gbl::offset = NULL; // initialize pointer to null or 0? gbl::solidAngle = 1.0; gbl::opticsArea = 1.0; gbl::sumFactor = 1.0; gbl::efficiencyFactor = 1.0; gbl::correctionFactor = 1.0; gbl::sensCorrection = false; gbl::sensVsTimeCorr = 1.0; // Set up our ProcessByLine objects // we will take 2 passes through the input cube ProcessByLine firstpass; ProcessByLine secondpass; // for the first pass, use the input cube. gbl::incube = firstpass.SetInputCube("FROM"); // CopyInput() or BitweightCorrect() parameter in // for the second pass, set input cube to "FROM" due to requirements of // ProcessByLine that there be at least 1 input buffer before setting the // output buffer, however this cube is not used in the Calibrate method, // instead the bitweightCorrected vector is used as the initial values before // the rest of the calibration steps are performed. gbl::incube = secondpass.SetInputCube("FROM"); // Calibrate() parameter in[0] // we need to set output cube at the beginning of the program to check right // away for CubeCustomization IsisPreference and throw an error, if necessary. Cube *outcube = secondpass.SetOutputCube("TO"); // Calibrate() parameter out[0] // resize 2dimensional vectors gbl::bitweightCorrected.resize(gbl::incube->sampleCount()); gbl::dark_DN.resize(gbl::incube->sampleCount()); for(unsigned int i = 0; i < gbl::bitweightCorrected.size(); i++) { gbl::bitweightCorrected[i].resize(gbl::incube->lineCount()); gbl::dark_DN[i].resize(gbl::incube->lineCount()); } // Add the radiometry group gbl::calgrp.setName("Radiometry"); gbl::calgrp += PvlKeyword("CisscalVersion", "3.9.1"); // The first ProcessByLine pass will either compute bitweight values or copy input values // BITWEIGHT CORRECTION gbl::calgrp += PvlKeyword("BitweightCorrectionPerformed", "Yes"); gbl::calgrp.findKeyword("BitweightCorrectionPerformed").addComment("Bitweight Correction Parameters"); // Bitweight correction is not applied to Lossy-compressed or Table-converted images if(gbl::cissLab->CompressionType() == "Lossy") { gbl::calgrp.findKeyword("BitweightCorrectionPerformed").setValue("No: Lossy compressed"); gbl::calgrp += PvlKeyword("BitweightFile", "Not applicable: No bitweight correction"); firstpass.Progress()->SetText("Lossy compressed: skip bitweight correction as insignificant.\nCopying input image..."); firstpass.StartProcess(gbl::CopyInput); firstpass.EndProcess(); } else if(gbl::cissLab->DataConversionType() == "Table") { gbl::calgrp.findKeyword("BitweightCorrectionPerformed").setValue("No: Table converted"); gbl::calgrp += PvlKeyword("BitweightFile", "Not applicable: No bitweight correction"); firstpass.Progress()->SetText("Table converted: skip bitweight correction as insignificant.\nCopying input image..."); firstpass.StartProcess(gbl::CopyInput); firstpass.EndProcess(); } // Skip bitweight correction for GainState==0, there is no data for this case, // see ground calibration report 5.1.9 Uneven Bit Weighting else if(gbl::cissLab->GainState() == 0) { gbl::calgrp.findKeyword("BitweightCorrectionPerformed").setValue("No: No bitweight calibration file for GainState 0."); gbl::calgrp += PvlKeyword("BitweightFile", "Not applicable: No bitweight correction."); firstpass.Progress()->SetText("No bitweight calibration file for GainState 0: skip bitweight correction.\nCopying input image..."); firstpass.StartProcess(gbl::CopyInput); firstpass.EndProcess(); } else { // Bitweight correction FileName bitweightFile = gbl::FindBitweightFile(); if(!bitweightFile.fileExists()) { // bitweight file not found, stop calibration // Remove the output cube since it will be empty at this point outcube->close(true); throw IException(IException::Io, "Unable to calibrate image. BitweightFile ***" + bitweightFile.expanded() + "*** not found.", _FILEINFO_); } else { gbl::calgrp += PvlKeyword("BitweightFile", bitweightFile.original()); gbl::CreateBitweightStretch(bitweightFile); firstpass.Progress()->SetText("Computing bitweight correction..."); firstpass.StartProcess(gbl::BitweightCorrect); firstpass.EndProcess(); } }// THIS ENDS FIRST PROCESS // Compute global values needed for the rest of the calibration steps //Subtract bias (debias) gbl::ComputeBias(); //Dark current subtraction try { DarkCurrent dark(*gbl::cissLab); gbl::dark_DN = dark.ComputeDarkDN(); gbl::calgrp += PvlKeyword("DarkSubtractionPerformed", "Yes"); gbl::calgrp.findKeyword("DarkSubtractionPerformed").addComment("Dark Current Subtraction Parameters"); gbl::calgrp += PvlKeyword("DarkParameterFile", dark.DarkParameterFile().original()); if(gbl::cissLab->NarrowAngle()) { gbl::calgrp += PvlKeyword("BiasDistortionTable", dark.BiasDistortionTable().original()); } else { gbl::calgrp += PvlKeyword("BiasDistortionTable", "ISSWA: No bias distortion table used"); } } catch(IException &e) { // cannot perform dark current, stop calibration e.print(); // Remove the output cube since it will be empty at this point outcube->close(true); throw IException(e, IException::Unknown, "Unable to calibrate image. Dark current calculations failed.", _FILEINFO_); } //Linearity Correction gbl::Linearize(); //Dust Ring Correction gbl::FindDustRingParameters(); //Flat Field Correction FileName flatFile = gbl::FindFlatFile(); //DN to Flux Correction gbl::DNtoElectrons(); gbl::FindShutterOffset(); gbl::DivideByAreaPixel(); gbl::FindEfficiencyFactor(ui.GetString("UNITS")); //Correction Factor // Set the remaining necessary input cube files for second pass CubeAttributeInput att; gbl::FindCorrectionFactors(); gbl::FindSensitivityCorrection(); if(gbl::flatCorrection) { // Calibrate() parameter in[1] secondpass.SetInputCube(flatFile.original(), att); } if(gbl::dustCorrection) { // Calibrate() parameter in[2] secondpass.SetInputCube(gbl::dustFile.original(), att); } if(gbl::mottleCorrection) { // Calibrate() parameter in[3] secondpass.SetInputCube(gbl::mottleFile.original(), att); } if (gbl::dustCorrection && !gbl::cissLab->AntibloomingOn()) { // Calibrate() parameter in[4] secondpass.SetInputCube(gbl::dustFile2.original(), att); } // this pass will call the Calibrate method secondpass.Progress()->SetText("Calibrating image..."); outcube->putGroup(gbl::calgrp); secondpass.StartProcess(gbl::Calibrate); secondpass.EndProcess(); gbl::calgrp.clear(); return; } //END MAIN /** * This calibration method runs through all calibration steps. * It takes a vector of input buffers that contains the * input image and, if needed, the flat field image, the * dustring correction image, and the mottle correction image. * The vector of output buffers will only contain one element: * the output image. * * @param in Vector of pointers to input buffers for the second * process in IsisMain() * @param out Vector of pointers to output buffer. * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-05-27 Jeannie Walldren - Added polarization * factor correction. Updated ConstOffset value per * new idl cisscal version, 3.6. * @history 2017-06-08 Cole Neubauer - Added dustfile2 correction. * Updated ConstOffset value to match new idl cisscal version, 3.8. * @history 2019-08-14 Kaitlyn Lee - Removed jupiter correction. Added * check for ShutterStateId, and if it is Disabled, * do not subtract an offset from the exposure time. * Added Sensitivity vs Time Correction after * correction factors. * Matches cisscal version 3.9.1. */ void gbl::Calibrate(vector<Buffer *> &in, vector<Buffer *> &out) { Buffer *flat = 0; Buffer *dustCorr = 0; Buffer *mottleCorr = 0; Buffer *dustCorr2 = 0; if(gbl::flatCorrection) { flat = in[1]; } if(gbl::dustCorrection) { dustCorr = in[2]; dustCorr2= in[4]; if(gbl::mottleCorrection) { mottleCorr = in[3]; } } Buffer &outLine = *out[0]; //get line index of output int lineIndex = outLine.Line() - 1; for(unsigned int sampIndex = 0; sampIndex < gbl::bitweightCorrected.size(); sampIndex++) { if(IsValidPixel(gbl::bitweightCorrected[sampIndex][lineIndex])) { /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 1) set output to bitweight corrected values outLine[sampIndex] = bitweightCorrected[sampIndex][lineIndex]; /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 2) remove bias (debias) if(gbl::numberOfOverclocks) { outLine[sampIndex] = outLine[sampIndex] - gbl::bias[lineIndex]; } else { outLine[sampIndex] = outLine[sampIndex] - gbl::bias[0]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // idl cisscal step "REMOVE 2-HZ NOISE" skipped // -- this is more of a filter than calibration /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 3) remove dark current outLine[sampIndex] = outLine[sampIndex] - gbl::dark_DN[sampIndex][lineIndex]; /////////////////////////////////////////////////////////////////////////////////////////////////////////// // idl cisscal step "ANTI-BLOOMING CORRECTION" skipped // -- this is more of a filter than calibration /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 4) linearity correction (linearize) if(outLine[sampIndex] < 0) { outLine[sampIndex] = (outLine[sampIndex]) * (gbl::stretch.Map(0)); } else { outLine[sampIndex] = (outLine[sampIndex]) * (gbl::stretch.Map((int) outLine[sampIndex])); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 5) flatfield correction // 5a1: dust ring correction if(gbl::dustCorrection) { outLine[sampIndex] = (outLine[sampIndex]) * ((*dustCorr)[sampIndex]); if (!gbl::cissLab->AntibloomingOn()) { outLine[sampIndex] = (outLine[sampIndex] * ((*dustCorr2)[sampIndex])); } // 5a2: mottle correction if(gbl::mottleCorrection) { outLine[sampIndex] = (outLine[sampIndex]) * (1 - ((gbl::strengthFactor) * ((*mottleCorr)[sampIndex]) / 1000.0)); } } // 5b: divide by flats if(gbl::flatCorrection) { if(Isis::IsSpecial((*flat)[sampIndex])){ (*flat)[sampIndex] = 1; } outLine[sampIndex] = outLine[sampIndex] / ((*flat)[sampIndex]); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 6) convert DN to flux // 6a DN to Electrons outLine[sampIndex] = outLine[sampIndex] * gbl::trueGain; // 6b Divide By Exposure Time // JPL confirm that these values must be subtracted thus: if(gbl::divideByExposure) { double exposureTime = gbl::cissLab->ExposureDuration() - (*gbl::offset)[gbl::offset->Index(sampIndex+1, 1, 1)]; // IDL documentation: // Need to develop way to subtract constant offset discussed in // section 4.3 of Ground Calibration Report. Right now just use 1 ms // for all cases. // CORRECTION: New analysis of Vega images points to a value more like // 2.85 ms (correct to within about 0.05 ms for the NAC, less certain // for the WAC. Use this until better data available. (12/1/2005 - BDK) // UPDATE: Used azimuthal ring scans to pin down WAC to around 1.8 ms. // (1/18/2006 - BDK) // UPDATE #2: S58 SPICA data gives WAC shutter offset of about 2.86 ms. // (9/21/2010 - BDK) // UPDATE #3: Rhea SATCAL obs from rev 163 give NAC offset of 2.74 and // WAC offset of 2.67 ms, much less noisy results than using stars. // (1/31/2013 - BDK) // UPDATE #4: From S100 Vega (WAC) and 77/78 Tau (NAC): NAC offset of // 2.51, WAC offset of 2.63, but analysis far more noisy than for Rhea // so keep previous values. (8/4/2017 - BDK) double ConstOffset; if(gbl::cissLab->ShutterStateId() != "Disabled") { if(gbl::cissLab->InstrumentId() == "ISSNA") { ConstOffset = 2.75; } else { ConstOffset = 2.67; } exposureTime = exposureTime - ConstOffset; } outLine[sampIndex] = outLine[sampIndex] * 1000 / exposureTime; // 1000 to scale ms to seconds } // 6c Divide By Area Pixel outLine[sampIndex] = outLine[sampIndex] * gbl::sumFactor / (gbl::solidAngle * gbl::opticsArea); // 6d Divide By Efficiency outLine[sampIndex] = outLine[sampIndex] / gbl::efficiencyFactor; /////////////////////////////////////////////////////////////////////////////////////////////////////////// // STEP 7) correction factors // 7a Correction Factors outLine[sampIndex] = outLine[sampIndex] / gbl::correctionFactor; if (outLine[sampIndex] < 0) { outLine[sampIndex] = 0; } // 7b Sensitivity vs Time Correction if(gbl::sensCorrection) { outLine[sampIndex] = outLine[sampIndex] * gbl::sensVsTimeCorr; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// } else if (IsSpecial(bitweightCorrected[sampIndex][lineIndex])) { outLine[sampIndex] = bitweightCorrected[sampIndex][lineIndex]; } else { outLine[sampIndex] = bitweightCorrected[sampIndex][lineIndex]; if (outLine[sampIndex] < 0) { outLine[sampIndex] = 0; } } } return; } //=====4 Bitweight Methods=======================================================================// // These methods are modelled after IDL CISSCAL's cassimg_bitweightcorrect.pro /** * The purpose of this method is to copy the input to output if * no bitweight correction occurs. * * @param in Input buffer for the first process in IsisMain() * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2008-12-22 Jeannie Walldren - Fixed bug in calls * to resize() method. * @history 2009-01-26 Jeannie Walldren - Moved resizing of * 2-dimensional vectors to main method */ void gbl::CopyInput(Buffer &in) { // find line index int lineIndex = in.Line() - 1; for(int sampIndex = 0; sampIndex < in.size(); sampIndex++) { // assign input value to image vector gbl::bitweightCorrected[sampIndex][lineIndex] = in[sampIndex]; } return; } /** * This method is modelled after IDL CISSCAL's * cassimg_bitweightcorrect.pro. The purpose is to correct the * image for uneven bit weights. This is done using one of * several tables developed from the ground calibration * exercises table depends on InstrumentId, GainModeId, and * OpticsTemperature. * * @param in Input buffer for the first process in IsisMain() * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-01-26 Jeannie Walldren - Moved resizing of * 2-dimensional vectors to main method */ void gbl::BitweightCorrect(Buffer &in) { // find line index int lineIndex = in.Line() - 1; // loop through samples of this line for(int sampIndex = 0; sampIndex < in.size(); sampIndex++) { // map bitweight corrected image output values to buffer input values if(IsValidPixel(in[sampIndex])) { gbl::bitweightCorrected[sampIndex][lineIndex] = gbl::stretch.Map(in[sampIndex]); } else { gbl::bitweightCorrected[sampIndex][lineIndex] = in[sampIndex]; } } return; } /** * This method sets up the strech for the conversion from file. * It is used by the BitweightCorrect() method to map LUT * values. * * @param bitweightTable Name of the bitweight table for this * image. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ void gbl::CreateBitweightStretch(FileName bitweightTable) { CisscalFile *stretchPairs = new CisscalFile(bitweightTable.original()); // Create the stretch pairs double stretch1 = 0, stretch2; gbl::stretch.ClearPairs(); for(int i = 0; i < stretchPairs->LineCount(); i++) { QString line; stretchPairs->GetLine(line); line = line.simplified().trimmed(); QStringList tokens = line.split(QRegExp("[, ]"), QString::SkipEmptyParts); foreach (QString token, tokens) { stretch2 = toDouble(token); gbl::stretch.AddPair(stretch1, stretch2); stretch1 = stretch1 + 1.0; } } stretchPairs->Close(); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_bitweightcorrect.pro. The purpose is to find the * look up table file name for this image. * * The table to be used depends on: * Camera NAC or WAC * GainState 1, 2 or 3 <=> GainModeId 95, 29, or 12 Optics temp. -10, +5 or * +25 * * @return <B>FileName</B> Name of the bitweight file * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ FileName gbl::FindBitweightFile() { // Get the directory where the CISS bitweight directory is QString bitweightName; if(gbl::cissLab->NarrowAngle()) { bitweightName += "nac"; } else { bitweightName += "wac"; } QString gainState(toString(gbl::cissLab->GainState())); bitweightName = bitweightName + "g" + gainState; if(gbl::cissLab->FrontOpticsTemp() < -5.0) { bitweightName += "m10_bwt.tab"; } else if(gbl::cissLab->FrontOpticsTemp() < 25.0) { bitweightName += "p5_bwt.tab"; } else { bitweightName += "p25_bwt.tab"; } return FileName(gbl::GetCalibrationDirectory("bitweight") + bitweightName); } //=====End Bitweight Methods=====================================================================// //=====2 Debias Methods============================================================================// //These methods are modelled after IDL CISSCAL's cassimg_debias.pro /** * This method is modelled after IDL CISSCAL's * cassimg_debias.pro. The purpose is to compute the bias * (zero-exposure DN level of CCD chip) to be subtracted in the * Calibrate() method. * There are two ways to do this * 1. (DEFAULT) using overclocked pixel array taken out of * binary line prefix * 2. subtract BiasMeanStrip value found in labels * * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-05-27 Jeannie Walldren - Commented out table * if-statement as done idl cisscal version 3.6. * @history 2019-08-14 Kaitlyn Lee - Added check for a corrupt * bias strip mean to match cisscal version 3.9.1. */ void gbl::ComputeBias() { gbl::calgrp += PvlKeyword("BiasSubtractionPerformed", "Yes"); gbl::calgrp.findKeyword("BiasSubtractionPerformed").addComment("Bias Subtraction Parameters"); QString fsw(gbl::cissLab->FlightSoftwareVersion()); double flightSoftwareVersion; if(fsw == "Unknown") { flightSoftwareVersion = 0.0;// cassimg_readlabels.pro sets this to 1.3, we treat this as 1.2??? } else { flightSoftwareVersion = toDouble(fsw); } // check overclocked pixels exist if(gbl::cissLab->CompressionType() != "Lossy") { if(flightSoftwareVersion < 1.3) { // (1.2=CAS-ISS2 or Unknown=0.0=CAS-ISS) gbl::numberOfOverclocks = 1; } else { //if(1.3=CAS-ISS3 or 1.4=CAS-ISS4) gbl::numberOfOverclocks = 2; } gbl::calgrp += PvlKeyword("BiasSubtractionMethod", "Overclock fit"); } // otherwise overclocked pixels are invalid and must use bias strip mean where possible else { // overclocks array is corrupt for lossy images (see cassimg_readvic.pro) #if 0 // 2009-04-27 Jeannie Walldren // following code comment out in new idl cisscal version, 3.6: if(gbl::cissLab->DataConversionType() == "Table") { // Lossy + Table = no debias gbl::calgrp.findKeyword("BiasSubtractionPerformed").setValue("No: Table converted and Lossy compressed"); gbl::calgrp += PvlKeyword("BiasSubtractionMethod", "Not applicable: No bias subtraction"); gbl::calgrp += PvlKeyword("NumberOfOverclocks", "Not applicable: No bias subtraction"); gbl::bias.resize(1); gbl::bias[0] = 0.0; return; } #endif // according to SIS if 1.2 or 1.3 and Lossy, ignore bias strip mean - invalid data if(flightSoftwareVersion <= 1.3) { // Lossy + 1.2 or 1.3 = no debias gbl::calgrp.findKeyword("BiasSubtractionPerformed").setValue("No: Lossy compressed on CAS-ISS2 or CAS-ISS3"); gbl::calgrp += PvlKeyword("BiasSubtractionMethod", "Not applicable: No bias subtraction"); gbl::calgrp += PvlKeyword("NumberOfOverclocks", "Not applicable: No bias subtraction"); gbl::bias.resize(1); gbl::bias[0] = 0.0; return; } gbl::calgrp += PvlKeyword("BiasSubtractionMethod", "Bias strip mean"); gbl::numberOfOverclocks = 0;//overclocks array is corrupt for lossy images } //Choose bias subtraction method if(gbl::numberOfOverclocks) { // use overclocked pixels as default gbl::bias = gbl::OverclockFit(); } else { // use BiasStripMean in image label if can't use overclock // Corrupt bias strip mean if(gbl::cissLab->BiasStripMean() < 0.0) { gbl::calgrp.findKeyword("BiasSubtractionPerformed").setValue("No: Bias strip mean value corrupt."); gbl::calgrp += PvlKeyword("BiasSubtractionMethod", "Not applicable: No bias subtraction"); gbl::calgrp += PvlKeyword("NumberOfOverclocks", "Not applicable: No bias subtraction"); gbl::bias.resize(1); gbl::bias[0] = 0.0; return; } gbl::bias.resize(1); gbl::bias[0] = gbl::cissLab->BiasStripMean(); } gbl::calgrp += PvlKeyword("NumberOfOverclocks", toString(gbl::numberOfOverclocks)); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_define.pro method, CassImg::OverclockAvg(). This * access function computes line-averaged overclocked pixel * values and returns a linear fit of these values. * * @return <B>vector <double> </B> Results of linear fit * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ vector<double> gbl::OverclockFit() { vector< vector <double> > overclocks; // Read overclocked info from table saved during ciss2isis // table should have 3 columns: // -col 3 is the "average" of the overclocked pixels // -if there are 2 overclocks, columns 1 and 2 contain them // -otherwise column 1 is all null and we use column 2 Table overClkTable = gbl::incube->readTable("ISS Prefix Pixels"); for(int i = 0; i < overClkTable.Records(); i++) { overclocks.push_back(overClkTable[i]["OverclockPixels"]); } vector<double> overclockfit, eqn, avg; PolynomialUnivariate poly(1); LeastSquares lsq(poly); //get overclocked averages for(unsigned int i = 0; i < overclocks.size(); i++) { avg.push_back(overclocks[i][2]); } if(avg[0] > 2 * avg[1]) { avg[0] = avg[1]; } // initialize eqn eqn.push_back(0.0); for(unsigned int i = 0; i < avg.size(); i++) { // if avg is a special pixel, we must change to integer values so we don't throw off the linear fit if(avg[i] == Isis::NULL2) { avg[i] = 0; } if(avg[i] == Isis::HIGH_REPR_SAT2) { if(gbl::cissLab->DataConversionType() == "Table") { avg[i] = 4095; } else { avg[i] = 255; } } eqn[0] = (double)(i + 1); // add to least squares variable lsq.AddKnown(eqn, avg[i]); } // solve linear fit lsq.Solve(LeastSquares::QRD); for(unsigned int i = 0; i < overclocks.size(); i++) { eqn[0] = (double)(i + 1); overclockfit.push_back(lsq.Evaluate(eqn)); } //return a copy of the vector of linear fitted overclocks // this will be used as the bias return overclockfit; } //=====End Debias Methods========================================================================// //=====Subtract Dark Methods=====================================================================// // THESE ARE CONTAINED IN THE CLASS DARKCURRENT //=====End Subtract Dark Methods=================================================================// //=====1 Linearize Methods=========================================================================// //This method is modelled after IDL CISSCAL's cassimg_linearise.pro /** * This method is modelled after IDL CISSCAL's * cassimg_linearise.pro. The purpose is to correct the image * for non-linearity. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ void gbl::Linearize() { // These are the correction factor tables from the referenced documents // For each gain state there are a list of DNs where measurements // were performed and the corresponding correction factors C // The correction is then performed as DN'=DN*Cdn // Where Cdn is an interpolation for C from the tabulated values QString lut; int gainState = gbl::cissLab->GainState(); if(gbl::cissLab->NarrowAngle()) { switch(gainState) { case 0: lut = "NAC0.lut"; break; case 1: lut = "NAC1.lut"; break; case 2: lut = "NAC2.lut"; break; case 3: lut = "NAC3.lut"; break; default: throw IException(IException::Unknown, "Input file contains invalid GainState. See Software Interface Specification (SIS), Version 1.1, page 86.", _FILEINFO_); } } else { switch(gainState) { case 0: lut = "WAC0.lut"; break; case 1: lut = "WAC1.lut"; break; case 2: lut = "WAC2.lut"; break; case 3: lut = "WAC3.lut"; break; default: throw IException(IException::Unknown, "Input file contains invalid GainState. See Software Interface Specification (SIS), Version 1.1, page 86.", _FILEINFO_); } } vector <double> DN_VALS, C_VALS; // Get the directory where the CISS linearize directory is. FileName linearLUT(gbl::GetCalibrationDirectory("linearize") + lut); if(!linearLUT.fileExists()) { throw IException(IException::Io, "Unable to calibrate image. LinearityCorrectionTable ***" + linearLUT.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("LinearityCorrectionPerformed", "Yes"); gbl::calgrp.findKeyword("LinearityCorrectionPerformed").addComment("Linearity Correction Parameters"); gbl::calgrp += PvlKeyword("LinearityCorrectionTable", linearLUT.original()); TextFile *pairs = new TextFile(linearLUT.original()); for(int i = 0; i < pairs->LineCount(); i++) { QString line; pairs->GetLine(line, true); line = line.simplified(); QStringList tokens = line.split(" "); DN_VALS.push_back(toDouble(tokens.takeFirst())); C_VALS.push_back(toDouble(tokens.takeFirst())); } pairs->Close(); // ASSUMPTION: C will not change significantly over fractional DN // If this is not the case, then can perform simple second interpolation // between DNs while mapping LUT onto the image NumericalApproximation linearInterp(NumericalApproximation::Linear); for(unsigned int i = 0; i < DN_VALS.size(); i++) { linearInterp.AddData(DN_VALS[i], C_VALS[i]); } // Create the stretch pairs gbl::stretch.ClearPairs(); for(unsigned int i = 0; i < 4096; i++) { double j = linearInterp.Evaluate((double) i); gbl::stretch.AddPair(i, j); } // Map LUT onto image, defending against out-of-range DN values return; } //=====End Linearize Methods=====================================================================// //=====2 Flatfield Methods=========================================================================// // These methods are modelled after IDL CISSCAL's cassimg_dustringcorrect.pro and cassimg_dividebyflats.pro /** * This method is modelled after IDL CISSCAL's * cassimg_dustringcorrect.pro. The purpose is to find the * files and value needed to perform dustring correction and * mottle correction: dustFile, mottleFile, strengthFactor. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-05-27 Jeannie Walldren - Changed to read * effective wavelength from 5th column of file * (rather than 3rd) since effective wavelength file * updated with new idl cisscal version, 3.6. Added * effective wavelength to calibration group in * labels. * @history 2019-08-14 Kaitlyn Lee - Added check for * ShutterStateId to disable dust ring correction. * Matches cisscal version 3.9.1. */ void gbl::FindDustRingParameters() { // No dustring or mottle correction for WAC if(gbl::cissLab->WideAngle()) { gbl::dustCorrection = false; gbl::mottleCorrection = false; gbl::calgrp += PvlKeyword("DustRingCorrectionPerformed", "No: ISSWA"); gbl::calgrp.findKeyword("DustRingCorrectionPerformed").addComment("DustRing Correction Parameters"); gbl::calgrp += PvlKeyword("DustRingFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("MottleCorrectionPerformed", "No: dustring correction"); gbl::calgrp += PvlKeyword("MottleFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("EffectiveWavelengthFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("StrengthFactor", "Not applicable: No dustring correction"); return; } // Disable dust ring and mottle correction if ShutterStateId is Disabled if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::dustCorrection = false; gbl::mottleCorrection = false; gbl::calgrp += PvlKeyword("DustRingCorrectionPerformed", "No: ShutterStateId is Disabled."); gbl::calgrp.findKeyword("DustRingCorrectionPerformed").addComment("DustRing Correction Parameters"); gbl::calgrp += PvlKeyword("DustRingFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("MottleCorrectionPerformed", "No: dustring correction"); gbl::calgrp += PvlKeyword("MottleFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("EffectiveWavelengthFile", "Not applicable: No dustring correction"); gbl::calgrp += PvlKeyword("StrengthFactor", "Not applicable: No dustring correction"); return; } // dustring correct for NAC gbl::dustCorrection = true; gbl::calgrp += PvlKeyword("DustRingCorrectionPerformed", "Yes"); gbl::calgrp.findKeyword("DustRingCorrectionPerformed").addComment("DustRing Correction Parameters"); // needs to check directory for current epochs and compare double imgNumber = gbl::cissLab->ImageNumber(); long largestEpochFileNum = 0; QStringList fileList = QDir(gbl::GetCalibrationDirectory("dustring")).entryList(); for(int i = 0; i < fileList.count(); i++){ long currentEpoch = FileName(fileList[i]).baseName().mid(13, 10).toInt(); if (currentEpoch > largestEpochFileNum && currentEpoch <= imgNumber) { largestEpochFileNum = currentEpoch; } } // get name of dust file gbl::dustFile = (gbl::GetCalibrationDirectory("dustring") + "nac_dustring_" + QString::number(largestEpochFileNum) + "." + gbl::cissLab->InstrumentModeId() + ".cub"); if(!gbl::dustFile.fileExists()) { // dustring file not found, assume file uses old dustring files gbl::dustFile = (gbl::GetCalibrationDirectory("dustring") + "nac_dustring_venus." + gbl::cissLab->InstrumentModeId() + ".cub"); if(!gbl::dustFile.fileExists()) { // dustring file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. DustRingFile ***" + gbl::dustFile.expanded() + "*** not found.", _FILEINFO_); } } gbl::calgrp += PvlKeyword("DustRingFile", gbl::dustFile.original()); // if anti-blooming correction is off correct ring at sample=887, line=388 if (!gbl::cissLab->AntibloomingOn()) { gbl::dustFile2 = (gbl::GetCalibrationDirectory("dustring") + "nac_dustring_aboff" + "." + gbl::cissLab->InstrumentModeId() +".cub"); if(!gbl::dustFile2.fileExists()) { // dustring file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. DustRingFile2 ***" + gbl::dustFile2.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("DustRingFile2", gbl::dustFile2.original()); } // No Mottling correction for images before sclk=1444733393: (i.e., 2003-286T10:28:04) if(gbl::cissLab->ImageNumber() < 1455892746) { gbl::mottleFile = ""; gbl::mottleCorrection = false; gbl::calgrp += PvlKeyword("MottleCorrectionPerformed", "No: Image before 2003-286T10:28:04"); gbl::calgrp += PvlKeyword("MottleFile", "Not applicable: No mottle correction"); gbl::calgrp += PvlKeyword("EffectiveWavelengthFile", "Not applicable: No mottle correction"); gbl::calgrp += PvlKeyword("StrengthFactor", "Not applicable: No mottle correction"); return; } // Mottling correction for images after 2003-286T10:28:04 gbl::mottleFile = (gbl::GetCalibrationDirectory("dustring") + "nac_mottle_1444733393."+ gbl::cissLab->InstrumentModeId() + ".cub"); if(!gbl::mottleFile.fileExists()) { // mottle file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. MottleFile ***" + gbl::mottleFile.expanded() + "*** not found.", _FILEINFO_); } gbl::mottleCorrection = true; gbl::calgrp += PvlKeyword("MottleCorrectionPerformed", "Yes"); gbl::calgrp += PvlKeyword("MottleFile", gbl::mottleFile.original()); // determine strength factor, need effective wavelength of filter vector <int> filterIndex(2); filterIndex[0] = gbl::cissLab->FilterIndex()[0]; filterIndex[1] = gbl::cissLab->FilterIndex()[1]; if((filterIndex[0] == 17 || filterIndex[0] == 21 || filterIndex[0] == 22 || filterIndex[0] == 23 \ || filterIndex[0] == 35) && filterIndex[1] == 18) { //filter combo CL1 or P0 or P60 or P120 or IRP0/CL2 filterIndex[0] = -1; } if((filterIndex[0] < 17 && filterIndex[1] < 17) || (filterIndex[0] >= 17 && filterIndex[1] >= 17)) { gbl::strengthFactor = 0.0; // use effective wavelength to estimate strength factor: FileName effectiveWavelength(gbl::GetCalibrationDirectory("efficiency") + "na_effwl.tab"); if(!effectiveWavelength.fileExists()) { // effectivewavelength file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. EffectiveWavelengthFile ***" + effectiveWavelength.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("EffectiveWavelengthFile", effectiveWavelength.original()); CisscalFile *effwlDB = new CisscalFile(effectiveWavelength.original()); QString col1, col2, col3, col4, col5; double effwl; for(int i = 0; i < effwlDB->LineCount(); i++) { QString line; effwlDB->GetLine(line); line = line.simplified(); QStringList cols = line.split(" "); col1 = cols.takeFirst(); if(col1 == gbl::cissLab->FilterName()[0]) { col2 = cols.takeFirst(); if(col2 == gbl::cissLab->FilterName()[1]) { col3 = cols.takeFirst(); // central wavelength of filter combo col4 = cols.takeFirst(); // full-width at half-maximum (FWHM) of filter combo col5 = cols.takeFirst(); // effective wavelength if(col5 == "") { // Couldn't find a match in the database gbl::calgrp.findKeyword("MottleCorrectionPerformed").setValue("Yes: EffectiveWavelengthFile contained no factor for filter combination, used strengthFactor of 1.0"); gbl::strengthFactor = 1.0; } else { effwl = toDouble(col5); gbl::calgrp += PvlKeyword("EffectiveWavelength", toString(effwl)); gbl::strengthFactor = 1.30280 - 0.000717552 * effwl; } break; } else { continue; } } else { continue; } } effwlDB->Close(); if(gbl::strengthFactor == 0.0) { gbl::calgrp.findKeyword("MottleCorrectionPerformed").setValue("Yes: EffectiveWavelengthFile contained no factor for filter combination, used strengthFactor of 1.0"); gbl::strengthFactor = 1.0; } } else {//if(filterIndex[0] > 17 || filterIndex[1] > 17 ) gbl::calgrp += PvlKeyword("EffectiveWavelengthFile", "No effective wavelength file used"); switch(filterIndex[0]) { case 0: gbl::strengthFactor = 1.119; break; case 1: gbl::strengthFactor = 1.186; break; case 3: gbl::strengthFactor = 1.00; break; case 6: gbl::strengthFactor = 0.843; break; case 8: gbl::strengthFactor = 0.897; break; case 10: gbl::strengthFactor = 0.780; break; case -1: gbl::strengthFactor = 0.763; break; default: switch(filterIndex[1]) { case 2: gbl::strengthFactor = 1.069; break; case 4: gbl::strengthFactor = 0.833; break; case 5: gbl::strengthFactor = 0.890; break; case 7: gbl::strengthFactor = 0.997; break; case 9: gbl::strengthFactor = 0.505; break; case 11: gbl::strengthFactor = 0.764; break; case 12: gbl::strengthFactor = 0.781; break; case 13: gbl::strengthFactor = 0.608; break; case 14: gbl::strengthFactor = 0.789; break; case 15: gbl::strengthFactor = 0.722; break; case 16: gbl::strengthFactor = 0.546; break; default: throw IException(IException::Unknown, "Input file contains invalid FilterName. See Software Interface Specification (SIS) Appendix A, Table 8.2.", _FILEINFO_); } } } gbl::calgrp += PvlKeyword("StrengthFactor", toString(gbl::strengthFactor)); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_dividebyflats.pro. The purpose is to find the flat * field file needed to correct the image for sensitivity * variations across the field by dividing by flat field image. * * @return <B>FileName</B> Name of the flat file for this image. * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2019-08-14 Kaitlyn Lee - Added check for * ShutterStateId to disable flat field correction. * Matches cisscal version 3.9.1. */ FileName gbl::FindFlatFile() { // Disable flat field correction if ShutterStateId is Disabled if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::calgrp += PvlKeyword("FlatfieldCorrectionPerformed", "No: ShutterStateId is Disabled."); gbl::calgrp.findKeyword("FlatfieldCorrectionPerformed").addComment("Flatfield Correction Parameters"); gbl::calgrp += PvlKeyword("SlopeDataBase", "Not applicable: No flat field correction"); gbl::flatCorrection = false; return ""; } // There is a text database file in the slope files directory // that maps filter combinations (and camera temperature) // to the corresponding slope field files. // according to slope_info.txt, slope_db_1 is original, slope_db_2 is the best and slope_db_3 is newest but has some issues FileName flatFile; FileName slopeDatabaseName(gbl::GetCalibrationDirectory("slope") + "slope_db_2.tab"); if(!slopeDatabaseName.fileExists()) { // slope database not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. SlopeDataBase ***" + slopeDatabaseName.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("FlatfieldCorrectionPerformed", "Yes"); gbl::calgrp.findKeyword("FlatfieldCorrectionPerformed").addComment("Flatfield Correction Parameters"); gbl::calgrp += PvlKeyword("SlopeDataBase", slopeDatabaseName.original()); gbl::flatCorrection = true; // Find the best-match flat file // Choose a nominal optics temp name as per ISSCAL QString frontOpticsTemp(""); if(gbl::cissLab->FrontOpticsTemp() < -5.0) { frontOpticsTemp += "m10"; } else if(gbl::cissLab->FrontOpticsTemp() < 25.0) { frontOpticsTemp += "p5"; } else { frontOpticsTemp += "p25"; } // Require match for instrument, temperature range name, Filter1, filter2 CisscalFile *slopeDB = new CisscalFile(slopeDatabaseName.original()); QString col1, col2, col3, col4, col5, col6, col7, col8; for(int i = 0; i < slopeDB->LineCount(); i++) { QString line; slopeDB->GetLine(line); //assigns value to line line = line.simplified(); QStringList cols = line.split(" "); cols.replaceInStrings(QRegExp("(^'|'$)"), ""); col1 = cols.takeFirst(); if(col1 == gbl::cissLab->InstrumentId()) { col2 = cols.takeFirst(); if((col2 == frontOpticsTemp) || (gbl::cissLab->WideAngle())) { col3 = cols.takeFirst(); if(col3 == gbl::cissLab->FilterName()[0]) { col4 = cols.takeFirst(); if(col4 == gbl::cissLab->FilterName()[1]) { col5 = cols.takeFirst();// col5 = gainstate (not used) col6 = cols.takeFirst();// col6 = antiblooming state (not used) col7 = cols.takeFirst();// col7 = file number (not used) col8 = cols.takeFirst();// col8 = slope file name break; } else { continue; } } else { continue; } } else { continue; } } else { continue; } } slopeDB->Close(); if(col8 == "") { // error in slope database, stop calibration // Couldn't find a match in the database throw IException(IException::Io, "Unable to calibrate image. SlopeDataBase contained no factor for combination:" + gbl::cissLab->InstrumentId() + ":" + frontOpticsTemp + ":" + gbl::cissLab->FilterName()[0] + ":" + gbl::cissLab->FilterName()[1] + ".", _FILEINFO_); } //Column 8 contains version of slopefile from which our flatfiles are derived int j = col8.indexOf("."); //attatch version number to "flat" by skipping // the first 5 characters("SLOPE") and skipping // any thing after "." ("IMG") col8 = "flat" + col8.mid(5, (j - 5) + 1); flatFile = (gbl::GetCalibrationDirectory("slope/flat") + col8 + gbl::cissLab->InstrumentModeId() + ".cub"); gbl::calgrp += PvlKeyword("FlatFile", flatFile.original()); if(!flatFile.fileExists()) { // flat file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. FlatFile ***" + flatFile.expanded() + "*** not found.", _FILEINFO_); } return flatFile; } //=====End Flatfield Methods=====================================================================// //=====5 Convert DN to Flux Methods================================================================// // These methods are modelled after IDL CISSCAL's cassimg_dntoelectrons.pro, cassimg_dividebyexpot.pro, // cassimg_dividebyareapixel.pro, cassimg_dividebyefficiency.pro /** * This method is modelled after IDL CISSCAL's * cassimg_dntoelectrons.pro. The purpose is to find the true * gain needed to multiply image by gain constant (convert DN to * electrons). * * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-05-27 Jeannie Walldren - Removed return * statement and added else statement so that the * TrueGain keyword is added in any case. */ void gbl::DNtoElectrons() { gbl::calgrp += PvlKeyword("DNtoFluxPerformed", "Yes"); gbl::calgrp.findKeyword("DNtoFluxPerformed").addComment("DN to Flux Parameters"); gbl::calgrp += PvlKeyword("DNtoElectrons", "Yes"); // Gain used for an image is documented by the GainModID attribute // of the image. Nominal values are as follow: // // Attribute Gain Usual Nominal Gain // Value state mode (e- per DN) // "1400K" 0 SUM4 215 // "400K" 1 SUM2 95 // "100K" 2 FULL 29 // "40K" 3 FULL 12 if(gbl::cissLab->NarrowAngle()) { switch(gbl::cissLab->GainState()) { case 0: gbl::trueGain = 30.27 / 0.135386; break; case 1: gbl::trueGain = 30.27 / 0.309569; break; case 2: gbl::trueGain = 30.27 / 1.0; break; case 3: gbl::trueGain = 30.27 / 2.357285; break; default: // invalid gainstate, unable to convert DN to electrons, stop calibration throw IException(IException::Unknown, "Input file contains invalid GainState. See Software Interface Specification (SIS), Version 1.1, page 86.", _FILEINFO_); } } else { switch(gbl::cissLab->GainState()) { case 0: gbl::trueGain = 27.68 / 0.125446; break; case 1: gbl::trueGain = 27.68 / 0.290637; break; case 2: gbl::trueGain = 27.68 / 1.0; break; case 3: gbl::trueGain = 27.68 / 2.360374; break; default: // invalid gainstate, unable to convert DN to electrons, stop calibration throw IException(IException::Unknown, "Input file contains invalid GainState. See Software Interface Specification (SIS), Version 1.1, page 86.", _FILEINFO_); } } gbl::calgrp += PvlKeyword("TrueGain", toString(gbl::trueGain)); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_dividebyexpot.pro. The purpose is to find the * shutter offset needed to divide a Cassini image by corrected * exposure time, correcting for shutter offset effects (sample * dependency of actual exposure time). * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ void gbl::FindShutterOffset() { // Don't do this for zero-exposure images! if(gbl::cissLab->ExposureDuration() == 0.0) { // exposuretime = 0, stop calibration throw IException(IException::Unknown, "Unable to calibrate image. Cannot divide by exposure time for zero exposure image.", _FILEINFO_); } gbl::calgrp += PvlKeyword("DividedByExposureTime", "Yes"); gbl::divideByExposure = true; // Define whereabouts of shutter offset files QString offsetFileName(""); if(gbl::cissLab->NarrowAngle()) { offsetFileName += (gbl::GetCalibrationDirectory("offset") + "nacfm_so_"); } else { offsetFileName += (gbl::GetCalibrationDirectory("offset") + "wacfm_so_"); } if(gbl::cissLab->FrontOpticsTemp() < -5.0) { offsetFileName += "m10."; } else if(gbl::cissLab->FrontOpticsTemp() < 25.0) { offsetFileName += "p5."; } else { offsetFileName += "p25."; } offsetFileName += (gbl::cissLab->InstrumentModeId() + ".cub"); FileName shutterOffsetFile(offsetFileName); if(!shutterOffsetFile.fileExists()) { // shutter offset file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. ShutterOffsetFile ***" + shutterOffsetFile.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("ShutterOffsetFile", shutterOffsetFile.original()); Cube offsetCube; offsetCube.open(shutterOffsetFile.original()); gbl::offset = new Brick(gbl::incube->sampleCount(), 1, 1, offsetCube.pixelType()); gbl::offset->SetBasePosition(1, 1, 1); offsetCube.read(*gbl::offset); offsetCube.close(); return; // Pixel value is now flux (electrons per second) } /** * This method is modelled after IDL CISSCAL's * cassimg_dividebyareapixel.pro. The purpose is to find the * values needed to normalise the image by dividing by area of * optics and by solid angle subtended by a pixel. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2019-08-14 Kaitlyn Lee - Added check for * ShutterStateId. Updated solid angle and optics * area values. Matches cisscal version 3.9.1. */ void gbl::DivideByAreaPixel() { // Disable flat field correction if ShutterStateId is Disabled if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::calgrp += PvlKeyword("DividedByAreaPixel", "No: ShutterStateId is Disabled."); gbl::calgrp += PvlKeyword("SolidAngle", "Not applicable: No division by area pixel"); gbl::calgrp += PvlKeyword("OpticsArea", "Not applicable: No division by area pixel"); gbl::calgrp += PvlKeyword("SumFactor", "Not applicable: No division by area pixel"); return; return; } // These values as per ISSCAL // SolidAngle is (FOV of Optics) / (Number of Pixels) // OpticsArea is (Diameter of Primary Mirror)^2 * Pi/4 // Optics areas below come from radii in "Final Report, Design // and Analysis of Filters for the Cassini Narrow and Wide // Optics" by David Hasenauer, May 19, 1994. // We will adjust here for the effects of SUM modes // (which effectively give pixels of 4 or 16 times normal size) gbl::calgrp += PvlKeyword("DividedByAreaPixel", "Yes"); if(gbl::cissLab->NarrowAngle()) { gbl::solidAngle = 3.58885 * pow(10.0, -11.0); gbl::opticsArea = 284.86; } else { gbl::solidAngle = 3.56994 * pow(10.0, -9); gbl::opticsArea = 29.43; } // Normalize summed images to real pixels // sumFactor is the inverse of the square of the summing mode, // it was expressed in IDL as the following: // [gbl::sumFactor = (gbl::incube->sampleCount()/1024.0)*(gbl::incube->lineCount()/1024.0);] gbl::sumFactor = 1 / pow(gbl::cissLab->SummingMode(), 2.0); gbl::calgrp += PvlKeyword("SolidAngle", toString(gbl::solidAngle)); gbl::calgrp += PvlKeyword("OpticsArea", toString(gbl::opticsArea)); gbl::calgrp += PvlKeyword("SumFactor", toString(gbl::sumFactor)); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_dividebyefficiency.pro. The purpose is to find the * efficiency factor for the given flux units. This value is * used to correct the image for filter and CCD efficiency. * * @b Note: For "I/F", The results diverge from the IDL results * due to differences in the way they calculate solar distance. * However, the DN results are still within 0.2% after we divide * by efficiency factor. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version of * FindEfficiencyFactor_IoverF() and * FindEfficiencyFactor_IntensityUnits() written. * @history 2009-02-12 Jeannie Walldren - Modified * FindEfficiencyFactor_IoverF() code to make a * second attempt to find the planet if the * Isis::Camera class fails to find it at the center * point of the cube. Previously, if the target was * not found, an exception was thrown. Now the * SubSpacecraftPoint() method from Isis::Camera * class is used to try to locate the target before * throwing the exception. * @history 2009-05-27 Jeannie Walldren - Joined * FindEfficiencyFactor_IoverF() and * FindEfficiencyFactor_IntensityUnits() into * FindEfficiencyFactor() per new idl cisscal * version, 3.6, updates. This version no longer uses * the effic_db (now called omega0) to calculate the * efficiency factor for intensity units. Now, the * method is not far off from the I/F method. * @history 2019-08-14 Kaitlyn Lee - Added check for * ShutterStateId. Matches cisscal version 3.9.1. */ void gbl::FindEfficiencyFactor(QString fluxunits) { // Disable flat field correction if ShutterStateId is Disabled if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::calgrp += PvlKeyword("DividedByEfficiency", "No: ShutterStateId is Disabled."); gbl::calgrp += PvlKeyword("EfficiencyFactorMethod", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("TransmissionFile", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("QuantumEfficiencyFile", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("SpectralFile", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("SolarDistance", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("EfficiencyFactor", "Not applicable: No division by efficiency"); gbl::calgrp += PvlKeyword("TotalEfficiency", "Not applicable: No division by efficiency"); return; } // for polarized filter combinations, use corresponding clear transmission: QString filter1 = gbl::cissLab->FilterName()[0]; QString filter2 = gbl::cissLab->FilterName()[1]; if(filter1 == "IRP0" || filter1 == "P120" || filter1 == "P60" || filter1 == "P0" || filter2 == "IRP90" || filter2 == "IRP0") { if(gbl::cissLab->InstrumentId() == "ISSNA") { filter1 = "CL1"; } if(gbl::cissLab->InstrumentId() == "ISSWA") { filter2 = "CL2"; } } gbl::calgrp += PvlKeyword("DividedByEfficiency", "Yes"); gbl::calgrp += PvlKeyword("EfficiencyFactorMethod", fluxunits); vector<double> lambda; // lambda will contain all wavelength vectors used //--- 1) CREATE LINEAR APPROXIMATION FROM SYSTEM TRANSMISSION FILE ---------- // find system transmission file (T0*T1*T2*QE) FileName transfile(gbl::GetCalibrationDirectory("efficiency/systrans") + gbl::cissLab->InstrumentId().toLower() + filter1.toLower() + filter2.toLower() + "_systrans.tab"); if(!transfile.fileExists()) { // transmission file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. TransmissionFile ***" + transfile.expanded() + "*** not found.", _FILEINFO_); } // read in system transmission to find transmitted wavelength and flux gbl::calgrp += PvlKeyword("TransmissionFile", transfile.original()); CisscalFile *trans = new CisscalFile(transfile.original()); vector<double> wavelengthT, transmittedFlux; double x, y; for(int i = 0; i < trans->LineCount(); i++) { QString line; trans->GetLine(line); //assigns value to line line = line.simplified().trimmed(); if(line == "") { break; } x = toDouble(line.split(" ")[0]); y = toDouble(line.split(" ")[1]); wavelengthT.push_back(x); transmittedFlux.push_back(y); } trans->Close(); // wavelength and flux are in descending order, reverse to ascending order if(wavelengthT[0] > wavelengthT.back()) { reverse(wavelengthT.begin(), wavelengthT.end()); reverse(transmittedFlux.begin(), transmittedFlux.end()); } lambda = wavelengthT; // Create Linear approximation from the transmitted data NumericalApproximation newtrans(NumericalApproximation::Linear); for(unsigned int i = 0; i < transmittedFlux.size(); i++) { newtrans.AddData(wavelengthT[i], transmittedFlux[i]); } //--- 2) CREATE LINEAR APPROXIMATION FROM QUANTUM EFFICIENCY FILE ----------- // find quantum efficiency file FileName qecorrfile; if(gbl::cissLab->NarrowAngle()) { qecorrfile = gbl::GetCalibrationDirectory("correction") + "nac_qe_correction.tab"; } else { qecorrfile = gbl::GetCalibrationDirectory("correction") + "wac_qe_correction.tab"; } if(!qecorrfile.fileExists()) { // quantum efficiency file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. QuantumEfficiencyFile ***" + qecorrfile.expanded() + "*** not found.", _FILEINFO_); } // read qe file to find qe wavelength and correction gbl::calgrp += PvlKeyword("QuantumEfficiencyFile", qecorrfile.original()); CisscalFile *qeCorr = new CisscalFile(qecorrfile.original()); vector<double> wavelengthQE, qecorrection; for(int i = 0; i < qeCorr->LineCount(); i++) { QString line; qeCorr->GetLine(line); //assigns value to line line = line.simplified().trimmed(); if(line == "") { break; } x = toDouble(line.split(" ").first()); y = toDouble(line.split(" ").last()); wavelengthQE.push_back(x); qecorrection.push_back(y); lambda.push_back(x); } qeCorr->Close(); // wavelength and qecorr are in descending order, reverse to ascending order if(wavelengthQE[0] > wavelengthQE.back()) { reverse(wavelengthQE.begin(), wavelengthQE.end()); reverse(qecorrection.begin(), qecorrection.end()); } // Create Linear approximation from the qe data NumericalApproximation newqecorr(NumericalApproximation::Linear); for(unsigned int i = 0; i < qecorrection.size(); i++) { newqecorr.AddData(wavelengthQE[i], qecorrection[i]); } // these variables will be defined in the if-statement QString units; double minlam, maxlam; vector<double> fluxproduct1, fluxproduct2; if(fluxunits == "INTENSITY") { gbl::calgrp += PvlKeyword("SpectralFile", "Not applicable: Intensity Units chosen"); gbl::calgrp += PvlKeyword("SolarDistance", "Not applicable: Intensity Units chosen"); //--- 3a) SORT AND MAKE LAMBDA UNIQUE, REMOVE OUTLIERS, ------------------- //--- FIND FLUX PRODUCTS TO BE INTERPOLATED --------------------------- units = "phot/cm^2/s/nm/ster"; // lambda domain min is the largest of the minimum wavelength values (rounded up) minlam = ceil(max(wavelengthT.front(), wavelengthQE.front())); // lambda domain max is the smallest of the maximum wavelength values (rounded down) maxlam = floor(min(wavelengthT.back(), wavelengthQE.back())); // NumericalApproximation requires lambda to be sorted sort(lambda.begin(), lambda.end()); // NumericalApproximation requires lambda to be unique vector<double>::iterator it = unique(lambda.begin(), lambda.end()); lambda.resize(it - lambda.begin()); // remove any values that fall below minlam while(lambda[0] < minlam) { lambda.erase(lambda.begin()); } // remove any values that fall above maxlam while(lambda[lambda.size()-1] > maxlam) { lambda.erase(lambda.end() - 1); } for(unsigned int i = 0; i < lambda.size(); i++) { double a = newtrans.Evaluate(lambda[i]); double b = newqecorr.Evaluate(lambda[i]); fluxproduct1.push_back(a * b); } fluxproduct2 = fluxproduct1; } else {// if(fluxunits == "I/F") { //--- 3b) CALCULATE SOLAR DISTANCE, --------------------------------------- // --- CREATE LINEAR APPROXIMATION FROM SPECTRAL FILE ------------------ //--- SORT AND MAKE LAMBDA UNIQUE, REMOVE OUTLIERS, ------------------- //--- FIND FLUX PRODUCTS TO BE INTERPOLATED --------------------------- units = "I/F"; // find spectral file FileName specfile(gbl::GetCalibrationDirectory("efficiency") + "solarflux.tab"); if(!specfile.fileExists()) { // spectral file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image using I/F. SpectralFile ***" + specfile.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("SpectralFile", specfile.original()); // get distance from sun (AU): double angstromsToNm = 10.0; double distFromSun = 0; try { Camera *cam = gbl::incube->camera(); bool camSuccess = cam->SetImage(gbl::incube->sampleCount() / 2, gbl::incube->lineCount() / 2); if(!camSuccess) {// the camera was unable to find the planet at the center of the image double lat, lon; // find values for lat/lon directly below spacecraft cam->subSpacecraftPoint(lat, lon); // use these values to set the ground coordinates cam->SetUniversalGround(lat, lon); } distFromSun = cam->SolarDistance(); } catch(IException &e) { // unable to get solar distance, can't divide by efficiency, stop calibration throw IException(IException::Unknown, "Unable to calibrate image using I/F. Cannot calculate Solar Distance using Isis::Camera object.", _FILEINFO_); } if(distFromSun <= 0) { // solar distance <= 0, can't divide by efficiency, stop calibration throw IException(IException::Unknown, "Unable to calibrate image using I/F. Solar Distance calculated is less than or equal to 0.", _FILEINFO_); } gbl::calgrp += PvlKeyword("SolarDistance", toString(distFromSun)); // read spectral file to find wavelength and flux CisscalFile *spectral = new CisscalFile(specfile.original()); vector<double> wavelengthF, flux; for(int i = 0; i < spectral->LineCount(); i++) { QString line; spectral->GetLine(line); //assigns value to line line = line.simplified().trimmed(); if(line == "") { break; } x = toDouble(line.split(" ").first()) / angstromsToNm; y = toDouble(line.split(" ").last()) * angstromsToNm; wavelengthF.push_back(x); flux.push_back(y); lambda.push_back(x); } spectral->Close(); // wavelength is in descending order, reverse to ascending order if(wavelengthF[0] > wavelengthF.back()) { reverse(wavelengthF.begin(), wavelengthF.end()); reverse(flux.begin(), flux.end()); } // Create Linear Approximation NumericalApproximation newflux(NumericalApproximation::Linear); for(unsigned int i = 0; i < flux.size(); i++) { newflux.AddData(wavelengthF[i], flux[i]); } // lambda domain min is the largest of the minimum wavelength values (rounded up) minlam = ceil(max(wavelengthF.front(), max(wavelengthT.front(), wavelengthQE.front()))); // lambda domain max is the smallest of the maximum wavelength values (rounded down) maxlam = floor(min(wavelengthF.back(), min(wavelengthT.back(), wavelengthQE.back()))); // NumericalApproximation requires lambda to be sorted sort(lambda.begin(), lambda.end()); // NumericalApproximation requires lambda to be unique vector<double>::iterator it = unique(lambda.begin(), lambda.end()); lambda.resize(it - lambda.begin()); // remove any values that fall below minlam while(lambda[0] < minlam) { lambda.erase(lambda.begin()); } // remove any values that fall above maxlam while(lambda[lambda.size()-1] > maxlam) { lambda.erase(lambda.end() - 1); } for(unsigned int i = 0; i < lambda.size(); i++) { double a = newtrans.Evaluate(lambda[i]); double b = newqecorr.Evaluate(lambda[i]); double c = newflux.Evaluate(lambda[i]) / (Isis::PI * pow(distFromSun, 2.0)); fluxproduct1.push_back(a * b * c); fluxproduct2.push_back(a * b); } } //--- 4) CALCULATE EFFICIENCY FACTOR AND TOTAL EFFICIENCY ------------------- //--- USING LAMBDA AND FLUX PRODUCTS ------------------------------------- NumericalApproximation spline1(NumericalApproximation::CubicNatural); NumericalApproximation spline2(NumericalApproximation::CubicNatural); spline1.AddData(lambda, fluxproduct1); spline2.AddData(lambda, fluxproduct2); gbl::efficiencyFactor = spline1.BoolesRule(spline1.DomainMinimum(), spline1.DomainMaximum()); double efficiency = spline2.BoolesRule(spline2.DomainMinimum(), spline2.DomainMaximum()); gbl::calgrp += PvlKeyword("EfficiencyFactor", toString(gbl::efficiencyFactor), units); gbl::calgrp += PvlKeyword("TotalEfficiency", toString(efficiency)); // Cannot divide by 0.0 if(gbl::efficiencyFactor == 0) { throw IException(IException::Unknown, "Unable to calibrate image using I/F. Cannot divide by efficiency factor of 0.", _FILEINFO_); } return; } //=====End DN to Flux Methods====================================================================// //=====2 Correction Factors Methods================================================================// /** * This method is modelled after IDL CISSCAL's * cassimg_correctionfactors.pro. The purpose is to find the * correction factor, i.e. the value used to correct the image * for ad-hoc factors. * * @internal * @history 2008-11-05 Jeannie Walldren - Original version * @history 2009-05-27 Jeannie Walldren - Renamed from * FindCorrectionFactor since code was added to find * the polarization correction factor, when * available. * @history 2017-06-08 Cole Neubauer - removed polarization correcton * factor and added Jupiter correction factor to match 3.8 update * @history 2019-08--14 Kaitlyn Lee - Removed Jupiter correction factor * since it was removed in the 3.9.1 update. */ void gbl::FindCorrectionFactors() { // Disable correction factor if ShutterStateId is Disabled if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::calgrp += PvlKeyword("CorrectionFactorPerformed", "No: ShutterStateId is Disabled."); gbl::calgrp.findKeyword("CorrectionFactorPerformed").addComment("Correction Factor Parameters"); gbl::calgrp += PvlKeyword("CorrectionFactorFile", "Not applicable: No correction factions."); return; } QString filter1 = gbl::cissLab->FilterName()[0]; QString filter2 = gbl::cissLab->FilterName()[1]; if(filter1 == "IRP0" || filter1 == "P120" || filter1 == "P60" || filter1 == "P0" || filter2 == "IRP90" || filter2 == "IRP0") { if(gbl::cissLab->InstrumentId() == "ISSNA") { filter1 = "CL1"; } if(gbl::cissLab->InstrumentId() == "ISSWA") { filter2 = "CL2"; } } // First Apply Standard Correction Factors // Get the directory where the CISS calibration directories are. FileName correctionFactorFile(gbl::GetCalibrationDirectory("correction") + "correctionfactors_qecorr.tab"); if(!correctionFactorFile.fileExists()) { // correction factor file not found, stop calibration throw IException(IException::Io, "Unable to calibrate image. CorrectionFactorFile ***" + correctionFactorFile.expanded() + "*** not found.", _FILEINFO_); } gbl::calgrp += PvlKeyword("CorrectionFactorPerformed", "Yes"); gbl::calgrp.findKeyword("CorrectionFactorPerformed").addComment("Correction Factor Parameters"); gbl::calgrp += PvlKeyword("CorrectionFactorFile", correctionFactorFile.original()); CisscalFile *corrFact = new CisscalFile(correctionFactorFile.original()); gbl::correctionFactor = 0.0; QString col1, col2, col3, col4; for(int i = 0; i < corrFact->LineCount(); i++) { QString line; corrFact->GetLine(line); //assigns value to line line = line.simplified().trimmed(); QStringList cols = line.split(" "); col1 = cols.takeFirst(); if(col1 == gbl::cissLab->InstrumentId()) { col2 = cols.takeFirst(); if(col2 == filter1) { col3 = cols.takeFirst(); if(col3 == filter2) { col4 = cols.takeFirst(); if(col4 == "") { gbl::correctionFactor = 1.0; // dividing by correction factor of 1.0 implies this correction is not performed gbl::calgrp.findKeyword("CorrectionFactorPerformed").setValue("No: CorrectionFactorFile contained no factor for filter combination"); } else { gbl::correctionFactor = toDouble(col4); } break; } else { continue; } } else { continue; } } else { continue; } } corrFact->Close(); // if no factor was found for instrument ID and filter combination if(gbl::correctionFactor == 0.0) { gbl::correctionFactor = 1.0; // dividing by correction factor of 1.0 implies this correction is not performed gbl::calgrp.findKeyword("CorrectionFactorPerformed").setValue("No: CorrectionFactorFile contained no factor for filter combination"); gbl::calgrp.findKeyword("CorrectionFactorPerformed").addComment("Correction Factor Parameters"); } gbl::calgrp += PvlKeyword("CorrectionFactor", toString(gbl::correctionFactor)); return; } /** * This method is modelled after IDL CISSCAL's * cassimg_sensvstime.pro. IDL documentation: * Sensitivity vs. time correction derived from stellar photometry: * * NAC, all data (~8% total decline from S03 to S100): * slope = -1.89457e-10 * * WAC, all data (~3% total decline from S17 to S100): * slope = -9.28360e-11 * * @internal * @history 2019-08-14 Kaitlyn Lee - Original version */ void gbl::FindSensitivityCorrection() { if(gbl::cissLab->ShutterStateId() == "Disabled") { gbl::calgrp += PvlKeyword("SensitivityCorrectionPerformed", "No: ShutterStateId is Disabled."); gbl::sensCorrection = false; gbl::calgrp += PvlKeyword("SensVsTimeCorr", "Not applicable: No Sensitivity correction."); return; } double imgNumber = gbl::cissLab->ImageNumber(); // Values taken from IDL double imgNumberS03 = 1.47036e9; double imgNumberS17 = 1.51463e9; if(gbl::cissLab->InstrumentId() == "ISSNA" && imgNumber < imgNumberS03) { gbl::calgrp += PvlKeyword("SensitivityCorrectionPerformed", "No: No NAC correction before S03"); gbl::sensCorrection = false; gbl::calgrp += PvlKeyword("SensVsTimeCorr", "Not applicable: No NAC correction before S03"); return; } if(gbl::cissLab->InstrumentId() == "ISSWA" && imgNumber < imgNumberS17) { gbl::calgrp += PvlKeyword("SensitivityCorrectionPerformed", "No: No WAC correction before S17"); gbl::sensCorrection = false; gbl::calgrp += PvlKeyword("SensVsTimeCorr", "Not applicable: No WAC correction before S17"); return; } if(gbl::cissLab->InstrumentId() == "ISSNA") { gbl::sensVsTimeCorr = 1.0 + (1.89457e-10 * (imgNumber - imgNumberS03)); } else if(gbl::cissLab->InstrumentId() == "ISSWA") { gbl::sensVsTimeCorr = 1.0 + (9.28360e-11 * (imgNumber - imgNumberS17)); } gbl::calgrp += PvlKeyword("SensitivityCorrectionPerformed", "Yes"); gbl::calgrp.findKeyword("SensitivityCorrectionPerformed").addComment("Sensitivity vs Time Correction Parameters"); gbl::sensCorrection = true; gbl::calgrp += PvlKeyword("SensVsTimeCorr", toString(gbl::sensVsTimeCorr)); } //=====End Correction Factor Methods=============================================================// /** * This method returns an QString containing the path of a * Cassini calibration directory * * @param calibrationType * @return <b>IString</b> Path of the calibration directory * * @internal * @history 2008-11-05 Jeannie Walldren - Original version */ QString gbl::GetCalibrationDirectory(QString calibrationType) { // Get the directory where the CISS calibration directories are. PvlGroup &dataDir = Preference::Preferences().findGroup("DataDirectory"); QString missionDir = (QString) dataDir["Cassini"]; return missionDir + "/calibration/" + calibrationType + "/"; }
40.400536
177
0.635287
gknorman
2403e60df3918394e99c3284b2a417e336fc3bae
12,424
cc
C++
paddle/fluid/framework/ir/mkldnn/conv_elementwise_add_mkldnn_fuse_pass.cc
tiancaishaonvjituizi/Paddle
76f8703445b269334035a891466a284148c26734
[ "Apache-2.0" ]
1
2022-03-14T23:22:21.000Z
2022-03-14T23:22:21.000Z
paddle/fluid/framework/ir/mkldnn/conv_elementwise_add_mkldnn_fuse_pass.cc
Abraham-Xu/Paddle
5d08a4471973e1c2b2a595781d0a0840875a0c77
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/ir/mkldnn/conv_elementwise_add_mkldnn_fuse_pass.cc
Abraham-Xu/Paddle
5d08a4471973e1c2b2a595781d0a0840875a0c77
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/mkldnn/conv_elementwise_add_mkldnn_fuse_pass.h" #include <functional> #include <list> #include <map> #include <memory> #include <tuple> #include "paddle/fluid/framework/ir/graph_traits.h" #include "paddle/fluid/framework/op_version_registry.h" #include "paddle/fluid/string/pretty_log.h" namespace paddle { namespace framework { namespace ir { bool IsReachable(ir::Graph* graph, Node* from, Node* to) { auto find_node = [](ir::Graph* graph, const Node* node) -> Node* { for (auto n : graph->Nodes()) { if (n == node) { return n; } } return nullptr; }; if (from == to) { return true; } std::map<Node*, bool> visited; for (auto& node : GraphTraits::DFS(*graph)) { visited[&node] = false; } visited[from] = true; std::list<Node*> queue; queue.push_back(from); while (!queue.empty()) { auto cur = find_node(graph, queue.front()); queue.pop_front(); if (!cur) return false; for (auto n : cur->outputs) { if (n == to) { return true; } if (!visited[n]) { visited[n] = true; queue.push_back(n); } } } return false; } template <typename T> paddle::optional<T> HasAttribute(const Node& op, const std::string& attr) { if (op.Op()->HasAttr(attr)) return BOOST_GET_CONST(T, op.Op()->GetAttr(attr)); else return paddle::none; } ResidualConnectionMKLDNNFusePass::ResidualConnectionMKLDNNFusePass() { AddOpCompat(OpCompat("conv2d")) .AddInput("Input") .IsTensor() .End() .AddInput("Filter") .IsTensor() .End() .AddInput("Bias") .IsTensor() .IsOptional() .End() .AddInput("ResidualData") .IsTensor() .IsOptional() .End() .AddOutput("Output") .IsTensor() .End() .AddAttr("strides") .IsType<std::vector<int>>() .End() .AddAttr("paddings") .IsType<std::vector<int>>() .End() .AddAttr("padding_algorithm") .IsOptional() .IsStringIn({"EXPLICIT", "SAME", "VALID"}) .End() .AddAttr("groups") .IsNumGE(1) .End() .AddAttr("dilations") .IsType<std::vector<int>>() .End() .AddAttr("data_format") .IsStringIn({"NCHW", "AnyLayout"}) .End(); AddOpCompat(OpCompat("elementwise_add")) .AddInput("X") .IsTensor() .End() .AddInput("Y") .IsTensor() .End() .AddOutput("Out") .IsTensor() .End() .AddAttr("axis") .IsIntIn({-1, 0, 1}) .End(); } GraphWithStats ResidualConnectionMKLDNNFusePass::FuseConvAsX( const std::string& name_scope, const GraphWithStats& graph_with_stats) const { GraphPatternDetector gpd; auto pattern = gpd.mutable_pattern(); patterns::Conv conv_pattern{pattern, name_scope}; auto conv_output = conv_pattern(); patterns::ElementwiseAdd elementwise_add_pattern{pattern, name_scope}; elementwise_add_pattern( conv_output, pattern->NewNode(elementwise_add_pattern.elementwise_add_y_repr())); conv_output->AsIntermediate(); int found_conv_as_x_count = 0; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(conv_op, conv_op, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_input, conv_input, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_filter, conv_filter, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_output, conv_output, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_op, elementwise_add_op, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_identity, elementwise_add_y, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out, elementwise_add_pattern); if (FindFuseOption(*conv_op, *elementwise_add_op) != FUSE_MKLDNN) return; if (!IsReachable(g, elementwise_add_identity, conv_output)) return; if (HasFusedActivation(conv_op)) return; if (!IsCompat(subgraph, g)) { LOG(WARNING) << "conv_elementwise_add_mkldnn_fuse_pass in op compat failed."; return; } conv_op->Op()->SetInput("ResidualData", {elementwise_add_identity->Name()}); conv_op->Op()->SetOutput("Output", {elementwise_add_out->Name()}); conv_op->Op()->SetAttr("fuse_residual_connection", true); GraphSafeRemoveNodes(g, {conv_output, elementwise_add_op}); IR_NODE_LINK_TO(elementwise_add_identity, conv_op); IR_NODE_LINK_TO(conv_op, elementwise_add_out); found_conv_as_x_count++; }; gpd(graph_with_stats.first, handler); if (!Has("disable_logs") || !Get<bool>("disable_logs")) { std::stringstream msg_ss; msg_ss << "--- Fused " << found_conv_as_x_count << " conv (as x) + elementwise_add patterns"; paddle::string::PrettyLogDetail(msg_ss.str().c_str()); } return std::make_pair(graph_with_stats.first, found_conv_as_x_count + graph_with_stats.second); } GraphWithStats ResidualConnectionMKLDNNFusePass::FuseConvAsY( const std::string& name_scope, const GraphWithStats& graph_with_stats) const { GraphPatternDetector gpd; auto pattern = gpd.mutable_pattern(); patterns::Conv conv_pattern{pattern, name_scope}; auto conv_output = conv_pattern(); patterns::ElementwiseAdd elementwise_add_pattern{pattern, name_scope}; elementwise_add_pattern( pattern->NewNode(elementwise_add_pattern.elementwise_add_x_repr()), conv_output); conv_output->AsIntermediate(); int found_conv_as_y_count = 0; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(conv_op, conv_op, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_input, conv_input, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_filter, conv_filter, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_output, conv_output, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_op, elementwise_add_op, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_x, elementwise_add_x, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out, elementwise_add_pattern); if (FindFuseOption(*conv_op, *elementwise_add_op) != FUSE_MKLDNN) return; if (!IsReachable(g, elementwise_add_x, conv_output)) return; if (HasFusedActivation(conv_op)) return; if (!IsCompat(subgraph, g)) { LOG(WARNING) << "conv_elementwise_add_mkldnn_fuse_pass in op compat failed."; return; } conv_op->Op()->SetInput("ResidualData", {elementwise_add_x->Name()}); conv_op->Op()->SetOutput("Output", {elementwise_add_out->Name()}); conv_op->Op()->SetAttr("fuse_residual_connection", true); GraphSafeRemoveNodes(g, {conv_output, elementwise_add_op}); IR_NODE_LINK_TO(elementwise_add_x, conv_op); IR_NODE_LINK_TO(conv_op, elementwise_add_out); found_conv_as_y_count++; }; gpd(graph_with_stats.first, handler); if (!Has("disable_logs") || !Get<bool>("disable_logs")) { std::stringstream msg_ss; msg_ss << "--- Fused " << found_conv_as_y_count << " conv (as y) + elementwise_add patterns"; paddle::string::PrettyLogDetail(msg_ss.str().c_str()); } return std::make_pair(graph_with_stats.first, found_conv_as_y_count + graph_with_stats.second); } GraphWithStats ResidualConnectionMKLDNNFusePass::FuseProjectionConv( const std::string& name_scope, const GraphWithStats& graph_with_stats) const { GraphPatternDetector gpd; auto pattern = gpd.mutable_pattern(); patterns::Conv conv_x_pattern{pattern, name_scope}; auto conv_x_output = conv_x_pattern(); patterns::Conv conv_y_pattern{pattern, name_scope}; auto conv_y_output = conv_y_pattern(); patterns::ElementwiseAdd elementwise_add_pattern{pattern, name_scope}; elementwise_add_pattern(conv_x_output, conv_y_output); conv_x_output->AsIntermediate(); conv_y_output->AsIntermediate(); int found_projection_conv_count = 0; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(conv_x_op, conv_op, conv_x_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_x_input, conv_input, conv_x_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_x_filter, conv_filter, conv_x_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_x_output, conv_output, conv_x_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_y_op, conv_op, conv_y_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_y_input, conv_input, conv_y_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_y_filter, conv_filter, conv_y_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_y_output, conv_output, conv_y_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_op, elementwise_add_op, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out, elementwise_add_pattern); if (!IsCompat(subgraph, g)) { LOG(WARNING) << "conv_elementwise_add_mkldnn_fuse_pass in op compat failed."; return; } if (FindFuseOption(*conv_x_op, *elementwise_add_op) != FUSE_MKLDNN) return; if (FindFuseOption(*conv_y_op, *elementwise_add_op) != FUSE_MKLDNN) return; Node* projection_node; Node* residual_conv_op; Node* residual_conv_output; if (IsReachable(g, conv_x_input, conv_y_output)) { projection_node = conv_x_output; residual_conv_op = conv_y_op; residual_conv_output = conv_y_output; } else if (IsReachable(g, conv_y_input, conv_x_output)) { projection_node = conv_y_output; residual_conv_op = conv_x_op; residual_conv_output = conv_x_output; } else { return; } if (HasFusedActivation(residual_conv_op)) return; residual_conv_op->Op()->SetInput("ResidualData", {projection_node->Name()}); residual_conv_op->Op()->SetOutput("Output", {elementwise_add_out->Name()}); residual_conv_op->Op()->SetAttr("fuse_residual_connection", true); GraphSafeRemoveNodes(g, {residual_conv_output, elementwise_add_op}); IR_NODE_LINK_TO(projection_node, residual_conv_op); IR_NODE_LINK_TO(residual_conv_op, elementwise_add_out); found_projection_conv_count++; }; gpd(graph_with_stats.first, handler); if (!Has("disable_logs") || !Get<bool>("disable_logs")) { std::stringstream msg_ss; msg_ss << "--- Fused " << found_projection_conv_count << " projection conv (as y) + elementwise_add patterns"; paddle::string::PrettyLogDetail(msg_ss.str().c_str()); } return std::make_pair(graph_with_stats.first, found_projection_conv_count + graph_with_stats.second); } void ResidualConnectionMKLDNNFusePass::ApplyImpl(ir::Graph* graph) const { FusePassBase::Init(name_scope_, graph); auto graph_with_stats = FuseProjectionConv(name_scope_, std::make_pair(graph, 0)); graph_with_stats = FuseConvAsX(name_scope_, graph_with_stats); graph_with_stats = FuseConvAsY(name_scope_, graph_with_stats); AddStatis(graph_with_stats.second); } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(conv_elementwise_add_mkldnn_fuse_pass, paddle::framework::ir::ResidualConnectionMKLDNNFusePass); REGISTER_PASS_CAPABILITY(conv_elementwise_add_mkldnn_fuse_pass) .AddCombination( paddle::framework::compatible::OpVersionComparatorCombination() .LE("conv2d", 1) .LE("elementwise_add", 1));
32.694737
83
0.690035
tiancaishaonvjituizi
240b8f928ba8dcce7e52e4d1b956548fb1b2e59d
132
hxx
C++
src/Providers/UNIXProviders/ClassifierService/UNIX_ClassifierService_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/ClassifierService/UNIX_ClassifierService_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/ClassifierService/UNIX_ClassifierService_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_CLASSIFIERSERVICE_PRIVATE_H #define __UNIX_CLASSIFIERSERVICE_PRIVATE_H #endif #endif
11
42
0.856061
brunolauze
240eb8b55ed74407258df7adb26a04d8de9a8527
12,739
cpp
C++
libs/core/execution/tests/unit/algorithm_then.cpp
bhumitattarde/hpx
5b34d8d77b1664fa552445d44cd98e51dc69a74a
[ "BSL-1.0" ]
1
2022-02-08T05:55:09.000Z
2022-02-08T05:55:09.000Z
libs/core/execution/tests/unit/algorithm_then.cpp
deepaksuresh1411/hpx
aa18024d35fe9884a977d4b6076c764dbb8b26d1
[ "BSL-1.0" ]
null
null
null
libs/core/execution/tests/unit/algorithm_then.cpp
deepaksuresh1411/hpx
aa18024d35fe9884a977d4b6076c764dbb8b26d1
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 ETH Zurich // Copyright (c) 2022 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/modules/execution.hpp> #include <hpx/modules/testing.hpp> #include "algorithm_test_utils.hpp" #include <atomic> #include <exception> #include <stdexcept> #include <string> #include <type_traits> #include <utility> namespace ex = hpx::execution::experimental; struct custom_transformer { std::atomic<bool>& tag_invoke_overload_called; std::atomic<bool>& call_operator_called; bool throws; void operator()() const { call_operator_called = true; if (throws) { throw std::runtime_error("error"); } } }; template <typename S> auto tag_invoke(ex::then_t, S&& s, custom_transformer t) { t.tag_invoke_overload_called = true; return ex::then(std::forward<S>(s), [t = std::move(t)]() { t(); }); } int main() { // Success path { std::atomic<bool> set_value_called{false}; auto s = ex::then(ex::just(), [] {}); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [] {}; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } { std::atomic<bool> set_value_called{false}; auto s = ex::then(ex::just(0), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [](int x) { HPX_TEST_EQ(x, 1); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } { std::atomic<bool> set_value_called{false}; auto s = ex::then(ex::just(custom_type_non_default_constructible{0}), [](custom_type_non_default_constructible x) { ++(x.x); return x; }); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types< hpx::variant<hpx::tuple<custom_type_non_default_constructible>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [](auto x) { HPX_TEST_EQ(x.x, 1); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } { std::atomic<bool> set_value_called{false}; auto s = ex::then( ex::just(custom_type_non_default_constructible_non_copyable{0}), [](custom_type_non_default_constructible_non_copyable&& x) { ++(x.x); return std::move(x); }); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant< hpx::tuple<custom_type_non_default_constructible_non_copyable>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [](auto x) { HPX_TEST_EQ(x.x, 1); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } { std::atomic<bool> set_value_called{false}; auto s1 = ex::then(ex::just(0), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s1)>); static_assert(ex::is_sender_v<decltype(s1), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s1); check_error_types<hpx::variant<std::exception_ptr>>(s1); check_sends_stopped<false>(s1); auto s2 = ex::then(std::move(s1), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s2)>); static_assert(ex::is_sender_v<decltype(s2), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s2); check_error_types<hpx::variant<std::exception_ptr>>(s2); check_sends_stopped<false>(s2); auto s3 = ex::then(std::move(s2), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s3)>); static_assert(ex::is_sender_v<decltype(s3), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s3); check_error_types<hpx::variant<std::exception_ptr>>(s3); check_sends_stopped<false>(s3); auto s4 = ex::then(std::move(s3), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s4)>); static_assert(ex::is_sender_v<decltype(s4), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s4); check_error_types<hpx::variant<std::exception_ptr>>(s4); check_sends_stopped<false>(s4); auto f = [](int x) { HPX_TEST_EQ(x, 4); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s4), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } { std::atomic<bool> set_value_called{false}; auto s1 = ex::then(ex::just(), []() { return 3; }); static_assert(ex::is_sender_v<decltype(s1)>); static_assert(ex::is_sender_v<decltype(s1), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s1); check_error_types<hpx::variant<std::exception_ptr>>(s1); check_sends_stopped<false>(s1); auto s2 = ex::then(std::move(s1), [](int x) { return x / 1.5; }); static_assert(ex::is_sender_v<decltype(s2)>); static_assert(ex::is_sender_v<decltype(s2), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<double>>>(s2); check_error_types<hpx::variant<std::exception_ptr>>(s2); check_sends_stopped<false>(s2); auto s3 = ex::then(std::move(s2), [](double x) -> int { return int(x / 2); }); static_assert(ex::is_sender_v<decltype(s3)>); static_assert(ex::is_sender_v<decltype(s3), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s3); check_error_types<hpx::variant<std::exception_ptr>>(s3); check_sends_stopped<false>(s3); auto s4 = ex::then(std::move(s3), [](int x) { return std::to_string(x); }); static_assert(ex::is_sender_v<decltype(s4)>); static_assert(ex::is_sender_v<decltype(s4), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<std::string>>>(s4); check_error_types<hpx::variant<std::exception_ptr>>(s4); check_sends_stopped<false>(s4); auto f = [](std::string x) { HPX_TEST_EQ(x, std::string("1")); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s4), std::move(r)); ex::start(os); HPX_TEST(set_value_called); } // operator| overload { std::atomic<bool> set_value_called{false}; auto s = ex::just() | ex::then([]() { return 3; }) | ex::then([](int x) { return x / 1.5; }) | ex::then([](double x) -> int { return int(x / 2); }) | ex::then([](int x) { return std::to_string(x); }); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<std::string>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [](std::string x) { HPX_TEST_EQ(x, std::string("1")); }; auto r = callback_receiver<decltype(f)>{f, set_value_called}; auto os = ex::connect(std::move(s), r); ex::start(os); HPX_TEST(set_value_called); } // tag_invoke overload { std::atomic<bool> receiver_set_value_called{false}; std::atomic<bool> tag_invoke_overload_called{false}; std::atomic<bool> custom_transformer_call_operator_called{false}; auto s = ex::then(ex::just(), custom_transformer{tag_invoke_overload_called, custom_transformer_call_operator_called, false}); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto f = [] {}; auto r = callback_receiver<decltype(f)>{f, receiver_set_value_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(receiver_set_value_called); HPX_TEST(tag_invoke_overload_called); HPX_TEST(custom_transformer_call_operator_called); } // Failure path { std::atomic<bool> set_error_called{false}; auto s = ex::then(ex::just(), [] { throw std::runtime_error("error"); }); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto r = error_callback_receiver<check_exception_ptr>{ check_exception_ptr{}, set_error_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(set_error_called); } { std::atomic<bool> set_error_called{false}; auto s1 = ex::then(ex::just(0), [](int x) { return ++x; }); static_assert(ex::is_sender_v<decltype(s1)>); static_assert(ex::is_sender_v<decltype(s1), ex::empty_env>); auto s2 = ex::then(std::move(s1), [](int x) { throw std::runtime_error("error"); return ++x; }); static_assert(ex::is_sender_v<decltype(s2)>); static_assert(ex::is_sender_v<decltype(s2), ex::empty_env>); auto s3 = ex::then(std::move(s2), [](int x) { HPX_TEST(false); return ++x; }); static_assert(ex::is_sender_v<decltype(s3)>); static_assert(ex::is_sender_v<decltype(s3), ex::empty_env>); auto s4 = ex::then(std::move(s3), [](int x) { HPX_TEST(false); return ++x; }); static_assert(ex::is_sender_v<decltype(s4)>); static_assert(ex::is_sender_v<decltype(s4), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<int>>>(s4); check_error_types<hpx::variant<std::exception_ptr>>(s4); check_sends_stopped<false>(s4); auto r = error_callback_receiver<check_exception_ptr>{ check_exception_ptr{}, set_error_called}; auto os = ex::connect(std::move(s4), std::move(r)); ex::start(os); HPX_TEST(set_error_called); } { std::atomic<bool> receiver_set_error_called{false}; std::atomic<bool> tag_invoke_overload_called{false}; std::atomic<bool> custom_transformer_call_operator_called{false}; auto s = ex::then(ex::just(), custom_transformer{tag_invoke_overload_called, custom_transformer_call_operator_called, true}); static_assert(ex::is_sender_v<decltype(s)>); static_assert(ex::is_sender_v<decltype(s), ex::empty_env>); check_value_types<hpx::variant<hpx::tuple<>>>(s); check_error_types<hpx::variant<std::exception_ptr>>(s); check_sends_stopped<false>(s); auto r = error_callback_receiver<check_exception_ptr>{ check_exception_ptr{}, receiver_set_error_called}; auto os = ex::connect(std::move(s), std::move(r)); ex::start(os); HPX_TEST(receiver_set_error_called); HPX_TEST(tag_invoke_overload_called); HPX_TEST(custom_transformer_call_operator_called); } return hpx::util::report_errors(); }
37.689349
80
0.610095
bhumitattarde
240f27ae03a15ed468946882508a85946d599e90
520
hpp
C++
src/include/dex/tables/stat.hpp
vapaee/telos-dex-contract
4c161b0b13f489d1d62c5fb058a4705af39ac7bf
[ "MIT" ]
null
null
null
src/include/dex/tables/stat.hpp
vapaee/telos-dex-contract
4c161b0b13f489d1d62c5fb058a4705af39ac7bf
[ "MIT" ]
null
null
null
src/include/dex/tables/stat.hpp
vapaee/telos-dex-contract
4c161b0b13f489d1d62c5fb058a4705af39ac7bf
[ "MIT" ]
null
null
null
#include "./_aux.hpp" // TABLE stats (currency) ----------- // scope: supply_code // STANDARD TABLE - DON'T CHANGE TABLE currency_stats { eosio::asset supply; eosio::asset max_supply; name issuer; uint64_t primary_key()const { return supply.symbol.code().raw(); } }; typedef eosio::multi_index< "stat"_n, currency_stats > stats; // ------------------------------------
37.142857
78
0.448077
vapaee
2410b9e66fc6670f7be2e7510dd21fff9b0331ac
823
cpp
C++
CPP/Challenges_hackerblocks/Hollow Diamond Pattern(Pattern 6).cpp
sanjanaprasad2k01/hacktoberfest2021
dc6d8c3dc6c97a263bb4964b51fd344d12e51052
[ "CC0-1.0" ]
null
null
null
CPP/Challenges_hackerblocks/Hollow Diamond Pattern(Pattern 6).cpp
sanjanaprasad2k01/hacktoberfest2021
dc6d8c3dc6c97a263bb4964b51fd344d12e51052
[ "CC0-1.0" ]
null
null
null
CPP/Challenges_hackerblocks/Hollow Diamond Pattern(Pattern 6).cpp
sanjanaprasad2k01/hacktoberfest2021
dc6d8c3dc6c97a263bb4964b51fd344d12e51052
[ "CC0-1.0" ]
null
null
null
#include<iostream> using namespace std; int main() { int i,j,k=0,n; cin>>n; for(i=0;i<n;i++) { if(i==0||i==n-1) { for(j=0;j<n;j++) cout<<"*\t"; } else if(i<=n/2) { for(j=0;j<(n/2)-i+1;j++) cout<<"*\t"; for(j=0;j<2*i-1;j++) cout<<"\t"; for(j=0;j<(n/2)-i+1;j++) cout<<"*\t"; if(i==n/2) k=2; } else { for(j=0;j<k;j++) cout<<"*\t"; for(j=0;j<n-(2*k);j++) cout<<"\t"; for(j=0;j<k;j++) cout<<"*\t"; k++; } cout<<"\n"; } }
20.575
39
0.234508
sanjanaprasad2k01
2410ea7b6d5c5adb1e95862e2b108a42c9142ea3
1,043
cpp
C++
sfq/src/crates/lzt/src/ffi/lzt_core/dictionary/lztrie_dict/huffman/HuffmanCoder.cpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
sfq/src/crates/lzt/src/ffi/lzt_core/dictionary/lztrie_dict/huffman/HuffmanCoder.cpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
sfq/src/crates/lzt/src/ffi/lzt_core/dictionary/lztrie_dict/huffman/HuffmanCoder.cpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
#include "HuffmanCoder.h" #include "../../../serialization_legacy/BitSequence.h" HuffmanCoder::HuffmanCoder(): codes(NULL), lengths(NULL) {} HuffmanCoder::~HuffmanCoder() { if (codes != NULL) delete [] codes; if (lengths != NULL) delete [] lengths; } /** Return huffman code for symbol with index i. */ HuffmanCode HuffmanCoder::getCode(size_t i) { HuffmanCode hcode; hcode.length = lengths[i]; int l = lengths[i]; size_t c = codes[i]; /* Write binary representation of c to first l bits of hcode.code, * with least significant bit at rightmost position, and pad with zeroes * to the left if neccessary. I.E. for c = 2 and l = 4, write 0010. * Only first l bits are set. */ for (int i = l-1; i >= 0; --i) { bool bit; if (c > 0) bit = (c % 2 == 1 ? true : false); else bit = false; hcode.code.setBit(i, bit); c /= 2; } return hcode; } /** Get length of huffman code with index i. */ int HuffmanCoder::getLength(size_t i) { return lengths[i]; }
29.8
76
0.611697
lisp-rbi
2413b3d46da51f5ceec102edc4d39aea9b99973b
379
cpp
C++
C_C++/oop_assignment/assignment/week8/Q1.cpp
oneofsunshine/program_learning
5afc2e5e6e7a6604d4bd9c8e102822e1cf751c0b
[ "Apache-2.0" ]
1
2018-02-10T03:53:45.000Z
2018-02-10T03:53:45.000Z
C_C++/oop_assignment/assignment/week8/Q1.cpp
oneofsunshine/program_learning
5afc2e5e6e7a6604d4bd9c8e102822e1cf751c0b
[ "Apache-2.0" ]
null
null
null
C_C++/oop_assignment/assignment/week8/Q1.cpp
oneofsunshine/program_learning
5afc2e5e6e7a6604d4bd9c8e102822e1cf751c0b
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { return 0; } /* *描述 我们定义一个正整数a比正整数b优先的含义是: *a的质因数数目(不包括自身)比b的质因数数目多; *当两者质因数数目相等时,数值较大者优先级高。 现在给定一个容器,初始元素数目为0,之后每次往里面添加10个元素,每次添加之后,要求输出优先级最高与最低的元素,并把该两元素从容器中删除。 输入 第一行: num (添加元素次数,num <= 30) 下面10*num行,每行一个正整数n(n < 10000000). 输出 每次输入10个整数后,输出容器中优先级最高与最低的元素,两者用空格间隔。 样例输入 1 10 7 66 4 5 30 91 100 8 9 样例输出 66 5 */
12.633333
69
0.738786
oneofsunshine
24150b339797315fedd1206fbe40ac90cdc812a8
3,454
cpp
C++
src/optimizer/matcher/expression_matcher.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/optimizer/matcher/expression_matcher.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/optimizer/matcher/expression_matcher.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/optimizer/matcher/expression_matcher.hpp" #include "guinsoodb/planner/expression/list.hpp" namespace guinsoodb { bool ExpressionMatcher::Match(Expression *expr, vector<Expression *> &bindings) { if (type && !type->Match(expr->return_type.InternalType())) { return false; } if (expr_type && !expr_type->Match(expr->type)) { return false; } if (expr_class != ExpressionClass::INVALID && expr_class != expr->GetExpressionClass()) { return false; } bindings.push_back(expr); return true; } bool ExpressionEqualityMatcher::Match(Expression *expr, vector<Expression *> &bindings) { if (!Expression::Equals(expression, expr)) { return false; } bindings.push_back(expr); return true; } bool CaseExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundCaseExpression *)expr_p; if (check && !check->Match(expr->check.get(), bindings)) { return false; } if (result_if_true && !result_if_true->Match(expr->result_if_true.get(), bindings)) { return false; } if (result_if_false && !result_if_false->Match(expr->result_if_false.get(), bindings)) { return false; } return true; } bool CastExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundCastExpression *)expr_p; if (child && !child->Match(expr->child.get(), bindings)) { return false; } return true; } bool ComparisonExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundComparisonExpression *)expr_p; vector<Expression *> expressions = {expr->left.get(), expr->right.get()}; return SetMatcher::Match(matchers, expressions, bindings, policy); } bool InClauseExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundOperatorExpression *)expr_p; return SetMatcher::Match(matchers, expr->children, bindings, policy); } bool ConjunctionExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundConjunctionExpression *)expr_p; if (!SetMatcher::Match(matchers, expr->children, bindings, policy)) { return false; } return true; } bool OperatorExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundOperatorExpression *)expr_p; return SetMatcher::Match(matchers, expr->children, bindings, policy); } bool FunctionExpressionMatcher::Match(Expression *expr_p, vector<Expression *> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; } auto expr = (BoundFunctionExpression *)expr_p; if (!FunctionMatcher::Match(function, expr->function.name)) { return false; } if (!SetMatcher::Match(matchers, expr->children, bindings, policy)) { return false; } return true; } bool FoldableConstantMatcher::Match(Expression *expr, vector<Expression *> &bindings) { // we match on ANY expression that is a scalar expression if (!expr->IsFoldable()) { return false; } bindings.push_back(expr); return true; } } // namespace guinsoodb
29.521368
94
0.728141
GuinsooLab
2417df3b9d62db528d4a1bdf286071bc08ec8528
5,417
cpp
C++
TagsGenerator/createMatrix25/Arduino/libraries/FaBo_307_BLE_Nordic/src/fabo-nordic.cpp
ThomasLengeling/L3MasterReader
37ada4be9c1d9a41287b7ff196a158d7816e86a8
[ "MIT" ]
null
null
null
TagsGenerator/createMatrix25/Arduino/libraries/FaBo_307_BLE_Nordic/src/fabo-nordic.cpp
ThomasLengeling/L3MasterReader
37ada4be9c1d9a41287b7ff196a158d7816e86a8
[ "MIT" ]
null
null
null
TagsGenerator/createMatrix25/Arduino/libraries/FaBo_307_BLE_Nordic/src/fabo-nordic.cpp
ThomasLengeling/L3MasterReader
37ada4be9c1d9a41287b7ff196a158d7816e86a8
[ "MIT" ]
null
null
null
#include "fabo-nordic.h" #ifdef USE_HARDWARE_SERIAL FaboBLE::FaboBLE(HardwareSerial &serial) { ble = new NordicBLE(serial); ble->handler = this; onScanned = NULL; } #else FaboBLE::FaboBLE(SoftwareSerial &serial) { ble = new NordicBLE(serial); ble->handler = this; onScanned = NULL; } #endif void FaboBLE::nrfReceive(NordicBLE::CommandData &data) { // BLE_GAP_EVT_CONNECTED if (data.command == 0x10) { #ifdef DEBUG_PRINT if (ble->debug) { Debug.println(F("\n*BLE_GAP_EVT_CONNECTED")); Debug.print(F("Connection Handle:")); Debug.print(data.data[0], HEX); Debug.print(F(" ")); Debug.println(data.data[1], HEX); Debug.print(F("Peer Address:")); for (int i=0; i<7; i++) { Debug.print(data.data[2+i], HEX); Debug.print(F(" ")); } Debug.print(F("\nOwn Address:")); for (int i=0; i<7; i++) { Debug.print(data.data[9+i], HEX); Debug.print(F(" ")); } Debug.print(F("\nIRK:")); Debug.println(data.data[17], HEX); Debug.print(F("GAP Connection Parameters:")); for (int i=0; i<8; i++) { Debug.print(data.data[18+i], HEX); Debug.print(F(" ")); } } #endif if (onConnected) { uint16_t handle = data.data[0] | (data.data[1] << 8); onConnected(handle); } } // BLE_GAP_EVT_DISCONNECTED if (data.command == 0x11) { if (onDisconnected) { #ifdef DEBUG_PRINT if (ble->debug) { Debug.println(F("\n*BLE_GAP_EVT_CONNECTED")); Debug.print(F("Connection Handle:")); Debug.print(data.data[0], HEX); Debug.print(F(" ")); Debug.println(data.data[1], HEX); Debug.print(F("Reason:")); Debug.println(data.data[2], HEX); } #endif uint16_t handle = data.data[0] | (data.data[1] << 8); uint8_t reason = data.data[2]; onDisconnected(handle, reason); } } // BLE_GAP_EVT_ADV_REPORT if (data.command == 0x1b) { #ifdef DEBUG_PRINT if (ble->debug) { Debug.println(F("\n*BLE_GAP_EVT_ADV_REPORT")); Debug.print(F("Connection Handle:")); Debug.print(data.data[0], HEX); Debug.print(F(" ")); Debug.println(data.data[1], HEX); Debug.print(F("Address Type:")); Debug.println(data.data[2], HEX); Debug.print(F("Address:")); for (int i=0; i<6; i++) { Debug.print(data.data[3+i], HEX); } Debug.print(F("\nRSSI:")); Debug.println((int8_t)data.data[9], DEC); Debug.print(F("Flags:")); Debug.println(data.data[10], HEX); Debug.print(F("DataLen:")); Debug.println(data.len, DEC); Debug.print(F("Data:")); for (int i=0; i<data.len-11; i++) { Debug.print(data.data[11+i], HEX); } Debug.print(F("\n")); } #endif // send event to handler ScanData scan = {0}; scan.handle = data.data[0] | (data.data[1] << 8); scan.addressType = data.data[2]; memcpy(&scan.address, &data.data[3], 8); scan.RSSI = data.data[9]; scan.flags = data.data[10]; scan.dataLen = data.len - 11; memcpy(&scan.data, &data.data[11], scan.dataLen); if (onScanned) { onScanned(scan); } } if (data.command == 0x50) { if (onWrite) { int len = data.data[21] | (data.data[22] << 8); byte wdata[len]; memcpy(&wdata, &data.data[23], len); onWrite(wdata, len); } } if (data.command == NordicBLE::sd_ble_enable_cmd) { if (onReady) { onReady(ver, data.data[0]); } } if (data.command == NordicBLE::sd_ble_gap_adv_data_set_cmd) { if (onSetAdvData) { onSetAdvData(data.data[0]); } } if (data.command == NordicBLE::sd_ble_uuid_vs_add_cmd) { ble->sd_ble_gap_device_name_set(this->name); } if (data.command == NordicBLE::sd_ble_version_get_cmd) { if (onReady) { if (data.data[0] == 0) { ver.lmp = data.data[4]; ver.companyID = data.data[5] | (data.data[6] << 8); ver.firmwareID = data.data[7] | (data.data[8] << 8); } ble->sd_ble_enable(); } } if (data.command == NordicBLE::sd_ble_gap_device_name_set_cmd) { ble->sd_ble_version_get(); } if (data.command == NordicBLE::sd_ble_gatts_service_add_cmd) { if (onServiceAdded) { uint16_t handle = data.data[4] | (data.data[5] << 8); onServiceAdded(handle, data.data[0]); } } if (data.command == NordicBLE::sd_ble_gatts_characteristic_add_cmd) { if (onCharacteristicAdded) { if (data.data[4] > 0) { uint16_t handle = data.data[5] | (data.data[6] << 8); onCharacteristicAdded(handle, data.data[0]); } else { onCharacteristicAdded(0, data.data[0]); } } } } void FaboBLE::init(void) { ble->sd_ble_version_get(); } void FaboBLE::init(const char *name, uint8_t *uuid) { this->name = name; ble->sd_ble_uuid_vs_add(uuid); } void FaboBLE::scan(void) { ble->sd_ble_gap_scan_start(); } void FaboBLE::tick(void) { ble->tick(); } void FaboBLE::setDebug(bool flg) { ble->debug = flg; } void FaboBLE::startAdvertise(void) { ble->sd_ble_gap_adv_start(); } void FaboBLE::setAdvData(byte *data, uint8_t dataLen) { ble->sd_ble_gap_adv_data_set(data, dataLen); } void FaboBLE::addService(uint16_t uuid, bool SIGUUID, bool primary) { uint8_t serviceType = primary ? 0x01 : 0x02; uint8_t uuidType = SIGUUID ? 0x01 : 0x02; ble->sd_ble_gatts_service_add(serviceType, uuidType, uuid); } void FaboBLE::addCharacteristic(uint8_t handle, byte *data, uint8_t dataLen, uint16_t uuid, bool SIGUUID) { // TODO: NordicBLE::GattCharProps props; props.read = 1; props.write = 1; uint8_t uuidType = SIGUUID ? 0x01 : 0x02; ble->sd_ble_gatts_characteristic_add(handle, props, uuidType, uuid, data, dataLen); }
26.169082
107
0.637807
ThomasLengeling
24189f4943e6c9d262cc34d0d50e2198698c5219
1,896
cpp
C++
MFMediaPropDump/MediaDump.cpp
amate/MFVideoReader
e766d018b6a738df200f0f7c36b78833b1dcd924
[ "MIT" ]
13
2020-02-25T10:07:22.000Z
2021-12-11T18:49:08.000Z
MFMediaPropDump/MediaDump.cpp
amate/MFVideoReader
e766d018b6a738df200f0f7c36b78833b1dcd924
[ "MIT" ]
null
null
null
MFMediaPropDump/MediaDump.cpp
amate/MFVideoReader
e766d018b6a738df200f0f7c36b78833b1dcd924
[ "MIT" ]
3
2020-02-25T22:02:00.000Z
2022-03-01T08:07:07.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "stdafx.h" #include "common.h" #include "helper.h" #include "mediatypedump.h" #include "metadatadump.h" #include "drmdump.h" #include "mediadump.h" #include "sourceresolver.h" /////////////////////////////////////////////////////////////////////////////// HRESULT CMediaDumper::Dump( __out LPWSTR pwszFilePath) { HRESULT hr = S_OK; IMFMediaSource *pMediaSrc = NULL; BOOL bIsDRM = FALSE; CMediaTypeDumper mediaTypeDumper; CMetadataDumper metadataDumper; CDRMDumper *pDRMDumper = NULL; if (NULL == pwszFilePath) { hr = E_INVALIDARG; return hr; } pDRMDumper = new (std::nothrow) CDRMDumper; CHECK_HR(hr = CSourceResolver::CreateMediaSource( pwszFilePath, &pMediaSrc)); CHECK_HR(hr = mediaTypeDumper.Dump(pMediaSrc)); // Ignoring metadata dump failures metadataDumper.Dump(pMediaSrc); // WMIsContentProtected() in some cases when it can't determine whether // the content is DRM returns failing hr but sets bIsDRM to TRUE. We treat // such files as NOT DRM. That means that we don't dump DRM info for // them. Also we don't propagate that failing hr for such cases. hr = WMIsContentProtected( pwszFilePath, &bIsDRM); if (S_OK != hr) { bIsDRM = FALSE; hr = S_OK; } else if (TRUE == bIsDRM) { // Ignoring DRM dump failures pDRMDumper->Dump(pwszFilePath); } done: if (NULL != pMediaSrc) { pMediaSrc->Shutdown(); } SAFE_RELEASE(pMediaSrc); delete pDRMDumper; return hr; }
25.621622
79
0.632384
amate
241e6bda3f32e59c906208bbfe614868ef8101a3
10,719
cpp
C++
src/RcppExports.cpp
mklarqvist/rtomahawk
cd6337dac479dcc121a02fe7590616d4aa302ffa
[ "MIT" ]
4
2019-01-28T15:39:16.000Z
2020-05-12T18:06:35.000Z
src/RcppExports.cpp
mklarqvist/rtomahawk
cd6337dac479dcc121a02fe7590616d4aa302ffa
[ "MIT" ]
3
2019-06-11T12:10:52.000Z
2020-05-13T23:30:45.000Z
src/RcppExports.cpp
mklarqvist/rtomahawk
cd6337dac479dcc121a02fe7590616d4aa302ffa
[ "MIT" ]
2
2019-05-22T22:08:03.000Z
2020-06-12T02:07:29.000Z
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // CheckIntervalContig bool CheckIntervalContig(const std::string& interval); RcppExport SEXP _rtomahawk_CheckIntervalContig(SEXP intervalSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string& >::type interval(intervalSEXP); rcpp_result_gen = Rcpp::wrap(CheckIntervalContig(interval)); return rcpp_result_gen; END_RCPP } // CheckIntervalContigPosition bool CheckIntervalContigPosition(const std::string& interval); RcppExport SEXP _rtomahawk_CheckIntervalContigPosition(SEXP intervalSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string& >::type interval(intervalSEXP); rcpp_result_gen = Rcpp::wrap(CheckIntervalContigPosition(interval)); return rcpp_result_gen; END_RCPP } // CheckIntervalContigRange bool CheckIntervalContigRange(const std::string& interval); RcppExport SEXP _rtomahawk_CheckIntervalContigRange(SEXP intervalSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string& >::type interval(intervalSEXP); rcpp_result_gen = Rcpp::wrap(CheckIntervalContigRange(interval)); return rcpp_result_gen; END_RCPP } // CheckInterval int CheckInterval(const std::string& interval); RcppExport SEXP _rtomahawk_CheckInterval(SEXP intervalSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string& >::type interval(intervalSEXP); rcpp_result_gen = Rcpp::wrap(CheckInterval(interval)); return rcpp_result_gen; END_RCPP } // twk_version std::string twk_version(); RcppExport SEXP _rtomahawk_twk_version() { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = Rcpp::wrap(twk_version()); return rcpp_result_gen; END_RCPP } // twk_import Rcpp::S4 twk_import(std::string& input, std::string& output, double missingness, int32_t block_size, int32_t c_level, bool filter_univariate); RcppExport SEXP _rtomahawk_twk_import(SEXP inputSEXP, SEXP outputSEXP, SEXP missingnessSEXP, SEXP block_sizeSEXP, SEXP c_levelSEXP, SEXP filter_univariateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string& >::type input(inputSEXP); Rcpp::traits::input_parameter< std::string& >::type output(outputSEXP); Rcpp::traits::input_parameter< double >::type missingness(missingnessSEXP); Rcpp::traits::input_parameter< int32_t >::type block_size(block_sizeSEXP); Rcpp::traits::input_parameter< int32_t >::type c_level(c_levelSEXP); Rcpp::traits::input_parameter< bool >::type filter_univariate(filter_univariateSEXP); rcpp_result_gen = Rcpp::wrap(twk_import(input, output, missingness, block_size, c_level, filter_univariate)); return rcpp_result_gen; END_RCPP } // twk_head Rcpp::DataFrame twk_head(Rcpp::S4& obj, uint32_t n_records); RcppExport SEXP _rtomahawk_twk_head(SEXP objSEXP, SEXP n_recordsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::S4& >::type obj(objSEXP); Rcpp::traits::input_parameter< uint32_t >::type n_records(n_recordsSEXP); rcpp_result_gen = Rcpp::wrap(twk_head(obj, n_records)); return rcpp_result_gen; END_RCPP } // twk_tail Rcpp::DataFrame twk_tail(Rcpp::S4& obj, uint32_t n_records); RcppExport SEXP _rtomahawk_twk_tail(SEXP objSEXP, SEXP n_recordsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::S4& >::type obj(objSEXP); Rcpp::traits::input_parameter< uint32_t >::type n_records(n_recordsSEXP); rcpp_result_gen = Rcpp::wrap(twk_tail(obj, n_records)); return rcpp_result_gen; END_RCPP } // OpenTomahawkOutput Rcpp::S4 OpenTomahawkOutput(std::string input); RcppExport SEXP _rtomahawk_OpenTomahawkOutput(SEXP inputSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type input(inputSEXP); rcpp_result_gen = Rcpp::wrap(OpenTomahawkOutput(input)); return rcpp_result_gen; END_RCPP } // ReadRecordsIntervals Rcpp::S4 ReadRecordsIntervals(const Rcpp::S4& twk, const Rcpp::S4& filters, const std::vector<std::string>& intervals, bool really); RcppExport SEXP _rtomahawk_ReadRecordsIntervals(SEXP twkSEXP, SEXP filtersSEXP, SEXP intervalsSEXP, SEXP reallySEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const Rcpp::S4& >::type twk(twkSEXP); Rcpp::traits::input_parameter< const Rcpp::S4& >::type filters(filtersSEXP); Rcpp::traits::input_parameter< const std::vector<std::string>& >::type intervals(intervalsSEXP); Rcpp::traits::input_parameter< bool >::type really(reallySEXP); rcpp_result_gen = Rcpp::wrap(ReadRecordsIntervals(twk, filters, intervals, really)); return rcpp_result_gen; END_RCPP } // ReadRecords Rcpp::S4 ReadRecords(const Rcpp::S4& twk, const Rcpp::S4& filters, bool really); RcppExport SEXP _rtomahawk_ReadRecords(SEXP twkSEXP, SEXP filtersSEXP, SEXP reallySEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const Rcpp::S4& >::type twk(twkSEXP); Rcpp::traits::input_parameter< const Rcpp::S4& >::type filters(filtersSEXP); Rcpp::traits::input_parameter< bool >::type really(reallySEXP); rcpp_result_gen = Rcpp::wrap(ReadRecords(twk, filters, really)); return rcpp_result_gen; END_RCPP } // twk_decay Rcpp::DataFrame twk_decay(Rcpp::S4& obj, uint32_t range, uint32_t n_bins); RcppExport SEXP _rtomahawk_twk_decay(SEXP objSEXP, SEXP rangeSEXP, SEXP n_binsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::S4& >::type obj(objSEXP); Rcpp::traits::input_parameter< uint32_t >::type range(rangeSEXP); Rcpp::traits::input_parameter< uint32_t >::type n_bins(n_binsSEXP); rcpp_result_gen = Rcpp::wrap(twk_decay(obj, range, n_bins)); return rcpp_result_gen; END_RCPP } // twk_read_aggregate Rcpp::S4 twk_read_aggregate(const std::string input); RcppExport SEXP _rtomahawk_twk_read_aggregate(SEXP inputSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string >::type input(inputSEXP); rcpp_result_gen = Rcpp::wrap(twk_read_aggregate(input)); return rcpp_result_gen; END_RCPP } // twk_aggregate Rcpp::S4 twk_aggregate(const Rcpp::S4& twk, std::string agg_name, std::string red_name, int32_t xbins, int32_t ybins, int32_t min_count, int32_t threads, bool verbose, bool progress); RcppExport SEXP _rtomahawk_twk_aggregate(SEXP twkSEXP, SEXP agg_nameSEXP, SEXP red_nameSEXP, SEXP xbinsSEXP, SEXP ybinsSEXP, SEXP min_countSEXP, SEXP threadsSEXP, SEXP verboseSEXP, SEXP progressSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const Rcpp::S4& >::type twk(twkSEXP); Rcpp::traits::input_parameter< std::string >::type agg_name(agg_nameSEXP); Rcpp::traits::input_parameter< std::string >::type red_name(red_nameSEXP); Rcpp::traits::input_parameter< int32_t >::type xbins(xbinsSEXP); Rcpp::traits::input_parameter< int32_t >::type ybins(ybinsSEXP); Rcpp::traits::input_parameter< int32_t >::type min_count(min_countSEXP); Rcpp::traits::input_parameter< int32_t >::type threads(threadsSEXP); Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP); Rcpp::traits::input_parameter< bool >::type progress(progressSEXP); rcpp_result_gen = Rcpp::wrap(twk_aggregate(twk, agg_name, red_name, xbins, ybins, min_count, threads, verbose, progress)); return rcpp_result_gen; END_RCPP } // twk_scalc Rcpp::S4 twk_scalc(const Rcpp::S4& twk, std::string interval, int32_t window, double minP, double minR2, int32_t threads, bool verbose, bool progress); RcppExport SEXP _rtomahawk_twk_scalc(SEXP twkSEXP, SEXP intervalSEXP, SEXP windowSEXP, SEXP minPSEXP, SEXP minR2SEXP, SEXP threadsSEXP, SEXP verboseSEXP, SEXP progressSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const Rcpp::S4& >::type twk(twkSEXP); Rcpp::traits::input_parameter< std::string >::type interval(intervalSEXP); Rcpp::traits::input_parameter< int32_t >::type window(windowSEXP); Rcpp::traits::input_parameter< double >::type minP(minPSEXP); Rcpp::traits::input_parameter< double >::type minR2(minR2SEXP); Rcpp::traits::input_parameter< int32_t >::type threads(threadsSEXP); Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP); Rcpp::traits::input_parameter< bool >::type progress(progressSEXP); rcpp_result_gen = Rcpp::wrap(twk_scalc(twk, interval, window, minP, minR2, threads, verbose, progress)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_rtomahawk_CheckIntervalContig", (DL_FUNC) &_rtomahawk_CheckIntervalContig, 1}, {"_rtomahawk_CheckIntervalContigPosition", (DL_FUNC) &_rtomahawk_CheckIntervalContigPosition, 1}, {"_rtomahawk_CheckIntervalContigRange", (DL_FUNC) &_rtomahawk_CheckIntervalContigRange, 1}, {"_rtomahawk_CheckInterval", (DL_FUNC) &_rtomahawk_CheckInterval, 1}, {"_rtomahawk_twk_version", (DL_FUNC) &_rtomahawk_twk_version, 0}, {"_rtomahawk_twk_import", (DL_FUNC) &_rtomahawk_twk_import, 6}, {"_rtomahawk_twk_head", (DL_FUNC) &_rtomahawk_twk_head, 2}, {"_rtomahawk_twk_tail", (DL_FUNC) &_rtomahawk_twk_tail, 2}, {"_rtomahawk_OpenTomahawkOutput", (DL_FUNC) &_rtomahawk_OpenTomahawkOutput, 1}, {"_rtomahawk_ReadRecordsIntervals", (DL_FUNC) &_rtomahawk_ReadRecordsIntervals, 4}, {"_rtomahawk_ReadRecords", (DL_FUNC) &_rtomahawk_ReadRecords, 3}, {"_rtomahawk_twk_decay", (DL_FUNC) &_rtomahawk_twk_decay, 3}, {"_rtomahawk_twk_read_aggregate", (DL_FUNC) &_rtomahawk_twk_read_aggregate, 1}, {"_rtomahawk_twk_aggregate", (DL_FUNC) &_rtomahawk_twk_aggregate, 9}, {"_rtomahawk_twk_scalc", (DL_FUNC) &_rtomahawk_twk_scalc, 8}, {NULL, NULL, 0} }; RcppExport void R_init_rtomahawk(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
47.64
201
0.764624
mklarqvist
242204684479d378523475eb1ec900c48df76848
7,896
cxx
C++
code/plugins/xray_re/xr_game_spawn.cxx
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/plugins/xray_re/xr_game_spawn.cxx
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/plugins/xray_re/xr_game_spawn.cxx
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
#include <algorithm> #include "xr_ai_version.h" #include "xr_game_spawn.h" #include "xr_level_game.h" #include "xr_entity.h" #include "xr_entity_factory.h" #include "xr_utils.h" #include "xr_file_system.h" using namespace xray_re; xr_game_spawn::xr_game_spawn(): m_version(AI_VERSION_8), m_num_levels(0), m_num_af_slots(0), m_af_slots(0) { m_guid.reset(); m_graph_guid.reset(); } xr_game_spawn::~xr_game_spawn() { delete_elements(m_spawns); delete[] m_af_slots; } void xr_game_spawn::load_spawns(xr_reader& r) { if (!r.find_chunk(0)) xr_not_expected(); size_t num_spawns = r.r_u32(); r.debug_find_chunk(); xr_assert(num_spawns < 65536); m_spawns.reserve(num_spawns); xr_reader* f = r.open_chunk(1); xr_assert(f); for (uint32_t id = 0; id != num_spawns; ++id) { xr_reader* s = f->open_chunk(id); uint16_t obj_id; if (!s->r_chunk(0, obj_id)) xr_not_expected(); xr_assert(id == obj_id); xr_reader* o = s->open_chunk(1); xr_assert(o); size_t size = o->find_chunk(0); xr_assert(size); size_t size16 = o->r_u16(); xr_assert(size16 + 2 == size); xr_packet packet; o->r_packet(packet, size16); uint16_t pkt_id; packet.r_begin(pkt_id); xr_assert(pkt_id == M_SPAWN); const char* name = packet.skip_sz(); packet.r_seek(0); cse_abstract* entity = create_entity(name); xr_assert(entity); entity->spawn_read(packet); size = o->find_chunk(1); xr_assert(size); size16 = o->r_u16(); xr_assert(size16 + 2 == size); o->r_packet(packet, size16); packet.r_begin(pkt_id); xr_assert(pkt_id == M_UPDATE); entity->update_read(packet); m_spawns.push_back(entity); s->close_chunk(o); f->close_chunk(s); } r.close_chunk(f); if (size_t size = r.find_chunk(2)) { // FIXME: what is this? r.advance(size); r.debug_find_chunk(); } } void xr_game_spawn::save_spawns(xr_writer& w) { w.open_chunk(1); w.open_chunk(0); w.w_size_u32(m_spawns.size()); w.close_chunk(); w.open_chunk(1); uint16_t id = 0; for (xr_entity_vec_it it = m_spawns.begin(), end = m_spawns.end(); it != end; ++it, ++id) { w.open_chunk(id); w.open_chunk(0); w.w_u16(id); w.close_chunk(); w.open_chunk(1); w.open_chunk(0); xr_packet packet; (*it)->spawn_write(packet, true); w.w_size_u16(packet.w_tell()); w.w_packet(packet); w.close_chunk(); w.open_chunk(1); packet.clear(); (*it)->update_write(packet); w.w_size_u16(packet.w_tell() + 2); w.w_u16(M_UPDATE); w.w_packet(packet); w.close_chunk(); w.close_chunk(); w.close_chunk(); } w.close_chunk(); // FIXME: what is this? w.open_chunk(2); w.close_chunk(); w.close_chunk(); } void xr_game_spawn::load_af_slots(xr_reader& r) { if ((m_num_af_slots = r.r_u32())) { m_af_slots = new gg_level_point[m_num_af_slots]; r.r_cseq(m_num_af_slots, m_af_slots, gg_level_point_io()); } } void xr_game_spawn::save_af_slots(xr_writer& w) const { w.open_chunk(2); w.w_u32(m_num_af_slots); w.w_cseq(m_num_af_slots, m_af_slots, gg_level_point_io()); w.close_chunk(); } struct read_point_gs { void operator()(way_point_gs& point, xr_reader& r) const { if (!r.find_chunk(1)) xr_not_expected(); r.r_sz(point.name); r.r_fvector3(point.position); point.flags = r.r_u32(); point.node_id = r.r_u32(); point.graph_id = r.r_u16(); r.debug_find_chunk(); }}; struct read_path_gs { void operator()(way_path_gs*& _path, xr_reader& r) const { way_path_gs* path = new way_path_gs; _path = path; if (!r.r_chunk(0, path->name)) xr_not_expected(); xr_reader* s = r.open_chunk(1); xr_assert(s); uint32_t num_points = 0; if (!s->r_chunk(0, num_points)) xr_not_expected(); xr_reader* f = s->open_chunk(1); xr_assert(f); f->r_chunks(path->points, read_point_gs()); s->close_chunk(f); for (size_t size = s->find_chunk(2); size > 0; ) { xr_assert(size >= 8); size -= 8; uint16_t from = uint16_t(s->r_u32() & UINT16_MAX); unsigned n = s->r_u32(); while (n--) { xr_assert(size >= 8); size -= 8; path->links.push_back(way_link()); way_link& link = path->links.back(); link.from = from; link.to = uint16_t(s->r_u32() & UINT16_MAX); link.weight = s->r_float(); } } r.close_chunk(s); }}; void xr_game_spawn::load_paths(xr_reader& r) { if (!r.find_chunk(0)) xr_not_expected(); size_t num_paths = r.r_u32(); r.debug_find_chunk(); xr_reader* s = r.open_chunk(1); xr_assert(s); m_paths.reserve(num_paths); s->r_chunks(m_paths, read_path_gs()); r.close_chunk(s); } struct link_pred { bool operator()(const way_link& l, const way_link& r) const { return l.from < r.from || (l.from == r.from && (l.to < r.to || (l.to == r.to && l.weight < r.weight))); }}; void xr_game_spawn::save_paths(xr_writer& w) { w.open_chunk(3); w.open_chunk(0); w.w_size_u32(m_paths.size()); w.close_chunk(); w.open_chunk(1); unsigned path_idx = 0; for (way_path_gs_vec_it it = m_paths.begin(), end = m_paths.end(); it != end; ++it, ++path_idx) { way_path_gs* path = *it; w.open_chunk(path_idx); w.w_chunk(0, path->name); w.open_chunk(1); w.open_chunk(0); w.w_size_u32(path->points.size()); w.close_chunk(); w.open_chunk(1); uint32_t point_idx = 0; for (way_point_gs_vec_it it1 = path->points.begin(), end1 = path->points.end(); it1 != end1; ++it1, ++point_idx) { w.open_chunk(point_idx); w.w_chunk(0, point_idx); w.open_chunk(1); w.w_sz(it1->name); w.w_fvector3(it1->position); w.w_u32(it1->flags); w.w_u32(it1->node_id); w.w_u16(it1->graph_id); w.close_chunk(); w.close_chunk(); } w.close_chunk(); w.open_chunk(2); way_link_vec_it link = path->links.begin(), end1 = path->links.end(); std::sort(link, end1, link_pred()); for (; link != end1;) { way_link_vec_it it1 = link; for (; ++it1 != end1 && it1->from == link->from;) {} xr_assert(link != it1); w.w_u32(link->from); w.w_size_u32(it1 - link); for (; link != it1; ++link) { w.w_u32(link->to); w.w_float(link->weight); } } w.close_chunk(); w.close_chunk(); w.close_chunk(); } w.close_chunk(); w.close_chunk(); } void xr_game_spawn::load(xr_reader& r) { if (!r.find_chunk(0)) xr_not_expected(); m_version = r.r_u32(); xr_assert(m_version >= AI_VERSION_8 && m_version <= AI_VERSION_10); m_guid.load(r); m_graph_guid.load(r); size_t num_spawns = r.r_u32(); m_num_levels = r.r_u32(); r.debug_find_chunk(); xr_reader* s = r.open_chunk(1); xr_assert(s); load_spawns(*s); xr_assert(num_spawns == m_spawns.size()); r.close_chunk(s); s = r.open_chunk(2); xr_assert(s); load_af_slots(*s); r.close_chunk(s); s = r.open_chunk(3); xr_assert(s); load_paths(*s); r.close_chunk(s); if (m_version >= AI_VERSION_9) { s = r.open_chunk(4); xr_assert(s); m_graph.load(*s); r.close_chunk(s); } } void xr_game_spawn::save(xr_writer& w) { w.open_chunk(0); w.w_u32(m_version); m_guid.save(w); m_graph_guid.save(w); w.w_size_u32(m_spawns.size()); w.w_u32(m_num_levels); w.close_chunk(); save_spawns(w); save_af_slots(w); save_paths(w); if (m_version >= AI_VERSION_9) { w.open_chunk(4); m_graph.save(w); w.close_chunk(); } } bool xr_game_spawn::load(const char* path, const char* name) { xr_file_system& fs = xr_file_system::instance(); xr_reader* r = fs.r_open(path, name); if (r == 0) return false; load(*r); fs.r_close(r); return true; } bool xr_game_spawn::save(const char* path, const char* name) { xr_memory_writer* w = new xr_memory_writer(); save(*w); bool status = w->save_to(path, name); delete w; return status; } bool xr_game_spawn::load_graph(const char* path, const char* name) { if (m_graph.load(path, name)) { xr_assert(m_graph.num_levels() >= m_num_levels); xr_assert(m_graph.version() == m_version); xr_assert(m_graph.guid() == m_graph_guid); return true; } return false; } bool xr_game_spawn::save_graph(const char* path, const char* name) const { return m_graph.save(path, name); }
21.752066
104
0.665527
Rikoshet-234
2425d0d9cf2ad409ab31af4dcad7958d8e361452
46,068
cpp
C++
doc/snippets/MagnumGL.cpp
Anon1428/magnum
384e148c24293f513df69e6c03f94a2d4a1e3b6a
[ "MIT" ]
1
2022-03-02T19:44:27.000Z
2022-03-02T19:44:27.000Z
doc/snippets/MagnumGL.cpp
Anon1428/magnum
384e148c24293f513df69e6c03f94a2d4a1e3b6a
[ "MIT" ]
null
null
null
doc/snippets/MagnumGL.cpp
Anon1428/magnum
384e148c24293f513df69e6c03f94a2d4a1e3b6a
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz> 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 <tuple> /* for std::tie() :( */ #include <Corrade/Containers/ArrayViewStl.h> #include <Corrade/Containers/Reference.h> #include <Corrade/TestSuite/Tester.h> #include "Magnum/Image.h" #include "Magnum/ImageView.h" #include "Magnum/PixelFormat.h" #include "Magnum/GL/AbstractShaderProgram.h" #include "Magnum/GL/Buffer.h" #include "Magnum/GL/Context.h" #include "Magnum/GL/CubeMapTexture.h" #include "Magnum/GL/DefaultFramebuffer.h" #include "Magnum/GL/Extensions.h" #include "Magnum/GL/Framebuffer.h" #include "Magnum/GL/Mesh.h" #include "Magnum/GL/PixelFormat.h" #include "Magnum/GL/Renderer.h" #include "Magnum/GL/Renderbuffer.h" #include "Magnum/GL/RenderbufferFormat.h" #include "Magnum/GL/Shader.h" #include "Magnum/GL/Texture.h" #include "Magnum/GL/TextureFormat.h" #include "Magnum/GL/Version.h" #include "Magnum/Math/Color.h" #include "Magnum/Math/Half.h" #include "Magnum/Math/Matrix4.h" #include "Magnum/MeshTools/Interleave.h" #include "Magnum/MeshTools/CompressIndices.h" #include "Magnum/Primitives/Cube.h" #include "Magnum/Primitives/Plane.h" #include "Magnum/Shaders/FlatGL.h" #include "Magnum/Shaders/PhongGL.h" #include "Magnum/Trade/MeshData.h" #if !(defined(MAGNUM_TARGET_GLES2) && defined(MAGNUM_TARGET_WEBGL)) #include "Magnum/GL/SampleQuery.h" #endif #ifndef MAGNUM_TARGET_WEBGL #include "Magnum/GL/DebugOutput.h" #include "Magnum/GL/TimeQuery.h" #endif #ifndef MAGNUM_TARGET_GLES2 #include "Magnum/GL/BufferImage.h" #include "Magnum/GL/PrimitiveQuery.h" #include "Magnum/GL/TextureArray.h" #include "Magnum/GL/TransformFeedback.h" #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) #include "Magnum/GL/BufferTexture.h" #include "Magnum/GL/BufferTextureFormat.h" #include "Magnum/GL/CubeMapTextureArray.h" #include "Magnum/GL/MultisampleTexture.h" #endif #ifndef MAGNUM_TARGET_GLES #include "Magnum/GL/RectangleTexture.h" #endif #define DOXYGEN_ELLIPSIS(...) __VA_ARGS__ using namespace Magnum; using namespace Magnum::Math::Literals; int main() { #ifndef MAGNUM_TARGET_GLES2 { ImageView2D diffuse{PixelFormat::RGBA8Unorm, {}}; ImageView2D specular{PixelFormat::RGBA8Unorm, {}}; ImageView2D bump{PixelFormat::RGBA8Unorm, {}}; /* [method-chaining-texture] */ GL::Texture2D carDiffuseTexture, carSpecularTexture, carBumpTexture; carDiffuseTexture.setStorage(5, GL::TextureFormat::SRGB8, {256, 256}); carSpecularTexture.setStorage(3, GL::TextureFormat::R8, {256, 256}); carBumpTexture.setStorage(5, GL::TextureFormat::RGB8, {256, 256}); carDiffuseTexture.setSubImage(0, {}, diffuse); carSpecularTexture.setSubImage(0, {}, specular); carBumpTexture.setSubImage(0, {}, bump); carDiffuseTexture.generateMipmap(); carSpecularTexture.generateMipmap(); carBumpTexture.generateMipmap(); /* [method-chaining-texture] */ /* [method-chaining-texture-chained] */ carDiffuseTexture.setStorage(5, GL::TextureFormat::SRGB8, {256, 256}) .setSubImage(0, {}, diffuse) .generateMipmap(); carSpecularTexture.setStorage(3, GL::TextureFormat::R8, {256, 256}) .setSubImage(0, {}, diffuse) .generateMipmap(); carBumpTexture.setStorage(5, GL::TextureFormat::RGB8, {256, 256}) .setSubImage(0, {}, bump) .generateMipmap(); /* [method-chaining-texture-chained] */ } #endif { struct Foo { void setSomeBuffer(GLuint) {} GLuint someBuffer() { return {}; } } externalLib; char someData[1]; /* [opengl-wrapping-transfer] */ /* Transferring the instance to external library */ { GL::Buffer buffer; buffer.setData(someData, GL::BufferUsage::StaticDraw); GLuint id = buffer.release(); externalLib.setSomeBuffer(id); /* The library is responsible for deletion */ } /* Acquiring an instance from external library */ { GLuint id = externalLib.someBuffer(); GL::Buffer buffer = GL::Buffer::wrap(id, GL::ObjectFlag::DeleteOnDestruction); /* The buffer instance now handles deletion */ } /* [opengl-wrapping-transfer] */ } #ifndef MAGNUM_TARGET_GLES { struct: GL::AbstractShaderProgram {} someShader; /* [opengl-wrapping-state] */ GL::Buffer buffer; GL::Mesh mesh; // ... someShader.draw(mesh); { /* Entering a section with 3rd-party OpenGL code -- clean up all state that could cause accidental modifications of our objects from outside */ GL::Context::current().resetState(GL::Context::State::EnterExternal); /* Raw OpenGL calls */ glBindBuffer(GL_ARRAY_BUFFER, buffer.id()); glBufferStorage(GL_ARRAY_BUFFER, 32768, nullptr, GL_MAP_READ_BIT|GL_MAP_WRITE_BIT); // ... /* Exiting a section with 3rd-party OpenGL code -- reset our state tracker */ GL::Context::current().resetState(GL::Context::State::ExitExternal); } /* Use the buffer through Magnum again */ auto data = buffer.map(0, 32768, GL::Buffer::MapFlag::Read|GL::Buffer::MapFlag::Write); // ... /* [opengl-wrapping-state] */ static_cast<void>(data); } #endif #ifndef MAGNUM_TARGET_GLES { /* [opengl-wrapping-extensions] */ GL::TextureFormat format; if(GL::Context::current().isExtensionSupported<GL::Extensions::ARB::depth_buffer_float>()) format = GL::TextureFormat::DepthComponent32F; else format = GL::TextureFormat::DepthComponent24; /* [opengl-wrapping-extensions] */ static_cast<void>(format); } #endif #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) { /* [opengl-wrapping-dsa] */ GL::Texture2D texture; /* - on OpenGL 4.5+/ARB_direct_state_access this calls glTextureStorage2D() - on OpenGL 4.2+/ARB_texture_storage and OpenGL ES 3.0+ calls glTexStorage2D() - on OpenGL ES 2.0 with EXT_texture_storage calls glTexStorage2DEXT() - otherwise emulated using a sequence of four glTexImage2D() calls */ texture.setStorage(4, GL::TextureFormat::RGBA8, {256, 256}); /* [opengl-wrapping-dsa] */ } #endif { /* [portability-targets] */ #ifndef MAGNUM_TARGET_GLES GL::Renderer::setPolygonMode(GL::Renderer::PolygonMode::Line); // draw mesh as wireframe... #else // use different mesh, as polygon mode is not supported in OpenGL ES... #endif /* [portability-targets] */ } #ifndef MAGNUM_TARGET_GLES { /* [portability-extensions] */ if(GL::Context::current().isExtensionSupported<GL::Extensions::ARB::geometry_shader4>()) { // draw mesh with wireframe on top in one pass using geometry shader... } else { // draw underlying mesh... GL::Renderer::setPolygonMode(GL::Renderer::PolygonMode::Line); // draw mesh as wirefreame in second pass... } /* [portability-extensions] */ } { /* [portability-extension-assert] */ MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::geometry_shader4); // just use geometry shader and don't care about old hardware /* [portability-extension-assert] */ } { /* [portability-shaders] */ // MyShader.cpp GL::Version version = GL::Context::current().supportedVersion({ GL::Version::GL430, GL::Version::GL330, GL::Version::GL210}); GL::Shader vert{version, GL::Shader::Type::Vertex}; vert.addFile("MyShader.vert"); /* [portability-shaders] */ } #endif #ifndef MAGNUM_TARGET_GLES struct MyShader: GL::AbstractShaderProgram { /* [AbstractShaderProgram-input-attributes] */ typedef GL::Attribute<0, Vector3> Position; typedef GL::Attribute<1, Vector3> Normal; typedef GL::Attribute<2, Vector2> TextureCoordinates; /* [AbstractShaderProgram-input-attributes] */ /* [AbstractShaderProgram-output-attributes] */ enum: UnsignedInt { ColorOutput = 0, NormalOutput = 1 }; /* [AbstractShaderProgram-output-attributes] */ #if !defined(MAGNUM_TARGET_GLES) && !defined(MAGNUM_TARGET_WEBGL) /* [AbstractShaderProgram-return-hide-irrelevant] */ public: MyShader& draw(GL::Mesh& mesh) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(mesh)); } MyShader& draw(GL::Mesh&& mesh) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(mesh)); } MyShader& draw(GL::MeshView& mesh) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(mesh)); } MyShader& draw(GL::MeshView&& mesh) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(mesh)); } /* Omit these if the shader is not ready for multidraw */ MyShader& draw(GL::Mesh& mesh, const Containers::StridedArrayView1D<const UnsignedInt>& counts, const Containers::StridedArrayView1D<const UnsignedInt>& vertexOffsets, const Containers::StridedArrayView1D<const UnsignedInt>& indexOffsets) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(mesh, counts, vertexOffsets, indexOffsets)); } MyShader& draw(Containers::ArrayView<const Containers::Reference<GL::MeshView>> meshes) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(meshes)); } MyShader& draw(std::initializer_list<Containers::Reference<GL::MeshView>> meshes) { return static_cast<MyShader&>(GL::AbstractShaderProgram::draw(meshes)); } private: using GL::AbstractShaderProgram::drawTransformFeedback; using GL::AbstractShaderProgram::dispatchCompute; /* [AbstractShaderProgram-return-hide-irrelevant] */ public: #endif /* [AbstractShaderProgram-constructor] */ explicit MyShader() { /* Load shader sources */ GL::Shader vert{GL::Version::GL430, GL::Shader::Type::Vertex}; GL::Shader frag{GL::Version::GL430, GL::Shader::Type::Fragment}; vert.addFile("MyShader.vert"); frag.addFile("MyShader.frag"); /* Invoke parallel compilation for best performance */ CORRADE_INTERNAL_ASSERT_OUTPUT(GL::Shader::compile({vert, frag})); /* Attach the shaders */ attachShaders({vert, frag}); /* Link the program together */ CORRADE_INTERNAL_ASSERT_OUTPUT(link()); } /* [AbstractShaderProgram-constructor] */ /* [AbstractShaderProgram-uniforms] */ MyShader& setProjectionMatrix(const Matrix4& matrix) { setUniform(0, matrix); return *this; } MyShader& setTransformationMatrix(const Matrix4& matrix) { setUniform(1, matrix); return *this; } MyShader& setNormalMatrix(const Matrix3x3& matrix) { setUniform(2, matrix); return *this; } /* [AbstractShaderProgram-uniforms] */ /* [AbstractShaderProgram-textures] */ MyShader& bindDiffuseTexture(GL::Texture2D& texture) { texture.bind(0); return *this; } MyShader& bindSpecularTexture(GL::Texture2D& texture) { texture.bind(1); return *this; } /* [AbstractShaderProgram-textures] */ /* [AbstractShaderProgram-xfb] */ MyShader& setTransformFeedback(GL::TransformFeedback& feedback, GL::Buffer& positions, GL::Buffer& data) { feedback.attachBuffers(0, {&positions, &data}); return *this; } MyShader& setTransformFeedback(GL::TransformFeedback& feedback, Int totalCount, GL::Buffer& positions, GLintptr positionsOffset, GL::Buffer& data, GLintptr dataOffset) { feedback.attachBuffers(0, { std::make_tuple(&positions, positionsOffset, totalCount*sizeof(Vector3)), std::make_tuple(&data, dataOffset, totalCount*sizeof(Vector2ui)) }); return *this; } /* [AbstractShaderProgram-xfb] */ void foo() { { GL::Version version{}; /* [portability-shaders-bind] */ if(!GL::Context::current().isExtensionSupported<GL::Extensions::ARB::explicit_attrib_location>(version)) { bindAttributeLocation(Position::Location, "position"); // ... } /* [portability-shaders-bind] */ } /* [AbstractShaderProgram-binding] */ // Shaders attached... bindAttributeLocation(Position::Location, "position"); bindAttributeLocation(Normal::Location, "normal"); bindAttributeLocation(TextureCoordinates::Location, "textureCoordinates"); bindFragmentDataLocation(ColorOutput, "color"); bindFragmentDataLocation(NormalOutput, "normal"); // Link... /* [AbstractShaderProgram-binding] */ /* [AbstractShaderProgram-uniform-location] */ Int projectionMatrixUniform = uniformLocation("projectionMatrix"); Int transformationMatrixUniform = uniformLocation("transformationMatrix"); Int normalMatrixUniform = uniformLocation("normalMatrix"); /* [AbstractShaderProgram-uniform-location] */ static_cast<void>(projectionMatrixUniform); static_cast<void>(transformationMatrixUniform); static_cast<void>(normalMatrixUniform); /* [AbstractShaderProgram-uniform-block-binding] */ setUniformBlockBinding(uniformBlockIndex("matrices"), 0); setUniformBlockBinding(uniformBlockIndex("material"), 1); /* [AbstractShaderProgram-uniform-block-binding] */ /* [AbstractShaderProgram-texture-uniforms] */ setUniform(uniformLocation("diffuseTexture"), 0); setUniform(uniformLocation("specularTexture"), 1); /* [AbstractShaderProgram-texture-uniforms] */ /* [AbstractShaderProgram-xfb-outputs] */ setTransformFeedbackOutputs({ // Buffer 0 "position", "gl_SkipComponents1", "normal", "gl_SkipComponents1", // Buffer 1 "gl_NextBuffer", "velocity" }, TransformFeedbackBufferMode::InterleavedAttributes); /* [AbstractShaderProgram-xfb-outputs] */ } }; #endif #ifndef MAGNUM_TARGET_GLES { MyShader shader; GL::Mesh mesh; Matrix4 transformation, projection; GL::Texture2D diffuseTexture, specularTexture; /* [AbstractShaderProgram-rendering] */ shader.setTransformationMatrix(transformation) .setProjectionMatrix(projection) .bindDiffuseTexture(diffuseTexture) .bindSpecularTexture(specularTexture) .draw(mesh); /* [AbstractShaderProgram-rendering] */ } #endif { GL::Framebuffer framebuffer{{}}; /* [AbstractFramebuffer-read1] */ Image2D image = framebuffer.read(framebuffer.viewport(), {PixelFormat::RGBA8Unorm}); /* [AbstractFramebuffer-read1] */ } #ifndef MAGNUM_TARGET_GLES2 { GL::Framebuffer framebuffer{{}}; /* [AbstractFramebuffer-read2] */ GL::BufferImage2D image = framebuffer.read(framebuffer.viewport(), {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [AbstractFramebuffer-read2] */ } #endif { /* [Buffer-setdata] */ const Vector3 data[]{ DOXYGEN_ELLIPSIS({}) }; GL::Buffer buffer; buffer.setData(data); GL::Buffer buffer2{data}; // or construct & fill in a single step /* [Buffer-setdata] */ } { GL::Buffer buffer; /* [Buffer-setdata-stl] */ std::vector<Vector3> data = DOXYGEN_ELLIPSIS({}); buffer.setData(data); /* [Buffer-setdata-stl] */ } #ifndef MAGNUM_TARGET_GLES { Containers::ArrayView<const void> data; /* [Buffer-setstorage] */ GL::Buffer buffer; buffer.setStorage(data, {}); /* [Buffer-setstorage] */ } #endif { GL::Buffer buffer; /* [Buffer-setdata-allocate] */ buffer.setData({nullptr, 200*sizeof(Vector3)}); /* [Buffer-setdata-allocate] */ } #ifndef MAGNUM_TARGET_WEBGL { GL::Buffer buffer; /* [Buffer-map] */ Containers::ArrayView<Vector3> data = Containers::arrayCast<Vector3>( buffer.map(0, 200*sizeof(Vector3), GL::Buffer::MapFlag::Write|GL::Buffer::MapFlag::InvalidateBuffer)); CORRADE_INTERNAL_ASSERT(data); for(Vector3& d: data) d = {/*...*/}; CORRADE_INTERNAL_ASSERT_OUTPUT(buffer.unmap()); /* [Buffer-map] */ } { GL::Buffer buffer; /* [Buffer-flush] */ Containers::ArrayView<Vector3> data = Containers::arrayCast<Vector3>( buffer.map(0, 200*sizeof(Vector3), GL::Buffer::MapFlag::Write|GL::Buffer::MapFlag::FlushExplicit)); CORRADE_INTERNAL_ASSERT(data); for(std::size_t i: {7, 27, 56, 128}) { data[i] = {/*...*/}; buffer.flushMappedRange(i*sizeof(Vector3), sizeof(Vector3)); } CORRADE_INTERNAL_ASSERT_OUTPUT(buffer.unmap()); /* [Buffer-flush] */ } #endif { /* [Buffer-webgl-nope] */ GL::Buffer vertices; GL::Buffer indices; /* [Buffer-webgl-nope] */ } { /* [Buffer-webgl] */ GL::Buffer vertices{GL::Buffer::TargetHint::Array}; GL::Buffer indices{GL::Buffer::TargetHint::ElementArray}; /* [Buffer-webgl] */ } #ifndef MAGNUM_TARGET_GLES2 { char data[3]; /* [BufferImage-usage] */ GL::BufferImage2D image{GL::PixelFormat::RGBA, GL::PixelType::UnsignedByte, {512, 256}, data, GL::BufferUsage::StaticDraw}; /* [BufferImage-usage] */ } { /* [BufferImage-usage-wrap] */ GL::Buffer buffer; GL::BufferImage2D image{GL::PixelFormat::RGBA, GL::PixelType::UnsignedByte, {512, 256}, std::move(buffer), 524288}; /* [BufferImage-usage-wrap] */ } #ifndef MAGNUM_TARGET_GLES { /* [BufferImage-usage-query] */ GL::Texture2D texture; GL::BufferImage2D image = texture.image(0, {GL::PixelFormat::RGBA, GL::PixelType::UnsignedByte}, GL::BufferUsage::StaticRead); /* [BufferImage-usage-query] */ } #endif { char data[3]; /* [CompressedBufferImage-usage] */ GL::CompressedBufferImage2D image{GL::CompressedPixelFormat::RGBS3tcDxt1, {512, 256}, data, GL::BufferUsage::StaticDraw}; /* [CompressedBufferImage-usage] */ } { /* [CompressedBufferImage-usage-wrap] */ GL::Buffer buffer; GL::CompressedBufferImage2D image{GL::CompressedPixelFormat::RGBS3tcDxt1, {512, 256}, std::move(buffer), 65536}; /* [CompressedBufferImage-usage-wrap] */ } #ifndef MAGNUM_TARGET_GLES { /* [CompressedBufferImage-usage-query] */ GL::Texture2D texture; GL::CompressedBufferImage2D image = texture.compressedImage(0, {}, GL::BufferUsage::StaticRead); /* [CompressedBufferImage-usage-query] */ } #endif #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) { /* [BufferTexture-usage] */ GL::Buffer buffer; GL::BufferTexture texture; texture.setBuffer(GL::BufferTextureFormat::RGB32F, buffer); Vector3 data[200]{ // ... }; buffer.setData(data, GL::BufferUsage::StaticDraw); /* [BufferTexture-usage] */ } #endif #ifndef MAGNUM_TARGET_GLES { /* [Context-supportedVersion] */ GL::Version v1 = GL::Context::current().isVersionSupported(GL::Version::GL330) ? GL::Version::GL330 : GL::Version::GL210; GL::Version v2 = GL::Context::current().supportedVersion({ GL::Version::GL330, GL::Version::GL210}); /* [Context-supportedVersion] */ static_cast<void>(v1); static_cast<void>(v2); /* [Context-isExtensionSupported] */ if(GL::Context::current().isExtensionSupported<GL::Extensions::ARB::tessellation_shader>()) { // draw fancy detailed model } else { // texture fallback } /* [Context-isExtensionSupported] */ /* [Context-isExtensionSupported-version] */ const GL::Version version = GL::Context::current().supportedVersion({ GL::Version::GL320, GL::Version::GL300, GL::Version::GL210}); if(GL::Context::current().isExtensionSupported<GL::Extensions::ARB::explicit_attrib_location>(version)) { // Called only if ARB_explicit_attrib_location is supported // *and* version is higher than GL 3.1 } /* [Context-isExtensionSupported-version] */ /* [Context-MAGNUM_ASSERT_GL_VERSION_SUPPORTED] */ MAGNUM_ASSERT_GL_VERSION_SUPPORTED(GL::Version::GL330); /* [Context-MAGNUM_ASSERT_GL_VERSION_SUPPORTED] */ /* [Context-MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED] */ MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::geometry_shader4); /* [Context-MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED] */ } #endif #if !(defined(MAGNUM_TARGET_GLES2) && defined(MAGNUM_TARGET_WEBGL)) { char data[1]{}; ImageView2D negativeX(GL::PixelFormat::RGBA, GL::PixelType::UnsignedByte, {256, 256}, data); /* [CubeMapTexture-usage] */ ImageView2D positiveX(GL::PixelFormat::RGBA, GL::PixelType::UnsignedByte, {256, 256}, data); // ... GL::CubeMapTexture texture; texture.setMagnificationFilter(GL::SamplerFilter::Linear) // ... .setStorage(Math::log2(256)+1, GL::TextureFormat::RGBA8, {256, 256}) .setSubImage(GL::CubeMapCoordinate::PositiveX, 0, {}, positiveX) .setSubImage(GL::CubeMapCoordinate::NegativeX, 0, {}, negativeX) // ... /* [CubeMapTexture-usage] */ ; } #endif #ifndef MAGNUM_TARGET_GLES { GL::CubeMapTexture texture; /* [CubeMapTexture-image1] */ Image3D image = texture.image(0, {PixelFormat::RGBA8Unorm}); /* [CubeMapTexture-image1] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-image2] */ GL::BufferImage3D image = texture.image(0, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-image2] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-compressedImage1] */ CompressedImage3D image = texture.compressedImage(0, {}); /* [CubeMapTexture-compressedImage1] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-compressedImage2] */ GL::CompressedBufferImage3D image = texture.compressedImage(0, {}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-compressedImage2] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-image3] */ Image2D image = texture.image(GL::CubeMapCoordinate::PositiveX, 0, {PixelFormat::RGBA8Unorm}); /* [CubeMapTexture-image3] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-image4] */ GL::BufferImage2D image = texture.image(GL::CubeMapCoordinate::PositiveX, 0, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-image4] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-compressedImage3] */ CompressedImage2D image = texture.compressedImage(GL::CubeMapCoordinate::PositiveX, 0, {}); /* [CubeMapTexture-compressedImage3] */ } { GL::CubeMapTexture texture; /* [CubeMapTexture-compressedImage4] */ GL::CompressedBufferImage2D image = texture.compressedImage(GL::CubeMapCoordinate::PositiveX, 0, {}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-compressedImage4] */ } { GL::CubeMapTexture texture; Range3Di range; /* [CubeMapTexture-subImage1] */ Image3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}); /* [CubeMapTexture-subImage1] */ } { GL::CubeMapTexture texture; Range3Di range; /* [CubeMapTexture-subImage2] */ GL::BufferImage3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-subImage2] */ } { GL::CubeMapTexture texture; Range3Di range; /* [CubeMapTexture-compressedSubImage1] */ CompressedImage3D image = texture.compressedSubImage(0, range, {}); /* [CubeMapTexture-compressedSubImage1] */ } { GL::CubeMapTexture texture; Range3Di range; /* [CubeMapTexture-compressedSubImage2] */ GL::CompressedBufferImage3D image = texture.compressedSubImage(0, range, {}, GL::BufferUsage::StaticRead); /* [CubeMapTexture-compressedSubImage2] */ } #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) { char data[1]{}; ImageView3D imageNegativeX(PixelFormat::RGBA8Unorm, {64, 64, 1}, data); ImageView3D imagePositiveY(PixelFormat::RGBA8Unorm, {64, 64, 1}, data); /* [CubeMapTextureArray-usage] */ GL::CubeMapTextureArray texture; texture.setMagnificationFilter(GL::SamplerFilter::Linear) // ... .setStorage(Math::log2(64)+1, GL::TextureFormat::RGBA8, {64, 64, 24}); for(std::size_t i = 0; i != 4; i += 6) { ImageView3D imagePositiveX(PixelFormat::RGBA8Unorm, {64, 64, 1}, data); // ... texture.setSubImage(0, Vector3i::zAxis(i+0), imagePositiveX); texture.setSubImage(0, Vector3i::zAxis(i+1), imageNegativeX); texture.setSubImage(0, Vector3i::zAxis(i+2), imagePositiveY); // ... } texture.generateMipmap(); /* [CubeMapTextureArray-usage] */ } #ifndef MAGNUM_TARGET_GLES { GL::CubeMapTextureArray texture; /* [CubeMapTextureArray-image1] */ Image3D image = texture.image(0, {PixelFormat::RGBA8Unorm}); /* [CubeMapTextureArray-image1] */ } { GL::CubeMapTextureArray texture; /* [CubeMapTextureArray-image2] */ GL::BufferImage3D image = texture.image(0, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [CubeMapTextureArray-image2] */ } { GL::CubeMapTextureArray texture; /* [CubeMapTextureArray-compressedImage1] */ CompressedImage3D image = texture.compressedImage(0, {}); /* [CubeMapTextureArray-compressedImage1] */ } { GL::CubeMapTextureArray texture; /* [CubeMapTextureArray-compressedImage2] */ GL::CompressedBufferImage3D image = texture.compressedImage(0, {}, GL::BufferUsage::StaticRead); /* [CubeMapTextureArray-compressedImage2] */ } { GL::CubeMapTextureArray texture; Range3Di range; /* [CubeMapTextureArray-subImage1] */ Image3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}); /* [CubeMapTextureArray-subImage1] */ } { GL::CubeMapTextureArray texture; Range3Di range; /* [CubeMapTextureArray-subImage2] */ GL::BufferImage3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [CubeMapTextureArray-subImage2] */ } { GL::CubeMapTextureArray texture; Range3Di range; /* [CubeMapTextureArray-compressedSubImage1] */ CompressedImage3D image = texture.compressedSubImage(0, range, {}); /* [CubeMapTextureArray-compressedSubImage1] */ } { GL::CubeMapTextureArray texture; Range3Di range; /* [CubeMapTextureArray-compressedSubImage2] */ GL::CompressedBufferImage3D image = texture.compressedSubImage(0, range, {}, GL::BufferUsage::StaticRead); /* [CubeMapTextureArray-compressedSubImage2] */ } #endif #endif #ifndef MAGNUM_TARGET_WEBGL { GL::Mesh mesh; struct: GL::AbstractShaderProgram {} shader; /* [DebugOutput-usage] */ GL::Renderer::enable(GL::Renderer::Feature::DebugOutput); GL::Renderer::enable(GL::Renderer::Feature::DebugOutputSynchronous); GL::DebugOutput::setDefaultCallback(); /* Disable rather spammy "Buffer detailed info" debug messages on NVidia drivers */ GL::DebugOutput::setEnabled( GL::DebugOutput::Source::Api, GL::DebugOutput::Type::Other, {131185}, false); { GL::DebugGroup group{GL::DebugGroup::Source::Application, 42, "Scene rendering"}; GL::DebugMessage::insert(GL::DebugMessage::Source::Application, GL::DebugMessage::Type::Marker, 1337, GL::DebugOutput::Severity::Notification, "Rendering a transparent mesh"); GL::Renderer::enable(GL::Renderer::Feature::Blending); shader.draw(mesh); GL::Renderer::disable(GL::Renderer::Feature::Blending); // ... } /* [DebugOutput-usage] */ } { /* [DebugOutput-setDefaultCallback] */ GL::DebugMessage::insert(GL::DebugMessage::Source::Application, GL::DebugMessage::Type::Marker, 1337, GL::DebugOutput::Severity::Notification, "Hello from OpenGL command stream!"); /* [DebugOutput-setDefaultCallback] */ } { /* [DebugMessage-usage] */ GL::DebugMessage::insert(GL::DebugMessage::Source::Application, GL::DebugMessage::Type::Marker, 1337, GL::DebugOutput::Severity::Notification, "Hello from OpenGL command stream!"); /* [DebugMessage-usage] */ } { GL::Mesh mesh; struct: GL::AbstractShaderProgram {} shader; /* [DebugGroup-usage1] */ { /* Push debug group */ GL::DebugGroup group{GL::DebugGroup::Source::Application, 42, "Scene rendering"}; GL::Renderer::enable(GL::Renderer::Feature::Blending); shader.draw(mesh); GL::Renderer::disable(GL::Renderer::Feature::Blending); /* The debug group is popped automatically at the end of the scope */ } /* [DebugGroup-usage1] */ } { GL::Mesh mesh; struct: GL::AbstractShaderProgram {} shader; /* [DebugGroup-usage2] */ GL::DebugGroup group; group.push(GL::DebugGroup::Source::Application, 42, "Scene rendering"); GL::Renderer::enable(GL::Renderer::Feature::Blending); shader.draw(mesh); GL::Renderer::disable(GL::Renderer::Feature::Blending); group.pop(); /* [DebugGroup-usage2] */ } #endif { struct MyShader { enum: UnsignedInt { ColorOutput = 0, NormalOutput = 1 }; }; /* [DefaultFramebuffer-usage-map] */ GL::defaultFramebuffer.mapForDraw({ {MyShader::ColorOutput, GL::DefaultFramebuffer::DrawAttachment::Back}, {MyShader::NormalOutput, GL::DefaultFramebuffer::DrawAttachment::None}}); /* [DefaultFramebuffer-usage-map] */ } #ifndef MAGNUM_TARGET_GLES2 { struct MyShader { void bindTexture(GL::Texture2D&) {} } myShader; Vector2i size; /* [Framebuffer-usage] */ GL::Texture2D color; GL::Renderbuffer depthStencil; color.setStorage(1, GL::TextureFormat::RGBA8, size); depthStencil.setStorage(GL::RenderbufferFormat::Depth24Stencil8, size); GL::Framebuffer framebuffer{{{}, size}}; framebuffer.attachTexture(GL::Framebuffer::ColorAttachment{0}, color, 0); framebuffer.attachRenderbuffer( GL::Framebuffer::BufferAttachment::DepthStencil, depthStencil); /* [Framebuffer-usage] */ /* [Framebuffer-usage-rendering] */ framebuffer .clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth) .bind(); // draw to this framebuffer ... /* Switch back to the default framebuffer */ GL::defaultFramebuffer .clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth) .bind(); // use the rendered texture in a shader ... myShader.bindTexture(color); /* [Framebuffer-usage-rendering] */ } #endif #ifndef MAGNUM_TARGET_GLES2 { /* [Framebuffer-usage-multisample] */ Vector2i size = GL::defaultFramebuffer.viewport().size(); /* 8x MSAA */ GL::Renderbuffer color, depthStencil; color.setStorageMultisample(8, GL::RenderbufferFormat::RGBA8, size); depthStencil.setStorageMultisample(8, GL::RenderbufferFormat::Depth24Stencil8, size); GL::Framebuffer framebuffer{{{}, size}}; framebuffer.attachRenderbuffer(GL::Framebuffer::ColorAttachment{0}, color); framebuffer.attachRenderbuffer( GL::Framebuffer::BufferAttachment::DepthStencil, depthStencil); framebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth) .bind(); // draw to the multisampled framebuffer ... /* Resolve the color output to a single-sampled default framebuffer */ GL::defaultFramebuffer.clear(GL::FramebufferClear::Color) .bind(); GL::Framebuffer::blit(framebuffer, GL::defaultFramebuffer, {{}, size}, GL::FramebufferBlit::Color); /* [Framebuffer-usage-multisample] */ } #endif #ifndef MAGNUM_TARGET_GLES2 { struct MyShader { enum: UnsignedInt { ColorOutput = 0, NormalOutput = 1 }; }; /* [Framebuffer-usage-deferred] */ GL::Framebuffer framebuffer{GL::defaultFramebuffer.viewport()}; GL::Texture2D color, normal; GL::Renderbuffer depthStencil; // setStorage() ... framebuffer.attachTexture(GL::Framebuffer::ColorAttachment{0}, color, 0); framebuffer.attachTexture(GL::Framebuffer::ColorAttachment{1}, normal, 0); framebuffer.attachRenderbuffer( GL::Framebuffer::BufferAttachment::DepthStencil, depthStencil); framebuffer.mapForDraw({ {MyShader::ColorOutput, GL::Framebuffer::ColorAttachment(0)}, {MyShader::NormalOutput, GL::Framebuffer::ColorAttachment(1)}}); /* [Framebuffer-usage-deferred] */ /* [Framebuffer-mapForDraw] */ framebuffer.mapForDraw({ {MyShader::ColorOutput, GL::Framebuffer::ColorAttachment(0)}, {MyShader::NormalOutput, GL::Framebuffer::DrawAttachment::None}}); /* [Framebuffer-mapForDraw] */ } #endif { /* [Mesh-vertices] */ const Vector3 positions[]{ DOXYGEN_ELLIPSIS({}) }; GL::Buffer vertices{positions}; GL::Mesh mesh; mesh.setCount(Containers::arraySize(positions)) .addVertexBuffer(vertices, 0, Shaders::FlatGL3D::Position{}); /* [Mesh-vertices] */ } { /* [Mesh-vertices-interleaved] */ struct Vertex { Vector3 position; Vector3 normal; }; const Vertex vertexData[]{ DOXYGEN_ELLIPSIS({}) }; GL::Buffer vertices{vertexData}; GL::Mesh mesh; mesh.setCount(Containers::arraySize(vertexData)) .addVertexBuffer(vertices, 0, Shaders::PhongGL::Position{}, Shaders::PhongGL::Normal{}); /* [Mesh-vertices-interleaved] */ } { GL::Mesh mesh; /* [Mesh-indices] */ const UnsignedInt indexData[]{ DOXYGEN_ELLIPSIS(0) }; GL::Buffer indices{indexData}; DOXYGEN_ELLIPSIS() mesh.setIndexBuffer(indices, 0, MeshIndexType::UnsignedInt); /* [Mesh-indices] */ } { GL::Mesh mesh; /* [Mesh-vertices-interleaved-tool] */ Containers::ArrayView<const Vector3> positions = DOXYGEN_ELLIPSIS({}); Containers::ArrayView<const Vector3> normals = DOXYGEN_ELLIPSIS({}); GL::Buffer vertices{MeshTools::interleave(positions, normals)}; DOXYGEN_ELLIPSIS() mesh.addVertexBuffer(vertices, 0, Shaders::PhongGL::Position{}, Shaders::PhongGL::Normal{}); /* [Mesh-vertices-interleaved-tool] */ } { GL::Mesh mesh; const UnsignedInt indexData[1]{}; /* [Mesh-indices-tool] */ Containers::Array<char> compressed; MeshIndexType type; std::tie(compressed, type) = MeshTools::compressIndices(indexData); GL::Buffer indices{compressed}; DOXYGEN_ELLIPSIS() mesh.setIndexBuffer(indices, 0, type); /* [Mesh-indices-tool] */ } #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) /* The damn thing doesn't understand unnamed bitfields in local structs */ #ifndef CORRADE_MSVC2015_COMPATIBILITY { GL::Mesh mesh; /* [Mesh-formats] */ struct Packed { Vector3h position; Short:16; Vector3s normal; Short:16; }; const Packed vertexData[]{ DOXYGEN_ELLIPSIS({}) }; GL::Buffer vertices{vertexData}; DOXYGEN_ELLIPSIS() mesh.addVertexBuffer(vertices, 0, Shaders::PhongGL::Position{Shaders::PhongGL::Position::Components::Three, Shaders::PhongGL::Position::DataType::Half}, 2, Shaders::PhongGL::Normal{Shaders::PhongGL::Normal::Components::Three, Shaders::PhongGL::Normal::DataType::Short, Shaders::PhongGL::Normal::DataOption::Normalized}, 2); /* [Mesh-formats] */ /* [Mesh-formats-vertexformat] */ mesh.addVertexBuffer(vertices, offsetof(Packed, position), sizeof(Packed), GL::DynamicAttribute{Shaders::PhongGL::Position{}, VertexFormat::Vector3h}); mesh.addVertexBuffer(vertices, offsetof(Packed, normal), sizeof(Packed), GL::DynamicAttribute{Shaders::PhongGL::Normal{}, VertexFormat::Vector3sNormalized}); /* [Mesh-formats-vertexformat] */ } #endif #endif { GL::Mesh mesh; GL::Buffer colorBuffer; /* [Mesh-dynamic] */ mesh.addVertexBuffer(colorBuffer, 0, 4, GL::DynamicAttribute{ GL::DynamicAttribute::Kind::GenericNormalized, 3, GL::DynamicAttribute::Components::Three, GL::DynamicAttribute::DataType::UnsignedByte}); /* [Mesh-dynamic] */ } { GL::Mesh mesh; /* [Mesh-buffer-ownership] */ GL::Buffer vertices, indices; DOXYGEN_ELLIPSIS() mesh.addVertexBuffer(std::move(vertices), 0, Shaders::PhongGL::Position{}, Shaders::PhongGL::Normal{}) .setIndexBuffer(std::move(indices), 0, MeshIndexType::UnsignedInt); /* [Mesh-buffer-ownership] */ /* [Mesh-buffer-ownership-multiple] */ mesh.addVertexBuffer(vertices, 0, Shaders::PhongGL::Position{}, 20) .addVertexBuffer(std::move(vertices), 0, 20, Shaders::PhongGL::Normal{}); /* [Mesh-buffer-ownership-multiple] */ } { GL::Mesh mesh; /* [Mesh-draw] */ Shaders::PhongGL shader{DOXYGEN_ELLIPSIS()}; DOXYGEN_ELLIPSIS() shader.draw(mesh); /* [Mesh-draw] */ } { /* [Mesh-addVertexBuffer1] */ GL::Buffer buffer; GL::Mesh mesh; mesh.addVertexBuffer(buffer, 76, /* initial array offset */ 4, /* skip vertex weight (Float) */ Shaders::PhongGL::Position(), /* vertex position */ 8, /* skip texture coordinates (Vector2) */ Shaders::PhongGL::Normal()); /* vertex normal */ /* [Mesh-addVertexBuffer1] */ /* [Mesh-addVertexBuffer2] */ mesh.addVertexBuffer(buffer, 76, 4, Shaders::PhongGL::Position{}, 20) .addVertexBuffer(buffer, 76, 24, Shaders::PhongGL::Normal{}, 0); /* [Mesh-addVertexBuffer2] */ /* [Mesh-addVertexBuffer3] */ Int vertexCount = 352; mesh.addVertexBuffer(buffer, 76 + 4*vertexCount, Shaders::PhongGL::Position{}) .addVertexBuffer(buffer, 76 + 24*vertexCount, Shaders::PhongGL::Normal{}); /* [Mesh-addVertexBuffer3] */ } #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) { /* [MultisampleTexture-usage] */ GL::MultisampleTexture2D texture; texture.setStorage(16, GL::TextureFormat::RGBA8, {1024, 1024}); /* [MultisampleTexture-usage] */ } #endif struct A: TestSuite::Tester { void foo() { /* [OpenGLTester-MAGNUM_VERIFY_NO_GL_ERROR] */ CORRADE_COMPARE(Magnum::GL::Renderer::error(), Magnum::GL::Renderer::Error::NoError); /* [OpenGLTester-MAGNUM_VERIFY_NO_GL_ERROR] */ } }; #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) { /* [PrimitiveQuery-usage] */ GL::PrimitiveQuery q{GL::PrimitiveQuery::Target::PrimitivesGenerated}; q.begin(); // rendering... q.end(); if(!q.resultAvailable()) { // do some work until to give OpenGL some time... } // ...or block until the result is available UnsignedInt primitiveCount = q.result<UnsignedInt>(); /* [PrimitiveQuery-usage] */ static_cast<void>(primitiveCount); } #endif #ifndef MAGNUM_TARGET_GLES { char data[1]{}; /* [RectangleTexture-usage] */ ImageView2D image{PixelFormat::RGBA8Unorm, {526, 137}, data}; GL::RectangleTexture texture; texture.setMagnificationFilter(GL::SamplerFilter::Linear) .setMinificationFilter(GL::SamplerFilter::Linear) .setWrapping(GL::SamplerWrapping::ClampToEdge) .setMaxAnisotropy(GL::Sampler::maxMaxAnisotropy()) .setStorage(GL::TextureFormat::RGBA8, {526, 137}) .setSubImage({}, image); /* [RectangleTexture-usage] */ } { GL::RectangleTexture texture; /* [RectangleTexture-image1] */ Image2D image = texture.image({PixelFormat::RGBA8Unorm}); /* [RectangleTexture-image1] */ } { GL::RectangleTexture texture; /* [RectangleTexture-image2] */ GL::BufferImage2D image = texture.image( {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [RectangleTexture-image2] */ } { GL::RectangleTexture texture; /* [RectangleTexture-compressedImage1] */ CompressedImage2D image = texture.compressedImage({}); /* [RectangleTexture-compressedImage1] */ } { GL::RectangleTexture texture; /* [RectangleTexture-compressedImage2] */ GL::CompressedBufferImage2D image = texture.compressedImage({}, GL::BufferUsage::StaticRead); /* [RectangleTexture-compressedImage2] */ } { GL::RectangleTexture texture; Range2Di range; /* [RectangleTexture-subImage1] */ Image2D image = texture.subImage(range, {PixelFormat::RGBA8Unorm}); /* [RectangleTexture-subImage1] */ } { GL::RectangleTexture texture; Range2Di range; /* [RectangleTexture-subImage2] */ GL::BufferImage2D image = texture.subImage(range, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [RectangleTexture-subImage2] */ } { GL::RectangleTexture texture; Range2Di range; /* [RectangleTexture-compressedSubImage1] */ CompressedImage2D image = texture.compressedSubImage(range, {}); /* [RectangleTexture-compressedSubImage1] */ } { GL::RectangleTexture texture; Range2Di range; /* [RectangleTexture-compressedSubImage2] */ GL::CompressedBufferImage2D image = texture.compressedSubImage(range, {}, GL::BufferUsage::StaticRead); /* [RectangleTexture-compressedSubImage2] */ } #endif { GL::Renderer::Feature feature = GL::Renderer::Feature::Blending; bool enabled{}; /* [Renderer-setFeature] */ enabled ? GL::Renderer::enable(feature) : GL::Renderer::disable(feature) /* [Renderer-setFeature] */ ; } { /* [Renderer-setBlendFunction] */ GL::Renderer::enable(GL::Renderer::Feature::Blending); GL::Renderer::setBlendFunction( GL::Renderer::BlendFunction::One, /* or SourceAlpha for non-premultiplied */ GL::Renderer::BlendFunction::OneMinusSourceAlpha); /* [Renderer-setBlendFunction] */ } #if !(defined(MAGNUM_TARGET_GLES2) && defined(MAGNUM_TARGET_WEBGL)) { /* [SampleQuery-usage] */ GL::SampleQuery q{GL::SampleQuery::Target::AnySamplesPassed}; q.begin(); /* Render simplified object to test whether it is visible at all */ // ... q.end(); /* Render full version of the object only if it is visible */ if(q.result<bool>()) { // ... } /* [SampleQuery-usage] */ } #ifndef MAGNUM_TARGET_GLES { /* [SampleQuery-conditional-render] */ GL::SampleQuery q{GL::SampleQuery::Target::AnySamplesPassed}; q.begin(); /* Render simplified object to test whether it is visible at all */ // ... q.end(); q.beginConditionalRender(GL::SampleQuery::ConditionalRenderMode::Wait); /* Render full version of the object only if the query returns nonzero result */ // ... q.endConditionalRender(); /* [SampleQuery-conditional-render] */ } #endif #endif #if !(defined(MAGNUM_TARGET_GLES2) && defined(MAGNUM_TARGET_WEBGL)) { char data[1]{}; /* [Texture-usage] */ ImageView2D image(PixelFormat::RGBA8Unorm, {4096, 4096}, data); GL::Texture2D texture; texture.setMagnificationFilter(GL::SamplerFilter::Linear) .setMinificationFilter(GL::SamplerFilter::Linear, GL::SamplerMipmap::Linear) .setWrapping(GL::SamplerWrapping::ClampToEdge) .setMaxAnisotropy(GL::Sampler::maxMaxAnisotropy()) .setStorage(Math::log2(4096)+1, GL::TextureFormat::RGBA8, {4096, 4096}) .setSubImage(0, {}, image) .generateMipmap(); /* [Texture-usage] */ } #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) { GL::Texture2D texture; /* [Texture-setSwizzle] */ texture.setSwizzle<'b', 'g', 'r', '0'>(); /* [Texture-setSwizzle] */ } #endif #ifndef MAGNUM_TARGET_GLES { GL::Texture2D texture; /* [Texture-image1] */ Image2D image = texture.image(0, {PixelFormat::RGBA8Unorm}); /* [Texture-image1] */ } { GL::Texture2D texture; /* [Texture-image2] */ GL::BufferImage2D image = texture.image(0, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [Texture-image2] */ } { GL::Texture2D texture; /* [Texture-compressedImage1] */ CompressedImage2D image = texture.compressedImage(0, {}); /* [Texture-compressedImage1] */ } { GL::Texture2D texture; /* [Texture-compressedImage2] */ GL::CompressedBufferImage2D image = texture.compressedImage(0, {}, GL::BufferUsage::StaticRead); /* [Texture-compressedImage2] */ } { GL::Texture2D texture; Range2Di range; /* [Texture-subImage1] */ Image2D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}); /* [Texture-subImage1] */ } { GL::Texture2D texture; Range2Di range; /* [Texture-subImage2] */ GL::BufferImage2D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [Texture-subImage2] */ } { GL::Texture2D texture; Range2Di range; /* [Texture-compressedSubImage1] */ CompressedImage2D image = texture.compressedSubImage(0, range, {}); /* [Texture-compressedSubImage1] */ } { GL::Texture2D texture; Range2Di range; /* [Texture-compressedSubImage2] */ GL::CompressedBufferImage2D image = texture.compressedSubImage(0, range, {}, GL::BufferUsage::StaticRead); /* [Texture-compressedSubImage2] */ } #endif #ifndef MAGNUM_TARGET_GLES2 { /* [TextureArray-usage1] */ GL::Texture2DArray texture; texture.setMagnificationFilter(GL::SamplerFilter::Linear) .setMinificationFilter(GL::SamplerFilter::Linear, GL::SamplerMipmap::Linear) .setWrapping(GL::SamplerWrapping::ClampToEdge) .setMaxAnisotropy(GL::Sampler::maxMaxAnisotropy());; /* [TextureArray-usage1] */ Int levels{}; char data[1]{}; /* [TextureArray-usage2] */ texture.setStorage(levels, GL::TextureFormat::RGBA8, {64, 64, 16}); for(std::size_t i = 0; i != 16; ++i) { ImageView3D image(PixelFormat::RGBA8Unorm, {64, 64, 1}, data); texture.setSubImage(0, Vector3i::zAxis(i), image); } /* [TextureArray-usage2] */ } #ifndef MAGNUM_TARGET_GLES { GL::Texture2DArray texture; /* [TextureArray-image1] */ Image3D image = texture.image(0, {PixelFormat::RGBA8Unorm}); /* [TextureArray-image1] */ } { GL::Texture2DArray texture; /* [TextureArray-image2] */ GL::BufferImage3D image = texture.image(0, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [TextureArray-image2] */ } { GL::Texture2DArray texture; /* [TextureArray-compressedImage1] */ CompressedImage3D image = texture.compressedImage(0, {}); /* [TextureArray-compressedImage1] */ } { GL::Texture2DArray texture; /* [TextureArray-compressedImage2] */ GL::CompressedBufferImage3D image = texture.compressedImage(0, {}, GL::BufferUsage::StaticRead); /* [TextureArray-compressedImage2] */ } { GL::Texture2DArray texture; Range3Di range; /* [TextureArray-subImage1] */ Image3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}); /* [TextureArray-subImage1] */ } { GL::Texture2DArray texture; Range3Di range; /* [TextureArray-subImage2] */ GL::BufferImage3D image = texture.subImage(0, range, {PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead); /* [TextureArray-subImage2] */ } { GL::Texture2DArray texture; Range3Di range; /* [TextureArray-compressedSubImage1] */ CompressedImage3D image = texture.compressedSubImage(0, range, {}); /* [TextureArray-compressedSubImage1] */ } { GL::Texture2DArray texture; Range3Di range; /* [TextureArray-compressedSubImage2] */ GL::CompressedBufferImage3D image = texture.compressedSubImage(0, range, {}, GL::BufferUsage::StaticRead); /* [TextureArray-compressedSubImage2] */ } #endif #endif #ifndef MAGNUM_TARGET_WEBGL { /* [TimeQuery-usage1] */ GL::TimeQuery q1{GL::TimeQuery::Target::TimeElapsed}, q2{GL::TimeQuery::Target::TimeElapsed}; q1.begin(); // rendering... q1.end(); q2.begin(); // another rendering... q2.end(); UnsignedInt timeElapsed1 = q1.result<UnsignedInt>(); UnsignedInt timeElapsed2 = q2.result<UnsignedInt>(); /* [TimeQuery-usage1] */ static_cast<void>(timeElapsed1); static_cast<void>(timeElapsed2); } { /* [TimeQuery-usage2] */ GL::TimeQuery q1{GL::TimeQuery::Target::Timestamp}, q2{GL::TimeQuery::Target::Timestamp}, q3{GL::TimeQuery::Target::Timestamp}; q1.timestamp(); // rendering... q2.timestamp(); // another rendering... q3.timestamp(); UnsignedInt tmp = q2.result<UnsignedInt>(); UnsignedInt timeElapsed1 = tmp - q1.result<UnsignedInt>(); UnsignedInt timeElapsed2 = q3.result<UnsignedInt>() - tmp; /* [TimeQuery-usage2] */ static_cast<void>(timeElapsed1); static_cast<void>(timeElapsed2); } #endif }
28.560446
244
0.720652
Anon1428
2427af07b6305decf64f849a0aad12886c845e92
497
cpp
C++
Common/DebugLog.cpp
Souhardya/Slavyana
e5dd2f14af1499c83650c371fa86dc1c51e2556d
[ "Apache-2.0" ]
20
2021-12-31T11:28:38.000Z
2022-03-22T13:28:59.000Z
Common/DebugLog.cpp
Souhardya/Slavyana
e5dd2f14af1499c83650c371fa86dc1c51e2556d
[ "Apache-2.0" ]
null
null
null
Common/DebugLog.cpp
Souhardya/Slavyana
e5dd2f14af1499c83650c371fa86dc1c51e2556d
[ "Apache-2.0" ]
8
2022-03-12T10:09:39.000Z
2022-03-15T08:39:27.000Z
#include <windows.h> #include <stdio.h> #include "./DebugLog.h" // //Usage // //#ifdef Dbg //DebugLog(DbgInfo,L"XXX"); //#endif // //Define // #define DbgLine "\r\n%s-%s-%d: " void DebugLog(LPCSTR lpFILE, LPCSTR lpFUNCTION, int lpLINE, LPCWSTR lpOutputString) { #ifdef Dbg char strDbgLine[512] = {0}; wsprintfA(strDbgLine,DbgLine,lpFILE,lpFUNCTION,lpLINE); OutputDebugStringA(strDbgLine); OutputDebugStringW(lpOutputString); #endif return; }
13.805556
84
0.643863
Souhardya
2427d5f846c42c8938236a4d4cf63d40fd947b41
778
cpp
C++
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPDL.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPDL.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPDL.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "./INCLUDE/LKH.h" #include "./INCLUDE/Segment.h" namespace LKH { static thread_local int DemandSum; GainType LKHAlg::Penalty_TSPDL() { Node *N = Depot, *NextN; GainType P = 0; int Draft; int Forward = SUCC(N)->Id != N->Id + DimensionSaved; if (DemandSum == 0) { do { if (N->Id <= DimensionSaved) DemandSum += N->Demand; NextN = Forward ? SUCC(N) : PREDD(N); } while ((N = NextN) != Depot); } Draft = DemandSum; do { if (N->Id <= DimensionSaved) { if (Draft > N->DraftLimit && (P += Draft - N->DraftLimit) > CurrentPenalty) return CurrentPenalty + 1; Draft -= N->Demand; NextN = Forward ? SUCC(N) : PREDD(N); } NextN = Forward ? SUCC(N) : PREDD(N); } while ((N = NextN) != Depot); return P; } }
23.575758
54
0.578406
BaiChunhui-9803
242f71f6435782338c17838e5adfe869cda6a8a3
2,729
hpp
C++
src/Gui/single/Widget.hpp
classix-ps/sfml-widgets
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
[ "MIT" ]
null
null
null
src/Gui/single/Widget.hpp
classix-ps/sfml-widgets
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
[ "MIT" ]
null
null
null
src/Gui/single/Widget.hpp
classix-ps/sfml-widgets
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
[ "MIT" ]
null
null
null
#ifndef GUI_WIDGET_SINGLE_HPP #define GUI_WIDGET_SINGLE_HPP #include <SFML/Graphics.hpp> #include <iostream> #include <functional> namespace guiSingle { enum State { StateDefault, StateHovered, StatePressed, StateFocused }; class Layout; /** * Abstract base class for gui widgets */ class Widget: public sf::Drawable { public: Widget(); /** * Widget's position */ void setPosition(const sf::Vector2f& pos); void setPosition(float x, float y); const sf::Vector2f& getPosition() const; sf::Vector2f getAbsolutePosition() const; /** * Get widget's dimensions */ const sf::Vector2f& getSize() const; /** * Check if a point is inside the widget */ bool containsPoint(const sf::Vector2f& point) const; /** * Check if the widget can be selected and trigger events */ bool isSelectable() const; /** * Check if the widget is currently focused */ bool isFocused() const; /** * Set a function to be called when this widget is triggered */ void setCallback(std::function<void(void)> callback); // Event callbacks --------------------------------------------------------- virtual void onStateChanged(State state); virtual void onMouseMoved(float x, float y); virtual void onMousePressed(float x, float y); virtual void onMouseReleased(float x, float y); virtual void onMouseWheelMoved(int delta); virtual void onKeyPressed(const sf::Event::KeyEvent& key); virtual void onKeyReleased(const sf::Event::KeyEvent& key); virtual void onTextEntered(sf::Uint32 unicode); protected: void setSize(const sf::Vector2f& size); void setSize(float widget, float height); friend class Layout; friend class FormLayout; friend class HBoxLayout; friend class VBoxLayout; void setSelectable(bool selectable); /** * Notify parent that the widget has been triggered by user input */ void triggerCallback(); void setState(State state); State getState() const; /** * Set the widget's container (parent) */ void setParent(Layout* parent); Layout* getParent() { return m_parent; } // hack... virtual Layout* toLayout() { return nullptr; } void centerText(sf::Text& text); virtual void recomputeGeometry() {}; const sf::Transform& getTransform() const; private: Layout* m_parent; Widget* m_previous; Widget* m_next; State m_state; sf::Vector2f m_position; sf::Vector2f m_size; bool m_selectable; std::function<void(void)> m_callback; sf::Transform m_transform; }; } #endif // GUI_WIDGET_SINGLE_HPP
21.65873
80
0.639428
classix-ps
2433a5c8ce5ff0577fc106ee422a1cf2657e585d
1,201
cpp
C++
sources/Leetcodes/src/228_summary_ranges.cpp
mcoder2014/myNotes
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
4
2020-06-22T13:20:26.000Z
2020-06-24T08:43:11.000Z
sources/Leetcodes/src/228_summary_ranges.cpp
mcoder2014/DataStructureAndAlgorithms
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
null
null
null
sources/Leetcodes/src/228_summary_ranges.cpp
mcoder2014/DataStructureAndAlgorithms
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <set> using namespace std; class Solution { public: vector<string> summaryRanges(vector<int>& nums) { set<int> numSet; for(int& item:nums) { numSet.insert(item); } vector<string> returnValue; for(int& item:nums) { int minValue = item; int maxValue = item; if(numSet.find(item) == numSet.end()) { continue; } numSet.erase(numSet.find(item)); // 向前查找 while(numSet.find(minValue-1) != numSet.end()) { // 还有小的元素 minValue--; numSet.erase(numSet.find(minValue)); } // 向后寻找 while(numSet.find(maxValue+1) != numSet.end()) { maxValue++; numSet.erase(numSet.find(maxValue)); } if(minValue == maxValue) { returnValue.push_back(to_string(item)); } else { returnValue.push_back(to_string(minValue) + "->" + to_string(maxValue)); } } return returnValue; } }; int main() { return 0; }
22.660377
88
0.477102
mcoder2014
2435f8d894358672d7342bc977212151bd7beacf
463
cpp
C++
c++11/nullptr.cpp
queertypes/cplusplus-examples
c4f784cbc9e97220c0e25f7ea9f1121f63d194fe
[ "BSD-3-Clause" ]
null
null
null
c++11/nullptr.cpp
queertypes/cplusplus-examples
c4f784cbc9e97220c0e25f7ea9f1121f63d194fe
[ "BSD-3-Clause" ]
null
null
null
c++11/nullptr.cpp
queertypes/cplusplus-examples
c4f784cbc9e97220c0e25f7ea9f1121f63d194fe
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> using namespace std; void f(void *x) { if (x == nullptr) { cout << "error: null argument\n"; return; } cout << "That's a good argument you make there...\n"; } int main() { int* p1 = nullptr; int* p2 = 0; int* x = new int; if (p1 == p2) cout << "nullptr is equivalent to 0\n"; if (p1 == nullptr) cout << "nullptr is equivalent to nullptr\n"; f(nullptr); f(0); f(x); delete x; return 0; }
13.617647
55
0.546436
queertypes
0f84fccbcc900461084fb2ee3a8317b812ee3922
2,970
cpp
C++
modules/brl/native/admob.ios.cpp
blitz-research/monkey
1ad8c237d1bae94ab6f12bd3c2db2073ecf38e58
[ "Zlib" ]
144
2015-01-04T08:43:08.000Z
2022-03-30T19:32:33.000Z
modules/brl/native/admob.ios.cpp
leonard-thieu/monkey
1ad8c237d1bae94ab6f12bd3c2db2073ecf38e58
[ "Zlib" ]
15
2015-02-26T13:15:16.000Z
2017-06-09T12:03:18.000Z
modules/brl/native/admob.ios.cpp
leonard-thieu/monkey
1ad8c237d1bae94ab6f12bd3c2db2073ecf38e58
[ "Zlib" ]
64
2015-01-12T14:44:47.000Z
2021-09-18T04:28:43.000Z
//admob.ios.h #import "GADBannerView.h" class BBAdmob{ static BBAdmob *_admob; GADBannerView *_view; public: BBAdmob(); static BBAdmob *GetAdmob(); void ShowAdView( int style,int layout ); void HideAdView(); int AdViewWidth(); int AdViewHeight(); }; //admob.ios.cpp #define _QUOTE(X) #X #define _STRINGIZE(X) _QUOTE(X) BBAdmob *BBAdmob::_admob; BBAdmob::BBAdmob():_view(0){ } BBAdmob *BBAdmob::GetAdmob(){ if( !_admob ) _admob=new BBAdmob(); return _admob; } void BBAdmob::ShowAdView( int style,int layout ){ if( _view ){ [_view removeFromSuperview]; [_view release]; } GADAdSize sz=kGADAdSizeBanner; switch( style ){ case 2:sz=kGADAdSizeSmartBannerPortrait;break; case 3:sz=kGADAdSizeSmartBannerLandscape;break; } _view=[[GADBannerView alloc] initWithAdSize:sz]; if( !_view ) return; _view.adUnitID=@_STRINGIZE(CFG_ADMOB_PUBLISHER_ID); BBMonkeyAppDelegate *appDelegate=(BBMonkeyAppDelegate*)[[UIApplication sharedApplication] delegate]; _view.rootViewController=appDelegate->viewController; UIView *appView=appDelegate->view; CGRect b1=appView.bounds; CGRect b2=_view.bounds; switch( layout ){ case 1: _view.autoresizingMask=UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin; break; case 2: b2.origin.x=(b1.size.width-b2.size.width)/2; _view.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin; break; case 3: b2.origin.x=(b1.size.width-b2.size.width); _view.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin; break; case 4: b2.origin.y=(b1.size.height-b2.size.height); _view.autoresizingMask=UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin; break; case 5: b2.origin.x=(b1.size.width-b2.size.width)/2; b2.origin.y=(b1.size.height-b2.size.height); _view.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin; break; case 6: b2.origin.x=(b1.size.width-b2.size.width); b2.origin.y=(b1.size.height-b2.size.height); _view.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin; break; default: b2.origin.x=(b1.size.width-b2.size.width)/2; b2.origin.y=(b1.size.height-b2.size.height)/2; _view.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin; } _view.frame=b2; [appView addSubview:_view]; GADRequest *request=[GADRequest request]; [_view loadRequest:request]; } void BBAdmob::HideAdView(){ if( !_view ) return; [_view removeFromSuperview]; [_view release]; _view=0; } int BBAdmob::AdViewWidth(){ return _view ? _view.bounds.size.width : 0; } int BBAdmob::AdViewHeight(){ return _view ? _view.bounds.size.height : 0; }
24.146341
175
0.769024
blitz-research
0f8981cdde5d0a93de38ebc52bfbf3be6f3591ee
2,518
cpp
C++
Codes/cpp/Yee_172/graph.cpp
Yee172/SHY_ACM_Template
e6ae56e0140bac15e35aed00577ad13e5370c92c
[ "MIT" ]
11
2018-06-07T13:51:32.000Z
2019-10-28T16:33:52.000Z
Codes/cpp/Yee_172/graph.cpp
Yee172/SHY_ACM_Template
e6ae56e0140bac15e35aed00577ad13e5370c92c
[ "MIT" ]
null
null
null
Codes/cpp/Yee_172/graph.cpp
Yee172/SHY_ACM_Template
e6ae56e0140bac15e35aed00577ad13e5370c92c
[ "MIT" ]
6
2018-06-07T13:51:49.000Z
2019-04-14T08:04:31.000Z
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll N = 100500; const ll M = 100500; const static ll inf = 0x3f3f3f3f3f3f3f3f; struct edge { ll u; ll v; ll w; }; vector<edge> e[N]; inline void insert_edge(ll u, ll v, ll w) { e[u].push_back(edge{u, v, w}); } inline void insert_double_edge(ll u, ll v, ll w) { insert_edge(u, v, w); insert_edge(v, u, w); } ll vis[N]; ll dis[N]; ll dij(ll st, ll n) { for (ll i = 1; i <= n; i++) dis[i] = inf, vis[i] = 0; priority_queue<pair<ll, ll> > q; q.push(make_pair(dis[st] = 0, st)); while (!q.empty()) { ll u = q.top().second; q.pop(); if (vis[u]) continue; vis[u] = 1; for (ll i = 0; i < e[u].size(); i++) { ll v = e[u][i].v; ll w = e[u][i].w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; q.push(make_pair(- dis[v], v)); } } } return dis[n]; } ll dp[N][N]; void floyd(ll n) { for (ll k = 1; k <= n; k++) for (ll i = 1; i <= n; i++) for (ll j = 1; j <= n; j++) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); } // Judge the negative cycle bool bellman_ford(ll st, ll n) { for (ll i = 1; i <= n; ++i) dis[i] = inf; dis[st] = 0; for (ll t = 1; t <= n; t++) for (ll u = 1; u <= n; u++) for (ll i = 0; i < e[u].size(); i++) { ll v = e[u][i].v; ll w = e[u][i].w; if (dis[v] > dis[u] + w) dis[v] = dis[u] + w; } for (ll u = 1; u <= n; u++) for (ll i = 0; i < e[u].size(); i++) { ll v = e[u][i].v; ll w = e[u][i].w; if (dis[v] > dis[u] + w) return true; } return false; } // Judge the negative cycle bool spfa(ll st, ll n) { queue<ll> q; for (ll i = 1; i <= n; ++i) { dis[i] = inf; vis[i] = 0; } q.push(st); dis[st] = 0; while (!q.empty()) { ll u = q.front(); q.pop(); for (ll i = 0; i < e[u].size(); i++) { ll v = e[u][i].v; ll w = e[u][i].w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; vis[v]++; if (vis[v] > n) return true; q.push(v); } } } if (dis[st] < 0) return true; return false; }
20.983333
62
0.378872
Yee172
0f8a339d5d18798266f399c5f2db98197d68ce19
1,382
cpp
C++
PulsingLed.cpp
BasPaap/Looms
a0f4babdecfc68a9308e5a708f81ecee352a8c86
[ "MIT" ]
null
null
null
PulsingLed.cpp
BasPaap/Looms
a0f4babdecfc68a9308e5a708f81ecee352a8c86
[ "MIT" ]
null
null
null
PulsingLed.cpp
BasPaap/Looms
a0f4babdecfc68a9308e5a708f81ecee352a8c86
[ "MIT" ]
null
null
null
// // // #include "PulsingLed.h" Bas::PulsingLed::PulsingLed(int pin, unsigned long fadeInDuration, unsigned long fadeOutDuration) : pin{ pin }, fadeInDuration{ fadeInDuration }, fadeOutDuration{ fadeOutDuration } { } Bas::PulsingLed::~PulsingLed() { } void Bas::PulsingLed::update() { if (this->phase != Phase::Off) { unsigned long now = millis(); unsigned long timeInPhase = now - this->currentPulsePhaseStartTime; double phaseDuration; if (this->phase == Phase::FadingIn) { phaseDuration = (double)this->fadeInDuration; } else if (this->phase == Phase::FadingOut) { phaseDuration = (double)this->fadeOutDuration; } double relativeTimeInPhase = timeInPhase / phaseDuration; if (relativeTimeInPhase > 1.0) { if (this->phase == Phase::FadingIn) { this->phase = Phase::FadingOut; } else { this->phase = Phase::Off; analogWrite(pin, 0); } } else { if (this->phase == Phase::FadingIn) { analogWrite(pin, 255 * relativeTimeInPhase); } else if (this->phase == Phase::FadingOut) { analogWrite(pin, 255 - (255 * relativeTimeInPhase)); } } } } void Bas::PulsingLed::pulse() { if (this->phase == Phase::Off) // Ignore calls to this function if we are already pulsing. { this->phase = Phase::FadingIn; this->currentPulsePhaseStartTime = millis(); } }
18.675676
182
0.640376
BasPaap
0f8eb9897ebe55ceddf7169b0b63469c40a1f334
132,170
cxx
C++
ParaViewCore/VTKExtensions/Default/vtkPEnSightGoldBinaryReader.cxx
sakjain92/paraview
f3af0cd9f6750e24ad038eac573b870c88d6b7dd
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-09-27T08:04:34.000Z
2019-10-16T22:30:54.000Z
ParaViewCore/VTKExtensions/Default/vtkPEnSightGoldBinaryReader.cxx
sakjain92/paraview
f3af0cd9f6750e24ad038eac573b870c88d6b7dd
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
ParaViewCore/VTKExtensions/Default/vtkPEnSightGoldBinaryReader.cxx
sakjain92/paraview
f3af0cd9f6750e24ad038eac573b870c88d6b7dd
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "vtkPEnSightGoldBinaryReader.h" #include "vtkByteSwap.h" #include "vtkCellData.h" #include "vtkCharArray.h" #include "vtkFloatArray.h" #include "vtkIdList.h" #include "vtkImageData.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" #include "vtkStructuredGrid.h" #include "vtkUnstructuredGrid.h" #include <vtksys/SystemTools.hxx> #include <ctype.h> #include <string> vtkStandardNewMacro(vtkPEnSightGoldBinaryReader); // This is half the precision of an int. #define MAXIMUM_PART_ID 65536 //---------------------------------------------------------------------------- vtkPEnSightGoldBinaryReader::vtkPEnSightGoldBinaryReader() { this->IFile = NULL; this->FileSize = 0; this->Fortran = 0; this->NodeIdsListed = 0; this->ElementIdsListed = 0; this->FloatBufferSize = 1000; this->FloatBuffer = (float**)malloc(3 * sizeof(float*)); this->FloatBuffer[0] = new float[this->FloatBufferSize]; this->FloatBuffer[1] = new float[this->FloatBufferSize]; this->FloatBuffer[2] = new float[this->FloatBufferSize]; this->FloatBufferIndexBegin = -1; this->FloatBufferFilePosition = 0; this->FloatBufferNumberOfVectors = 0; } //---------------------------------------------------------------------------- vtkPEnSightGoldBinaryReader::~vtkPEnSightGoldBinaryReader() { if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } delete[] this->FloatBuffer[2]; delete[] this->FloatBuffer[1]; delete[] this->FloatBuffer[0]; free(this->FloatBuffer); } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::OpenFile(const char* filename) { if (!filename) { vtkErrorMacro(<< "Missing filename."); return 0; } // Close file from any previous image if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } // Open the new file vtkDebugMacro(<< "Opening file " << filename); vtksys::SystemTools::Stat_t fs; if (!vtksys::SystemTools::Stat(filename, &fs)) { // Find out how big the file is. this->FileSize = (long)(fs.st_size); #ifdef _WIN32 this->IFile = new ifstream(filename, ios::in | ios::binary); #else this->IFile = new ifstream(filename, ios::in); #endif } else { vtkErrorMacro("stat failed."); return 0; } if (!this->IFile || this->IFile->fail()) { vtkErrorMacro(<< "Could not open file " << filename); return 0; } // we now need to check for Fortran and byte ordering // we need to look at the first 4 bytes of the file, and the 84-87 bytes // of the file to correctly determine what it is. If we only check the first // 4 bytes we can get incorrect detection if it is a property file named "P" // we check the 84-87 bytes as that is the start of the next line on a fortran file char result[88]; this->IFile->read(result, 88); if (this->IFile->eof() || this->IFile->fail()) { vtkErrorMacro(<< filename << " is missing header information"); return 0; } this->IFile->seekg(0, ios::beg); // reset the file to the start // if the first 4 bytes is the length, then this data is no doubt // a fortran data write!, copy the last 76 into the beginning char le_len[4] = { 0x50, 0x00, 0x00, 0x00 }; char be_len[4] = { 0x00, 0x00, 0x00, 0x50 }; // the fortran test here depends on the byte ordering. But if the user didn't // set any byte ordering then, we have to try both byte orderings. There was a // bug here which was resulting in binary-fortran-big-endian files being read // incorrectly on intel machines (BUG #10593). This dual-check avoids that // bug. bool le_isFortran = true; bool be_isFortran = true; for (int c = 0; c < 4; c++) { le_isFortran = le_isFortran && (result[c] == le_len[c]) && (result[c + 84] == le_len[c]); be_isFortran = be_isFortran && (result[c] == be_len[c]) && (result[c + 84] == be_len[c]); } switch (this->ByteOrder) { case FILE_BIG_ENDIAN: this->Fortran = be_isFortran; break; case FILE_LITTLE_ENDIAN: this->Fortran = le_isFortran; break; case FILE_UNKNOWN_ENDIAN: if (le_isFortran) { this->Fortran = true; this->ByteOrder = FILE_LITTLE_ENDIAN; } else if (be_isFortran) { this->Fortran = true; this->ByteOrder = FILE_BIG_ENDIAN; } else { this->Fortran = false; } break; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::InitializeFile(const char* fileName) { char line[80], subLine[80]; // Initialize // if (!fileName) { vtkErrorMacro("A GeometryFileName must be specified in the case file."); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to geometry file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } line[0] = '\0'; subLine[0] = '\0'; if (this->ReadLine(line) == 0) { vtkErrorMacro("Error with line reading upon file initialization"); return 0; } if (sscanf(line, " %*s %s", subLine) != 1) { vtkErrorMacro("Error with subline extraction upon file initialization"); return 0; } if (strncmp(subLine, "Binary", 6) != 0 && strncmp(subLine, "binary", 6) != 0) { vtkErrorMacro("This is not a binary data set. Try " << "vtkEnSightGoldReader."); return 0; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadGeometryFile( const char* fileName, int timeStep, vtkMultiBlockDataSet* output) { char line[80], subLine[80], nameline[80]; int partId, realId; int lineRead, i; if (!this->InitializeFile(fileName)) { return 0; } /* Disable this. This is too slow on big files and the CASE file * is supposed to be correct anyway... //this will close the file, so we need to reinitialize it int numberOfTimeStepsInFile=this->CountTimeSteps(); if (!this->InitializeFile(fileName)) { return 0; } */ if (this->UseFileSets) { int realTimeStep = timeStep - 1; int j = 0; // Try to find the nearest time step for which we know the offset for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { if (!this->SkipTimeStep()) { return 0; } else { if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } } while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } // Skip the 2 description lines. this->ReadLine(line); this->ReadLine(line); // Read the node id and element id lines. this->ReadLine(line); sscanf(line, " %*s %*s %s", subLine); if (strncmp(subLine, "given", 5) == 0) { this->NodeIdsListed = 1; } else if (strncmp(subLine, "ignore", 6) == 0) { this->NodeIdsListed = 1; } else { this->NodeIdsListed = 0; } this->ReadLine(line); sscanf(line, " %*s %*s %s", subLine); if (strncmp(subLine, "given", 5) == 0) { this->ElementIdsListed = 1; } else if (strncmp(subLine, "ignore", 6) == 0) { this->ElementIdsListed = 1; } else { this->ElementIdsListed = 0; } lineRead = this->ReadLine(line); // "extents" or "part" if (strncmp(line, "extents", 7) == 0) { // Skipping the extents. this->IFile->seekg(6 * sizeof(float), ios::cur); lineRead = this->ReadLine(line); // "part" } while (lineRead > 0 && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing at 1. if (partId < 0 || partId >= MAXIMUM_PART_ID) { vtkErrorMacro("Invalid part id; check that ByteOrder is set correctly."); return 0; } realId = this->InsertNewPartId(partId); // Increment the number of geometry parts such that the measured geometry, // if any, can be properly combined into a vtkMultiBlockDataSet object. // --- fix to bug #7453 this->NumberOfGeometryParts++; this->ReadLine(line); // part description line strncpy(nameline, line, 80); // 80 characters in line are allowed nameline[79] = '\0'; // Ensure NULL character at end of part name char* name = strdup(nameline); // fix to bug #0008237 // The original "return 1" operation upon "strncmp(line, "interface", 9) == 0" // was removed here as 'interface' is NOT a keyword of an EnSight Gold file. this->ReadLine(line); if (strncmp(line, "block", 5) == 0) { if (sscanf(line, " %*s %s", subLine) == 1) { if (strncmp(subLine, "rectilinear", 11) == 0) { // block rectilinear lineRead = this->CreateRectilinearGridOutput(realId, line, name, output); } else if (strncmp(subLine, "uniform", 7) == 0) { // block uniform lineRead = this->CreateImageDataOutput(realId, line, name, output); } else { // block iblanked lineRead = this->CreateStructuredGridOutput(realId, line, name, output); } } else { // block lineRead = this->CreateStructuredGridOutput(realId, line, name, output); } } else { lineRead = this->CreateUnstructuredGridOutput(realId, line, name, output); if (lineRead < 0) { free(name); if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 0; } } free(name); } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } if (lineRead < 0) { return 0; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::CountTimeSteps() { int count = 0; while (1) { int result = this->SkipTimeStep(); if (result) { count++; } else { break; } } return count; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::SkipTimeStep() { char line[80], subLine[80]; int lineRead; line[0] = '\0'; while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { if (!this->ReadLine(line)) { return 0; } } // Skip the 2 description lines. this->ReadLine(line); this->ReadLine(line); // Read the node id and element id lines. this->ReadLine(line); sscanf(line, " %*s %*s %s", subLine); if (strncmp(subLine, "given", 5) == 0 || strncmp(subLine, "ignore", 6) == 0) { this->NodeIdsListed = 1; } else { this->NodeIdsListed = 0; } this->ReadLine(line); sscanf(line, " %*s %*s %s", subLine); if (strncmp(subLine, "given", 5) == 0) { this->ElementIdsListed = 1; } else if (strncmp(subLine, "ignore", 6) == 0) { this->ElementIdsListed = 1; } else { this->ElementIdsListed = 0; } lineRead = this->ReadLine(line); // "extents" or "part" if (strncmp(line, "extents", 7) == 0) { // Skipping the extents. this->IFile->seekg(6 * sizeof(float), ios::cur); lineRead = this->ReadLine(line); // "part" } while (lineRead > 0 && strncmp(line, "part", 4) == 0) { int tmpInt; this->ReadPartId(&tmpInt); if (tmpInt < 0 || tmpInt > MAXIMUM_PART_ID) { vtkErrorMacro("Invalid part id; check that ByteOrder is set correctly."); return 0; } this->ReadLine(line); // part description line this->ReadLine(line); if (strncmp(line, "block", 5) == 0) { if (sscanf(line, " %*s %s", subLine) == 1) { if (strncmp(subLine, "rectilinear", 11) == 0) { // block rectilinear lineRead = this->SkipRectilinearGrid(line); } else if (strncmp(subLine, "uniform,", 7) == 0) { // block uniform lineRead = this->SkipImageData(line); } else { // block iblanked lineRead = this->SkipStructuredGrid(line); } } else { // block lineRead = this->SkipStructuredGrid(line); } } else { lineRead = this->SkipUnstructuredGrid(line); } } if (lineRead < 0) { if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 0; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::SkipStructuredGrid(char line[256]) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; int numPts; if (sscanf(line, " %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); numPts = dimensions[0] * dimensions[1] * dimensions[2]; if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || numPts < 0 || numPts * (int)sizeof(int) > this->FileSize || numPts > this->FileSize) { vtkErrorMacro("Invalid dimensions read; check that ByteOrder is set correctly."); return -1; } // Skip xCoords, yCoords and zCoords. this->IFile->seekg(sizeof(float) * numPts * 3, ios::cur); if (iblanked) { // skip iblank array. this->IFile->seekg(numPts * sizeof(int), ios::cur); } // reading next line to check for EOF lineRead = this->ReadLine(line); return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::SkipUnstructuredGrid(char line[256]) { int lineRead = 1; int i; int numElements; int cellType; while (lineRead && strncmp(line, "part", 4) != 0) { if (strncmp(line, "coordinates", 11) == 0) { vtkDebugMacro("coordinates"); int numPts; this->ReadInt(&numPts); if (numPts < 0 || numPts * (int)sizeof(int) > this->FileSize || numPts > this->FileSize) { vtkErrorMacro("Invalid number of points; check that ByteOrder is set correctly."); return -1; } vtkDebugMacro("num. points: " << numPts); if (this->NodeIdsListed) { // skip node ids. this->IFile->seekg(sizeof(int) * numPts, ios::cur); } // Skip xCoords, yCoords and zCoords. this->IFile->seekg(sizeof(float) * 3 * numPts, ios::cur); } else if (strncmp(line, "point", 5) == 0 || strncmp(line, "g_point", 7) == 0) { vtkDebugMacro("point"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of point cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { // skip element ids. this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * numElements, ios::cur); } else if (strncmp(line, "bar2", 4) == 0 || strncmp(line, "g_bar2", 6) == 0) { vtkDebugMacro("bar2"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of bar2 cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 2 * numElements, ios::cur); } else if (strncmp(line, "bar3", 4) == 0 || strncmp(line, "g_bar3", 6) == 0) { vtkDebugMacro("bar3"); vtkWarningMacro("Only vertex nodes of this element will be read."); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of bar3 cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 2 * numElements, ios::cur); } else if (strncmp(line, "nsided", 6) == 0 || strncmp(line, "g_nsided", 8) == 0) { vtkDebugMacro("nsided"); int* numNodesPerElement; int numNodes = 0; // cellType = vtkPEnSightReader::NSIDED; this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of nsided cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } numNodesPerElement = new int[numElements]; this->ReadIntArray(numNodesPerElement, numElements); for (i = 0; i < numElements; i++) { numNodes += numNodesPerElement[i]; } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * numNodes, ios::cur); delete[] numNodesPerElement; } else if (strncmp(line, "tria3", 5) == 0 || strncmp(line, "tria6", 5) == 0 || strncmp(line, "g_tria3", 7) == 0 || strncmp(line, "g_tria6", 7) == 0) { if (strncmp(line, "tria6", 5) == 0 || strncmp(line, "g_tria6", 7) == 0) { vtkDebugMacro("tria6"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::TRIA6; } else { vtkDebugMacro("tria3"); cellType = vtkPEnSightReader::TRIA3; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of triangle cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TRIA6) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 6 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 3 * numElements, ios::cur); } } else if (strncmp(line, "quad4", 5) == 0 || strncmp(line, "quad8", 5) == 0 || strncmp(line, "g_quad4", 7) == 0 || strncmp(line, "g_quad8", 7) == 0) { if (strncmp(line, "quad8", 5) == 0 || strncmp(line, "g_quad8", 7) == 0) { vtkDebugMacro("quad8"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::QUAD8; } else { vtkDebugMacro("quad4"); cellType = vtkPEnSightReader::QUAD4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of quad cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::QUAD8) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 8 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 4 * numElements, ios::cur); } } else if (strncmp(line, "nfaced", 6) == 0) { vtkDebugMacro("nfaced"); int* numFacesPerElement; int* numNodesPerFace; int numFaces = 0; int numNodes = 0; this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of nfaced cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } numFacesPerElement = new int[numElements]; this->ReadIntArray(numFacesPerElement, numElements); for (i = 0; i < numElements; i++) { numFaces += numFacesPerElement[i]; } delete[] numFacesPerElement; numNodesPerFace = new int[numFaces]; this->ReadIntArray(numNodesPerFace, numFaces); for (i = 0; i < numFaces; i++) { numNodes += numNodesPerFace[i]; } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * numNodes, ios::cur); delete[] numNodesPerFace; } else if (strncmp(line, "tetra4", 6) == 0 || strncmp(line, "tetra10", 7) == 0 || strncmp(line, "g_tetra4", 8) == 0 || strncmp(line, "g_tetra10", 9) == 0) { if (strncmp(line, "tetra10", 7) == 0 || strncmp(line, "g_tetra10", 9) == 0) { vtkDebugMacro("tetra10"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::TETRA10; } else { vtkDebugMacro("tetra4"); cellType = vtkPEnSightReader::TETRA4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro( "Invalid number of tetrahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TETRA10) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 10 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 4 * numElements, ios::cur); } } else if (strncmp(line, "pyramid5", 8) == 0 || strncmp(line, "pyramid13", 9) == 0 || strncmp(line, "g_pyramid5", 10) == 0 || strncmp(line, "g_pyramid13", 11) == 0) { if (strncmp(line, "pyramid13", 9) == 0 || strncmp(line, "g_pyramid13", 11) == 0) { vtkDebugMacro("pyramid13"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::PYRAMID13; } else { vtkDebugMacro("pyramid5"); cellType = vtkPEnSightReader::PYRAMID5; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pyramid cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PYRAMID13) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 13 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 5 * numElements, ios::cur); } } else if (strncmp(line, "hexa8", 5) == 0 || strncmp(line, "hexa20", 6) == 0 || strncmp(line, "g_hexa8", 7) == 0 || strncmp(line, "g_hexa20", 8) == 0) { if (strncmp(line, "hexa20", 6) == 0 || strncmp(line, "g_hexa20", 8) == 0) { vtkDebugMacro("hexa20"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::HEXA20; } else { vtkDebugMacro("hexa8"); cellType = vtkPEnSightReader::HEXA8; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of hexahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::HEXA20) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 20 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 8 * numElements, ios::cur); } } else if (strncmp(line, "penta6", 6) == 0 || strncmp(line, "penta15", 7) == 0 || strncmp(line, "g_penta6", 8) == 0 || strncmp(line, "g_penta15", 9) == 0) { if (strncmp(line, "penta15", 7) == 0 || strncmp(line, "g_penta15", 9) == 0) { vtkDebugMacro("penta15"); vtkWarningMacro("Only vertex nodes of this element will be read."); cellType = vtkPEnSightReader::PENTA15; } else { vtkDebugMacro("penta6"); cellType = vtkPEnSightReader::PENTA6; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pentagonal cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PENTA15) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 15 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 6 * numElements, ios::cur); } } else if (strncmp(line, "END TIME STEP", 13) == 0) { return 1; } else { vtkErrorMacro("undefined geometry file line"); return -1; } lineRead = this->ReadLine(line); } return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::SkipRectilinearGrid(char line[256]) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; int numPts; if (sscanf(line, " %*s %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || (dimensions[0] + dimensions[1] + dimensions[2]) < 0 || (dimensions[0] + dimensions[1] + dimensions[2]) * (int)sizeof(int) > this->FileSize || (dimensions[0] + dimensions[1] + dimensions[2]) > this->FileSize) { vtkErrorMacro("Invalid dimensions read; check that BytetOrder is set correctly."); return -1; } numPts = dimensions[0] * dimensions[1] * dimensions[2]; // Skip xCoords this->IFile->seekg(sizeof(float) * dimensions[0], ios::cur); // Skip yCoords this->IFile->seekg(sizeof(float) * dimensions[1], ios::cur); // Skip zCoords this->IFile->seekg(sizeof(float) * dimensions[2], ios::cur); if (iblanked) { vtkWarningMacro("VTK does not handle blanking for rectilinear grids."); this->IFile->seekg(sizeof(int) * numPts, ios::cur); } // reading next line to check for EOF lineRead = this->ReadLine(line); return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::SkipImageData(char line[256]) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; float origin[3], delta[3]; int numPts; if (sscanf(line, " %*s %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); this->ReadFloatArray(origin, 3); this->ReadFloatArray(delta, 3); if (iblanked) { vtkWarningMacro("VTK does not handle blanking for image data."); numPts = dimensions[0] * dimensions[1] * dimensions[2]; if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || numPts < 0 || numPts * (int)sizeof(int) > this->FileSize || numPts > this->FileSize) { return -1; } this->IFile->seekg(sizeof(int) * numPts, ios::cur); } // reading next line to check for EOF lineRead = this->ReadLine(line); return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadMeasuredGeometryFile( const char* fileName, int timeStep, vtkMultiBlockDataSet* output) { char line[80], subLine[80]; vtkIdType i; int* pointIds; float *xCoords, *yCoords, *zCoords; vtkPoints* points = vtkPoints::New(); vtkPolyData* pd = vtkPolyData::New(); this->NumberOfNewOutputs++; // Initialize // if (!fileName) { vtkErrorMacro("A MeasuredFileName must be specified in the case file."); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to measured geometry file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } this->ReadLine(line); sscanf(line, " %*s %s", subLine); if (strncmp(subLine, "Binary", 6) != 0) { vtkErrorMacro("This is not a binary data set. Try " << "vtkEnSightGoldReader."); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; int k, j = 0; // Try to find the nearest time step for which we know the offset for (k = realTimeStep; k >= 0; k--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(k) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][k], ios::beg); j = k; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } // Skip the description line. this->ReadLine(line); this->ReadLine(line); // "particle coordinates" this->ReadInt(&this->NumberOfMeasuredPoints); // Skip pointIds // this->IFile->ignore(sizeof(int)*this->NumberOfMeasuredPoints); // Skip xCoords // this->IFile->ignore(sizeof(float)*this->NumberOfMeasuredPoints); // Skip yCoords // this->IFile->ignore(sizeof(float)*this->NumberOfMeasuredPoints); // Skip zCoords // this->IFile->ignore(sizeof(float)*this->NumberOfMeasuredPoints); this->IFile->seekg( (sizeof(float) * 3 + sizeof(int)) * this->NumberOfMeasuredPoints, ios::cur); this->ReadLine(line); // END TIME STEP if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } // Skip the description line. this->ReadLine(line); this->ReadLine(line); // "particle coordinates" this->ReadInt(&this->NumberOfMeasuredPoints); this->UnstructuredPartIds->InsertNextId(this->NumberOfGeometryParts); int partId = this->UnstructuredPartIds->IsId(this->NumberOfGeometryParts); this->GetPointIds(partId)->Reset(); this->GetCellIds(partId, 0)->Reset(); // Measured Points are like a n * 1 * 1 IJK Structure... this->GetPointIds(partId)->SetMode(IMPLICIT_STRUCTURED_MODE); this->GetCellIds(partId, 0)->SetMode(IMPLICIT_STRUCTURED_MODE); int dimensions[3]; dimensions[0] = this->NumberOfMeasuredPoints; dimensions[1] = 1; dimensions[2] = 1; int newDimensions[3]; int splitDimension; int splitDimensionBeginIndex; this->PrepareStructuredDimensionsForDistribution( partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, 0, NULL, NULL); pointIds = new int[this->NumberOfMeasuredPoints]; xCoords = new float[this->NumberOfMeasuredPoints]; yCoords = new float[this->NumberOfMeasuredPoints]; zCoords = new float[this->NumberOfMeasuredPoints]; points->Allocate(this->GetPointIds(partId)->GetLocalNumberOfIds()); pd->Allocate(this->GetPointIds(partId)->GetLocalNumberOfIds()); // Extract the array of point indices. Note EnSight Manual v8.2 (pp. 559, // http://www-vis.lbl.gov/NERSC/Software/ensight/docs82/UserManual.pdf) // is wrong in describing the format of binary measured geometry files. // As opposed to this description, the actual format employs a 'hybrid' // storage scheme. Specifically, point indices are stored in an array, // whereas 3D coordinates follow the array in a tuple-by-tuple manner. // The following code segment (20+ lines) serves as a fix to bug #9245. this->ReadIntArray(pointIds, this->NumberOfMeasuredPoints); // Read point coordinates tuple by tuple while each tuple contains three // components: (x-cord, y-cord, z-cord) int floatSize = sizeof(float); for (i = 0; i < this->NumberOfMeasuredPoints; i++) { this->IFile->read((char*)(xCoords + i), floatSize); this->IFile->read((char*)(yCoords + i), floatSize); this->IFile->read((char*)(zCoords + i), floatSize); } if (this->ByteOrder == FILE_LITTLE_ENDIAN) { vtkByteSwap::Swap4LERange(xCoords, this->NumberOfMeasuredPoints); vtkByteSwap::Swap4LERange(yCoords, this->NumberOfMeasuredPoints); vtkByteSwap::Swap4LERange(zCoords, this->NumberOfMeasuredPoints); } else { vtkByteSwap::Swap4BERange(xCoords, this->NumberOfMeasuredPoints); vtkByteSwap::Swap4BERange(yCoords, this->NumberOfMeasuredPoints); vtkByteSwap::Swap4BERange(zCoords, this->NumberOfMeasuredPoints); } for (i = 0; i < this->NumberOfMeasuredPoints; i++) { int realId = this->GetPointIds(partId)->GetId(i); if (realId != -1) { vtkIdType tempId = realId; points->InsertNextPoint(xCoords[i], yCoords[i], zCoords[i]); pd->InsertNextCell(VTK_VERTEX, 1, &tempId); } } pd->SetPoints(points); this->AddToBlock(output, partId, pd); points->Delete(); pd->Delete(); delete[] pointIds; delete[] xCoords; delete[] yCoords; delete[] zCoords; if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadScalarsPerNode(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput, int measured, int numberOfComponents, int component) { char line[80]; int partId, realId, numPts, i, lineRead; vtkFloatArray* scalars; float* scalarsRead; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL ScalarPerNode variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to scalar per node file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; // Try to find the nearest time step for which we know the offset int j = 0; for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line if (measured) { partId = this->UnstructuredPartIds->IsId(this->NumberOfGeometryParts); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, partId)); numPts = this->GetPointIds(partId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // Skip sclalars this->IFile->seekg(sizeof(float) * numPts, ios::cur); } } while (this->ReadLine(line) && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, realId)); numPts = this->GetPointIds(realId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // "coordinates" or "block" // Skip sclalars this->IFile->seekg(sizeof(float) * numPts, ios::cur); } } if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line if (measured) { partId = this->UnstructuredPartIds->IsId(this->NumberOfGeometryParts); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, partId)); numPts = this->GetPointIds(partId)->GetNumberOfIds(); if (numPts) { // 'this->ReadLine(line)' was removed here, otherwise there would be a // problem with timestep retrieval of the measured scalars. // This bug was noticed while fixing bug #7453. scalars = vtkFloatArray::New(); scalars->SetNumberOfComponents(numberOfComponents); scalars->SetNumberOfTuples(this->GetPointIds(partId)->GetLocalNumberOfIds()); scalarsRead = new float[numPts]; this->ReadFloatArray(scalarsRead, numPts); // Why are we setting only one component here? // Only one component is set because scalars are single-component arrays. // For complex scalars, there is a file for the real part and another // file for the imaginary part, but we are storing them as a 2-component // array. for (i = 0; i < numPts; i++) { this->InsertVariableComponent( scalars, i, component, &(scalarsRead[i]), partId, 0, SCALAR_PER_NODE); } scalars->SetName(description); output->GetPointData()->AddArray(scalars); if (!output->GetPointData()->GetScalars()) { output->GetPointData()->SetScalars(scalars); } scalars->Delete(); delete[] scalarsRead; } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } lineRead = this->ReadLine(line); while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numPts = this->GetPointIds(realId)->GetNumberOfIds(); // If the part has no points, then only the part number is listed in // the variable file. if (numPts) { this->ReadLine(line); // "coordinates" or "block" if (component == 0) { scalars = vtkFloatArray::New(); scalars->SetNumberOfComponents(numberOfComponents); scalars->SetNumberOfTuples(this->GetPointIds(realId)->GetLocalNumberOfIds()); } else { scalars = (vtkFloatArray*)(output->GetPointData()->GetArray(description)); } scalarsRead = new float[numPts]; this->ReadFloatArray(scalarsRead, numPts); for (i = 0; i < numPts; i++) { this->InsertVariableComponent( scalars, i, component, &(scalarsRead[i]), realId, 0, SCALAR_PER_NODE); } if (component == 0) { scalars->SetName(description); output->GetPointData()->AddArray(scalars); if (!output->GetPointData()->GetScalars()) { output->GetPointData()->SetScalars(scalars); } scalars->Delete(); } else { output->GetPointData()->AddArray(scalars); } delete[] scalarsRead; } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; continue; } lineRead = this->ReadLine(line); } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadVectorsPerNode(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput, int measured) { char line[80]; int partId, realId, numPts, i, lineRead; vtkFloatArray* vectors; float tuple[3]; float *comp1, *comp2, *comp3; float* vectorsRead; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL VectorPerNode variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to vector per node file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; // Try to find the nearest time step for which we know the offset int j = 0; for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line if (measured) { partId = this->UnstructuredPartIds->IsId(this->NumberOfGeometryParts); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, partId)); numPts = this->GetPointIds(partId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // Skip vectors. this->IFile->seekg(sizeof(float) * 3 * numPts, ios::cur); } } while (this->ReadLine(line) && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, realId)); numPts = this->GetPointIds(realId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // "coordinates" or "block" // Skip comp1, comp2 and comp3 this->IFile->seekg(sizeof(float) * 3 * numPts, ios::cur); } } if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line if (measured) { partId = this->UnstructuredPartIds->IsId(this->NumberOfGeometryParts); output = static_cast<vtkDataSet*>(this->GetDataSetFromBlock(compositeOutput, partId)); numPts = this->GetPointIds(partId)->GetNumberOfIds(); if (numPts) { // NOTE: NO ReadLine() here since there is only one description // line (already read above), immediately followed by the actual data. vectors = vtkFloatArray::New(); vectors->SetNumberOfComponents(3); vectors->SetNumberOfTuples(this->GetPointIds(partId)->GetNumberOfIds()); vectorsRead = vectors->GetPointer(0); this->ReadFloatArray(vectorsRead, numPts * 3); vtkFloatArray* localVectors = vtkFloatArray::New(); localVectors->SetNumberOfComponents(3); localVectors->SetNumberOfTuples(this->GetPointIds(partId)->GetLocalNumberOfIds()); float* vec = new float[3]; for (i = 0; i < numPts; i++) { vectors->GetTypedTuple(i, vec); this->InsertVariableComponent(localVectors, i, 0, vec, partId, 0, VECTOR_PER_NODE); } delete[] vec; localVectors->SetName(description); output->GetPointData()->AddArray(localVectors); if (!output->GetPointData()->GetVectors()) { output->GetPointData()->SetVectors(localVectors); } vectors->Delete(); } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } lineRead = this->ReadLine(line); while (lineRead && strncmp(line, "part", 4) == 0) { vectors = vtkFloatArray::New(); this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numPts = this->GetPointIds(realId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // "coordinates" or "block" vectors->SetNumberOfComponents(3); vectors->SetNumberOfTuples(this->GetPointIds(realId)->GetLocalNumberOfIds()); comp1 = new float[numPts]; comp2 = new float[numPts]; comp3 = new float[numPts]; this->ReadFloatArray(comp1, numPts); this->ReadFloatArray(comp2, numPts); this->ReadFloatArray(comp3, numPts); for (i = 0; i < numPts; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; this->InsertVariableComponent(vectors, i, -1, tuple, realId, 0, VECTOR_PER_NODE); } vectors->SetName(description); output->GetPointData()->AddArray(vectors); if (!output->GetPointData()->GetVectors()) { output->GetPointData()->SetVectors(vectors); } vectors->Delete(); delete[] comp1; delete[] comp2; delete[] comp3; } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; continue; } lineRead = this->ReadLine(line); } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadTensorsPerNode(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput) { char line[80]; int partId, realId, numPts, i, lineRead; vtkFloatArray* tensors; float *comp1, *comp2, *comp3, *comp4, *comp5, *comp6; float tuple[6]; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL TensorPerNode variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to tensor per node file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; int j = 0; // Try to find the nearest time step for which we know the offset for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line while (this->ReadLine(line) && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numPts = this->GetPointIds(realId)->GetNumberOfIds(); if (numPts) { this->ReadLine(line); // "coordinates" or "block" // Skip over comp1, comp2, ... comp6 this->IFile->seekg(sizeof(float) * 6 * numPts, ios::cur); } } if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numPts = this->GetPointIds(realId)->GetNumberOfIds(); if (numPts) { tensors = vtkFloatArray::New(); this->ReadLine(line); // "coordinates" or "block" tensors->SetNumberOfComponents(6); tensors->SetNumberOfTuples(this->GetPointIds(realId)->GetLocalNumberOfIds()); comp1 = new float[numPts]; comp2 = new float[numPts]; comp3 = new float[numPts]; comp4 = new float[numPts]; comp5 = new float[numPts]; comp6 = new float[numPts]; this->ReadFloatArray(comp1, numPts); this->ReadFloatArray(comp2, numPts); this->ReadFloatArray(comp3, numPts); this->ReadFloatArray(comp4, numPts); this->ReadFloatArray(comp6, numPts); this->ReadFloatArray(comp5, numPts); for (i = 0; i < numPts; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; tuple[3] = comp4[i]; tuple[4] = comp5[i]; tuple[5] = comp6[i]; this->InsertVariableComponent(tensors, i, -1, tuple, realId, 0, TENSOR_SYMM_PER_NODE); } tensors->SetName(description); output->GetPointData()->AddArray(tensors); tensors->Delete(); delete[] comp1; delete[] comp2; delete[] comp3; delete[] comp4; delete[] comp5; delete[] comp6; } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; continue; } lineRead = this->ReadLine(line); } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadScalarsPerElement(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput, int numberOfComponents, int component) { char line[80]; int partId, realId, numCells, numCellsPerElement, i, idx; vtkFloatArray* scalars; float* scalarsRead; int lineRead, elementType; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL ScalarPerElement variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to scalar per element file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; // Try to find the nearest time step for which we know the offset int j = 0; for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { this->ReadLine(line); // element type or "block" // need to find out from CellIds how many cells we have of this // element type (and what their ids are) -- IF THIS IS NOT A BLOCK // SECTION if (strncmp(line, "block", 5) == 0) { // Skip over float scalars. this->IFile->seekg(sizeof(float) * numCells, ios::cur); lineRead = this->ReadLine(line); } else { while ( lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); this->IFile->seekg(sizeof(float) * numCellsPerElement, ios::cur); lineRead = this->ReadLine(line); } } // end else } // end if (numCells) else { lineRead = this->ReadLine(line); } } // end while if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } // end for this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { this->ReadLine(line); // element type or "block" if (component == 0) { scalars = vtkFloatArray::New(); scalars->SetNumberOfComponents(numberOfComponents); scalars->SetNumberOfTuples(this->GetLocalTotalNumberOfCellIds(realId)); } else { scalars = (vtkFloatArray*)(output->GetCellData()->GetArray(description)); } // need to find out from CellIds how many cells we have of this element // type (and what their ids are) -- IF THIS IS NOT A BLOCK SECTION if (strncmp(line, "block", 5) == 0) { scalarsRead = new float[numCells]; this->ReadFloatArray(scalarsRead, numCells); for (i = 0; i < numCells; i++) { this->InsertVariableComponent( scalars, i, component, &(scalarsRead[i]), realId, 0, SCALAR_PER_ELEMENT); } if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] scalarsRead; } else { while (lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } if (component == 0) { scalars->Delete(); } return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); scalarsRead = new float[numCellsPerElement]; this->ReadFloatArray(scalarsRead, numCellsPerElement); for (i = 0; i < numCellsPerElement; i++) { this->InsertVariableComponent( scalars, i, component, &(scalarsRead[i]), idx, elementType, SCALAR_PER_ELEMENT); } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] scalarsRead; } // end while } // end else if (component == 0) { scalars->SetName(description); output->GetCellData()->AddArray(scalars); if (!output->GetCellData()->GetScalars()) { output->GetCellData()->SetScalars(scalars); } scalars->Delete(); } else { output->GetCellData()->AddArray(scalars); } } else { this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } } } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadVectorsPerElement(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput) { char line[80]; int partId, realId, numCells, numCellsPerElement, i, idx; vtkFloatArray* vectors; float *comp1, *comp2, *comp3; int lineRead, elementType; float tuple[3]; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL VectorPerElement variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to vector per element file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; // Try to find the nearest time step for which we know the offset int j = 0; for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { this->ReadLine(line); // element type or "block" // need to find out from CellIds how many cells we have of this // element type (and what their ids are) -- IF THIS IS NOT A BLOCK // SECTION if (strncmp(line, "block", 5) == 0) { // Skip over comp1, comp2 and comp3 this->IFile->seekg(sizeof(float) * 3 * numCells, ios::cur); lineRead = this->ReadLine(line); } else { while ( lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); delete this->IS; this->IS = NULL; return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); // Skip over comp1, comp2 and comp3 this->IFile->seekg(sizeof(float) * 3 * numCellsPerElement, ios::cur); lineRead = this->ReadLine(line); } // end while } // end else } else { lineRead = this->ReadLine(line); } } if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { vectors = vtkFloatArray::New(); this->ReadLine(line); // element type or "block" vectors->SetNumberOfComponents(3); vectors->SetNumberOfTuples(this->GetLocalTotalNumberOfCellIds(realId)); // need to find out from CellIds how many cells we have of this element // type (and what their ids are) -- IF THIS IS NOT A BLOCK SECTION if (strncmp(line, "block", 5) == 0) { comp1 = new float[numCells]; comp2 = new float[numCells]; comp3 = new float[numCells]; this->ReadFloatArray(comp1, numCells); this->ReadFloatArray(comp2, numCells); this->ReadFloatArray(comp3, numCells); for (i = 0; i < numCells; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; this->InsertVariableComponent(vectors, i, -1, tuple, realId, 0, VECTOR_PER_ELEMENT); } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] comp1; delete[] comp2; delete[] comp3; } else { while (lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); delete this->IS; this->IS = NULL; vectors->Delete(); return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); comp1 = new float[numCellsPerElement]; comp2 = new float[numCellsPerElement]; comp3 = new float[numCellsPerElement]; this->ReadFloatArray(comp1, numCellsPerElement); this->ReadFloatArray(comp2, numCellsPerElement); this->ReadFloatArray(comp3, numCellsPerElement); for (i = 0; i < numCellsPerElement; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; this->InsertVariableComponent( vectors, i, 0, tuple, idx, elementType, VECTOR_PER_ELEMENT); } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] comp1; delete[] comp2; delete[] comp3; } // end while } // end else vectors->SetName(description); output->GetCellData()->AddArray(vectors); if (!output->GetCellData()->GetVectors()) { output->GetCellData()->SetVectors(vectors); } vectors->Delete(); } else { this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } } } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadTensorsPerElement(const char* fileName, const char* description, int timeStep, vtkMultiBlockDataSet* compositeOutput) { char line[80]; int partId, realId, numCells, numCellsPerElement, i, idx; vtkFloatArray* tensors; int lineRead, elementType; float *comp1, *comp2, *comp3, *comp4, *comp5, *comp6; float tuple[6]; vtkDataSet* output; // Initialize // if (!fileName) { vtkErrorMacro("NULL TensorPerElement variable file name"); return 0; } std::string sfilename; if (this->FilePath) { sfilename = this->FilePath; if (sfilename.at(sfilename.length() - 1) != '/') { sfilename += "/"; } sfilename += fileName; vtkDebugMacro("full path to tensor per element file: " << sfilename.c_str()); } else { sfilename = fileName; } if (this->OpenFile(sfilename.c_str()) == 0) { vtkErrorMacro("Unable to open file: " << sfilename.c_str()); return 0; } if (this->UseFileSets) { int realTimeStep = timeStep - 1; // Try to find the nearest time step for which we know the offset int j = 0; for (i = realTimeStep; i >= 0; i--) { if (this->FileOffsets.find(fileName) != this->FileOffsets.end() && this->FileOffsets[fileName].find(i) != this->FileOffsets[fileName].end()) { this->IFile->seekg(this->FileOffsets[fileName][i], ios::beg); j = i; break; } } // Hopefully we are not very far from the timestep we want to use // Find it (and cache any timestep we find on the way...) while (j++ < realTimeStep) { this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { this->ReadLine(line); // element type or "block" // need to find out from CellIds how many cells we have of this // element type (and what their ids are) -- IF THIS IS NOT A BLOCK // SECTION if (strncmp(line, "block", 5) == 0) { // Skip comp1 - comp6 this->IFile->seekg(sizeof(float) * 6 * numCells, ios::cur); lineRead = this->ReadLine(line); } else { while ( lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); delete this->IS; this->IS = NULL; return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); // Skip over comp1->comp6 this->IFile->seekg(sizeof(float) * 6 * numCellsPerElement, ios::cur); lineRead = this->ReadLine(line); } // end while } // end else } // end if (numCells) else { lineRead = this->ReadLine(line); } } if (this->FileOffsets.find(fileName) == this->FileOffsets.end()) { std::map<int, long> tsMap; this->FileOffsets[fileName] = tsMap; } this->FileOffsets[fileName][j] = this->IFile->tellg(); } this->ReadLine(line); while (strncmp(line, "BEGIN TIME STEP", 15) != 0) { this->ReadLine(line); } } this->ReadLine(line); // skip the description line lineRead = this->ReadLine(line); // "part" while (lineRead && strncmp(line, "part", 4) == 0) { this->ReadPartId(&partId); partId--; // EnSight starts #ing with 1. realId = this->InsertNewPartId(partId); output = this->GetDataSetFromBlock(compositeOutput, realId); numCells = this->GetTotalNumberOfCellIds(realId); if (numCells) { tensors = vtkFloatArray::New(); this->ReadLine(line); // element type or "block" tensors->SetNumberOfComponents(6); tensors->SetNumberOfTuples(this->GetLocalTotalNumberOfCellIds(realId)); // need to find out from CellIds how many cells we have of this element // type (and what their ids are) -- IF THIS IS NOT A BLOCK SECTION if (strncmp(line, "block", 5) == 0) { comp1 = new float[numCells]; comp2 = new float[numCells]; comp3 = new float[numCells]; comp4 = new float[numCells]; comp5 = new float[numCells]; comp6 = new float[numCells]; this->ReadFloatArray(comp1, numCells); this->ReadFloatArray(comp2, numCells); this->ReadFloatArray(comp3, numCells); this->ReadFloatArray(comp4, numCells); this->ReadFloatArray(comp6, numCells); this->ReadFloatArray(comp5, numCells); for (i = 0; i < numCells; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; tuple[3] = comp4[i]; tuple[4] = comp5[i]; tuple[5] = comp6[i]; this->InsertVariableComponent(tensors, i, -1, tuple, realId, 0, TENSOR_SYMM_PER_ELEMENT); } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] comp1; delete[] comp2; delete[] comp3; delete[] comp4; delete[] comp5; delete[] comp6; } else { while (lineRead && strncmp(line, "part", 4) != 0 && strncmp(line, "END TIME STEP", 13) != 0) { elementType = this->GetElementType(line); if (elementType == -1) { vtkErrorMacro("Unknown element type \"" << line << "\""); delete this->IS; this->IS = NULL; tensors->Delete(); return 0; } idx = this->UnstructuredPartIds->IsId(realId); numCellsPerElement = this->GetCellIds(idx, elementType)->GetNumberOfIds(); comp1 = new float[numCellsPerElement]; comp2 = new float[numCellsPerElement]; comp3 = new float[numCellsPerElement]; comp4 = new float[numCellsPerElement]; comp5 = new float[numCellsPerElement]; comp6 = new float[numCellsPerElement]; this->ReadFloatArray(comp1, numCellsPerElement); this->ReadFloatArray(comp2, numCellsPerElement); this->ReadFloatArray(comp3, numCellsPerElement); this->ReadFloatArray(comp4, numCellsPerElement); this->ReadFloatArray(comp6, numCellsPerElement); this->ReadFloatArray(comp5, numCellsPerElement); for (i = 0; i < numCellsPerElement; i++) { tuple[0] = comp1[i]; tuple[1] = comp2[i]; tuple[2] = comp3[i]; tuple[3] = comp4[i]; tuple[4] = comp5[i]; tuple[5] = comp6[i]; this->InsertVariableComponent( tensors, i, 0, tuple, idx, elementType, TENSOR_SYMM_PER_ELEMENT); } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } delete[] comp1; delete[] comp2; delete[] comp3; delete[] comp4; delete[] comp5; delete[] comp6; } // end while } // end else tensors->SetName(description); output->GetCellData()->AddArray(tensors); tensors->Delete(); } else { this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } } } if (this->IFile) { this->IFile->close(); delete this->IFile; this->IFile = NULL; } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::CreateUnstructuredGridOutput( int partId, char line[80], const char* name, vtkMultiBlockDataSet* compositeOutput) { int lineRead = 1; int i, j; vtkIdType* nodeIds; int* nodeIdList; int numElements; int idx, cellType; this->NumberOfNewOutputs++; if (this->GetDataSetFromBlock(compositeOutput, partId) == NULL || !this->GetDataSetFromBlock(compositeOutput, partId)->IsA("vtkUnstructuredGrid")) { vtkDebugMacro("creating new unstructured output"); vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New(); this->AddToBlock(compositeOutput, partId, ugrid); ugrid->Delete(); this->UnstructuredPartIds->InsertNextId(partId); } vtkUnstructuredGrid* output = vtkUnstructuredGrid::SafeDownCast(this->GetDataSetFromBlock(compositeOutput, partId)); this->SetBlockName(compositeOutput, partId, name); // Clear all cell ids from the last execution, if any. idx = this->UnstructuredPartIds->IsId(partId); for (i = 0; i < vtkPEnSightReader::NUMBER_OF_ELEMENT_TYPES; i++) { this->GetCellIds(idx, i)->Reset(); this->GetPointIds(idx)->Reset(); } output->Allocate(1000); long coordinatesOffset = -1; this->CoordinatesAtEnd = false; this->InjectGlobalNodeIds = false; this->InjectGlobalElementIds = false; this->LastPointId = 0; while (lineRead && strncmp(line, "part", 4) != 0) { if (strncmp(line, "coordinates", 11) == 0) { // keep coordinates offset in mind coordinatesOffset = -1; this->GetPointIds(idx)->Reset(); this->LastPointId = 0; vtkDebugMacro("coordinates"); vtkPoints* points = vtkPoints::New(); coordinatesOffset = this->IFile->tellg(); int pointsRead = this->ReadOrSkipCoordinates(points, coordinatesOffset, idx, true); points->Delete(); if (pointsRead == -1) { return -1; } } else if (strncmp(line, "point", 5) == 0) { vtkDebugMacro("point"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of point cells; check that ByteOrder is set correctly."); return -1; } nodeIds = new vtkIdType[1]; if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } nodeIdList = new int[numElements]; this->ReadIntArray(nodeIdList, numElements); for (i = 0; i < numElements; i++) { nodeIds[0] = nodeIdList[i] - 1; this->InsertNextCellAndId( output, VTK_VERTEX, 1, nodeIds, idx, vtkPEnSightReader::POINT, i, numElements); } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_point", 7) == 0) { // skipping ghost cells vtkDebugMacro("g_point"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of g_point cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { // skip element ids. this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * numElements, ios::cur); } else if (strncmp(line, "bar2", 4) == 0) { vtkDebugMacro("bar2"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of bar2 cells; check that ByteOrder is set correctly."); return -1; } nodeIds = new vtkIdType[2]; if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } nodeIdList = new int[numElements * 2]; this->ReadIntArray(nodeIdList, numElements * 2); for (i = 0; i < numElements; i++) { for (j = 0; j < 2; j++) { nodeIds[j] = nodeIdList[2 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_LINE, 2, nodeIds, idx, vtkPEnSightReader::BAR2, i, numElements); } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_bar2", 6) == 0) { // skipping ghost cells vtkDebugMacro("g_bar2"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of g_bar2 cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 2 * numElements, ios::cur); } else if (strncmp(line, "bar3", 4) == 0) { vtkDebugMacro("bar3"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of bar3 cells; check that ByteOrder is set correctly."); return -1; } nodeIds = new vtkIdType[3]; if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } nodeIdList = new int[numElements * 3]; this->ReadIntArray(nodeIdList, numElements * 3); for (i = 0; i < numElements; i++) { nodeIds[0] = nodeIdList[3 * i] - 1; nodeIds[1] = nodeIdList[3 * i + 2] - 1; nodeIds[2] = nodeIdList[3 * i + 1] - 1; this->InsertNextCellAndId( output, VTK_QUADRATIC_EDGE, 3, nodeIds, idx, vtkPEnSightReader::BAR3, i, numElements); } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_bar3", 6) == 0) { // skipping ghost cells vtkDebugMacro("g_bar3"); this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of g_bar3 cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 2 * numElements, ios::cur); } else if (strncmp(line, "nsided", 6) == 0) { vtkDebugMacro("nsided"); int* numNodesPerElement; int numNodes = 0; int nodeCount = 0; cellType = vtkPEnSightReader::NSIDED; this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of nsided cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } numNodesPerElement = new int[numElements]; this->ReadIntArray(numNodesPerElement, numElements); for (i = 0; i < numElements; i++) { numNodes += numNodesPerElement[i]; } nodeIdList = new int[numNodes]; this->ReadIntArray(nodeIdList, numNodes); for (i = 0; i < numElements; i++) { nodeIds = new vtkIdType[numNodesPerElement[i]]; for (j = 0; j < numNodesPerElement[i]; j++) { nodeIds[j] = nodeIdList[nodeCount] - 1; nodeCount++; } this->InsertNextCellAndId( output, VTK_POLYGON, numNodesPerElement[i], nodeIds, idx, cellType, i, numElements); delete[] nodeIds; } delete[] nodeIdList; delete[] numNodesPerElement; } else if (strncmp(line, "g_nsided", 8) == 0) { // skipping ghost cells vtkDebugMacro("g_nsided"); int* numNodesPerElement; int numNodes = 0; // cellType = vtkPEnSightReader::NSIDED; this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of g_nsided cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } numNodesPerElement = new int[numElements]; this->ReadIntArray(numNodesPerElement, numElements); for (i = 0; i < numElements; i++) { numNodes += numNodesPerElement[i]; } // Skip nodeIdList. this->IFile->seekg(sizeof(int) * numNodes, ios::cur); delete[] numNodesPerElement; } else if (strncmp(line, "tria3", 5) == 0 || strncmp(line, "tria6", 5) == 0) { if (strncmp(line, "tria6", 5) == 0) { vtkDebugMacro("tria6"); cellType = vtkPEnSightReader::TRIA6; } else { vtkDebugMacro("tria3"); cellType = vtkPEnSightReader::TRIA3; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of triangle cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TRIA6) { nodeIds = new vtkIdType[6]; nodeIdList = new int[numElements * 6]; this->ReadIntArray(nodeIdList, numElements * 6); } else { nodeIds = new vtkIdType[3]; nodeIdList = new int[numElements * 3]; this->ReadIntArray(nodeIdList, numElements * 3); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::TRIA6) { for (j = 0; j < 6; j++) { nodeIds[j] = nodeIdList[6 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_TRIANGLE, 6, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 3; j++) { nodeIds[j] = nodeIdList[3 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_TRIANGLE, 3, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_tria3", 7) == 0 || strncmp(line, "g_tria6", 7) == 0) { // skipping ghost cells if (strncmp(line, "g_tria6", 7) == 0) { vtkDebugMacro("g_tria6"); cellType = vtkPEnSightReader::TRIA6; } else { vtkDebugMacro("g_tria3"); cellType = vtkPEnSightReader::TRIA3; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of triangle cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TRIA6) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 6 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 3 * numElements, ios::cur); } } else if (strncmp(line, "quad4", 5) == 0 || strncmp(line, "quad8", 5) == 0) { if (strncmp(line, "quad8", 5) == 0) { vtkDebugMacro("quad8"); cellType = vtkPEnSightReader::QUAD8; } else { vtkDebugMacro("quad4"); cellType = vtkPEnSightReader::QUAD4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of quad cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::QUAD8) { nodeIds = new vtkIdType[8]; nodeIdList = new int[numElements * 8]; this->ReadIntArray(nodeIdList, numElements * 8); } else { nodeIds = new vtkIdType[4]; nodeIdList = new int[numElements * 4]; this->ReadIntArray(nodeIdList, numElements * 4); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::QUAD8) { for (j = 0; j < 8; j++) { nodeIds[j] = nodeIdList[8 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_QUAD, 8, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 4; j++) { nodeIds[j] = nodeIdList[4 * i + j] - 1; } this->InsertNextCellAndId(output, VTK_QUAD, 4, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_quad4", 7) == 0 || strncmp(line, "g_quad8", 7) == 0) { // skipping ghost cells if (strncmp(line, "g_quad8", 7) == 0) { vtkDebugMacro("g_quad8"); cellType = vtkPEnSightReader::QUAD8; } else { vtkDebugMacro("g_quad4"); cellType = vtkPEnSightReader::QUAD4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of quad cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::QUAD8) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 8 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 4 * numElements, ios::cur); } } else if (strncmp(line, "nfaced", 6) == 0) { vtkDebugMacro("nfaced"); int* numFacesPerElement; int* numNodesPerFace; int* numNodesPerElement; int* nodeMarker; int numPts = 0; int numFaces = 0; int numNodes = 0; int faceCount = 0; int nodeCount = 0; int elementNodeCount = 0; cellType = vtkPEnSightReader::NFACED; this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of nfaced cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } numFacesPerElement = new int[numElements]; this->ReadIntArray(numFacesPerElement, numElements); for (i = 0; i < numElements; i++) { numFaces += numFacesPerElement[i]; } numNodesPerFace = new int[numFaces]; this->ReadIntArray(numNodesPerFace, numFaces); numNodesPerElement = new int[numElements]; for (i = 0; i < numElements; i++) { numNodesPerElement[i] = 0; for (j = 0; j < numFacesPerElement[i]; j++) { numNodesPerElement[i] += numNodesPerFace[faceCount + j]; } faceCount += numFacesPerElement[i]; } delete[] numFacesPerElement; delete[] numNodesPerFace; for (i = 0; i < numElements; i++) { numNodes += numNodesPerElement[i]; } // Points may have not been read here // but we have an estimation in ReadOrSkipCoordinates( .... , skip = true ) numPts = this->GetPointIds(idx)->GetNumberOfIds(); nodeMarker = new int[numPts]; for (i = 0; i < numPts; i++) { nodeMarker[i] = -1; } nodeIdList = new int[numNodes]; this->ReadIntArray(nodeIdList, numNodes); for (i = 0; i < numElements; i++) { // For each nfaced... elementNodeCount = 0; nodeIds = new vtkIdType[numNodesPerElement[i]]; for (j = 0; j < numNodesPerElement[i]; j++) { // For each Node (Point) in Element (Nfaced) ... if (nodeMarker[nodeIdList[nodeCount] - 1] < i) { nodeIds[elementNodeCount] = nodeIdList[nodeCount] - 1; nodeMarker[nodeIdList[nodeCount] - 1] = i; elementNodeCount += 1; } nodeCount++; } this->InsertNextCellAndId( output, VTK_CONVEX_POINT_SET, elementNodeCount, nodeIds, idx, cellType, i, numElements); delete[] nodeIds; } delete[] nodeMarker; delete[] nodeIdList; delete[] numNodesPerElement; } else if (strncmp(line, "tetra4", 6) == 0 || strncmp(line, "tetra10", 7) == 0) { if (strncmp(line, "tetra10", 7) == 0) { vtkDebugMacro("tetra10"); cellType = vtkPEnSightReader::TETRA10; } else { vtkDebugMacro("tetra4"); cellType = vtkPEnSightReader::TETRA4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro( "Invalid number of tetrahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TETRA10) { nodeIds = new vtkIdType[10]; nodeIdList = new int[numElements * 10]; this->ReadIntArray(nodeIdList, numElements * 10); } else { nodeIds = new vtkIdType[4]; nodeIdList = new int[numElements * 4]; this->ReadIntArray(nodeIdList, numElements * 4); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::TETRA10) { for (j = 0; j < 10; j++) { nodeIds[j] = nodeIdList[10 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_TETRA, 10, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 4; j++) { nodeIds[j] = nodeIdList[4 * i + j] - 1; } this->InsertNextCellAndId(output, VTK_TETRA, 4, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_tetra4", 8) == 0 || strncmp(line, "g_tetra10", 9) == 0) { // skipping ghost cells if (strncmp(line, "g_tetra10", 9) == 0) { vtkDebugMacro("g_tetra10"); cellType = vtkPEnSightReader::TETRA10; } else { vtkDebugMacro("g_tetra4"); cellType = vtkPEnSightReader::TETRA4; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro( "Invalid number of tetrahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::TETRA10) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 10 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 4 * numElements, ios::cur); } } else if (strncmp(line, "pyramid5", 8) == 0 || strncmp(line, "pyramid13", 9) == 0) { if (strncmp(line, "pyramid13", 9) == 0) { vtkDebugMacro("pyramid13"); cellType = vtkPEnSightReader::PYRAMID13; } else { vtkDebugMacro("pyramid5"); cellType = vtkPEnSightReader::PYRAMID5; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pyramid cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PYRAMID13) { nodeIds = new vtkIdType[13]; nodeIdList = new int[numElements * 13]; this->ReadIntArray(nodeIdList, numElements * 13); } else { nodeIds = new vtkIdType[5]; nodeIdList = new int[numElements * 5]; this->ReadIntArray(nodeIdList, numElements * 5); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::PYRAMID13) { for (j = 0; j < 13; j++) { nodeIds[j] = nodeIdList[13 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_PYRAMID, 13, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 5; j++) { nodeIds[j] = nodeIdList[5 * i + j] - 1; } this->InsertNextCellAndId(output, VTK_PYRAMID, 5, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_pyramid5", 10) == 0 || strncmp(line, "g_pyramid13", 11) == 0) { // skipping ghost cells if (strncmp(line, "g_pyramid13", 11) == 0) { vtkDebugMacro("g_pyramid13"); cellType = vtkPEnSightReader::PYRAMID13; } else { vtkDebugMacro("g_pyramid5"); cellType = vtkPEnSightReader::PYRAMID5; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pyramid cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PYRAMID13) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 13 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 5 * numElements, ios::cur); } } else if (strncmp(line, "hexa8", 5) == 0 || strncmp(line, "hexa20", 6) == 0) { if (strncmp(line, "hexa20", 6) == 0) { vtkDebugMacro("hexa20"); cellType = vtkPEnSightReader::HEXA20; } else { vtkDebugMacro("hexa8"); cellType = vtkPEnSightReader::HEXA8; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of hexahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::HEXA20) { nodeIds = new vtkIdType[20]; nodeIdList = new int[numElements * 20]; this->ReadIntArray(nodeIdList, numElements * 20); } else { nodeIds = new vtkIdType[8]; nodeIdList = new int[numElements * 8]; this->ReadIntArray(nodeIdList, numElements * 8); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::HEXA20) { for (j = 0; j < 20; j++) { nodeIds[j] = nodeIdList[20 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_HEXAHEDRON, 20, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 8; j++) { nodeIds[j] = nodeIdList[8 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_HEXAHEDRON, 8, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_hexa8", 7) == 0 || strncmp(line, "g_hexa20", 8) == 0) { // skipping ghost cells if (strncmp(line, "g_hexa20", 8) == 0) { vtkDebugMacro("g_hexa20"); cellType = vtkPEnSightReader::HEXA20; } else { vtkDebugMacro("g_hexa8"); cellType = vtkPEnSightReader::HEXA8; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of hexahedral cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::HEXA20) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 20 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 8 * numElements, ios::cur); } } else if (strncmp(line, "penta6", 6) == 0 || strncmp(line, "penta15", 7) == 0) { if (strncmp(line, "penta15", 7) == 0) { vtkDebugMacro("penta15"); cellType = vtkPEnSightReader::PENTA15; } else { vtkDebugMacro("penta6"); cellType = vtkPEnSightReader::PENTA6; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pentagonal cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PENTA15) { nodeIds = new vtkIdType[15]; nodeIdList = new int[numElements * 15]; this->ReadIntArray(nodeIdList, numElements * 15); } else { nodeIds = new vtkIdType[6]; nodeIdList = new int[numElements * 6]; this->ReadIntArray(nodeIdList, numElements * 6); } for (i = 0; i < numElements; i++) { if (cellType == vtkPEnSightReader::PENTA15) { for (j = 0; j < 15; j++) { nodeIds[j] = nodeIdList[15 * i + j] - 1; } this->InsertNextCellAndId( output, VTK_QUADRATIC_WEDGE, 15, nodeIds, idx, cellType, i, numElements); } else { for (j = 0; j < 6; j++) { nodeIds[j] = nodeIdList[6 * i + j] - 1; } this->InsertNextCellAndId(output, VTK_WEDGE, 6, nodeIds, idx, cellType, i, numElements); } } delete[] nodeIds; delete[] nodeIdList; } else if (strncmp(line, "g_penta6", 8) == 0 || strncmp(line, "g_penta15", 9) == 0) { // skipping ghost cells if (strncmp(line, "g_penta15", 9) == 0) { vtkDebugMacro("g_penta15"); cellType = vtkPEnSightReader::PENTA15; } else { vtkDebugMacro("g_penta6"); cellType = vtkPEnSightReader::PENTA6; } this->ReadInt(&numElements); if (numElements < 0 || numElements * (int)sizeof(int) > this->FileSize || numElements > this->FileSize) { vtkErrorMacro("Invalid number of pentagonal cells; check that ByteOrder is set correctly."); return -1; } if (this->ElementIdsListed) { this->IFile->seekg(sizeof(int) * numElements, ios::cur); } if (cellType == vtkPEnSightReader::PENTA15) { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 15 * numElements, ios::cur); } else { // Skip nodeIdList. this->IFile->seekg(sizeof(int) * 6 * numElements, ios::cur); } } else if (strncmp(line, "END TIME STEP", 13) == 0) { // time to read coordinates at end if necessary if (this->CoordinatesAtEnd && (this->InjectCoordinatesAtEnd(output, coordinatesOffset, idx) == -1)) { return -1; } return 1; } else if (this->IS->fail()) { // May want consistency check here? // time to read coordinates at end if necessary if (this->CoordinatesAtEnd && (this->InjectCoordinatesAtEnd(output, coordinatesOffset, idx) == -1)) { return -1; } // vtkWarningMacro("EOF on geometry file"); return 1; } else { vtkErrorMacro("undefined geometry file line"); return -1; } this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; // time to read coordinates at end if necessary if (this->CoordinatesAtEnd && (this->InjectCoordinatesAtEnd(output, coordinatesOffset, idx) == -1)) { return -1; } continue; } lineRead = this->ReadLine(line); } // time to read coordinates at end if necessary if (this->CoordinatesAtEnd && (this->InjectCoordinatesAtEnd(output, coordinatesOffset, idx) == -1)) { return -1; } return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::CreateStructuredGridOutput( int partId, char line[80], const char* name, vtkMultiBlockDataSet* compositeOutput) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; int i; vtkPoints* points = vtkPoints::New(); int numPts; this->NumberOfNewOutputs++; vtkDataSet* ds = this->GetDataSetFromBlock(compositeOutput, partId); if (ds == NULL || !ds->IsA("vtkStructuredGrid")) { vtkDebugMacro("creating new structured grid output"); vtkStructuredGrid* sgrid = vtkStructuredGrid::New(); this->AddToBlock(compositeOutput, partId, sgrid); sgrid->Delete(); ds = sgrid; } if (this->StructuredPartIds->IsId(partId) == -1) this->StructuredPartIds->InsertNextId(partId); vtkStructuredGrid* output = vtkStructuredGrid::SafeDownCast(ds); this->SetBlockName(compositeOutput, partId, name); if (sscanf(line, " %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); // global number of points numPts = dimensions[0] * dimensions[1] * dimensions[2]; if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || numPts < 0 || numPts * (int)sizeof(int) > this->FileSize || numPts > this->FileSize) { vtkErrorMacro("Invalid dimensions read; check that ByteOrder is set correctly."); points->Delete(); return -1; } int newDimensions[3]; int splitDimension; int splitDimensionBeginIndex; vtkUnsignedCharArray* pointGhostArray = NULL; vtkUnsignedCharArray* cellGhostArray = NULL; if (this->GhostLevels == 0) { this->PrepareStructuredDimensionsForDistribution( partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, 0, NULL, NULL); } else { pointGhostArray = vtkUnsignedCharArray::New(); pointGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); cellGhostArray = vtkUnsignedCharArray::New(); cellGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); this->PrepareStructuredDimensionsForDistribution(partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, this->GhostLevels, pointGhostArray, cellGhostArray); } output->SetDimensions(newDimensions); // output->SetWholeExtent( // 0, newDimensions[0]-1, 0, newDimensions[1]-1, 0, newDimensions[2]-1); points->Allocate(this->GetPointIds(partId)->GetLocalNumberOfIds()); long currentPositionInFile = this->IFile->tellg(); // Buffer Read. this->FloatBufferFilePosition = currentPositionInFile; this->FloatBufferIndexBegin = 0; this->FloatBufferNumberOfVectors = numPts; long endFilePosition = currentPositionInFile + 3 * numPts * sizeof(float); if (this->Fortran) endFilePosition += 24; // 4 * (begin + end) * number of components (3) this->UpdateFloatBuffer(); this->IFile->seekg(endFilePosition); for (i = 0; i < numPts; i++) { int realPointId = this->GetPointIds(partId)->GetId(i); if (realPointId != -1) { float vec[3]; this->GetVectorFromFloatBuffer(i, vec); points->InsertNextPoint(vec[0], vec[1], vec[2]); } } output->SetPoints(points); if (iblanked) { int* iblanks = new int[numPts]; this->ReadIntArray(iblanks, numPts); for (i = 0; i < numPts; i++) { if (!iblanks[i]) { int realPointId = this->GetPointIds(partId)->GetId(i); if (realPointId != -1) output->BlankPoint(realPointId); } } delete[] iblanks; } // Ghost level End if (this->GhostLevels > 0) { output->GetPointData()->AddArray(pointGhostArray); output->GetCellData()->AddArray(cellGhostArray); } points->Delete(); this->IFile->peek(); if (this->IFile->eof()) { lineRead = 0; } else { lineRead = this->ReadLine(line); } if (strncmp(line, "node_ids", 8) == 0) { int* nodeIds = new int[numPts]; this->ReadIntArray(nodeIds, numPts); lineRead = this->ReadLine(line); delete[] nodeIds; } if (strncmp(line, "element_ids", 11) == 0) { int numElements = (dimensions[0] - 1) * (dimensions[1] - 1) * (dimensions[2] - 1); int* elementIds = new int[numElements]; this->ReadIntArray(elementIds, numElements); lineRead = this->ReadLine(line); delete[] elementIds; } return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::CreateRectilinearGridOutput( int partId, char line[80], const char* name, vtkMultiBlockDataSet* compositeOutput) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; int i; vtkFloatArray* xCoords = vtkFloatArray::New(); vtkFloatArray* yCoords = vtkFloatArray::New(); vtkFloatArray* zCoords = vtkFloatArray::New(); float* tempCoords; int numPts; this->NumberOfNewOutputs++; vtkDataSet* ds = this->GetDataSetFromBlock(compositeOutput, partId); if (ds == NULL || !ds->IsA("vtkRectilinearGrid")) { vtkDebugMacro("creating new rectilinear grid output"); vtkRectilinearGrid* rgrid = vtkRectilinearGrid::New(); this->AddToBlock(compositeOutput, partId, rgrid); rgrid->Delete(); ds = rgrid; } if (this->StructuredPartIds->IsId(partId) == -1) this->StructuredPartIds->InsertNextId(partId); vtkRectilinearGrid* output = vtkRectilinearGrid::SafeDownCast(ds); this->SetBlockName(compositeOutput, partId, name); if (sscanf(line, " %*s %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || (dimensions[0] + dimensions[1] + dimensions[2]) < 0 || (dimensions[0] + dimensions[1] + dimensions[2]) * (int)sizeof(int) > this->FileSize || (dimensions[0] + dimensions[1] + dimensions[2]) > this->FileSize) { vtkErrorMacro("Invalid dimensions read; check that BytetOrder is set correctly."); xCoords->Delete(); yCoords->Delete(); zCoords->Delete(); return -1; } int newDimensions[3]; int splitDimension; int splitDimensionBeginIndex; vtkUnsignedCharArray* pointGhostArray = NULL; vtkUnsignedCharArray* cellGhostArray = NULL; if (this->GhostLevels == 0) { this->PrepareStructuredDimensionsForDistribution( partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, 0, NULL, NULL); } else { pointGhostArray = vtkUnsignedCharArray::New(); pointGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); cellGhostArray = vtkUnsignedCharArray::New(); cellGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); this->PrepareStructuredDimensionsForDistribution(partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, this->GhostLevels, pointGhostArray, cellGhostArray); } output->SetDimensions(newDimensions); // output->SetWholeExtent( // 0, newDimensions[0]-1, 0, newDimensions[1]-1, 0, newDimensions[2]-1); xCoords->Allocate(newDimensions[0]); yCoords->Allocate(newDimensions[1]); zCoords->Allocate(newDimensions[2]); int beginDimension[3]; beginDimension[splitDimension] = splitDimensionBeginIndex; beginDimension[(splitDimension + 1) % 3] = 0; beginDimension[(splitDimension + 2) % 3] = 0; tempCoords = new float[dimensions[0]]; this->ReadFloatArray(tempCoords, dimensions[0]); for (i = beginDimension[0]; i < (beginDimension[0] + newDimensions[0]); i++) { xCoords->InsertNextTuple(&tempCoords[i]); } delete[] tempCoords; tempCoords = new float[dimensions[1]]; this->ReadFloatArray(tempCoords, dimensions[1]); for (i = beginDimension[1]; i < (beginDimension[1] + newDimensions[1]); i++) { yCoords->InsertNextTuple(&tempCoords[i]); } delete[] tempCoords; tempCoords = new float[dimensions[2]]; this->ReadFloatArray(tempCoords, dimensions[2]); for (i = beginDimension[2]; i < (beginDimension[2] + newDimensions[2]); i++) { zCoords->InsertNextTuple(&tempCoords[i]); } delete[] tempCoords; // Ghost level End if (this->GhostLevels > 0) { output->GetPointData()->AddArray(pointGhostArray); output->GetCellData()->AddArray(cellGhostArray); } if (iblanked) { vtkWarningMacro("VTK does not handle blanking for rectilinear grids."); numPts = dimensions[0] * dimensions[1] * dimensions[2]; int* tempArray = new int[numPts]; this->ReadIntArray(tempArray, numPts); delete[] tempArray; } output->SetXCoordinates(xCoords); output->SetYCoordinates(yCoords); output->SetZCoordinates(zCoords); xCoords->Delete(); yCoords->Delete(); zCoords->Delete(); // reading next line to check for EOF lineRead = this->ReadLine(line); return lineRead; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::CreateImageDataOutput( int partId, char line[80], const char* name, vtkMultiBlockDataSet* compositeOutput) { char subLine[80]; int lineRead; int iblanked = 0; int dimensions[3]; float origin[3], delta[3]; int numPts; this->NumberOfNewOutputs++; vtkDataSet* ds = this->GetDataSetFromBlock(compositeOutput, partId); if (ds == NULL || !ds->IsA("vtkImageData")) { vtkDebugMacro("creating new image data output"); vtkImageData* idata = vtkImageData::New(); this->AddToBlock(compositeOutput, partId, idata); idata->Delete(); ds = idata; } if (this->StructuredPartIds->IsId(partId) == -1) this->StructuredPartIds->InsertNextId(partId); vtkImageData* output = vtkImageData::SafeDownCast(ds); this->SetBlockName(compositeOutput, partId, name); if (sscanf(line, " %*s %*s %s", subLine) == 1) { if (strncmp(subLine, "iblanked", 8) == 0) { iblanked = 1; } } this->ReadIntArray(dimensions, 3); int newDimensions[3]; int splitDimension; int splitDimensionBeginIndex; vtkUnsignedCharArray* pointGhostArray = NULL; vtkUnsignedCharArray* cellGhostArray = NULL; if (this->GhostLevels == 0) { this->PrepareStructuredDimensionsForDistribution( partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, 0, NULL, NULL); } else { pointGhostArray = vtkUnsignedCharArray::New(); pointGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); cellGhostArray = vtkUnsignedCharArray::New(); cellGhostArray->SetName(vtkDataSetAttributes::GhostArrayName()); this->PrepareStructuredDimensionsForDistribution(partId, dimensions, newDimensions, &splitDimension, &splitDimensionBeginIndex, this->GhostLevels, pointGhostArray, cellGhostArray); } output->SetDimensions(newDimensions); // output->SetWholeExtent( // 0, newDimensions[0]-1, 0, newDimensions[1]-1, 0, newDimensions[2]-1); this->ReadFloatArray(origin, 3); this->ReadFloatArray(delta, 3); // Compute new origin float newOrigin[3]; newOrigin[splitDimension] = origin[splitDimension] + ((float)splitDimensionBeginIndex) * delta[splitDimension]; newOrigin[(splitDimension + 1) % 3] = origin[(splitDimension + 1) % 3]; newOrigin[(splitDimension + 2) % 3] = origin[(splitDimension + 2) % 3]; output->SetOrigin(newOrigin[0], newOrigin[1], newOrigin[2]); output->SetSpacing(delta[0], delta[1], delta[2]); // Ghost level End if (this->GhostLevels > 0) { output->GetPointData()->AddArray(pointGhostArray); output->GetCellData()->AddArray(cellGhostArray); } if (iblanked) { vtkWarningMacro("VTK does not handle blanking for image data."); numPts = dimensions[0] * dimensions[1] * dimensions[2]; if (dimensions[0] < 0 || dimensions[0] * (int)sizeof(int) > this->FileSize || dimensions[0] > this->FileSize || dimensions[1] < 0 || dimensions[1] * (int)sizeof(int) > this->FileSize || dimensions[1] > this->FileSize || dimensions[2] < 0 || dimensions[2] * (int)sizeof(int) > this->FileSize || dimensions[2] > this->FileSize || numPts < 0 || numPts * (int)sizeof(int) > this->FileSize || numPts > this->FileSize) { return -1; } int* tempArray = new int[numPts]; this->ReadIntArray(tempArray, numPts); delete[] tempArray; } // reading next line to check for EOF lineRead = this->ReadLine(line); return lineRead; } // Internal function to read in a line up to 80 characters. // Returns zero if there was an error. int vtkPEnSightGoldBinaryReader::ReadLine(char result[80]) { if (!(this->IFile->read(result, 80).good())) { // The read fails when reading the last part/array when there are no points. // I took out the error macro as a tempory fix. // We need to determine what EnSight does when the part with zero point // is not the last, and change the read array method. // int fixme; // I do not a file to test with yet. vtkDebugMacro("Read failed"); return 0; } // fix to the memory leakage problem detected by Valgrind result[79] = '\0'; if (this->Fortran) { strncpy(result, &result[4], 76); result[76] = 0; // better read an extra 8 bytes to prevent error next time char dummy[8]; if (!(this->IFile->read(dummy, 8).good())) { vtkDebugMacro("Read (fortran) failed"); return 0; } } return 1; } // Internal function to read a single integer. // Returns zero if there was an error. // Sets byte order so that part id is reasonable. int vtkPEnSightGoldBinaryReader::ReadPartId(int* result) { // first swap like normal. if (this->ReadInt(result) == 0) { vtkErrorMacro("Read failed"); return 0; } // second: try an experimental byte swap. // Only experiment if byte order is not set. if (this->ByteOrder == FILE_UNKNOWN_ENDIAN) { int tmpLE = *result; int tmpBE = *result; vtkByteSwap::Swap4LE(&tmpLE); vtkByteSwap::Swap4BE(&tmpBE); if (tmpLE >= 0 && tmpLE < MAXIMUM_PART_ID) { this->ByteOrder = FILE_LITTLE_ENDIAN; *result = tmpLE; return 1; } if (tmpBE >= 0 && tmpBE < MAXIMUM_PART_ID) { this->ByteOrder = FILE_BIG_ENDIAN; *result = tmpBE; return 1; } vtkErrorMacro("Byte order could not be determined."); return 0; } return 1; } // Internal function to read a single integer. // Returns zero if there was an error. int vtkPEnSightGoldBinaryReader::ReadInt(int* result) { char dummy[4]; if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } if (!this->IFile->read((char*)result, sizeof(int)).good()) { vtkErrorMacro("Read failed"); return 0; } if (this->ByteOrder == FILE_LITTLE_ENDIAN) { vtkByteSwap::Swap4LE(result); } else if (this->ByteOrder == FILE_BIG_ENDIAN) { vtkByteSwap::Swap4BE(result); } if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } return 1; } // Internal function to read an integer array. // Returns zero if there was an error. int vtkPEnSightGoldBinaryReader::ReadIntArray(int* result, int numInts) { if (numInts <= 0) { return 1; } char dummy[4]; if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } if (!this->IFile->read((char*)result, sizeof(int) * numInts).good()) { vtkErrorMacro("Read failed."); return 0; } if (this->ByteOrder == FILE_LITTLE_ENDIAN) { vtkByteSwap::Swap4LERange(result, numInts); } else { vtkByteSwap::Swap4BERange(result, numInts); } if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } return 1; } // Internal function to read a float array. // Returns zero if there was an error. int vtkPEnSightGoldBinaryReader::ReadFloatArray(float* result, int numFloats) { if (numFloats <= 0) { return 1; } char dummy[4]; if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } if (!this->IFile->read((char*)result, sizeof(float) * numFloats).good()) { vtkErrorMacro("Read failed"); return 0; } if (this->ByteOrder == FILE_LITTLE_ENDIAN) { vtkByteSwap::Swap4LERange(result, numFloats); } else { vtkByteSwap::Swap4BERange(result, numFloats); } if (this->Fortran) { if (!this->IFile->read(dummy, 4).good()) { vtkErrorMacro("Read (fortran) failed."); return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::ReadOrSkipCoordinates( vtkPoints* points, long offset, int partId, bool skip) { int numPts; if (offset == -1) { return 0; } this->IFile->seekg(offset); this->ReadInt(&numPts); if (numPts < 0 || numPts > this->FileSize || numPts * (int)sizeof(int) > this->FileSize) { vtkErrorMacro( "Invalid number of unstructured points read; check that ByteOrder is set correctly."); return -1; } vtkDebugMacro("num. points: " << numPts); if (this->NodeIdsListed) { this->IFile->seekg(sizeof(int) * numPts, ios::cur); } long currentPositionInFile = this->IFile->tellg(); this->FloatBufferFilePosition = currentPositionInFile; this->FloatBufferIndexBegin = 0; this->FloatBufferNumberOfVectors = numPts; this->UpdateFloatBuffer(); // Position to reach at the end of this method long endFilePosition = currentPositionInFile + 3 * numPts * sizeof(float); if (this->Fortran) endFilePosition += 24; // 4 * (begin + end) * number of components (3) // Only to quickly visualize who reads what... if (skip) { // Inject real Number of points, as we cannot take the size of the vector as a reference // numPts comes from the file, it cannot be wrong // Needed in nfaced... this->GetPointIds(partId)->SetNumberOfIds(numPts); this->IFile->seekg(endFilePosition); return 0; } else { if (this->GetPointIds(partId)->GetNumberOfIds() == 0) { // No Point was injected at all For this Part. There is clearly a problem... // TODO: Do something ? // delete [] xCoords; // delete [] yCoords; // delete [] zCoords; this->IFile->seekg(endFilePosition); return 0; } else { // Inject really needed points int i; int localNumberOfIds = this->GetPointIds(partId)->GetLocalNumberOfIds(); points->Allocate(localNumberOfIds); points->SetNumberOfPoints(localNumberOfIds); int maxId = -1; int minId = -1; for (i = 0; i < numPts; i++) { float vec[3]; int id = this->GetPointIds(partId)->GetId(i); if (id != -1) { if ((minId == -1) || (minId > id)) minId = id; if ((maxId == -1) || (maxId < id)) maxId = id; this->GetVectorFromFloatBuffer(i, vec); points->SetPoint(id, vec[0], vec[1], vec[2]); } } // Inject real Number of points, as we cannot take the size of the vector as a reference // numPts comes from the file, it cannot be wrong // Needed in nfaced... // In case read has never been skipped, we do this again here this->GetPointIds(partId)->SetNumberOfIds(numPts); // delete [] xCoords; // delete [] yCoords; // delete [] zCoords; this->IFile->seekg(endFilePosition); return localNumberOfIds; } } } //---------------------------------------------------------------------------- int vtkPEnSightGoldBinaryReader::InjectCoordinatesAtEnd( vtkUnstructuredGrid* output, long coordinatesOffset, int partId) { bool eof = false; if (this->IFile->eof()) eof = true; if (eof) { // remove the EOF flag to read back coordinates this->IFile->clear(); } long currentFilePosition = this->IFile->tellg(); vtkPoints* points = vtkPoints::New(); int pointsRead = this->ReadOrSkipCoordinates(points, coordinatesOffset, partId, false); this->IFile->seekg(currentFilePosition); if (pointsRead == -1) { return -1; } output->SetPoints(points); points->Delete(); this->CoordinatesAtEnd = false; // Inject Global Node Ids vtkPointData* pointData = output->GetPointData(); vtkDataArray* globalNodeIds = this->GetPointIds(partId)->GenerateGlobalIdsArray("GlobalNodeId"); pointData->SetGlobalIds(globalNodeIds); globalNodeIds->Delete(); // We do not inject global Element Ids: It is not required for D3, for example, // and it consumes a lot of memory if (eof) { // put the EOF flag back this->IFile->peek(); } return pointsRead; } //---------------------------------------------------------------------------- void vtkPEnSightGoldBinaryReader::GetVectorFromFloatBuffer(int i, float* vector) { // We assume FloatBufferIndexBegin, FloatBufferFilePosition, and FloatBufferNumberOfVectors // were previously set. int closestBufferBegin = (i / this->FloatBufferSize) * this->FloatBufferSize; if ((this->FloatBufferIndexBegin == -1) || (closestBufferBegin != this->FloatBufferIndexBegin)) { this->FloatBufferIndexBegin = closestBufferBegin; this->UpdateFloatBuffer(); } int index = i - this->FloatBufferIndexBegin; vector[0] = this->FloatBuffer[0][index]; vector[1] = this->FloatBuffer[1][index]; vector[2] = this->FloatBuffer[2][index]; } //---------------------------------------------------------------------------- void vtkPEnSightGoldBinaryReader::UpdateFloatBuffer() { long currentPosition = this->IFile->tellg(); int sizeToRead; if (this->FloatBufferIndexBegin + this->FloatBufferSize > this->FloatBufferNumberOfVectors) { sizeToRead = this->FloatBufferNumberOfVectors - this->FloatBufferIndexBegin; } else { sizeToRead = this->FloatBufferSize; } for (int i = 0; i < 3; i++) { // We cannot use ReadFloatArray method, because Fortran format has dummy things if (this->Fortran) this->IFile->seekg(this->FloatBufferFilePosition + 4 + i * (this->FloatBufferNumberOfVectors * sizeof(float) + 8) + this->FloatBufferIndexBegin * sizeof(float)); else this->IFile->seekg(this->FloatBufferFilePosition + i * this->FloatBufferNumberOfVectors * sizeof(float) + this->FloatBufferIndexBegin * sizeof(float)); if (!this->IFile->read((char*)this->FloatBuffer[i], sizeof(float) * sizeToRead).good()) { vtkErrorMacro("Read failed"); } if (this->ByteOrder == FILE_LITTLE_ENDIAN) { vtkByteSwap::Swap4LERange(this->FloatBuffer[i], sizeToRead); } else { vtkByteSwap::Swap4BERange(this->FloatBuffer[i], sizeToRead); } } this->IFile->seekg(currentPosition); } //---------------------------------------------------------------------------- void vtkPEnSightGoldBinaryReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
29.112335
100
0.577188
sakjain92
0f9226fe427935f07725e7a9f76d870136e14917
176
cpp
C++
shared/fixes2.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
1
2017-07-04T02:50:26.000Z
2017-07-04T02:50:26.000Z
shared/fixes2.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
null
null
null
shared/fixes2.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
2
2016-05-12T02:47:26.000Z
2020-03-02T10:54:14.000Z
#include "fixes2.hpp" #include <opencv2/core/core.hpp> double getTickCount() { return cv::getTickCount(); } double getTickFrequency() { return cv::getTickFrequency(); }
16
34
0.710227
uroboro
0f9719aae6a7bfd572e601cd287e5efcb3ebd0f9
2,434
cpp
C++
MonoNative.Tests/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Runtime.Serialization.Formatters // Name: ServerFault // C++ Typed Name: mscorlib::System::Runtime::Serialization::Formatters::ServerFault #include <gtest/gtest.h> #include <mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_ServerFault.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Runtime { namespace Serialization { namespace Formatters { //Constructors Tests //ServerFault(mscorlib::System::String exceptionType, mscorlib::System::String message, mscorlib::System::String stackTrace) TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,Constructor_1) { } //Public Methods Tests //Public Properties Tests // Property ExceptionType // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,get_ExceptionType_Test) { } // Property ExceptionType // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,set_ExceptionType_Test) { } // Property ExceptionMessage // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,get_ExceptionMessage_Test) { } // Property ExceptionMessage // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,set_ExceptionMessage_Test) { } // Property StackTrace // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,get_StackTrace_Test) { } // Property StackTrace // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_Runtime_Serialization_Formatters_ServerFault_Fixture,set_StackTrace_Test) { } } } } } }
24.585859
129
0.693509
brunolauze
0f97aeb5a2ce6aaa937bacc6722b0f0a924d848f
8,621
cpp
C++
VC2010Samples/ATL/OLEDB/Consumer/catdb/CatDBvw.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/ATL/OLEDB/Consumer/catdb/CatDBvw.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/ATL/OLEDB/Consumer/catdb/CatDBvw.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// Cat3View.cpp : implementation of the CCatDBView class // // This is a part of the Microsoft Foundation Classes and // Templates (MFC&T). // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // MFC&T Reference and related electronic documentation provided // with the library. See these sources for detailed information // regarding the MFC&T product. // #include "stdafx.h" #include "CatDB.h" #include "CatDBDoc.h" #include "CatDBVw.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCatDBView IMPLEMENT_DYNCREATE(CCatDBView, CListView) BEGIN_MESSAGE_MAP(CCatDBView, CListView) //{{AFX_MSG_MAP(CCatDBView) ON_UPDATE_COMMAND_UI(ID_VIEW_COLUMNINFO, OnUpdateViewColumnlevel) ON_UPDATE_COMMAND_UI(ID_VIEW_TABLES, OnUpdateViewTablelevel) ON_COMMAND(ID_VIEW_COLUMNINFO, OnViewColumnlevel) ON_COMMAND(ID_VIEW_TABLES, OnViewTablelevel) ON_COMMAND(ID_FILE_OPEN, OnFileOpen) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCatDBView construction/destruction CCatDBView::CCatDBView() { } CCatDBView::~CCatDBView() { } BOOL CCatDBView::PreCreateWindow(CREATESTRUCT& cs) { // set list view control to report, single selection cs.style &= ~(LVS_LIST | LVS_ICON | LVS_SMALLICON); cs.style |= LVS_REPORT; cs.style |= LVS_SINGLESEL; return CListView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CCatDBView drawing void CCatDBView::OnDraw(CDC* ) { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here } void CCatDBView::OnInitialUpdate() { CListView::OnInitialUpdate(); // TODO: You may populate your ListView with items by directly accessing // its list control through a call to GetListCtrl(). } ///////////////////////////////////////////////////////////////////////////// // CCatDBView diagnostics #ifdef _DEBUG void CCatDBView::AssertValid() const { CListView::AssertValid(); } void CCatDBView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } CCatDBDoc* CCatDBView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCatDBDoc))); return (CCatDBDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CCatDBView message handlers void CCatDBView::OnUpdateViewColumnlevel(CCmdUI* pCmdUI) { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (pDoc->m_nLevel == CCatDBDoc::levelTable && GetListCtrl().GetSelectedCount()) { pCmdUI->Enable(); } else pCmdUI->Enable(FALSE); } void CCatDBView::OnUpdateViewTablelevel(CCmdUI* pCmdUI) { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (pDoc->m_nLevel == CCatDBDoc::levelColumn) pCmdUI->Enable(); else pCmdUI->Enable(FALSE); } BOOL CCatDBView::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult) { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // handle double click if at table view level if (pDoc->m_nLevel == CCatDBDoc::levelTable) { if (message == WM_NOTIFY && ((NMHDR*)lParam)->code == NM_DBLCLK) { OnViewColumnlevel(); return 0; } } return CListView::OnChildNotify(message, wParam, lParam, pLResult); } void CCatDBView::OnViewColumnlevel() { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // determine list control selection CListCtrl& control = GetListCtrl(); int nCount = control.GetItemCount(); int i; for (i = 0; i < nCount; i++) { if (control.GetItemState(i,LVIS_SELECTED)) break; } if (i < nCount) { // pull table name to send to document pDoc->m_strTableName = control.GetItemText(i,0); #ifndef _UNICODE LPCSTR lpszName; lpszName = pDoc->m_strTableName; #else LPSTR lpszName; char rgchTableName[257]; lpszName = rgchTableName; int nSize; nSize = ::WideCharToMultiByte(CP_ACP,0,pDoc->m_strTableName, -1, lpszName, 257, NULL, NULL); // Notify on failure ASSERT(nSize); #endif // _UNICODE pDoc->FetchColumnInfo(lpszName); pDoc->SetLevel(CCatDBDoc::levelColumn); } } void CCatDBView::OnViewTablelevel() { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->m_strTableName.Empty(); pDoc->FetchTableInfo(); pDoc->SetLevel(CCatDBDoc::levelTable); } void CCatDBView::OnFileOpen() { CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (pDoc->OnOpenDocument()) pDoc->SetLevel(CCatDBDoc::levelTable); else pDoc->SetLevel(CCatDBDoc::levelNone); } void CCatDBView::OnUpdate(CView* , LPARAM , CObject* ) { USES_CONVERSION; CCatDBDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // delete all items and columns CListCtrl& control = GetListCtrl(); control.DeleteAllItems(); while (control.DeleteColumn(0)); // set up view based on the document's level switch (pDoc->m_nLevel) { case CCatDBDoc::levelNone: // set the document title pDoc->SetTitle(pDoc->GetDSN()); break; case CCatDBDoc::levelTable: { // set the document title CString strDataSource = pDoc->GetDSN(); strDataSource += _T(" [Tables]"); pDoc->SetTitle(strDataSource); // add columns to display control.InsertColumn(0,_T("Name"),LVCFMT_LEFT,100,-1); control.InsertColumn(1,_T("Type"),LVCFMT_LEFT,100,1); control.InsertColumn(2,_T("Catalog"),LVCFMT_LEFT,100,2); control.InsertColumn(3,_T("Schema"),LVCFMT_LEFT,100,3); control.InsertColumn(4,_T("Description"),LVCFMT_LEFT,100,4); // traverse the table recordset // displaying the table information int item = 0; while (pDoc->m_pTableset->MoveNext() == S_OK) { control.InsertItem(item, pDoc->m_pTableset->m_szName); control.SetItem(item,1,LVIF_TEXT, pDoc->m_pTableset->m_szType,0,0,0,0); control.SetItem(item,2,LVIF_TEXT, pDoc->m_pTableset->m_szCatalog,0,0,0,0); control.SetItem(item,3,LVIF_TEXT, pDoc->m_pTableset->m_szSchema,0,0,0,0); control.SetItem(item,4,LVIF_TEXT, pDoc->m_pTableset->m_szDescription,0,0,0,0); item++; } break; } case CCatDBDoc::levelColumn: { int column; // set the document title CString strDataSource = pDoc->GetDSN(); strDataSource += _T(" - "); strDataSource += pDoc->m_strTableName; strDataSource += _T(" [Column Info]"); pDoc->SetTitle(strDataSource); // add columns to display // respect the column info settings values column = 0; control.InsertColumn(column++,_T("Name"),LVCFMT_LEFT,100,-1); control.InsertColumn(column,_T("Type"),LVCFMT_LEFT,100,column++); if (pDoc->m_bLength) control.InsertColumn(column,_T("Length"),LVCFMT_LEFT,80,column++); if (pDoc->m_bPrecision) { control.InsertColumn(column,_T("Precision"),LVCFMT_LEFT,80,column++); control.InsertColumn(column,_T("Scale"),LVCFMT_LEFT,50,column++); } if (pDoc->m_bNullability) control.InsertColumn(column,_T("Nullable"),LVCFMT_LEFT,50,column++); // traverse the column info recordset // respect the column info settings values int item = 0; // If the column rowset couldn't be opened, don't attempt to fetch // any data. if (pDoc->m_pColumnset == NULL) break; while (pDoc->m_pColumnset->MoveNext() == S_OK) { CString strValue; // always insert the column name control.InsertItem(item, pDoc->m_pColumnset->m_szColumnName); // always insert the column type column = 1; CString strType; strType.Format("%d", pDoc->m_pColumnset->m_nDataType); control.SetItem(item,column++,LVIF_TEXT, strType,0,0,0,0); // only show type if requested if (pDoc->m_bLength) { strValue.Format(_T("%ld"),pDoc->m_pColumnset->m_nMaxLength); control.SetItem(item,column++,LVIF_TEXT,strValue,0,0,0,0); } // only show precision,scale,radix if requested if (pDoc->m_bPrecision) { // precision strValue.Format(_T("%d"),pDoc->m_pColumnset->m_nNumericPrecision); control.SetItem(item,column++,LVIF_TEXT,strValue,0,0,0,0); // scale strValue.Format(_T("%d"),pDoc->m_pColumnset->m_nNumericScale); control.SetItem(item,column++,LVIF_TEXT,strValue,0,0,0,0); } // only show nullability if requested if (pDoc->m_bNullability) { if (pDoc->m_pColumnset->m_bIsNullable == FALSE) control.SetItem(item,column++,LVIF_TEXT,_T("No"),0,0,0,0); else control.SetItem(item,column++,LVIF_TEXT,_T("Yes"),0,0,0,0); } item++; } break; } } }
25.061047
93
0.670108
alonmm
0f986fb17c7a0ee24ea5ddfea7d3df9d1aed99a9
2,982
cpp
C++
src/cpp/QOpenGLDebugLogger/qopengldebuglogger_wrap.cpp
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
3
2021-10-16T03:40:08.000Z
2021-11-10T07:16:11.000Z
src/cpp/QOpenGLDebugLogger/qopengldebuglogger_wrap.cpp
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
null
null
null
src/cpp/QOpenGLDebugLogger/qopengldebuglogger_wrap.cpp
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
1
2022-02-16T01:34:24.000Z
2022-02-16T01:34:24.000Z
#include <Extras/Utils/nutils.h> #include <QtCore/QObject/qobject_wrap.h> #include "qopengldebuglogger_wrap.h" Napi::FunctionReference QOpenGLDebugLoggerWrap::constructor; Napi::Object QOpenGLDebugLoggerWrap::init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); char CLASSNAME[] = "QOpenGLDebugLogger"; Napi::Function func = DefineClass(env, CLASSNAME, {InstanceMethod("initialize", &QOpenGLDebugLoggerWrap::initialize), InstanceMethod("loggedMessages", &QOpenGLDebugLoggerWrap::loggedMessages), InstanceMethod("logMessage", &QOpenGLDebugLoggerWrap::logMessage), COMPONENT_WRAPPED_METHODS_EXPORT_DEFINE(QOpenGLDebugLoggerWrap)}); constructor = Napi::Persistent(func); exports.Set(CLASSNAME, func); return exports; } QOpenGLDebugLogger* QOpenGLDebugLoggerWrap::getInternalInstance() { return this->instance; } QOpenGLDebugLoggerWrap::QOpenGLDebugLoggerWrap(const Napi::CallbackInfo& info) : Napi::ObjectWrap<QOpenGLDebugLoggerWrap>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); if (info.Length() != 0) { Napi::TypeError::New(env, "Wrong number of arguments") .ThrowAsJavaScriptException(); } this->instance = new QOpenGLDebugLogger(); this->rawData = extrautils::configureComponent(this->getInternalInstance()); } QOpenGLDebugLoggerWrap::~QOpenGLDebugLoggerWrap() { delete this->instance; } Napi::Value QOpenGLDebugLoggerWrap::initialize(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); bool result = this->instance->initialize(); return Napi::Boolean::New(env, result); } Napi::Value QOpenGLDebugLoggerWrap::loggedMessages(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); const QList<QOpenGLDebugMessage> messages = this->instance->loggedMessages(); QString completeMsg; for (const QOpenGLDebugMessage &message : messages) { QString formattedMessage = QString("%1\t%2\t%3\t%4\t%5\n") .arg(message.id()) .arg(message.severity()) .arg(message.source()) .arg(message.type()) .arg(message.message()); completeMsg.append(formattedMessage); } return Napi::String::New(env, completeMsg.toStdString()); } Napi::Value QOpenGLDebugLoggerWrap::logMessage(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); QString text = QString::fromStdString(info[0].As<Napi::String>().Utf8Value()); auto severity = static_cast<QOpenGLDebugMessage::Severity>(info[1].As<Napi::Number>().Uint32Value()); auto type = static_cast<QOpenGLDebugMessage::Type>(info[2].As<Napi::Number>().Uint32Value()); GLuint id = info[3].As<Napi::Number>().Uint32Value(); QOpenGLDebugMessage debugMessage = QOpenGLDebugMessage::createApplicationMessage(text, id, severity, type); this->instance->logMessage(debugMessage); return env.Null(); }
35.5
109
0.718981
sedwards2009
0f98e0aabf43de25086855fac9e255c494a1a273
447
cpp
C++
AquaEngine/Core/Allocators/LinearAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
55
2015-05-29T20:19:28.000Z
2022-01-18T21:23:15.000Z
AquaEngine/Core/Allocators/LinearAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
null
null
null
AquaEngine/Core/Allocators/LinearAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
6
2015-09-02T09:51:38.000Z
2020-08-16T07:54:34.000Z
#include "LinearAllocator.h" #include "..\..\Utilities\Debug.h" using namespace aqua; LinearAllocator::LinearAllocator(size_t size, void* start) : Allocator(size), _start(start), _current_pos(start) { } void LinearAllocator::deallocate(void* p) { //ASSERT("Cannot call deallocate on Linear Allocators" && false); } void* LinearAllocator::getStart() const { return _start; } void* LinearAllocator::getMark() const { return _current_pos; }
17.88
66
0.736018
tiagovcosta
0fa2764d7cfce470f37da26e1545996dfe8b260d
7,906
cpp
C++
importfbx/parsemisc.cpp
walbourn/contentexporter
2559ac92bbb1ce1409f1c63b51957ea088427b24
[ "MIT" ]
62
2015-04-14T22:28:11.000Z
2022-03-28T07:02:28.000Z
importfbx/parsemisc.cpp
TienAska/contentexporter
746cf69136b63b0502e9e6e8687ed66b5a268103
[ "MIT" ]
18
2015-07-01T18:29:14.000Z
2021-11-13T12:28:08.000Z
importfbx/parsemisc.cpp
TienAska/contentexporter
746cf69136b63b0502e9e6e8687ed66b5a268103
[ "MIT" ]
21
2015-05-31T07:57:37.000Z
2021-07-30T10:20:06.000Z
//------------------------------------------------------------------------------------- // ParseMisc.cpp // // Advanced Technology Group (ATG) // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=226208 //------------------------------------------------------------------------------------- #include "StdAfx.h" #include "ParseMisc.h" #include "ParseMesh.h" using namespace ATG; using namespace DirectX; extern ATG::ExportScene* g_pScene; static XMMATRIX ConvertMatrix(const FbxMatrix& matFbx) { XMFLOAT4X4 matConverted = {}; auto pFloats = reinterpret_cast<float*>(&matConverted); auto pDoubles = reinterpret_cast<const DOUBLE*>(matFbx.mData); for (DWORD i = 0; i < 16; ++i) { pFloats[i] = (float)pDoubles[i]; } return XMLoadFloat4x4(&matConverted); } inline bool IsEqual(float A, float B) { return fabs(A - B) <= 1e-5f; } XMMATRIX ParseTransform(FbxNode* pNode, ExportFrame* pFrame, CXMMATRIX matParentWorld, const bool bWarnings = true) { XMMATRIX matWorld = {}; XMMATRIX matLocal = {}; bool bProcessDefaultTransform = true; if (!g_BindPoseMap.empty()) { PoseMap::iterator iter = g_BindPoseMap.find(pNode); if (iter != g_BindPoseMap.end()) { FbxMatrix PoseMatrix = iter->second; matWorld = ConvertMatrix(PoseMatrix); const XMMATRIX matInvParentWorld = XMMatrixInverse(nullptr, matParentWorld); matLocal = XMMatrixMultiply(matWorld, matInvParentWorld); bProcessDefaultTransform = false; } } if (bProcessDefaultTransform) { FbxVector4 Translation; if (pNode->LclTranslation.IsValid()) Translation = pNode->LclTranslation.Get(); FbxVector4 Rotation; if (pNode->LclRotation.IsValid()) Rotation = pNode->LclRotation.Get(); FbxVector4 Scale; if (pNode->LclScaling.IsValid()) Scale = pNode->LclScaling.Get(); FbxMatrix matTransform(Translation, Rotation, Scale); matLocal = ConvertMatrix(matTransform); matWorld = XMMatrixMultiply(matParentWorld, matLocal); } pFrame->Transform().Initialize(matLocal); const XMFLOAT3& Scale = pFrame->Transform().Scale(); if (bWarnings && (!IsEqual(Scale.x, Scale.y) || !IsEqual(Scale.y, Scale.z) || !IsEqual(Scale.x, Scale.z))) { ExportLog::LogWarning("Non-uniform scale found on node \"%s\".", pFrame->GetName().SafeString()); } const ExportTransform& Transform = pFrame->Transform(); ExportLog::LogMsg(5, "Node transform for \"%s\": Translation <%0.3f %0.3f %0.3f> Rotation <%0.3f %0.3f %0.3f %0.3f> Scale <%0.3f %0.3f %0.3f>", pFrame->GetName().SafeString(), Transform.Position().x, Transform.Position().y, Transform.Position().z, Transform.Orientation().x, Transform.Orientation().y, Transform.Orientation().z, Transform.Orientation().w, Transform.Scale().x, Transform.Scale().y, Transform.Scale().z); return matWorld; } void ParseNode(FbxNode* pNode, ExportFrame* pParentFrame, CXMMATRIX matParentWorld) { ExportLog::LogMsg(2, "Parsing node \"%s\".", pNode->GetName()); auto pFrame = new ExportFrame(pNode->GetName()); pFrame->SetDCCObject(pNode); const XMMATRIX matWorld = ParseTransform(pNode, pFrame, matParentWorld); pParentFrame->AddChild(pFrame); if (pNode->GetSubdiv()) { ParseSubDiv(pNode, pNode->GetSubdiv(), pFrame); } else if (pNode->GetMesh()) { ParseMesh(pNode, pNode->GetMesh(), pFrame, false); } ParseCamera(pNode->GetCamera(), pFrame); ParseLight(pNode->GetLight(), pFrame); const DWORD dwChildCount = pNode->GetChildCount(); for (DWORD i = 0; i < dwChildCount; ++i) { ParseNode(pNode->GetChild(i), pFrame, matWorld); } } void FixupNode(ExportFrame* pFrame, CXMMATRIX matParentWorld) { auto pNode = static_cast<FbxNode*>(pFrame->GetDCCObject()); XMMATRIX matWorld = {}; if (pNode) { ExportLog::LogMsg(4, "Fixing up frame \"%s\".", pFrame->GetName().SafeString()); matWorld = ParseTransform(pNode, pFrame, matParentWorld, false); } else { matWorld = matParentWorld; } const size_t dwChildCount = pFrame->GetChildCount(); for (size_t i = 0; i < dwChildCount; ++i) { FixupNode(pFrame->GetChildByIndex(i), matWorld); } } void ParseCamera(FbxCamera* pFbxCamera, ExportFrame* pParentFrame) { if (!pFbxCamera || !g_pScene->Settings().bExportCameras) return; ExportLog::LogMsg(2, "Parsing camera \"%s\".", pFbxCamera->GetName()); ExportCamera* pCamera = new ExportCamera(pFbxCamera->GetName()); pCamera->SetDCCObject(pFbxCamera); pCamera->fNearClip = (float)pFbxCamera->NearPlane.Get(); pCamera->fFarClip = (float)pFbxCamera->FarPlane.Get(); pCamera->fFieldOfView = (float)pFbxCamera->FieldOfView.Get(); pCamera->fFocalLength = (float)pFbxCamera->FocalLength.Get(); pParentFrame->AddCamera(pCamera); } void ParseLight(FbxLight* pFbxLight, ExportFrame* pParentFrame) { if (!pFbxLight || !g_pScene->Settings().bExportLights) return; ExportLog::LogMsg(2, "Parsing light \"%s\".", pFbxLight->GetName()); switch (pFbxLight->LightType.Get()) { case FbxLight::ePoint: case FbxLight::eSpot: case FbxLight::eDirectional: break; case FbxLight::eArea: case FbxLight::eVolume: ExportLog::LogWarning("Ignores area and volume lights"); return; default: ExportLog::LogWarning("Could not determine light type, ignored."); return; } ExportLight* pLight = new ExportLight(pFbxLight->GetName()); pLight->SetDCCObject(pFbxLight); pParentFrame->AddLight(pLight); auto colorRGB = pFbxLight->Color.Get(); float fIntensity = (float)pFbxLight->Intensity.Get(); fIntensity *= 0.01f; const XMFLOAT4 Color((float)colorRGB[0] * fIntensity, (float)colorRGB[1] * fIntensity, (float)colorRGB[2] * fIntensity, 1.0f); pLight->Color = Color; switch (pFbxLight->DecayType.Get()) { case FbxLight::eNone: pLight->Falloff = ExportLight::LF_NONE; pLight->fRange = 20.0f; break; case FbxLight::eLinear: pLight->Falloff = ExportLight::LF_LINEAR; pLight->fRange = 4.0f * fIntensity; break; case FbxLight::eQuadratic: case FbxLight::eCubic: pLight->Falloff = ExportLight::LF_SQUARED; pLight->fRange = 2.0f * sqrtf(fIntensity); break; default: ExportLog::LogWarning("Could not determine light decay type, using None"); pLight->Falloff = ExportLight::LF_NONE; pLight->fRange = 20.0f; break; } pLight->fRange *= g_pScene->Settings().fLightRangeScale; ExportLog::LogMsg(4, "Light color (multiplied by intensity): <%0.2f %0.2f %0.2f> intensity: %0.2f falloff: %0.2f", Color.x, Color.y, Color.z, fIntensity, pLight->fRange); switch (pFbxLight->LightType.Get()) { case FbxLight::ePoint: pLight->Type = ExportLight::LT_POINT; break; case FbxLight::eSpot: pLight->Type = ExportLight::LT_SPOT; pLight->fOuterAngle = (float)pFbxLight->OuterAngle.Get(); pLight->fInnerAngle = (float)pFbxLight->InnerAngle.Get(); pLight->SpotFalloff = pLight->Falloff; break; case FbxLight::eDirectional: pLight->Type = ExportLight::LT_DIRECTIONAL; break; } }
31.373016
175
0.603466
walbourn
0fa295a15444e8946f867d13102491eebb6b6a72
11,887
hpp
C++
ClassPath/include/File/ScanFolder.hpp
X-Ryl669/Frost
5eefa4d4d73ecb0985389bc142609221047b0e6b
[ "MIT" ]
24
2015-03-23T19:16:56.000Z
2022-02-02T01:55:55.000Z
ClassPath/include/File/ScanFolder.hpp
X-Ryl669/Frost
5eefa4d4d73ecb0985389bc142609221047b0e6b
[ "MIT" ]
12
2015-03-22T03:49:01.000Z
2019-04-10T08:08:54.000Z
ClassPath/include/File/ScanFolder.hpp
X-Ryl669/Frost
5eefa4d4d73ecb0985389bc142609221047b0e6b
[ "MIT" ]
2
2016-03-14T08:09:38.000Z
2020-08-07T11:40:23.000Z
#include "File.hpp" #include "../Container/FIFO.hpp" #include "../Strings/Strings.hpp" namespace File { /** This is useful to scan a directory recursively (or not), applying a filter on the file names to select */ class Scanner { public: /** The string class we use */ typedef Strings::FastString String; /** A file filter check if the given file name match the filter set This example here, simply match the file extension. */ class FileFilter { // Members protected: /** The file pattern to match */ const String filePattern; /** The found count */ mutable uint32 found; // Interface public: void Reset() { found = 0; } /** Check if the file extension match our filter */ virtual bool matchFile(const String & fileName) const { bool match = (filePattern == fileName.midString(fileName.getLength() - filePattern.getLength(), filePattern.getLength())); found += match; return match; } FileFilter() : filePattern(""), found(0) {} FileFilter(const String & pattern) : filePattern(pattern), found(0) {} virtual ~FileFilter() {} }; /** The file filter array */ typedef Container::NotConstructible<FileFilter>::IndexList FileFilters; /** When using the low-level system, you can provide your own EntryFound structure that'll be called each time a new entry is found in the folder scanning process. @sa DefaultEntryIterator */ struct EntryIterator { /** Called to extract the next file in the given directory. @return false when no more file of interest in the given directory. */ virtual bool getNextFile(File::DirectoryIterator & dir, File::Info & file, const String & name) = 0; virtual ~EntryIterator() {} /** The entry iterator */ EntryIterator(const bool recursive) : recursive(recursive) {} /** Set to true in case the iterator should recurse into directories */ const bool recursive; }; /** The default implementation: - ignores hidden files and parent directory - ignores symbolic link for directories (since there is no way to figure out if they lead out of the initial path) - applies file filter on the file name to select a file for inclusion in the final list */ class DefaultEntryIterator : public EntryIterator { FileFilters & filters; public: /** Called to fetch information about files in directory */ virtual bool getFileInfo(File::DirectoryIterator & dir, File::Info & file) { return dir.getNextFile(file); } /** Called to extract the next file in the given directory. @return false when no more file of interest in the given directory. */ virtual bool getNextFile(File::DirectoryIterator & dir, File::Info & file, const String & name) { while (getFileInfo(dir, file)) { if (file.name[0] == '.') continue; // Ignore hidden files and parent/current directory if (recursive && file.isDir() && !file.isLink()) return true; for (uint32 i = 0; i < filters.getSize(); i++) { const FileFilter & filter = filters[i]; if (filter.matchFile(file.name)) return true; } } return false; } /** We need the filters and recursive information to figure out what to do next */ DefaultEntryIterator(FileFilters & filters, const bool recursive) : EntryIterator(recursive), filters(filters) {} }; /** The filename only implementation: - ignores hidden files and parent directory - ignores symbolic link for directories (since there is no way to figure out if they lead out of the initial path) - applies file filter on the file name to select a file for inclusion in the final list */ struct FileNameOnlyIterator : public DefaultEntryIterator { public: /** Called to fetch information about files in directory */ bool getFileInfo(File::DirectoryIterator & dir, File::Info & file) { return dir.getNextFilePath(file); } /** We need the filters and recursive information to figure out what to do next */ FileNameOnlyIterator(FileFilters & filters, const bool recursive) : DefaultEntryIterator(filters, recursive) {} }; /** Event based iterator. The given callback is called for each matching file. @warning If you use this class, the scanFolderGeneric function will always return false (since no files are matched anyway), and you must set onlyFile to true (the default) */ class EventIterator : public EntryIterator { // Type definition and enumeration public: /** You need to implement this callback to be notified when a file is found */ struct FileFoundCB { /** This is called each time a file is found. @param info The file that's currently iterated upon @param strippedFilePath The file path that was stripped from the given mount point @return false to stop iterating */ virtual bool fileFound(File::Info & info, const String & strippedFilePath) = 0; virtual ~FileFoundCB() {} }; private: /** Set to true when the iteration is finished */ bool finished; /** The callback to call */ FileFoundCB & callback; public: /** Called to extract the next file in the given directory. @return false when no more file of interest in the given directory. */ virtual bool getNextFile(File::DirectoryIterator & dir, File::Info & file, const String & name) { if (finished) return false; while (dir.getNextFilePath(file)) { if (file.name == "." || file.name == "..") continue; if (!callback.fileFound(file, name + file.name)) { finished = true; return false; } if (recursive && file.isDir() && !file.isLink()) { // Let the scanner feed the directory in the stack of directory to scan return true; } } return false; } /** You need to provide a logical callback that's not owned */ EventIterator(const bool recursive, FileFoundCB & callback) : EntryIterator(recursive), finished(false), callback(callback) {} }; /** The basic engine. This scans the files hierarchy in a depth last manner, that is for a folder structure like this: @verbatim root |--- file1 |--- subDir1 | |--- file2 |--- file3 @endverbatim will be filled/called in the following order: @verbatim root, file1, subDir1, file3, file2 @endverbatim */ static bool scanFolderGeneric(String mountPath, const String & path, File::FileItemArray & array, EntryIterator & iterator, const bool onlyFiles = true) { Stack::WithClone::FIFO<File::FileItem> dirs; array.Clear(); File::FileItem * item = 0; dirs.Push(new File::FileItem(File::General::normalizePath(path), 0, File::Info::Directory)); mountPath = mountPath.normalizedPath(Platform::Separator); bool foundOne = false; while ((item = dirs.Pop())) { const String & name = item->name; if (!onlyFiles) array.Append(new File::FileItem(name, item->level + 1, File::Info::Directory)); File::DirectoryIterator dir = File::General::listFilesIn(mountPath + name); File::Info file; while (iterator.getNextFile(dir, file, name)) { // Ignore hidden files and directories if (file.isDir()) { if (iterator.recursive) dirs.Push(new File::FileItem(name + file.name + (char)Platform::Separator, item->level + 1, File::Info::Directory)); } else if (!file.isDir() || !onlyFiles) { foundOne = true; array.Append(new File::FileItem(name + file.name, item->level + 1, file.type, file.size, (uint32)file.modification)); } } delete item; } return foundOne; } /** Analyze the files in the given path and store the path of the files matching the given filter in array @param mountPath The mount point path (the file scanned have their path stripped from this mount point path, so if the mount point path change, the path doesn't) @param path The initial directory path to scan @param array On output, contains the matching files @param filters The file filters to match against @param recursive When true, the folder is search recursively @param onlyFiles When set, only the files are returned, and not the directories @return true if at least a file was found */ static bool scanFolder(const String & mountPath, const String & path, File::FileItemArray & array, FileFilters & filters, const bool recursive = false, const bool onlyFiles = true) { DefaultEntryIterator iterator(filters, recursive); return scanFolderGeneric(mountPath, path, array, iterator, onlyFiles); } /** Analyze the files in the given path and store the path of the files matching the given filter in array @warning This version doesn't try to stat the files found (so it doesn't fill the file size and modifications time information), but is preferable for folders with tens of thousands of files (it's faster in that case). @param mountPath The mount point path (the file scanned have their path stripped from this mount point path, so if the mount point path change, the path doesn't) @param path The initial directory path to scan @param array On output, contains the matching files @param filters The file filters to match against @param recursive When true, the folder is search recursively @param onlyFiles When set, only the files are returned, and not the directories @return true if at least a file was found */ static bool scanFolderFilename(const String & mountPath, const String & path, File::FileItemArray & array, FileFilters & filters, const bool recursive = false, const bool onlyFiles = true) { FileNameOnlyIterator iterator(filters, recursive); return scanFolderGeneric(mountPath, path, array, iterator, onlyFiles); } }; }
49.945378
196
0.567847
X-Ryl669
0fa7b3e03494a613e1130226b083f666316cc8a7
702
cc
C++
seminar2/class-exercise-1.cc
holmgr/tddd38
c9230a227c8c2813345250df9b2aa86b32d682bf
[ "MIT" ]
null
null
null
seminar2/class-exercise-1.cc
holmgr/tddd38
c9230a227c8c2813345250df9b2aa86b32d682bf
[ "MIT" ]
null
null
null
seminar2/class-exercise-1.cc
holmgr/tddd38
c9230a227c8c2813345250df9b2aa86b32d682bf
[ "MIT" ]
null
null
null
#include <iostream> class Integer { public: Integer (int i): i_(i) {} operator int() const { return i_; } private: int i_; }; struct Ten { operator Integer() const { return Integer(10); } }; int main() { Integer i(10); // Constructor Integer(int) is supposed to be defined const char* hex = "0123456789ABCDEF"; char d = hex[i]; std::cout << d << std::endl; Ten ten {}; //Cannot do double implicit conversion // d = hex[ten]; // Single explicit conversion, single implicit d = hex[ten.operator Integer()]; // Double explicit conversion d = hex[ten.operator Integer().operator int()]; std::cout << d << std::endl; return 0; }
18
72
0.60114
holmgr
0fad8d142950f0bcf6e27fc76dadd26b2dbede9d
617
hpp
C++
waterbox/ares64/ares/nall/counting-sort.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
waterbox/ares64/ares/nall/counting-sort.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
296
2021-10-16T18:00:18.000Z
2022-03-31T12:09:00.000Z
waterbox/ares64/ares/nall/counting-sort.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once #include <nall/range.hpp> namespace nall { //counting sort by powers of two: used to implement radix sort template<u32 Bits, u32 Shift, typename T> auto counting_sort(T* output, const T* input, u32 size) -> void { static_assert(Bits >= 1 && Bits <= 20, "must be between 1 and 20 bits"); enum : u32 { Base = 1 << Bits, Mask = Base - 1 }; u64 count[Base] = {}, last = 0; for(u32 n : range(size)) ++count[(input[n] >> Shift) & Mask]; for(u32 n : range(Base)) last += count[n], count[n] = last - count[n]; for(u32 n : range(size)) output[count[(input[n] >> Shift) & Mask]++] = input[n]; } }
30.85
82
0.622366
Fortranm
0fae446ad8dd5f53be083ed1997bef6652db4c27
4,082
cpp
C++
tests/PinnedImageTest.cpp
liguisheng/skia
817dab18b4a3005530f4e567cc12b0d37100c670
[ "BSD-3-Clause" ]
3
2019-10-14T06:36:32.000Z
2021-02-20T10:55:14.000Z
tests/PinnedImageTest.cpp
liguisheng/skia
817dab18b4a3005530f4e567cc12b0d37100c670
[ "BSD-3-Clause" ]
null
null
null
tests/PinnedImageTest.cpp
liguisheng/skia
817dab18b4a3005530f4e567cc12b0d37100c670
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. #include "tests/Test.h" using namespace sk_gpu_test; #include "tools/gpu/GrContextFactory.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkSurface.h" #include "include/gpu/GrDirectContext.h" #include "src/core/SkImagePriv.h" static bool surface_is_expected_color(SkSurface* surf, const SkImageInfo& ii, SkColor color) { SkBitmap bm; bm.allocPixels(ii); surf->readPixels(bm, 0, 0); for (int y = 0; y < bm.height(); ++y) { for (int x = 0; x < bm.width(); ++x) { if (bm.getColor(x, y) != color) { return false; } } } return true; } static void basic_test(skiatest::Reporter* reporter, GrRecordingContext* rContext) { const SkImageInfo ii = SkImageInfo::Make(64, 64, kN32_SkColorType, kPremul_SkAlphaType); SkBitmap bm; bm.allocPixels(ii); SkCanvas bmCanvas(bm); bmCanvas.clear(SK_ColorRED); // We start off with the raster image being all red. sk_sp<SkImage> img = SkMakeImageFromRasterBitmap(bm, kNever_SkCopyPixelsMode); sk_sp<SkSurface> gpuSurface = SkSurface::MakeRenderTarget(rContext, SkBudgeted::kYes, ii); SkCanvas* canvas = gpuSurface->getCanvas(); // w/o pinning - the gpu draw always reflects the current state of the underlying bitmap { canvas->drawImage(img, 0, 0); REPORTER_ASSERT(reporter, surface_is_expected_color(gpuSurface.get(), ii, SK_ColorRED)); bmCanvas.clear(SK_ColorGREEN); canvas->drawImage(img, 0, 0); REPORTER_ASSERT(reporter, surface_is_expected_color(gpuSurface.get(), ii, SK_ColorGREEN)); } // w/ pinning - the gpu draw is stuck at the pinned state { SkImage_pinAsTexture(img.get(), rContext); // pin at blue canvas->drawImage(img, 0, 0); REPORTER_ASSERT(reporter, surface_is_expected_color(gpuSurface.get(), ii, SK_ColorGREEN)); bmCanvas.clear(SK_ColorBLUE); canvas->drawImage(img, 0, 0); REPORTER_ASSERT(reporter, surface_is_expected_color(gpuSurface.get(), ii, SK_ColorGREEN)); SkImage_unpinAsTexture(img.get(), rContext); } // once unpinned local changes will be picked up { canvas->drawImage(img, 0, 0); REPORTER_ASSERT(reporter, surface_is_expected_color(gpuSurface.get(), ii, SK_ColorBLUE)); } } // Deleting the context while there are still pinned images shouldn't result in a crash. static void cleanup_test(skiatest::Reporter* reporter) { const SkImageInfo ii = SkImageInfo::Make(64, 64, kN32_SkColorType, kPremul_SkAlphaType); SkBitmap bm; bm.allocPixels(ii); SkCanvas bmCanvas(bm); bmCanvas.clear(SK_ColorRED); for (int i = 0; i < GrContextFactory::kContextTypeCnt; ++i) { GrContextFactory::ContextType ctxType = (GrContextFactory::ContextType) i; { sk_sp<SkImage> img; GrDirectContext* dContext = nullptr; { GrContextFactory testFactory; ContextInfo info = testFactory.getContextInfo(ctxType); dContext = info.directContext(); if (!dContext) { continue; } img = SkMakeImageFromRasterBitmap(bm, kNever_SkCopyPixelsMode); if (!SkImage_pinAsTexture(img.get(), dContext)) { continue; } } // The context used to pin the image is gone at this point! // "context" isn't technically used in this call but it can't be null! // We don't really want to support this use case but it currently happens. SkImage_unpinAsTexture(img.get(), dContext); } } } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(PinnedImageTest, reporter, ctxInfo) { basic_test(reporter, ctxInfo.directContext()); cleanup_test(reporter); }
31.160305
98
0.647722
liguisheng
0fb1d8e993c55936e1db43daab9808934a841a87
11,756
cpp
C++
libutils/BlobCache.cpp
fling2/platform_system_core
97aaad7e316d78a4614b7536b4c4f622329c9349
[ "MIT" ]
39
2015-02-22T12:57:10.000Z
2022-03-30T03:43:34.000Z
libutils/BlobCache.cpp
fling2/platform_system_core
97aaad7e316d78a4614b7536b4c4f622329c9349
[ "MIT" ]
4
2015-10-04T00:43:51.000Z
2021-05-06T20:59:47.000Z
libutils/BlobCache.cpp
fling2/platform_system_core
97aaad7e316d78a4614b7536b4c4f622329c9349
[ "MIT" ]
23
2015-01-29T12:19:33.000Z
2022-02-26T15:39:14.000Z
/* ** Copyright 2011, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #define LOG_TAG "BlobCache" //#define LOG_NDEBUG 0 #include <stdlib.h> #include <string.h> #include <utils/BlobCache.h> #include <utils/Errors.h> #include <utils/Log.h> namespace android { // BlobCache::Header::mMagicNumber value static const uint32_t blobCacheMagic = '_Bb$'; // BlobCache::Header::mBlobCacheVersion value static const uint32_t blobCacheVersion = 1; // BlobCache::Header::mDeviceVersion value static const uint32_t blobCacheDeviceVersion = 1; BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize): mMaxKeySize(maxKeySize), mMaxValueSize(maxValueSize), mMaxTotalSize(maxTotalSize), mTotalSize(0) { nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); #ifdef _WIN32 srand(now); #else mRandState[0] = (now >> 0) & 0xFFFF; mRandState[1] = (now >> 16) & 0xFFFF; mRandState[2] = (now >> 32) & 0xFFFF; #endif ALOGV("initializing random seed using %lld", now); } void BlobCache::set(const void* key, size_t keySize, const void* value, size_t valueSize) { if (mMaxKeySize < keySize) { ALOGV("set: not caching because the key is too large: %d (limit: %d)", keySize, mMaxKeySize); return; } if (mMaxValueSize < valueSize) { ALOGV("set: not caching because the value is too large: %d (limit: %d)", valueSize, mMaxValueSize); return; } if (mMaxTotalSize < keySize + valueSize) { ALOGV("set: not caching because the combined key/value size is too " "large: %d (limit: %d)", keySize + valueSize, mMaxTotalSize); return; } if (keySize == 0) { ALOGW("set: not caching because keySize is 0"); return; } if (valueSize <= 0) { ALOGW("set: not caching because valueSize is 0"); return; } sp<Blob> dummyKey(new Blob(key, keySize, false)); CacheEntry dummyEntry(dummyKey, NULL); while (true) { ssize_t index = mCacheEntries.indexOf(dummyEntry); if (index < 0) { // Create a new cache entry. sp<Blob> keyBlob(new Blob(key, keySize, true)); sp<Blob> valueBlob(new Blob(value, valueSize, true)); size_t newTotalSize = mTotalSize + keySize + valueSize; if (mMaxTotalSize < newTotalSize) { if (isCleanable()) { // Clean the cache and try again. clean(); continue; } else { ALOGV("set: not caching new key/value pair because the " "total cache size limit would be exceeded: %d " "(limit: %d)", keySize + valueSize, mMaxTotalSize); break; } } mCacheEntries.add(CacheEntry(keyBlob, valueBlob)); mTotalSize = newTotalSize; ALOGV("set: created new cache entry with %d byte key and %d byte value", keySize, valueSize); } else { // Update the existing cache entry. sp<Blob> valueBlob(new Blob(value, valueSize, true)); sp<Blob> oldValueBlob(mCacheEntries[index].getValue()); size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize(); if (mMaxTotalSize < newTotalSize) { if (isCleanable()) { // Clean the cache and try again. clean(); continue; } else { ALOGV("set: not caching new value because the total cache " "size limit would be exceeded: %d (limit: %d)", keySize + valueSize, mMaxTotalSize); break; } } mCacheEntries.editItemAt(index).setValue(valueBlob); mTotalSize = newTotalSize; ALOGV("set: updated existing cache entry with %d byte key and %d byte " "value", keySize, valueSize); } break; } } size_t BlobCache::get(const void* key, size_t keySize, void* value, size_t valueSize) { if (mMaxKeySize < keySize) { ALOGV("get: not searching because the key is too large: %d (limit %d)", keySize, mMaxKeySize); return 0; } sp<Blob> dummyKey(new Blob(key, keySize, false)); CacheEntry dummyEntry(dummyKey, NULL); ssize_t index = mCacheEntries.indexOf(dummyEntry); if (index < 0) { ALOGV("get: no cache entry found for key of size %d", keySize); return 0; } // The key was found. Return the value if the caller's buffer is large // enough. sp<Blob> valueBlob(mCacheEntries[index].getValue()); size_t valueBlobSize = valueBlob->getSize(); if (valueBlobSize <= valueSize) { ALOGV("get: copying %d bytes to caller's buffer", valueBlobSize); memcpy(value, valueBlob->getData(), valueBlobSize); } else { ALOGV("get: caller's buffer is too small for value: %d (needs %d)", valueSize, valueBlobSize); } return valueBlobSize; } static inline size_t align4(size_t size) { return (size + 3) & ~3; } size_t BlobCache::getFlattenedSize() const { size_t size = sizeof(Header); for (size_t i = 0; i < mCacheEntries.size(); i++) { const CacheEntry& e(mCacheEntries[i]); sp<Blob> keyBlob = e.getKey(); sp<Blob> valueBlob = e.getValue(); size = align4(size); size += sizeof(EntryHeader) + keyBlob->getSize() + valueBlob->getSize(); } return size; } status_t BlobCache::flatten(void* buffer, size_t size) const { // Write the cache header if (size < sizeof(Header)) { ALOGE("flatten: not enough room for cache header"); return BAD_VALUE; } Header* header = reinterpret_cast<Header*>(buffer); header->mMagicNumber = blobCacheMagic; header->mBlobCacheVersion = blobCacheVersion; header->mDeviceVersion = blobCacheDeviceVersion; header->mNumEntries = mCacheEntries.size(); // Write cache entries uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer); off_t byteOffset = align4(sizeof(Header)); for (size_t i = 0; i < mCacheEntries.size(); i++) { const CacheEntry& e(mCacheEntries[i]); sp<Blob> keyBlob = e.getKey(); sp<Blob> valueBlob = e.getValue(); size_t keySize = keyBlob->getSize(); size_t valueSize = valueBlob->getSize(); size_t entrySize = sizeof(EntryHeader) + keySize + valueSize; if (byteOffset + entrySize > size) { ALOGE("flatten: not enough room for cache entries"); return BAD_VALUE; } EntryHeader* eheader = reinterpret_cast<EntryHeader*>( &byteBuffer[byteOffset]); eheader->mKeySize = keySize; eheader->mValueSize = valueSize; memcpy(eheader->mData, keyBlob->getData(), keySize); memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize); byteOffset += align4(entrySize); } return OK; } status_t BlobCache::unflatten(void const* buffer, size_t size) { // All errors should result in the BlobCache being in an empty state. mCacheEntries.clear(); // Read the cache header if (size < sizeof(Header)) { ALOGE("unflatten: not enough room for cache header"); return BAD_VALUE; } const Header* header = reinterpret_cast<const Header*>(buffer); if (header->mMagicNumber != blobCacheMagic) { ALOGE("unflatten: bad magic number: %d", header->mMagicNumber); return BAD_VALUE; } if (header->mBlobCacheVersion != blobCacheVersion || header->mDeviceVersion != blobCacheDeviceVersion) { // We treat version mismatches as an empty cache. return OK; } // Read cache entries const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer); off_t byteOffset = align4(sizeof(Header)); size_t numEntries = header->mNumEntries; for (size_t i = 0; i < numEntries; i++) { if (byteOffset + sizeof(EntryHeader) > size) { mCacheEntries.clear(); ALOGE("unflatten: not enough room for cache entry headers"); return BAD_VALUE; } const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>( &byteBuffer[byteOffset]); size_t keySize = eheader->mKeySize; size_t valueSize = eheader->mValueSize; size_t entrySize = sizeof(EntryHeader) + keySize + valueSize; if (byteOffset + entrySize > size) { mCacheEntries.clear(); ALOGE("unflatten: not enough room for cache entry headers"); return BAD_VALUE; } const uint8_t* data = eheader->mData; set(data, keySize, data + keySize, valueSize); byteOffset += align4(entrySize); } return OK; } long int BlobCache::blob_random() { #ifdef _WIN32 return rand(); #else return nrand48(mRandState); #endif } void BlobCache::clean() { // Remove a random cache entry until the total cache size gets below half // the maximum total cache size. while (mTotalSize > mMaxTotalSize / 2) { size_t i = size_t(blob_random() % (mCacheEntries.size())); const CacheEntry& entry(mCacheEntries[i]); mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize(); mCacheEntries.removeAt(i); } } bool BlobCache::isCleanable() const { return mTotalSize > mMaxTotalSize / 2; } BlobCache::Blob::Blob(const void* data, size_t size, bool copyData): mData(copyData ? malloc(size) : data), mSize(size), mOwnsData(copyData) { if (data != NULL && copyData) { memcpy(const_cast<void*>(mData), data, size); } } BlobCache::Blob::~Blob() { if (mOwnsData) { free(const_cast<void*>(mData)); } } bool BlobCache::Blob::operator<(const Blob& rhs) const { if (mSize == rhs.mSize) { return memcmp(mData, rhs.mData, mSize) < 0; } else { return mSize < rhs.mSize; } } const void* BlobCache::Blob::getData() const { return mData; } size_t BlobCache::Blob::getSize() const { return mSize; } BlobCache::CacheEntry::CacheEntry() { } BlobCache::CacheEntry::CacheEntry(const sp<Blob>& key, const sp<Blob>& value): mKey(key), mValue(value) { } BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce): mKey(ce.mKey), mValue(ce.mValue) { } bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const { return *mKey < *rhs.mKey; } const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) { mKey = rhs.mKey; mValue = rhs.mValue; return *this; } sp<BlobCache::Blob> BlobCache::CacheEntry::getKey() const { return mKey; } sp<BlobCache::Blob> BlobCache::CacheEntry::getValue() const { return mValue; } void BlobCache::CacheEntry::setValue(const sp<Blob>& value) { mValue = value; } } // namespace android
32.385675
86
0.608285
fling2
0fb2197e99e293921d4b08e3f46492fc50e7c17b
2,777
cpp
C++
test/copy_exception_test.cpp
DanielaE/boost.exception
3ae756dd491f179c28e6660dd9625265535afee9
[ "BSL-1.0" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
test/copy_exception_test.cpp
DanielaE/boost.exception
3ae756dd491f179c28e6660dd9625265535afee9
[ "BSL-1.0" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
Libs/boost_1_76_0/libs/exception/test/copy_exception_test.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
50
2015-03-07T15:12:38.000Z
2021-09-28T10:58:32.000Z
//Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/config.hpp> #if defined( BOOST_NO_EXCEPTIONS ) # error This program requires exception handling. #endif #include <boost/exception_ptr.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/thread.hpp> #include <boost/detail/atomic_count.hpp> #include <boost/detail/lightweight_test.hpp> typedef boost::error_info<struct tag_answer,int> answer; int const thread_count = 100; boost::detail::atomic_count exc_count(0); struct err: virtual boost::exception, virtual std::exception { err() { ++exc_count; } err( err const & ) { ++exc_count; } virtual ~err() BOOST_NOEXCEPT_OR_NOTHROW { --exc_count; } private: err & operator=( err const & ); }; class future { public: future(): ready_(false) { } void set_exception( boost::exception_ptr const & e ) { boost::unique_lock<boost::mutex> lck(mux_); exc_ = e; ready_ = true; cond_.notify_all(); } void get_exception() const { boost::unique_lock<boost::mutex> lck(mux_); while( !ready_ ) cond_.wait(lck); rethrow_exception(exc_); } private: bool ready_; boost::exception_ptr exc_; mutable boost::mutex mux_; mutable boost::condition_variable cond_; }; void producer( future & f ) { f.set_exception(boost::copy_exception(err() << answer(42))); } void consumer() { future f; boost::thread thr(boost::bind(&producer, boost::ref(f))); try { f.get_exception(); } catch( err & e ) { int const * ans=boost::get_error_info<answer>(e); BOOST_TEST(ans && *ans==42); } thr.join(); } void consume() { for( int i=0; i!=thread_count; ++i ) consumer(); } void thread_test() { boost::thread_group grp; for( int i=0; i!=thread_count; ++i ) grp.create_thread(&consume); grp.join_all(); } void simple_test() { boost::exception_ptr p = boost::copy_exception(err() << answer(42)); try { rethrow_exception(p); BOOST_TEST(false); } catch( err & ) { } catch( ... ) { BOOST_TEST(false); } } int main() { BOOST_TEST(++exc_count==1); simple_test(); thread_test(); BOOST_TEST(!--exc_count); return boost::report_errors(); }
17.801282
78
0.565358
DanielaE
0fb28a65bbf1cf6f070bfb1fc60da51f25c3cac1
41,296
cpp
C++
src/fit_field.cpp
kuperov/f
9413008e05315f647ace6272b17589f61f50fe5e
[ "MIT" ]
31
2015-04-04T12:05:02.000Z
2021-07-30T11:40:37.000Z
src/fit_field.cpp
kuperov/f
9413008e05315f647ace6272b17589f61f50fe5e
[ "MIT" ]
5
2017-10-25T14:36:34.000Z
2019-12-11T20:07:53.000Z
src/fit_field.cpp
kuperov/f
9413008e05315f647ace6272b17589f61f50fe5e
[ "MIT" ]
22
2016-04-05T09:24:12.000Z
2021-10-01T00:44:41.000Z
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 12.20Release // Tag = $Name$ //////////////////////////////////////////////////////////////////////////////// #include <sstream> #include <cstring> #include "fit_field.hpp" #include "fit_mesg.hpp" #include "fit_unicode.hpp" namespace fit { Field::Field(void) : profile(NULL) { } Field::Field(const Field &field) : profile(field.profile), profileIndex(field.profileIndex), values(field.values) { } Field::Field(const Profile::MESG_INDEX mesgIndex, const FIT_UINT16 fieldIndex) : profile(&Profile::mesgs[mesgIndex]), profileIndex(fieldIndex) { } Field::Field(const FIT_UINT16 mesgNum, const FIT_UINT8 fieldNum) : profile(Profile::GetMesg(mesgNum)), profileIndex(Profile::GetFieldIndex(mesgNum, fieldNum)) { } Field::Field(const std::string& mesgName, const std::string& fieldName) : profile(Profile::GetMesg(mesgName)), profileIndex(Profile::GetFieldIndex(mesgName, fieldName)) { } FIT_BOOL Field::IsValid(void) const { return profileIndex != FIT_UINT16_INVALID; } FIT_UINT16 Field::GetIndex(void) const { return profileIndex; } std::string Field::GetName(const FIT_UINT16 subFieldIndex) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return "unknown"; else if (subFieldIndex >= profile->fields[profileIndex].numSubFields) return profile->fields[profileIndex].name; else return profile->fields[profileIndex].subFields[subFieldIndex].name; } FIT_UINT8 Field::GetNum(void) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return FIT_FIELD_NUM_INVALID; return profile->fields[profileIndex].num; } FIT_UINT8 Field::GetType(const FIT_UINT16 subFieldIndex) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return FIT_UINT8_INVALID; else if (subFieldIndex >= profile->fields[profileIndex].numSubFields) return profile->fields[profileIndex].type; else return profile->fields[profileIndex].subFields[subFieldIndex].type; } FIT_BOOL Field::IsSignedInteger(const FIT_UINT16 subFieldIndex) const { switch (GetType(subFieldIndex)) { case FIT_BASE_TYPE_SINT8: case FIT_BASE_TYPE_SINT16: case FIT_BASE_TYPE_SINT32: return FIT_TRUE; default: return FIT_FALSE; } } std::string Field::GetUnits(const FIT_UINT16 subFieldIndex) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return ""; else if (subFieldIndex >= profile->fields[profileIndex].numSubFields) return profile->fields[profileIndex].units; else return profile->fields[profileIndex].subFields[subFieldIndex].units; } FIT_FLOAT32 Field::GetScale(const FIT_UINT16 subFieldIndex) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return 1; else if (subFieldIndex >= profile->fields[profileIndex].numSubFields) return profile->fields[profileIndex].scale; else return profile->fields[profileIndex].subFields[subFieldIndex].scale; } FIT_FLOAT32 Field::GetOffset(const FIT_UINT16 subFieldIndex) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return 0; else if (subFieldIndex >= profile->fields[profileIndex].numSubFields) return profile->fields[profileIndex].offset; else return profile->fields[profileIndex].subFields[subFieldIndex].offset; } FIT_UINT16 Field::GetNumComponents(void) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return 0; return profile->fields[profileIndex].numComponents; } FIT_UINT16 Field::GetNumSubFields(void) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return 0; return profile->fields[profileIndex].numSubFields; } const Profile::FIELD_COMPONENT* Field::GetComponent(const FIT_UINT16 component) const { if (component >= GetNumComponents()) return NULL; return &profile->fields[profileIndex].components[component]; } const Profile::SUBFIELD* Field::GetSubField(const FIT_UINT16 subFieldIndex) const { if (subFieldIndex >= GetNumSubFields()) return NULL; return &profile->fields[profileIndex].subFields[subFieldIndex]; } FIT_UINT8 Field::GetSize(void) const { FIT_UINT8 size = 0; if ((profile == NULL) || (profileIndex >= profile->numFields)) return 0; for (FIT_UINT8 valueIndex = 0; valueIndex < values.size(); valueIndex++) size += values[valueIndex].size(); return size; } FIT_UINT8 Field::GetNumValues(void) const { if ((profile == NULL) || (profileIndex >= profile->numFields)) return 0; return (FIT_UINT8) values.size(); } FIT_UINT32 Field::GetBitsValue(const FIT_UINT16 offset, const FIT_UINT8 bits) const { FIT_UINT32 value = 0; FIT_UINT8 bitsInValue = 0; FIT_SINT16 bitsInData; FIT_UINT8 index = 0; FIT_UINT8 data; FIT_UINT8 mask; FIT_UINT16 newOffset = offset; if (values.size() == 0) return FIT_UINT32_INVALID; while (bitsInValue < bits) { if (index >= GetSize()) return FIT_UINT32_INVALID; // Get Nth byte from the jagged array considering elements may be multibyte data = GetValuesUINT8(index++); data >>= newOffset; bitsInData = 8 - newOffset; newOffset -= 8; if (bitsInData > 0) { newOffset = 0; if (bitsInData > (bits - bitsInValue)) bitsInData = bits - bitsInValue; mask = (1 << bitsInData) - 1; value |= (FIT_UINT32)(data & mask) << bitsInValue; bitsInValue += bitsInData; } } return value; } FIT_SINT32 Field::GetBitsSignedValue(const FIT_UINT16 offset, const FIT_UINT8 bits) const { FIT_UINT32 value; FIT_SINT32 signedValue; value = GetBitsValue(offset, bits); if (value == FIT_UINT32_INVALID) return FIT_SINT32_INVALID; signedValue = (1L << (bits - 1)); if ((value & signedValue) != 0) // sign bit set signedValue = -signedValue + (value & (signedValue - 1)); else signedValue = value; return signedValue; } FIT_BYTE Field::GetValuesBYTE(FIT_UINT8 index) const { /// Returns the Nth byte of the jagged values array if (index >= GetSize()) { return FIT_BYTE_INVALID; } for (unsigned int i=0; i<values.size(); i++) { if (index < values[i].size()) { return values[i][index]; } else { index -= values[i].size(); } } return FIT_BYTE_INVALID; } FIT_UINT8 Field::GetValuesUINT8(FIT_UINT8 index) const { /// Returns the Nth byte of the jagged values array if (index >= GetSize()) { return FIT_UINT8_INVALID; } for (unsigned int i=0; i<values.size(); i++) { if (index < values[i].size()) { return values[i][index]; } else { index -= values[i].size(); } } return FIT_UINT8_INVALID; } FIT_SINT8 Field::GetValuesSINT8(FIT_UINT8 index) const { /// Returns the Nth byte of the jagged values array if (index >= GetSize()) { return FIT_SINT8_INVALID; } for (unsigned int i=0; i<values.size(); i++) { if (index < values[i].size()) { return values[i][index]; } else { index -= values[i].size(); } } return FIT_SINT8_INVALID; } FIT_ENUM Field::GetENUMValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_ENUM))) return FIT_ENUM_INVALID; return values[fieldArrayIndex][0]; } FIT_BYTE Field::GetBYTEValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_BYTE))) return FIT_BYTE_INVALID; return values[fieldArrayIndex][0]; } FIT_SINT8 Field::GetSINT8Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_SINT8))) return FIT_SINT8_INVALID; return values[fieldArrayIndex][0]; } FIT_UINT8 Field::GetUINT8Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT8))) return FIT_UINT8_INVALID; return values[fieldArrayIndex][0]; } FIT_UINT8Z Field::GetUINT8ZValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT8Z))) return FIT_UINT8Z_INVALID; return values[fieldArrayIndex][0]; } FIT_SINT16 Field::GetSINT16Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_SINT16))) return FIT_SINT16_INVALID; return ((FIT_SINT16) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_UINT16 Field::GetUINT16Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT16))) return FIT_UINT16_INVALID; return ((FIT_UINT16) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_UINT16Z Field::GetUINT16ZValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT16Z))) return FIT_UINT16Z_INVALID; return ((FIT_UINT16Z) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_SINT32 Field::GetSINT32Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_SINT32))) return FIT_SINT32_INVALID; return ((FIT_SINT32) values[fieldArrayIndex][3] << 24) | ((FIT_SINT32) values[fieldArrayIndex][2] << 16) | ((FIT_SINT32) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_UINT32 Field::GetUINT32Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT32))) return FIT_UINT32_INVALID; return ((FIT_UINT32) values[fieldArrayIndex][3] << 24) | ((FIT_UINT32) values[fieldArrayIndex][2] << 16) | ((FIT_UINT32) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_UINT32Z Field::GetUINT32ZValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_UINT32Z))) return FIT_UINT32Z_INVALID; return ((FIT_UINT32Z) values[fieldArrayIndex][3] << 24) | ((FIT_UINT32Z) values[fieldArrayIndex][2] << 16) | ((FIT_UINT32Z) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; } FIT_FLOAT32 Field::GetFLOAT32Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { FIT_FLOAT32 float32Value; if ((profile == NULL) || (profileIndex >= profile->numFields)) return FIT_FLOAT32_INVALID; switch (GetType()) { // Note: This checks the type of the MAIN field since data is aligned according to that type case FIT_BASE_TYPE_BYTE: { FIT_BYTE byteValue = GetBYTEValue(fieldArrayIndex, subFieldIndex); if (byteValue == FIT_BYTE_INVALID) return FIT_FLOAT32_INVALID; float32Value = byteValue; break; } case FIT_BASE_TYPE_ENUM: { FIT_ENUM enumValue = GetENUMValue(fieldArrayIndex, subFieldIndex); if (enumValue == FIT_ENUM_INVALID) return FIT_FLOAT32_INVALID; float32Value = enumValue; break; } case FIT_BASE_TYPE_SINT8: { FIT_SINT8 sint8Value = GetSINT8Value(fieldArrayIndex, subFieldIndex); if (sint8Value == FIT_SINT8_INVALID) return FIT_FLOAT32_INVALID; float32Value = sint8Value; break; } case FIT_BASE_TYPE_UINT8: { FIT_UINT8 uint8Value = GetUINT8Value(fieldArrayIndex, subFieldIndex); if (uint8Value == FIT_UINT8_INVALID) return FIT_FLOAT32_INVALID; float32Value = uint8Value; break; } case FIT_BASE_TYPE_UINT8Z: { FIT_UINT8Z uint8zValue = GetUINT8ZValue(fieldArrayIndex, subFieldIndex); if (uint8zValue == FIT_UINT8Z_INVALID) return FIT_FLOAT32_INVALID; float32Value = uint8zValue; break; } case FIT_BASE_TYPE_SINT16: { FIT_SINT16 sint16Value = GetSINT16Value(fieldArrayIndex, subFieldIndex); if (sint16Value == FIT_SINT16_INVALID) return FIT_FLOAT32_INVALID; float32Value = sint16Value; break; } case FIT_BASE_TYPE_UINT16: { FIT_UINT16 uint16Value = GetUINT16Value(fieldArrayIndex, subFieldIndex); if (uint16Value == FIT_UINT16_INVALID) return FIT_FLOAT32_INVALID; float32Value = uint16Value; break; } case FIT_BASE_TYPE_UINT16Z: { FIT_UINT16Z uint16zValue = GetUINT16ZValue(fieldArrayIndex, subFieldIndex); if (uint16zValue == FIT_UINT16Z_INVALID) return FIT_FLOAT32_INVALID; float32Value = uint16zValue; break; } case FIT_BASE_TYPE_SINT32: { FIT_SINT32 sint32Value = GetSINT32Value(fieldArrayIndex, subFieldIndex); if (sint32Value == FIT_SINT32_INVALID) return FIT_FLOAT32_INVALID; float32Value = (FIT_FLOAT32) sint32Value; break; } case FIT_BASE_TYPE_UINT32: { FIT_UINT32 uint32Value = GetUINT32Value(fieldArrayIndex, subFieldIndex); if (uint32Value == FIT_UINT32_INVALID) return FIT_FLOAT32_INVALID; float32Value = (FIT_FLOAT32) uint32Value; break; } case FIT_BASE_TYPE_UINT32Z: { FIT_UINT32Z uint32zValue = GetUINT32ZValue(fieldArrayIndex, subFieldIndex); if (uint32zValue == FIT_UINT32Z_INVALID) return FIT_FLOAT32_INVALID; float32Value = (FIT_FLOAT32) uint32zValue; break; } case FIT_BASE_TYPE_FLOAT32: { FIT_SINT32 sint32Value = GetSINT32Value(fieldArrayIndex, subFieldIndex); if (sint32Value == FIT_SINT32_INVALID) return FIT_FLOAT32_INVALID; memcpy(&float32Value, &sint32Value, sizeof(FIT_FLOAT32)); break; } case FIT_BASE_TYPE_FLOAT64: return (FIT_FLOAT32) GetFLOAT32Value(fieldArrayIndex, subFieldIndex); break; default: return FIT_FLOAT32_INVALID; } return float32Value / GetScale(subFieldIndex) - GetOffset(subFieldIndex); } FIT_FLOAT64 Field::GetFLOAT64Value(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { FIT_FLOAT64 float64Value; if ((profile == NULL) || (profileIndex >= profile->numFields)) return FIT_FLOAT64_INVALID; switch (GetType()) { // Note: This checks the type of the MAIN field since data is aligned according to that type case FIT_BASE_TYPE_BYTE: { FIT_BYTE byteValue = GetBYTEValue(fieldArrayIndex, subFieldIndex); if (byteValue == FIT_BYTE_INVALID) return FIT_FLOAT64_INVALID; float64Value = byteValue; break; } case FIT_BASE_TYPE_ENUM: { FIT_ENUM enumValue = GetENUMValue(fieldArrayIndex, subFieldIndex); if (enumValue == FIT_ENUM_INVALID) return FIT_FLOAT64_INVALID; float64Value = enumValue; break; } case FIT_BASE_TYPE_SINT8: { FIT_SINT8 sint8Value = GetSINT8Value(fieldArrayIndex, subFieldIndex); if (sint8Value == FIT_SINT8_INVALID) return FIT_FLOAT64_INVALID; float64Value = sint8Value; break; } case FIT_BASE_TYPE_UINT8: { FIT_UINT8 uint8Value = GetUINT8Value(fieldArrayIndex, subFieldIndex); if (uint8Value == FIT_UINT8_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint8Value; break; } case FIT_BASE_TYPE_UINT8Z: { FIT_UINT8Z uint8zValue = GetUINT8ZValue(fieldArrayIndex, subFieldIndex); if (uint8zValue == FIT_UINT8Z_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint8zValue; break; } case FIT_BASE_TYPE_SINT16: { FIT_SINT16 sint16Value = GetSINT16Value(fieldArrayIndex, subFieldIndex); if (sint16Value == FIT_SINT16_INVALID) return FIT_FLOAT64_INVALID; float64Value = sint16Value; break; } case FIT_BASE_TYPE_UINT16: { FIT_UINT16 uint16Value = GetUINT16Value(fieldArrayIndex, subFieldIndex); if (uint16Value == FIT_UINT16_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint16Value; break; } case FIT_BASE_TYPE_UINT16Z: { FIT_UINT16Z uint16zValue = GetUINT16ZValue(fieldArrayIndex, subFieldIndex); if (uint16zValue == FIT_UINT16Z_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint16zValue; break; } case FIT_BASE_TYPE_SINT32: { FIT_SINT32 sint32Value = GetSINT32Value(fieldArrayIndex, subFieldIndex); if (sint32Value == FIT_SINT32_INVALID) return FIT_FLOAT64_INVALID; float64Value = sint32Value; break; } case FIT_BASE_TYPE_UINT32: { FIT_UINT32 uint32Value = GetUINT32Value(fieldArrayIndex, subFieldIndex); if (uint32Value == FIT_UINT32_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint32Value; break; } case FIT_BASE_TYPE_UINT32Z: { FIT_UINT32Z uint32zValue = GetUINT32ZValue(fieldArrayIndex, subFieldIndex); if (uint32zValue == FIT_UINT32Z_INVALID) return FIT_FLOAT64_INVALID; float64Value = uint32zValue; break; } case FIT_BASE_TYPE_FLOAT32: return (FIT_FLOAT64) GetFLOAT32Value(fieldArrayIndex, subFieldIndex); break; case FIT_BASE_TYPE_FLOAT64: { unsigned long long uint64Value; if ((fieldArrayIndex >= values.size()) || (values[fieldArrayIndex].size() < sizeof(FIT_FLOAT64))) return FIT_FLOAT64_INVALID; uint64Value = ((unsigned long long) values[fieldArrayIndex][7] << 56) | ((unsigned long long) values[fieldArrayIndex][6] << 48) | ((unsigned long long) values[fieldArrayIndex][5] << 40) | ((unsigned long long) values[fieldArrayIndex][4] << 32) | ((unsigned long long) values[fieldArrayIndex][3] << 24) | ((unsigned long long) values[fieldArrayIndex][2] << 16) | ((unsigned long long) values[fieldArrayIndex][1] << 8) | values[fieldArrayIndex][0]; memcpy(&float64Value, &uint64Value, sizeof(FIT_FLOAT64)); break; } default: return FIT_FLOAT64_INVALID; } return float64Value / GetScale(subFieldIndex) - GetOffset(subFieldIndex); } FIT_WSTRING Field::GetSTRINGValue(const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) const { Unicode::UTF8_STRING value; if ((profile == NULL) || (profileIndex >= profile->numFields) || (fieldArrayIndex >= values.size())) return FIT_WSTRING_INVALID; if (GetType() == FIT_BASE_TYPE_STRING) // Note: This checks the type of the MAIN field since data is aligned according to that type { FIT_UINT8 i = 0; while ((i < values[fieldArrayIndex].size()) && (values[fieldArrayIndex][i] != 0)) { value += static_cast<Unicode::UTF8_STRING::value_type>(values[fieldArrayIndex][i]); i++; } } else { FIT_FLOAT64 floatValue = GetFLOAT64Value(fieldArrayIndex, subFieldIndex); if (floatValue != FIT_FLOAT64_INVALID) { Unicode::UTF8_OSSTREAM valueStream; valueStream.setf(std::ios_base::fixed); valueStream.precision(9); valueStream << floatValue; value = valueStream.str(); if ((value.find('.') != Unicode::UTF8_STRING::npos) && (value[value.length() - 1] == '0')) { Unicode::UTF8_STRING::size_type lastZeroIndex = value.length() - 1; while (value[lastZeroIndex - 1] == '0') lastZeroIndex--; if (value[lastZeroIndex - 1] == '.') value.erase(lastZeroIndex - 1); else value.erase(lastZeroIndex); } } else { value = ""; } } return Unicode::Encode_UTF8ToBase(value); } void Field::SetENUMValue(const FIT_ENUM value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT8Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetBYTEValue(const FIT_BYTE value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT8Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetSINT8Value(const FIT_SINT8 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT8Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetUINT8Value(const FIT_UINT8 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { while (values.size() <= fieldArrayIndex) { std::vector<FIT_BYTE> newValueBytes; values.push_back(newValueBytes); } values[fieldArrayIndex].clear(); values[fieldArrayIndex].push_back((FIT_BYTE) value); } void Field::SetUINT8ZValue(const FIT_UINT8 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT8Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetSINT16Value(const FIT_SINT16 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT16Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetUINT16Value(const FIT_UINT16 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { while (values.size() <= fieldArrayIndex) { std::vector<FIT_BYTE> newValueBytes; values.push_back(newValueBytes); } values[fieldArrayIndex].clear(); values[fieldArrayIndex].push_back((FIT_BYTE) value); values[fieldArrayIndex].push_back((FIT_BYTE)(value >> 8)); } void Field::SetUINT16ZValue(const FIT_UINT16Z value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT16Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetSINT32Value(const FIT_SINT32 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT32Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetUINT32Value(const FIT_UINT32 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { while (values.size() <= fieldArrayIndex) { std::vector<FIT_BYTE> newValueBytes; values.push_back(newValueBytes); } values[fieldArrayIndex].clear(); values[fieldArrayIndex].push_back((FIT_BYTE) value); values[fieldArrayIndex].push_back((FIT_BYTE)(value >> 8)); values[fieldArrayIndex].push_back((FIT_BYTE)(value >> 16)); values[fieldArrayIndex].push_back((FIT_BYTE)(value >> 24)); } void Field::SetUINT32ZValue(const FIT_UINT32Z value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetUINT32Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetFLOAT32Value(const FIT_FLOAT32 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { SetFLOAT64Value(value, fieldArrayIndex, subFieldIndex); } void Field::SetFLOAT64Value(const FIT_FLOAT64 value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { if ((profile == NULL) || (profileIndex >= profile->numFields)) return; FIT_FLOAT64 recalculatedValue = (value + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); // Make sure floating point representations trunc to the expected integer FIT_FLOAT64 roundedValue = (recalculatedValue >= 0.0) ? (recalculatedValue + 0.5) : (recalculatedValue - 0.5); switch (GetType()) { // Note: This checks the type of the MAIN field since data is aligned according to that type case FIT_BASE_TYPE_BYTE: case FIT_BASE_TYPE_ENUM: case FIT_BASE_TYPE_SINT8: case FIT_BASE_TYPE_UINT8: case FIT_BASE_TYPE_UINT8Z: SetUINT8Value((FIT_UINT8) roundedValue, fieldArrayIndex, subFieldIndex); break; case FIT_BASE_TYPE_SINT16: case FIT_BASE_TYPE_UINT16: case FIT_BASE_TYPE_UINT16Z: SetUINT16Value((FIT_UINT16) roundedValue, fieldArrayIndex, subFieldIndex); break; case FIT_BASE_TYPE_SINT32: case FIT_BASE_TYPE_UINT32: case FIT_BASE_TYPE_UINT32Z: SetUINT32Value((FIT_UINT32) roundedValue, fieldArrayIndex, subFieldIndex); break; case FIT_BASE_TYPE_FLOAT32: { FIT_FLOAT32 float32Value = (FIT_FLOAT32)recalculatedValue; FIT_UINT32 uint32Value; memcpy(&uint32Value, &float32Value, sizeof(FIT_FLOAT32)); SetUINT32Value(uint32Value, fieldArrayIndex, subFieldIndex); break; } case FIT_BASE_TYPE_FLOAT64: while (values.size() <= fieldArrayIndex) { std::vector<FIT_BYTE> newValueBytes; values.push_back(newValueBytes); } values[fieldArrayIndex].clear(); values[fieldArrayIndex].push_back(*((FIT_BYTE *) &recalculatedValue)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 1)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 2)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 3)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 4)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 5)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 6)); values[fieldArrayIndex].push_back(*(((FIT_BYTE *) &recalculatedValue) + 7)); break; default: break; } } void Field::SetSTRINGValue(const FIT_WSTRING& value, const FIT_UINT8 fieldArrayIndex, const FIT_UINT16 subFieldIndex) { if ((profile == NULL) || (profileIndex >= profile->numFields)) return; while (values.size() <= fieldArrayIndex) { std::vector<FIT_BYTE> newValueBytes; values.push_back(newValueBytes); } Unicode::UTF8_STRING stringValue = Unicode::Encode_BaseToUTF8(value); switch (GetType()) { // Note: This checks the type of the MAIN field since data is aligned according to that type case FIT_BASE_TYPE_STRING: values[fieldArrayIndex].clear(); for (int i = 0; i < (int) stringValue.length(); i++) values[fieldArrayIndex].push_back(static_cast<FIT_BYTE>(stringValue[i])); values[fieldArrayIndex].push_back(0); // null terminate break; case FIT_BASE_TYPE_BYTE: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 byteValueAsFloat64; ss << stringValue; ss >> byteValueAsFloat64; if (ss.fail()) { SetBYTEValue(FIT_BYTE_INVALID, fieldArrayIndex, subFieldIndex); } else { byteValueAsFloat64 = (byteValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); byteValueAsFloat64 += ((byteValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetBYTEValue(static_cast<FIT_BYTE>(byteValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_ENUM: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 enumValueAsFloat64; ss << stringValue; ss >> enumValueAsFloat64; if (ss.fail()) { SetENUMValue(FIT_ENUM_INVALID, fieldArrayIndex, subFieldIndex); } else { enumValueAsFloat64 = (enumValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); enumValueAsFloat64 += ((enumValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetENUMValue(static_cast<FIT_ENUM>(enumValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_SINT8: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 sint8ValueAsFloat64; ss << stringValue; ss >> sint8ValueAsFloat64; if (ss.fail()) { SetSINT8Value(FIT_SINT8_INVALID, fieldArrayIndex, subFieldIndex); } else { sint8ValueAsFloat64 = (sint8ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); sint8ValueAsFloat64 += ((sint8ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetSINT8Value(static_cast<FIT_SINT8>(sint8ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT8: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint8ValueAsFloat64; ss << stringValue; ss >> uint8ValueAsFloat64; if (ss.fail()) { SetUINT8Value(FIT_UINT8_INVALID, fieldArrayIndex, subFieldIndex); } else { uint8ValueAsFloat64 = (uint8ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint8ValueAsFloat64 += ((uint8ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT8Value(static_cast<FIT_UINT8>(uint8ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT8Z: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint8zValueAsFloat64; ss << stringValue; ss >> uint8zValueAsFloat64; if (ss.fail()) { SetUINT8ZValue(FIT_UINT8Z_INVALID, fieldArrayIndex, subFieldIndex); } else { uint8zValueAsFloat64 = (uint8zValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint8zValueAsFloat64 += ((uint8zValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT8ZValue(static_cast<FIT_UINT8Z>(uint8zValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_SINT16: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 sint16ValueAsFloat64; ss << stringValue; ss >> sint16ValueAsFloat64; if (ss.fail()) { SetSINT16Value(FIT_SINT16_INVALID, fieldArrayIndex, subFieldIndex); } else { sint16ValueAsFloat64 = (sint16ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); sint16ValueAsFloat64 += ((sint16ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetSINT16Value(static_cast<FIT_SINT16>(sint16ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT16: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint16ValueAsFloat64; ss << stringValue; ss >> uint16ValueAsFloat64; if (ss.fail()) { SetUINT16Value(FIT_UINT16_INVALID, fieldArrayIndex, subFieldIndex); } else { uint16ValueAsFloat64 = (uint16ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint16ValueAsFloat64 += ((uint16ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT16Value(static_cast<FIT_UINT16>(uint16ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT16Z: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint16zValueAsFloat64; ss << stringValue; ss >> uint16zValueAsFloat64; if (ss.fail()) { SetUINT16ZValue(FIT_UINT16Z_INVALID, fieldArrayIndex, subFieldIndex); } else { uint16zValueAsFloat64 = (uint16zValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint16zValueAsFloat64 += ((uint16zValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT16ZValue(static_cast<FIT_UINT16Z>(uint16zValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_SINT32: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 sint32ValueAsFloat64; ss << stringValue; ss >> sint32ValueAsFloat64; if (ss.fail()) { SetSINT32Value(FIT_SINT32_INVALID, fieldArrayIndex, subFieldIndex); } else { sint32ValueAsFloat64 = (sint32ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); sint32ValueAsFloat64 += ((sint32ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetSINT32Value(static_cast<FIT_SINT32>(sint32ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT32: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint32ValueAsFloat64; ss << stringValue; ss >> uint32ValueAsFloat64; if (ss.fail()) { SetUINT32Value(FIT_UINT32_INVALID, fieldArrayIndex, subFieldIndex); } else { uint32ValueAsFloat64 = (uint32ValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint32ValueAsFloat64 += ((uint32ValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT32Value(static_cast<FIT_UINT32>(uint32ValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_UINT32Z: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 uint32zValueAsFloat64; ss << stringValue; ss >> uint32zValueAsFloat64; if (ss.fail()) { SetUINT32ZValue(FIT_UINT32Z_INVALID, fieldArrayIndex, subFieldIndex); } else { uint32zValueAsFloat64 = (uint32zValueAsFloat64 + GetOffset(subFieldIndex)) * GetScale(subFieldIndex); uint32zValueAsFloat64 += ((uint32zValueAsFloat64 >= 0.0) ? (0.5) : (-0.5)); SetUINT32ZValue(static_cast<FIT_UINT32Z>(uint32zValueAsFloat64), fieldArrayIndex, subFieldIndex); } break; } case FIT_BASE_TYPE_FLOAT32: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT32 float32Value; ss << stringValue; ss >> float32Value; if (ss.fail()) { SetFLOAT32Value(FIT_FLOAT32_INVALID, fieldArrayIndex, subFieldIndex); } else { SetFLOAT32Value(float32Value, fieldArrayIndex, subFieldIndex); } break; } break; case FIT_BASE_TYPE_FLOAT64: { Unicode::UTF8_SSTREAM ss; FIT_FLOAT64 float64Value; ss << stringValue; ss >> float64Value; if (ss.fail()) { SetFLOAT64Value(FIT_FLOAT64_INVALID, fieldArrayIndex, subFieldIndex); } else { SetFLOAT64Value(float64Value, fieldArrayIndex, subFieldIndex); } break; } default: break; } } FIT_BOOL Field::Read(const void *data, const FIT_UINT8 size) { int bytesLeft = size; FIT_UINT8 typeSize = baseTypeSizes[profile->fields[profileIndex].type & FIT_BASE_TYPE_NUM_MASK]; FIT_BYTE *byteData = (FIT_BYTE *) data; values.clear(); switch (profile->fields[profileIndex].type) { case FIT_BASE_TYPE_STRING: { std::vector<FIT_BYTE> value; int emptyStrings = 0; while (bytesLeft-- > 0) { FIT_BYTE byte = *byteData++; if (byte == 0) { if (value.size() > 0) { while (emptyStrings > 0) { values.push_back(std::vector<FIT_BYTE>(1, (FIT_BYTE)0)); // Add empty (null-terminated) string. emptyStrings--; } value.push_back(0); // Null-terminate. values.push_back(value); } else { emptyStrings++; } value.clear(); } else { value.push_back(byte); } } if (value.size() > 0) { while (emptyStrings > 0) { values.push_back(std::vector<FIT_BYTE>(1, (FIT_BYTE)0)); // Add empty (null-terminated) string. emptyStrings--; } value.push_back(0); // Null-terminate. values.push_back(value); } } break; default: { FIT_BOOL invalid = FIT_TRUE; while (bytesLeft > 0) { std::vector<FIT_BYTE> value; if (memcmp(byteData, baseTypeInvalids[profile->fields[profileIndex].type & FIT_BASE_TYPE_NUM_MASK], typeSize) != 0) invalid = FIT_FALSE; for (int i = 0; i < typeSize; i++) value.push_back(*byteData++); values.push_back(value); bytesLeft -= typeSize; } if (invalid) values.clear(); } break; } return FIT_TRUE; } FIT_UINT8 Field::Write(std::ostream &file) const { for (FIT_UINT8 valueIndex = 0; valueIndex < values.size(); valueIndex++) { for (FIT_UINT8 valueOffset = 0; valueOffset < values[valueIndex].size(); valueOffset++) file.put(values[valueIndex][valueOffset]); } return GetSize(); } } // namespace fit
32.212168
198
0.601947
kuperov
0fb3f85dfb9d5d44e197181e677366365f2604ce
24,054
cpp
C++
AppCUI/src/Utils/String.cpp
gheoan/AppCUI
5a8e188646867be8d6d3014d7c6e5d61a7492496
[ "MIT" ]
null
null
null
AppCUI/src/Utils/String.cpp
gheoan/AppCUI
5a8e188646867be8d6d3014d7c6e5d61a7492496
[ "MIT" ]
null
null
null
AppCUI/src/Utils/String.cpp
gheoan/AppCUI
5a8e188646867be8d6d3014d7c6e5d61a7492496
[ "MIT" ]
null
null
null
#include "AppCUI.hpp" #include "Internal.hpp" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> const unsigned char __lower_case_table__[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; #define STRING_FLAG_STACK_BUFFER 0x80000000 #define SNPRINTF _snprintf #define STRING_FLAG_STATIC_BUFFER 1 #define STRING_FLAG_CONSTANT 2 #define STRING_FLAG_STATIC_WITH_GROW 4 #define COMPUTE_TEXT_SIZE(text, textSize) \ if (textSize == 0xFFFFFFFF) \ { \ textSize = Len(text); \ } #define PREPATE_STRING_SOURCE_DESTINATION_PARAMS \ CHECK(destination, false, "Expecting a valid (non-null) destination string"); \ CHECK(source, false, "Expecting a valid (non-null) source parameter"); \ CHECK(maxDestinationSize > 0, \ false, \ "Expecting at least one character available in destination (maxDestinationSize should be bigger than 0)"); \ COMPUTE_TEXT_SIZE(source, sourceSize); \ CHECK(sourceSize < maxDestinationSize, \ false, \ "Current destination size (%d) is smaller than the size of the text (%d)", \ maxDestinationSize, \ sourceSize); #define VALIDATE_STRINGS_TO_COMPARE \ CHECK(sir1, false, "Expecting a valid (non-null) first parameter !"); \ CHECK(sir2, false, "Expecting a valid (non-null) first parameter !"); \ const unsigned char* p1 = (const unsigned char*) sir1; \ const unsigned char* p2 = (const unsigned char*) sir2; #define VALIDATE_ALLOCATED_SPACE(requiredSpace, returnValue) \ if ((requiredSpace) > (Allocated & 0x7FFFFFFF)) \ { \ CHECK(Grow(requiredSpace), returnValue, "Fail to allocate space for %d bytes", (requiredSpace)); \ } #define MEMCOPY memcpy char tempCharForReferenceReturn; // Statical functions unsigned int AppCUI::Utils::String::Len(const char* string) { if (string == nullptr) return 0; const char* p = string; while ((*string) != 0) { string++; } return (unsigned int) (string - p); } bool AppCUI::Utils::String::Add( char* destination, const char* source, unsigned int maxDestinationSize, unsigned int destinationSize, unsigned int sourceSize, unsigned int* resultedDestinationSize) { PREPATE_STRING_SOURCE_DESTINATION_PARAMS; COMPUTE_TEXT_SIZE(destination, destinationSize); CHECK(destinationSize + sourceSize < maxDestinationSize, false, "A total space of %d bytes is required to add string (available is %d)", destinationSize + sourceSize, maxDestinationSize); if (sourceSize > 0) { MEMCOPY(destination + destinationSize, source, sourceSize); } destination[sourceSize + destinationSize] = 0; if (resultedDestinationSize) *resultedDestinationSize = sourceSize + destinationSize; return true; } bool AppCUI::Utils::String::Set( char* destination, const char* source, unsigned int maxDestinationSize, unsigned int sourceSize, unsigned int* resultedDestinationSize) { PREPATE_STRING_SOURCE_DESTINATION_PARAMS; if (sourceSize > 0) { MEMCOPY(destination, source, sourceSize); } destination[sourceSize] = 0; if (resultedDestinationSize) *resultedDestinationSize = sourceSize; return true; } bool AppCUI::Utils::String::Equals(const char* sir1, const char* sir2, bool ignoreCase) { VALIDATE_STRINGS_TO_COMPARE; if (ignoreCase) { while ((*p1) && (*p2) && ((__lower_case_table__[*p1]) == (__lower_case_table__[*p2]))) { p1++; p2++; } return ((*p2) == 0) && ((*p1) == 0); } else { while ((*p1) && (*p2) && ((*p1) == (*p2))) { p1++; p2++; } return ((*p2) == 0) && ((*p1) == 0); } } bool AppCUI::Utils::String::StartsWith(const char* sir1, const char* sir2, bool ignoreCase) { VALIDATE_STRINGS_TO_COMPARE; if (ignoreCase) { while ((*p1) && (*p2) && ((__lower_case_table__[*p1]) == (__lower_case_table__[*p2]))) { p1++; p2++; } return (*p2) == 0; } else { while ((*p1) && (*p2) && ((*p1) == (*p2))) { p1++; p2++; } return (*p2) == 0; } } bool AppCUI::Utils::String::EndsWith( const char* sir1, const char* sir2, bool ignoreCase, unsigned int sir1Size, unsigned int sir2Size) { VALIDATE_STRINGS_TO_COMPARE COMPUTE_TEXT_SIZE(sir1, sir1Size); COMPUTE_TEXT_SIZE(sir2, sir2Size); if (sir2Size > sir1Size) return false; p1 += (sir2Size - sir1Size); if (ignoreCase) { while ((*p1) && (*p2) && ((__lower_case_table__[*p1]) == (__lower_case_table__[*p2]))) { p1++; p2++; } return ((*p2) == 0) && ((*p1) == 0); } else { while ((*p1) && (*p2) && ((*p1) == (*p2))) { p1++; p2++; } return ((*p2) == 0) && ((*p1) == 0); } } bool AppCUI::Utils::String::Contains(const char* sir, const char* textToFind, bool ignoreCase) { CHECK((sir != nullptr) && (textToFind != nullptr), false, "Invalid parameters (both 'sir' and 'textToFind' must not be null)"); if ((*textToFind) == 0) return true; // empty string exists in every strings const unsigned char* p_sir = (const unsigned char*) sir; const unsigned char* p_find = (const unsigned char*) textToFind; const unsigned char* ps; const unsigned char* pf; unsigned char char_to_find = *(p_find); if (ignoreCase) { char_to_find = __lower_case_table__[*p_find]; while (*p_sir) { if (__lower_case_table__[*p_sir] == char_to_find) { ps = p_sir; pf = p_find; for (; (*pf) && (*ps) && (__lower_case_table__[*ps] == __lower_case_table__[*pf]); pf++, ps++) ; if (!(*pf)) return true; } p_sir++; } } else { while (*p_sir) { if ((*p_sir) == char_to_find) { ps = p_sir; pf = p_find; for (; (*pf) && (*ps) && ((*ps) == (*pf)); pf++, ps++) ; if (!(*pf)) return true; } p_sir++; } } return false; } int AppCUI::Utils::String::Compare(const char* sir1, const char* sir2, bool ignoreCase) { VALIDATE_STRINGS_TO_COMPARE; if (ignoreCase) { while ((*p1) && (*p2) && ((__lower_case_table__[*p1]) == (__lower_case_table__[*p2]))) { p1++; p2++; } if (__lower_case_table__[*p1] < __lower_case_table__[*p2]) return -1; if (__lower_case_table__[*p1] > __lower_case_table__[*p2]) return 1; return 0; } else { while ((*p1) && (*p2) && ((*p1) == (*p2))) { p1++; p2++; } if ((*p1) < (*p2)) return -1; if ((*p1) > (*p2)) return 1; return 0; } } //--------------------------------------------------- CONSTRUCTORI OBIECT //---------------------------------------------------------------- AppCUI::Utils::String::String(void) { Text = nullptr; Size = Allocated = 0; } AppCUI::Utils::String::String(const AppCUI::Utils::String& s) { Text = nullptr; Size = Allocated = 0; if (Create(s.Size + 32)) { if (s.Text) { MEMCOPY(this->Text, s.Text, s.Size + 1); this->Size = s.Size; } } } AppCUI::Utils::String::~String(void) { Destroy(); } void AppCUI::Utils::String::Destroy() { if ((Text != nullptr) && ((Allocated & STRING_FLAG_STACK_BUFFER) == 0)) { delete Text; } Text = nullptr; Size = Allocated = 0; } bool AppCUI::Utils::String::Create(unsigned int initialAllocatedBufferSize) { CHECK(initialAllocatedBufferSize == 0, false, "initialAllocatedBufferSize must be bigger than 0 !"); initialAllocatedBufferSize = ((initialAllocatedBufferSize | 15) + 1) & 0x7FFFFFFF; if (initialAllocatedBufferSize <= (Allocated & 0x7FFFFFFF)) { *Text = 0; Size = 0; return true; } Destroy(); char* temp = new char[initialAllocatedBufferSize]; CHECK(temp, false, "Failed to allocate %d bytes", initialAllocatedBufferSize); Text = temp; Size = 0; *Text = 0; Allocated = initialAllocatedBufferSize; return true; } bool AppCUI::Utils::String::Create(const char* text) { CHECK(text, false, "Expecting a non-null string !"); unsigned int len = String::Len(text); CHECK(Create(len + 1), false, "Fail to create string buffer with len: %d", len); MEMCOPY(this->Text, text, len + 1); Size = len + 1; this->Text[len] = 0; return true; } bool AppCUI::Utils::String::Create(char* buffer, unsigned int bufferSize, bool emptyString) { CHECK(buffer, false, "Expecting a valid (non-null) buffer"); CHECK(bufferSize >= 1, false, "bufferSize must be bigger than 1"); CHECK(bufferSize < 0x7FFFFFFF, false, "bufferSize must be smaller than 0x7FFFFFFF"); Destroy(); Text = buffer; Allocated = (bufferSize & 0x7FFFFFFF) | STRING_FLAG_STACK_BUFFER; if (emptyString) { Size = 0; Text[Size] = 0; } else { const char* e = buffer + bufferSize - 1; Size = 0; while ((buffer < e) && (*buffer)) { buffer++; Size++; } *buffer = 0; } return true; } void AppCUI::Utils::String::Clear() { if (Text) { *Text = 0; Size = 0; } } bool AppCUI::Utils::String::Realloc(unsigned int newSize) { if (newSize <= (Allocated & 0x7FFFFFFF)) return true; return Grow(newSize); } bool AppCUI::Utils::String::Grow(unsigned int newSize) { newSize = ((newSize | 15) + 1) & 0x7FFFFFFF; if (newSize <= (Allocated & 0x7FFFFFFF)) return true; char* temp = new char[newSize]; CHECK(temp, false, "Failed to allocate: %d bytes", newSize); if (Text) { MEMCOPY(temp, Text, Size + 1); if ((Allocated & STRING_FLAG_STACK_BUFFER) == 0) delete Text; } Text = temp; Allocated = newSize; return true; } // ============================================================================================[ADD // FUNCTIONS]===================== bool AppCUI::Utils::String::Add(const char* text, unsigned int txSize) { CHECK(text, false, "Expecting a non-null parameter !"); COMPUTE_TEXT_SIZE(text, txSize); VALIDATE_ALLOCATED_SPACE(this->Size + txSize + 1, false); MEMCOPY(this->Text + this->Size, text, txSize); this->Size += txSize; this->Text[this->Size] = 0; return true; } bool AppCUI::Utils::String::Add(const String& text) { return this->Add(text.Text, text.Size); } bool AppCUI::Utils::String::Add(const String* text) { CHECK(text, false, "Expecting a non-null first parameter !"); return this->Add(text->Text, text->Size); } bool AppCUI::Utils::String::AddChar(char ch) { CHECK(ch, false, "NULL character can not be added !"); char temp[2]; temp[0] = ch; temp[1] = 0; return this->Add(temp, 1); } bool AppCUI::Utils::String::AddChars(char ch, unsigned int count) { CHECK(ch, false, "NULL character can not be added !"); CHECK(count, false, "'count' should be bigger than 0"); VALIDATE_ALLOCATED_SPACE(this->Size + count + 1, false); char* p = this->Text + this->Size; this->Size += count; while (count) { *p = ch; p++; count--; } *p = 0; return true; } // ============================================================================================[SET // FUNCTIONS]===================== bool AppCUI::Utils::String::Set(const char* text, unsigned int txSize) { CHECK(text, false, "Expecting a non-null parameter !"); COMPUTE_TEXT_SIZE(text, txSize); VALIDATE_ALLOCATED_SPACE(txSize + 1, false); MEMCOPY(this->Text, text, txSize); this->Size = txSize; this->Text[this->Size] = 0; return true; } bool AppCUI::Utils::String::Set(const AppCUI::Utils::String& text) { return this->Set(text.Text, text.Size); } bool AppCUI::Utils::String::Set(const AppCUI::Utils::String* text) { CHECK(text, false, "Expecting a non-null first parameter !"); return this->Set(text->Text, text->Size); } bool AppCUI::Utils::String::SetChars(char ch, unsigned int count) { CHECK(ch, false, "NULL character can not be added !"); CHECK(count, false, "'count' should be bigger than 0"); VALIDATE_ALLOCATED_SPACE(count + 1, false); char* p = this->Text; this->Size += count; while (count) { *p = ch; p++; count--; } *p = 0; return true; } bool AppCUI::Utils::String::InsertChar(char character, unsigned int position) { CHECK(character, false, "NULL character can not be added !"); VALIDATE_ALLOCATED_SPACE(this->Size + 2, false); CHECK(position <= this->Size, false, "Invalid insert offset: %d (should be between 0 and %d)", position, this->Size); if (position == this->Size) { this->Text[this->Size++] = character; this->Text[this->Size] = 0; } else { memmove(this->Text + position + 1, this->Text + position, this->Size - position); this->Text[position] = character; this->Size++; this->Text[this->Size] = 0; } return true; } bool AppCUI::Utils::String::DeleteChar(unsigned int position) { CHECK(position < this->Size, false, "Invalid delete offset: %d (should be between 0 and %d)", position, this->Size - 1); if ((position + 1) == this->Size) { this->Size--; this->Text[this->Size] = 0; } else { memmove(this->Text + position, this->Text + position + 1, this->Size - (position + 1)); this->Size--; this->Text[this->Size] = 0; } return true; } bool AppCUI::Utils::String::Delete(unsigned int start, unsigned int end) { CHECK(end <= this->Size, false, "Invalid delete offset: %d (should be between 0 and %d)", end, this->Size); CHECK(start < end, false, "Start parameter (%d) should be smaller than End parameter (%d)", start, end); if (end == this->Size) { this->Size = start; this->Text[this->Size] = 0; } else { memmove(this->Text + start, this->Text + end, this->Size - end); this->Size -= (end - start); this->Text[this->Size] = 0; } return true; } int AppCUI::Utils::String::GetChar(int index) const { if (Text == nullptr) return 0; if ((index >= 0) && (index < (int) Size)) return Text[(unsigned int) index]; unsigned int idx = (unsigned int) (-index); if (idx < Size) return Text[Size - idx]; return 0; } bool AppCUI::Utils::String::SetChar(int index, char value) { CHECK(Text, false, "Text buffer was not allocated !"); if ((index >= 0) && (index < (int) Size)) { Text[index] = value; return true; } unsigned int idx = (unsigned int) (-index); if (idx < Size) { Text[Size + idx] = value; return true; } RETURNERROR(false, "Invalid text index: %d for a text with length %d", index, this->Size); } bool AppCUI::Utils::String::SetFormat(const char* format, ...) { va_list args; int len, len2; CHECK(format, false, "Expecting a valid(non-null) format parameter !"); va_start(args, format); len = vsnprintf(nullptr, 0, format, args); va_end(args); CHECK(len >= 0, false, "Invalid format (unable to format your string) !"); VALIDATE_ALLOCATED_SPACE(((unsigned int) len) + 2, false); va_start(args, format); len2 = vsnprintf(Text, (Allocated & 0x7FFFFFFF) - 1, format, args); va_end(args); if (len2 < 0) { Clear(); RETURNERROR(false, "Fail on vsnprintf !"); } this->Size = (unsigned int) len2; Text[this->Size] = 0; return true; } bool AppCUI::Utils::String::AddFormat(const char* format, ...) { va_list args; int len, len2; CHECK(format, false, "Expecting a valid(non-null) format parameter !"); va_start(args, format); len = vsnprintf(nullptr, 0, format, args); va_end(args); CHECK(len >= 0, false, "Invalid format (unable to format your string) !"); VALIDATE_ALLOCATED_SPACE(((unsigned int) len) + 2 + this->Size, false); va_start(args, format); len2 = vsnprintf(Text + this->Size, (Allocated & 0x7FFFFFFF) - 1, format, args); va_end(args); if (len2 < 0) { Clear(); RETURNERROR(false, "Fail on vsnprintf !"); } this->Size += (unsigned int) len2; Text[this->Size] = 0; return true; } const char* AppCUI::Utils::String::Format(const char* format, ...) { va_list args; int len, len2; CHECK(format, nullptr, "Expecting a valid(non-null) format parameter !"); va_start(args, format); len = vsnprintf(nullptr, 0, format, args); va_end(args); CHECK(len >= 0, nullptr, "Invalid format (unable to format your string) !"); VALIDATE_ALLOCATED_SPACE(((unsigned int) len) + 2, nullptr); va_start(args, format); len2 = vsnprintf(Text, (Allocated & 0x7FFFFFFF) - 1, format, args); va_end(args); if (len2 < 0) { Clear(); RETURNERROR(nullptr, "Fail on vsnprintf !"); } this->Size = ((unsigned int) len2); Text[this->Size] = 0; return Text; } bool AppCUI::Utils::String::Truncate(unsigned int newText) { if ((newText <= Size) && (newText >= 0)) { Size = newText; Text[Size] = 0; return true; } return false; } bool AppCUI::Utils::String::StartsWith(const char* text, bool ignoreCase) const { return String::StartsWith(Text, text, ignoreCase); } bool AppCUI::Utils::String::StartsWith(const AppCUI::Utils::String* text, bool ignoreCase) const { CHECK(text != nullptr, false, "Expecting a non null parameter"); return String::StartsWith(Text, text->Text, ignoreCase); } bool AppCUI::Utils::String::StartsWith(const AppCUI::Utils::String& text, bool ignoreCase) const { return String::StartsWith(Text, text.Text, ignoreCase); } bool AppCUI::Utils::String::Contains(const char* text, bool ignoreCase) const { return String::Contains(this->Text, text, ignoreCase); } bool AppCUI::Utils::String::Contains(const String& ss, bool ignoreCase) const { return String::Contains(this->Text, ss.Text, ignoreCase); } bool AppCUI::Utils::String::EndsWith(const char* ss, bool ignoreCase) const { return String::EndsWith(Text, ss, ignoreCase, Size); } bool AppCUI::Utils::String::EndsWith(const AppCUI::Utils::String* text, bool ignoreCase) const { CHECK(text != nullptr, false, "Expecting a non null parameter"); return String::EndsWith(Text, text->Text, ignoreCase, Size, text->Size); } bool AppCUI::Utils::String::EndsWith(const AppCUI::Utils::String& text, bool ignoreCase) const { return String::EndsWith(Text, text.Text, ignoreCase, Size, text.Size); } bool AppCUI::Utils::String::Equals(const char* text, bool ignoreCase) const { return String::Equals(this->Text, text, ignoreCase); } bool AppCUI::Utils::String::Equals(const String& text, bool ignoreCase) const { if (this->Size != text.Size) return false; return String::Equals(this->Text, text.Text, ignoreCase); } int AppCUI::Utils::String::CompareWith(const char* text, bool ignoreCase) const { return String::Compare(this->Text, text, ignoreCase); } char& AppCUI::Utils::String::operator[](int poz) { if ((Text == nullptr) || (Size == 0)) { tempCharForReferenceReturn = 0; return tempCharForReferenceReturn; } if (poz < 0) poz += (int) this->Size; if (((poz + 1) > (int) Size) || (poz < 0)) { tempCharForReferenceReturn = 0; return tempCharForReferenceReturn; } return Text[poz]; } void AppCUI::Utils::String::ConvertToInternalNewLineFormat() { if ((this->Text == nullptr) || (this->Size == 0)) return; // nothing to convert char* s = Text; char* e = Text + this->Size; char* o = Text; while (s < e) { if ((*s) == '\r') { *o = NEW_LINE_CODE; s++; o++; if ((s < e) && ((*s) == '\n')) s++; continue; } if ((*s) == '\n') { *o = NEW_LINE_CODE; s++; o++; if ((s < e) && ((*s) == '\r')) s++; continue; } *o = *s; o++; s++; } this->Size -= (unsigned int) (s - o); this->Text[this->Size] = 0; }
31.944223
120
0.525858
gheoan
0fb5bfe74ca243467ad5182fdb40a7bc86ae77e9
10,550
cpp
C++
sources/Notebook.cpp
YosefKahlon/Notebook-b
9ea65641e374e3c6663781e664aba7797b09764a
[ "MIT" ]
null
null
null
sources/Notebook.cpp
YosefKahlon/Notebook-b
9ea65641e374e3c6663781e664aba7797b09764a
[ "MIT" ]
null
null
null
sources/Notebook.cpp
YosefKahlon/Notebook-b
9ea65641e374e3c6663781e664aba7797b09764a
[ "MIT" ]
null
null
null
// // Created by 97252 on 3/22/2022. // #include "exception" #include "Direction.hpp" #include "Notebook.hpp" #include "iostream" #include "string" #include "stdexcept" #include "map" using namespace std; using namespace ariel; //constructor Notebook::Notebook() { string col = "____________________________________________________________________________________________________"; unordered_map<int, string> row; row[0] = col; this->book[0] = row; } //destructor Notebook::~Notebook() { cout << " done - Notebook - done" << endl; } /** * Method of writing the given text on the given position */ void Notebook::write(int page, int row, int column, Direction direction, const std::string &text) { int len = text.length(); if (negative_num(page) || negative_num(row) || negative_num(column)) { throw std::invalid_argument("Negative argument is not allowed !!"); } if (invalid_num(column)) { throw std::invalid_argument("No more than 100!!"); } if (invalid_char(text)) { throw std::invalid_argument("You can't write this char! "); } if (direction == Direction::Horizontal) { if (invalid_num(len) || invalid_num(column + len)) { throw std::invalid_argument("No more than 100!!"); } if (alreadyWroteHoriz(page, row, column, len, text)) { throw std::invalid_argument("You can't write there !!"); } horizontal(page, row, column, direction, &text, len); } else { if (alreadyWroteVert(page, row, column, len, text)) { throw std::invalid_argument("You can't write there !!"); } vertical(page, row, column, direction, &text, len); } } /** * @return line to read */ std::string Notebook::read(int page, int row, int column, Direction direction, int length) { if (negative_num(page) || negative_num(row) || negative_num(column) || negative_num(length)) { throw std::invalid_argument("Negative argument is not allowed !!"); } const int one_hundred = 100; if (invalid_num(column)) { throw std::invalid_argument("column no more than 100!!"); } if (direction == Direction::Horizontal) { if (length > one_hundred) { throw std::invalid_argument("length No more than 100!!"); } if ((column + length) > one_hundred) { throw std::invalid_argument("col + len No more than 100!!"); } } if (check_key(this->book, page) == "Not Present") { add_row(page, row, direction, length); } else if (check_key_row(this->book[page], row + length) == "Not Present") { extra_row(page, row, direction, length); } string ans; if (direction == Direction::Horizontal) { for (int i = column; i < column + length; i++) { ans += this->book[page][row][(unsigned int) i]; } } else { for (int i = row; i < row + length; i++) { ans += this->book[page][i][(unsigned int) column]; } } return ans; } /** * A method to "erase" line with the given length * by replace each char to ~ */ void Notebook::erase(int page, int row, int column, Direction direction, int length) { if (negative_num(page) || negative_num(row) || negative_num(column) || negative_num(length)) { throw std::invalid_argument("Negative argument is not allowed !!"); } if (invalid_num(column)) { throw std::invalid_argument("No more than 100!!"); } // first need to check there is rows in the correct page // or there is row but not enough if (check_key(this->book, page) == "Not Present") { add_row(page, row, direction, length); } else if (check_key_row(this->book[page], row + length) == "Not Present") { extra_row(page, row, direction, length); } if (direction == Direction::Horizontal) { if (invalid_num(length) || invalid_num(column + length)) { throw std::invalid_argument("No more than 100!!"); } for (int i = column; i < column + length; i++) { this->book[page][row][(unsigned int) i] = '~'; } } else { for (int i = row; i < row + length; i++) { this->book[page][(unsigned long) i][(unsigned int) column] = '~'; } } } void Notebook::show(int page_number) { if (negative_num(page_number)) { throw std::invalid_argument("Page number start from 0 !!"); } cout << "-------------------------------------------- Page Number: " << page_number << " --------------------------------------------" << endl; map<int, string> ans; for (const auto &x: this->book) { if (x.first == page_number) { for (const auto &y: x.second) { ans.insert(make_pair(y.first, y.second)); } } } //print the line in order for (const auto &x: ans) { cout << x.first << ". " << x.second << endl; } } /** * method to write on the book in horizontal mod */ void Notebook::horizontal(int page, int row, int column, Direction direction, const string *text, int len) { string line = "____________________________________________________________________________________________________"; int j = 0; // //Have not added those rows if (check_key(this->book, page) == "Not Present") { add_row(page, row, direction, len); //Change the char in the line for (int i = column; i < column + len; i++) { line.at((unsigned long) i) = text->at((unsigned long) j++); } this->book[page][row] = line; } else { j = 0; extra_row(page, row, direction, len); //Change the char in correct column for (int i = column; i < column + len; i++) { this->book[page][row][(unsigned long) i] = text->at((unsigned long) j++); } } } /** * method to write on the book in vertical mod */ void Notebook::vertical(int page, int row, int column, Direction direction, const string *text, int len) { string line = "____________________________________________________________________________________________________"; int k = 0; add_row(page, row, direction, len + row); //have not added those rows if (check_key(this->book, page) == "Not Present") { //change the char in the line for (int i = row; i < row + len && k < len; i++) { this->book[page][(unsigned long) i][(unsigned long) column] = text->at((unsigned long) k++); } } else { k = 0; //not enough row extra_row(page, row, direction, row + len); //change the char in correct line for (int i = row; i < row + len && k < len; i++) { this->book[page][(unsigned long) i][(unsigned long) column] = text->at((unsigned long) k++); } } } /** * @param text write * @return true if the text contain bad char to write else false */ bool Notebook::invalid_char(const string &text) { for (int i = 0; i < text.length(); ++i) { if (text.at((unsigned long) i) < ' ' || text.at((unsigned long) i) >= '~') { return true; } } return false; } /** * A method for adding rows for new page */ void Notebook::add_row(int page, int row, Direction direction, int len) { string line = "____________________________________________________________________________________________________"; if (direction == Direction::Horizontal) { unordered_map<int, string> new_row; for (int i = 0; i <= row; i++) { new_row[(unsigned long) i] = line; } this->book[page] = new_row; } else if (direction == Direction::Vertical) { unordered_map<int, string> new_row; int add_row = len + row; for (int i = 0; i < add_row; i++) { new_row[(unsigned long) i] = line; } this->book[page] = new_row; } } /** * A method for adding rows that do not appear in the page */ void Notebook::extra_row(int page, int row, Direction direction, int len) { string line = "____________________________________________________________________________________________________"; if (direction == Direction::Horizontal) { int size_row = this->book[page].size(); //not enough row if (size_row <= row) { for (int i = size_row; i <= row; i++) { this->book[page][(unsigned long) i] = line; } } } else if (direction == Direction::Vertical) { int size_row = this->book[page].size(); //not enough row if (size_row < row + len) { for (int i = size_row; i <= row + len; i++) { this->book[page][(unsigned long) i] = line; } } } } bool Notebook::negative_num(int num) { bool ans = false; const int x = 0; if (num < x) { ans = true; } return ans; } bool Notebook::invalid_num(int num) { bool ans = false; const int x = 100; if (x <= num) { ans = true; } return ans; } // https://www.geeksforgeeks.org/check-key-present-cpp-map-unordered_map/ string Notebook::check_key(unordered_map<int, unordered_map<int, string>> m, int key) { // Key is not present if (m.find(key) == m.end()) { return "Not Present"; } return "Present"; } string Notebook::check_key_row(unordered_map<int, string> m, int key) { // Key is not present if (m.find(key) == m.end()) { return "Not Present"; } return "Present"; } bool Notebook::alreadyWroteHoriz(int page, int row, int column, int len, const std::string &text) { if (check_key(this->book, page) == "Present") { if (!(this->book[page].find(row) == this->book[page].end())) { for (int j = column; j < column + len; j++) { if (this->book[page][row][(unsigned long) j] != '_') { return true; } } } } return false; } bool Notebook::alreadyWroteVert(int page, int row, int column, int len, const string &basicString) { if (check_key(this->book, page) == "Present") { for (int i = row; i < row + len; ++i) { if (!(this->book[page].find(i) == this->book[page].end())) { if (this->book[page][(unsigned long) i][(unsigned int) column] != '_') { return true; } } } } return false; }
29.224377
121
0.569953
YosefKahlon
0fba3fad1481c3575d006d699a8fffcdbd5ef730
866
cpp
C++
codeforces/contests/1365/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
codeforces/contests/1365/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
codeforces/contests/1365/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Codeforces Round #648 (Div. 2) - B. Trouble Sort https://codeforces.com/contest/1365/problem/B */ #include <bits/stdc++.h> using namespace std; #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { FAST_INP; int t,n; cin >> t; while(t--){ cin >> n; vector<int> a(n+1),b(n+1); bool s=1, zero=0, one=0; for(int i=1;i<=n;i++){ cin >> a[i]; if(i>=2&&a[i]<a[i-1]) { s=0; } } for(int i=1;i<=n;i++){ cin >> b[i]; if(b[i]==0) zero=1; else one=1; } // if we have 0 and 1, we can use it to rearrange for all positions if(zero&&one) cout << "Yes\n"; // if it is sorted already, no operation is needed. else if(s) cout << "Yes\n"; // if not, it is not possible to sort else cout << "No\n"; } return 0; }
21.65
69
0.512702
wingkwong
0fc0a9ace78287c7bd6688d21c5250c7f5cab6dc
646
cpp
C++
atcoder/abc/abc139/c.cpp
zaurus-yusya/atcoder
5fc345b3da50222fa1366d1ce52ae58799488cef
[ "MIT" ]
3
2020-05-27T16:27:12.000Z
2021-01-27T12:47:12.000Z
atcoder/abc/abc139/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
atcoder/abc/abc139/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<(n);i++) #define repr(i,n) for(int i=(n-1);i>=0;i--) #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() using namespace std; typedef long long ll; int main() { ll n; cin >> n; vector<ll> vec(100000); ll ans = 0; ll count = 0; for(ll i = 0; i < n; i++){ cin >> vec.at(i); if(i == 0) continue; if(vec.at(i-1) >= vec.at(i)){ count++; }else{ if(ans < count){ ans = count; count = 0; }else{ count = 0; } } } if(ans < count){ ans = count; } cout << ans << endl; }
16.564103
43
0.48452
zaurus-yusya
0fc84af934a911ed4a0613a76644b4f6a6ce8992
1,364
cpp
C++
ACM-ICPC/14889.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/14889.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/14889.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <cmath> using namespace std; int n, answer = 987654321; int arr[21][21]; bool visited[21]; void f(int idx, int temp) { // n은 무조건 짝수 이므로 // temp == n / 2면 팀선택 완료 if (n / 2 == temp) { int x = 0, y = 0; vector<int> start, link; // visited값에 따라 팀 분배 for (int i = 0; i < n; i++) { if (visited[i]) { start.push_back(i); } else { link.push_back(i); } } // 팀 능력치 합산 for (int i = 0; i < start.size(); i++) { for (int j = i + 1; j < start.size(); j++) { x += arr[start[i]][start[j]] + arr[start[j]][start[i]]; y += arr[link[i]][link[j]] + arr[link[j]][link[i]]; } } // 차이값이 작은 값이 정답 answer = (answer > abs(x - y)) ? abs(x - y) : answer; return; } for (int i = idx + 1; i < n; i++) { if (!visited[i]) { visited[i] = true; f(i, temp + 1); visited[i] = false; } } } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%d", &arr[i][j]); } } f(0, 0); printf("%d\n", answer); }
22.733333
72
0.370235
KimBoWoon
0fc97fa73dcbea91c4a74aa76542c0ac71e9d4fd
4,489
hpp
C++
source/opengl/reshade_api_type_utils.hpp
EliphasNUIT/reshade
d767bece469df57aef005c71de6a53d83886c080
[ "BSD-3-Clause" ]
null
null
null
source/opengl/reshade_api_type_utils.hpp
EliphasNUIT/reshade
d767bece469df57aef005c71de6a53d83886c080
[ "BSD-3-Clause" ]
null
null
null
source/opengl/reshade_api_type_utils.hpp
EliphasNUIT/reshade
d767bece469df57aef005c71de6a53d83886c080
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2021 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once namespace reshade::opengl { struct query_heap_impl { ~query_heap_impl() { glDeleteQueries(static_cast<GLsizei>(queries.size()), queries.data()); } std::vector<GLuint> queries; }; struct pipeline_layout_impl { std::vector<GLuint> bindings; }; struct pipeline_compute_impl { ~pipeline_compute_impl() { glDeleteProgram(program); } GLuint program; }; struct pipeline_graphics_impl { ~pipeline_graphics_impl() { glDeleteProgram(program); glDeleteVertexArrays(1, &vao); } GLuint program; GLuint vao; GLenum prim_mode; GLuint patch_vertices; GLenum front_face; GLenum cull_mode; GLenum polygon_mode; GLenum blend_eq; GLenum blend_eq_alpha; GLenum blend_src; GLenum blend_dst; GLenum blend_src_alpha; GLenum blend_dst_alpha; GLenum back_stencil_op_fail; GLenum back_stencil_op_depth_fail; GLenum back_stencil_op_pass; GLenum back_stencil_func; GLenum front_stencil_op_fail; GLenum front_stencil_op_depth_fail; GLenum front_stencil_op_pass; GLenum front_stencil_func; GLuint stencil_read_mask; GLuint stencil_write_mask; GLboolean blend_enable; GLboolean depth_test; GLboolean depth_write_mask; GLboolean stencil_test; GLboolean scissor_test; GLboolean multisample; GLboolean sample_alpha_to_coverage; GLbitfield sample_mask; GLuint color_write_mask; GLint stencil_reference_value; }; struct descriptor_set_impl { reshade::api::descriptor_type type; std::vector<uint64_t> descriptors; std::vector<reshade::api::sampler_with_resource_view> sampler_with_resource_views; }; struct descriptor_set_layout_impl { reshade::api::descriptor_range range; }; inline api::resource make_resource_handle(GLenum target, GLuint object) { if (!object) return { 0 }; return { (static_cast<uint64_t>(target) << 40) | object }; } inline api::resource_view make_resource_view_handle(GLenum target, GLuint object, uint8_t extra_bits = 0) { return { (static_cast<uint64_t>(target) << 40) | (static_cast<uint64_t>(extra_bits) << 32) | object }; } auto convert_format(api::format format) -> GLenum; auto convert_format(GLenum internal_format) -> api::format; auto convert_attrib_format(api::format format, GLint &size, GLboolean &normalized) -> GLenum; auto convert_upload_format(GLenum internal_format, GLenum &type)->GLenum; bool is_depth_stencil_format(GLenum internal_format, GLenum usage = GL_DEPTH_STENCIL); void convert_memory_heap_to_usage(api::memory_heap heap, GLenum &usage); void convert_memory_heap_to_flags(api::memory_heap heap, GLbitfield &flags); api::memory_heap convert_memory_heap_from_usage(GLenum usage); api::memory_heap convert_memory_heap_from_flags(GLbitfield flags); bool check_resource_desc(GLenum target, const api::resource_desc &desc, GLenum &internal_format); api::resource_type convert_resource_type(GLenum target); api::resource_desc convert_resource_desc(GLenum target, GLsizeiptr buffer_size, api::memory_heap heap); api::resource_desc convert_resource_desc(GLenum target, GLsizei levels, GLsizei samples, GLenum internal_format, GLsizei width, GLsizei height = 1, GLsizei depth = 1); bool check_resource_view_desc(GLenum target, const api::resource_view_desc &desc, GLenum &internal_format); api::resource_view_type convert_resource_view_type(GLenum target); api::resource_view_desc convert_resource_view_desc(GLenum target, GLenum internal_format, GLintptr offset, GLsizeiptr size); api::resource_view_desc convert_resource_view_desc(GLenum target, GLenum internal_format, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); api::subresource_data convert_mapped_subresource(GLenum format, GLenum type, const GLvoid *pixels, GLsizei width, GLsizei height = 1, GLsizei depth = 1); GLuint get_index_type_size(GLenum index_type); GLenum get_binding_for_target(GLenum target); GLenum convert_blend_op(api::blend_op value); GLenum convert_blend_factor(api::blend_factor value); GLenum convert_fill_mode(api::fill_mode value); GLenum convert_cull_mode(api::cull_mode value); GLenum convert_compare_op(api::compare_op value); GLenum convert_stencil_op(api::stencil_op value); GLenum convert_primitive_topology(api::primitive_topology value); GLenum convert_query_type(api::query_type type); GLenum convert_shader_type(api::shader_stage type); }
31.391608
168
0.788594
EliphasNUIT
0fcdb28981ffd6c8c42858ec4d658fcad3c9f1ac
1,215
hpp
C++
Utility/tRect.hpp
raydelto/GeometryWars
a692a5a08dc2945aeb187853059d5a7339100879
[ "MIT" ]
7
2015-01-18T07:05:43.000Z
2017-08-20T06:48:49.000Z
code/source/Utility/tRect.h
tatewake/shapeblaster-ios
c121a254e3e96736c3135ce14c9e11603621c2b5
[ "BSD-2-Clause" ]
null
null
null
code/source/Utility/tRect.h
tatewake/shapeblaster-ios
c121a254e3e96736c3135ce14c9e11603621c2b5
[ "BSD-2-Clause" ]
6
2015-01-17T02:00:13.000Z
2020-09-23T15:33:15.000Z
#pragma once //--------------------------------------------------------------------------------- // Written by Terence J. Grant - tjgrant [at] tatewake [dot] com // Find the full tutorial at: http://gamedev.tutsplus.com/series/ //---------------------------------------------------------------------------------- class tRectf { public: tVector2f location; tVector2f size; //Comparison / relational operators bool operator ==(const tRectf& b) const { return (location == b.location) && (size == b.size); } bool operator !=(const tRectf& b) const { return !(*this == b); } public: tRectf() { } tRectf(float nx, float ny, float nw, float nh) : location(nx, ny), size(nw, nh) { } tRectf(float nx, float ny, const tVector2f& nd) : location(nx, ny), size(nd) { } tRectf(const tVector2f& np, float nw, float nh) : location(np), size(nw, nh) { } tRectf(const tVector2f& np, const tVector2f& nd) : location(np), size(nd) { } bool contains(const tVector2f& newPt) const { return newPt.x >= location.x && newPt.y >= location.y && newPt.x < (location.x + size.width) && newPt.y < (location.y + size.height); } };
36.818182
100
0.518519
raydelto
0fce58ae70344825526ed892083a82ff6924ff1c
731
hpp
C++
src/stan/math/prim/mat/fun/trace_quad_form.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/math/prim/mat/fun/trace_quad_form.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/math/prim/mat/fun/trace_quad_form.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_MAT_FUN_TRACE_QUAD_FORM_HPP #define STAN_MATH_PRIM_MAT_FUN_TRACE_QUAD_FORM_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/err/check_multiplicable.hpp> #include <stan/math/prim/mat/err/check_square.hpp> namespace stan { namespace math { /** * Compute trace(B^T A B). **/ template <int RA, int CA, int RB, int CB> inline double trace_quad_form(const Eigen::Matrix<double, RA, CA> &A, const Eigen::Matrix<double, RB, CB> &B) { check_square("trace_quad_form", "A", A); check_multiplicable("trace_quad_form", "A", A, "B", B); return (B.transpose() * A * B).trace(); } } // namespace math } // namespace stan #endif
29.24
72
0.667579
alashworth