hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b536dda31e5e83e803ef52be20ab2ad61f31ddfc | 1,035 | cpp | C++ | Days 241 - 250/Day 245/MinJumpsAcrossArray.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 241 - 250/Day 245/MinJumpsAcrossArray.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 241 - 250/Day 245/MinJumpsAcrossArray.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <vector>
unsigned int GetMinNumberOfJumpsHelper(const std::vector<unsigned int>& steps, const size_t currentIndex, const unsigned int currentJumpCount)
{
if (currentIndex >= steps.size() - 1)
{
return currentJumpCount;
}
if (steps[currentIndex] == 0)
{
return std::numeric_limits<unsigned int>::max();
}
const unsigned int currentSteps = steps[currentIndex];
unsigned int minJumpCount = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 1; i <= currentSteps; ++i)
{
minJumpCount = std::min(minJumpCount, GetMinNumberOfJumpsHelper(steps, currentIndex + i, currentJumpCount + 1));
}
return minJumpCount;
}
inline unsigned int GetMinNumberOfJumps(const std::vector<unsigned int>& steps)
{
return GetMinNumberOfJumpsHelper(steps, 0, 0);
}
int main(int argc, char* argv[])
{
std::cout << GetMinNumberOfJumps({ 6, 2, 4, 0, 5, 1, 1, 4, 2, 9 }) << "\n";
std::cin.get();
return EXIT_SUCCESS;
} | 24.069767 | 142 | 0.711111 | [
"vector"
] |
b53ea03019730c359ec2f889a078e3504a09abce | 4,020 | cpp | C++ | Alfred/src/HttpClientTransactions.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | Alfred/src/HttpClientTransactions.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | Alfred/src/HttpClientTransactions.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | /**
* @file HttpClientTransactions.cpp
*
* This module contains the implementation of the HttpClientTransactions class
* which uses an Http::Client object to create and complete request-response
* transactions.
*/
#include "HttpClientTransactions.hpp"
#include <memory>
#include <mutex>
#include <unordered_set>
/**
* This contains the private properties of a HttpClientTransactions class instance.
*/
struct HttpClientTransactions::Impl
: public std::enable_shared_from_this< HttpClientTransactions::Impl >
{
// Properties
SystemAbstractions::DiagnosticsSender diagnosticsSender;
std::shared_ptr< Http::Client > httpClient;
std::mutex mutex;
int nextTransactionId = 1;
std::unordered_set< std::shared_ptr< Http::IClient::Transaction > > transactions;
// Constructor
Impl()
: diagnosticsSender("HttpClientTransactions")
{
}
void OnCompletion(
int id,
const std::shared_ptr< Http::IClient::Transaction >& transaction,
CompletionDelegate completionDelegate
) {
std::unique_lock< decltype(mutex) > lock(mutex);
diagnosticsSender.SendDiagnosticInformationFormatted(
0,
"%d reply: %u (%s)",
id,
transaction->response.statusCode,
transaction->response.reasonPhrase.c_str()
);
auto response = std::move(transaction->response);
(void)transactions.erase(transaction);
lock.unlock();
completionDelegate(response);
}
};
HttpClientTransactions::~HttpClientTransactions() noexcept {
Demobilize();
}
HttpClientTransactions::HttpClientTransactions(HttpClientTransactions&&) noexcept = default;
HttpClientTransactions& HttpClientTransactions::operator=(HttpClientTransactions&&) noexcept = default;
HttpClientTransactions::HttpClientTransactions()
: impl_(new Impl())
{
}
void HttpClientTransactions::Demobilize() {
impl_->httpClient = nullptr;
impl_->transactions.clear();
}
SystemAbstractions::DiagnosticsSender::UnsubscribeDelegate HttpClientTransactions::SubscribeToDiagnostics(
SystemAbstractions::DiagnosticsSender::DiagnosticMessageDelegate delegate,
size_t minLevel
) {
return impl_->diagnosticsSender.SubscribeToDiagnostics(delegate, minLevel);
}
void HttpClientTransactions::Mobilize(
const std::shared_ptr< Http::Client >& httpClient
) {
impl_->httpClient = httpClient;
}
void HttpClientTransactions::Post(
Http::Request& request,
CompletionDelegate completionDelegate
) {
std::lock_guard< decltype(impl_->mutex) > lock(impl_->mutex);
if (!request.target.HasPort()) {
const auto scheme = request.target.GetScheme();
if (
(scheme == "https")
|| (scheme == "wss")
) {
request.target.SetPort(443);
}
}
const auto id = impl_->nextTransactionId++;
impl_->diagnosticsSender.SendDiagnosticInformationFormatted(
0,
"%d request: %s",
id,
request.target.GenerateString().c_str()
);
auto transaction = impl_->httpClient->Request(request);
(void)impl_->transactions.insert(transaction);
std::weak_ptr< Http::IClient::Transaction > transactionWeak(transaction);
std::weak_ptr< Impl > implWeak(impl_);
transaction->SetCompletionDelegate(
[
completionDelegate,
id,
implWeak,
transactionWeak
]{
auto impl = implWeak.lock();
if (impl == nullptr) {
return;
}
auto transaction = transactionWeak.lock();
if (transaction == nullptr) {
impl->diagnosticsSender.SendDiagnosticInformationFormatted(
SystemAbstractions::DiagnosticsSender::Levels::WARNING,
"%d abandoned",
id
);
return;
}
impl->OnCompletion(id, transaction, completionDelegate);
}
);
}
| 29.558824 | 106 | 0.649502 | [
"object"
] |
b5425f02862f80637d822ca14dce5769c777c94c | 2,943 | cpp | C++ | VUEImporter/Source/ThirdParty/EarClipper/EarClipperWrapper/EarClipperWrapper.cpp | LeGone/Konzeption-und-Realisierung-eines-Plugins-f-r-die-Aufbereitung-von-CAD-Daten-zur-Nutzung-in-einer-GE | a631cd43850b1f3c11f29fbb67279da7a8fe4f90 | [
"MIT"
] | null | null | null | VUEImporter/Source/ThirdParty/EarClipper/EarClipperWrapper/EarClipperWrapper.cpp | LeGone/Konzeption-und-Realisierung-eines-Plugins-f-r-die-Aufbereitung-von-CAD-Daten-zur-Nutzung-in-einer-GE | a631cd43850b1f3c11f29fbb67279da7a8fe4f90 | [
"MIT"
] | null | null | null | VUEImporter/Source/ThirdParty/EarClipper/EarClipperWrapper/EarClipperWrapper.cpp | LeGone/Konzeption-und-Realisierung-eines-Plugins-f-r-die-Aufbereitung-von-CAD-Daten-zur-Nutzung-in-einer-GE | a631cd43850b1f3c11f29fbb67279da7a8fe4f90 | [
"MIT"
] | 1 | 2019-10-31T11:56:59.000Z | 2019-10-31T11:56:59.000Z | #include "stdafx.h"
#define WRAPPER_EXPORTS
#include "EarClipperWrapper.hpp"
#include <msclr/marshal.h>
using namespace msclr::interop;
#include <strsafe.h>
#include <vcclr.h>
using namespace System;
using namespace System::Runtime::InteropServices;
namespace EarClipperW
{
System::Reflection::Assembly^ currentDomain_AssemblyResolve(Object^ sender, ResolveEventArgs^ args)
{
sender;
// If this is an mscorlib, do a bare load
if (args->Name->Length >= 8 && args->Name->Substring(0, 8) == L"mscorlib")
{
return System::Reflection::Assembly::Load(args->Name->Substring(0, args->Name->IndexOf(L",")) + L".dll");
}
// Load the assembly from the specified path
String^ finalPath = nullptr;
try
{
finalPath = gcnew String("C:/Users/LeGone/Documents/Unreal Projects/VUEProject/Plugins/VUEImporter/Source/ThirdParty/EarClipper/Binaries/") + args->Name->Substring(0, args->Name->IndexOf(",")) + ".dll";
System::Reflection::Assembly^ retval = System::Reflection::Assembly::LoadFrom(finalPath);
return retval;
}
catch (...)
{
}
return nullptr;
}
EarClipper::EarClipper()
{
AppDomain::CurrentDomain->AssemblyResolve += gcnew ResolveEventHandler(currentDomain_AssemblyResolve);
// Managed
// Instantiate the C# class CSSimpleObject.
EarClipperLib::Helper^ EarClipperInstance = gcnew EarClipperLib::Helper();
// Pin the CSSimpleObject .NET object, and record the address of the
// pinned object in m_impl.
EarClipperPointer = GCHandle::ToIntPtr(GCHandle::Alloc(EarClipperInstance)).ToPointer();
// Unmanaged
ResultIndices = NULL;
}
EarClipper::~EarClipper()
{
// Managed
GCHandle AGCHandle = GCHandle::FromIntPtr(IntPtr(EarClipperPointer));
AGCHandle.Free();
// Unmanaged
if (ResultIndices)
{
delete[] ResultIndices;
}
}
void EarClipper::AddVertex(double X, double Y, double Z)
{
GCHandle AGCHandle = GCHandle::FromIntPtr(IntPtr(EarClipperPointer));
EarClipperLib::Helper^ EarClipperInstance = safe_cast<EarClipperLib::Helper^>(AGCHandle.Target);
EarClipperInstance->AddVertex(X, Y, Z);
}
void EarClipper::SetNormal(double X, double Y, double Z)
{
GCHandle AGCHandle = GCHandle::FromIntPtr(IntPtr(EarClipperPointer));
EarClipperLib::Helper^ EarClipperInstance = safe_cast<EarClipperLib::Helper^>(AGCHandle.Target);
EarClipperInstance->SetNormal(X, Y, Z);
}
void EarClipper::Triangulate()
{
GCHandle AGCHandle = GCHandle::FromIntPtr(IntPtr(EarClipperPointer));
EarClipperLib::Helper^ EarClipperInstance = safe_cast<EarClipperLib::Helper^>(AGCHandle.Target);
System::Collections::Generic::List<short>^ ManagedIndices = EarClipperInstance->TriangulateAndReturnIndices();
ResultIndicesCount = ManagedIndices->Count;
if (ResultIndicesCount)
{
ResultIndices = new short[ResultIndicesCount];
for (short Index = 0; Index < ResultIndicesCount; Index++)
{
ResultIndices[Index] = ManagedIndices[Index];
}
}
}
} | 28.298077 | 205 | 0.729867 | [
"object"
] |
b5489c4b0ceb95ed4b64947e9edafad1e81a821f | 1,968 | hpp | C++ | src/aardvark/spi.hpp | embvm-drivers/aardvark | b0520e70721330d7b74943918a4e8ada944e0523 | [
"MIT"
] | 1 | 2021-03-05T10:04:18.000Z | 2021-03-05T10:04:18.000Z | src/aardvark/spi.hpp | embvm-drivers/aardvark | b0520e70721330d7b74943918a4e8ada944e0523 | [
"MIT"
] | null | null | null | src/aardvark/spi.hpp | embvm-drivers/aardvark | b0520e70721330d7b74943918a4e8ada944e0523 | [
"MIT"
] | null | null | null | // Copyright 2020 Embedded Artistry LLC
// SPDX-License-Identifier: MIT
#ifndef AARDVARK_SPI_DRIVER_HPP_
#define AARDVARK_SPI_DRIVER_HPP_
#include "base.hpp"
#include <active_object/active_object.hpp>
#include <cstdint>
#include <driver/spi.hpp>
namespace embdrv
{
/** Create an Aardvark SPI Master Driver
*
* This driver requires an aardvarkAdapter to work. The aardvark adapter must be
* configured with aardvarkMode::SpiGpio or aardvarkMode::SpiI2C.
*
* This is an active object: it has its own thread of control.
*
* @code
* embdrv::aardvarkAdapter aardvark{embdrv::aardvarkMode::SpiI2C};
* embdrv::aardvarkSPIMaster spi0{aardvark, "spi0"};
* @endcode
*
* @ingroup AardvarkDrivers
*/
class aardvarkSPIMaster final
: public embvm::spi::master,
public embutil::activeObject<aardvarkSPIMaster,
std::pair<embvm::spi::op_t, const embvm::spi::master::cb_t>>
{
/// The storage type that the active object stores.
using storagePair_t = std::pair<embvm::spi::op_t, const embvm::spi::master::cb_t>;
public:
/** Construct an Aardvark SPI master
*
* @param base_driver The aardvarkAdapter instance associated with this driver.
*/
explicit aardvarkSPIMaster(aardvarkAdapter& base_driver) noexcept : base_driver_(base_driver) {}
/// Default destructor.
~aardvarkSPIMaster() noexcept;
/// Active object process function
void process_(const storagePair_t& op) noexcept;
private:
void start_() noexcept final;
void stop_() noexcept final;
void configure_() noexcept final;
uint32_t baudrate_(uint32_t baud) noexcept final;
embvm::comm::status transfer_(const embvm::spi::op_t& op,
const embvm::spi::master::cb_t& cb) noexcept final;
void setMode_(embvm::spi::mode mode) noexcept final;
void setOrder_(embvm::spi::order order) noexcept final;
private:
/// The aardvarkAdapter instance associated with this driver.
aardvarkAdapter& base_driver_;
};
} // namespace embdrv
#endif // AARDVARK_SPI_DRIVER_HPP_
| 29.373134 | 97 | 0.746951 | [
"object"
] |
b557941a90488dd1b9df396f8a38e056de6019d8 | 902 | cpp | C++ | Algorithms/200.Number-of-Islands/solution.cpp | moranzcw/LeetCode_Solutions | 49a7e33b83d8d9ce449c758717f74a69e72f808e | [
"MIT"
] | 178 | 2017-07-09T23:13:11.000Z | 2022-02-26T13:35:06.000Z | Algorithms/200.Number-of-Islands/solution.cpp | cfhyxxj/LeetCode-NOTES | 455d33aae54d065635d28ebf37f815dc4ace7e63 | [
"MIT"
] | 1 | 2020-10-10T16:38:03.000Z | 2020-10-10T16:38:03.000Z | Algorithms/200.Number-of-Islands/solution.cpp | cfhyxxj/LeetCode-NOTES | 455d33aae54d065635d28ebf37f815dc4ace7e63 | [
"MIT"
] | 82 | 2017-08-19T07:14:39.000Z | 2022-02-17T14:07:55.000Z | class Solution
{
public:
void dfs(vector<vector<char>> &grid, int x, int y)
{
if (x < 0 || x >= grid.size())
return;
if (y < 0 || y >= grid[0].size())
return;
if (grid[x][y] != '1')
return;
grid[x][y] = 'X';
dfs(grid, x + 1, y);
dfs(grid, x - 1, y);
dfs(grid, x, y + 1);
dfs(grid, x, y - 1);
}
int numIslands(vector<vector<char>> &grid)
{
if (grid.empty() || grid[0].empty())
return 0;
int N = grid.size(), M = grid[0].size();
int cnt = 0;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
if (grid[i][j] == '1')
{
dfs(grid, i, j);
++cnt;
}
}
}
return cnt;
}
}; | 23.736842 | 55 | 0.329268 | [
"vector"
] |
b55f8c494806d3ba0c07fb60955afee507b6f430 | 2,920 | cpp | C++ | Problems/HackerRank/quicksort1/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/HackerRank/quicksort1/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/HackerRank/quicksort1/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <chrono>
using namespace std;
vector<string> split_string(string);
// Complete the quickSort function below.
vector<int> quickSort(vector<int> arr) {
const int pivot = arr[0];
int smallerFromTheEnd = arr.size() - 1;
int pos = 1;
int pivotPos = 0;
while (pos <= smallerFromTheEnd) {
if (pos == pivotPos) {
pos++;
} else if (arr[pos] == pivot) {
pos++;
continue;
} else if (arr[pos] < pivot) {
swap(arr[pos], arr[pivotPos]);
pivotPos = pos;
pos++;
continue;
} else {
//locate the position from the end which is smaller then pivot and swap them
bool swapped = false;
for (int i = smallerFromTheEnd; i > pos; i--) {
if (arr[i] < pivot) {
swap(arr[i], arr[pos]);
smallerFromTheEnd = i - 1;
swapped = true;
break;
}
}
if (swapped)
continue;
//on the next cycle the item in the arr[pos] will be mvoed to the left partition
//no need to increase pos;
}
//means item is on it's position
pos++;
}
return arr;
}
int main()
{
#ifdef LOCAL_TEST
freopen("input.txt", "rt", stdin);
ostream& fout = cout;
#else
ofstream fout(getenv("OUTPUT_PATH"));
#endif
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split_string(arr_temp_temp);
vector<int> arr(n);
for (int i = 0; i < n; i++) {
int arr_item = stoi(arr_temp[i]);
arr[i] = arr_item;
}
vector<int> result = quickSort(arr);
for (int i = 0; i < result.size(); i++) {
fout << result[i];
if (i != result.size() - 1) {
fout << " ";
}
}
fout << "\n";
#ifndef LOCAL_TEST
fout.close();
#endif
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [](const char &x, const char &y) {
return x == y && x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
| 23.739837 | 114 | 0.532877 | [
"vector"
] |
b5662fda5567edc6002bc27f86f8db1b81d815cd | 6,877 | cpp | C++ | src/netcdf_writer.cpp | landreman/qsc | 1b91dea34bc2981177f3ac2270057bd23135e4b1 | [
"BSD-2-Clause"
] | 1 | 2021-09-22T11:03:21.000Z | 2021-09-22T11:03:21.000Z | src/netcdf_writer.cpp | landreman/qsc | 1b91dea34bc2981177f3ac2270057bd23135e4b1 | [
"BSD-2-Clause"
] | null | null | null | src/netcdf_writer.cpp | landreman/qsc | 1b91dea34bc2981177f3ac2270057bd23135e4b1 | [
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include <valarray>
#include <algorithm>
#include <stdexcept>
#include <iomanip>
#include <sstream>
#include <netcdf.h>
#include "qsc.hpp"
#include "netcdf_writer.hpp"
using namespace qsc;
qsc::NetCDFWriter::NetCDFWriter(std::string filename, bool append) {
int retval;
if (append) {
// Add to an existing netcdf file:
if ((retval = nc_open(filename.c_str(), NC_WRITE, &ncid)))
ERR(retval);
// Go from "data mode" back to "define mode":
if ((retval = nc_redef(ncid)))
ERR(retval);
} else {
// Create a new netcdf file, overwriting any existing one with the same name.
// If you want to store long longs, "|NC_NETCDF4" must be included
// in the file type, but such files cannot be read with
// scipy.io.netcdf.
if ((retval = nc_create(filename.c_str(), NC_CLOBBER, &ncid))) ERR(retval);
}
}
void qsc::NetCDFWriter::ERR(int e) {
throw std::runtime_error(nc_strerror(e));
}
/**
* Create a new dimension.
*/
int qsc::NetCDFWriter::dim(std::string dimname, int val) {
int dim_id, retval;
if ((retval = nc_def_dim(ncid, dimname.c_str(), val, &dim_id)))
ERR(retval);
return dim_id;
}
/**
* Get the id for an existing dimension.
*/
int qsc::NetCDFWriter::get_dim(std::string dimname) {
int dim_id, retval;
if ((retval = nc_inq_dimid(ncid, dimname.c_str(), &dim_id)))
ERR(retval);
return dim_id;
}
/**
* If an empty string is provided, no attribute is written.
*/
void qsc::NetCDFWriter::add_attribute(int var_id, std::string str, std::string units) {
int retval;
if (str.size() > 0) {
if ((retval = nc_put_att_text(ncid, var_id, "description",
str.size(), str.c_str())))
ERR(retval);
}
if (units.size() > 0) {
if ((retval = nc_put_att_text(ncid, var_id, "units",
units.size(), units.c_str())))
ERR(retval);
}
}
void qsc::NetCDFWriter::put(std::string varname, int& val, std::string att, std::string units) {
// Variant for scalar ints
int var_id, retval;
if ((retval = nc_def_var(ncid, varname.c_str(), NC_INT, 0, NULL, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_INT);
pointers.push_back((void*) &val);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(std::string varname, qscfloat& val, std::string att, std::string units) {
// Variant for scalar floats
int var_id, retval;
if ((retval = nc_def_var(ncid, varname.c_str(), QSCFLOAT, 0, NULL, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_FLOAT);
pointers.push_back((void*) &val);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(std::string varname, big& val, std::string att, std::string units) {
// Variant for "bigs".
// Convert results to qscfloat, since long long ints require netcdf4, which scipy.io.netcdf cannot read
qscfloat* floatval = new qscfloat;
*floatval = (qscfloat) val;
int var_id, retval;
//if ((retval = nc_def_var(ncid, varname.c_str(), NC_UINT64, 0, NULL, &var_id)))
if ((retval = nc_def_var(ncid, varname.c_str(), QSCFLOAT, 0, NULL, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_FLOAT);
pointers.push_back((void*) floatval);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(std::string varname, std::string& val, std::string att) {
// Variant for strings. Note that unlike numerical quantities, strings have no units.
int var_id, retval;
// Make a name for the dimensions corresponding to the
int len = val.size();
std::ostringstream converter;
converter << "dim_" << std::setfill('0') << std::setw(5) << len;
std::string dim_str = converter.str();
// See if this dimension already exists:
int dim_id;
retval = nc_inq_dimid(ncid, dim_str.c_str(), &dim_id);
if (retval != NC_NOERR) {
// The dimension does not yet exist, so create it.
if ((retval = nc_def_dim(ncid, dim_str.c_str(), len, &dim_id)))
ERR(retval);
}
// Now that we have a dimension, define the string variable
if ((retval = nc_def_var(ncid, varname.c_str(), NC_CHAR, 1, &dim_id, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_STRING);
pointers.push_back((void*) &val[0]);
std::string units = "";
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(dim_id_type dim_id, std::string varname, std::valarray<int>& val, std::string att, std::string units) {
// Variant for 1D int arrays
int var_id, retval;
if ((retval = nc_def_var(ncid, varname.c_str(), NC_INT, 1, &dim_id, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_INT);
pointers.push_back((void*) &val[0]);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(dim_id_type dim_id, std::string varname, Vector& val, std::string att, std::string units) {
// Variant for 1D float arrays
int var_id, retval;
if ((retval = nc_def_var(ncid, varname.c_str(), QSCFLOAT, 1, &dim_id, &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_FLOAT);
pointers.push_back((void*) &val[0]);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::put(std::vector<dim_id_type> dim_id, std::string varname, qscfloat* pointer, std::string att, std::string units) {
// Variant for ND float arrays for N > 1
// NetCDF wants the order of the dimensions to be reversed compared to the QSC definitions.
// Therefore we make a copy of the array of dimensions, and reverse the order of the copy.
std::vector<dim_id_type> dim_id_reversed(dim_id);
std::reverse(std::begin(dim_id_reversed), std::end(dim_id_reversed));
int var_id, retval;
if ((retval = nc_def_var(ncid, varname.c_str(), QSCFLOAT, dim_id.size(), &dim_id_reversed[0], &var_id)))
ERR(retval);
var_ids.push_back(var_id);
types.push_back(QSC_NC_FLOAT);
pointers.push_back((void*) pointer);
add_attribute(var_id, att, units);
}
void qsc::NetCDFWriter::write_and_close() {
int retval;
// End define mode. This tells netCDF we are done defining metadata.
if ((retval = nc_enddef(ncid))) ERR(retval);
// Write the data
for (int j = 0; j < var_ids.size(); j++) {
if (types[j] == QSC_NC_INT) {
// ints
if ((retval = nc_put_var_int(ncid, var_ids[j], (int*) pointers[j])))
ERR(retval);
} else if (types[j] == QSC_NC_BIG) {
// bigs
std::cout << "About to nc_put a big" << std::endl;
if ((retval = nc_put_var_ulonglong(ncid, var_ids[j], (big*) pointers[j])))
ERR(retval);
} else if (types[j] == QSC_NC_STRING) {
// strings
if ((retval = nc_put_var_text(ncid, var_ids[j], (char*) pointers[j])))
ERR(retval);
} else {
// floats
if ((retval = nc_put_var_qscfloat(ncid, var_ids[j], (qscfloat*) pointers[j])))
ERR(retval);
}
}
// Close the file
if ((retval = nc_close(ncid))) ERR(retval);
}
| 32.747619 | 138 | 0.669187 | [
"vector"
] |
b566c787328a22ffae83f526e24adac0c2cf2e54 | 10,300 | cpp | C++ | QtPropertySerializer.cpp | QtDemo/QtPropertySerializer | 15efdb628c08cfa259fa866955c25302c866ecab | [
"MIT"
] | 1 | 2018-11-14T07:32:04.000Z | 2018-11-14T07:32:04.000Z | QtPropertySerializer.cpp | QtDemo/QtPropertySerializer | 15efdb628c08cfa259fa866955c25302c866ecab | [
"MIT"
] | null | null | null | QtPropertySerializer.cpp | QtDemo/QtPropertySerializer | 15efdb628c08cfa259fa866955c25302c866ecab | [
"MIT"
] | null | null | null | /* --------------------------------------------------------------------------------
* Author: Marcel Paz Goldschen-Ohm
* Email: marcel.goldschen@gmail.com
* -------------------------------------------------------------------------------- */
#include "QtPropertySerializer.h"
#include <QFile>
#include <QJsonDocument>
#include <QMetaObject>
#include <QMetaProperty>
#include <QTextStream>
#include <QVariantList>
namespace QtPropertySerializer
{
QVariantMap serialize(const QObject *object, int childDepth, bool includeReadOnlyProperties, bool includeObjectName)
{
QVariantMap data;
if(!object)
return data;
// Properties.
const QMetaObject *metaObject = object->metaObject();
int propertyCount = metaObject->propertyCount();
for(int i = 0; i < propertyCount; ++i) {
const QMetaProperty metaProperty = metaObject->property(i);
if(metaProperty.isReadable() && (includeReadOnlyProperties || metaProperty.isWritable())) {
const QByteArray propertyName = QByteArray(metaProperty.name());
if(includeObjectName || (propertyName != "objectName")) {
const QVariant propertyValue = object->property(propertyName.constData());
addMappedData(data, propertyName, propertyValue);
}
}
}
foreach(const QByteArray &propertyName, object->dynamicPropertyNames()) {
const QVariant propertyValue = object->property(propertyName.constData());
addMappedData(data, propertyName, propertyValue);
}
// Children.
if(childDepth == -1 || childDepth > 0) {
if(childDepth > 0)
--childDepth;
foreach(QObject *child, object->children()) {
const QByteArray className(child->metaObject()->className());
addMappedData(data, className, serialize(child, childDepth, includeReadOnlyProperties));
}
}
return data;
}
void addMappedData(QVariantMap &data, const QByteArray &key, const QVariant &value)
{
if(data.contains(key)) {
// If data already contains key, make sure key's value is a list and append the input value.
QVariant &existingData = data[key];
if(existingData.type() == QVariant::List) {
QVariantList values = existingData.toList();
values.append(value);
data[key] = values;
} else {
QVariantList values;
values.append(existingData);
values.append(value);
data[key] = values;
}
} else {
data[key] = value;
}
if (value.canConvert<QList<QObject *>>()) {
QList<QObject *> list = qvariant_cast<QList<QObject *> >(value);
QVariantList result;
for (QObject *each : list) {
result.append(QtPropertySerializer::serialize(each));
}
data[key] = result;
}
}
void deserialize(QObject *object, const QVariantMap &data, ObjectFactory *factory)
{
if(!object)
return;
for(QVariantMap::const_iterator i = data.constBegin(); i != data.constEnd(); ++i) {
if(i.value().type() == QVariant::Map) {
// Child object.
QByteArray className = i.key().toUtf8();
const QVariantMap &childData = i.value().toMap();
bool childFound = false;
if(childData.contains("objectName")) {
// If objectName is specified for the child, find the first existing child with matching objectName and className.
QObjectList children = object->findChildren<QObject*>(childData.value("objectName").toString());
foreach(QObject *child, children) {
if(className == QByteArray(child->metaObject()->className())) {
deserialize(child, childData, factory);
childFound = true;
break;
}
}
} else {
// If objectName is NOT specified for the child, find the first existing child with matching className.
foreach(QObject *child, object->children()) {
if(className == QByteArray(child->metaObject()->className())) {
deserialize(child, childData, factory);
childFound = true;
break;
}
}
}
// If we still have not found an existing child, attempt to create one dynamically.
if(!childFound) {
QObject *child = 0;
if(className == QByteArray("QObject"))
child = new QObject;
else if(factory && factory->hasCreator(className))
child = factory->create(className);
if(child) {
child->setParent(object);
deserialize(child, childData, factory);
}
}
} else if(i.value().type() == QVariant::List) {
// List of child objects and/or properties.
QByteArray className = i.key().toUtf8();
const QVariantList &childDataList = i.value().toList();
// Keep track of existing children that have been deserialized.
QObjectList existingChildrenWithClassNameAndObjectName;
QObjectList existingChildrenWithClassName;
foreach(QObject *child, object->children()) {
if(className == QByteArray(child->metaObject()->className())) {
if(!child->objectName().isEmpty())
existingChildrenWithClassNameAndObjectName.append(child);
else
existingChildrenWithClassName.append(child);
}
}
for(QVariantList::const_iterator j = childDataList.constBegin(); j != childDataList.constEnd(); ++j) {
if(j->type() == QVariant::Map) {
// Child object.
const QVariantMap &childData = j->toMap();
bool childFound = false;
if(childData.contains("objectName")) {
// If objectName is specified for the child, find the first existing child with matching objectName and className.
foreach(QObject *child, existingChildrenWithClassNameAndObjectName) {
if(child->objectName() == childData.value("objectName").toString()) {
deserialize(child, childData, factory);
existingChildrenWithClassNameAndObjectName.removeOne(child);
childFound = true;
break;
}
}
}
if(!childFound) {
// If objectName is NOT specified for the child or we could NOT find an object with the same name,
// find the first existing child with matching className.
if(!existingChildrenWithClassName.isEmpty()) {
QObject *child = existingChildrenWithClassName.first();
deserialize(child, childData, factory);
existingChildrenWithClassName.removeOne(child);
childFound = true;
}
}
// If we still havent found an existing child, attempt to create one dynamically.
if(!childFound) {
QObject *child = 0;
if(className == QByteArray("QObject"))
child = new QObject;
else if(factory && factory->hasCreator(className))
child = factory->create(className);
if(child) {
child->setParent(object);
deserialize(child, childData, factory);
}
}
} else {
// Property.
const QByteArray &propertyName = className;
const QVariant &propertyValue = *j;
object->setProperty(propertyName.constData(), propertyValue);
}
}
} else {
// Property.
const QByteArray propertyName = i.key().toUtf8();
const QVariant &propertyValue = i.value();
object->setProperty(propertyName.constData(), propertyValue);
}
}
}
bool readJson(QObject *object, const QString &filePath, ObjectFactory *factory)
{
QFile file(filePath);
if(!file.open(QIODevice::Text | QIODevice::ReadOnly))
return false;
QString buffer = file.readAll();
file.close();
QVariantMap data = QJsonDocument::fromJson(buffer.toUtf8()).toVariant().toMap();
deserialize(object, data, factory);
return true;
}
bool writeJson(QObject *object, const QString &filePath, int childDepth, bool includeReadOnlyProperties, bool includeObjectName)
{
QFile file(filePath);
if(!file.open(QIODevice::Text | QIODevice::WriteOnly))
return false;
QTextStream out(&file);
QVariantMap data = serialize(object, childDepth, includeReadOnlyProperties, includeObjectName);
out << QJsonDocument::fromVariant(data).toJson(QJsonDocument::Indented);
file.close();
return true;
}
} // QtPropertySerializer
| 47.465438 | 142 | 0.503981 | [
"object"
] |
b56b6b93e36a3b79a4fe5f343b97d4fb407fd3c6 | 3,074 | cpp | C++ | Server-Client/LinearPrediction.cpp | matzar/SFML-Networking | 2623ae7c38ada2dfcbbdf725345222e58a86336b | [
"MIT"
] | null | null | null | Server-Client/LinearPrediction.cpp | matzar/SFML-Networking | 2623ae7c38ada2dfcbbdf725345222e58a86336b | [
"MIT"
] | null | null | null | Server-Client/LinearPrediction.cpp | matzar/SFML-Networking | 2623ae7c38ada2dfcbbdf725345222e58a86336b | [
"MIT"
] | null | null | null | #include "LinearPrediction.h"
LinearPrediction::LinearPrediction() {}
LinearPrediction::~LinearPrediction() {}
void LinearPrediction::keepTrackOfLinearLocalPositoins(const Message& local_message)
{
if (local_message_history.size() >= linear_message_number) local_message_history.pop();
local_message_history.push(local_message);
}
void LinearPrediction::keepTrackOfLinearNetworkPositions(const Message& message_receive)
{
if (network_message_history.size() >= linear_message_number) network_message_history.pop();
network_message_history.push(message_receive);
}
sf::Vector2f LinearPrediction::predictLinearLocalPath(sf::Vector2f& msg0_local_position, sf::Vector2f& msg1_local_position,
float& msg0_time, float& msg1_time, float& time)
{
float x_average_velocity, y_average_velocity;
// average velocity = (recieved_position - last_position) / (recieved_time - last_time)
x_average_velocity = (msg0_local_position.x - msg1_local_position.x) / (msg0_time - msg1_time);
y_average_velocity = (msg0_local_position.y - msg1_local_position.y) / (msg0_time - msg1_time);
//// linear model
float x_, y_;
x_ = x_average_velocity * (time - msg1_time) + msg1_local_position.x;
y_ = y_average_velocity * (time - msg1_time) + msg1_local_position.y;
sf::Vector2f local_player_pos(x_, y_);
return local_player_pos;
}
sf::Vector2f LinearPrediction::predictLinearNetworkPath(sf::Vector2f& msg0_network_position, sf::Vector2f& msg1_network_position,
float& msg0_time, float& msg1_time, float& time)
{
float x_average_velocity, y_average_velocity, x_, y_;
// average velocity = (recieved_position - last_position) / (recieved_time - last_time)
x_average_velocity = (msg0_network_position.x - msg1_network_position.x) / (msg0_time - msg1_time);
y_average_velocity = (msg0_network_position.y - msg1_network_position.y) / (msg0_time - msg1_time);
// linear model
x_ = x_average_velocity * (time - msg1_time) + msg1_network_position.x;
y_ = y_average_velocity * (time - msg1_time) + msg1_network_position.y;
sf::Vector2f network_player_pos(x_, y_);
return network_player_pos;
}
// pass local position vectors and network position vectors of the sprite
sf::Vector2f LinearPrediction::linearInterpolation(Sprite& sprite,
sf::Vector2f& msg0_local_position,
sf::Vector2f& msg1_local_position,
sf::Vector2f& msg0_network_position,
sf::Vector2f& msg1_network_position,
float& msg0_time,
float& msg1_time,
const sf::Int32& tm,
const bool& lerp_mode)
{
float time = (float)tm;
// TODO
sf::Vector2f local_path = predictLinearLocalPath(msg0_local_position,
msg1_local_position,
msg0_time,
msg1_time,
time);
sf::Vector2f network_path = predictLinearNetworkPath(msg0_network_position,
msg1_network_position,
msg0_time,
msg1_time,
time);
//lerp path works better with 100ms lag
sf::Vector2f lerp_position = lerp(local_path, network_path, 0.1);
// set player_position
lerp_mode ? sprite.setPosition(lerp_position) : sprite.setPosition(network_path);
// add lerped to the history of the local posistions
return lerp_position;
}
| 35.333333 | 129 | 0.783344 | [
"model"
] |
b56b96ed15d1bf2f3dc97d2d08d4b7b2c4b40de4 | 1,181 | cc | C++ | src/dialog.cc | baptisteesteban/OpenGL-Project-V2 | e18fca7468c12c0fde77e56e7ce16ebae02833db | [
"MIT"
] | null | null | null | src/dialog.cc | baptisteesteban/OpenGL-Project-V2 | e18fca7468c12c0fde77e56e7ce16ebae02833db | [
"MIT"
] | null | null | null | src/dialog.cc | baptisteesteban/OpenGL-Project-V2 | e18fca7468c12c0fde77e56e7ce16ebae02833db | [
"MIT"
] | null | null | null | #include <dialog.hh>
#include <iostream>
Dialog::Dialog(SDL_GLContext context, SDL_Window* window)
: window_(window)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(window, context);
ImGui_ImplOpenGL3_Init("#version 130");
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window);
}
void Dialog::render(const Camera& camera)
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window_);
ImGui::NewFrame();
ImGui::Begin("Informations");
ImGui::Text("Pos: (%f, %f, %f)", camera.pos_get().x, camera.pos_get().y,
camera.pos_get().z);
ImGui::Text("X axis: (%f, %f, %f)", camera.x_axis_get().x,
camera.x_axis_get().y, camera.x_axis_get().z);
ImGui::Text("Y axis: (%f, %f, %f)", camera.y_axis_get().x,
camera.y_axis_get().y, camera.y_axis_get().z);
ImGui::Text("Z axis: (%f, %f, %f)", camera.z_axis_get().x,
camera.z_axis_get().y, camera.z_axis_get().z);
ImGui::End();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
Dialog::~Dialog()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
}
| 28.804878 | 74 | 0.666384 | [
"render"
] |
b577a80ddda13940ce752405e548c90b3c885a3b | 7,205 | cpp | C++ | src/chunk_system.cpp | olekolek1000/multipixel | 74760f92c6d9cf2be5f05cebc5b10780136f2662 | [
"BSD-3-Clause"
] | 4 | 2022-02-07T09:57:58.000Z | 2022-02-27T23:03:07.000Z | src/chunk_system.cpp | olekolek1000/multipixel | 74760f92c6d9cf2be5f05cebc5b10780136f2662 | [
"BSD-3-Clause"
] | null | null | null | src/chunk_system.cpp | olekolek1000/multipixel | 74760f92c6d9cf2be5f05cebc5b10780136f2662 | [
"BSD-3-Clause"
] | null | null | null | #include "chunk_system.hpp"
#include "chunk.hpp"
#include "room.hpp"
#include "server.hpp"
#include "session.hpp"
#include "util/timestep.hpp"
#include "util/types.hpp"
#include <cassert>
#include <mutex>
#include <thread>
#include <vector>
static const char *LOG_CHUNK = "ChunkSystem";
ChunkSystem::ChunkSystem(Room *room)
: room(room) {
running = true;
needs_garbage_collect = false;
step_ticks.setRate(20);
thr_runner = std::thread([this] {
runner();
});
room->dispatcher_session_remove.add(listener_session_remove, [this](Session *removing_session) {
LockGuard lock(mtx_access);
// For every chunk
for(auto &i : chunks) { // X
for(auto &j : i.second) { // Y
auto *chunk = j.second.get();
deannounceChunkForSession_nolock(removing_session, chunk->getPosition());
}
}
});
}
ChunkSystem::~ChunkSystem() {
running = false;
if(thr_runner.joinable())
thr_runner.join();
}
Chunk *ChunkSystem::getChunk(Int2 chunk_pos) {
LockGuard lock(mtx_access);
return getChunk_nolock(chunk_pos);
}
Chunk *ChunkSystem::getChunk_nolock(Int2 chunk_pos) {
if(last_accessed_chunk_cache && last_accessed_chunk_cache->position == chunk_pos)
return last_accessed_chunk_cache;
auto &horizontal = chunks[chunk_pos.x];
auto it = horizontal.find(chunk_pos.y);
if(it == horizontal.end()) {
SharedVector<u8> compressed_chunk_data;
{
// Load chunk pixels from database
room->database.lock();
auto record = room->database.chunkLoadData(chunk_pos);
room->database.unlock();
if(!record.data || !record.data->empty())
compressed_chunk_data = record.data;
}
// Chunk not found, create new chunk
auto &cell = horizontal[chunk_pos.y];
cell.create(this, chunk_pos, compressed_chunk_data);
last_accessed_chunk_cache = cell.get();
return cell.get();
} else {
last_accessed_chunk_cache = it->second.get();
return it->second.get();
}
}
bool ChunkSystem::getPixel(Int2 global_pixel_pos, u8 *r, u8 *g, u8 *b) {
LockGuard lock(mtx_access);
auto chunk_pos = globalPixelPosToChunkPos(global_pixel_pos);
auto local_pixel_pos = globalPixelPosToLocalPixelPos(global_pixel_pos);
auto *chunk = getChunk_nolock(chunk_pos);
chunk->lock();
chunk->allocateImage_nolock();
chunk->getPixel_nolock(local_pixel_pos, r, g, b);
chunk->unlock();
return true;
}
Int2 ChunkSystem::globalPixelPosToChunkPos(Int2 pixel_pos) {
s32 chunkX = (pixel_pos.x + (pixel_pos.x < 0 ? 1 : 0)) / (s32)getChunkSize();
s32 chunkY = (pixel_pos.y + (pixel_pos.y < 0 ? 1 : 0)) / (s32)getChunkSize();
if(pixel_pos.x < 0)
chunkX--;
if(pixel_pos.y < 0)
chunkY--;
return {chunkX, chunkY};
}
int modulo(int x, int n) {
return (x % n + n) % n;
}
UInt2 ChunkSystem::globalPixelPosToLocalPixelPos(Int2 global_pixel_pos) {
auto chunk_size = (s32)getChunkSize();
s32 x = modulo(global_pixel_pos.x, chunk_size);
s32 y = modulo(global_pixel_pos.y, chunk_size);
// Can be removed later
assert(x >= 0 && y >= 0 && x < chunk_size && y < chunk_size);
return {(u32)x, (u32)y};
}
void ChunkSystem::announceChunkForSession(Session *session, Int2 chunk_pos) {
LockGuard lock(mtx_access);
announceChunkForSession_nolock(session, chunk_pos);
}
void ChunkSystem::deannounceChunkForSession(Session *session, Int2 chunk_pos) {
LockGuard lock(mtx_access);
deannounceChunkForSession_nolock(session, chunk_pos);
}
void ChunkSystem::announceChunkForSession_nolock(Session *session, Int2 chunk_pos) {
auto *chunk = getChunk_nolock(chunk_pos);
session->linkChunk(chunk);
chunk->linkSession(session);
}
void ChunkSystem::deannounceChunkForSession_nolock(Session *session, Int2 chunk_pos) {
auto *chunk = getChunk_nolock(chunk_pos);
session->unlinkChunk(chunk);
chunk->unlinkSession(session);
}
void ChunkSystem::autosave() {
auto start = getMillis();
LockGuard lock(mtx_access);
std::vector<Chunk *> to_autosave;
u32 total_chunk_count = 0;
u32 saved_chunk_count = 0;
auto transaction = room->database.transactionBegin();
for(auto &i : chunks) {
for(auto &j : i.second) {
auto *chunk = j.second.get();
total_chunk_count++;
if(chunk->isModified()) {
saveChunk_nolock(chunk);
saved_chunk_count++;
}
}
}
transaction->commit();
if(saved_chunk_count) {
u32 dur = getMillis() - start;
room->log(LOG_CHUNK, "Autosaved %u chunks in %ums (%u chunks loaded)", saved_chunk_count, dur, total_chunk_count);
}
}
void ChunkSystem::saveChunk_nolock(Chunk *chunk) {
auto chunk_data = chunk->encodeChunkData(true);
room->database.chunkSaveData(chunk->getPosition(), chunk_data->data(), chunk_data->size(), CompressionType::LZ4);
}
void ChunkSystem::removeChunk_nolock(Chunk *to_remove) {
if(to_remove == last_accessed_chunk_cache)
last_accessed_chunk_cache = nullptr;
for(auto it = chunks.begin(); it != chunks.end(); it++) {
for(auto jt = it->second.begin(); jt != it->second.end();) {
if(jt->second.get() == to_remove) {
it->second.erase(jt);
// Remove empty map row
if(it->second.empty())
it = chunks.erase(it);
return;
} else {
jt++;
}
}
}
}
void ChunkSystem::markGarbageCollect() {
needs_garbage_collect = true;
}
void ChunkSystem::runner() {
last_autosave_timestamp = getMillis();
last_garbage_collect_timestamp = getMillis();
while(running) {
bool used = runner_tick();
if(!used) {
// Idle
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
autosave();
}
#define AUTOSAVE_INTERVAL 5000
bool ChunkSystem::runner_tick() {
bool used = false;
auto millis = getMillis();
if(last_autosave_timestamp + AUTOSAVE_INTERVAL < millis) { // Autosave
autosave();
last_autosave_timestamp = millis;
}
if(last_garbage_collect_timestamp + 10000 < millis) {
needs_garbage_collect = true;
last_garbage_collect_timestamp = millis;
}
// Atomic operation:
// if(needs_garbage_collect) { needs_garbage_collect = false; (...) }
if(needs_garbage_collect.exchange(false)) {
LockGuard lock(mtx_access);
bool done = false;
// Informational use only
u32 saved_chunk_count = 0;
u32 removed_chunk_count = 0;
u32 loaded_chunk_count = 0;
do {
done = true;
loaded_chunk_count = 0;
// Iterate all loaded chunks as long as all chunks are deallocated
for(auto &i : chunks) {
loaded_chunk_count += i.second.size();
for(auto &j : i.second) {
auto *chunk = j.second.get();
if(chunk->isLinkedSessionsEmpty()) {
// Save chunk data to database (only if modified)
if(chunk->isModified()) {
saved_chunk_count++;
room->database.lock();
saveChunk_nolock(chunk);
room->database.unlock();
}
removed_chunk_count++;
removeChunk_nolock(chunk);
done = false;
goto breakloop;
}
}
}
breakloop:;
} while(!done);
if(saved_chunk_count || removed_chunk_count)
room->log(LOG_CHUNK, "Saved %u chunks, %u total chunks loaded, %u removed (GC))", saved_chunk_count, loaded_chunk_count, removed_chunk_count);
}
while(step_ticks.onTick()) {
used = true;
if(ticks % 2 == 0) {
LockGuard lock(mtx_access);
for(auto &i : chunks) {
for(auto &j : i.second) {
j.second->flushQueuedPixels();
}
}
}
ticks++;
}
return used;
} | 24.09699 | 145 | 0.69424 | [
"vector"
] |
b5835af55c79bf59c43e008540fab31f40e15be8 | 12,969 | cpp | C++ | artifact/storm/src/test/storm/solver/FullySymbolicGameSolverTest.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/test/storm/solver/FullySymbolicGameSolverTest.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/test/storm/solver/FullySymbolicGameSolverTest.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "test/storm_gtest.h"
#include "storm-config.h"
#include "storm/storage/dd/DdManager.h"
#include "storm/utility/solver.h"
#include "storm/settings/SettingsManager.h"
#include "storm/environment/Environment.h"
#include "storm/solver/SymbolicGameSolver.h"
#include "storm/settings/modules/NativeEquationSolverSettings.h"
TEST(FullySymbolicGameSolverTest, Solve_Cudd) {
storm::Environment env;
// Create some variables.
std::shared_ptr<storm::dd::DdManager<storm::dd::DdType::CUDD>> manager(new storm::dd::DdManager<storm::dd::DdType::CUDD>());
std::pair<storm::expressions::Variable, storm::expressions::Variable> state = manager->addMetaVariable("x", 1, 4);
std::pair<storm::expressions::Variable, storm::expressions::Variable> pl1 = manager->addMetaVariable("a", 0, 1);
std::pair<storm::expressions::Variable, storm::expressions::Variable> pl2 = manager->addMetaVariable("b", 0, 1);
storm::dd::Bdd<storm::dd::DdType::CUDD> allRows = manager->getBddZero();
std::set<storm::expressions::Variable> rowMetaVariables({state.first});
std::set<storm::expressions::Variable> columnMetaVariables({state.second});
std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> rowColumnMetaVariablePairs = {state};
std::set<storm::expressions::Variable> player1Variables({pl1.first});
std::set<storm::expressions::Variable> player2Variables({pl2.first});
// Construct simple game.
storm::dd::Add<storm::dd::DdType::CUDD, double> matrix = manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 2).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.6);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 1).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.4);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 2).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant(0.2);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 3).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant(0.8);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 3).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.5);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 4).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.5);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 1).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant<double>(1);
std::unique_ptr<storm::solver::SymbolicGameSolverFactory<storm::dd::DdType::CUDD, double>> solverFactory(new storm::solver::SymbolicGameSolverFactory<storm::dd::DdType::CUDD, double>());
storm::dd::Bdd<storm::dd::DdType::CUDD> tmp = matrix.toBdd().existsAbstract({state.second});
storm::dd::Bdd<storm::dd::DdType::CUDD> illegalPlayer2Mask = !tmp && manager->getRange(state.first);
storm::dd::Bdd<storm::dd::DdType::CUDD> illegalPlayer1Mask = tmp.existsAbstract({pl2.first});
illegalPlayer2Mask &= illegalPlayer1Mask;
illegalPlayer1Mask &= !illegalPlayer1Mask && manager->getRange(state.first);
std::unique_ptr<storm::solver::SymbolicGameSolver<storm::dd::DdType::CUDD>> solver = solverFactory->create(matrix, allRows, illegalPlayer1Mask, illegalPlayer2Mask, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs, player1Variables, player2Variables);
// Create solution and target state vector.
storm::dd::Add<storm::dd::DdType::CUDD, double> x = manager->template getAddZero<double>();
storm::dd::Add<storm::dd::DdType::CUDD, double> b = manager->getEncoding(state.first, 2).template toAdd<double>() + manager->getEncoding(state.first, 4).template toAdd<double>();
// Now solve the game with different strategies for the players.
storm::dd::Add<storm::dd::DdType::CUDD> result = solver->solveGame(env, storm::OptimizationDirection::Minimize, storm::OptimizationDirection::Minimize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Minimize, storm::OptimizationDirection::Maximize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.5, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Maximize, storm::OptimizationDirection::Minimize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.2, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Maximize, storm::OptimizationDirection::Maximize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.99999892625817599, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
}
TEST(FullySymbolicGameSolverTest, Solve_Sylvan) {
storm::Environment env;
// Create some variables.
std::shared_ptr<storm::dd::DdManager<storm::dd::DdType::Sylvan>> manager(new storm::dd::DdManager<storm::dd::DdType::Sylvan>());
std::pair<storm::expressions::Variable, storm::expressions::Variable> state = manager->addMetaVariable("x", 1, 4);
std::pair<storm::expressions::Variable, storm::expressions::Variable> pl1 = manager->addMetaVariable("a", 0, 1);
std::pair<storm::expressions::Variable, storm::expressions::Variable> pl2 = manager->addMetaVariable("b", 0, 1);
storm::dd::Bdd<storm::dd::DdType::Sylvan> allRows = manager->getBddZero();
std::set<storm::expressions::Variable> rowMetaVariables({state.first});
std::set<storm::expressions::Variable> columnMetaVariables({state.second});
std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> rowColumnMetaVariablePairs = {state};
std::set<storm::expressions::Variable> player1Variables({pl1.first});
std::set<storm::expressions::Variable> player2Variables({pl2.first});
// Construct simple game.
storm::dd::Add<storm::dd::DdType::Sylvan, double> matrix = manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 2).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.6);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 1).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.4);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 2).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant(0.2);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 3).template toAdd<double>() * manager->getEncoding(pl1.first, 0).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant(0.8);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 3).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.5);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 4).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 0).template toAdd<double>() * manager->getConstant(0.5);
matrix += manager->getEncoding(state.first, 1).template toAdd<double>() * manager->getEncoding(state.second, 1).template toAdd<double>() * manager->getEncoding(pl1.first, 1).template toAdd<double>() * manager->getEncoding(pl2.first, 1).template toAdd<double>() * manager->getConstant<double>(1);
std::unique_ptr<storm::solver::SymbolicGameSolverFactory<storm::dd::DdType::Sylvan, double>> solverFactory(new storm::solver::SymbolicGameSolverFactory<storm::dd::DdType::Sylvan, double>());
storm::dd::Bdd<storm::dd::DdType::Sylvan> tmp = matrix.toBdd().existsAbstract({state.second});
storm::dd::Bdd<storm::dd::DdType::Sylvan> illegalPlayer2Mask = !tmp && manager->getRange(state.first);
storm::dd::Bdd<storm::dd::DdType::Sylvan> illegalPlayer1Mask = tmp.existsAbstract({pl2.first});
illegalPlayer2Mask &= illegalPlayer1Mask;
illegalPlayer1Mask &= !illegalPlayer1Mask && manager->getRange(state.first);
std::unique_ptr<storm::solver::SymbolicGameSolver<storm::dd::DdType::Sylvan>> solver = solverFactory->create(matrix, allRows, illegalPlayer1Mask, illegalPlayer2Mask, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs, player1Variables,player2Variables);
// Create solution and target state vector.
storm::dd::Add<storm::dd::DdType::Sylvan, double> x = manager->template getAddZero<double>();
storm::dd::Add<storm::dd::DdType::Sylvan, double> b = manager->getEncoding(state.first, 2).template toAdd<double>() + manager->getEncoding(state.first, 4).template toAdd<double>();
// Now solve the game with different strategies for the players.
storm::dd::Add<storm::dd::DdType::Sylvan> result = solver->solveGame(env, storm::OptimizationDirection::Minimize, storm::OptimizationDirection::Minimize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Minimize, storm::OptimizationDirection::Maximize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.5, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Maximize, storm::OptimizationDirection::Minimize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.2, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
x = manager->getAddZero<double>();
result = solver->solveGame(env, storm::OptimizationDirection::Maximize, storm::OptimizationDirection::Maximize, x, b);
result *= manager->getEncoding(state.first, 1).template toAdd<double>();
result = result.sumAbstract({state.first});
EXPECT_NEAR(0.99999892625817599, result.getValue(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision());
}
| 90.0625 | 342 | 0.729355 | [
"vector"
] |
b5843459860b6d8d12385666f7a686b6096283a8 | 2,366 | hpp | C++ | src/efscape/impl/RunSim.hpp | clinejc/efscape | ef8bbf272827c7b364aa02af33dc5d239f070e0b | [
"0BSD"
] | 1 | 2019-07-29T07:44:13.000Z | 2019-07-29T07:44:13.000Z | src/efscape/impl/RunSim.hpp | clinejc/efscape | ef8bbf272827c7b364aa02af33dc5d239f070e0b | [
"0BSD"
] | null | null | null | src/efscape/impl/RunSim.hpp | clinejc/efscape | ef8bbf272827c7b364aa02af33dc5d239f070e0b | [
"0BSD"
] | 1 | 2019-07-11T10:49:48.000Z | 2019-07-11T10:49:48.000Z | // __COPYRIGHT_START__
// Package Name : efscape
// File Name : RunSim.hpp
// Copyright (C) 2006-2018 Jon C. Cline
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
// __COPYRIGHT_END__
#ifndef EFSCAPE_UTILS_RUNSIM_HH
#define EFSCAPE_UTILS_RUNSIM_HH
#include <efscape/utils/CommandOpt.hpp>
namespace efscape {
namespace impl {
/**
* Implements a simple model simulation runner for the efscape modeling
* framework. It provides a command-line interface derived from the
* CommandOpt class. The command 'efdriver' takes a parameter file name
* as input. There are 3 different types of valid input files:\n
*
* 1. Model parameter for in JSON format (see model metadata)
* 2. Cereal serialization JSON format
* 3. Boost serialiation XML format
*
* If an input file is not specified, the user will be prompted to
* select one of the available models, from which a valid parameter file
* will be generated.
*
* @author Jon Cline <jon.c.cline@gmail.com>
* @version 1.0.1 created 01 Feb 2008, revised 26 May 2018
*/
class RunSim : public efscape::utils::CommandOpt
{
public:
RunSim();
virtual ~RunSim();
int parse_options( int argc, char *argv[]);
int execute();
const char* program_name();
const char* program_version();
static const char* ProgramName();
protected:
void usage( int exit_value = 0 );
private:
/** program name */
static const char* mScp_program_name;
/** program version */
static const char* mScp_program_version;
};
}
}
#endif // #ifndef EFSCAPE_UTILS_RUNSIM_HH
| 31.546667 | 158 | 0.693576 | [
"model"
] |
b588e8f9306faf58dfdd5f1951808ba4801398e0 | 12,207 | cpp | C++ | indra/newview/llpanelmediasettingssecurity.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/newview/llpanelmediasettingssecurity.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | null | null | null | indra/newview/llpanelmediasettingssecurity.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file llpanelmediasettingssecurity.cpp
* @brief LLPanelMediaSettingsSecurity class implementation
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llpanelmediasettingssecurity.h"
#include "llfloaterreg.h"
#include "llpanelcontents.h"
#include "llcheckboxctrl.h"
#include "llnotificationsutil.h"
#include "llscrolllistctrl.h"
#include "llscrolllistitem.h"
#include "lluictrlfactory.h"
#include "llwindow.h"
#include "llviewerwindow.h"
#include "llsdutil.h"
#include "llselectmgr.h"
#include "llmediaentry.h"
#include "lltextbox.h"
#include "llfloaterwhitelistentry.h"
#include "llfloatermediasettings.h"
////////////////////////////////////////////////////////////////////////////////
//
LLPanelMediaSettingsSecurity::LLPanelMediaSettingsSecurity() :
mParent( NULL )
{
mCommitCallbackRegistrar.add("Media.whitelistAdd", boost::bind(&LLPanelMediaSettingsSecurity::onBtnAdd, this));
mCommitCallbackRegistrar.add("Media.whitelistDelete", boost::bind(&LLPanelMediaSettingsSecurity::onBtnDel, this));
// build dialog from XML
buildFromFile( "panel_media_settings_security.xml");
}
////////////////////////////////////////////////////////////////////////////////
//
BOOL LLPanelMediaSettingsSecurity::postBuild()
{
mEnableWhiteList = getChild< LLCheckBoxCtrl >( LLMediaEntry::WHITELIST_ENABLE_KEY );
mWhiteListList = getChild< LLScrollListCtrl >( LLMediaEntry::WHITELIST_KEY );
mHomeUrlFailsWhiteListText = getChild<LLTextBox>( "home_url_fails_whitelist" );
setDefaultBtn("whitelist_add");
return true;
}
////////////////////////////////////////////////////////////////////////////////
// virtual
LLPanelMediaSettingsSecurity::~LLPanelMediaSettingsSecurity()
{
}
////////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::draw()
{
// housekeeping
LLPanel::draw();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLPanelMediaSettingsSecurity::initValues( void* userdata, const LLSD& media_settings , bool editable)
{
LLPanelMediaSettingsSecurity *self =(LLPanelMediaSettingsSecurity *)userdata;
std::string base_key( "" );
std::string tentative_key( "" );
struct
{
std::string key_name;
LLUICtrl* ctrl_ptr;
std::string ctrl_type;
} data_set [] =
{
{ LLMediaEntry::WHITELIST_ENABLE_KEY, self->mEnableWhiteList, "LLCheckBoxCtrl" },
{ LLMediaEntry::WHITELIST_KEY, self->mWhiteListList, "LLScrollListCtrl" },
{ "", NULL , "" }
};
for( int i = 0; data_set[ i ].key_name.length() > 0; ++i )
{
base_key = std::string( data_set[ i ].key_name );
tentative_key = base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX );
bool enabled_overridden = false;
// TODO: CP - I bet there is a better way to do this using Boost
if ( media_settings[ base_key ].isDefined() )
{
if ( data_set[ i ].ctrl_type == "LLCheckBoxCtrl" )
{
static_cast< LLCheckBoxCtrl* >( data_set[ i ].ctrl_ptr )->
setValue( media_settings[ base_key ].asBoolean() );
}
else
if ( data_set[ i ].ctrl_type == "LLScrollListCtrl" )
{
// get control
LLScrollListCtrl* list = static_cast< LLScrollListCtrl* >( data_set[ i ].ctrl_ptr );
list->deleteAllItems();
// points to list of white list URLs
LLSD url_list = media_settings[ base_key ];
// better be the whitelist
llassert(data_set[ i ].ctrl_ptr == self->mWhiteListList);
// If tentative, don't add entries
if (media_settings[ tentative_key ].asBoolean())
{
self->mWhiteListList->setEnabled(false);
enabled_overridden = true;
}
else {
// iterate over them and add to scroll list
LLSD::array_iterator iter = url_list.beginArray();
while( iter != url_list.endArray() )
{
std::string entry = *iter;
self->addWhiteListEntry( entry );
++iter;
}
}
};
if ( ! enabled_overridden) data_set[ i ].ctrl_ptr->setEnabled(editable);
data_set[ i ].ctrl_ptr->setTentative( media_settings[ tentative_key ].asBoolean() );
};
};
// initial update - hides/shows status messages etc.
self->updateWhitelistEnableStatus();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLPanelMediaSettingsSecurity::clearValues( void* userdata , bool editable)
{
LLPanelMediaSettingsSecurity *self =(LLPanelMediaSettingsSecurity *)userdata;
self->mEnableWhiteList->clear();
self->mWhiteListList->deleteAllItems();
self->mEnableWhiteList->setEnabled(editable);
self->mWhiteListList->setEnabled(editable);
}
////////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::preApply()
{
// no-op
}
////////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::getValues( LLSD &fill_me_in, bool include_tentative )
{
if (include_tentative || !mEnableWhiteList->getTentative())
fill_me_in[LLMediaEntry::WHITELIST_ENABLE_KEY] = (LLSD::Boolean)mEnableWhiteList->getValue();
if (include_tentative || !mWhiteListList->getTentative())
{
// iterate over white list and extract items
std::vector< LLScrollListItem* > whitelist_items = mWhiteListList->getAllData();
std::vector< LLScrollListItem* >::iterator iter = whitelist_items.begin();
// *NOTE: need actually set the key to be an emptyArray(), or the merge
// we do with this LLSD will think there's nothing to change.
fill_me_in[LLMediaEntry::WHITELIST_KEY] = LLSD::emptyArray();
while( iter != whitelist_items.end() )
{
LLScrollListCell* cell = (*iter)->getColumn( ENTRY_COLUMN );
std::string whitelist_url = cell->getValue().asString();
fill_me_in[ LLMediaEntry::WHITELIST_KEY ].append( whitelist_url );
++iter;
};
}
}
////////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::postApply()
{
// no-op
}
///////////////////////////////////////////////////////////////////////////////
// Try to make a valid URL if a fragment (
// white list list box widget and build a list to test against. Can also
const std::string LLPanelMediaSettingsSecurity::makeValidUrl( const std::string& src_url )
{
// use LLURI to determine if we have a valid scheme
LLURI candidate_url( src_url );
if ( candidate_url.scheme().empty() )
{
// build a URL comprised of default scheme and the original fragment
const std::string default_scheme( "http://" );
return default_scheme + src_url;
};
// we *could* test the "default scheme" + "original fragment" URL again
// using LLURI to see if it's valid but I think the outcome is the same
// in either case - our only option is to return the original URL
// we *think* the original url passed in was valid
return src_url;
}
///////////////////////////////////////////////////////////////////////////////
// wrapper for testing a URL against the whitelist. We grab entries from
// white list list box widget and build a list to test against.
bool LLPanelMediaSettingsSecurity::urlPassesWhiteList( const std::string& test_url )
{
// If the whitlelist list is tentative, it means we have multiple settings.
// In that case, we have no choice but to return true
if ( mWhiteListList->getTentative() ) return true;
// the checkUrlAgainstWhitelist(..) function works on a vector
// of strings for the white list entries - in this panel, the white list
// is stored in the widgets themselves so we need to build something compatible.
std::vector< std::string > whitelist_strings;
whitelist_strings.clear(); // may not be required - I forget what the spec says.
// step through whitelist widget entries and grab them as strings
std::vector< LLScrollListItem* > whitelist_items = mWhiteListList->getAllData();
std::vector< LLScrollListItem* >::iterator iter = whitelist_items.begin();
while( iter != whitelist_items.end() )
{
LLScrollListCell* cell = (*iter)->getColumn( ENTRY_COLUMN );
std::string whitelist_url = cell->getValue().asString();
whitelist_strings.push_back( whitelist_url );
++iter;
};
// possible the URL is just a fragment so we validize it
const std::string valid_url = makeValidUrl( test_url );
// indicate if the URL passes whitelist
return LLMediaEntry::checkUrlAgainstWhitelist( valid_url, whitelist_strings );
}
///////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::updateWhitelistEnableStatus()
{
// get the value for home URL and make it a valid URL
const std::string valid_url = makeValidUrl( mParent->getHomeUrl() );
// now check to see if the home url passes the whitelist in its entirity
if ( urlPassesWhiteList( valid_url ) )
{
mEnableWhiteList->setEnabled( true );
mHomeUrlFailsWhiteListText->setVisible( false );
}
else
{
mEnableWhiteList->set( false );
mEnableWhiteList->setEnabled( false );
mHomeUrlFailsWhiteListText->setVisible( true );
};
}
///////////////////////////////////////////////////////////////////////////////
// Add an entry to the whitelist scrollbox and indicate if the current
// home URL passes this entry or not using an icon
void LLPanelMediaSettingsSecurity::addWhiteListEntry( const std::string& entry )
{
// grab the home url
std::string home_url( "" );
if ( mParent )
home_url = mParent->getHomeUrl();
// try to make a valid URL based on what the user entered - missing scheme for example
const std::string valid_url = makeValidUrl( home_url );
// check the home url against this single whitelist entry
std::vector< std::string > whitelist_entries;
whitelist_entries.push_back( entry );
bool home_url_passes_entry = LLMediaEntry::checkUrlAgainstWhitelist( valid_url, whitelist_entries );
// build an icon cell based on whether or not the home url pases it or not
LLSD row;
if ( home_url_passes_entry || home_url.empty() )
{
row[ "columns" ][ ICON_COLUMN ][ "type" ] = "icon";
row[ "columns" ][ ICON_COLUMN ][ "value" ] = "";
row[ "columns" ][ ICON_COLUMN ][ "width" ] = 20;
}
else
{
row[ "columns" ][ ICON_COLUMN ][ "type" ] = "icon";
row[ "columns" ][ ICON_COLUMN ][ "value" ] = "Parcel_Exp_Color";
row[ "columns" ][ ICON_COLUMN ][ "width" ] = 20;
};
// always add in the entry itself
row[ "columns" ][ ENTRY_COLUMN ][ "type" ] = "text";
row[ "columns" ][ ENTRY_COLUMN ][ "value" ] = entry;
// add to the white list scroll box
mWhiteListList->addElement( row );
};
///////////////////////////////////////////////////////////////////////////////
// static
void LLPanelMediaSettingsSecurity::onBtnAdd( void* userdata )
{
LLFloaterReg::showInstance("whitelist_entry");
}
///////////////////////////////////////////////////////////////////////////////
// static
void LLPanelMediaSettingsSecurity::onBtnDel( void* userdata )
{
LLPanelMediaSettingsSecurity *self =(LLPanelMediaSettingsSecurity *)userdata;
self->mWhiteListList->deleteSelectedItems();
// contents of whitelist changed so recheck it against home url
self->updateWhitelistEnableStatus();
}
////////////////////////////////////////////////////////////////////////////////
//
void LLPanelMediaSettingsSecurity::setParent( LLFloaterMediaSettings* parent )
{
mParent = parent;
};
| 34.193277 | 116 | 0.646269 | [
"vector"
] |
b59a22935aefba1451127db9d6f9e42c67a8e4eb | 12,286 | cc | C++ | mysql-server/sql/dd/impl/types/parameter_impl.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/dd/impl/types/parameter_impl.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/dd/impl/types/parameter_impl.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /* Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql/dd/impl/types/parameter_impl.h"
#include <stddef.h>
#include <set>
#include <sstream>
#include <string>
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "mysqld_error.h"
#include "sql/dd/impl/properties_impl.h" // Properties_impl
#include "sql/dd/impl/raw/raw_record.h" // Raw_record
#include "sql/dd/impl/tables/parameter_type_elements.h" // Parameter_type_elements
#include "sql/dd/impl/tables/parameters.h" // Parameters
#include "sql/dd/impl/transaction_impl.h" // Open_dictionary_tables_ctx
#include "sql/dd/impl/types/parameter_type_element_impl.h" // Parameter_type_element_impl
#include "sql/dd/impl/types/routine_impl.h" // Routine_impl
#include "sql/dd/string_type.h" // dd::String_type
#include "sql/dd/types/object_table.h"
#include "sql/dd/types/parameter_type_element.h"
#include "sql/dd/types/weak_object.h"
using dd::tables::Parameter_type_elements;
using dd::tables::Parameters;
namespace dd {
static const std::set<String_type> default_valid_option_keys = {"geom_type"};
///////////////////////////////////////////////////////////////////////////
// Parameter_impl implementation.
///////////////////////////////////////////////////////////////////////////
Parameter_impl::Parameter_impl()
: m_is_name_null(false),
m_parameter_mode(PM_IN),
m_parameter_mode_null(false),
m_data_type(enum_column_types::LONG),
m_is_zerofill(false),
m_is_unsigned(false),
m_ordinal_position(0),
m_char_length(0),
m_numeric_precision(0),
m_numeric_precision_null(true),
m_numeric_scale(0),
m_numeric_scale_null(true),
m_datetime_precision(0),
m_datetime_precision_null(true),
m_elements(),
m_options(default_valid_option_keys),
m_routine(nullptr),
m_collation_id(INVALID_OBJECT_ID) {}
Parameter_impl::Parameter_impl(Routine_impl *routine)
: m_is_name_null(false),
m_parameter_mode(PM_IN),
m_parameter_mode_null(false),
m_data_type(enum_column_types::LONG),
m_is_zerofill(false),
m_is_unsigned(false),
m_ordinal_position(0),
m_char_length(0),
m_numeric_precision(0),
m_numeric_precision_null(true),
m_numeric_scale(0),
m_numeric_scale_null(true),
m_datetime_precision(0),
m_datetime_precision_null(true),
m_elements(),
m_options(default_valid_option_keys),
m_routine(routine),
m_collation_id(INVALID_OBJECT_ID) {}
///////////////////////////////////////////////////////////////////////////
/* purecov: begin deadcode */
const Routine &Parameter_impl::routine() const { return *m_routine; }
Routine &Parameter_impl::routine() { return *m_routine; }
/* purecov: end */
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::validate() const {
if (!m_routine) {
my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(),
"Parameter does not belong to any routine.");
return true;
}
if (m_collation_id == INVALID_OBJECT_ID) {
my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(),
"Collation ID is not set");
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::restore_children(Open_dictionary_tables_ctx *otx) {
switch (data_type()) {
case enum_column_types::ENUM:
case enum_column_types::SET:
return m_elements.restore_items(
this, otx, otx->get_table<Parameter_type_element>(),
Parameter_type_elements::create_key_by_parameter_id(this->id()));
default:
return false;
}
return false;
}
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::store_children(Open_dictionary_tables_ctx *otx) {
return m_elements.store_items(otx);
}
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::drop_children(Open_dictionary_tables_ctx *otx) const {
if (data_type() == enum_column_types::ENUM ||
data_type() == enum_column_types::SET)
return m_elements.drop_items(
otx, otx->get_table<Parameter_type_element>(),
Parameter_type_elements::create_key_by_parameter_id(this->id()));
return false;
}
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::restore_attributes(const Raw_record &r) {
check_parent_consistency(m_routine,
r.read_ref_id(Parameters::FIELD_ROUTINE_ID));
restore_id(r, Parameters::FIELD_ID);
restore_name(r, Parameters::FIELD_NAME);
m_is_name_null = r.is_null(Parameters::FIELD_NAME);
m_data_type_utf8 = r.read_str(Parameters::FIELD_DATA_TYPE_UTF8);
m_is_zerofill = r.read_bool(Parameters::FIELD_IS_ZEROFILL);
m_is_unsigned = r.read_bool(Parameters::FIELD_IS_UNSIGNED);
m_parameter_mode = (enum_parameter_mode)r.read_int(Parameters::FIELD_MODE);
m_parameter_mode_null = r.is_null(Parameters::FIELD_MODE);
m_data_type = (enum_column_types)r.read_int(Parameters::FIELD_DATA_TYPE);
m_ordinal_position = r.read_uint(Parameters::FIELD_ORDINAL_POSITION);
m_char_length = r.read_uint(Parameters::FIELD_CHAR_LENGTH);
m_numeric_precision = r.read_uint(Parameters::FIELD_NUMERIC_PRECISION);
m_numeric_precision_null = r.is_null(Parameters::FIELD_NUMERIC_PRECISION);
m_numeric_scale = r.read_uint(Parameters::FIELD_NUMERIC_SCALE);
m_numeric_scale_null = r.is_null(Parameters::FIELD_NUMERIC_SCALE);
m_datetime_precision = r.read_uint(Parameters::FIELD_DATETIME_PRECISION);
m_datetime_precision_null = r.is_null(Parameters::FIELD_DATETIME_PRECISION);
m_collation_id = r.read_ref_id(Parameters::FIELD_COLLATION_ID);
set_options(r.read_str(Parameters::FIELD_OPTIONS, ""));
return false;
}
///////////////////////////////////////////////////////////////////////////
bool Parameter_impl::store_attributes(Raw_record *r) {
return store_id(r, Parameters::FIELD_ID) ||
store_name(r, Parameters::FIELD_NAME, m_is_name_null) ||
r->store(Parameters::FIELD_ROUTINE_ID, m_routine->id()) ||
r->store(Parameters::FIELD_ORDINAL_POSITION, m_ordinal_position) ||
r->store(Parameters::FIELD_DATA_TYPE_UTF8, m_data_type_utf8) ||
r->store(Parameters::FIELD_MODE, m_parameter_mode,
m_parameter_mode_null) ||
r->store(Parameters::FIELD_DATA_TYPE, static_cast<int>(m_data_type)) ||
r->store(Parameters::FIELD_IS_ZEROFILL, m_is_zerofill) ||
r->store(Parameters::FIELD_IS_UNSIGNED, m_is_unsigned) ||
r->store(Parameters::FIELD_CHAR_LENGTH,
static_cast<uint>(m_char_length)) ||
r->store(Parameters::FIELD_NUMERIC_PRECISION, m_numeric_precision,
m_numeric_precision_null) ||
r->store(Parameters::FIELD_NUMERIC_SCALE, m_numeric_scale,
m_numeric_scale_null) ||
r->store(Parameters::FIELD_DATETIME_PRECISION, m_datetime_precision,
m_datetime_precision_null) ||
r->store_ref_id(Parameters::FIELD_COLLATION_ID, m_collation_id) ||
r->store(Parameters::FIELD_OPTIONS, m_options);
}
///////////////////////////////////////////////////////////////////////////
void Parameter_impl::debug_print(String_type &outb) const {
dd::Stringstream_type ss;
ss << "PARAMETER OBJECT: { "
<< "m_id: {OID: " << id() << "}; "
<< "m_routine_id: {OID: " << m_routine->id() << "}; "
<< "m_name: " << name() << "; "
<< "m_is_name_null: " << m_is_name_null << "; "
<< "m_ordinal_position: " << m_ordinal_position << "; "
<< "m_parameter_mode: " << m_parameter_mode << "; "
<< "m_parameter_mode_null: " << m_parameter_mode_null << "; "
<< "m_data_type: " << static_cast<int>(m_data_type) << "; "
<< "m_data_type_utf8: " << m_data_type_utf8 << "; "
<< "m_is_zerofill: " << m_is_zerofill << "; "
<< "m_is_unsigned: " << m_is_unsigned << "; "
<< "m_char_length: " << m_char_length << "; "
<< "m_numeric_precision: " << m_numeric_precision << "; "
<< "m_numeric_precision_null: " << m_numeric_precision_null << "; "
<< "m_numeric_scale: " << m_numeric_scale << "; "
<< "m_numeric_scale_null: " << m_numeric_scale_null << "; "
<< "m_datetime_precision: " << m_datetime_precision << "; "
<< "m_datetime_precision_null: " << m_datetime_precision_null << "; "
<< "m_collation_id: {OID: " << m_collation_id << "}; "
<< "m_options: " << m_options.raw_string() << "; ";
if (data_type() == enum_column_types::ENUM ||
data_type() == enum_column_types::SET) {
/* purecov: begin inspected */
ss << "m_elements: [ ";
for (const Parameter_type_element *e : elements()) {
String_type ob;
e->debug_print(ob);
ss << ob;
}
ss << " ]";
/* purecov: end */
}
outb = ss.str();
}
///////////////////////////////////////////////////////////////////////////
// Enum-elements.
///////////////////////////////////////////////////////////////////////////
Parameter_type_element *Parameter_impl::add_element() {
DBUG_ASSERT(data_type() == enum_column_types::ENUM ||
data_type() == enum_column_types::SET);
Parameter_type_element_impl *e =
new (std::nothrow) Parameter_type_element_impl(this);
m_elements.push_back(e);
return e;
}
///////////////////////////////////////////////////////////////////////////
Parameter_impl::Parameter_impl(const Parameter_impl &src, Routine_impl *parent)
: Weak_object(src),
Entity_object_impl(src),
m_is_name_null(src.m_is_name_null),
m_parameter_mode(src.m_parameter_mode),
m_parameter_mode_null(src.m_parameter_mode_null),
m_data_type(src.m_data_type),
m_data_type_utf8(src.m_data_type_utf8),
m_is_zerofill(src.m_is_zerofill),
m_is_unsigned(src.m_is_unsigned),
m_ordinal_position(src.m_ordinal_position),
m_char_length(src.m_char_length),
m_numeric_precision(src.m_numeric_precision),
m_numeric_precision_null(src.m_numeric_precision_null),
m_numeric_scale(src.m_numeric_scale),
m_numeric_scale_null(src.m_numeric_scale_null),
m_datetime_precision(src.m_datetime_precision),
m_datetime_precision_null(src.m_datetime_precision_null),
m_elements(),
m_options(src.m_options),
m_routine(parent),
m_collation_id(src.m_collation_id) {
m_elements.deep_copy(src.m_elements, this);
}
///////////////////////////////////////////////////////////////////////////
const Object_table &Parameter_impl::object_table() const {
return DD_table::instance();
}
///////////////////////////////////////////////////////////////////////////
void Parameter_impl::register_tables(Open_dictionary_tables_ctx *otx) {
otx->add_table<Parameters>();
otx->register_tables<Parameter_type_element>();
}
///////////////////////////////////////////////////////////////////////////
} // namespace dd
| 38.39375 | 90 | 0.631288 | [
"object"
] |
b59b172ccf00efba663b91f03e7ff326e419812e | 2,189 | cpp | C++ | third party/openRTMFP-Cumulus/CumulusLib/sources/FlowGroup.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | 5 | 2015-04-30T09:08:30.000Z | 2018-08-13T05:00:39.000Z | third party/openRTMFP-Cumulus/CumulusLib/sources/FlowGroup.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | null | null | null | third party/openRTMFP-Cumulus/CumulusLib/sources/FlowGroup.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | null | null | null | /*
Copyright 2010 OpenRTMFP
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License received along this program for more
details (or else see http://www.gnu.org/licenses/).
This file is a part of Cumulus.
*/
#include "FlowGroup.h"
#include "Logs.h"
#include <openssl/evp.h>
using namespace std;
using namespace Poco;
using namespace Poco::Net;
namespace Cumulus {
string FlowGroup::Signature("\x00\x47\x43",3);
string FlowGroup::_Name("NetGroup");
FlowGroup::FlowGroup(UInt32 id,Peer& peer,Invoker& invoker,BandWriter& band) : Flow(id,Signature,_Name,peer,invoker,band),_pGroup(NULL) {
(UInt32&)writer.flowId = id;
}
FlowGroup::~FlowGroup() {
// delete member of group
DEBUG("Group closed")
if(_pGroup)
peer.unjoinGroup(*_pGroup);
}
void FlowGroup::rawHandler(UInt8 type,PacketReader& data) {
if(type==0x01) {
if(data.available()>0) {
UInt32 size = data.read7BitValue()-1;
UInt8 flag = data.read8();
UInt8 groupId[ID_SIZE];
if(flag==0x10) {
vector<UInt8> groupIdVar(size);
data.readRaw(&groupIdVar[0],size);
EVP_Digest(&groupIdVar[0],groupIdVar.size(),(unsigned char *)groupId,NULL,EVP_sha256(),NULL);
} else
data.readRaw(groupId,ID_SIZE);
_pGroup = invoker.groups(groupId);
if(_pGroup) {
UInt16 count=6;
Group::Iterator it;
for(it=_pGroup->begin();it!=_pGroup->end();++it) {
if(peer==(*it)->id)
continue;
BinaryWriter& response(writer.writeRawMessage(true));
response.write8(0x0b); // unknown
response.writeRaw((*it)->id,ID_SIZE);
if((*it)->ping>=1000)
continue;
if(--count==0)
break;
}
peer.joinGroup(*_pGroup);
} else
peer.joinGroup(groupId);
}
} else
Flow::rawHandler(type,data);
}
} // namespace Cumulus
| 26.373494 | 137 | 0.687529 | [
"vector"
] |
b5a30dd246b4001f569d044e730b89d6644c51b7 | 3,984 | cc | C++ | Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/ParallelPhaseApplicator.cc | steve-ord/askapsoft | 21b9df1b393b973ec312591efad7ee2b8c974811 | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/ParallelPhaseApplicator.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/ParallelPhaseApplicator.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file ParallelPhaseApplicator.cc
///
/// @copyright (c) 2010 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
// Local package includes
#include "ingestpipeline/phasetracktask/ParallelPhaseApplicator.h"
// Include package level header file
#include "askap_cpingest.h"
// ASKAPsoft includes
#include "askap/AskapLogging.h"
#include "askap/AskapError.h"
#include "askap/AskapUtil.h"
#include "casacore/casa/Arrays/Vector.h"
#include "casacore/casa/Arrays/Cube.h"
#include "boost/thread/thread.hpp"
#include "boost/tuple/tuple.hpp"
#include "askap/CircularBuffer.h"
ASKAP_LOGGER(logger, ".ParallelPhaseApplicator");
namespace askap {
namespace cp {
namespace ingest {
ParallelPhaseApplicator::ParallelPhaseApplicator(const casa::Vector<double> &freq, casa::Cube<casa::Complex> &vis, size_t nThreads) :
itsFreq(freq), itsCube(vis), itsBuffer(nThreads), itsInterrupted(false) {
ASKAPASSERT(freq.nelements() == vis.ncolumn());
for (size_t th = 0; th <nThreads; ++th) {
itsThreadGroup.create_thread(boost::bind(&ParallelPhaseApplicator::run, this));
}
}
ParallelPhaseApplicator::~ParallelPhaseApplicator() {
itsInterrupted = true;
itsThreadGroup.join_all();
}
void ParallelPhaseApplicator::run() {
const int32_t ONE_SECOND=1000000;
while (!itsInterrupted) {
boost::shared_ptr<boost::tuple<casa::uInt, double, double> > item = itsBuffer.next(ONE_SECOND);
if (!item) {
continue;
}
const casa::uInt row = item->get<0>();
const double phaseOffset = item->get<1>();
const double residualDelay = item->get<2>();
const casa::IPosition &shape = itsCube.shape();
casa::Cube<casa::Complex> tmpBuf;
tmpBuf.takeStorage(shape, itsCube.data(), casa::SHARE);
casa::Matrix<casa::Complex> thisRow = tmpBuf.yzPlane(row);
for (casa::uInt chan = 0; chan < shape[1]; ++chan) {
const float phase = static_cast<float>(phaseOffset +
2. * casa::C::pi * itsFreq[chan] * residualDelay);
const casa::Complex phasor(cos(phase), sin(phase));
// actual rotation (same for all polarisations)
for (casa::uInt pol = 0; pol < thisRow.ncolumn(); ++pol) {
thisRow(chan,pol) *= phasor;
}
}
}
}
void ParallelPhaseApplicator::add(casa::uInt row, double phaseOffset, double residualDelay) {
ASKAPDEBUGASSERT(row < itsCube.nrow());
boost::shared_ptr<boost::tuple<casa::uInt, double, double> > item(new boost::tuple<casa::uInt, double, double>(row,phaseOffset,residualDelay));
itsBuffer.addWhenThereIsSpace(item);
};
void ParallelPhaseApplicator::complete() {
const int32_t ONE_SECOND=1000000;
if (itsBuffer.size() > 0 && !itsInterrupted) {
itsBuffer.waitUntilEmpty(ONE_SECOND);
}
}
} // namespace ingest
} // namespace cp
} // namespace askap
| 36.218182 | 146 | 0.67495 | [
"shape",
"vector"
] |
b5a3ecbdbecbdd6c18cdc3a8a65060f5215914b7 | 1,361 | cpp | C++ | src/Dron/Animations/CollectAnimation.cpp | Dobiasd/Dron | be1fe06e47ad5e40f97d2e683ed8033f4edb11e8 | [
"MIT"
] | null | null | null | src/Dron/Animations/CollectAnimation.cpp | Dobiasd/Dron | be1fe06e47ad5e40f97d2e683ed8033f4edb11e8 | [
"MIT"
] | null | null | null | src/Dron/Animations/CollectAnimation.cpp | Dobiasd/Dron | be1fe06e47ad5e40f97d2e683ed8033f4edb11e8 | [
"MIT"
] | null | null | null | #include "../World.h"
#include "CollectAnimation.h"
#include "../GameStates/PlayView.h"
namespace Dron
{
CollectAnimation::CollectAnimation(const sf::Color& color, const World::Position& position, const std::string& text) :
color_(color), position_(position), elapsedTimeSum_(0.f), text_(text)
{
}
void CollectAnimation::Update(float elapsedTime)
{
elapsedTimeSum_ += elapsedTime;
if (elapsedTimeSum_ > 1.f)
SetDone();
}
void CollectAnimation::Display(sf::RenderTarget& renderTarget, const World& world) const
{
sf::String sfText(text_);
// Adjust the text's scale to the display size.
float sfTextScale(.3f * renderTarget.GetView().GetRect().GetWidth() / sfText.GetRect().GetWidth());
sfText.Scale(sfTextScale, sfTextScale);
// Increase the transparency gradually with time.
sf::Color color(color_);
color.a = static_cast<sf::Uint8>(255.f - 255.f * elapsedTimeSum_ / 1.f);
sfText.SetColor(color);
// Float away to the top right.
Vector step(PlayView::GetStep(renderTarget, world));
Vector floatingDirection(step.x_, -step.y_);
Vector screenPos(
PlayView::FloatPositionWindowCoordinate(position_, renderTarget, world)
+ floatingDirection * 1.2f * elapsedTimeSum_);
sfText.Move(screenPos.x_ - sfText.GetRect().GetWidth() / 2, screenPos.y_ - sfText.GetRect().GetHeight());
renderTarget.Draw(sfText);
}
} /* namespace Dron */
| 29.586957 | 118 | 0.734019 | [
"vector"
] |
b27563726a3958be37e90006ae6da4dc0746fb57 | 18,293 | hpp | C++ | tests/hot/rowex-test/include/hot/rowex/ConcurrentTestHelper.hpp | yishayahu/hot | 579e225ba5f9b1e5cda0cd282121f4202406f245 | [
"0BSD"
] | 99 | 2018-03-23T11:08:48.000Z | 2022-03-03T10:03:35.000Z | tests/hot/rowex-test/include/hot/rowex/ConcurrentTestHelper.hpp | SheldonZhong/hot | ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0 | [
"ISC"
] | 3 | 2018-12-18T19:00:04.000Z | 2021-09-07T13:05:36.000Z | tests/hot/rowex-test/include/hot/rowex/ConcurrentTestHelper.hpp | SheldonZhong/hot | ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0 | [
"ISC"
] | 29 | 2018-06-03T07:56:35.000Z | 2022-03-04T07:31:50.000Z | #ifndef __HOT__CONCURRENT_TEST_HELPER__
#define __HOT__CONCURRENT_TEST_HELPER__
#include <thread>
#include <atomic>
#include <vector>
#include <memory>
#include <utility>
#include <sstream>
#include <tbb/tbb_allocator.h> // zero_allocator defined here
#include <tbb/concurrent_vector.h>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <tbb/concurrent_hash_map.h>
#include <tbb/task_arena.h>
#include <tbb/task_group.h>
#include <idx/contenthelpers/ContentEquals.hpp>
#include <idx/contenthelpers/KeyComparator.hpp>
#include <hot/rowex/HOTRowex.hpp>
#include <hot/singlethreaded/HOTSingleThreaded.hpp>
#include "hot/rowex/TreeTestHelper.hpp"
namespace hot { namespace rowex {
template<typename ValueType>
void checkConsistency(
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> const &cobTrie,
std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> const &unsynchronizedHOT,
std::vector<ValueType> const &valuesToInsert
) {
using KeyType = typename hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>::KeyType;
//BOOST_REQUIRE_EQUAL(HOTRowexNodeBase::getNumberActiveLocks(), 0u);
bool heightsMatch = (cobTrie->mRoot.isEmpty() && unsynchronizedHOT->mRoot.isUnused()) || (cobTrie->mRoot.getHeight() == unsynchronizedHOT->mRoot.getHeight());
if (!heightsMatch) {
std::cout << "Heights do not match!" << std::endl;
}
BOOST_CHECK_EQUAL(cobTrie->mRoot.getHeight(), unsynchronizedHOT->mRoot.getHeight());
bool found = true;
//works only because key == value
std::set<ValueType, typename idx::contenthelpers::KeyComparator<ValueType>::type> temporarySet(
valuesToInsert.begin(), valuesToInsert.end());
std::vector<ValueType> sortedValues(temporarySet.begin(), temporarySet.end());
size_t numberValues = sortedValues.size();
for (size_t j = 0u; j < numberValues; ++j) {
idx::contenthelpers::OptionalValue<ValueType> result = cobTrie->lookup(sortedValues[j]);
bool foundEntry = result.mIsValid && (result.mValue == sortedValues[j]);
found = found & foundEntry;
if (!foundEntry) {
std::cout << "j :: " << j << " searched <" << sortedValues[j] << "> but found <" << result.mValue << ">"
<< std::endl;
}
}
if (!found) {
std::cout << "Values are: ";
for (ValueType const &value : *cobTrie) {
std::cout << value << ", ";
}
std::cout << std::endl;
}
if (numberValues < 1000) {
for (size_t j = 0u; j < numberValues; ++j) {
KeyType rawSearchValue = sortedValues[j];
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->find(rawSearchValue), cobTrie->end(), sortedValues.begin() + j,
sortedValues.end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->lower_bound(rawSearchValue), cobTrie->end(),
sortedValues.begin() + j, sortedValues.end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->upper_bound(rawSearchValue), cobTrie->end(),
sortedValues.begin() + j + 1, sortedValues.end());
BOOST_REQUIRE(
cobTrie->scan(rawSearchValue, numberValues - j - 1).compliesWith({true, *sortedValues.rbegin()}));
}
} else {
for (size_t j = 0u; j < numberValues; j += (numberValues / 100)) {
KeyType rawSearchValue = sortedValues[j];
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->find(rawSearchValue), cobTrie->end(), sortedValues.begin() + j,
sortedValues.end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->lower_bound(rawSearchValue), cobTrie->end(),
sortedValues.begin() + j, sortedValues.end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->upper_bound(rawSearchValue), cobTrie->end(),
sortedValues.begin() + j + 1, sortedValues.end());
BOOST_REQUIRE(
cobTrie->scan(rawSearchValue, numberValues - j - 1).compliesWith({true, *sortedValues.rbegin()}));
}
}
//std::cout << "Starting to check integrity" << std::endl;
BOOST_REQUIRE_EQUAL_COLLECTIONS(cobTrie->begin(), cobTrie->end(), sortedValues.begin(), sortedValues.end());
bool subtreeValid = isSubTreeValid<ValueType, idx::contenthelpers::IdentityKeyExtractor>(&(cobTrie->mRoot));
BOOST_REQUIRE(subtreeValid);
BOOST_REQUIRE(found);
}
uint64_t rdtsc() {
uint32_t hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return static_cast<uint64_t>(lo) | (static_cast<uint64_t>(hi) << 32);
}
struct ThreadIdHashCompare {
static std::hash<std::thread::id> hasher;
static size_t hash(const std::thread::id &threadId) {
return hasher(threadId);
}
//! True if strings are equal
static bool equal(const std::thread::id &x, const std::thread::id &y) {
return x == y;
}
};
std::hash<std::thread::id> ThreadIdHashCompare::hasher;
class TimerBasedIncreasingIdGenerator {
public:
uint64_t generateValue(size_t /* index */, size_t shortThreadId) const {
assert(shortThreadId < (1 << 6));
uint64_t increasingId = ((rdtsc() << 6) + shortThreadId ) & static_cast<uint64_t>(INT64_MAX);
return increasingId + shortThreadId;
}
};
class TimerBasedDecreasingIdGenerator {
private:
TimerBasedIncreasingIdGenerator mIncreasingGenerator;
public:
uint64_t generateValue(size_t index, size_t shortThreadId) const {
uint64_t increasingId = mIncreasingGenerator.generateValue(index, shortThreadId);
uint64_t decreasingId = INT64_MAX - increasingId;
return decreasingId;
}
};
template<typename ValueType>
class VectorBasedValueGenerator {
private:
std::vector<ValueType> const mValues;
public:
template<typename ProvidedValues> VectorBasedValueGenerator(ProvidedValues && values)
: mValues(std::forward<ProvidedValues>(values)) {
}
ValueType generateValue(size_t index, size_t /* shortThreadId */) const {
return mValues[index];
}
};
template<typename ValueType> using AlreadyInsertedValuesType = tbb::concurrent_vector<std::atomic<std::vector<ValueType>*>, tbb::zero_allocator<std::atomic<std::vector<ValueType>*>>>;
template<typename ValueType, typename ValueGenerator>
struct Inserter {
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> mAlreadyInsertedRanges;
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> mHot;
std::atomic<uint16_t> mNextThreadId;
tbb::concurrent_hash_map<std::thread::id, uint16_t, ThreadIdHashCompare> mThreadIdMap;
using thread_id_accessor = typename tbb::concurrent_hash_map<std::thread::id, uint16_t, ThreadIdHashCompare>::accessor;
std::atomic<size_t> mNumberSuccessfulInserts;
std::atomic<size_t> mNumberFailed;
std::unique_ptr<ValueGenerator> mValueGenerator;
Inserter(
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> alreadyInsertedRanges,
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hot,
std::unique_ptr<ValueGenerator> &&valueGenerator
)
: mAlreadyInsertedRanges(alreadyInsertedRanges), mHot(hot), mNextThreadId(0u), mThreadIdMap(),
mNumberSuccessfulInserts(0), mNumberFailed(0), mValueGenerator(std::forward<std::unique_ptr<ValueGenerator>>(valueGenerator)) {
}
void operator()(const tbb::blocked_range<size_t> &range) {
std::vector<ValueType>* insertedValues = new std::vector<ValueType>();
insertedValues->reserve(range.size());
thread_id_accessor accessor;
std::thread::id const ¤tThreadId = std::this_thread::get_id();
if (!mThreadIdMap.find(accessor, currentThreadId)) {
mThreadIdMap.insert(accessor, currentThreadId);
accessor->second = mNextThreadId.fetch_add(1u);
}
uint16_t shortThreadId = accessor->second;
size_t numberSuccessful = 0;
for (size_t i = range.begin(); i != range.end(); ++i) {
ValueType valueToInsert = mValueGenerator->generateValue(i, static_cast<size_t>(shortThreadId));
insertedValues->push_back(valueToInsert);
numberSuccessful += mHot->insert(valueToInsert);
}
mNumberSuccessfulInserts.fetch_add(numberSuccessful);
mNumberFailed.fetch_add(range.size() - numberSuccessful);
mAlreadyInsertedRanges->emplace_back(insertedValues);
}
size_t getNumberOfSuccesfulInserts() {
return mNumberSuccessfulInserts.load(std::memory_order_acquire);
}
size_t getNumberOfFailedInserts() {
return mNumberFailed.load(std::memory_order_acquire);
}
};
template<typename ValueType> struct Scanner {
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> mAlreadyInsertedRanges;
tbb::concurrent_vector<std::string> mFailures;
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> mHot;
std::atomic<bool> mShouldAbort;
std::atomic<bool> mExecutedSuccessful;
std::atomic<size_t> mNumberScanOperationsSuccesfullyCompleted;
Scanner(std::shared_ptr<AlreadyInsertedValuesType<ValueType>> alreadyInsertedRanges,
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hot
)
: mAlreadyInsertedRanges(alreadyInsertedRanges), mHot(hot), mShouldAbort(false), mExecutedSuccessful(true), mNumberScanOperationsSuccesfullyCompleted(0u)
{
}
void operator()() {
typename idx::contenthelpers::KeyComparator<ValueType>::type lessThan;
while(!mShouldAbort.load(std::memory_order_acquire) && mAlreadyInsertedRanges->size() == 0) {
_mm_pause();
}
while(!mShouldAbort.load(std::memory_order_acquire)) {
size_t numberValuesInAlreadyInsertedRange = 0u;
std::set<ValueType, typename idx::contenthelpers::KeyComparator<ValueType>::type> sampleValues;
for (typename AlreadyInsertedValuesType<ValueType>::iterator it = mAlreadyInsertedRanges->begin(); it != mAlreadyInsertedRanges->end(); ++it) {
std::vector<ValueType>* vector = it->load(std::memory_order_acquire);
if(vector != nullptr) { //otherwise the element is not constructed completely
numberValuesInAlreadyInsertedRange += vector->size();
sampleValues.insert((*vector)[0]);
}
}
size_t iteratedValues = 0u;
size_t numberMatched = 0u;
ValueType previousValue;
for (ValueType const &value : *mHot) {
if(iteratedValues > 0) {
if(idx::contenthelpers::contentEquals(value, previousValue) || lessThan(value, previousValue)) {
std::ostringstream out;
out << "Wrong bound (previous value: " << previousValue << " currentValue " << value << ")";
mFailures.push_back(out.str());
}
}
++iteratedValues;
if (sampleValues.find(value) != sampleValues.end()) {
++numberMatched;
}
previousValue = value;
}
for (typename AlreadyInsertedValuesType<ValueType>::iterator it = mAlreadyInsertedRanges->begin(); it != mAlreadyInsertedRanges->end(); ++it) {
std::vector<ValueType>* vector = it->load(std::memory_order_acquire);
if(vector != nullptr) { //otherwise the element is not constructed completely
ValueType searchKey = (*vector)[0];
if (mHot->find(searchKey) == mHot->end()) {
std::ostringstream out;
out << "mHot->find(" << searchKey << ") != mHot->end() failed";
mFailures.push_back(out.str());
}
}
}
std::vector<ValueType>* firstRange = (*mAlreadyInsertedRanges)[0].load(std::memory_order_acquire);
if(firstRange != nullptr) {
size_t mNumberValuesInRangeScan = 0ul;
ValueType const &firstInsertedValue = firstRange->at(0);
for (auto it = mHot->find(firstInsertedValue); it != mHot->end(); ++it) {
ValueType const &value = *it;
if (mNumberValuesInRangeScan > 0) {
if (idx::contenthelpers::contentEquals(value, previousValue) ||
lessThan(value, previousValue)) {
std::ostringstream out;
out << "Wrong bound (previous value: " << previousValue << " currentValue " << value << ")";
mFailures.push_back(out.str());
}
}
++mNumberValuesInRangeScan;
previousValue = value;
}
}
if(numberMatched != sampleValues.size()) {
std::ostringstream out;
out << "numberMatched != sampleValues.size() (" << numberMatched << " != " << sampleValues.size() << ")";
mFailures.push_back(out.str());
}
if(iteratedValues < numberValuesInAlreadyInsertedRange) {
std::ostringstream out;
out << "iteratedValues < numberValuesInAlreadyInsertedRange failed (" << iteratedValues << "<" << numberValuesInAlreadyInsertedRange << ")";
mFailures.push_back(out.str());
}
mNumberScanOperationsSuccesfullyCompleted.fetch_add(1u);
}
}
void abortAllScanners() {
mShouldAbort.store(true, std::memory_order_release);
}
size_t getNumberSuccessfulScanOperations() {
return mNumberScanOperationsSuccesfullyCompleted.load(std::memory_order_acquire);
}
};
template<typename ValueType>
struct Searcher {
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> mAlreadyInsertedRanges;
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> mHot;
std::atomic<size_t> mNumberSuccesfulLookups;
std::atomic<size_t> mNumberFailedLookups;
std::atomic<bool> mShouldAbort;
std::atomic<size_t> mTotalNumberOfExecutedLookups;
Searcher(
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> alreadyInsertedRanges,
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hot
) : mAlreadyInsertedRanges(alreadyInsertedRanges), mHot(hot), mNumberSuccesfulLookups(0u), mNumberFailedLookups(0u),
mShouldAbort(false), mTotalNumberOfExecutedLookups(0u) {
}
void operator()() {
while (!mShouldAbort.load(std::memory_order_acquire)) {
for (typename AlreadyInsertedValuesType<ValueType>::iterator it = mAlreadyInsertedRanges->begin(); it != mAlreadyInsertedRanges->end(); ++it) {
std::vector<ValueType>* partOfInsertedValues = it->load(std::memory_order_acquire);
if(partOfInsertedValues != nullptr) { //otherwise the current element is not initialized
size_t numberSuccesfulInserted = 0u;
for (ValueType const &insertedValue : *partOfInsertedValues) {
numberSuccesfulInserted += mHot->lookup(insertedValue).mIsValid;
}
mNumberSuccesfulLookups.fetch_add(numberSuccesfulInserted);
mNumberFailedLookups.fetch_add(partOfInsertedValues->size() - numberSuccesfulInserted);
mTotalNumberOfExecutedLookups.fetch_add(partOfInsertedValues->size());
}
_mm_pause();
if (mShouldAbort.load(std::memory_order_acquire)) {
return;
}
}
}
}
size_t getNumberOfSuccesfulLookups() {
return mNumberSuccesfulLookups.load(std::memory_order_acquire);
}
size_t getNumberOfFailedLookups() {
return mNumberFailedLookups.load(std::memory_order_acquire);
}
size_t getTotalNumberOfExecutedLookups() {
return mTotalNumberOfExecutedLookups.load(std::memory_order_acquire);
}
void abortAllSearchers() {
mShouldAbort.store(true, std::memory_order_release);
}
};
template<typename ValueType, typename ValueGenerator, typename... Args> void executeMixedWorkloadLookupScanAndInsertTest(
size_t numberOfValuesToInsert, Args &&... args) {
std::shared_ptr<AlreadyInsertedValuesType<ValueType>> alreadyInsertedRanges(
new AlreadyInsertedValuesType<ValueType>(),
[](AlreadyInsertedValuesType<ValueType>* alreadyInserted) {
for(std::atomic<std::vector<ValueType>*> & insertedRange : *alreadyInserted) {
delete insertedRange.load(std::memory_order_acquire);
}
delete alreadyInserted;
}
);
std::shared_ptr<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hot
= std::make_shared<hot::rowex::HOTRowex<ValueType, idx::contenthelpers::IdentityKeyExtractor>>();
Inserter<ValueType, ValueGenerator> inserter(alreadyInsertedRanges, hot, std::make_unique<ValueGenerator>(std::forward<Args>(args)...));
Searcher<ValueType> searcher { alreadyInsertedRanges, hot };
Scanner<ValueType> scanner { alreadyInsertedRanges, hot };
size_t numberValuesToInsert = numberOfValuesToInsert;
size_t numberThreadsToUse = std::max<size_t>(static_cast<size_t>(std::thread::hardware_concurrency()/2.0), 1ul);
std::vector<std::thread> searchThreads;
for(size_t i=0; i < numberThreadsToUse; ++i) {
searchThreads.push_back(std::thread([&searcher] {
searcher();
}));
}
std::vector<std::thread> scanThreads;
for(size_t i=0; i < numberThreadsToUse; ++i) {
scanThreads.push_back(std::thread([&scanner] {
scanner();
}));
}
tbb::task_group insertGroup;
tbb::task_arena limitedInsertThreads(std::max<size_t>(2, numberThreadsToUse), 1);
limitedInsertThreads.execute([&]{ // Use at most 2 threads for this job.
insertGroup.run([&]{ // run in task group
tbb::parallel_for(tbb::blocked_range<size_t>( 0, numberValuesToInsert, 100), [&](const tbb::blocked_range<size_t>& range) {
try {
inserter(range);
} catch(std::exception const & e) {
std::cout << "Exception on insert " << e.what() << std::endl;
} catch(...) {
std::cout << "Unknown exception" << std::endl;
}
});
});
});
insertGroup.wait();
searcher.abortAllSearchers();
scanner.abortAllScanners();
std::for_each(searchThreads.begin(), searchThreads.end(), [](std::thread & thread) -> void {
thread.join();
});
std::for_each(scanThreads.begin(), scanThreads.end(), [](std::thread & thread) -> void {
thread.join();
});
std::cout << "Executed " << inserter.getNumberOfSuccesfulInserts() << " succesful inserts ( " << inserter.getNumberOfFailedInserts() << " failed)" << std::endl;
std::cout << "Executed " << searcher.getNumberOfSuccesfulLookups() << " succesful lookups (" << searcher.getNumberOfFailedLookups() << " failed)" << std::endl;
std::cout << "Executed " << scanner.getNumberSuccessfulScanOperations() << " scans" << std::endl;
for(std::string const & failure : scanner.mFailures) {
std::cerr << "Failure in scan: " << failure << std::endl;
}
std::vector<ValueType> allInsertedValues;
std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> unsynchronizedHOT = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>();
for (std::atomic<std::vector<ValueType>*> & partOfInsertedValuesHolder : (*alreadyInsertedRanges)) {
std::vector<ValueType>* partOfInsertedValues = partOfInsertedValuesHolder.load(std::memory_order_acquire);
if(partOfInsertedValues != nullptr) {
for (ValueType const &insertedValue : (*partOfInsertedValues)) {
allInsertedValues.push_back(insertedValue);
unsynchronizedHOT->insert(insertedValue);
}
}
}
checkConsistency(hot, unsynchronizedHOT, allInsertedValues);
}
} }
#endif | 38.269874 | 244 | 0.731318 | [
"vector"
] |
b2794b81175e150bb0d8139ca153c0fb7d978c7e | 18,544 | cpp | C++ | samples/softrender/TextureCube.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 6 | 2019-01-25T08:41:14.000Z | 2021-08-22T07:06:11.000Z | samples/softrender/TextureCube.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | null | null | null | samples/softrender/TextureCube.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 3 | 2019-01-25T08:41:16.000Z | 2020-09-04T06:04:29.000Z | //
// Created by huangkun on 2018/6/25.
//
#include "TextureCube.h"
#include "Input.h"
TEST_NODE_IMP_BEGIN
TextureCube::TextureCube() {
vertices = {
// Back face
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
// Front face
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // top-left
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
// Left face
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-left
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
// Right face
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
// Bottom face
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // top-left
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
// Top face
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f // bottom-left
// -4 / 1.732, 0, 2, 0, 0,
// 4 / 1.732, 0, 2, 1, 0,
// 0, 10, 2, 0.5, 1,
};
texture2D.load("../res/net.jpg");
}
void TextureCube::draw(const mat4 &transform) {
setDepthTest(true);
setFaceCull(true);
clearColor(50, 50, 50, 255);
clearDepth();
modelMatrix.setIdentity();
// modelMatrix.translate(Vector(0.5, -0.5, 0));
modelMatrix.rotate(Vector(0, 1, 0), 2 * 3.14f * sin(glfwGetTime() / 4));
modelMatrix.rotate(Vector(1, 0, 0), radians(30.0f));
// modelMatrix.scale(Vector(1.5f, 1, 0.5));
vec3 target = cameraPos + cameraDir;
viewMatrix = Matrix::lookAt(Vector(cameraPos.x, cameraPos.y, cameraPos.z), Vector(target.x, target.y, target.z),
Vector(cameraUp.x, cameraUp.y, cameraUp.z));
projectMatrix = Matrix::perspective(radians(60.0f), (float) TEX_WIDTH / TEX_HEIGHT, 0.1, 100.0f);
Matrix m = modelMatrix;
m.mult(viewMatrix);
m.mult(projectMatrix);
int column = 5;
vec4 triangle[3];
vec3 triangleWorld[3];
vec2 uv[3];
for (int i = 0; i < vertices.size(); i += column * 3) {
for (int j = 0; j < 3; j++) {
int row = i + j * column;
vec4 p = vec4(vertices.at(row), vertices.at(row + 1),
vertices.at(row + 2), 1.0);
// 模型 --> 世界 --> 相机空间 --> 齐次裁剪空间,xyz ~ [-w,w], w = Z(相机空间)
Vector v = m.applyPoint(Vector(p.x, p.y, p.z));
triangle[j] = vec4(v.x, v.y, v.z, v.w);
uv[j] = vec2(vertices.at(row + 3), vertices.at(row + 4));
Vector v0 = modelMatrix.applyPoint(Vector(p.x, p.y, p.z));
triangleWorld[j] = vec3(v0.x, v0.y, v0.z);
}
if (cvvCull(triangle)) {
// log("cvv cull");
continue;
}
if (faceCull(triangle)) {
// 背面剔除
// log("backface cull");
continue;
}
// 转换为屏幕坐标
pointToScreen(triangle);
// 光栅化
std::vector<VertexCoords> verts = {
{triangle[0], uv[0] * triangle[0].w},
{triangle[1], uv[1] * triangle[1].w},
{triangle[2], uv[2] * triangle[2].w},};
fill(verts);
}
SoftRender::draw(transform);
setDepthTest(false);
setFaceCull(false);
}
void TextureCube::fill(std::vector<VertexCoords> &verts, const std::vector<vec3> &uniforms) {
std::sort(verts.begin(), verts.end(),
[](const VertexCoords &a, const VertexCoords &b) { return a.p.y > b.p.y; });
const auto &max = verts[0].p;
const auto &mid = verts[1].p;
const auto &min = verts[2].p;
const auto &maxUV = verts[0].uv;
const auto &midUV = verts[1].uv;
const auto &minUV = verts[2].uv;
vec3 *maxVarying = verts[0].varying;
vec3 *midVarying = verts[1].varying;
vec3 *minVarying = verts[2].varying;
int varyingCount = verts[0].varyingCount;
/*
* mid ---- max
* \ /
* \/
* min
*
* max
* /\
* / \
* min ---- mid
*/
if (mid.y == min.y || max.y == mid.y) {
int dy = max.y - min.y;
vec4 a, b;
a.y = b.y = max.y;
vec2 uv1, uv2;
float dvdy = abs(dy) < FLT_EPSILON ? 0 : (maxUV.y - minUV.y) / dy;
vec3 varyingA[varyingCount];
vec3 varyingB[varyingCount];
float fdy = 1.0f / (max.y - min.y);
for (int i = 0; i <= dy; i++) {
float f = (float) i * fdy;
if (max.y == mid.y) {
a.x = interp(mid.x, min.x, f);
a.z = interp(mid.z, min.z, f);
a.w = interp(mid.w, min.w, f);
uv1 = interp(midUV, minUV, f);
verts[0].interp(varyingA, midVarying, minVarying, f);
} else {
a.x = interp(max.x, mid.x, f);
a.z = interp(max.z, mid.z, f);
a.w = interp(max.w, mid.w, f);
uv1 = interp(maxUV, midUV, f);
verts[0].interp(varyingA, maxVarying, midVarying, f);
}
b.x = interp(max.x, min.x, f);
b.z = interp(max.z, min.z, f);
b.w = interp(max.w, min.w, f);
uv2 = interp(maxUV, minUV, f);
verts[0].interp(varyingB, maxVarying, minVarying, f);
if (a == b) {
// point
verts[0].divideW(varyingA, a.w);
setPixel(a.x, a.y, a.z, uv1.x / a.w, uv1.y / a.w, varyingA, uniforms, 0, dvdy / a.w);
} else {
dda_line(createVertexCoords(a, uv1, varyingA, varyingCount),
createVertexCoords(b, uv2, varyingB, varyingCount), uniforms, dvdy);
}
a.y -= 1;
b.y -= 1;
}
} else {
/*
* max
* /|
* / |
* mid / |
* \ |
* \ |
* \|
* min
*/
float dy = max.y - min.y;
vec4 midP;
midP.y = mid.y;
float f = (midP.y - min.y) / dy;
midP.w = interp(min.w, max.w, f);
midP.z = interp(min.z, max.z, f);
midP.x = interp(min.x, max.x, f);
vec2 uv = interp(minUV, maxUV, f);
vec3 interpVarying[varyingCount];
verts[0].interp(interpVarying, minVarying, maxVarying, f);
std::vector<VertexCoords> verts1 = {
createVertexCoords(max, maxUV, maxVarying, varyingCount),
createVertexCoords(mid, midUV, midVarying, varyingCount),
createVertexCoords(midP, uv, interpVarying, varyingCount)};
fill(verts1, uniforms);
std::vector<VertexCoords> verts2 = {
createVertexCoords(mid, midUV, midVarying, varyingCount),
createVertexCoords(midP, uv, interpVarying, varyingCount),
createVertexCoords(min, minUV, minVarying, varyingCount)};
fill(verts2, uniforms);
}
}
void TextureCube::dda_line(const VertexCoords &vert1, const VertexCoords &vert2,
const std::vector<vec3> &uniforms, float dvdy) {
const vec4 &pa = vert1.p;
const vec4 &pb = vert2.p;
const vec2 &uv1 = vert1.uv;
const vec2 &uv2 = vert2.uv;
vec3 *varyingA = (vec3 *) vert1.varying;
vec3 *varyingB = (vec3 *) vert2.varying;
int varyingCount = vert1.varyingCount;
vec4 p1 = pa;
vec4 p2 = pb;
vec4 p11 = pa;
vec4 p22 = pb;
if (clip_3D_line(p11, p22)) {
return;
}
p1.x = p11.x;
p1.y = p11.y;
p2.x = p22.x;
p2.y = p22.y;
vec2 uv11 = uv1;
vec2 uv12 = uv2;
float f1 = 0, f2 = 0;
if (pb.x != pa.x) {
f1 = (p11.x - pa.x) / (pb.x - pa.x);
f2 = (p22.x - pa.x) / (pb.x - pa.x);
}
if (pb.y != pa.y) {
f1 = (p11.y - pa.y) / (pb.y - pa.y);
f2 = (p22.y - pa.y) / (pb.y - pa.y);
}
p1.w = interp(pa.w, pb.w, f1);
p2.w = interp(pa.w, pb.w, f2);
p1.z = interp(pa.z, pb.z, f1);
p2.z = interp(pa.z, pb.z, f2);
uv11 = interp(uv1, uv2, f1);
uv12 = interp(uv1, uv2, f2);
vec3 varying1[varyingCount];
vert1.interp(varying1, varyingA, varyingB, f1);
vec3 varying2[varyingCount];
vert1.interp(varying2, varyingA, varyingB, f2);
// DDA
float dy = p2.y - p1.y;
float dx = p2.x - p1.x;
float stepX, stepY;
int steps;
float fsteps;
if (abs(dy) > abs(dx)) {
steps = abs((int) dy);
fsteps = 1.0f / abs(dy);
stepY = dy > 0 ? 1 : -1;
stepX = dx > 0 ? fabs(dx / dy) : -fabs(dx / dy);
} else {
steps = abs((int) dx);
fsteps = 1.0f / abs(dx);
stepX = dx > 0 ? 1 : -1;
if (dx == 0)
stepY = 0;
else
stepY = dy > 0 ? fabs(dy / dx) : -fabs(dy / dx);
}
float dudx = abs(dx) < FLT_EPSILON ? 0 : (uv12.x - uv11.x) / dx;
float x = p1.x, y = p1.y;
vec3 interpVarying[varyingCount];
for (int k = 0; k <= steps; k++) {
float f = k * fsteps;
float z = interp(p1.z, p2.z, f);
float w = interp(p1.w, p2.w, f);
vec2 uv0 = interp(uv11, uv12, f);
vert1.interp(interpVarying, varying1, varying2, f);
vert1.divideW(interpVarying, w);
setPixel(x, y, z, uv0.x / w, uv0.y / w, interpVarying, uniforms, dudx / w, dvdy / w);
x += stepX;
y += stepY;
}
// Bresenham
// float x0 = p1.x, x1 = p2.x, y0 = p1.y, y1 = p2.y;
// bool flip = abs(y1 - y0) > abs(x1 - x0);
// if (flip) {
// swap(x0, y0);
// swap(x1, y1);
// }
// if (x0 > x1) {
// swap(x0, x1);
// swap(y0, y1);
// }
// int dx = x1 - x0;
// int dy = abs(y1 - y0);
// int error = dx / 2;
// int ystep = y0 < y1 ? 1 : -1;
// int y = y0;
// for (int x = x0; x <= x1; x++) {
// if (flip) {
// float f = dx == 0 ? (y - y0) / (float) dy : (x - x0) / (float) dx;
// float z = interp(p1.z, p2.z, f);
// float w = interp(p1.w, p2.w, f);
// vec2 uv0 = interp(uv11, uv12, f);
// std::vector<vec4> interpVarying;
// for (int m = 0; m < varyingA.size(); m++) {
// interpVarying.push_back(interp(varying1[m], varying2[m], f));
// }
// setPixel(y, x, p1.z, uv11.x / p1.w, uv11.y / p1.w, varying1, uniforms);
// } else {
// float f = dx == 0 ? (y - y0) / (float) dy : (x - x0) / (float) dx;
// float z = interp(p1.z, p2.z, f);
// float w = interp(p1.w, p2.w, f);
// vec2 uv0 = interp(uv11, uv12, f);
// std::vector<vec4> interpVarying;
// for (int m = 0; m < varyingA.size(); m++) {
// interpVarying.push_back(interp(varying1[m], varying2[m], f));
// }
// setPixel(x, y, p1.z, uv11.x / p1.w, uv11.y / p1.w, varying1, uniforms);
// }
// error = error - dy;
// if (error < 0) {
// y += ystep;
// error += dx;
// }
// }
}
void TextureCube::setPixel(int x, int y, float z, float u, float v, vec3 varying[],
const std::vector<vec3> &uniforms) {
const vec4 &color = texture2D.sample(u, v);
SoftRender::setPixel(x, y, z, color);
}
void TextureCube::setPixel(int x, int y, float z, float u, float v, vec3 varying[],
const std::vector<vec3> &uniforms, float dudx, float dudy) {
setPixel(x, y, z, u, v, varying, uniforms);
}
TextureCube::~TextureCube() {
}
void TextureCube::drawMesh(const Mesh &mesh, const Matrix &mvp, int varyingCount) {
const auto &vertices = mesh._vertices;
const auto &indices = mesh._indices;
bindTextures(mesh._texture2Ds);
bool useIndices = indices.size() > 0;
int num = useIndices ? indices.size() / 3 : vertices.size() / 3;
vec4 triangle[3];
vec3 triangleWorld[3];
vec3 normals[3];
vec2 uv[3];
for (int i = 0; i < num; i++) {
for (int j = 0; j < 3; j++) {
const Vertex &vertex = useIndices ? vertices[indices[i * 3 + j]] : vertices[i * 3 + j];
vec3 p = vertex.position;
Vector v = mvp.applyPoint(p);
triangle[j] = v.vec4();
normals[j] = vertex.normal;
uv[j] = vertex.texCoords;
Vector v0 = modelMatrix.applyPoint(p);
triangleWorld[j] = v0.vec3();
}
if (cvvCull(triangle)) {
// log("cvv cull");
continue;
}
if (faceCull(triangle)) {
// 背面剔除
// log("backface cull");
continue;
}
// 转换为屏幕坐标
pointToScreen(triangle);
// vec3 norms[] = {
// modelMatrix.applyVector(normals[0]).vec3(),
// modelMatrix.applyVector(normals[1]).vec3(),
// modelMatrix.applyVector(normals[2]).vec3(),
// };
mat4 matrix = mat4(modelMatrix.m[0][0], modelMatrix.m[0][1], modelMatrix.m[0][2], modelMatrix.m[0][3],
modelMatrix.m[1][0], modelMatrix.m[1][1], modelMatrix.m[1][2], modelMatrix.m[1][3],
modelMatrix.m[2][0], modelMatrix.m[2][1], modelMatrix.m[2][2], modelMatrix.m[2][3],
modelMatrix.m[3][0], modelMatrix.m[3][1], modelMatrix.m[3][2], modelMatrix.m[3][3]);
matrix = glm::transpose(glm::inverse(matrix));
vec3 norms[] = {
matrix * vec4(normals[0].x, normals[0].y, normals[0].z, 0),
matrix * vec4(normals[1].x, normals[1].y, normals[1].z, 0),
matrix * vec4(normals[2].x, normals[2].y, normals[2].z, 0),
};
// 光栅化
vec3 v1[3], v2[3], v3[3];
if (varyingCount == 1) {
v1[0] = triangleWorld[0] * triangle[0].w;
v2[0] = triangleWorld[1] * triangle[1].w;
v3[0] = triangleWorld[2] * triangle[2].w;
} else if (varyingCount == 2) {
v1[0] = triangleWorld[0] * triangle[0].w;
v2[0] = triangleWorld[1] * triangle[1].w;
v3[0] = triangleWorld[2] * triangle[2].w;
v1[1] = norms[0] * triangle[0].w;
v2[1] = norms[1] * triangle[1].w;
v3[1] = norms[2] * triangle[2].w;
}
std::vector<VertexCoords> verts = {
createVertexCoords(triangle[0], uv[0] * triangle[0].w, v1, varyingCount),
createVertexCoords(triangle[1], uv[1] * triangle[1].w, v2, varyingCount),
createVertexCoords(triangle[2], uv[2] * triangle[2].w, v3, varyingCount),
};
fill(verts);
}
}
void TextureCube::bindTextures(const std::vector<Texture2D *> &textures) {
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int defaultNr = 0;
for (unsigned int i = 0; i < textures.size(); i++) {
std::stringstream ss;
std::string name = textures[i]->type;
if (name == "texture_diffuse")
ss << name << diffuseNr++; // transfer unsigned int to stream
else if (name == "texture_specular")
ss << name << specularNr++; // transfer unsigned int to stream
else
ss << "texture" << defaultNr++;
auto it = _bindTextures.find(ss.str());
if (it != _bindTextures.end())
it->second = textures[i];
else
_bindTextures.insert(std::make_pair(ss.str(), textures[i]));
}
}
TEST_NODE_IMP_END | 40.756044 | 120 | 0.439226 | [
"mesh",
"vector",
"transform"
] |
b27b3c76814e818864f1968f63aa12061bf7bd62 | 5,437 | cpp | C++ | src/receiver.cpp | NithoAlif/sliding-window-protocol | 185a9e3707ff674598ea946ee984cc0c6a015a65 | [
"MIT"
] | null | null | null | src/receiver.cpp | NithoAlif/sliding-window-protocol | 185a9e3707ff674598ea946ee984cc0c6a015a65 | [
"MIT"
] | null | null | null | src/receiver.cpp | NithoAlif/sliding-window-protocol | 185a9e3707ff674598ea946ee984cc0c6a015a65 | [
"MIT"
] | null | null | null | /* Nama/NIM : Nitho Alif Ibadurrahman/13513072 */
/* File : receiver.cpp */
/* Deskripsi : Deklarasi objek receiver */
#include <iostream>
#include <vector>
#include <thread>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <queue>
#include "dcomm.h"
#include "response.cpp"
using namespace std;
#define DELAY 500 // Delay to adjust speed of consuming buffer, in milliseconds
#define UPLIMIT 6 // Define minimum upper limit
#define LOWLIMIT 2 // Define maximum lower limit
struct frameComparator
{
bool operator()(frame& a, frame& b)
{
return a.getFrameNumber() > b.getFrameNumber();
}
};
class buffer{
public:
/* CREATE NEW BUFFER */
buffer() : maxsize(RXQSIZE){
/*count = 0;
data = new frame [maxsize];
for (int i = 0; i < maxsize; ++i){
data[i] = 0;
}*/
}
/* DELETE BUFFER REGION */
~buffer(){
}
/* ADD LAST ELEMENT IN BUFFER */
void add(char tx_result[DATASIZE + 15]){
/* Add frame to buffer */
frame frame_(tx_result);
if (!isFull()){
data.push_back(frame_);
data_all.push(frame_);
}
}
/* CONSUME FIRST ELEMENT IN BUFFER */
void consume(frame *frame_){
if (!isEmpty()){
*frame_ = data[0];
data.erase(data.begin());
}
}
/* GETTER CURRENT BUFFER SIZE */
int getCount(){
return data.size();
}
/* GET BUFFER FULL STATUS */
bool isFull(){
return (data.size() == maxsize);
}
/* GET BUFFER EMPTY STATUS */
bool isEmpty(){
return data.empty();
}
priority_queue<frame, vector<frame>, frameComparator> getDataAll() {
return data_all;
}
private:
vector<frame> data; // Buffer memory region
priority_queue<frame, vector<frame>, frameComparator> data_all;
int maxsize; // Maximum buffer size
//Byte *data;
};
class receiver{
public:
/* CREATE NEW RECEIVER OBJECT */
receiver(const char* arg) : port(arg){
createSocket(); // Create new socket
bindSocket(); // Bind socket to IP/Port
doReceive(); // Do the receiving
closeSocket(); // Close socket
}
/* CLOSE RECEIVER SOCKET */
~receiver(){
closeSocket();
}
/* CREATE SOCKET */
void createSocket(){
if ((socket_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
throw "Error opening socket!";
}
}
/* BIND SOCKET */
void bindSocket(){
bzero(&receiver_endpoint, sizeof(receiver_endpoint));
receiver_endpoint.sin_family = AF_INET;
receiver_endpoint.sin_addr.s_addr = htonl(INADDR_ANY);
receiver_endpoint.sin_port = htons(atoi(port));
if (bind(socket_, (struct sockaddr *)&receiver_endpoint, sizeof(receiver_endpoint)) < 0){
throw "Error binding. Try different port!";
} else{
inet_ntop(AF_INET, &(receiver_endpoint.sin_addr), address, INET_ADDRSTRLEN);
cout << "Binding pada " << getAddress() << ":" << getPort() << " ..." << endl;
}
}
/* RECEIVE DATA FROM TRANSMITTER */
void doReceive(){
socklen_t addrlen = sizeof(transmitter_endpoint);
char frame_[DATASIZE + 15];
int received = 1;
thread consume_t(doConsume, &rxbuf, &socket_, &transmitter_endpoint); // Create new thread for consuming the buffer data
do{
int recvlen = recvfrom(socket_, frame_, DATASIZE + 15, 0, (struct sockaddr *)&transmitter_endpoint, &addrlen);
if (recvlen > 0){
//if (c[0]>32 || c[0]==CR || c[0]==LF || c[0]==Endfile){
//cout << "Menerima byte ke-" << received << "." << endl;
//received++;
rxbuf.add(frame_);
//}
}
usleep(DELAY * 1000);
} while(frame_[6] != Endfile);
consume_t.join(); // Join the buffer-consumer thread to this thread
}
/* CONSUME DATA IN BUFFER */
static void doConsume(buffer *buf, int *sockfd, sockaddr_in *transmitter){
socklen_t addrlen = sizeof(*transmitter);
frame frame_;
while(frame_.getData()[0] != Endfile){
if (!buf->isEmpty()){ // Consume the buffer data unless empty
buf->consume(&frame_);
response response_(frame_);
if (response_.getResult()[0] == ACK){
cout << "ACK" << endl;
} else if (response_.getResult()[0] == NAK){
cout << "NAK" << endl;
} else{
cout << "LOL" << endl;
}
cout << "Receiving data: " << frame_.getData() << endl;
if (sendto(*sockfd, response_.getResult(), CHECKSUMSIZE+5, 0, (struct sockaddr *)transmitter, addrlen) < 0){
throw "Error sending signal";
}
}
usleep(DELAY * 3000);
}
priority_queue<frame, vector<frame>, frameComparator> data_all(buf->getDataAll());
// Print data seara terurut
while(!data_all.empty()) {
frame x = data_all.top();
cout << x.getData();
data_all.pop();
}
cout << endl;
}
/* GETTER RECEIVER BOUND ADDRESS */
string getAddress(){
return address;
}
/* GETTER RECEIVER BOUND PORT */
string getPort(){
return port;
}
/* CLOSE SOCKET */
void closeSocket(){
close(socket_);
}
private:
int socket_; // Opened socket
struct sockaddr_in receiver_endpoint; // Receiver endpoint
struct sockaddr_in transmitter_endpoint; // Transmitter endpoint
char address[INET_ADDRSTRLEN]; // Receiver bound address
const char* port; // Receiver bound port
buffer rxbuf; // Buffer
};
int main(int argc, char const *argv[]){
try{
if (argc < 2){ // Parameter checking
throw "Usage: receiver <port>";
}
receiver rx(argv[1]); // Create receiver object
} catch (const char* msg) { // Exception handling
cerr << msg << endl;
} catch(std::exception& e){
cerr << "Exception: " << e.what() << endl; // Unhandled exception
}
return 0;
} | 24.057522 | 122 | 0.647784 | [
"object",
"vector"
] |
b27e9b197220f568ac86525285c7c32a5d0ef0eb | 3,564 | cpp | C++ | tc 160+/StrongEconomy.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/StrongEconomy.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/StrongEconomy.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class StrongEconomy {
public:
long long earn(long long n, long long k, long long price, long long target) {
if (n > k) {
swap(n, k);
}
if (price >= target) {
if (n > 1000000) {
return 1;
}
long long add = n*k;
return (target+add-1)/add;
}
long long cur = 0;
long long rounds = 0;
long long sol = 1234567890123456LL;
while (cur<target && rounds<sol) {
if (n > 1000000) {
return min(sol, rounds + 1);
}
long long add = n*k;
// no buys
sol = min(sol, rounds + (target-cur+add-1)/add);
// buy all
long long can_buy = cur/price;
long long ncur = cur - can_buy*price;
long long nn, nk;
if (n < k) {
long long diff = k - n;
long long x = min(diff, can_buy);
nn = n + x;
nk = k;
can_buy -= x;
} else {
nn = n;
nk = k;
}
nn += can_buy/2;
nk += (can_buy+1)/2;
if (nn > 1000000) {
return min(sol, rounds + 1);
}
long long nadd = nn*nk;
long long to_next_buy = (price-ncur+nadd-1)/nadd;
rounds += to_next_buy;
cur = ncur + to_next_buy * nadd;
n = nn;
k = nk;
}
return min(sol, rounds);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { long long Arg0 = 2LL; long long Arg1 = 1LL; long long Arg2 = 2LL; long long Arg3 = 10LL; long long Arg4 = 4LL; verify_case(0, Arg4, earn(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { long long Arg0 = 2LL; long long Arg1 = 1LL; long long Arg2 = 2LL; long long Arg3 = 9LL; long long Arg4 = 3LL; verify_case(1, Arg4, earn(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { long long Arg0 = 1LL; long long Arg1 = 1LL; long long Arg2 = 500000LL; long long Arg3 = 1000002LL; long long Arg4 = 1000001LL; verify_case(2, Arg4, earn(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { long long Arg0 = 5LL; long long Arg1 = 4LL; long long Arg2 = 15LL; long long Arg3 = 100LL; long long Arg4 = 5LL; verify_case(3, Arg4, earn(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
StrongEconomy ___test;
___test.run_test(-1);
}
// END CUT HERE
| 37.125 | 321 | 0.503367 | [
"vector"
] |
b288bdf6f090a11b9f18189e29e7bd48db535176 | 14,434 | cpp | C++ | lib/testing/gpuTrackingBeamformSimulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 19 | 2018-12-14T00:51:52.000Z | 2022-02-20T02:43:50.000Z | lib/testing/gpuTrackingBeamformSimulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 487 | 2018-12-13T00:59:53.000Z | 2022-02-07T16:12:56.000Z | lib/testing/gpuTrackingBeamformSimulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 5 | 2019-05-09T19:52:19.000Z | 2021-03-27T20:13:21.000Z | #include "gpuTrackingBeamformSimulate.hpp"
#include "Config.hpp" // for Config
#include "StageFactory.hpp" // for REGISTER_KOTEKAN_STAGE, StageMakerTemplate
#include "Telescope.hpp"
#include "buffer.h" // for Buffer, mark_frame_empty, mark_frame_full, pass_metadata
#include "bufferContainer.hpp" // for bufferContainer
#include "chimeMetadata.hpp" // for beamCoord, get_fpga_seq_num, get_gps_time
#include "kotekanLogging.hpp" // for INFO, ERROR
#include <algorithm> // for copy
#include <assert.h> // for assert
#include <atomic> // for atomic_bool
#include <cmath> // for cos, sin, fmod, pow, acos, asin, atan2, sqrt
#include <cstdint> // for int32_t
#include <exception> // for exception
#include <functional> // for _Bind_helper<>::type, bind, function
#include <memory> // for allocator_traits<>::value_type
#include <regex> // for match_results<>::_Base_type
#include <stdexcept> // for runtime_error
#include <stdio.h> // for fclose, fopen, fread, snprintf, FILE
#include <stdlib.h> // for free, malloc
#include <string.h> // for memcpy
#include <time.h> // for tm, timespec, localtime
#define HI_NIBBLE(b) (((b) >> 4) & 0x0F)
#define LO_NIBBLE(b) ((b)&0x0F)
#define PI 3.14159265
#define light 299792458.
#define one_over_c 0.0033356
#define R2D 180. / PI
#define D2R PI / 180.
#define TAU 2 * PI
#define inst_long -119.6175
#define inst_lat 49.3203
using kotekan::bufferContainer;
using kotekan::Config;
using kotekan::Stage;
REGISTER_KOTEKAN_STAGE(gpuTrackingBeamformSimulate);
gpuTrackingBeamformSimulate::gpuTrackingBeamformSimulate(Config& config,
const std::string& unique_name,
bufferContainer& buffer_container) :
Stage(config, unique_name, buffer_container,
std::bind(&gpuTrackingBeamformSimulate::main_thread, this)) {
// Apply config.
_num_elements = config.get<int32_t>(unique_name, "num_elements");
_samples_per_data_set = config.get<int32_t>(unique_name, "samples_per_data_set");
_num_pol = config.get<int32_t>(unique_name, "num_pol");
_num_beams = config.get<int32_t>(unique_name, "num_beams");
_feed_sep_NS = config.get<float>(unique_name, "feed_sep_NS");
_feed_sep_EW = config.get<int32_t>(unique_name, "feed_sep_EW");
_source_ra = config.get<std::vector<float>>(unique_name, "source_ra");
_source_dec = config.get<std::vector<float>>(unique_name, "source_dec");
_reorder_map = config.get<std::vector<int32_t>>(unique_name, "reorder_map");
_gain_dir =
config.get<std::vector<std::string>>(unique_name, "tracking_gain/tracking_gain_dir");
INFO("[TRACKING CPU] start with gain {:s} {:s} {:s}", _gain_dir[0], _gain_dir[1], _gain_dir[2]);
std::vector<float> dg = {0.0, 0.0}; // re,im
default_gains = config.get_default<std::vector<float>>(unique_name, "frb_missing_gains", dg);
input_buf = get_buffer("network_in_buf");
register_consumer(input_buf, unique_name.c_str());
output_buf = get_buffer("beam_out_buf");
register_producer(output_buf, unique_name.c_str());
input_len = _samples_per_data_set * _num_elements * 2;
output_len = _samples_per_data_set * _num_beams * _num_pol * 2;
input_unpacked = (double*)malloc(input_len * sizeof(double));
phase = (double*)malloc(_num_elements * _num_beams * 2 * sizeof(double));
cpu_output = (float*)malloc(output_len * sizeof(float));
assert(phase != nullptr);
cpu_gain = (float*)malloc(2 * _num_elements * _num_beams * sizeof(float));
second_last = 0;
metadata_buf = get_buffer("network_in_buf");
metadata_buffer_id = 0;
metadata_buffer_precondition_id = 0;
freq_now = FREQ_ID_NOT_SET;
freq_MHz = -1;
// Backward compatibility, array in c
reorder_map_c = (int*)malloc(512 * sizeof(int));
for (uint i = 0; i < 512; ++i) {
reorder_map_c[i] = _reorder_map[i];
}
for (int i = 0; i < _num_beams; i++) {
beam_coord.ra[i] = _source_ra[i];
beam_coord.dec[i] = _source_dec[i];
}
}
gpuTrackingBeamformSimulate::~gpuTrackingBeamformSimulate() {
free(input_unpacked);
free(cpu_output);
free(phase);
free(cpu_gain);
free(reorder_map_c);
}
void gpuTrackingBeamformSimulate::reorder(unsigned char* data, int* map) {
int* tmp512;
tmp512 = (int*)malloc(_num_elements * sizeof(int));
for (int j = 0; j < _samples_per_data_set; j++) {
for (int i = 0; i < 512; i++) {
int id = map[i];
tmp512[i * 4] = data[j * _num_elements + (id * 4)];
tmp512[i * 4 + 1] = data[j * _num_elements + (id * 4 + 1)];
tmp512[i * 4 + 2] = data[j * _num_elements + (id * 4 + 2)];
tmp512[i * 4 + 3] = data[j * _num_elements + (id * 4 + 3)];
}
for (uint i = 0; i < _num_elements; i++) {
data[j * _num_elements + i] = tmp512[i];
}
}
free(tmp512);
}
void gpuTrackingBeamformSimulate::calculate_phase(struct beamCoord beam_coord, timespec time_now,
float freq_now, float* gains, double* output) {
float FREQ = freq_now;
struct tm* timeinfo;
timeinfo = localtime(&time_now.tv_sec);
uint year = timeinfo->tm_year + 1900;
uint month = timeinfo->tm_mon + 1;
if (month < 3) {
month = month + 12;
year = year - 1;
}
uint day = timeinfo->tm_mday;
float JD = 2 - int(year / 100.) + int(int(year / 100.) / 4.) + int(365.25 * year)
+ int(30.6001 * (month + 1)) + day + 1720994.5;
double T = (JD - 2451545.0)
/ 36525.0; // Works if time after year 2000, otherwise T is -ve and might break
double T0 = fmod((6.697374558 + (2400.051336 * T) + (0.000025862 * T * T)), 24.);
double UT = (timeinfo->tm_hour) + (timeinfo->tm_min / 60.)
+ (timeinfo->tm_sec + time_now.tv_nsec / 1.e9) / 3600.;
double GST = fmod((T0 + UT * 1.002737909), 24.);
double LST = GST + inst_long / 15.;
while (LST < 0) {
LST = LST + 24;
}
LST = fmod(LST, 24);
for (int b = 0; b < _num_beams; b++) {
double hour_angle = LST * 15. - beam_coord.ra[b];
double alt = sin(beam_coord.dec[b] * D2R) * sin(inst_lat * D2R)
+ cos(beam_coord.dec[b] * D2R) * cos(inst_lat * D2R) * cos(hour_angle * D2R);
alt = asin(alt);
double az = (sin(beam_coord.dec[b] * D2R) - sin(alt) * sin(inst_lat * D2R))
/ (cos(alt) * cos(inst_lat * D2R));
az = acos(az);
if (sin(hour_angle * D2R) >= 0) {
az = TAU - az;
}
double projection_angle, effective_angle, offset_distance;
for (int i = 0; i < 4; i++) { // loop 4 cylinders
for (int j = 0; j < 256; j++) { // loop 256 feeds
float dist_y = j * _feed_sep_NS;
float dist_x = i * _feed_sep_EW;
projection_angle = 90 * D2R - atan2(dist_y, dist_x);
offset_distance = sqrt(pow(dist_y, 2) + pow(dist_x, 2));
effective_angle = projection_angle - az;
float delay_real = cos(TAU * cos(effective_angle) * cos(alt) * offset_distance
* FREQ * one_over_c);
float delay_imag = -sin(TAU * cos(effective_angle) * cos(-alt) * offset_distance
* FREQ * one_over_c);
for (int p = 0; p < 2; p++) { // loop 2 pol
uint elem_id = p * 1024 + i * 256 + j;
// Not scrembled, assume reordering kernel has been run
output[(b * _num_elements + elem_id) * 2] =
delay_real * gains[(b * _num_elements + elem_id) * 2]
- delay_imag * gains[(b * _num_elements + elem_id) * 2 + 1];
output[(b * _num_elements + elem_id) * 2 + 1] =
delay_real * gains[(b * _num_elements + elem_id) * 2 + 1]
+ delay_imag * gains[(b * _num_elements + elem_id) * 2];
}
}
}
}
}
void gpuTrackingBeamformSimulate::cpu_tracking_beamformer(double* input_unpacked, double* phase,
float* cpu_output,
int _samples_per_data_set,
int _num_elements, int _num_beams,
int _num_pol) {
float sum_re, sum_im;
for (int t = 0; t < _samples_per_data_set; t++) {
for (int b = 0; b < _num_beams; b++) {
for (int p = 0; p < _num_pol; p++) {
sum_re = 0.0;
sum_im = 0.0;
for (int n = 0; n < 1024; n++) {
// Input and phase both have pol as second fastest
sum_re += input_unpacked[(t * _num_elements + p * 1024 + n) * 2]
* phase[((b * _num_pol + p) * 1024 + n) * 2]
+ input_unpacked[(t * _num_elements + p * 1024 + n) * 2 + 1]
* phase[((b * _num_pol + p) * 1024 + n) * 2 + 1];
sum_im += (input_unpacked[(t * _num_elements + p * 1024 + n) * 2 + 1]
* phase[((b * _num_pol + p) * 1024 + n) * 2]
- input_unpacked[(t * _num_elements + p * 1024 + n) * 2]
* phase[((b * _num_pol + p) * 1024 + n) * 2 + 1]);
}
cpu_output[(t * _num_beams * _num_pol + b * _num_pol + p) * 2] = sum_re;
cpu_output[(t * _num_beams * _num_pol + b * _num_pol + p) * 2 + 1] = sum_im;
// Output has polarization as fastest varying
}
}
}
}
void gpuTrackingBeamformSimulate::main_thread() {
auto& tel = Telescope::instance();
int input_buf_id = 0;
int output_buf_id = 0;
while (!stop_thread) {
unsigned char* input =
(unsigned char*)wait_for_full_frame(input_buf, unique_name.c_str(), input_buf_id);
if (input == nullptr)
break;
float* output =
(float*)wait_for_empty_frame(output_buf, unique_name.c_str(), output_buf_id);
if (output == nullptr)
break;
for (int i = 0; i < input_len; i++) {
input_unpacked[i] = 0.0; // Need this
}
for (int i = 0; i < output_len; i++) {
cpu_output[i] = 0;
}
INFO("Simulating GPU tracking beamform processing for {:s}[{:d}] putting result in "
"{:s}[{:d}]",
input_buf->buffer_name, input_buf_id, output_buf->buffer_name, output_buf_id);
// Figure out which freq
freq_now = tel.to_freq_id(metadata_buf, metadata_buffer_id);
freq_MHz = tel.to_freq(freq_now);
INFO("[CPU] freq_now={:d} freq+MHz={:.2f} metadat_buf_id={:d} input_buf_id={:d}", freq_now,
freq_MHz, metadata_buffer_id, input_buf_id);
// Load in gains (without dynamic update capability like in GPU, just get set once in the
// beginning)
FILE* ptr_myfile = nullptr;
char filename[512];
for (int b = 0; b < _num_beams; b++) {
snprintf(filename, sizeof(filename), "%s/quick_gains_%04d_reordered.bin",
_gain_dir[b].c_str(), freq_now);
ptr_myfile = fopen(filename, "rb");
if (ptr_myfile == nullptr) {
ERROR("CPU verification code: Cannot open gain file {:s}", filename);
for (uint i = 0; i < _num_elements; i++) {
cpu_gain[(b * _num_elements + i) * 2] = default_gains[0];
cpu_gain[(b * _num_elements + i) * 2 + 1] = default_gains[1];
}
} else {
if (_num_elements
!= fread(&cpu_gain[b * _num_elements * 2], sizeof(float) * 2, _num_elements,
ptr_myfile)) {
ERROR("Couldn't read gain file...");
}
fclose(ptr_myfile);
}
}
INFO("[CPU] gain {:.2f} {:.2f} {:.2f} {:.2f}", cpu_gain[0], cpu_gain[1], cpu_gain[2],
cpu_gain[3]);
// Update phase every one second
const uint64_t phase_update_period = 390625;
uint64_t current_seq = get_fpga_seq_num(metadata_buf, metadata_buffer_id);
second_now = (current_seq / phase_update_period) % 2;
if (second_now != second_last) {
update_phase = true;
}
second_last = second_now;
if (update_phase) {
// GPS time, need ch_master
time_now_gps = get_gps_time(metadata_buf, metadata_buffer_id);
if (time_now_gps.tv_sec == 0) {
ERROR("GPS time appears to be zero, bad news for tracking timing!");
}
calculate_phase(beam_coord, time_now_gps, freq_MHz, cpu_gain, phase);
update_phase = false;
}
// Reorder
reorder(input, reorder_map_c);
// Unpack input data
int dest_idx = 0;
for (int i = 0; i < input_buf->frame_size; ++i) {
input_unpacked[dest_idx++] = HI_NIBBLE(input[i]) - 8;
input_unpacked[dest_idx++] = LO_NIBBLE(input[i]) - 8;
}
// Beamform 10 trackings.
cpu_tracking_beamformer(input_unpacked, phase, cpu_output, _samples_per_data_set,
_num_elements, _num_beams, _num_pol);
memcpy(output, cpu_output, output_buf->frame_size);
INFO(
"Simulating GPU tracking beamform processing done for {:s}[{:d}] result is in {:s}[{:d}"
"]",
input_buf->buffer_name, input_buf_id, output_buf->buffer_name, output_buf_id);
pass_metadata(input_buf, input_buf_id, output_buf, output_buf_id);
mark_frame_empty(input_buf, unique_name.c_str(), input_buf_id);
mark_frame_full(output_buf, unique_name.c_str(), output_buf_id);
input_buf_id = (input_buf_id + 1) % input_buf->num_frames;
metadata_buffer_id = (metadata_buffer_id + 1) % metadata_buf->num_frames;
output_buf_id = (output_buf_id + 1) % output_buf->num_frames;
}
}
| 43.87234 | 100 | 0.560482 | [
"vector"
] |
b28d3b910dce055c839dcfff861b277fba9ca1e2 | 774 | cpp | C++ | LeetCode/Algorithms/Medium/BeautfulArray.cpp | roshan11160/Competitive-Programming-Solutions | 2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e | [
"MIT"
] | 40 | 2020-07-25T19:35:37.000Z | 2022-01-28T02:57:02.000Z | LeetCode/Algorithms/Medium/BeautfulArray.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 160 | 2021-04-26T19:04:15.000Z | 2022-03-26T20:18:37.000Z | LeetCode/Algorithms/Medium/BeautfulArray.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 24 | 2020-05-03T08:11:53.000Z | 2021-10-04T03:23:20.000Z | class Solution {
public:
vector<int> beautifulArray(int n) {
vector<int> result = {1};
// result.push_back(1);
while(result.size() < n)
{
vector<int> curr;
for(int &num: result)
{
if((2 * num)- 1 <= n)
curr.push_back((2 * num) - 1);
}
for(int &num: result)
{
if((2 * num) <= n)
curr.push_back(2 * num);
}
result = curr;
}
return result;
}
};
// Time Complexity - O(N), forms a logarithmic series
// Space Complexity - O(N)
// ---> A bit weird problem but can be solved using simple mathematics, see lee215's solution
| 24.1875 | 93 | 0.432817 | [
"vector"
] |
b2a34af8ad476d70c4e13e265fa25530688032ab | 7,301 | hpp | C++ | include/qpl/maths.hpp | DanielRabl/QPL | 4b487a7d31eab511a961c100ed1985aa11f0572c | [
"Zlib"
] | 5 | 2020-09-02T00:59:26.000Z | 2021-08-21T19:14:40.000Z | include/qpl/maths.hpp | DanielRabl/QPL | 4b487a7d31eab511a961c100ed1985aa11f0572c | [
"Zlib"
] | null | null | null | include/qpl/maths.hpp | DanielRabl/QPL | 4b487a7d31eab511a961c100ed1985aa11f0572c | [
"Zlib"
] | 2 | 2021-01-23T20:03:12.000Z | 2021-08-21T19:15:58.000Z | #ifndef QPL_MATHS_HPP
#define QPL_MATHS_HPP
#pragma once
#include <qpl/qpldeclspec.hpp>
#include <qpl/vardef.hpp>
#include <qpl/string.hpp>
#include <qpl/bits.hpp>
#include <cmath>
#include <sstream>
#include <vector>
namespace qpl {
template<typename T>
bool is_prime(T value) {
if (value < 5u) {
return value == 2u || value == 3u;
}
qpl::u32 add = 2u;
auto sqrt = std::sqrt(value);
for (qpl::u32 i = 5u; i < sqrt; i += add) {
if (value % i == 0) {
return false;
}
add = 6u - add;
}
return true;
}
template<typename T>
std::vector<T> prime_factors(T value) {
if (qpl::is_prime(value)) {
return {};
}
std::vector<T> result;
for (T i = 2; value > T{ 1 }; ++i) {
if (qpl::is_prime(i)) {
while (value % i == T{}) {
result.push_back(i);
value /= i;
}
}
}
return result;
}
template<typename T>
std::vector<T> dividers(T value) {
std::vector<T> result;
for (T i = 1; i < value; ++i) {
if (value % i == T{}) {
result.push_back(i);
}
}
return result;
}
struct exponential_moving_average {
exponential_moving_average(qpl::f64 time_period = 5.0) {
this->time_period = time_period;
}
qpl::f64 time_period;
qpl::size time_ctr = 0u;
qpl::f64 last_ma = 0.0;
QPLDLL void reset();
QPLDLL void add_value(double value);
QPLDLL double get_average() const;
};
template<typename T>
struct fast_moving_average {
void reset() {
this->ctr = 0u;
this->sum = T{ 0 };
this->progress = 0u;
}
void set_time_period(qpl::u32 time_period) {
this->time_period = time_period;
}
void set_step(qpl::u32 ctr) {
this->ctr = ctr;
this->sum = T{ 0 };
this->progress = 0u;
}
qpl::size used_size() const {
return qpl::min(this->time_period, this->progress);
}
template<typename R = qpl::f64>
R get_average() const {
return static_cast<R>(this->sum) / static_cast<R>(this->used_size());
}
void add(T add, T subtract) {
this->sum += add;
if (this->progress >= this->time_period) {
this->sum -= subtract;
}
++this->ctr;
++this->progress;
}
qpl::size get_needed_index(qpl::u32 index) const {
return index - this->used_size();
}
T sum = T{ 0 };
qpl::u32 time_period = 1u;
qpl::u32 ctr = 0u;
qpl::u32 progress = 0u;
};
enum class mathematical_operation {
none, add, sub, mul, div, pow
};
QPLDLL std::string mathematical_operation_string(mathematical_operation op);
enum class mathematical_prefix {
none, positive, negated
};
template<typename T>
struct mathematical_functon {
struct number_operation {
constexpr mathematical_operation get_operation() const {
return static_cast<mathematical_operation>(this->info[{0, 3}].get());
}
constexpr void set_operation(mathematical_operation operation) {
this->info[{0, 3}] = qpl::u64_cast(operation);
}
constexpr mathematical_prefix get_prefix() const {
return static_cast<mathematical_prefix>(this->info[{4, 5}].get());
}
constexpr void set_prefix(mathematical_prefix prefix) {
this->info[{4, 5}] = qpl::u64_cast(prefix);
}
constexpr bool is_link() const {
return this->info[6];
}
constexpr qpl::u32 get_link() const {
return qpl::u32_cast(this->number);
}
constexpr void set_link(qpl::u32 link) {
this->info[6] = true;
this->number = qpl::f64_cast(link);
}
constexpr bool is_variable() const {
return this->info[7];
}
constexpr qpl::u32 get_variable() const {
return qpl::u32_cast(this->number);
}
constexpr void set_variable(qpl::u32 variable_index) {
this->info[7] = true;
this->number = qpl::f64_cast(variable_index);
}
constexpr void clear() {
this->info.clear();
this->number = 0u;
}
std::string string() const {
std::ostringstream stream;
if (this->get_prefix() == mathematical_prefix::negated) {
stream << "-";
}
else if (this->get_prefix() == mathematical_prefix::positive) {
stream << "+";
}
if (this->is_link()) {
stream << qpl::to_string("#", this->get_link());
}
else if (this->is_variable()) {
stream << qpl::to_string("v", this->get_variable());
}
else {
stream << this->number;
}
if (this->get_operation() != mathematical_operation::none) {
stream << " " << mathematical_operation_string(this->get_operation());
}
return stream.str();
}
T number;
qpl::bitset<32> info;
};
std::vector<number_operation> chain;
std::vector<number_operation> result;
template <class C>
constexpr T solve(const C& variables) {
this->result = this->chain;
for (qpl::u32 i = 0u; i < this->result.size() - 1; ++i) {
for (qpl::u32 c = i; c < this->result.size() - 1; ++c) {
auto op = this->result[c].get_operation();
auto is_c_non = (this->result[c + 1].get_operation() == mathematical_operation::none);
if (i == c) {
if (this->result[i].is_link()) {
this->result[i].number = this->result[this->result[i].get_link()].number;
}
else if (this->result[i].is_variable()) {
this->result[i].number = variables[this->result[i].get_variable()];
}
auto prefix = this->result[i].get_prefix();
if (prefix == qpl::mathematical_prefix::negated) {
this->result[i].number = -this->result[i].number;
}
else if (prefix == qpl::mathematical_prefix::positive) {
this->result[i].number = +this->result[i].number;
}
//qpl::print(this->result[i].number, " ", mathematical_operation_string(op), " ");
}
//qpl::print(this->result[c + 1].string(), " ");
T right = this->result[c + 1].number;
auto prefix = this->result[c + 1].get_prefix();
if (this->result[c + 1].is_link()) {
right = this->result[this->result[c + 1].get_link()].number;
}
else if (this->result[c + 1].is_variable()) {
right = variables[this->result[c + 1].get_variable()];
}
if (prefix == qpl::mathematical_prefix::negated) {
right = -right;
}
else if (prefix == qpl::mathematical_prefix::positive) {
right = +right;
}
switch (op) {
case mathematical_operation::add:
this->result[i].number += right; break;
case mathematical_operation::sub:
this->result[i].number -= right; break;
case mathematical_operation::mul:
this->result[i].number *= right; break;
case mathematical_operation::div:
if (right == 0) this->result[i].number = 0;
else this->result[i].number /= right;
break;
case mathematical_operation::pow:
this->result[i].number = std::pow(this->result[i].number, right); break;
}
if (is_c_non) {
//qpl::println("=> ", this->result[i].number);
if (c == this->result.size() - 2) {
return this->result[i].number;
}
i = c + 1;
break;
}
}
}
}
template<typename... Args>
constexpr T operator()(Args... variables) {
return this->solve(qpl::to_array<T>(variables...));
}
std::string string() const {
std::ostringstream stream;
for (auto& i : this->chain) {
stream << i.string() << " ";
if (i.get_operation() == qpl::mathematical_operation::none) {
stream << '\n';
}
}
return stream.str();
}
};
}
#endif | 24.749153 | 91 | 0.601835 | [
"vector"
] |
b2a53e2b6a36cb5205b4784e3ce293c5d4227c7f | 1,169 | cpp | C++ | Test/Function/test_logic.cpp | CrackerCat/MiniSTL | d94fa37f69313a2ea99ab983239270839dc962b3 | [
"MIT"
] | null | null | null | Test/Function/test_logic.cpp | CrackerCat/MiniSTL | d94fa37f69313a2ea99ab983239270839dc962b3 | [
"MIT"
] | null | null | null | Test/Function/test_logic.cpp | CrackerCat/MiniSTL | d94fa37f69313a2ea99ab983239270839dc962b3 | [
"MIT"
] | null | null | null | #include "Algorithms/algo/stl_algo.h"
#include "Function/stl_function.h"
#include <gtest/gtest.h>
using namespace ::MiniSTL;
class LogicTest : public testing::Test {
protected:
void SetUp() override {
}
};
TEST_F(LogicTest, logicand) {
bool input1[4] = {true, true, false, true};
bool input2[4] = {false, true, false, false};
bool output[4];
transform((bool *) input1, (bool *) input1 + 4, (bool *) input2, (bool *) output, logical_and<bool>());
ASSERT_TRUE(output[0] == false);
ASSERT_TRUE(output[1] == true);
ASSERT_TRUE(output[2] == false);
ASSERT_TRUE(output[3] == false);
}
TEST_F(LogicTest, logicnot) {
bool input[7] = {true, false, false, true, true, true, true};
int n = count_if(input, input + 7, logical_not<bool>());
ASSERT_TRUE(n == 2);
}
TEST_F(LogicTest, logicor) {
bool input1[4] = {true, true, false, true};
bool input2[4] = {false, true, false, false};
bool output[4];
transform((bool *) input1, (bool *) input1 + 4, (bool *) input2, (bool *) output, logical_or<bool>());
ASSERT_TRUE(output[0] == true);
ASSERT_TRUE(output[1] == true);
ASSERT_TRUE(output[2] == false);
ASSERT_TRUE(output[3] == true);
} | 28.512195 | 105 | 0.650128 | [
"transform"
] |
b2a73333eb9842ebd8679d9361eb2437170e60e4 | 5,479 | hpp | C++ | include/CL/sycl/detail/debug.hpp | infinitesnow/InceptionCL | e3d3a6218e551d42dfcead4f121cec294d50d85c | [
"Unlicense"
] | 2 | 2017-10-05T13:13:41.000Z | 2019-05-15T19:20:49.000Z | include/CL/sycl/detail/debug.hpp | infinitesnow/InceptionCL | e3d3a6218e551d42dfcead4f121cec294d50d85c | [
"Unlicense"
] | null | null | null | include/CL/sycl/detail/debug.hpp | infinitesnow/InceptionCL | e3d3a6218e551d42dfcead4f121cec294d50d85c | [
"Unlicense"
] | null | null | null | #ifndef TRISYCL_SYCL_DETAIL_DEBUG_HPP
#define TRISYCL_SYCL_DETAIL_DEBUG_HPP
/** \file Track constructor/destructor invocations and trace kernel execution
Define the TRISYCL_DEBUG CPP flag to have an output.
To use it in some class C, make C inherit from debug<C>.
Ronan at Keryell point FR
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
*/
#include <iostream>
// The common debug and trace infrastructure
#if defined(TRISYCL_DEBUG) || defined(TRISYCL_TRACE_KERNEL)
#include <sstream>
#include <string>
#include <thread>
#include <boost/log/trivial.hpp>
#include <boost/type_index.hpp>
// To be able to construct string literals like "blah"s
using namespace std::string_literals;
/** Dump a debug message in a formatted way.
Use an intermediate ostringstream because there are issues with
BOOST_LOG_TRIVIAL to display C strings
*/
#define TRISYCL_INTERNAL_DUMP(expression) do { \
std::ostringstream s; \
s << expression; \
BOOST_LOG_TRIVIAL(debug) << s.str(); \
} while(0)
#endif
#ifdef TRISYCL_DEBUG
#define TRISYCL_DUMP(expression) TRISYCL_INTERNAL_DUMP(expression)
/// Same as TRISYCL_DUMP() but with thread id first
#define TRISYCL_DUMP_T(expression) \
TRISYCL_DUMP("Thread " << std::hex \
<< std::this_thread::get_id() << ": " << expression)
#else
#define TRISYCL_DUMP(expression) do { } while(0)
#define TRISYCL_DUMP_T(expression) do { } while(0)
#endif
namespace cl {
namespace sycl {
namespace detail {
/** \addtogroup debug_trace Debugging and tracing support
@{
*/
/** Class used to trace the construction, copy-construction,
move-construction and destruction of classes that inherit from it
\param T is the real type name to be used in the debug output.
*/
template <typename T>
struct debug {
// To trace the execution of the conSTRUCTORs and deSTRUCTORs
#ifdef TRISYCL_DEBUG_STRUCTORS
/// Trace the construction with the compiler-dependent mangled named
debug() {
TRISYCL_DUMP("Constructor of "
<< boost::typeindex::type_id<T>().pretty_name()
<< " " << (void*) this);
}
/** Trace the copy construction with the compiler-dependent mangled
named
Only add this constructor if T has itself the same constructor,
otherwise it may prevent the synthesis of default copy
constructor and assignment.
*/
template <typename U = T>
debug(debug const &,
/* Use intermediate U type to have the type dependent for
enable_if to work
\todo Use is_copy_constructible_v when moving to C++17 */
std::enable_if_t<std::is_copy_constructible<U>::value> * = 0) {
TRISYCL_DUMP("Copy of " << boost::typeindex::type_id<T>().pretty_name()
<< " " << (void*) this);
}
/** Trace the move construction with the compiler-dependent mangled
named
Only add this constructor if T has itself the same constructor,
otherwise it may prevent the synthesis of default move
constructor and move assignment.
*/
template <typename U = T>
debug(debug &&,
/* Use intermediate U type to have the type dependent for
enable_if to work
\todo Use is_move_constructible_v when moving to C++17 */
std::enable_if_t<std::is_move_constructible<U>::value> * = 0) {
TRISYCL_DUMP("Move of " << boost::typeindex::type_id<T>().pretty_name()
<< " " << (void*) this);
}
/// Trace the destruction with the compiler-dependent mangled named
~debug() {
TRISYCL_DUMP("~ Destructor of "
<< boost::typeindex::type_id<T>().pretty_name()
<< " " << (void*) this);
}
#endif
};
/** Wrap a kernel functor in some tracing messages to have start/stop
information when TRISYCL_TRACE_KERNEL macro is defined */
template <typename KernelName, typename Functor>
auto trace_kernel(const Functor &f) {
#ifdef TRISYCL_TRACE_KERNEL
// Inject tracing message around the kernel
return [=] {
/* Since the class KernelName may just be declared and not really
defined, just use it through a class pointer to have
typeid().name() not complaining */
TRISYCL_INTERNAL_DUMP(
"Kernel started "
<< boost::typeindex::type_id<KernelName *>().pretty_name());
f();
TRISYCL_INTERNAL_DUMP(
"Kernel stopped "
<< boost::typeindex::type_id<KernelName *>().pretty_name());
};
#else
// Identity by default
return f;
#endif
}
/** Class used to display a vector-like type of classes that inherit from
it
\param T is the real type name to be used in the debug output.
Calling the display() method dump the values on std::cout
*/
template <typename T>
struct display_vector {
/// To debug and test
void display() const {
#ifdef TRISYCL_DEBUG
std::cout << boost::typeindex::type_id<T>().pretty_name() << ":";
#endif
// Get a pointer to the real object
for (auto e : *static_cast<const T *>(this))
std::cout << " " << e;
std::cout << std::endl;
}
};
/// @} End the debug_trace Doxygen group
}
}
}
/*
# Some Emacs stuff:
### Local Variables:
### ispell-local-dictionary: "american"
### eval: (flyspell-prog-mode)
### End:
*/
#endif // TRISYCL_SYCL_DETAIL_DEBUG_HPP
| 28.836842 | 77 | 0.655047 | [
"object",
"vector"
] |
b2b0912ad14b78991199c3ee7f445d06cddcbd06 | 24,384 | cpp | C++ | App/enclave_bridge.cpp | goten-team/Goten | 690f1429b62c70caec72f4010ee5b7a9786f0d25 | [
"MIT"
] | 17 | 2020-04-28T09:18:28.000Z | 2021-12-28T08:38:00.000Z | App/enclave_bridge.cpp | goten-team/Goten | 690f1429b62c70caec72f4010ee5b7a9786f0d25 | [
"MIT"
] | 2 | 2021-09-26T04:10:51.000Z | 2022-03-31T05:28:25.000Z | App/enclave_bridge.cpp | goten-team/Goten | 690f1429b62c70caec72f4010ee5b7a9786f0d25 | [
"MIT"
] | 2 | 2021-09-26T05:06:17.000Z | 2021-12-14T16:25:06.000Z | #include <stdio.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <chrono>
#include <memory>
#include <omp.h>
#include <unordered_map>
#include <cstdlib>
#include <malloc.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include "sgx_tseal.h"
#include "sgx_urts.h"
#include "Enclave_u.h"
#include "common_with_enclaves.h"
#include "common_utils.cpp"
#include "crypto_common.h"
#include "ThreadPool.h"
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define TOKEN_FILENAME "enclave.token"
#define ENCLAVE_FILENAME "enclave.signed.so"
using namespace std::chrono;
using std::shared_ptr;
using std::make_shared;
#define eidT unsigned long int eid
typedef struct _sgx_errlist_t {
sgx_status_t err;
const char *msg;
const char *sug; /* Suggestion */
} sgx_errlist_t;
/* Error code returned by sgx_create_enclave */
static sgx_errlist_t sgx_errlist[] = {
{
SGX_ERROR_UNEXPECTED,
"Unexpected error occurred.",
NULL
},
{
SGX_ERROR_INVALID_PARAMETER,
"Invalid parameter.",
NULL
},
{
SGX_ERROR_OUT_OF_MEMORY,
"Out of memory.",
NULL
},
{
SGX_ERROR_ENCLAVE_LOST,
"Power transition occurred.",
"Please refer to the sample \"PowerTransition\" for details."
},
{
SGX_ERROR_INVALID_ENCLAVE,
"Invalid enclave image.",
NULL
},
{
SGX_ERROR_INVALID_ENCLAVE_ID,
"Invalid enclave identification.",
NULL
},
{
SGX_ERROR_INVALID_SIGNATURE,
"Invalid enclave signature.",
NULL
},
{
SGX_ERROR_OUT_OF_EPC,
"Out of EPC memory.",
NULL
},
{
SGX_ERROR_NO_DEVICE,
"Invalid SGX device.",
"Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards."
},
{
SGX_ERROR_MEMORY_MAP_CONFLICT,
"Memory map conflicted.",
NULL
},
{
SGX_ERROR_INVALID_METADATA,
"Invalid enclave metadata.",
NULL
},
{
SGX_ERROR_DEVICE_BUSY,
"SGX device was busy.",
NULL
},
{
SGX_ERROR_INVALID_VERSION,
"Enclave version was invalid.",
NULL
},
{
SGX_ERROR_INVALID_ATTRIBUTE,
"Enclave was not authorized.",
NULL
},
{
SGX_ERROR_ENCLAVE_FILE_ACCESS,
"Can't open enclave file.",
NULL
},
};
void print_error_message(sgx_status_t ret);
DimsT CreateDims(int dim0_, int dim1_, int dim2_, int dim3_) {
DimsT res = {dim0_, dim1_, dim2_, dim3_};
return res;
}
inline int CeilDiv(int x, int y) {
return (x + y - 1)/y;
}
inline int FloorDiv(int x, int y) {
return x / y;
}
// Eigen::Map<Eigen::Matrix<DtypeForCpuOp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
void ModP(MapMatRowMajor& m) {
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<DtypeForCpuOp>(1) / PrimeLimit;
MatRowMajor mat = m;
// m = m - (mat * invPLimit) * PLimit;
m.array() = m.array() - (mat * invPLimit).array().floor() * PLimit;
}
void ModP(MapEigenTensor& m) {
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<DtypeForCpuOp>(1) / PrimeLimit;
m = m - (m * invPLimit).floor() * PLimit;
}
/* Check error conditions for loading enclave */
void print_error_message(sgx_status_t ret)
{
size_t idx = 0;
size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0];
for (idx = 0; idx < ttl; idx++) {
if(ret == sgx_errlist[idx].err) {
if(NULL != sgx_errlist[idx].sug)
printf("Info: %s\n", sgx_errlist[idx].sug);
printf("Error: %s\n", sgx_errlist[idx].msg);
break;
}
}
if (idx == ttl)
printf("Error: Unexpected error occurred.\n");
}
/* OCall functions */
void ocall_print_string(const char *str)
{
/* Proxy/Bridge will check the length and null-terminate
* the input string to prevent buffer overflow.
*/
printf("%s", str);
}
thread_local std::chrono::time_point<std::chrono::high_resolution_clock> start;
void ocall_start_clock()
{
start = std::chrono::high_resolution_clock::now();
}
void ocall_end_clock(const char * str)
{
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
printf(str, elapsed.count());
}
double ocall_get_time()
{
auto now = std::chrono::high_resolution_clock::now();
return time_point_cast<microseconds>(now).time_since_epoch().count();
}
void* ocall_allocate_mem(int num_byte) {
void* res = (void*)malloc(num_byte);
return res;
}
class UntrustedChunkManager {
public:
static UntrustedChunkManager& getInstance() {
static UntrustedChunkManager instance; // Guaranteed to be destroyed.
return instance;
}
UntrustedChunkManager(UntrustedChunkManager const&) = delete;
void operator=(UntrustedChunkManager const&) = delete;
void StoreChunk(IdT id, void* src_buf, int num_byte) {
void* dst_buf;
bool is_diff_size = false;
auto it = IdAddress.begin();
auto end = IdAddress.end();
{
std::unique_lock <std::mutex> lock(address_mutex);
it = IdAddress.find(id);
end = IdAddress.end();
}
if (it == end) {
dst_buf = (void*)malloc(num_byte);
{
std::unique_lock<std::mutex> lock(address_mutex);
IdAddress[id] = dst_buf;
IdSize[id] = num_byte;
}
} else {
std::unique_lock<std::mutex> lock(address_mutex);
dst_buf = IdAddress[id];
if (IdSize[id] != num_byte) {
is_diff_size = true;
}
}
if (is_diff_size) {
throw std::invalid_argument("A id has assigned with multiple size.");
}
memcpy(dst_buf, src_buf, num_byte);
}
void GetChunk(IdT id, void* dst_buf, int num_byte) {
auto it = IdAddress.begin();
auto end = IdAddress.end();
void* src_buf;
{
std::unique_lock <std::mutex> lock(address_mutex);
auto it = IdAddress.find(id);
auto end = IdAddress.end();
}
if (it == end) {
throw std::invalid_argument("Id doesnt exist");
}
{
std::unique_lock <std::mutex> lock(address_mutex);
src_buf = IdAddress[id];
}
memcpy(dst_buf, src_buf, num_byte);
}
private:
UntrustedChunkManager() {}
std::unordered_map<IdT, void*> IdAddress;
std::unordered_map<IdT, int> IdSize;
std::mutex address_mutex;
};
ThreadPool thread_pool(THREAD_POOL_SIZE);
std::vector< std::future<TaskIdT> > task_results;
TaskIdT task_indexor = -1;
TaskIdT task_counter = 0;
const int max_async_task = 1000;
template<typename Func>
TaskIdT add_async_task(Func f) {
// task_results.emplace_back(thread_pool.enqueue(f));
// task_indexor++;
// return task_indexor;
if (task_results.size() < max_async_task) {
task_results.resize(max_async_task + 5);
}
TaskIdT task_id = (task_indexor + 1) % max_async_task;
// task_results.emplace(task_results.begin() + task_id, thread_pool.enqueue(f));
task_results[task_id] = std::future<TaskIdT>(thread_pool.enqueue(f));
task_indexor = task_id;
return task_id;
}
extern "C"
{
/*
* Initialize the enclave
*/
uint64_t initialize_enclave(void)
{
std::cout << "Initializing Enclave..." << std::endl;
sgx_enclave_id_t eid = 0;
sgx_launch_token_t token = {0};
sgx_status_t ret = SGX_ERROR_UNEXPECTED;
int updated = 0;
/* call sgx_create_enclave to initialize an enclave instance */
/* Debug Support: set 2nd parameter to 1 */
ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);
if (ret != SGX_SUCCESS) {
print_error_message(ret);
throw ret;
}
std::cout << "Enclave id: " << eid << std::endl;
return eid;
}
/*
* Destroy the enclave
*/
void destroy_enclave(uint64_t eid)
{
std::cout << "Destroying Enclave with id: " << eid << std::endl;
sgx_destroy_enclave(eid);
}
int CalcEncNeededInByte(const uint32_t txt_encrypt_size) {
return CalcEncDataSize(0, txt_encrypt_size * sizeof(DtypeForCpuOp));
}
void InitTensor(EidT eid, IdT TenId, int dim0, int dim1, int dim2, int dim3) {
DimsT Dims = CreateDims(dim0, dim1, dim2, dim3);
sgx_status_t ret = ecall_init_tensor(eid, TenId, (void*) &Dims);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void SetTen(EidT eid, IdT TenId, DtypeForCpuOp* Arr) {
sgx_status_t ret = ecall_set_ten(eid, TenId, (void*) Arr);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void GetTen(EidT eid, IdT TenId, DtypeForCpuOp* Arr) {
sgx_status_t ret = ecall_get_ten(eid, TenId, (void*) Arr);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void SetSeed(EidT eid, IdT TenId, uint64_t RawSeed) {
sgx_status_t ret = ecall_set_seed(eid, TenId, RawSeed);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void GetRandom(EidT eid, IdT TenId, DtypeForCpuOp* Arr, uint64_t RawSeed) {
sgx_status_t ret = ecall_get_random(eid, TenId, (void*) Arr, RawSeed);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void GetShare(EidT eid, IdT TenId, DtypeForCpuOp* Arr, uint64_t RawSeed) {
sgx_status_t ret = ecall_get_share(eid, TenId, (void*) Arr, RawSeed);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void MaskingC01(EidT eid, IdT storeId, uint64_t mainRawSeed, uint64_t rawSeed0, uint64_t rawSeed1, DtypeForCpuOp *DstArr) {
sgx_status_t ret = ecall_masking_c01(eid, storeId, mainRawSeed, rawSeed0, rawSeed1, DstArr);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncMaskingC01(EidT eid, IdT storeId, uint64_t mainRawSeed, uint64_t rawSeed0, uint64_t rawSeed1, DtypeForCpuOp *DstArr) {
return add_async_task( [=, task_counter] {
MaskingC01(eid, storeId, mainRawSeed, rawSeed0, rawSeed1, DstArr);
return task_counter;
});
}
void AddFromCpu(EidT eid, void* inputArr, IdT dstId) {
sgx_status_t ret = ecall_add_from_cpu(eid, inputArr, dstId);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncAddFromCpu(EidT eid, void* inputArr, IdT dstId) {
return add_async_task( [=, task_counter] {
AddFromCpu(eid, inputArr, dstId);
return task_counter;
});
}
void AesEncryptTensor(DtypeForCpuOp* SrcBuf, uint32_t NumElem, uint8_t* DstBuf) {
SgxEncT* Dst = (SgxEncT*) DstBuf;
uint32_t NumByte = NumElem * sizeof(DtypeForCpuOp);
encrypt((uint8_t *) SrcBuf,
NumByte,
(uint8_t *) (&(Dst->payload)),
(sgx_aes_gcm_128bit_iv_t *)(&(Dst->reserved)),
(sgx_aes_gcm_128bit_tag_t *)(&(Dst->payload_tag)));
}
void AesDecryptTensor(uint8_t* SrcBuf, uint32_t NumElem, DtypeForCpuOp* DstBuf) {
SgxEncT* Src = (SgxEncT*) SrcBuf;
uint32_t NumByte = NumElem * sizeof(DtypeForCpuOp);
float* blind = (float*)malloc(NumByte);
decrypt((uint8_t *) (&(Src->payload)),
NumByte,
(uint8_t *) DstBuf,
(sgx_aes_gcm_128bit_iv_t *)(&(Src->reserved)),
(sgx_aes_gcm_128bit_tag_t *)(&(Src->payload_tag)),
(uint8_t *) blind);
free(blind);
}
int GetTaskStatus(TaskIdT task_id) {
auto && task_future = task_results[task_id];
std::future_status task_status = task_future.wait_for(std::chrono::microseconds::zero());
if (task_status == std::future_status::ready) {
// std::cout << "Task is ready: " << task_future.get() << std::endl;
return 1;
} else {
return 0;
}
}
TaskIdT AsyncGetRandom(EidT eid, IdT TenId, DtypeForCpuOp* Arr, uint64_t RawSeed) {
return add_async_task( [=, task_counter] {
GetRandom(eid, TenId, Arr, RawSeed);
return task_counter;
});
}
TaskIdT AsyncGetShare(EidT eid, IdT TenId, DtypeForCpuOp* Arr, uint64_t RawSeed) {
return add_async_task( [=, task_counter] {
GetShare(eid, TenId, Arr, RawSeed);
return task_counter;
});
}
void SgdUpdate(EidT eid, IdT paramId, IdT gradId, IdT momentumId,
DtypeForCpuOp lr, DtypeForCpuOp momentum, DtypeForCpuOp weight_decay,
DtypeForCpuOp dampening, bool nesterov, bool first_momentum) {
sgx_status_t ret = ecall_sgd_update(eid, paramId, gradId, momentumId,
lr, momentum, weight_decay, dampening, nesterov, first_momentum);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncSgdUpdate(EidT eid, IdT paramId, IdT gradId, IdT momentumId,
DtypeForCpuOp lr, DtypeForCpuOp momentum, DtypeForCpuOp weight_decay,
DtypeForCpuOp dampening, bool nesterov, bool first_momentum) {
return add_async_task( [=, task_counter] {
SgdUpdate(eid, paramId, gradId, momentumId, lr, momentum, weight_decay, dampening, nesterov, first_momentum);
return task_counter;
});
}
void StochasticQuantize(EidT eid, IdT src_id, IdT dst_id, uint64_t q_tag) {
sgx_status_t ret = ecall_stochastic_quantize(eid, src_id, dst_id, q_tag);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncStochasticQuantize(EidT eid, IdT src_id, IdT dst_id, uint64_t q_tag) {
return add_async_task( [=, task_counter] {
StochasticQuantize(eid, src_id, dst_id, q_tag);
return task_counter;
});
}
void FusedQuantizeShare(EidT eid, IdT af_id, DtypeForCpuOp* e_arr, uint64_t q_tag, uint64_t u_seed) {
sgx_status_t ret = ecall_fused_quantize_share(eid, af_id, e_arr, q_tag, u_seed);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncFusedQuantizeShare(EidT eid, IdT af_id, DtypeForCpuOp* e_arr, uint64_t q_tag, uint64_t u_seed) {
return add_async_task( [=, task_counter] {
FusedQuantizeShare(eid, af_id, e_arr, q_tag, u_seed);
return task_counter;
});
}
void ReLUfunction(EidT eid, IdT TenIdin, IdT TenIdout, uint64_t size){
sgx_status_t ret = ecall_relu(eid, TenIdin, TenIdout, size);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void ReLUbackward(EidT eid, IdT TenIdout, IdT TenIddout, IdT TenIddin, uint64_t size){
sgx_status_t ret = ecall_reluback(eid, TenIdout, TenIddout, TenIddin, size);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void FusedQuantizeShare2(EidT eid, IdT af_id, DtypeForCpuOp* a1_arr, DtypeForCpuOp* e_arr,
uint64_t q_tag, uint64_t a0_seed, uint64_t u_seed) {
sgx_status_t ret = ecall_fused_quantize_share2(eid, af_id, a1_arr, e_arr, q_tag, a0_seed, u_seed);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncFusedQuantizeShare2(EidT eid, IdT af_id, DtypeForCpuOp* a1_arr, DtypeForCpuOp* e_arr,
uint64_t q_tag, uint64_t a0_seed, uint64_t u_seed) {
return add_async_task( [=, task_counter] {
FusedQuantizeShare2(eid, af_id, a1_arr, e_arr, q_tag, a0_seed, u_seed);
return task_counter;
});
}
void FusedRecon(EidT eid, IdT cf_id, IdT cq_id, DtypeForCpuOp* c_left_arr, uint64_t x_tag, uint64_t y_tag) {
sgx_status_t ret = ecall_secret_fused_recon(eid, cf_id, cq_id, c_left_arr, x_tag, y_tag);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
TaskIdT AsyncFusedRecon(EidT eid, IdT cf_id, IdT cq_id, DtypeForCpuOp* c_left_arr, uint64_t x_tag, uint64_t y_tag) {
return add_async_task( [=, task_counter] {
FusedRecon(eid, cf_id, cq_id, c_left_arr, x_tag, y_tag);
return task_counter;
});
}
void AsyncTask(EidT eid,
IdT TenId1, DtypeForCpuOp* Arr1, uint64_t size1, uint64_t RawSeed1,
IdT TenId2, DtypeForCpuOp* Arr2, uint64_t size2, uint64_t RawSeed2,
IdT TenId3, DtypeForCpuOp* Arr3, uint64_t size3, uint64_t RawSeed3,
IdT TenId4, DtypeForCpuOp* Arr4, uint64_t size4, uint64_t RawSeed4
) {
// ThreadPool pool(4);
auto& pool = thread_pool;
std::vector< std::future<int> > results;
std::cout << "AsyncTask" << std::endl;
results.emplace_back( pool.enqueue([&] {
sgx_status_t ret = ecall_get_share(eid, TenId1, (void*) Arr1, RawSeed1);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
return 1;
}));
results.emplace_back( pool.enqueue([&] {
sgx_status_t ret = ecall_get_share(eid, TenId2, (void*) Arr2, RawSeed2);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
return 2;
}));
results.emplace_back( pool.enqueue([&] {
sgx_status_t ret = ecall_get_share(eid, TenId3, (void*) Arr3, RawSeed3);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
return 3;
}));
results.emplace_back( pool.enqueue([&] {
sgx_status_t ret = ecall_get_share(eid, TenId4, (void*) Arr4, RawSeed4);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
return 4;
}));
for(auto && result: results) std::cout << result.get() << std::endl;
std::cout << std::endl;
}
void InitMaxpool(EidT eid, IdT FunId, IdT TenIdin_trans, IdT TenIdout_trans){
sgx_status_t ret = ecall_initmaxpool(eid, FunId, TenIdin_trans, TenIdout_trans);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void Maxpoolfunction(EidT eid, IdT FunId, IdT TenIdin, IdT TenIdout, uint32_t batch, uint32_t channel, uint32_t input_height, uint32_t input_width, uint32_t output_height, uint32_t output_width, uint32_t filter_height, uint32_t filter_width, uint32_t row_stride,uint32_t col_stride, uint32_t row_pad, uint32_t col_pad){
sgx_status_t ret = ecall_maxpool(eid, FunId, TenIdin, TenIdout, batch, channel, input_height, input_width, output_height, output_width, filter_height, filter_width, row_stride, col_stride, row_pad, col_pad);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void Maxpoolbackwardfunction(EidT eid, IdT FunId, IdT TenIddout, IdT TenIddin, uint32_t batch, uint32_t channel, uint32_t input_height, uint32_t input_width, uint32_t output_height, uint32_t output_width, uint32_t filter_height, uint32_t filter_width, uint32_t row_stride,uint32_t col_stride){
sgx_status_t ret = ecall_maxpoolback(eid, FunId, TenIddout, TenIddin, batch, channel, input_height, input_width, output_height, output_width, filter_height, filter_width, row_stride, col_stride);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void InitBatchnorm(
EidT eid,
IdT FunId,
IdT input, IdT output, IdT gamma, IdT beta,
IdT der_input, IdT der_output, IdT der_gamma, IdT der_beta,
IdT run_mean, IdT run_var, IdT cur_mean, IdT cur_var,
IdT mu,
uint32_t batch_, uint32_t channel_, uint32_t height_, uint32_t width_,
int affine_, int is_cumulative_, float momentum_, float epsilon_) {
sgx_status_t ret = ecall_init_batchnorm(
eid,
FunId,
input, output, gamma, beta,
der_input, der_output, der_gamma, der_beta,
run_mean, run_var, cur_mean, cur_var,
mu,
batch_, channel_, height_, width_,
affine_, is_cumulative_, momentum_, epsilon_);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void BatchnormForward(EidT eid, uint64_t FunId, int Training) {
sgx_status_t ret = ecall_batchnorm_forward(eid, FunId, Training);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
void BatchnormBackward(EidT eid, uint64_t FunId) {
sgx_status_t ret = ecall_batchnorm_backward(eid, FunId);
if (ret != SGX_SUCCESS) { print_error_message(ret); throw ret; }
}
}
/* Application entry */
int main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
try {
sgx_enclave_id_t eid = initialize_enclave();
std::cout << "Enclave id: " << eid << std::endl;
// const unsigned int filter_sizes[] = {3*3*3*64, 64,
// 3*3*64*64, 64,
// 3*3*64*128, 128,
// 3*3*128*128, 128,
// 3*3*128*256, 256,
// 3*3*256*256, 256,
// 3*3*256*256, 256,
// 3*3*256*512, 512,
// 3*3*512*512, 512,
// 3*3*512*512, 512,
// 3*3*512*512, 512,
// 3*3*512*512, 512,
// 3*3*512*512, 512,
// 7 * 7 * 512 * 4096, 4096,
// 4096 * 4096, 4096,
// 4096 * 1000, 1000};
//
// float** filters = (float**) malloc(2*16*sizeof(float*));
// for (int i=0; i<2*16; i++) {
// filters[i] = (float*) malloc(filter_sizes[i] * sizeof(float));
// }
//
// const unsigned int output_sizes[] = {224*224*64,
// 224*224*64,
// 112*112*128,
// 112*112*128,
// 56*56*256,
// 56*56*256,
// 56*56*256,
// 28*28*512,
// 28*28*512,
// 28*28*512,
// 14*14*512,
// 14*14*512,
// 14*14*512,
// 4096,
// 4096,
// 1000};
//
// float** extras = (float**) malloc(16*sizeof(float*));
// for (int i=0; i<16; i++) {
// extras[i] = (float*) malloc(output_sizes[i] * sizeof(float));
// }
//
// float* img = (float*) malloc(224 * 224 * 3 * sizeof(float));
// float* output = (float*) malloc(1000 * sizeof(float));
// printf("filters initalized\n");
//
// std::ifstream t("App/vgg16.json");
// std::stringstream buffer;
// buffer << t.rdbuf();
// std::cout << buffer.str() << std::endl;
// printf("Loading model...\n");
// load_model_float(eid, (char*)buffer.str().c_str(), filters);
// printf("Model loaded!\n");
//
// for(int i=0; i<4; i++) {
// auto start = std::chrono::high_resolution_clock::now();
// //predict_float(eid, img, output, 1);
// predict_verify_float(eid, img, output, extras, 1);
// auto finish = std::chrono::high_resolution_clock::now();
// std::chrono::duration<double> elapsed = finish - start;
// printf("predict required %4.2f sec\n", elapsed.count());
// }
// printf("Enter a character to destroy enclave ...\n");
// getchar();
//
// // Destroy the enclave
sgx_destroy_enclave(eid);
printf("Info: Enclave Launcher successfully returned.\n");
printf("Enter a character before exit ...\n");
getchar();
return 0;
}
catch (int e)
{
printf("Info: Enclave Launch failed!.\n");
printf("Enter a character before exit ...\n");
getchar();
return -1;
}
}
| 34.538244 | 323 | 0.604372 | [
"vector",
"model"
] |
b2cd4d436e4b957b715372be5d8fa5a470e1c4e4 | 3,558 | cpp | C++ | SevenZip++/MemoryInStream.cpp | ProtocolONE/cord.seven-zip | 1c85a852cb01efd7aabbacfa01253ca213fcb2ef | [
"Apache-2.0"
] | 1 | 2019-08-07T06:15:09.000Z | 2019-08-07T06:15:09.000Z | SevenZip++/MemoryInStream.cpp | ProtocolONE/cord.seven-zip | 1c85a852cb01efd7aabbacfa01253ca213fcb2ef | [
"Apache-2.0"
] | null | null | null | SevenZip++/MemoryInStream.cpp | ProtocolONE/cord.seven-zip | 1c85a852cb01efd7aabbacfa01253ca213fcb2ef | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "MemoryInStream.h"
#include <algorithm>
namespace SevenZip {
namespace intl {
MemoryInStream::MemoryInStream(const std::vector<unsigned char>& memory)
: _buffer(memory)
, _offset(0)
, _refCount(0)
{
}
MemoryInStream::~MemoryInStream()
{
}
HRESULT STDMETHODCALLTYPE MemoryInStream::QueryInterface(REFIID iid, void** ppvObject)
{
if (iid == __uuidof(IUnknown))
{
*ppvObject = reinterpret_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
if (iid == IID_ISequentialInStream)
{
*ppvObject = static_cast<ISequentialInStream*>(this);
AddRef();
return S_OK;
}
if (iid == IID_IInStream)
{
*ppvObject = static_cast<IInStream*>(this);
AddRef();
return S_OK;
}
if (iid == IID_IStreamGetSize)
{
*ppvObject = static_cast<IStreamGetSize*>(this);
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE MemoryInStream::AddRef()
{
return static_cast<ULONG>(InterlockedIncrement(&_refCount));
}
ULONG STDMETHODCALLTYPE MemoryInStream::Release()
{
ULONG res = static_cast<ULONG>(InterlockedDecrement(&_refCount));
if (res == 0)
delete this;
return res;
}
STDMETHODIMP MemoryInStream::Read(void* data, UInt32 size, UInt32* processedSize)
{
if (data == nullptr || processedSize == nullptr)
return STG_E_INVALIDPOINTER;
size_t remainBytes = 0;
if (this->_offset < this->_buffer.size())
remainBytes = this->_buffer.size() - this->_offset;
size_t needToRead = min(size, remainBytes);
bool endOfStream = needToRead != size;
bool copySuccess = true;
if (needToRead > 0)
memcpy_s(data, size, this->_buffer.data() + this->_offset, needToRead);
if (processedSize != nullptr)
*processedSize = needToRead;
this->_offset += needToRead;
return endOfStream ? S_FALSE : S_OK;
}
STDMETHODIMP MemoryInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64* newPosition)
{
uint64_t size = this->_buffer.size();
if (seekOrigin == STREAM_SEEK_SET) {
uint64_t realOffset = (uint64_t)offset;
if (realOffset > size)
return STG_E_INVALIDFUNCTION;
this->_offset = (size_t)realOffset;
if (newPosition != nullptr)
*newPosition = this->_offset;
return S_OK;
}
if (seekOrigin == STREAM_SEEK_CUR) {
int64_t currentPosition = this->_offset;
currentPosition += offset;
if (currentPosition < 0 || currentPosition > size)
return STG_E_INVALIDFUNCTION;
this->_offset = (size_t)currentPosition;
if (newPosition != nullptr)
*newPosition = this->_offset;
return S_OK;
}
if (seekOrigin == STREAM_SEEK_END) {
int64_t currentPosition = size;
currentPosition += offset;
if (currentPosition < 0 || currentPosition > size)
return STG_E_INVALIDFUNCTION;
this->_offset = (size_t)currentPosition;
if (newPosition != nullptr)
*newPosition = this->_offset;
return S_OK;
}
return STG_E_INVALIDFUNCTION;
}
STDMETHODIMP MemoryInStream::GetSize(UInt64* size)
{
if (size == nullptr)
return STG_E_INVALIDPOINTER;
*size = this->_buffer.size();
return S_OK;
}
}
} | 24.040541 | 91 | 0.599775 | [
"vector"
] |
b2cdbf36fca605ea9a82982850eff319079d3351 | 1,175 | cpp | C++ | trunk/cocos2dx-tui/samples/HelloTui/Classes/HelloWorldScene.cpp | tongpengfei/tui | 4aeeb7a3db9e5be2124f277d5c082fa10e25034e | [
"MIT"
] | 12 | 2015-02-22T08:05:16.000Z | 2020-12-16T06:36:03.000Z | trunk/cocos2dx-tui/samples/HelloTui/Classes/HelloWorldScene.cpp | fuhongxue/tui | 4aeeb7a3db9e5be2124f277d5c082fa10e25034e | [
"MIT"
] | null | null | null | trunk/cocos2dx-tui/samples/HelloTui/Classes/HelloWorldScene.cpp | fuhongxue/tui | 4aeeb7a3db9e5be2124f277d5c082fa10e25034e | [
"MIT"
] | 6 | 2015-01-26T11:45:29.000Z | 2020-12-16T06:39:38.000Z | #include "HelloWorldScene.h"
#include <gameuicontroller.h>
#include <gameuievent.h>
USING_NS_CC;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() ){
return false;
}
GameUIController* uic = GameUIController::I();
addChild( uic );
uic->showTui( s_t_panel_start );
// enable standard touch
this->setTouchEnabled(true);
return true;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
CCTouch* touch = (CCTouch*)(* pTouches->begin());
CCPoint pos = touch->getLocation();
CCLog("touch, x = %f, y = %f", pos.x, pos.y);
}
| 21.363636 | 65 | 0.63234 | [
"object"
] |
b2d3952de34ac773c25827f84bb9c04699b3b59e | 2,011 | cpp | C++ | ExternalTrainer/ExternalTrainer.cpp | N3TBI0S/AssaultCubeExternalTrainer | df44af6af9eaf9ed1411d9385dc2e7857a67458c | [
"BSD-3-Clause"
] | null | null | null | ExternalTrainer/ExternalTrainer.cpp | N3TBI0S/AssaultCubeExternalTrainer | df44af6af9eaf9ed1411d9385dc2e7857a67458c | [
"BSD-3-Clause"
] | null | null | null | ExternalTrainer/ExternalTrainer.cpp | N3TBI0S/AssaultCubeExternalTrainer | df44af6af9eaf9ed1411d9385dc2e7857a67458c | [
"BSD-3-Clause"
] | null | null | null | // ExternalTrainer.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <vector>
#include <windows.h>
#include "proc.h"
#include "mem.h"
int main()
{
HANDLE hProcess = 0;
uintptr_t moduleBase = 0, localPlayerPtr = 0, healthAddr = 0;
bool bHealth = false, bAmmo = false, bRecoil = false;
const int newValue = 1337;
DWORD procId = GetProcId(L"ac_client.exe");
if (procId)
{
hProcess = OpenProcess(PROCESS_ALL_ACCESS, NULL, procId);
moduleBase = GetModuleBaseAddress(procId, L"ac_client.exe");
localPlayerPtr = moduleBase + 0x10F4F4;
healthAddr = FindDMAAddy(hProcess, localPlayerPtr, { 0xF8 });
}
else
{
std::cout << "Process not found, press enter to exit \n";
std::cin.get();
return 0;
}
DWORD dwExit = 0;
while (GetExitCodeProcess(hProcess, &dwExit) && dwExit == STILL_ACTIVE)
{
if (GetAsyncKeyState(VK_F1) & 1)
{
bHealth = !bHealth;
}
if (GetAsyncKeyState(VK_F2) & 1)
{
bAmmo = !bAmmo;
if (bAmmo)
{
//ff 06 == inc [esi]
mem::PatchEx((BYTE*)(moduleBase + 0x637E9), (BYTE*)"\xFF\x06", 2, hProcess);
}
else
{
//ff 0e = dec [esi]
mem::PatchEx((BYTE*)(moduleBase + 0x637E9), (BYTE*)"\xFF\x0E", 2, hProcess);
}
}
if (GetAsyncKeyState(VK_F3) & 1)
{
bRecoil = !bRecoil;
if (bRecoil)
{
mem::NopEx((BYTE*)(moduleBase + 0x63786), 10, hProcess);
}
else
{
mem::PatchEx((BYTE*)(moduleBase + 0x63786), (BYTE*)"\x50\x8d\x4c\x24\x1c\x51\x8b\xce\xff\xd2", 10, hProcess);
}
}
if (GetAsyncKeyState(VK_INSERT) & 1)
{
return 0;
}
// Continuous write or freeze
if (bHealth)
{
mem::PatchEx((BYTE*)healthAddr, (BYTE*)&newValue, sizeof(newValue), hProcess);
}
Sleep(10);
}
std::cout << "Process not found, press enter to exit\n" << std::endl;
std::cin.get();
return 0;
}
| 20.731959 | 114 | 0.591745 | [
"vector"
] |
b2f25b3a1712278449cf8dfd2bedfba6d77f3e68 | 998 | cc | C++ | Codeforces/256 Division 2/Problem D/D.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/256 Division 2/Problem D/D.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/256 Division 2/Problem D/D.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
long long n, m, k, cnt;
long long get(long long x){
long long c = 0;
for(long long i = 1; i <= n; i++) c += min(x/i, m);
return c;
}
int main(){
cin >> n >> m >> k;
long long lo = 1, hi = n*m+1, mid;
while(lo+1 < hi){
mid = (lo+hi)/2;
cnt = get(mid-1);
if(cnt < k) lo = mid;
else hi = mid;
}
tr(lo);
return 0;
}
| 19.96 | 72 | 0.593186 | [
"vector"
] |
b2f89bb523986fe70608bedfd11689ae9c0f3916 | 5,640 | cpp | C++ | git-branch-status/Git/Remote.cpp | macmade/git-branch-status | a5fac651cb365e49c45ed24fd0e84e13b62e8bef | [
"MIT"
] | 5 | 2018-10-25T20:12:52.000Z | 2021-10-01T21:17:33.000Z | git-branch-status/Git/Remote.cpp | macmade/git-branch-status | a5fac651cb365e49c45ed24fd0e84e13b62e8bef | [
"MIT"
] | null | null | null | git-branch-status/Git/Remote.cpp | macmade/git-branch-status | a5fac651cb365e49c45ed24fd0e84e13b62e8bef | [
"MIT"
] | null | null | null | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2018 Jean-David Gadina - www-xs-labs.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
/*!
* @file Remote.cpp
* @copyright (c) 2018, Jean-David Gadina - www.xs-labs.com
*/
#include <stdexcept>
#include "Remote.hpp"
#include "Repository.hpp"
#include "Credentials.hpp"
#include "Arguments.hpp"
namespace Git
{
class Remote::IMPL
{
public:
IMPL( git_remote * remote, const Repository & repos );
IMPL( const IMPL & o );
~IMPL( void );
static int credentials( git_cred ** cred, const char * url, const char * usernameFromURL, unsigned int allowedTypes, void * payload );
git_remote * _remote;
const Repository & _repos;
};
Remote::Remote( git_remote * remote, const Repository & repos ): impl( std::make_shared< IMPL >( remote, repos ) )
{}
Remote::Remote( const Remote & o ): impl( std::make_shared< IMPL >( *( o.impl ) ) )
{}
Remote::~Remote( void )
{}
Remote & Remote::operator =( Remote o )
{
swap( *( this ), o );
return *( this );
}
Remote::operator git_remote * () const
{
return this->impl->_remote;
}
bool Remote::operator ==( const Remote & o ) const
{
return this->impl->_repos == o.impl->_repos && this->name() == o.name() && this->url() == o.url();
}
bool Remote::operator !=( const Remote & o ) const
{
return !operator ==( o );
}
std::string Remote::name( void ) const
{
const char * s( git_remote_name( this->impl->_remote ) );
return ( s == nullptr ) ? "" : s;
}
std::string Remote::url( void ) const
{
const char * s( git_remote_url( this->impl->_remote ) );
return ( s == nullptr ) ? "" : s;
}
bool Remote::fetch( const std::vector< std::string > & refspecs, const std::string & reflogMessage ) const
{
git_strarray array;
int status;
git_fetch_options options = GIT_FETCH_OPTIONS_INIT;
memset( &array, 0, sizeof( git_strarray ) );
options.callbacks.credentials = IMPL::credentials;
if( refspecs.size() > 0 )
{
array.count = refspecs.size();
array.strings = new char *[ refspecs.size() ];
for( size_t i = 0; i < refspecs.size(); i++ )
{
array.strings[ i ] = new char[ refspecs[ i ].length() + 1 ];
strcpy( array.strings[ i ], refspecs[ i ].c_str() );
}
}
status = git_remote_fetch
(
this->impl->_remote,
( refspecs.size() == 0 ) ? nullptr : &array,
&options,
( reflogMessage.length() == 0 ) ? nullptr : reflogMessage.c_str()
);
if( refspecs.size() > 0 )
{
for( size_t i = 0; i < refspecs.size(); i++ )
{
delete [] array.strings[ i ];
}
delete [] array.strings;
}
return status == 0;
}
void swap( Remote & o1, Remote & o2 )
{
using std::swap;
swap( o1.impl, o2.impl );
}
Remote::IMPL::IMPL( git_remote * remote, const Repository & repos ):
_remote( remote ),
_repos( repos )
{
if( remote == nullptr )
{
throw std::runtime_error( "Cannot initialize with a NULL git remote" );
}
}
Remote::IMPL::IMPL( const IMPL & o ): IMPL( o._remote, o._repos )
{}
Remote::IMPL::~IMPL( void )
{}
int Remote::IMPL::credentials( git_cred ** cred, const char * url, const char * usernameFromURL, unsigned int allowedTypes, void * payload )
{
Utility::Credentials c;
std::string user;
std::string password;
if( c.retrieve( Utility::Arguments::sharedInstance().keychainItem(), user, password ) )
{
if( git_cred_userpass_plaintext_new( cred, user.c_str(), password.c_str() ) == 0 )
{
return 0;
}
*( cred ) = nullptr;
}
return -1;
}
}
| 30.819672 | 146 | 0.525177 | [
"vector"
] |
b2f9ef1bca8010122a182fd02947bbd60ef749e0 | 3,886 | cc | C++ | pre_processors/filter_ground_removal.cc | Gatsby23/StaticMapping | 71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024 | [
"MIT"
] | 264 | 2019-08-08T08:39:39.000Z | 2022-03-27T09:46:42.000Z | pre_processors/filter_ground_removal.cc | Gatsby23/StaticMapping | 71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024 | [
"MIT"
] | 26 | 2019-08-26T13:35:05.000Z | 2022-03-14T10:16:55.000Z | pre_processors/filter_ground_removal.cc | Gatsby23/StaticMapping | 71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024 | [
"MIT"
] | 62 | 2019-08-20T17:14:14.000Z | 2022-03-16T12:18:35.000Z | // MIT License
// Copyright (c) 2019 Edward Liu
// 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 "pre_processors/filter_ground_removal.h"
namespace static_map {
namespace pre_processers {
namespace filter {
GroundRemoval::GroundRemoval()
: Interface(),
min_point_num_in_voxel_(10),
leaf_size_(0.8),
height_threshold_(0.15) {
// float params
INIT_FLOAT_PARAM("leaf_size", leaf_size_);
INIT_FLOAT_PARAM("height_threshold", height_threshold_);
// int32_t params
INIT_INT32_PARAM("min_point_num_in_voxel", min_point_num_in_voxel_);
}
void GroundRemoval::DisplayAllParams() {
PARAM_INFO(min_point_num_in_voxel_);
PARAM_INFO(leaf_size_);
PARAM_INFO(height_threshold_);
}
void GroundRemoval::SetInputCloud(const data::InnerCloudType::Ptr& cloud) {
this->inliers_.clear();
this->outliers_.clear();
if (cloud == nullptr || cloud->points.empty()) {
LOG(WARNING) << "cloud empty, do nothing!" << std::endl;
this->inner_cloud_ = nullptr;
return;
}
this->inner_cloud_ = cloud;
voxels_.clear();
for (int i = 0; i < this->inner_cloud_->points.size(); ++i) {
auto& point = this->inner_cloud_->points[i];
Eigen::Vector3i index(static_cast<int>(point.x / leaf_size_),
static_cast<int>(point.y / leaf_size_),
static_cast<int>(point.z / leaf_size_));
voxels_[index].push_back(i);
}
}
void GroundRemoval::Filter(const data::InnerCloudType::Ptr& cloud) {
if (!cloud || !Interface::inner_cloud_) {
LOG(WARNING) << "nullptr cloud, do nothing!" << std::endl;
return;
}
this->FilterPrepare(cloud);
for (auto& index_vector : voxels_) {
auto& index = index_vector.first;
auto& vector = index_vector.second;
if ((int32_t)vector.size() < min_point_num_in_voxel_) {
continue;
}
bool is_ground = false;
if (index[2] <= 0) { // z index <= 0 ---> z <= leaf_size
float max_z_in_voxel = -1.e9;
float min_z_in_voxel = 1.e9;
for (auto& i : vector) {
auto& point = this->inner_cloud_->points[i];
if (point.z > max_z_in_voxel) {
max_z_in_voxel = point.z;
}
if (point.z < min_z_in_voxel) {
min_z_in_voxel = point.z;
}
}
auto delta = max_z_in_voxel - min_z_in_voxel;
if (delta >= 0. && delta <= height_threshold_) {
is_ground = true;
for (auto& i : vector) {
this->outliers_.push_back(i);
}
}
}
if (!is_ground) {
for (auto& i : vector) {
this->inliers_.push_back(i);
cloud->points.push_back(this->inner_cloud_->points[i]);
}
}
}
std::sort(this->inliers_.begin(), this->inliers_.end());
std::sort(this->outliers_.begin(), this->outliers_.end());
}
} // namespace filter
} // namespace pre_processers
} // namespace static_map
| 33.5 | 80 | 0.667782 | [
"vector"
] |
65088dc3f75b3c4e09ae8b75f76d1f5aa9753041 | 10,320 | cpp | C++ | lib/ome/files/TileCoverage.cpp | rleigh-dundee/bioformats-cpp | e8e3c03cab4d00edb96f40aa2b86bc7c99d6588c | [
"BSD-2-Clause"
] | 5 | 2017-12-11T16:23:16.000Z | 2019-08-13T18:32:27.000Z | lib/ome/files/TileCoverage.cpp | rleigh-dundee/bioformats-cpp | e8e3c03cab4d00edb96f40aa2b86bc7c99d6588c | [
"BSD-2-Clause"
] | 83 | 2016-02-28T19:29:11.000Z | 2019-02-21T08:52:37.000Z | lib/ome/files/TileCoverage.cpp | rleigh-dundee/bioformats-cpp | e8e3c03cab4d00edb96f40aa2b86bc7c99d6588c | [
"BSD-2-Clause"
] | 13 | 2016-02-26T17:18:15.000Z | 2020-04-22T00:40:59.000Z | /*
* #%L
* OME-FILES C++ library for image IO.
* Copyright © 2006 - 2015 Open Microscopy Environment:
* - Massachusetts Institute of Technology
* - National Institutes of Health
* - University of Dundee
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* %%
* 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 HOLDERS 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
#include <ome/common/config.h>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/box.hpp>
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
#include <boost/geometry/index/rtree.hpp>
#endif
#include <algorithm>
#include <list>
#include <ome/files/Types.h>
#include <ome/files/TileCoverage.h>
using ome::files::dimension_size_type;
namespace geom = boost::geometry;
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
namespace geomi = boost::geometry::index;
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
typedef geom::model::point<dimension_size_type, 2, geom::cs::cartesian> point;
typedef geom::model::box<point> box;
namespace
{
box
box_from_region(const ::ome::files::PlaneRegion &r)
{
return box(point(r.x, r.y),
point(r.x + r.w, r.y + r.h));
}
::ome::files::PlaneRegion
region_from_box(const box& b)
{
const point& bmin = b.min_corner();
const point& bmax = b.max_corner();
return ::ome::files::PlaneRegion
(bmin.get<0>(), bmin.get<1>(),
bmax.get<0>() - bmin.get<0>(), bmax.get<1>() - bmin.get<1>());
}
#ifndef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
// Compare box
struct BoxCompare
{
const box& cmp;
BoxCompare(const box& cmp):
cmp(cmp)
{}
bool
operator()(const box& v) const
{
const point& amin = cmp.min_corner();
const point& amax = cmp.max_corner();
const point& bmin = v.min_corner();
const point& bmax = v.max_corner();
return (amin.get<0>() == bmin.get<0>() &&
amin.get<1>() == bmin.get<1>() &&
amax.get<0>() == bmax.get<0>() &&
amax.get<1>() == bmax.get<1>());
}
};
#endif // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
}
namespace ome
{
namespace files
{
/**
* Internal implementation details of TileCoverage.
*/
class TileCoverage::Impl
{
public:
/// Region coverage stored as box ranges.
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
geomi::rtree<box, geomi::quadratic<16> > rtree;
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
std::list<box> rtree;
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
/**
* Constructor.
*/
Impl():
rtree()
{
}
/// Destructor.
~Impl()
{
}
/**
* Boxes intersecting with the specified box.
*
* @param b the box to intersect with.
* @returns a list of intersecting boxes.
*/
std::vector<box>
intersecting(const box& b)
{
std::vector<box> results;
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
rtree.query(geomi::intersects(b),
std::back_inserter(results));
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
// Slower linear search in the absence of rtree.
PlaneRegion region(region_from_box(b));
for (std::list<box>::const_iterator i = rtree.begin();
i != rtree.end();
++i)
{
PlaneRegion test(region_from_box(*i));
PlaneRegion intersection = region & test;
if (intersection.w && intersection.h)
results.push_back(*i);
else
{
// Also include non-intersecting but touching
// regions for coalescing, both edges and corners.
// These are included by the R*Tree box intersection
// search and needed for the region coalescing logic.
if ((region.x + region.w == test.x ||
test.x + test.w == region.x) &&
((region.y >= test.y &&
region.y <= test.y + test.h) ||
(region.y + region.h >= test.y &&
region.y +region.h <= test.y + test.h)))
results.push_back(*i);
else if ((region.y + region.h == test.y ||
test.y + test.h == region.y) &&
((region.x >= test.x &&
region.x <= test.x + test.w) ||
(region.x + region.w >= test.x &&
region.x +region.w <= test.x + test.w)))
results.push_back(*i);
}
}
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
return results;
}
};
TileCoverage::TileCoverage():
impl(std::shared_ptr<Impl>(new Impl()))
{
}
TileCoverage::~TileCoverage()
{
}
bool
TileCoverage::insert(const PlaneRegion& region,
bool coalesce)
{
bool inserted = false;
if (coverage(region) == 0)
{
box b(box_from_region(region));
if (!coalesce)
{
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
impl->rtree.insert(b);
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
impl->rtree.push_back(b);
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
inserted = true;
}
else // Merge adjacent regions
{
// Merged regions to remove
std::vector<box> remove;
PlaneRegion merged_region = region;
// Merge any adjacent regions and then loop and retry
// with the resulting enlarged region until no further
// merges are possible
bool merged = true;
while(merged)
{
merged = false;
std::vector<box> results = impl->intersecting(b);
for(const auto& i : results)
{
PlaneRegion test(region_from_box(i));
PlaneRegion m = merged_region | test;
if (m.valid())
{
merged_region = m;
remove.push_back(i);
merged = true;
}
}
}
// Remove merged regions
if (!remove.empty())
{
for (const auto& r : remove)
{
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
impl->rtree.remove(r);
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
auto ib = std::find_if(impl->rtree.begin(), impl->rtree.end(), BoxCompare(r));
if (ib != impl->rtree.end())
impl->rtree.erase(ib);
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
}
}
// Insert merged region
box mb(box_from_region(merged_region));
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
impl->rtree.insert(mb);
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
impl->rtree.push_back(mb);
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
inserted = true;
}
}
return inserted;
}
bool
TileCoverage::remove(const PlaneRegion& region)
{
box b(box_from_region(region));
#ifdef OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
return (impl->rtree.remove(b));
#else // ! OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
bool found = false;
std::list<box>::iterator i = std::find_if(impl->rtree.begin(), impl->rtree.end(), BoxCompare(b));
if (i != impl->rtree.end())
{
impl->rtree.erase(i);
found = true;
}
return found;
#endif // OME_HAVE_BOOST_GEOMETRY_INDEX_RTREE_HPP
}
dimension_size_type
TileCoverage::size() const
{
return impl->rtree.size();
}
void
TileCoverage::clear()
{
impl->rtree.clear();
}
dimension_size_type
TileCoverage::coverage(const PlaneRegion& region) const
{
box b(box_from_region(region));
std::vector<box> results = impl->intersecting(b);
dimension_size_type area = 0;
for(const auto& i : results)
{
PlaneRegion test(region_from_box(i));
PlaneRegion intersection = region & test;
if (intersection.valid())
area += intersection.area();
}
return area;
}
bool
TileCoverage::covered(const PlaneRegion& region) const
{
return (region.w * region.h) == coverage(region);
}
}
}
| 30.175439 | 103 | 0.580717 | [
"geometry",
"vector",
"model"
] |
650bcd8486a3f05e40627f499f183babe490dc09 | 14,455 | cpp | C++ | DmTft24363Display/DmTft24363Display.cpp | anasBahou/touchscreen | db0810cdee71973660bdd22281ece51a40c7b00d | [
"Apache-2.0"
] | null | null | null | DmTft24363Display/DmTft24363Display.cpp | anasBahou/touchscreen | db0810cdee71973660bdd22281ece51a40c7b00d | [
"Apache-2.0"
] | null | null | null | DmTft24363Display/DmTft24363Display.cpp | anasBahou/touchscreen | db0810cdee71973660bdd22281ece51a40c7b00d | [
"Apache-2.0"
] | null | null | null | /*
* DmTft24363Display.cpp
*
* Created on: 15 avr. 2019
* Author: sixtron-training
*/
#include "DmTft24363Display.h"
using namespace sixtron;
DmTft24_363_Display::DmTft24_363_Display() {
printf("DmTft24_363_Display created \n\n");
}
DmTft24_363_Display::DmTft24_363_Display(FlashIAP* flash, DmTftIli9341* tft, DmTouch* touch, InterruptIn* touchItr, I2C* i2c, uint32_t settingsAddress) {
printf("Creation of DmTft24_363_Display...");
_pageID = HOMEPAGE;
_changePage = false;
_speedChanged = false;
_micSensChanged = false;
_batteryLevel = 0;
_previousBatteryLevel = 0;
_angle = 0;
_previousAngle = 0;
_minMicSens = 0;
_maxMicSens = 1;
_minSpeed = 0;
_maxSpeed = 1;
_settingsAddress = settingsAddress;
_myflash = flash;
_tft = tft;
_touch = touch;
_touchItr = touchItr;
_i2c = i2c;
_battery = new MAX17201(_i2c);
_queue = mbed_event_queue();
printf("... completed \n\n");
}
DmTft24_363_Display::~DmTft24_363_Display() {
printf("DmTft24_363_Dsiplay destroyed\n\n");
}
void DmTft24_363_Display::handleTouchEvent()
{
_queue->call_in(200, callback(_touchItr, &InterruptIn::enable_irq));
uint8_t which;
if ( _pageID == HOMEPAGE ) {
if ( GraphObjectTouched(_buttons, NUM_BUTTONS, &which, _tft, _touch) == GO_STATUS_NOERR ) {
_changePage = true;
_pageID = SETTINGSPAGE;
_buttons[SETTINGS].TouchActive = false;
return;
}
}
else if ( _pageID == SETTINGSPAGE ) {
if ( GraphObjectTouched(_buttons, NUM_BUTTONS, &which, _tft, _touch) == GO_STATUS_NOERR) {
if ( which == BACK ) {
_changePage = true;
_pageID = HOMEPAGE;
_buttons[BACK].TouchActive = false;
_buttons[SPEED_MINUS].TouchActive = false;
_buttons[SPEED_PLUS].TouchActive = false;
_buttons[MIC_SENS_MINUS].TouchActive = false;
_buttons[MIC_SENS_PLUS].TouchActive = false;
return;
}
else if ( which == SPEED_MINUS ) {
if ( ( _minSpeed <= _settingsVariables[SPEED] ) && ( _settingsVariables[SPEED] <= _maxSpeed ) ) {
_speedChanged = true;
_settingsVariables[SPEED]-=0.05;
}
return;
}
else if ( which == SPEED_PLUS ) {
if ( ( _minSpeed <= _settingsVariables[SPEED] ) && ( _settingsVariables[SPEED] <= _maxSpeed ) ) {
_speedChanged = true;
_settingsVariables[SPEED]+=0.05;
}
return;
}
else if ( which == MIC_SENS_MINUS ) {
if ( ( _minMicSens <= _settingsVariables[MIC_SENS] ) && ( _settingsVariables[MIC_SENS] <= _maxMicSens ) ) {
_micSensChanged = true;
_settingsVariables[MIC_SENS]-=0.015;
}
return;
}
else if ( which == MIC_SENS_PLUS ) {
if ( ( _minMicSens <= _settingsVariables[MIC_SENS] ) && ( _settingsVariables[MIC_SENS] <= _maxMicSens ) ) {
_micSensChanged = true;
_settingsVariables[MIC_SENS]+=0.015;
}
return;
}
}
}
}
void DmTft24_363_Display::itrFunc() {
_touchItr->disable_irq();
_queue->call(callback(this, &DmTft24_363_Display::handleTouchEvent));
printf("touch\n");
return;
}
void DmTft24_363_Display::init() {
printf("Initialization...\n");
/*
* OBJECT INITILIZATION
*/
_tft->init(); // screen initialization
_touch->init(); // touch controller initialization
_myflash->init(); // flash memory initialization
_touchItr->fall(callback(this, &DmTft24_363_Display::itrFunc)); // set up the function linked to the interruption
_battery->configure(1, 800, 3.3, false, false); //battery configuration
/*
* BUTTONS INITILIZATION
*/
// settings button initialization
_buttons[SETTINGS].Id = SETTINGS;
_buttons[SETTINGS].Type = GO_RECTANGLE;
_buttons[SETTINGS].Xpos = 0;
_buttons[SETTINGS].Ypos = 0;
_buttons[SETTINGS].Width = 100;
_buttons[SETTINGS].Height = 50;
_buttons[SETTINGS].FrontColor = WHITE; //color of borders
_buttons[SETTINGS].DoFill = true;
_buttons[SETTINGS].FillColor = BLACK;
_buttons[SETTINGS].TouchActive = false;
// back button initialization
_buttons[BACK].Id = BACK;
_buttons[BACK].Type = GO_RECTANGLE;
_buttons[BACK].Xpos = 0;
_buttons[BACK].Ypos = 0;
_buttons[BACK].Width = 50;
_buttons[BACK].Height = 50;
_buttons[BACK].FrontColor = WHITE; //color of borders
_buttons[BACK].DoFill = true;
_buttons[BACK].FillColor = BLACK;
_buttons[BACK].TouchActive = false;
// "-" speed button initialization
_buttons[SPEED_MINUS].Id = SPEED_MINUS;
_buttons[SPEED_MINUS].Type = GO_RECTANGLE;
_buttons[SPEED_MINUS].Xpos = 70;
_buttons[SPEED_MINUS].Ypos =55;
_buttons[SPEED_MINUS].Width = 50;
_buttons[SPEED_MINUS].Height = 50;
_buttons[SPEED_MINUS].FrontColor = WHITE; //color of borders
_buttons[SPEED_MINUS].DoFill = true;
_buttons[SPEED_MINUS].FillColor = BLACK;
_buttons[SPEED_MINUS].TouchActive = false;
// "+" speed button initialization
_buttons[SPEED_PLUS].Id = SPEED_PLUS,
_buttons[SPEED_PLUS].Type = GO_RECTANGLE;
_buttons[SPEED_PLUS].Xpos = 190;
_buttons[SPEED_PLUS].Ypos =55;
_buttons[SPEED_PLUS].Width = 50;
_buttons[SPEED_PLUS].Height = 50;
_buttons[SPEED_PLUS].FrontColor = WHITE; //color of borders
_buttons[SPEED_PLUS].DoFill = true;
_buttons[SPEED_PLUS].FillColor = BLACK;
_buttons[SPEED_PLUS].TouchActive = false;
// "-" mic_sens button initialization
_buttons[MIC_SENS_MINUS].Id = MIC_SENS_MINUS;
_buttons[MIC_SENS_MINUS].Type = GO_RECTANGLE;
_buttons[MIC_SENS_MINUS].Xpos = 70;
_buttons[MIC_SENS_MINUS].Ypos =110;
_buttons[MIC_SENS_MINUS].Width = 50;
_buttons[MIC_SENS_MINUS].Height = 50;
_buttons[MIC_SENS_MINUS].FrontColor = WHITE; //color of borders
_buttons[MIC_SENS_MINUS].DoFill = true;
_buttons[MIC_SENS_MINUS].FillColor = BLACK;
_buttons[MIC_SENS_MINUS].TouchActive = false;
// "+" mi_sens button initialization
_buttons[MIC_SENS_PLUS].Id = MIC_SENS_PLUS;
_buttons[MIC_SENS_PLUS].Type = GO_RECTANGLE;
_buttons[MIC_SENS_PLUS].Xpos = 190;
_buttons[MIC_SENS_PLUS].Ypos =110;
_buttons[MIC_SENS_PLUS].Width = 50;
_buttons[MIC_SENS_PLUS].Height = 50;
_buttons[MIC_SENS_PLUS].FrontColor = WHITE; //color of borders
_buttons[MIC_SENS_PLUS].DoFill = true;
_buttons[MIC_SENS_PLUS].FillColor = BLACK;
_buttons[MIC_SENS_PLUS].TouchActive = false;
/*
* LEVEL BATTERY INITIALIZATION
*/
wait_ms(1000); // wait for battery configuration
_batteryLevel = _battery->state_of_charge();
/*
* SETTINGS VARIABLES AND MIC SENS INITIALIZATION
*/
readSettings();
printf("...completed\n\n");
return;
}
void DmTft24_363_Display::setAngle(int angle) {
_previousAngle = _angle;
_angle = angle;
return;
}
void DmTft24_363_Display::setBatteryLevel(float batteryLevel) {
_previousBatteryLevel = _batteryLevel;
_batteryLevel = batteryLevel;;
return;
}
void DmTft24_363_Display::refreshBatteryLevel() {
setBatteryLevel(_battery->state_of_charge());
if ( _previousBatteryLevel != _batteryLevel ) {
// variables display battery
uint16_t x0_rect = 200;
uint16_t y0_rect = 20;
uint16_t x1_rect = 230;
uint16_t y1_rect = 30;
uint16_t rect_width = x1_rect -1 - (x0_rect +1) ; // -/+ 1 to avoid the pixels of the white rectangle
// battery
uint16_t level_to_pixel = (uint16_t)((_batteryLevel/100)*rect_width); // conversion to an integer
// erase the existing value
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + rect_width, y1_rect-1, BLACK);
_tft->fillRectangle(200 , 0 , 260, 16, BLACK); // erase the text <=> battery level
// level to string
char battery_level_str[6];
sprintf(battery_level_str, "%.0f%s", _batteryLevel, "%"); // to convert battery_level to a string of a format "70.0 %"
// draw the string
_tft->drawString(200, 0, battery_level_str);
if (_batteryLevel > 66) {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, GREEN);
}
else if ( (33 < _batteryLevel) && (_batteryLevel < 67) ) {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, YELLOW);
}
else {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, RED);
}
}
return;
}
void DmTft24_363_Display::refreshAngle() {
if ( _previousAngle != _angle ) {
// screen size
uint16_t w = _tft->width();
uint16_t h = _tft->height();
// erase old direction line
float sound_angle_rad = (float)_previousAngle * 3.14/180;
uint16_t circle_radius = 80;
uint16_t x_sound1, y_sound1;
x_sound1 = w/2 + circle_radius*cos(sound_angle_rad);
y_sound1 = h/2 - circle_radius*sin(sound_angle_rad);
// display new direction line
float sound_angle_rad2 = (float)_angle * 3.14/180;
uint16_t x_sound2, y_sound2;
x_sound2 = w/2 + circle_radius*cos(sound_angle_rad2);
y_sound2 = h/2 - circle_radius*sin(sound_angle_rad2);
// draw
_tft->drawLine(w/2, h/2, x_sound1, y_sound1, BLACK); // erase the drawn line
_tft->drawPoint(x_sound1, y_sound1);
_tft->drawLine(w/2, h/2, x_sound2, y_sound2, RED);
}
return;
}
void DmTft24_363_Display::refresh() {
if (_pageID==HOMEPAGE){ // in case the user is in the home_page
if (_changePage == 1) {
_changePage = 0;
_tft->clearScreen(BLACK);
homePage();
}
refreshAngle();
refreshBatteryLevel();
}
else if(_pageID==SETTINGSPAGE){
char speed_c[5];
char mic_sens_c[5];
sprintf(speed_c, "%.1f", _settingsVariables[SPEED]*100);
sprintf(mic_sens_c, "%.1f", _settingsVariables[MIC_SENS]*100);
uint16_t x1 = _tft->width()/2 ;
uint16_t y1 = 55;
uint16_t size1 = 50;
if (_changePage == 1) {
_changePage = 0;
_tft->clearScreen(BLACK);
settingsPage();
}
if (_speedChanged==1){ // redraw the speed value
_tft->fillRectangle(x1 + 5, y1, x1+size1+15, y1+size1, BLACK);
_tft->drawString(135 , 70, speed_c);
}
if (_micSensChanged==1){ // redraw the mic_sens value
_tft->fillRectangle(x1+5, 2*y1, x1+size1+15, 2*y1+size1, BLACK);
_tft->drawString(135 , 125, mic_sens_c);
}
}
return;
}
void DmTft24_363_Display::readSettings() {
// read blocks from flash memory
_myflash->read(_settingsVariables, _settingsAddress, sizeof(_settingsVariables));//_myflash->get_page_size());
if (isnan(_settingsVariables[SPEED]) != 0) {
_settingsVariables[SPEED] = 0.95;
}
if (isnan(_settingsVariables[MIC_SENS]) != 0) {
_settingsVariables[MIC_SENS] = 0.30;
}
printf("speed : %f\n", _settingsVariables[SPEED]);
printf("mic_sens : %f\n", _settingsVariables[MIC_SENS]);
return;
}
void DmTft24_363_Display::saveSettings() {
// erase blocks on flash memory
_myflash->erase(_settingsAddress, _myflash->get_sector_size(_settingsAddress));
// program blocks
_myflash->program(_settingsVariables , _settingsAddress, sizeof(_settingsVariables));//_myflash->get_page_size());
printf("Settings saved \n");
printf("Saved speed : %f\n", _settingsVariables[SPEED]);
printf("Saved mic_sens : %f\n", _settingsVariables[MIC_SENS]);
return;
}
void DmTft24_363_Display::homePage() {
printf("Home page...");
// case the settings were changed ==> save the settings
if ((_speedChanged== 1)||(_micSensChanged==1)){
_speedChanged = false;
_micSensChanged = false;
saveSettings();
}
// screen size
uint16_t w = _tft->width();
uint16_t h = _tft->height();
/*
* BATTERY
*/
uint16_t x0_rect = 200;
uint16_t y0_rect = 20;
uint16_t x1_rect = 230;
uint16_t y1_rect = 30;
uint16_t rect_width = x1_rect -1 - (x0_rect + 1) ; // -/+ 1 to avoid the pixels of the white rectangle
uint16_t level_to_pixel = (uint16_t)((_batteryLevel/100)*rect_width);
char battery_level_str[6];
sprintf(battery_level_str, "%.0f%s", _batteryLevel, "%"); // to convert battery_level to a string of a format "70.0 %"
_tft->drawString(200, 0, battery_level_str);
_tft->drawRectangle(x0_rect, y0_rect, x1_rect, y1_rect, WHITE);
_tft->drawVerticalLine(x1_rect+1, y0_rect+4, 2, WHITE);
if (_batteryLevel > 66) {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, GREEN);
}
else if ( (33 < _batteryLevel) && (_batteryLevel < 67) ) {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, YELLOW);
}
else {
_tft->fillRectangle(x0_rect+1 , y0_rect+1 , x0_rect+1 + level_to_pixel, y1_rect-1, RED);
}
/*
* ANGLE
*/
float sound_angle_rad = (float)_angle * 3.14/180;
uint16_t circle_radius = 80;
uint16_t x_sound, y_sound;
x_sound = w/2 + circle_radius*cos(sound_angle_rad);
y_sound = h/2 - circle_radius*sin(sound_angle_rad);
_tft->drawCircle(w/2, h/2, circle_radius, WHITE);
_tft->drawPoint(w/2, h/2);
_tft->drawLine(w/2, h/2, x_sound, y_sound, RED);
/*
* BUTTON
*/
GraphObjectDraw(&_buttons[SETTINGS], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[SETTINGS].Xpos, _buttons[SETTINGS].Ypos, _buttons[SETTINGS].Width, _buttons[SETTINGS].Height, "settings");
printf("...completed\n\n");
return;
}
void DmTft24_363_Display::settingsPage() {
printf("Settings page...");
char speed_c[5];
char mic_sens_c[5];
sprintf(speed_c, "%.1f", _settingsVariables[SPEED]*100);
sprintf(mic_sens_c, "%.1f", _settingsVariables[MIC_SENS]*100);
_tft->drawString(0, 70, "Speed");
_tft->drawString(135 , 70, speed_c); // _settingsVariables[0] <=> speed variable
_tft->drawString(0, 125, "Mic Sens");
_tft->drawString(135 , 125, mic_sens_c); // _settingsVariables[1] <=> mic_sens variable
/*
* BUTTONS
*/
GraphObjectDraw(&_buttons[BACK], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[BACK].Xpos, _buttons[BACK].Ypos, _buttons[BACK].Width, _buttons[BACK].Height, "back");
GraphObjectDraw(&_buttons[SPEED_MINUS], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[SPEED_MINUS].Xpos, _buttons[SPEED_MINUS].Ypos, _buttons[SPEED_MINUS].Width, _buttons[SPEED_MINUS].Height, "-");
GraphObjectDraw(&_buttons[SPEED_PLUS], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[SPEED_PLUS].Xpos, _buttons[SPEED_PLUS].Ypos, _buttons[SPEED_PLUS].Width, _buttons[SPEED_PLUS].Height, "+");
GraphObjectDraw(&_buttons[MIC_SENS_MINUS], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[MIC_SENS_MINUS].Xpos, _buttons[MIC_SENS_MINUS].Ypos, _buttons[MIC_SENS_MINUS].Width, _buttons[MIC_SENS_MINUS].Height, "-");
GraphObjectDraw(&_buttons[MIC_SENS_PLUS], 0, true, true, _tft, _touch);
_tft->drawStringCentered(_buttons[MIC_SENS_PLUS].Xpos, _buttons[MIC_SENS_PLUS].Ypos, _buttons[MIC_SENS_PLUS].Width, _buttons[MIC_SENS_PLUS].Height, "+");
printf("...completed\n\n");
return;
}
float DmTft24_363_Display::getSpeed() {
return _settingsVariables[SPEED];
}
float DmTft24_363_Display::getMicSens() {
return _settingsVariables[MIC_SENS];
}
| 28.287671 | 158 | 0.709927 | [
"object"
] |
650bd39555f4c19bc23fbb4cbdb2ce6897e29f4e | 1,567 | hpp | C++ | ESMF/src/Infrastructure/Mesh/src/Moab/parallel/moab/ParallelData.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2018-07-05T16:48:58.000Z | 2018-07-05T16:48:58.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/parallel/moab/ParallelData.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/parallel/moab/ParallelData.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | null | null | null |
#ifndef MOAB_PARALLEL_DATA_HPP
#define MOAB_PARALLEL_DATA_HPP
#include "moab/Forward.hpp"
#include "moab/Range.hpp"
namespace moab {
class ParallelComm;
/**
* \brief Parallel data in MOAB
* \author Tim Tautges
*
* This class implements methods to retrieve information about
* the parallel mesh from MOAB. Most of this data can be retrieved
* directly from MOAB as sets and tags; this class provides convenience
* methods implemented on top of other MOAB functions.
*
*/
class ParallelData
{
public:
//! constructor; if non-null parallelcomm, that is used to
//! determine rank, otherwise rank is taken from impl
ParallelData(Interface *impl, ParallelComm *pcomm = NULL);
//! return partition sets; if tag_name is input, gets sets with
//! that tag name, otherwise uses PARALLEL_PARTITION tag
ErrorCode get_partition_sets(Range &part_sets,
const char *tag_name = NULL);
//! get communication interface sets and the processors with which
//! this processor communicates; sets are sorted by processor
ErrorCode get_interface_sets(std::vector<EntityHandle> &iface_sets,
std::vector<int> &iface_procs);
private:
//! interface instance to which this instance corresponds
Interface *mbImpl;
//! ParallelComm object to which this is bound
ParallelComm *parallelComm;
};
inline ParallelData::ParallelData(Interface *impl,
ParallelComm *pcomm)
: mbImpl(impl), parallelComm(pcomm)
{}
}
#endif
| 26.559322 | 71 | 0.690491 | [
"mesh",
"object",
"vector"
] |
65104de891aaf54a3f11a33bc953148ef28db703 | 74,522 | cpp | C++ | Engine/cal3d/loader.cpp | odiminox/DeadBeef-Engine | 89fbaf3c62a11da9eef0ea5971c0c49223da452f | [
"Apache-2.0"
] | null | null | null | Engine/cal3d/loader.cpp | odiminox/DeadBeef-Engine | 89fbaf3c62a11da9eef0ea5971c0c49223da452f | [
"Apache-2.0"
] | null | null | null | Engine/cal3d/loader.cpp | odiminox/DeadBeef-Engine | 89fbaf3c62a11da9eef0ea5971c0c49223da452f | [
"Apache-2.0"
] | null | null | null | //****************************************************************************//
// loader.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// This library is free software; you can redistribute it and/or modify it //
// under the terms of the GNU Lesser General Public License as published by //
// the Free Software Foundation; either version 2.1 of the License, or (at //
// your option) any later version. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/loader.h"
#include "cal3d/error.h"
#include "cal3d/matrix.h"
#include "cal3d/vector.h"
#include "cal3d/quaternion.h"
#include "cal3d/coremodel.h"
#include "cal3d/coreskeleton.h"
#include "cal3d/corebone.h"
#include "cal3d/coreanimation.h"
#include "cal3d/coremesh.h"
#include "cal3d/coresubmesh.h"
#include "cal3d/corematerial.h"
#include "cal3d/corekeyframe.h"
#include "cal3d/coretrack.h"
#include "cal3d/tinyxml.h"
#include "cal3d/streamsource.h"
#include "cal3d/buffersource.h"
using namespace cal3d;
int CalLoader::loadingMode;
/*****************************************************************************/
/** Sets optional flags which affect how the model is loaded into memory.
*
* This function sets the loading mode for all future loader calls.
*
* @param flags A boolean OR of any of the following flags
* \li LOADER_ROTATE_X_AXIS will rotate the mesh 90 degrees about the X axis,
* which has the effect of swapping Y/Z coordinates.
* \li LOADER_INVERT_V_COORD will substitute (1-v) for any v texture coordinate
* to eliminate the need for texture inversion after export.
*
*****************************************************************************/
void CalLoader::setLoadingMode(int flags)
{
loadingMode = flags;
}
/*****************************************************************************/
/** Loads a core animation instance.
*
* This function loads a core animation instance from a file.
*
* @param strFilename The file to load the core animation instance from.
*
* @return One of the following values:
* \li a pointer to the core animation
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreAnimationPtr CalLoader::loadCoreAnimation(const std::string& strFilename, CalCoreSkeleton *skel)
{
if(strFilename.size()>= 3 && stricmp(strFilename.substr(strFilename.size()-3,3).c_str(),Cal::ANIMATION_XMLFILE_MAGIC)==0)
return loadXmlCoreAnimation(strFilename, skel);
// open the file
std::ifstream file(strFilename.c_str(), std::ios::in | std::ios::binary);
//make sure it was opened properly
if(!file)
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
//make a new stream data source and use it to load the animation
CalStreamSource streamSrc( file );
CalCoreAnimationPtr coreanim = loadCoreAnimation( streamSrc,skel );
if(coreanim) coreanim->setFilename( strFilename );
//close the file
file.close();
return coreanim;
}
/*****************************************************************************/
/** Loads a core material instance.
*
* This function loads a core material instance from a file.
*
* @param strFilename The file to load the core material instance from.
*
* @return One of the following values:
* \li a pointer to the core material
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMaterialPtr CalLoader::loadCoreMaterial(const std::string& strFilename)
{
if(strFilename.size()>= 3 && stricmp(strFilename.substr(strFilename.size()-3,3).c_str(),Cal::MATERIAL_XMLFILE_MAGIC)==0)
return loadXmlCoreMaterial(strFilename);
// open the file
std::ifstream file;
file.open(strFilename.c_str(), std::ios::in | std::ios::binary);
// make sure it opened properly
if(!file)
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
//make a new stream data source and use it to load the material
CalStreamSource streamSrc( file );
CalCoreMaterialPtr coremat = loadCoreMaterial( streamSrc );
if(coremat) coremat->setFilename( strFilename );
//close the file
file.close();
return coremat;
}
/*****************************************************************************/
/** Loads a core mesh instance.
*
* This function loads a core mesh instance from a file.
*
* @param strFilename The file to load the core mesh instance from.
*
* @return One of the following values:
* \li a pointer to the core mesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMeshPtr CalLoader::loadCoreMesh(const std::string& strFilename)
{
if(strFilename.size()>= 3 && stricmp(strFilename.substr(strFilename.size()-3,3).c_str(),Cal::MESH_XMLFILE_MAGIC)==0)
return loadXmlCoreMesh(strFilename);
// open the file
std::ifstream file;
file.open(strFilename.c_str(), std::ios::in | std::ios::binary);
// make sure it opened properly
if(!file)
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
//make a new stream data source and use it to load the mesh
CalStreamSource streamSrc( file );
CalCoreMeshPtr coremesh = loadCoreMesh( streamSrc );
if(coremesh) coremesh->setFilename( strFilename );
//close the file
file.close();
return coremesh;
}
/*****************************************************************************/
/** Loads a core skeleton instance.
*
* This function loads a core skeleton instance from a file.
*
* @param strFilename The file to load the core skeleton instance from.
*
* @return One of the following values:
* \li a pointer to the core skeleton
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSkeletonPtr CalLoader::loadCoreSkeleton(const std::string& strFilename)
{
if(strFilename.size()>= 3 && stricmp(strFilename.substr(strFilename.size()-3,3).c_str(),Cal::SKELETON_XMLFILE_MAGIC)==0)
return loadXmlCoreSkeleton(strFilename);
// open the file
std::ifstream file;
file.open(strFilename.c_str(), std::ios::in | std::ios::binary);
//make sure it opened properly
if(!file)
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
//make a new stream data source and use it to load the skeleton
CalStreamSource streamSrc( file );
CalCoreSkeletonPtr coreskeleton = loadCoreSkeleton( streamSrc );
//close the file
file.close();
return coreskeleton;
}
/*****************************************************************************/
/** Loads a core animation instance.
*
* This function loads a core animation instance from an input stream.
*
* @param inputStream The stream to load the core animation instance from. This
* stream should be initialized and ready to be read from.
*
* @return One of the following values:
* \li a pointer to the core animation
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreAnimationPtr CalLoader::loadCoreAnimation(std::istream& inputStream, CalCoreSkeleton *skel )
{
//Create a new istream data source and pass it on
CalStreamSource streamSrc(inputStream);
return loadCoreAnimation(streamSrc, skel);
}
/*****************************************************************************/
/** Loads a core material instance.
*
* This function loads a core material instance from an input stream.
*
* @param inputStream The stream to load the core material instance from. This
* stream should be initialized and ready to be read from.
*
* @return One of the following values:
* \li a pointer to the core material
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMaterialPtr CalLoader::loadCoreMaterial(std::istream& inputStream)
{
//Create a new istream data source and pass it on
CalStreamSource streamSrc(inputStream);
return loadCoreMaterial(streamSrc);
}
/*****************************************************************************/
/** Loads a core mesh instance.
*
* This function loads a core mesh instance from an input stream.
*
* @param inputStream The stream to load the core mesh instance from. This
* stream should be initialized and ready to be read from.
*
* @return One of the following values:
* \li a pointer to the core mesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMeshPtr CalLoader::loadCoreMesh(std::istream& inputStream)
{
//Create a new istream data source and pass it on
CalStreamSource streamSrc(inputStream);
return loadCoreMesh(streamSrc);
}
/*****************************************************************************/
/** Loads a core skeleton instance.
*
* This function loads a core skeleton instance from an input stream.
*
* @param inputStream The stream to load the core skeleton instance from. This
* stream should be initialized and ready to be read from.
*
* @return One of the following values:
* \li a pointer to the core skeleton
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSkeletonPtr CalLoader::loadCoreSkeleton(std::istream& inputStream)
{
//Create a new istream data source and pass it on
CalStreamSource streamSrc(inputStream);
return loadCoreSkeleton(streamSrc);
}
/*****************************************************************************/
/** Loads a core animation instance.
*
* This function loads a core animation instance from a memory buffer.
*
* @param inputBuffer The memory buffer to load the core animation instance
* from. This buffer should be initialized and ready to
* be read from.
*
* @return One of the following values:
* \li a pointer to the core animation
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreAnimationPtr CalLoader::loadCoreAnimation(void* inputBuffer, CalCoreSkeleton *skel)
{
//Create a new buffer data source and pass it on
CalBufferSource bufferSrc(inputBuffer);
return loadCoreAnimation(bufferSrc,skel);
}
/*****************************************************************************/
/** Loads a core material instance.
*
* This function loads a core material instance from a memory buffer.
*
* @param inputBuffer The memory buffer to load the core material instance
* from. This buffer should be initialized and ready to
* be read from.
*
* @return One of the following values:
* \li a pointer to the core material
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMaterialPtr CalLoader::loadCoreMaterial(void* inputBuffer)
{
//Create a new buffer data source and pass it on
CalBufferSource bufferSrc(inputBuffer);
return loadCoreMaterial(bufferSrc);
}
/*****************************************************************************/
/** Loads a core mesh instance.
*
* This function loads a core mesh instance from a memory buffer.
*
* @param inputBuffer The memory buffer to load the core mesh instance from.
* This buffer should be initialized and ready to be
* read from.
*
* @return One of the following values:
* \li a pointer to the core mesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMeshPtr CalLoader::loadCoreMesh(void* inputBuffer)
{
//Create a new buffer data source and pass it on
CalBufferSource bufferSrc(inputBuffer);
return loadCoreMesh(bufferSrc);
}
/*****************************************************************************/
/** Loads a core skeleton instance.
*
* This function loads a core skeleton instance from a memory buffer.
*
* @param inputBuffer The memory buffer to load the core skeleton instance
* from. This buffer should be initialized and ready to
* be read from.
*
* @return One of the following values:
* \li a pointer to the core skeleton
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSkeletonPtr CalLoader::loadCoreSkeleton(void* inputBuffer)
{
//Create a new buffer data source and pass it on
CalBufferSource bufferSrc(inputBuffer);
return loadCoreSkeleton(bufferSrc);
}
/*****************************************************************************/
/** Loads a core animation instance.
*
* This function loads a core animation instance from a data source.
*
* @param dataSrc The data source to load the core animation instance from.
*
* @return One of the following values:
* \li a pointer to the core animation
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreAnimationPtr CalLoader::loadCoreAnimation(CalDataSource& dataSrc, CalCoreSkeleton *skel)
{
// check if this is a valid file
char magic[4];
if(!dataSrc.readBytes(&magic[0], 4) || (memcmp(&magic[0], Cal::ANIMATION_FILE_MAGIC, 4) != 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// check if the version is compatible with the library
int version;
if(!dataSrc.readInteger(version) || (version < Cal::EARLIEST_COMPATIBLE_FILE_VERSION) || (version > Cal::CURRENT_FILE_VERSION))
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__);
return 0;
}
// allocate a new core animation instance
CalCoreAnimationPtr pCoreAnimation(new CalCoreAnimation);
if(!pCoreAnimation)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// get the duration of the core animation
float duration;
if(!dataSrc.readFloat(duration))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// check for a valid duration
if(duration <= 0.0f)
{
CalError::setLastError(CalError::INVALID_ANIMATION_DURATION, __FILE__, __LINE__);
return 0;
}
// set the duration in the core animation instance
pCoreAnimation->setDuration(duration);
// read the number of tracks
int trackCount;
if(!dataSrc.readInteger(trackCount) || (trackCount <= 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// load all core bones
int trackId;
for(trackId = 0; trackId < trackCount; ++trackId)
{
// load the core track
CalCoreTrack *pCoreTrack;
pCoreTrack = loadCoreTrack(dataSrc, skel, duration);
if(pCoreTrack == 0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// add the core track to the core animation instance
pCoreAnimation->addCoreTrack(pCoreTrack);
}
return pCoreAnimation;
}
/*****************************************************************************/
/** Loads a core material instance.
*
* This function loads a core material instance from a data source.
*
* @param dataSrc The data source to load the core material instance from.
*
* @return One of the following values:
* \li a pointer to the core material
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMaterialPtr CalLoader::loadCoreMaterial(CalDataSource& dataSrc)
{
// check if this is a valid file
char magic[4];
if(!dataSrc.readBytes(&magic[0], 4) || (memcmp(&magic[0], Cal::MATERIAL_FILE_MAGIC, 4) != 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// check if the version is compatible with the library
int version;
if(!dataSrc.readInteger(version) || (version < Cal::EARLIEST_COMPATIBLE_FILE_VERSION) || (version > Cal::CURRENT_FILE_VERSION))
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__);
return 0;
}
// allocate a new core material instance
CalCoreMaterialPtr pCoreMaterial = new CalCoreMaterial();
if(!pCoreMaterial)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// get the ambient color of the core material
CalCoreMaterial::Color ambientColor;
dataSrc.readBytes(&ambientColor, sizeof(ambientColor));
// get the diffuse color of the core material
CalCoreMaterial::Color diffuseColor;
dataSrc.readBytes(&diffuseColor, sizeof(diffuseColor));
// get the specular color of the core material
CalCoreMaterial::Color specularColor;
dataSrc.readBytes(&specularColor, sizeof(specularColor));
// get the shininess factor of the core material
float shininess;
dataSrc.readFloat(shininess);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// set the colors and the shininess
pCoreMaterial->setAmbientColor(ambientColor);
pCoreMaterial->setDiffuseColor(diffuseColor);
pCoreMaterial->setSpecularColor(specularColor);
pCoreMaterial->setShininess(shininess);
// read the number of maps
int mapCount;
if(!dataSrc.readInteger(mapCount) || (mapCount < 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// reserve memory for all the material data
if(!pCoreMaterial->reserve(mapCount))
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// load all maps
int mapId;
for(mapId = 0; mapId < mapCount; ++mapId)
{
CalCoreMaterial::Map map;
// read the filename of the map
std::string strName;
dataSrc.readString(map.strFilename);
// initialize the user data
map.userData = 0;
// check if an error happened
if(!dataSrc.ok())
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// set map in the core material instance
pCoreMaterial->setMap(mapId, map);
}
return pCoreMaterial;
}
/*****************************************************************************/
/** Loads a core mesh instance.
*
* This function loads a core mesh instance from a data source.
*
* @param dataSrc The data source to load the core mesh instance from.
*
* @return One of the following values:
* \li a pointer to the core mesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMeshPtr CalLoader::loadCoreMesh(CalDataSource& dataSrc)
{
// check if this is a valid file
char magic[4];
if(!dataSrc.readBytes(&magic[0], 4) || (memcmp(&magic[0], Cal::MESH_FILE_MAGIC, 4) != 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// check if the version is compatible with the library
int version;
if(!dataSrc.readInteger(version) || (version < Cal::EARLIEST_COMPATIBLE_FILE_VERSION) || (version > Cal::CURRENT_FILE_VERSION))
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__);
return 0;
}
// get the number of submeshes
int submeshCount;
if(!dataSrc.readInteger(submeshCount))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// allocate a new core mesh instance
CalCoreMeshPtr pCoreMesh = new CalCoreMesh();
if(!pCoreMesh)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// load all core submeshes
for(int submeshId = 0; submeshId < submeshCount; ++submeshId)
{
// load the core submesh
CalCoreSubmesh *pCoreSubmesh = loadCoreSubmesh(dataSrc);
if(pCoreSubmesh == 0)
{
return 0;
}
// add the core submesh to the core mesh instance
pCoreMesh->addCoreSubmesh(pCoreSubmesh);
}
return pCoreMesh;
}
/*****************************************************************************/
/** Loads a core skeleton instance.
*
* This function loads a core skeleton instance from a data source.
*
* @param dataSrc The data source to load the core skeleton instance from.
*
* @return One of the following values:
* \li a pointer to the core skeleton
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSkeletonPtr CalLoader::loadCoreSkeleton(CalDataSource& dataSrc)
{
// check if this is a valid file
char magic[4];
if(!dataSrc.readBytes(&magic[0], 4) || (memcmp(&magic[0], Cal::SKELETON_FILE_MAGIC, 4) != 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// check if the version is compatible with the library
int version;
if(!dataSrc.readInteger(version) || (version < Cal::EARLIEST_COMPATIBLE_FILE_VERSION) || (version > Cal::CURRENT_FILE_VERSION))
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__);
return 0;
}
// read the number of bones
int boneCount;
if(!dataSrc.readInteger(boneCount) || (boneCount <= 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// allocate a new core skeleton instance
CalCoreSkeletonPtr pCoreSkeleton = new CalCoreSkeleton();
if(!pCoreSkeleton)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// load all core bones
for(int boneId = 0; boneId < boneCount; ++boneId)
{
// load the core bone
CalCoreBone *pCoreBone = loadCoreBones(dataSrc);
if(pCoreBone == 0)
{
return 0;
}
// set the core skeleton of the core bone instance
pCoreBone->setCoreSkeleton(pCoreSkeleton.get());
// add the core bone to the core skeleton instance
pCoreSkeleton->addCoreBone(pCoreBone);
// add a core skeleton mapping of the bone's name for quick reference later
pCoreSkeleton->mapCoreBoneName(boneId, pCoreBone->getName());
}
// calculate state of the core skeleton
pCoreSkeleton->calculateState();
return pCoreSkeleton;
}
/*****************************************************************************/
/** Loads a core bone instance.
*
* This function loads a core bone instance from a data source.
*
* @param dataSrc The data source to load the core bone instance from.
*
* @return One of the following values:
* \li a pointer to the core bone
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreBone *CalLoader::loadCoreBones(CalDataSource& dataSrc)
{
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// read the name of the bone
std::string strName;
dataSrc.readString(strName);
// get the translation of the bone
float tx, ty, tz;
dataSrc.readFloat(tx);
dataSrc.readFloat(ty);
dataSrc.readFloat(tz);
// get the rotation of the bone
float rx, ry, rz, rw;
dataSrc.readFloat(rx);
dataSrc.readFloat(ry);
dataSrc.readFloat(rz);
dataSrc.readFloat(rw);
// get the bone space translation of the bone
float txBoneSpace, tyBoneSpace, tzBoneSpace;
dataSrc.readFloat(txBoneSpace);
dataSrc.readFloat(tyBoneSpace);
dataSrc.readFloat(tzBoneSpace);
// get the bone space rotation of the bone
float rxBoneSpace, ryBoneSpace, rzBoneSpace, rwBoneSpace;
dataSrc.readFloat(rxBoneSpace);
dataSrc.readFloat(ryBoneSpace);
dataSrc.readFloat(rzBoneSpace);
dataSrc.readFloat(rwBoneSpace);
// get the parent bone id
int parentId;
dataSrc.readInteger(parentId);
CalQuaternion rot(rx,ry,rz,rw);
CalQuaternion rotbs(rxBoneSpace, ryBoneSpace, rzBoneSpace, rwBoneSpace);
CalVector trans(tx,ty,tz);
if (loadingMode & LOADER_ROTATE_X_AXIS)
{
if (parentId == -1) // only root bone necessary
{
// Root bone must have quaternion rotated
CalQuaternion x_axis_90(0.7071067811f,0.0f,0.0f,0.7071067811f);
rot *= x_axis_90;
// Root bone must have translation rotated also
trans *= x_axis_90;
}
}
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// allocate a new core bone instance
CalCoreBone *pCoreBone;
pCoreBone = new CalCoreBone(strName);
if(pCoreBone == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// set the parent of the bone
pCoreBone->setParentId(parentId);
// set all attributes of the bone
pCoreBone->setTranslation(trans);
pCoreBone->setRotation(rot);
pCoreBone->setTranslationBoneSpace(CalVector(txBoneSpace, tyBoneSpace, tzBoneSpace));
pCoreBone->setRotationBoneSpace(rotbs);
// read the number of children
int childCount;
if(!dataSrc.readInteger(childCount) || (childCount < 0))
{
delete pCoreBone;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// load all children ids
for(; childCount > 0; childCount--)
{
int childId;
if(!dataSrc.readInteger(childId) || (childId < 0))
{
delete pCoreBone;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
pCoreBone->addChildId(childId);
}
return pCoreBone;
}
/*****************************************************************************/
/** Loads a core keyframe instance.
*
* This function loads a core keyframe instance from a data source.
*
* @param dataSrc The data source to load the core keyframe instance from.
*
* @return One of the following values:
* \li a pointer to the core keyframe
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreKeyframe* CalLoader::loadCoreKeyframe(CalDataSource& dataSrc)
{
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// get the time of the keyframe
float time;
dataSrc.readFloat(time);
// get the translation of the bone
float tx, ty, tz;
dataSrc.readFloat(tx);
dataSrc.readFloat(ty);
dataSrc.readFloat(tz);
// get the rotation of the bone
float rx, ry, rz, rw;
dataSrc.readFloat(rx);
dataSrc.readFloat(ry);
dataSrc.readFloat(rz);
dataSrc.readFloat(rw);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
return false;
}
// allocate a new core keyframe instance
CalCoreKeyframe *pCoreKeyframe = new CalCoreKeyframe();
if(pCoreKeyframe == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// create the core keyframe instance
if(!pCoreKeyframe->create())
{
delete pCoreKeyframe;
return 0;
}
// set all attributes of the keyframe
pCoreKeyframe->setTime(time);
pCoreKeyframe->setTranslation(CalVector(tx, ty, tz));
pCoreKeyframe->setRotation(CalQuaternion(rx, ry, rz, rw));
return pCoreKeyframe;
}
/*****************************************************************************/
/** Loads a core submesh instance.
*
* This function loads a core submesh instance from a data source.
*
* @param dataSrc The data source to load the core submesh instance from.
*
* @return One of the following values:
* \li a pointer to the core submesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSubmesh *CalLoader::loadCoreSubmesh(CalDataSource& dataSrc)
{
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// get the material thread id of the submesh
int coreMaterialThreadId;
dataSrc.readInteger(coreMaterialThreadId);
// get the number of vertices, faces, level-of-details and springs
int vertexCount;
dataSrc.readInteger(vertexCount);
int faceCount;
dataSrc.readInteger(faceCount);
int lodCount;
dataSrc.readInteger(lodCount);
int springCount;
dataSrc.readInteger(springCount);
// get the number of texture coordinates per vertex
int textureCoordinateCount;
dataSrc.readInteger(textureCoordinateCount);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// allocate a new core submesh instance
CalCoreSubmesh *pCoreSubmesh;
pCoreSubmesh = new CalCoreSubmesh();
if(pCoreSubmesh == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// set the LOD step count
pCoreSubmesh->setLodCount(lodCount);
// set the core material id
pCoreSubmesh->setCoreMaterialThreadId(coreMaterialThreadId);
// reserve memory for all the submesh data
if(!pCoreSubmesh->reserve(vertexCount, textureCoordinateCount, faceCount, springCount))
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
delete pCoreSubmesh;
return 0;
}
// load the tangent space enable flags.
int textureCoordinateId;
for (textureCoordinateId = 0; textureCoordinateId < textureCoordinateCount; textureCoordinateId++)
{
pCoreSubmesh->enableTangents(textureCoordinateId, false);
}
// load all vertices and their influences
int vertexId;
for(vertexId = 0; vertexId < vertexCount; ++vertexId)
{
CalCoreSubmesh::Vertex vertex;
// load data of the vertex
dataSrc.readFloat(vertex.position.x);
dataSrc.readFloat(vertex.position.y);
dataSrc.readFloat(vertex.position.z);
dataSrc.readFloat(vertex.normal.x);
dataSrc.readFloat(vertex.normal.y);
dataSrc.readFloat(vertex.normal.z);
dataSrc.readInteger(vertex.collapseId);
dataSrc.readInteger(vertex.faceCollapseCount);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// load all texture coordinates of the vertex
int textureCoordinateId;
for(textureCoordinateId = 0; textureCoordinateId < textureCoordinateCount; ++textureCoordinateId)
{
CalCoreSubmesh::TextureCoordinate textureCoordinate;
// load data of the influence
dataSrc.readFloat(textureCoordinate.u);
dataSrc.readFloat(textureCoordinate.v);
if (loadingMode & LOADER_INVERT_V_COORD)
{
textureCoordinate.v = 1.0f - textureCoordinate.v;
}
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// set texture coordinate in the core submesh instance
pCoreSubmesh->setTextureCoordinate(vertexId, textureCoordinateId, textureCoordinate);
}
// get the number of influences
int influenceCount;
if(!dataSrc.readInteger(influenceCount) || (influenceCount < 0))
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// reserve memory for the influences in the vertex
vertex.vectorInfluence.reserve(influenceCount);
vertex.vectorInfluence.resize(influenceCount);
// load all influences of the vertex
int influenceId;
for(influenceId = 0; influenceId < influenceCount; ++influenceId)
{
// load data of the influence
dataSrc.readInteger(vertex.vectorInfluence[influenceId].boneId),
dataSrc.readFloat(vertex.vectorInfluence[influenceId].weight);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
}
// set vertex in the core submesh instance
pCoreSubmesh->setVertex(vertexId, vertex);
// load the physical property of the vertex if there are springs in the core submesh
if(springCount > 0)
{
CalCoreSubmesh::PhysicalProperty physicalProperty;
// load data of the physical property
dataSrc.readFloat(physicalProperty.weight);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// set the physical property in the core submesh instance
pCoreSubmesh->setPhysicalProperty(vertexId, physicalProperty);
}
}
// load all springs
int springId;
for(springId = 0; springId < springCount; ++springId)
{
CalCoreSubmesh::Spring spring;
// load data of the spring
dataSrc.readInteger(spring.vertexId[0]);
dataSrc.readInteger(spring.vertexId[1]);
dataSrc.readFloat(spring.springCoefficient);
dataSrc.readFloat(spring.idleLength);
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// set spring in the core submesh instance
pCoreSubmesh->setSpring(springId, spring);
}
// load all faces
int faceId;
int justOnce = 0;
bool flipModel = false;
for(faceId = 0; faceId < faceCount; ++faceId)
{
CalCoreSubmesh::Face face;
// load data of the face
int tmp[4];
dataSrc.readInteger(tmp[0]);
dataSrc.readInteger(tmp[1]);
dataSrc.readInteger(tmp[2]);
if(sizeof(CalIndex)==2)
{
if(tmp[0]>65535 || tmp[1]>65535 || tmp[2]>65535)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
delete pCoreSubmesh;
return 0;
}
}
face.vertexId[0]=tmp[0];
face.vertexId[1]=tmp[1];
face.vertexId[2]=tmp[2];
// check if an error happened
if(!dataSrc.ok())
{
dataSrc.setError();
delete pCoreSubmesh;
return 0;
}
// check if left-handed coord system is used by the object
// can be done only once since the object has one system for all faces
if (justOnce==0)
{
// get vertexes of first face
std::vector<CalCoreSubmesh::Vertex>& vectorVertex = pCoreSubmesh->getVectorVertex();
CalCoreSubmesh::Vertex& v1 = vectorVertex[tmp[0]];
CalCoreSubmesh::Vertex& v2 = vectorVertex[tmp[1]];
CalCoreSubmesh::Vertex& v3 = vectorVertex[tmp[2]];
CalVector point1 = CalVector(v1.position.x, v1.position.y, v1.position.z);
CalVector point2 = CalVector(v2.position.x, v2.position.y, v2.position.z);
CalVector point3 = CalVector(v3.position.x, v3.position.y, v3.position.z);
// gets vectors (v1-v2) and (v3-v2)
CalVector vect1 = point1 - point2;
CalVector vect2 = point3 - point2;
// calculates normal of face
CalVector cross = vect1 % vect2;
CalVector faceNormal = cross / cross.length();
// compare the calculated normal with the normal of a vertex
CalVector maxNorm = v1.normal;
// if the two vectors point to the same direction then the poly needs flipping
// so if the dot product > 0 it needs flipping
if (faceNormal*maxNorm>0)
flipModel = true;
// flip the winding order if the loading flags request it
if (loadingMode & LOADER_FLIP_WINDING)
flipModel = !flipModel;
justOnce = 1;
}
// flip if needed
if (flipModel)
{
tmp[3] = face.vertexId[1];
face.vertexId[1]=face.vertexId[2];
face.vertexId[2]=tmp[3];
}
// set face in the core submesh instance
pCoreSubmesh->setFace(faceId, face);
}
return pCoreSubmesh;
}
/*****************************************************************************/
/** Loads a core track instance.
*
* This function loads a core track instance from a data source.
*
* @param dataSrc The data source to load the core track instance from.
*
* @return One of the following values:
* \li a pointer to the core track
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreTrack *CalLoader::loadCoreTrack(CalDataSource& dataSrc, CalCoreSkeleton *skel, float duration)
{
if(!dataSrc.ok())
{
dataSrc.setError();
return 0;
}
// read the bone id
int coreBoneId;
if(!dataSrc.readInteger(coreBoneId) || (coreBoneId < 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// allocate a new core track instance
CalCoreTrack *pCoreTrack;
pCoreTrack = new CalCoreTrack();
if(pCoreTrack == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// create the core track instance
if(!pCoreTrack->create())
{
delete pCoreTrack;
return 0;
}
// link the core track to the appropriate core bone instance
pCoreTrack->setCoreBoneId(coreBoneId);
// read the number of keyframes
int keyframeCount;
if(!dataSrc.readInteger(keyframeCount) || (keyframeCount <= 0))
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__);
return 0;
}
// load all core keyframes
int keyframeId;
for(keyframeId = 0; keyframeId < keyframeCount; ++keyframeId)
{
// load the core keyframe
CalCoreKeyframe *pCoreKeyframe = loadCoreKeyframe(dataSrc);
if(pCoreKeyframe == 0)
{
pCoreTrack->destroy();
delete pCoreTrack;
return 0;
}
if(loadingMode & LOADER_ROTATE_X_AXIS)
{
// Check for anim rotation
if (skel && skel->getCoreBone(coreBoneId)->getParentId() == -1) // root bone
{
// rotate root bone quaternion
CalQuaternion rot = pCoreKeyframe->getRotation();
CalQuaternion x_axis_90(0.7071067811f,0.0f,0.0f,0.7071067811f);
rot *= x_axis_90;
pCoreKeyframe->setRotation(rot);
// rotate root bone displacement
CalVector vec = pCoreKeyframe->getTranslation();
vec *= x_axis_90;
pCoreKeyframe->setTranslation(vec);
}
}
// add the core keyframe to the core track instance
pCoreTrack->addCoreKeyframe(pCoreKeyframe);
}
return pCoreTrack;
}
/*****************************************************************************/
/** Loads a core skeleton instance from a XML file.
*
* This function loads a core skeleton instance from a XML file.
*
* @param strFilename The name of the file to load the core skeleton instance
* from.
*
* @return One of the following values:
* \li a pointer to the core skeleton
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreSkeletonPtr CalLoader::loadXmlCoreSkeleton(const std::string& strFilename)
{
std::stringstream str;
TiXmlDocument doc(strFilename);
if(!doc.LoadFile())
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlNode* node;
TiXmlElement*skeleton = doc.FirstChildElement();
if(!skeleton)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
if(stricmp(skeleton->Value(),"HEADER")==0)
{
if(stricmp(skeleton->Attribute("MAGIC"),Cal::SKELETON_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(atoi(skeleton->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
skeleton = skeleton->NextSiblingElement();
}
if(!skeleton || stricmp(skeleton->Value(),"SKELETON")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(skeleton->Attribute("MAGIC")!=NULL && stricmp(skeleton->Attribute("MAGIC"),Cal::SKELETON_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(skeleton->Attribute("VERSION")!=NULL && atoi(skeleton->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
// allocate a new core skeleton instance
CalCoreSkeletonPtr pCoreSkeleton = new CalCoreSkeleton();
if(!pCoreSkeleton)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
TiXmlElement* bone;
for( bone = skeleton->FirstChildElement();bone;bone = bone->NextSiblingElement() )
{
if(stricmp(bone->Value(),"BONE")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
std::string strName=bone->Attribute("NAME");
// get the translation of the bone
TiXmlElement* translation = bone->FirstChildElement();
if(!translation || stricmp( translation->Value(),"TRANSLATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
float tx, ty, tz;
node = translation->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* translationdata = node->ToText();
if(!translationdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << translationdata->Value();
str >> tx >> ty >> tz;
// get the rotation of the bone
TiXmlElement* rotation = translation->NextSiblingElement();
if(!rotation || stricmp(rotation->Value(),"ROTATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
float rx, ry, rz, rw;
node = rotation->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* rotationdata = node->ToText();
if(!rotationdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << rotationdata->Value();
str >> rx >> ry >> rz >> rw;
// get the bone space translation of the bone
TiXmlElement* translationBoneSpace = rotation->NextSiblingElement();
if(!rotation || stricmp(translationBoneSpace->Value(),"LOCALTRANSLATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
float txBoneSpace, tyBoneSpace, tzBoneSpace;
node = translationBoneSpace->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* translationBoneSpacedata = node->ToText();
if(!translationBoneSpacedata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << translationBoneSpacedata->Value();
str >> txBoneSpace >> tyBoneSpace >> tzBoneSpace;
// get the bone space rotation of the bone
TiXmlElement* rotationBoneSpace = translationBoneSpace->NextSiblingElement();
if(!rotationBoneSpace || stricmp(rotationBoneSpace->Value(),"LOCALROTATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
float rxBoneSpace, ryBoneSpace, rzBoneSpace, rwBoneSpace;
node = rotationBoneSpace->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* rotationBoneSpacedata = node->ToText();
if(!rotationBoneSpacedata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << rotationBoneSpacedata->Value();
str >> rxBoneSpace >> ryBoneSpace >> rzBoneSpace >> rwBoneSpace;
// get the parent bone id
TiXmlElement* parent = rotationBoneSpace->NextSiblingElement();
if(!parent ||stricmp(parent->Value(),"PARENTID")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
int parentId;
node = parent->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* parentid = node->ToText();
if(!parentid)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
parentId = atoi(parentid->Value());
// allocate a new core bone instance
CalCoreBone *pCoreBone = new CalCoreBone(strName);
if(pCoreBone == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// set the parent of the bone
pCoreBone->setParentId(parentId);
// set all attributes of the bone
CalVector trans = CalVector(tx, ty, tz);
CalQuaternion rot = CalQuaternion(rx, ry, rz, rw);
if (loadingMode & LOADER_ROTATE_X_AXIS)
{
if (parentId == -1) // only root bone necessary
{
// Root bone must have quaternion rotated
CalQuaternion x_axis_90(0.7071067811f,0.0f,0.0f,0.7071067811f);
rot *= x_axis_90;
// Root bone must have translation rotated also
trans *= x_axis_90;
}
}
pCoreBone->setTranslation(trans);
pCoreBone->setRotation(rot);
pCoreBone->setTranslationBoneSpace(CalVector(txBoneSpace, tyBoneSpace, tzBoneSpace));
pCoreBone->setRotationBoneSpace(CalQuaternion(rxBoneSpace, ryBoneSpace, rzBoneSpace, rwBoneSpace));
TiXmlElement* child;
for( child = parent->NextSiblingElement();child;child = child->NextSiblingElement() )
{
if(stricmp(child->Value(),"CHILDID")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
delete pCoreBone;
return false;
}
TiXmlNode *node= child->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
delete pCoreBone;
return false;
}
TiXmlText* childid = node->ToText();
if(!childid)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
delete pCoreBone;
return false;
}
int childId = atoi(childid->Value());
pCoreBone->addChildId(childId);
}
// set the core skeleton of the core bone instance
pCoreBone->setCoreSkeleton(pCoreSkeleton.get());
// add the core bone to the core skeleton instance
pCoreSkeleton->addCoreBone(pCoreBone);
}
doc.Clear();
pCoreSkeleton->calculateState();
return pCoreSkeleton;
}
/*****************************************************************************/
/** Loads a core animation instance from a XML file.
*
* This function loads a core animation instance from a XML file.
*
* @param strFilename The name of the file to load the core animation instance
* from.
*
* @return One of the following values:
* \li a pointer to the core animation
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreAnimationPtr CalLoader::loadXmlCoreAnimation(const std::string& strFilename, CalCoreSkeleton *skel)
{
std::stringstream str;
TiXmlDocument doc(strFilename);
if(!doc.LoadFile())
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlNode* node;
TiXmlElement*animation = doc.FirstChildElement();
if(!animation)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(stricmp(animation->Value(),"HEADER")==0)
{
if(stricmp(animation->Attribute("MAGIC"),Cal::ANIMATION_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(atoi(animation->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
animation = animation->NextSiblingElement();
}
if(!animation || stricmp(animation->Value(),"ANIMATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(animation->Attribute("MAGIC") !=NULL && stricmp(animation->Attribute("MAGIC"),Cal::ANIMATION_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(animation->Attribute("VERSION")!=NULL && atoi(animation->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
int trackCount= atoi(animation->Attribute("NUMTRACKS"));
float duration= (float) atof(animation->Attribute("DURATION"));
// allocate a new core animation instance
CalCoreAnimation *pCoreAnimation;
pCoreAnimation = new CalCoreAnimation();
if(pCoreAnimation == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// check for a valid duration
if(duration <= 0.0f)
{
CalError::setLastError(CalError::INVALID_ANIMATION_DURATION, __FILE__, __LINE__, strFilename);
return 0;
}
// set the duration in the core animation instance
pCoreAnimation->setDuration(duration);
TiXmlElement* track=animation->FirstChildElement();
// load all core bones
int trackId;
for(trackId = 0; trackId < trackCount; ++trackId)
{
if(!track || stricmp(track->Value(),"TRACK")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
CalCoreTrack *pCoreTrack;
pCoreTrack = new CalCoreTrack();
if(pCoreTrack == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// create the core track instance
if(!pCoreTrack->create())
{
delete pCoreTrack;
return 0;
}
int coreBoneId = atoi(track->Attribute("BONEID"));
// link the core track to the appropriate core bone instance
pCoreTrack->setCoreBoneId(coreBoneId);
// read the number of keyframes
int keyframeCount= atoi(track->Attribute("NUMKEYFRAMES"));
if(keyframeCount <= 0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlElement* keyframe= track->FirstChildElement();
// load all core keyframes
int keyframeId;
for(keyframeId = 0; keyframeId < keyframeCount; ++keyframeId)
{
// load the core keyframe
if(!keyframe|| stricmp(keyframe->Value(),"KEYFRAME")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
float time= (float) atof(keyframe->Attribute("TIME"));
TiXmlElement* translation = keyframe->FirstChildElement();
if(!translation || stricmp(translation->Value(),"TRANSLATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
float tx, ty, tz;
node = translation->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlText* translationdata = node->ToText();
if(!translationdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
str.clear();
str << translationdata->Value();
str >> tx >> ty >> tz;
TiXmlElement* rotation = translation->NextSiblingElement();
if(!rotation || stricmp(rotation->Value(),"ROTATION")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
float rx, ry, rz, rw;
node = rotation->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlText* rotationdata = node->ToText();
if(!rotationdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return 0;
}
str.clear();
str << rotationdata->Value();
str >> rx >> ry >> rz >> rw;
// allocate a new core keyframe instance
CalCoreKeyframe *pCoreKeyframe;
pCoreKeyframe = new CalCoreKeyframe();
if(pCoreKeyframe == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// create the core keyframe instance
if(!pCoreKeyframe->create())
{
return 0;
}
// set all attributes of the keyframe
pCoreKeyframe->setTime(time);
pCoreKeyframe->setTranslation(CalVector(tx, ty, tz));
pCoreKeyframe->setRotation(CalQuaternion(rx, ry, rz, rw));
if (loadingMode & LOADER_ROTATE_X_AXIS)
{
// Check for anim rotation
if (skel && skel->getCoreBone(coreBoneId)->getParentId() == -1) // root bone
{
// rotate root bone quaternion
CalQuaternion rot = pCoreKeyframe->getRotation();
CalQuaternion x_axis_90(0.7071067811f,0.0f,0.0f,0.7071067811f);
rot *= x_axis_90;
pCoreKeyframe->setRotation(rot);
// rotate root bone displacement
CalVector trans = pCoreKeyframe->getTranslation();
trans *= x_axis_90;
pCoreKeyframe->setTranslation(trans);
}
}
// add the core keyframe to the core track instance
pCoreTrack->addCoreKeyframe(pCoreKeyframe);
keyframe = keyframe->NextSiblingElement();
}
pCoreAnimation->addCoreTrack(pCoreTrack);
track=track->NextSiblingElement();
}
// explicitly close the file
doc.Clear();
return pCoreAnimation;
}
/*****************************************************************************/
/** Loads a core mesh instance from a Xml file.
*
* This function loads a core mesh instance from a Xml file.
*
* @param strFilename The name of the file to load the core mesh instance from.
*
* @return One of the following values:
* \li a pointer to the core mesh
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMeshPtr CalLoader::loadXmlCoreMesh(const std::string& strFilename)
{
std::stringstream str;
TiXmlDocument doc(strFilename);
if(!doc.LoadFile())
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlNode* node;
TiXmlElement*mesh = doc.FirstChildElement();
if(!mesh)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(stricmp(mesh->Value(),"HEADER")==0)
{
if(stricmp(mesh->Attribute("MAGIC"),Cal::MESH_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(atoi(mesh->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
mesh = mesh->NextSiblingElement();
}
if(!mesh || stricmp(mesh->Value(),"MESH")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(mesh->Attribute("MAGIC")!=NULL && stricmp(mesh->Attribute("MAGIC"),Cal::MESH_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(mesh->Attribute("VERSION")!=NULL && atoi(mesh->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
// get the number of submeshes
int submeshCount = atoi(mesh->Attribute("NUMSUBMESH"));
// allocate a new core mesh instance
CalCoreMeshPtr pCoreMesh = new CalCoreMesh;
if(!pCoreMesh)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
TiXmlElement*submesh = mesh->FirstChildElement();
// load all core submeshes
int submeshId;
for(submeshId = 0; submeshId < submeshCount; ++submeshId)
{
if(!submesh || stricmp(submesh->Value(),"SUBMESH")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
// get the material thread id of the submesh
int coreMaterialThreadId = atoi(submesh->Attribute("MATERIAL"));
// get the number of vertices, faces, level-of-details and springs
int vertexCount = atoi(submesh->Attribute("NUMVERTICES"));
int faceCount = atoi(submesh->Attribute("NUMFACES"));
int lodCount = atoi(submesh->Attribute("NUMLODSTEPS"));
int springCount = atoi(submesh->Attribute("NUMSPRINGS"));
int textureCoordinateCount = atoi(submesh->Attribute("NUMTEXCOORDS"));
// allocate a new core submesh instance
CalCoreSubmesh *pCoreSubmesh = new CalCoreSubmesh();
if(pCoreSubmesh == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
// set the LOD step count
pCoreSubmesh->setLodCount(lodCount);
// set the core material id
pCoreSubmesh->setCoreMaterialThreadId(coreMaterialThreadId);
// reserve memory for all the submesh data
if(!pCoreSubmesh->reserve(vertexCount, textureCoordinateCount, faceCount, springCount))
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__, strFilename);
delete pCoreSubmesh;
return 0;
}
TiXmlElement *vertex = submesh->FirstChildElement();
// load all vertices and their influences
int vertexId;
for(vertexId = 0; vertexId < vertexCount; ++vertexId)
{
if(!vertex || stricmp(vertex->Value(),"VERTEX")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
CalCoreSubmesh::Vertex Vertex;
TiXmlElement *pos= vertex->FirstChildElement();
if(!pos || stricmp(pos->Value(),"POS")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = pos->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* posdata = node->ToText();
if(!posdata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << posdata->Value();
str >> Vertex.position.x >> Vertex.position.y >> Vertex.position.z;
TiXmlElement *norm= pos->NextSiblingElement();
if(!norm||stricmp(norm->Value(),"NORM")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = norm->FirstChild();
if(!norm)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* normdata = node->ToText();
if(!normdata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << normdata->Value();
str >> Vertex.normal.x >> Vertex.normal.y >> Vertex.normal.z;
TiXmlElement *collapse= norm->NextSiblingElement();
if(collapse && stricmp(collapse->Value(),"COLLAPSEID")==0)
{
node = collapse->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* collapseid = node->ToText();
if(!collapseid)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
Vertex.collapseId = atoi(collapseid->Value());
TiXmlElement *collapseCount= collapse->NextSiblingElement();
if(!collapseCount|| stricmp(collapseCount->Value(),"COLLAPSECOUNT")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = collapseCount->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* collapseCountdata = node->ToText();
if(!collapseCountdata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
Vertex.faceCollapseCount= atoi(collapseCountdata->Value());
collapse = collapseCount->NextSiblingElement();
}
else
{
Vertex.collapseId=-1;
Vertex.faceCollapseCount=0;
}
TiXmlElement *texcoord = collapse;
// load all texture coordinates of the vertex
int textureCoordinateId;
for(textureCoordinateId = 0; textureCoordinateId < textureCoordinateCount; ++textureCoordinateId)
{
CalCoreSubmesh::TextureCoordinate textureCoordinate;
// load data of the influence
if(!texcoord || stricmp(texcoord->Value(),"TEXCOORD")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = texcoord->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* texcoorddata = node->ToText();
if(!texcoorddata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << texcoorddata->Value();
str >> textureCoordinate.u >> textureCoordinate.v;
if (loadingMode & LOADER_INVERT_V_COORD)
{
textureCoordinate.v = 1.0f - textureCoordinate.v;
}
// set texture coordinate in the core submesh instance
pCoreSubmesh->setTextureCoordinate(vertexId, textureCoordinateId, textureCoordinate);
texcoord = texcoord->NextSiblingElement();
}
// get the number of influences
int influenceCount= atoi(vertex->Attribute("NUMINFLUENCES"));
if(influenceCount < 0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
delete pCoreSubmesh;
return 0;
}
// reserve memory for the influences in the vertex
Vertex.vectorInfluence.reserve(influenceCount);
Vertex.vectorInfluence.resize(influenceCount);
TiXmlElement *influence = texcoord;
// load all influences of the vertex
int influenceId;
for(influenceId = 0; influenceId < influenceCount; ++influenceId)
{
if(!influence ||stricmp(influence->Value(),"INFLUENCE")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = influence->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* influencedata = node->ToText();
if(!influencedata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
Vertex.vectorInfluence[influenceId].boneId = atoi(influence->Attribute("ID"));
Vertex.vectorInfluence[influenceId].weight = (float) atof(influencedata->Value());
influence=influence->NextSiblingElement();
}
// set vertex in the core submesh instance
pCoreSubmesh->setVertex(vertexId, Vertex);
TiXmlElement *physique = influence;
// load the physical property of the vertex if there are springs in the core submesh
if(springCount > 0)
{
CalCoreSubmesh::PhysicalProperty physicalProperty;
if(!physique || stricmp(physique->Value(),"PHYSIQUE")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node = physique->FirstChild();
if(!node)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* physiquedata = node->ToText();
if(!physiquedata)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
physicalProperty.weight = (float) atof(physiquedata->Value());
// set the physical property in the core submesh instance
pCoreSubmesh->setPhysicalProperty(vertexId, physicalProperty);
}
vertex = vertex->NextSiblingElement();
}
TiXmlElement *spring= vertex;
// load all springs
int springId;
for(springId = 0; springId < springCount; ++springId)
{
CalCoreSubmesh::Spring Spring;
if(!spring ||stricmp(spring->Value(),"SPRING")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << spring->Attribute("VERTEXID");
str >> Spring.vertexId[0] >> Spring.vertexId[1];
Spring.springCoefficient = (float) atof(spring->Attribute("COEF"));
Spring.idleLength = (float) atof(spring->Attribute("LENGTH"));
// set spring in the core submesh instance
pCoreSubmesh->setSpring(springId, Spring);
spring = spring->NextSiblingElement();
}
TiXmlElement *face = spring;
// load all faces
int faceId;
for(faceId = 0; faceId < faceCount; ++faceId)
{
CalCoreSubmesh::Face Face;
if(!face || stricmp(face->Value(),"FACE")!=0)
{
delete pCoreSubmesh;
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
int tmp[3];
// load data of the face
str.clear();
str << face->Attribute("VERTEXID");
str >> tmp[0] >> tmp [1] >> tmp[2];
if(sizeof(CalIndex)==2)
{
if(tmp[0]>65535 || tmp[1]>65535 || tmp[2]>65535)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
delete pCoreSubmesh;
return 0;
}
}
Face.vertexId[0]=tmp[0];
Face.vertexId[1]=tmp[1];
Face.vertexId[2]=tmp[2];
pCoreSubmesh->setFace(faceId, Face);
face=face->NextSiblingElement();
}
submesh=submesh->NextSiblingElement();
// add the core submesh to the core mesh instance
pCoreMesh->addCoreSubmesh(pCoreSubmesh);
}
// explicitly close the file
doc.Clear();
return pCoreMesh;
}
/*****************************************************************************/
/** Loads a core material instance from a XML file.
*
* This function loads a core material instance from a XML file.
*
* @param strFilename The name of the file to load the core material instance
* from.
*
* @return One of the following values:
* \li a pointer to the core material
* \li \b 0 if an error happened
*****************************************************************************/
CalCoreMaterialPtr CalLoader::loadXmlCoreMaterial(const std::string& strFilename)
{
std::stringstream str;
int r,g,b,a;
TiXmlDocument doc(strFilename);
if(!doc.LoadFile())
{
CalError::setLastError(CalError::FILE_NOT_FOUND, __FILE__, __LINE__, strFilename);
return 0;
}
TiXmlNode* node;
TiXmlElement*material = doc.FirstChildElement();
if(!material)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(stricmp(material->Value(),"HEADER")==0)
{
if(stricmp(material->Attribute("MAGIC"),Cal::MATERIAL_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(atoi(material->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
material = material->NextSiblingElement();
}
if(!material||stricmp(material->Value(),"MATERIAL")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(material->Attribute("MAGIC")!=NULL && stricmp(material->Attribute("MAGIC"),Cal::MATERIAL_XMLFILE_MAGIC)!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
if(material->Attribute("VERSION") != NULL && atoi(material->Attribute("VERSION")) < Cal::EARLIEST_COMPATIBLE_FILE_VERSION )
{
CalError::setLastError(CalError::INCOMPATIBLE_FILE_VERSION, __FILE__, __LINE__, strFilename);
return false;
}
CalCoreMaterialPtr pCoreMaterial = new CalCoreMaterial();
if(!pCoreMaterial)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return 0;
}
TiXmlElement* ambient = material->FirstChildElement();
if(!ambient ||stricmp(ambient->Value(),"AMBIENT")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
CalCoreMaterial::Color ambientColor;
node = ambient->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* ambientdata = node->ToText();
if(!ambientdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str << ambientdata->Value();
str >> r >> g >> b >> a;
ambientColor.red = (unsigned char)r;
ambientColor.green = (unsigned char)g;
ambientColor.blue = (unsigned char)b;
ambientColor.alpha = (unsigned char)a;
TiXmlElement* diffuse = ambient->NextSiblingElement();
if(!diffuse || stricmp(diffuse->Value(),"DIFFUSE")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
CalCoreMaterial::Color diffuseColor;
node = diffuse->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* diffusedata = node->ToText();
if(!diffusedata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << diffusedata->Value();
str >> r >> g >> b >> a;
diffuseColor.red = (unsigned char)r;
diffuseColor.green = (unsigned char)g;
diffuseColor.blue = (unsigned char)b;
diffuseColor.alpha = (unsigned char)a;
TiXmlElement* specular = diffuse->NextSiblingElement();
if(!specular||stricmp(specular->Value(),"SPECULAR")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
CalCoreMaterial::Color specularColor;
node = specular->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* speculardata = node->ToText();
if(!speculardata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
str.clear();
str << speculardata->Value();
str >> r >> g >> b >> a;
specularColor.red = (unsigned char)r;
specularColor.green = (unsigned char)g;
specularColor.blue = (unsigned char)b;
specularColor.alpha = (unsigned char)a;
TiXmlElement* shininess = specular->NextSiblingElement();
if(!shininess||stricmp(shininess->Value(),"SHININESS")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
float fshininess;
node = shininess->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* shininessdata = node->ToText();
if(!shininessdata)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
fshininess = (float)atof(shininessdata->Value());
// set the colors and the shininess
pCoreMaterial->setAmbientColor(ambientColor);
pCoreMaterial->setDiffuseColor(diffuseColor);
pCoreMaterial->setSpecularColor(specularColor);
pCoreMaterial->setShininess(fshininess);
std::vector<std::string> MatFileName;
TiXmlElement* map;
for(map = shininess->NextSiblingElement();map;map = map->NextSiblingElement() )
{
if(!map||stricmp(map->Value(),"MAP")!=0)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
node= map->FirstChild();
if(!node)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
TiXmlText* mapfile = node->ToText();
if(!mapfile)
{
CalError::setLastError(CalError::INVALID_FILE_FORMAT, __FILE__, __LINE__, strFilename);
return false;
}
MatFileName.push_back(mapfile->Value());
}
pCoreMaterial->reserve(MatFileName.size());
for(unsigned int mapId=0; mapId < MatFileName.size(); ++mapId)
{
CalCoreMaterial::Map Map;
// initialize the user data
Map.userData = 0;
Map.strFilename= MatFileName[mapId];
// set map in the core material instance
pCoreMaterial->setMap(mapId, Map);
}
doc.Clear();
return pCoreMaterial;
}
//****************************************************************************//
| 29.281729 | 129 | 0.653324 | [
"mesh",
"object",
"vector",
"model"
] |
6514f658ca7f08fcf4e874a0460ae23cce7ce343 | 4,879 | cpp | C++ | IndirectBuffer.cpp | evanw/indirectbuffer | f18febb01f8ff74cc4abfd4d95e6ced7d2439088 | [
"Unlicense"
] | 87 | 2015-12-07T16:17:17.000Z | 2022-03-29T09:44:25.000Z | IndirectBuffer.cpp | evanw/indirectbuffer | f18febb01f8ff74cc4abfd4d95e6ced7d2439088 | [
"Unlicense"
] | 1 | 2019-04-19T07:46:17.000Z | 2019-04-19T07:46:17.000Z | IndirectBuffer.cpp | evanw/indirectbuffer | f18febb01f8ff74cc4abfd4d95e6ced7d2439088 | [
"Unlicense"
] | 7 | 2016-08-17T12:44:24.000Z | 2021-10-18T21:09:19.000Z | #include "IndirectBuffer.h"
#include <assert.h>
#if defined(__EMSCRIPTEN__)
#include <emscripten.h>
#endif
IndirectBuffer::IndirectBuffer() {
#if defined(__EMSCRIPTEN__)
static int nextHandle = 1;
_handle = ++nextHandle;
EM_ASM_ARGS({
(Module._IB_ || (Module._IB_ = {}))[$0] = new Uint8Array();
}, _handle);
#endif
}
IndirectBuffer::IndirectBuffer(size_t count) : IndirectBuffer() {
resize(count);
}
IndirectBuffer::IndirectBuffer(const std::string &text) : IndirectBuffer((const uint8_t *)text.data(), text.size()) {
}
IndirectBuffer::IndirectBuffer(const std::vector<uint8_t> &bytes) : IndirectBuffer(bytes.data(), bytes.size()) {
}
IndirectBuffer::IndirectBuffer(const uint8_t *bytes, size_t count) : IndirectBuffer(count) {
set(0, bytes, count);
}
IndirectBuffer::IndirectBuffer(IndirectBuffer &&buffer) noexcept : IndirectBuffer() {
*this = std::move(buffer);
}
IndirectBuffer::~IndirectBuffer() {
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
delete Module._IB_[$0];
}, _handle);
#endif
}
IndirectBuffer &IndirectBuffer::operator = (IndirectBuffer &&buffer) noexcept {
#if defined(__EMSCRIPTEN__)
std::swap(_handle, buffer._handle);
std::swap(_size, buffer._size);
#else
_data.swap(buffer._data);
#endif
return *this;
}
IndirectBuffer IndirectBuffer::clone() const {
IndirectBuffer result(size());
result.copyFrom(0, size(), *this, 0);
return result;
}
uint8_t IndirectBuffer::get(size_t index) const {
assert(index < size());
#if defined(__EMSCRIPTEN__)
return EM_ASM_INT({
return Module._IB_[$0][$1];
}, _handle, index);
#else
return _data[index];
#endif
}
void IndirectBuffer::set(size_t index, uint8_t byte) {
assert(index < size());
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
Module._IB_[$0][$1] = $2;
}, _handle, index, byte);
#else
_data[index] = byte;
#endif
}
void IndirectBuffer::get(size_t index, uint8_t *bytes, size_t count) const {
assert(index + count <= size());
if (!bytes || !count) {
return;
}
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
Module.HEAP8.set(Module._IB_[$0].subarray($1, $1 + $3), $2);
}, _handle, index, bytes, count);
#else
memcpy(bytes, _data.data() + index, count);
#endif
}
void IndirectBuffer::set(size_t index, const uint8_t *bytes, size_t count) {
assert(index + count <= size());
if (!bytes || !count) {
return;
}
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
Module._IB_[$0].set(Module.HEAP8.subarray($2, $2 + $3), $1);
}, _handle, index, bytes, count);
#else
memcpy(_data.data() + index, bytes, count);
#endif
}
size_t IndirectBuffer::size() const {
#if defined(__EMSCRIPTEN__)
return _size;
#else
return _data.size();
#endif
}
void IndirectBuffer::resize(size_t count) {
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
var old = Module._IB_[$0];
(Module._IB_[$0] = new Uint8Array($1)).set(old.length < $1 ? old : old.subarray(0, $1));
}, _handle, count);
_size = count;
#else
_data.resize(count);
#endif
}
void IndirectBuffer::move(size_t newIndex, size_t oldIndex, size_t count) {
assert(oldIndex + count <= size());
assert(newIndex + count <= size());
if (oldIndex == newIndex) {
return;
}
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
var array = Module._IB_[$0];
array.set(array.subarray($2, $2 + $3), $1);
}, _handle, newIndex, oldIndex, count);
#else
memmove(_data.data() + newIndex, _data.data() + oldIndex, count);
#endif
}
void IndirectBuffer::copyFrom(size_t toIndex, size_t count, const IndirectBuffer &buffer, size_t fromIndex) {
assert(fromIndex + count <= buffer.size());
assert(toIndex + count <= size());
if (this == &buffer) {
move(toIndex, fromIndex, count);
} else {
#if defined(__EMSCRIPTEN__)
EM_ASM_ARGS({
var fromArray = Module._IB_[$3];
var toArray = Module._IB_[$0];
toArray.set(fromArray.subarray($4, $4 + $2), $1);
}, _handle, toIndex, count, buffer._handle, fromIndex);
#else
set(toIndex, buffer._data.data() + fromIndex, count);
#endif
}
}
IndirectBuffer IndirectBuffer::concat(const std::vector<const IndirectBuffer *> &buffers) {
size_t totalSize = 0;
for (const auto &buffer : buffers) {
totalSize += buffer->size();
}
IndirectBuffer result(totalSize);
size_t index = 0;
for (const auto &buffer : buffers) {
result.copyFrom(index, buffer->size(), *buffer, 0);
index += buffer->size();
}
return std::move(result);
}
std::string IndirectBuffer::toString() const {
std::string result;
result.resize(size());
get(0, (uint8_t *)&result[0], size());
return result;
}
int IndirectBuffer::handleForEmscripten() const {
#if defined(__EMSCRIPTEN__)
return _handle;
#else
return 0;
#endif
}
| 24.034483 | 117 | 0.649723 | [
"vector"
] |
651618db10bfd7923215a28765e44bb468112a75 | 5,232 | cpp | C++ | 2019/day05/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2019/day05/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2019/day05/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <functional>
#include <vector>
#include <map>
static const int INPUT_PART1 = 1;
static const int INPUT_PART2 = 5;
enum OPCODE {
ADD = 1,
MUL = 2,
IN = 3,
OUT = 4,
JMPT = 5,
JMPF = 6,
LT = 7,
EQ = 8,
HALT = 99,
};
enum PARAM_MODE {
POSITION = 0,
IMMEDIATE = 1,
};
static const std::map<enum OPCODE, int> opSizes{
{ ADD, 4 },
{ MUL, 4 },
{ IN, 2 },
{ OUT, 2 },
{ JMPT, 3 },
{ JMPF, 3 },
{ LT, 4 },
{ EQ, 4 },
{ HALT, 1 },
};
typedef struct Instruction {
int opcode;
int param1, param2, param3;
enum PARAM_MODE mode1, mode2, mode3;
} Instruction;
class IntCodeComputer {
private:
std::vector<int> v;
int ip; // instruction pointer
int diagCode;
Instruction getNextInstruction();
int getValueByMode(int param, enum PARAM_MODE mode);
void addInstruction(Instruction ins);
void mulInstruction(Instruction ins);
void inInstruction(Instruction ins, int input);
void outInstruction(Instruction ins);
void jmptInstruction(Instruction ins);
void jmpfInstruction(Instruction ins);
void ltInstruction(Instruction ins);
void eqInstruction(Instruction ins);
public:
IntCodeComputer() : v(), ip(), diagCode() {
}
IntCodeComputer(std::vector<int> v) : v(v), ip(), diagCode() {
}
int run(int input);
};
int main() {
std::ifstream fin("data.in");
std::vector<int> v;
int x;
while (fin >> x) {
v.push_back(x);
fin.ignore();
}
fin.close();
IntCodeComputer computer{v};
std::cout << "The answer for part1 is: " << computer.run(INPUT_PART1) << "\n";
std::cout << "The answer for part2 is: " << computer.run(INPUT_PART2) << "\n";
return 0;
}
int IntCodeComputer::getValueByMode(int param, enum PARAM_MODE mode) {
if (mode == POSITION) {
return v[param];
}
return param;
}
int IntCodeComputer::run(int input) {
std::vector<int> copyV = v;
ip = 0;
diagCode = 0;
while (ip >= 0 && ip < (int)v.size()) {
Instruction ins = getNextInstruction();
switch (ins.opcode) {
case ADD:
addInstruction(ins);
break;
case MUL:
mulInstruction(ins);
break;
case IN:
inInstruction(ins, input);
break;
case OUT:
outInstruction(ins);
break;
case JMPT:
jmptInstruction(ins);
break;
case JMPF:
jmpfInstruction(ins);
break;
case LT:
ltInstruction(ins);
break;
case EQ:
eqInstruction(ins);
break;
case HALT:
ip = v.size();
break;
default:
std::cout << "Invalid opcode " << ins.opcode << " at index " << ip << "\n";
ip = -1;
break;
}
}
v = copyV;
ip = 0;
return diagCode;
}
Instruction IntCodeComputer::getNextInstruction() {
Instruction ins = {0};
ins.opcode = v[ip] % 100;
ins.mode1 = (enum PARAM_MODE)((v[ip] / 100) % 10);
ins.mode2 = (enum PARAM_MODE)((v[ip] / 1000) % 10);
ins.mode3 = (enum PARAM_MODE)((v[ip] / 10000) % 10);
if (ins.opcode == HALT) {
return ins;
}
ins.param1 = v[ip + 1];
if (ins.opcode == IN || ins.opcode == OUT) {
return ins;
}
ins.param2 = v[ip + 2];
if (ins.opcode == JMPT || ins.opcode == JMPF) {
return ins;
}
ins.param3 = v[ip + 3];
return ins;
}
void IntCodeComputer::addInstruction(Instruction ins) {
v[ins.param3] = getValueByMode(ins.param1, ins.mode1) +
getValueByMode(ins.param2, ins.mode2);
ip += opSizes.at(ADD);
}
void IntCodeComputer::mulInstruction(Instruction ins) {
v[ins.param3] = getValueByMode(ins.param1, ins.mode1) *
getValueByMode(ins.param2, ins.mode2);
ip += opSizes.at(MUL);
}
void IntCodeComputer::inInstruction(Instruction ins, int input) {
v[ins.param1] = input;
ip += opSizes.at(IN);
}
void IntCodeComputer::outInstruction(Instruction ins) {
diagCode = getValueByMode(ins.param1, ins.mode1);
ip += opSizes.at(OUT);
}
void IntCodeComputer::jmptInstruction(Instruction ins) {
if (getValueByMode(ins.param1, ins.mode1) != 0) {
ip = getValueByMode(ins.param2, ins.mode2);
} else {
ip += opSizes.at(JMPT);
}
}
void IntCodeComputer::jmpfInstruction(Instruction ins) {
if (getValueByMode(ins.param1, ins.mode1) == 0) {
ip = getValueByMode(ins.param2, ins.mode2);
} else {
ip += opSizes.at(JMPF);
}
}
void IntCodeComputer::ltInstruction(Instruction ins) {
int diff = 0;
diff = getValueByMode(ins.param1, ins.mode1) -
getValueByMode(ins.param2, ins.mode2);
v[ins.param3] = (diff < 0);
ip += opSizes.at(LT);
}
void IntCodeComputer::eqInstruction(Instruction ins) {
int diff = 0;
diff = getValueByMode(ins.param1, ins.mode1) -
getValueByMode(ins.param2, ins.mode2);
v[ins.param3] = (diff == 0);
ip += opSizes.at(EQ);
}
| 21.891213 | 87 | 0.563073 | [
"vector"
] |
651b548b5fe15824e1b276b691243ab6bb1be57a | 613 | cpp | C++ | src/Generic/common/cleanup_hooks.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Generic/common/cleanup_hooks.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Generic/common/cleanup_hooks.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2011 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h" // This must be the first #include
#include "Generic/common/cleanup_hooks.h"
#include <vector>
#include <boost/foreach.hpp>
namespace {
std::vector<CleanupFunction>& _cleanupFunctions() {
static std::vector<CleanupFunction> cleanupFunctions;
return cleanupFunctions;
}
}
void addCleanupHook(CleanupFunction hook) {
_cleanupFunctions().push_back(hook);
}
/** Run all registered cleanup hooks. */
void runCleanupHooks() {
BOOST_FOREACH(CleanupFunction f, _cleanupFunctions()) {
f();
}
}
| 21.892857 | 77 | 0.748777 | [
"vector"
] |
fb993f19b5cc1026eb5a76aa9759e8f46e71acb0 | 16,365 | cpp | C++ | cppcrypto/mars.cpp | crashdemons/kerukuro-cppcrypto | 090d0e97280c0c34267ab50b72a2ffa5b991110b | [
"BSD-2-Clause"
] | null | null | null | cppcrypto/mars.cpp | crashdemons/kerukuro-cppcrypto | 090d0e97280c0c34267ab50b72a2ffa5b991110b | [
"BSD-2-Clause"
] | null | null | null | cppcrypto/mars.cpp | crashdemons/kerukuro-cppcrypto | 090d0e97280c0c34267ab50b72a2ffa5b991110b | [
"BSD-2-Clause"
] | null | null | null | /*
This code is written by kerukuro for cppcrypto library (http://cppcrypto.sourceforge.net/)
and released into public domain.
*/
#include "mars.h"
#include "portability.h"
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <bitset>
#ifdef _MSC_VER
#define inline __forceinline
#endif
//#define CPPCRYPTO_DEBUG
namespace cppcrypto
{
static const uint32_t S[512] = {
0x09d0c479, 0x28c8ffe0, 0x84aa6c39, 0x9dad7287, 0x7dff9be3, 0xd4268361, 0xc96da1d4, 0x7974cc93, 0x85d0582e, 0x2a4b5705,
0x1ca16a62, 0xc3bd279d, 0x0f1f25e5, 0x5160372f, 0xc695c1fb, 0x4d7ff1e4, 0xae5f6bf4, 0x0d72ee46, 0xff23de8a, 0xb1cf8e83,
0xf14902e2, 0x3e981e42, 0x8bf53eb6, 0x7f4bf8ac, 0x83631f83, 0x25970205, 0x76afe784, 0x3a7931d4, 0x4f846450, 0x5c64c3f6,
0x210a5f18, 0xc6986a26, 0x28f4e826, 0x3a60a81c, 0xd340a664, 0x7ea820c4, 0x526687c5, 0x7eddd12b, 0x32a11d1d, 0x9c9ef086,
0x80f6e831, 0xab6f04ad, 0x56fb9b53, 0x8b2e095c, 0xb68556ae, 0xd2250b0d, 0x294a7721, 0xe21fb253, 0xae136749, 0xe82aae86,
0x93365104, 0x99404a66, 0x78a784dc, 0xb69ba84b, 0x04046793, 0x23db5c1e, 0x46cae1d6, 0x2fe28134, 0x5a223942, 0x1863cd5b,
0xc190c6e3, 0x07dfb846, 0x6eb88816, 0x2d0dcc4a, 0xa4ccae59, 0x3798670d, 0xcbfa9493, 0x4f481d45, 0xeafc8ca8, 0xdb1129d6,
0xb0449e20, 0x0f5407fb, 0x6167d9a8, 0xd1f45763, 0x4daa96c3, 0x3bec5958, 0xababa014, 0xb6ccd201, 0x38d6279f, 0x02682215,
0x8f376cd5, 0x092c237e, 0xbfc56593, 0x32889d2c, 0x854b3e95, 0x05bb9b43, 0x7dcd5dcd, 0xa02e926c, 0xfae527e5, 0x36a1c330,
0x3412e1ae, 0xf257f462, 0x3c4f1d71, 0x30a2e809, 0x68e5f551, 0x9c61ba44, 0x5ded0ab8, 0x75ce09c8, 0x9654f93e, 0x698c0cca,
0x243cb3e4, 0x2b062b97, 0x0f3b8d9e, 0x00e050df, 0xfc5d6166, 0xe35f9288, 0xc079550d, 0x0591aee8, 0x8e531e74, 0x75fe3578,
0x2f6d829a, 0xf60b21ae, 0x95e8eb8d, 0x6699486b, 0x901d7d9b, 0xfd6d6e31, 0x1090acef, 0xe0670dd8, 0xdab2e692, 0xcd6d4365,
0xe5393514, 0x3af345f0, 0x6241fc4d, 0x460da3a3, 0x7bcf3729, 0x8bf1d1e0, 0x14aac070, 0x1587ed55, 0x3afd7d3e, 0xd2f29e01,
0x29a9d1f6, 0xefb10c53, 0xcf3b870f, 0xb414935c, 0x664465ed, 0x024acac7, 0x59a744c1, 0x1d2936a7, 0xdc580aa6, 0xcf574ca8,
0x040a7a10, 0x6cd81807, 0x8a98be4c, 0xaccea063, 0xc33e92b5, 0xd1e0e03d, 0xb322517e, 0x2092bd13, 0x386b2c4a, 0x52e8dd58,
0x58656dfb, 0x50820371, 0x41811896, 0xe337ef7e, 0xd39fb119, 0xc97f0df6, 0x68fea01b, 0xa150a6e5, 0x55258962, 0xeb6ff41b,
0xd7c9cd7a, 0xa619cd9e, 0xbcf09576, 0x2672c073, 0xf003fb3c, 0x4ab7a50b, 0x1484126a, 0x487ba9b1, 0xa64fc9c6, 0xf6957d49,
0x38b06a75, 0xdd805fcd, 0x63d094cf, 0xf51c999e, 0x1aa4d343, 0xb8495294, 0xce9f8e99, 0xbffcd770, 0xc7c275cc, 0x378453a7,
0x7b21be33, 0x397f41bd, 0x4e94d131, 0x92cc1f98, 0x5915ea51, 0x99f861b7, 0xc9980a88, 0x1d74fd5f, 0xb0a495f8, 0x614deed0,
0xb5778eea, 0x5941792d, 0xfa90c1f8, 0x33f824b4, 0xc4965372, 0x3ff6d550, 0x4ca5fec0, 0x8630e964, 0x5b3fbbd6, 0x7da26a48,
0xb203231a, 0x04297514, 0x2d639306, 0x2eb13149, 0x16a45272, 0x532459a0, 0x8e5f4872, 0xf966c7d9, 0x07128dc0, 0x0d44db62,
0xafc8d52d, 0x06316131, 0xd838e7ce, 0x1bc41d00, 0x3a2e8c0f, 0xea83837e, 0xb984737d, 0x13ba4891, 0xc4f8b949, 0xa6d6acb3,
0xa215cdce, 0x8359838b, 0x6bd1aa31, 0xf579dd52, 0x21b93f93, 0xf5176781, 0x187dfdde, 0xe94aeb76, 0x2b38fd54, 0x431de1da,
0xab394825, 0x9ad3048f, 0xdfea32aa, 0x659473e3, 0x623f7863, 0xf3346c59, 0xab3ab685, 0x3346a90b, 0x6b56443e, 0xc6de01f8,
0x8d421fc0, 0x9b0ed10c, 0x88f1a1e9, 0x54c1f029, 0x7dead57b, 0x8d7ba426, 0x4cf5178a, 0x551a7cca, 0x1a9a5f08, 0xfcd651b9,
0x25605182, 0xe11fc6c3, 0xb6fd9676, 0x337b3027, 0xb7c8eb14, 0x9e5fd030, 0x6b57e354, 0xad913cf7, 0x7e16688d, 0x58872a69,
0x2c2fc7df, 0xe389ccc6, 0x30738df1, 0x0824a734, 0xe1797a8b, 0xa4a8d57b, 0x5b5d193b, 0xc8a8309b, 0x73f9a978, 0x73398d32,
0x0f59573e, 0xe9df2b03, 0xe8a5b6c8, 0x848d0704, 0x98df93c2, 0x720a1dc3, 0x684f259a, 0x943ba848, 0xa6370152, 0x863b5ea3,
0xd17b978b, 0x6d9b58ef, 0x0a700dd4, 0xa73d36bf, 0x8e6a0829, 0x8695bc14, 0xe35b3447, 0x933ac568, 0x8894b022, 0x2f511c27,
0xddfbcc3c, 0x006662b6, 0x117c83fe, 0x4e12b414, 0xc2bca766, 0x3a2fec10, 0xf4562420, 0x55792e2a, 0x46f5d857, 0xceda25ce,
0xc3601d3b, 0x6c00ab46, 0xefac9c28, 0xb3c35047, 0x611dfee3, 0x257c3207, 0xfdd58482, 0x3b14d84f, 0x23becb64, 0xa075f3a3,
0x088f8ead, 0x07adf158, 0x7796943c, 0xfacabf3d, 0xc09730cd, 0xf7679969, 0xda44e9ed, 0x2c854c12, 0x35935fa3, 0x2f057d9f,
0x690624f8, 0x1cb0bafd, 0x7b0dbdc6, 0x810f23bb, 0xfa929a1a, 0x6d969a17, 0x6742979b, 0x74ac7d05, 0x010e65c4, 0x86a3d963,
0xf907b5a0, 0xd0042bd3, 0x158d7d03, 0x287a8255, 0xbba8366f, 0x096edc33, 0x21916a7b, 0x77b56b86, 0x951622f9, 0xa6c5e650,
0x8cea17d1, 0xcd8c62bc, 0xa3d63433, 0x358a68fd, 0x0f9b9d3c, 0xd6aa295b, 0xfe33384a, 0xc000738e, 0xcd67eb2f, 0xe2eb6dc2,
0x97338b02, 0x06c9f246, 0x419cf1ad, 0x2b83c045, 0x3723f18a, 0xcb5b3089, 0x160bead7, 0x5d494656, 0x35f8a74b, 0x1e4e6c9e,
0x000399bd, 0x67466880, 0xb4174831, 0xacf423b2, 0xca815ab3, 0x5a6395e7, 0x302a67c5, 0x8bdb446b, 0x108f8fa4, 0x10223eda,
0x92b8b48b, 0x7f38d0ee, 0xab2701d4, 0x0262d415, 0xaf224a30, 0xb3d88aba, 0xf8b2c3af, 0xdaf7ef70, 0xcc97d3b7, 0xe9614b6c,
0x2baebff4, 0x70f687cf, 0x386c9156, 0xce092ee5, 0x01e87da6, 0x6ce91e6a, 0xbb7bcc84, 0xc7922c20, 0x9d3b71fd, 0x060e41c6,
0xd7590f15, 0x4e03bb47, 0x183c198e, 0x63eeb240, 0x2ddbf49a, 0x6d5cba54, 0x923750af, 0xf9e14236, 0x7838162b, 0x59726c72,
0x81b66760, 0xbb2926c1, 0x48a0ce0d, 0xa6c0496d, 0xad43507b, 0x718d496a, 0x9df057af, 0x44b1bde6, 0x054356dc, 0xde7ced35,
0xd51a138b, 0x62088cc9, 0x35830311, 0xc96efca2, 0x686f86ec, 0x8e77cb68, 0x63e1d6b8, 0xc80f9778, 0x79c491fd, 0x1b4c67f2,
0x72698d7d, 0x5e368c31, 0xf7d95e2e, 0xa1d3493f, 0xdcd9433e, 0x896f1552, 0x4bc4ca7a, 0xa6d1baf4, 0xa5a96dcc, 0x0bef8b46,
0xa169fda7, 0x74df40b7, 0x4e208804, 0x9a756607, 0x038e87c8, 0x20211e44, 0x8b7ad4bf, 0xc6403f35, 0x1848e36d, 0x80bdb038,
0x1e62891c, 0x643d2107, 0xbf04d6f8, 0x21092c8c, 0xf644f389, 0x0778404e, 0x7b78adb8, 0xa2c52d53, 0x42157abe, 0xa2253e2e,
0x7bf3f4ae, 0x80f594f9, 0x953194e7, 0x77eb92ed, 0xb3816930, 0xda8d9336, 0xbf447469, 0xf26d9483, 0xee6faed5, 0x71371235,
0xde425f73, 0xb4e59f43, 0x7dbe2d4e, 0x2d37b185, 0x49dc9a63, 0x98c39d98, 0x1301c9a2, 0x389b1bbf, 0x0c18588d, 0xa421c1ba,
0x7aa3865c, 0x71e08558, 0x3c5cfcaa, 0x7d239ca4, 0x0297d9dd, 0xd7dc2830, 0x4b37802b, 0x7428ab54, 0xaeee0347, 0x4b3fbb85,
0x692f2f08, 0x134e578e, 0x36d9e0bf, 0xae8b5fcf, 0xedb93ecf, 0x2b27248e, 0x170eb1ef, 0x7dc57fd6, 0x1e760f16, 0xb1136601,
0x864e1b9b, 0xd7ea7319, 0x3ab871bd, 0xcfa4d76f, 0xe31bd782, 0x0dbeb469, 0xabb96061, 0x5370f85d, 0xffb07e37, 0xda30d0fb,
0xebc977b6, 0x0b98b40f, 0x3a4d0fe6, 0xdf4fc26b, 0x159cf22a, 0xc298d6e2, 0x2b78ef6a, 0x61a94ac0, 0xab561187, 0x14eea0f0,
0xdf0d4164, 0x19af70ee
};
static inline void E(uint32_t x, uint32_t k1, uint32_t k2, uint32_t& o1, uint32_t& o2, uint32_t& o3)
{
uint32_t R = rotatel32(x, 13);
uint32_t M = x + k1;
uint32_t L = S[M & 0x1FF];
R *= k2;
R = rotatel32(R, 5);
L ^= R;
M = rotatel32(M, R & 0x1F);
R = rotatel32(R, 5);
L ^= R;
L = rotatel32(L, R & 0x1F);
o1 = L;
o2 = M;
o3 = R;
}
static inline uint32_t gen_mask(uint32_t w)
{
uint32_t M = 0;
for (int k = 0; k < 23; k++)
{
uint32_t x = w >> k;
uint32_t t = x & 0x3FF;
if (!t || t == 0x3FF)
M |= 0x3FF << k;
}
M &= ((~w ^ (w << 1)) & (~w ^ (w >> 1))) & 0x7FFFFFFC;
return M;
}
static inline bool do_init(uint32_t* T, uint32_t* rk)
{
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 15; i++)
T[i] = T[i] ^ rotatel32(T[(i + 15 - 7) % 15] ^ T[(i + 15 - 2) % 15], 3) ^ (4 * i + j);
for (int k = 0; k < 4; k++)
{
for (int i = 0; i < 15; i++)
T[i] = rotatel32(T[i] + S[T[(i + 15 - 1) % 15] & 0x1FF], 9);
}
for (int i = 0; i < 10; i++)
rk[10 * j + i] = T[4 * i % 15];
}
for (int i = 5; i <= 35; i += 2)
{
uint32_t j = rk[i] & 3, w = rk[i] | 3;
uint32_t M = gen_mask(w);
if (M)
{
uint32_t p = rotatel32(S[265 + j], rk[i - 1] & 0x0000001F);
rk[i] = w ^ (p & M);
}
else
rk[i] = w;
}
#ifdef CPPCRYPTO_DEBUG
for(int i = 0; i < 40; i++)
printf("rk[%d] = %08x\n", i, rk[i]);
#endif
return true;
}
static inline void forward_mix(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3)
{
x1 = (x1 ^ S[(unsigned char)(x0)]) + S[256 + (unsigned char)(x0 >> 8)];
x2 += S[(unsigned char)(x0 >> 16)];
x3 ^= S[256 + (unsigned char)(x0 >> 24)];
x0 = rotater32(x0, 24);
if (i == 0 || i == 4)
x0 = x0 + x3;
else if (i == 1 || i == 5)
x0 = x0 + x1;
}
static inline void keyed_transform_a(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3, uint32_t* rk)
{
uint32_t o1, o2, o3;
E(x0, rk[2 * i + 4], rk[2 * i + 5], o1, o2, o3);
x0 = rotatel32(x0, 13);
x2 += o2;
x1 += o1;
x3 ^= o3;
}
static inline void keyed_transform_b(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3, uint32_t* rk)
{
uint32_t o1, o2, o3;
E(x0, rk[2 * i + 4], rk[2 * i + 5], o1, o2, o3);
x0 = rotatel32(x0, 13);
x2 += o2;
x3 += o1;
x1 ^= o3;
}
static inline void keyed_transform_a_decr(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3, uint32_t* rk)
{
uint32_t o1, o2, o3;
x0 = rotater32(x0, 13);
E(x0, rk[2 * i + 4], rk[2 * i + 5], o1, o2, o3);
x2 -= o2;
x1 -= o1;
x3 ^= o3;
}
static inline void keyed_transform_b_decr(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3, uint32_t* rk)
{
uint32_t o1, o2, o3;
x0 = rotater32(x0, 13);
E(x0, rk[2 * i + 4], rk[2 * i + 5], o1, o2, o3);
x2 -= o2;
x3 -= o1;
x1 ^= o3;
}
static inline void backwards_mix(int i, uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3)
{
if (i == 2 || i == 6)
x0 = x0 - x3;
else if (i == 3 || i == 7)
x0 = x0 - x1;
x1 = x1 ^ S[256 + (unsigned char)(x0)];
x2 = x2 - S[(unsigned char)(x0 >> 24)];
x3 = (x3 - S[256 + (unsigned char)(x0 >> 16)]) ^ S[(unsigned char)(x0 >> 8)];
x0 = rotatel32(x0, 24);
}
namespace detail
{
mars::~mars()
{
clear();
}
void mars::clear()
{
zero_memory(rk, sizeof(rk));
}
void mars::encrypt_block(const unsigned char* in, unsigned char* out)
{
uint32_t x0, x1, x2, x3;
x0 = *(((const uint32_t*)in) + 0) + rk[0];
x1 = *(((const uint32_t*)in) + 1) + rk[1];
x2 = *(((const uint32_t*)in) + 2) + rk[2];
x3 = *(((const uint32_t*)in) + 3) + rk[3];
forward_mix(0, x0, x1, x2, x3);
forward_mix(1, x1, x2, x3, x0);
forward_mix(2, x2, x3, x0, x1);
forward_mix(3, x3, x0, x1, x2);
forward_mix(4, x0, x1, x2, x3);
forward_mix(5, x1, x2, x3, x0);
forward_mix(6, x2, x3, x0, x1);
forward_mix(7, x3, x0, x1, x2);
#ifdef CPPCRYPTO_DEBUG
printf("fwdmix: %08x %08x %08x %08x\n", x0, x1, x2, x3);
#endif
keyed_transform_a(0, x0, x1, x2, x3, rk);
keyed_transform_a(1, x1, x2, x3, x0, rk);
keyed_transform_a(2, x2, x3, x0, x1, rk);
keyed_transform_a(3, x3, x0, x1, x2, rk);
keyed_transform_a(4, x0, x1, x2, x3, rk);
keyed_transform_a(5, x1, x2, x3, x0, rk);
keyed_transform_a(6, x2, x3, x0, x1, rk);
keyed_transform_a(7, x3, x0, x1, x2, rk);
keyed_transform_b(8, x0, x1, x2, x3, rk);
keyed_transform_b(9, x1, x2, x3, x0, rk);
keyed_transform_b(10, x2, x3, x0, x1, rk);
keyed_transform_b(11, x3, x0, x1, x2, rk);
keyed_transform_b(12, x0, x1, x2, x3, rk);
keyed_transform_b(13, x1, x2, x3, x0, rk);
keyed_transform_b(14, x2, x3, x0, x1, rk);
keyed_transform_b(15, x3, x0, x1, x2, rk);
#ifdef CPPCRYPTO_DEBUG
printf("keyed-transform: %08x %08x %08x %08x\n", x0, x1, x2, x3);
#endif
backwards_mix(0, x0, x1, x2, x3);
backwards_mix(1, x1, x2, x3, x0);
backwards_mix(2, x2, x3, x0, x1);
backwards_mix(3, x3, x0, x1, x2);
backwards_mix(4, x0, x1, x2, x3);
backwards_mix(5, x1, x2, x3, x0);
backwards_mix(6, x2, x3, x0, x1);
backwards_mix(7, x3, x0, x1, x2);
*(((uint32_t*)out) + 0) = x0 - rk[36];
*(((uint32_t*)out) + 1) = x1 - rk[37];
*(((uint32_t*)out) + 2) = x2 - rk[38];
*(((uint32_t*)out) + 3) = x3 - rk[39];
}
void mars::decrypt_block(const unsigned char* in, unsigned char* out)
{
uint32_t x0, x1, x2, x3;
x0 = *(((const uint32_t*)in) + 0) + rk[36];
x1 = *(((const uint32_t*)in) + 1) + rk[37];
x2 = *(((const uint32_t*)in) + 2) + rk[38];
x3 = *(((const uint32_t*)in) + 3) + rk[39];
forward_mix(0, x3, x2, x1, x0);
forward_mix(1, x2, x1, x0, x3);
forward_mix(2, x1, x0, x3, x2);
forward_mix(3, x0, x3, x2, x1);
forward_mix(4, x3, x2, x1, x0);
forward_mix(5, x2, x1, x0, x3);
forward_mix(6, x1, x0, x3, x2);
forward_mix(7, x0, x3, x2, x1);
#ifdef CPPCRYPTO_DEBUG
printf("fwdmix-decr: %08x %08x %08x %08x\n", x0, x1, x2, x3);
#endif
keyed_transform_a_decr(15, x3, x2, x1, x0, rk);
keyed_transform_a_decr(14, x2, x1, x0, x3, rk);
keyed_transform_a_decr(13, x1, x0, x3, x2, rk);
keyed_transform_a_decr(12, x0, x3, x2, x1, rk);
keyed_transform_a_decr(11, x3, x2, x1, x0, rk);
keyed_transform_a_decr(10, x2, x1, x0, x3, rk);
keyed_transform_a_decr(9, x1, x0, x3, x2, rk);
keyed_transform_a_decr(8, x0, x3, x2, x1, rk);
keyed_transform_b_decr(7, x3, x2, x1, x0, rk);
keyed_transform_b_decr(6, x2, x1, x0, x3, rk);
keyed_transform_b_decr(5, x1, x0, x3, x2, rk);
keyed_transform_b_decr(4, x0, x3, x2, x1, rk);
keyed_transform_b_decr(3, x3, x2, x1, x0, rk);
keyed_transform_b_decr(2, x2, x1, x0, x3, rk);
keyed_transform_b_decr(1, x1, x0, x3, x2, rk);
keyed_transform_b_decr(0, x0, x3, x2, x1, rk);
#ifdef CPPCRYPTO_DEBUG
printf("keyed-transform-decr: %08x %08x %08x %08x\n", x0, x1, x2, x3);
#endif
backwards_mix(0, x3, x2, x1, x0);
backwards_mix(1, x2, x1, x0, x3);
backwards_mix(2, x1, x0, x3, x2);
backwards_mix(3, x0, x3, x2, x1);
backwards_mix(4, x3, x2, x1, x0);
backwards_mix(5, x2, x1, x0, x3);
backwards_mix(6, x1, x0, x3, x2);
backwards_mix(7, x0, x3, x2, x1);
*(((uint32_t*)out) + 0) = x0 - rk[0];
*(((uint32_t*)out) + 1) = x1 - rk[1];
*(((uint32_t*)out) + 2) = x2 - rk[2];
*(((uint32_t*)out) + 3) = x3 - rk[3];
}
}
bool mars448::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 448 / 8);
T[14] = 448 / 32;
return do_init(T, rk);
}
bool mars192::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 192 / 8);
T[6] = 192 / 32;
memset(T + 7, 0, 8 * 32 / 8);
return do_init(T, rk);
}
bool mars256::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 256 / 8);
T[8] = 256 / 32;
memset(T + 9, 0, 6 * 32 / 8);
return do_init(T, rk);
}
bool mars320::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 320 / 8);
T[10] = 320 / 32;
memset(T + 11, 0, 4 * 32 / 8);
return do_init(T, rk);
}
bool mars128::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 128 / 8);
T[4] = 128 / 32;
memset(T + 5, 0, 10 * 32 / 8);
return do_init(T, rk);
}
bool mars160::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 160 / 8);
T[5] = 160 / 32;
memset(T + 6, 0, 9 * 32 / 8);
return do_init(T, rk);
}
bool mars224::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 224 / 8);
T[7] = 224 / 32;
memset(T + 8, 0, 7 * 32 / 8);
return do_init(T, rk);
}
bool mars288::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 288 / 8);
T[9] = 288 / 32;
memset(T + 10, 0, 5 * 32 / 8);
return do_init(T, rk);
}
bool mars352::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 352 / 8);
T[11] = 352 / 32;
memset(T + 12, 0, 3 * 32 / 8);
return do_init(T, rk);
}
bool mars384::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 384 / 8);
T[12] = 384 / 32;
memset(T + 13, 0, 2 * 32 / 8);
return do_init(T, rk);
}
bool mars416::init(const unsigned char* key, block_cipher::direction direction)
{
uint32_t T[15];
memcpy(&T, key, 416 / 8);
T[13] = 416 / 32;
memset(T + 14, 0, 1 * 32 / 8);
return do_init(T, rk);
}
}
| 37.277904 | 121 | 0.668011 | [
"vector",
"transform"
] |
fb9f3e166b140c167669d87431e4a675e1ea559f | 504 | cpp | C++ | LeetCode/subarray-sum-equals-k.cpp | Iltwats/Competitive-Programming- | 5e3af928e10d06a11dd5daab1b572184029ac3a4 | [
"MIT"
] | 1 | 2020-09-29T11:21:22.000Z | 2020-09-29T11:21:22.000Z | LeetCode/subarray-sum-equals-k.cpp | Iltwats/Competitive-Programming- | 5e3af928e10d06a11dd5daab1b572184029ac3a4 | [
"MIT"
] | null | null | null | LeetCode/subarray-sum-equals-k.cpp | Iltwats/Competitive-Programming- | 5e3af928e10d06a11dd5daab1b572184029ac3a4 | [
"MIT"
] | null | null | null | // Problem statement: https://leetcode.com/problems/subarray-sum-equals-k/
class Solution {
public:
int subarraySum(vector<int>& arr, int k) {
int n = arr.size();
int count =0;
unordered_map<int,int> map;
int sum = 0;
map.insert({0,1});
for(int i =0; i<n; i++){
sum+=arr[i];
if(map.find(sum-k)!=map.end()){
count += map[sum-k];
}
map[sum]++;
}
return count;
}
};
| 22.909091 | 74 | 0.462302 | [
"vector"
] |
fbbe4c6910218af7e2ca39e226df5241b7a0f735 | 812 | cpp | C++ | API/GameEngineContents/Coin.cpp | hooony1324/Portfolio | 5be1b439d53dcc861b4e06ec69bad53f3bd05ab5 | [
"MIT"
] | null | null | null | API/GameEngineContents/Coin.cpp | hooony1324/Portfolio | 5be1b439d53dcc861b4e06ec69bad53f3bd05ab5 | [
"MIT"
] | null | null | null | API/GameEngineContents/Coin.cpp | hooony1324/Portfolio | 5be1b439d53dcc861b4e06ec69bad53f3bd05ab5 | [
"MIT"
] | null | null | null | #include "Coin.h"
#include <GameEngine/GameEngine.h>
#include <GameEngineBase/GameEngineWindow.h>
#include <GameEngine/GameEngineImageManager.h>
#include <GameEngine/GameEngineRenderer.h>
#include <GameEngine/GameEngineCollision.h>
#include <GameEngineBase/GameEngineSound.h>
#include "GameInfo.h"
Coin::Coin()
: Col_(nullptr)
{
}
Coin::~Coin()
{
}
void Coin::Start()
{
GameEngineRenderer* Renderer_ = CreateRenderer("CoinGold.bmp");
SetScale(Renderer_->GetScale());
Col_ = CreateCollision("Coin", Renderer_->GetScale());
NextLevelOff();
}
void Coin::Update()
{
if (true == Col_->CollisionCheck("Player", CollisionType::Rect, CollisionType::Rect))
{
GameEngineSound::SoundPlayOneShot("GetCoin.mp3", 0);
GameInfo::GetPlayerInfo()->EearnedCoin_ += 100;
Death();
}
}
void Coin::Render()
{
}
| 18.883721 | 86 | 0.724138 | [
"render"
] |
fbc3a0bf7fdc56c743f7455594e17632f10f85b2 | 5,433 | hh | C++ | src/mem/cache/prefetch/tlbfree.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 2 | 2020-03-31T03:34:16.000Z | 2020-06-08T10:04:53.000Z | src/mem/cache/prefetch/tlbfree.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | null | null | null | src/mem/cache/prefetch/tlbfree.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 1 | 2020-06-25T15:46:52.000Z | 2020-06-25T15:46:52.000Z | /*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Qianlong zhang
*/
/**
* @file
* Describes a tlbfree prefetcher.
*/
#ifndef __MEM_CACHE_PREFETCH_TLBFREE_HH__
#define __MEM_CACHE_PREFETCH_TLBFREE_HH__
#include "mem/cache/prefetch/queued.hh"
#include "params/TLBFreePrefetcher.hh"
using namespace std;
class correlation_entry {
private:
uint64_t ProducerPC;
uint64_t ConsumerPC;
std::string ConsumerDisass;
uint32_t ConsumerDataSize; //TODO:this shouold be producer's datasize
int32_t ConsumerOffset;
public:
std::vector <correlation_entry> DepList;
correlation_entry()
{
ProducerPC = 0;
ConsumerPC = 0;
ConsumerDisass = "";
ConsumerDataSize = 0;
}
correlation_entry(uint64_t pr, uint64_t cn, std::string dis, uint32_t size)
{
ProducerPC = pr;
ConsumerPC = cn;
ConsumerDisass = dis;
ConsumerDataSize = size;
}
~correlation_entry()
{
}
void SetCT(uint64_t Producer, uint64_t Consumer, std::string dis, uint32_t size)
{
ProducerPC = Producer;
ConsumerPC = Consumer;
ConsumerDisass = dis;
ConsumerDataSize = size;
ConsumerOffset = 0;
}
uint64_t GetProducerPC()
{
return ProducerPC;
}
uint64_t GetConsumerPC()
{
return ConsumerPC;
}
std::string GetDisass()
{
return ConsumerDisass;
}
uint32_t GetDataSize()
{
return ConsumerDataSize;
}
int32_t GetConsumerOffset()
{
return ConsumerOffset;
}
void SetConsumerOffset(uint32_t off)
{
ConsumerOffset = off;
}
};
class potential_producer_entry{
private:
Addr ProducerPC;
Addr TargetValue;
uint32_t DataSize; //Producer data size
public:
potential_producer_entry()
{
ProducerPC = 0;
TargetValue = 0;
DataSize=0;
}
potential_producer_entry(Addr pc, Addr target_reg, uint32_t size)
{
ProducerPC = pc;
TargetValue = target_reg;
DataSize=size;
}
~potential_producer_entry()
{
}
Addr GetProducerPC() const
{
return ProducerPC;
}
uint64_t GetTargetValue()
{
return TargetValue;
}
uint32_t GetDataSize()
{
return DataSize;
}
};
class TLBFreePrefetcher : public QueuedPrefetcher
{
protected:
int degree;
int num_flattern_prefetches;
public:
TLBFreePrefetcher(const TLBFreePrefetcherParams *p);
int32_t DisassGetOffset(std::string inst);
~TLBFreePrefetcher() {}
void calculatePrefetch(const PacketPtr &pkt, std::vector<Addr> &addresses);
void PushInPrefetchList(Addr current_address, Addr prefetch_adress, std::vector<Addr> &addresses, uint32_t max_prefetches);
/* The outest vector is coreID number, inner vector index is entry number */
map<Addr, uint64_t> potential_producer_window ; //ProgramCounter, TargetValue
vector< potential_producer_entry > tlbfree_ppw; //ProgramCounter, TargetValue, DataSize
vector < correlation_entry > correlation_table; //correlation table
uint32_t potential_producer_window_size; //those param are only used to limit the size of the queue.
uint32_t correlation_table_size;
uint32_t correlation_table_dep_size;
uint32_t prefetch_request_queue_size;
uint32_t prefetch_buffer_size;
bool stop_at_page;
bool only_count_lds;
};
#endif // __MEM_CACHE_PREFETCH_TLBFREE_HH__
| 31.045714 | 127 | 0.651758 | [
"vector"
] |
fbc4c960ed7ce87036fdb2053cb429ab4ac2d393 | 8,245 | cpp | C++ | tests/pyqubotest.cpp | dmiracle/pyqubo | 21a3404c6276a0dda58efd983bdc32f8e3a27ecf | [
"Apache-2.0"
] | 2 | 2021-06-09T19:13:55.000Z | 2021-11-17T11:16:22.000Z | tests/pyqubotest.cpp | dmiracle/pyqubo | 21a3404c6276a0dda58efd983bdc32f8e3a27ecf | [
"Apache-2.0"
] | 35 | 2021-07-19T04:21:53.000Z | 2022-03-31T05:33:55.000Z | tests/pyqubotest.cpp | dmiracle/pyqubo | 21a3404c6276a0dda58efd983bdc32f8e3a27ecf | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
#include <express.h>
#include <prod.h>
#include <poly.h>
#include <model.h>
#include <coeffprod.h>
#include <placeholderpoly.h>
#include <coeff.h>
#include <expanded.h>
#include <binary_quadratic_model.hpp>
#include <vartypes.hpp>
#include <hash.hpp>
#include <unordered_map>
#include <utility>
#include <vector>
#include <cstdint>
#include <string>
#include <iostream>
#include <tuple>
using namespace std;
TEST(PROD, EQUALITY){
Prod const_prod_1 = Prod();
Prod const_prod_2 = Prod();
Prod linear_prod_1 = Prod::create(1);
Prod linear_prod_2 = Prod::create(1);
Prod linear_prod_3 = Prod::create(2);
Prod quad_prod_1 = Prod::create(1, 2);
Prod quad_prod_2 = Prod::create(1, 2);
Prod quad_prod_3 = Prod::create(2, 3);
Prod c = Prod::create(1);
EXPECT_EQ(const_prod_1, const_prod_2);
EXPECT_EQ(linear_prod_1, linear_prod_2);
EXPECT_NE(linear_prod_1, linear_prod_3);
EXPECT_NE(const_prod_1, linear_prod_1);
EXPECT_NE(const_prod_1, quad_prod_1);
EXPECT_TRUE(std::ProdEqual()(quad_prod_1, quad_prod_2));
EXPECT_NE(quad_prod_1, quad_prod_3);
EXPECT_NE(std::ProdHash()(quad_prod_1), std::ProdHash()(quad_prod_3));
}
TEST(EXPRESS, COMPILE){
BasePtr a(new Binary("a"));
BasePtr b(new Binary("b"));
BasePtr d(new Num(2.0));
BasePtr e(new Placeholder("e"));
typedef unordered_map<int, int> Map;
typedef pair<int, int> MapPair;
Map* m = new Map();
m->insert(MapPair{1, 2});
cout << to_string(m->at(1)) << endl;
Encoder encoder = Encoder();
auto a_b = a->add(b)->add(d);
auto a_b_2 = a_b->mul(a_b);
auto a_b_2_e = a_b_2->mul(e);
auto expanded = a_b_2_e->expand(encoder);
auto mp = expanded->poly->to_multiple_poly();
auto expected = new Poly();
// original terms
CoeffPtr coeff_e = make_shared<CoeffPlaceholder>("e");
expected->add_term(Prod::create(1), coeff_e->mul(5.0));
expected->add_term(Prod::create(0, 1), coeff_e->mul(2.0));
expected->add_term(Prod::create(0), coeff_e->mul(5.0));
expected->add_term(Prod(), coeff_e->mul(4.0));
EXPECT_TRUE(mp->equal_to(expected));
//compile
map<std::string, double> feed_dict{{"e", 2.0}};
auto model = a_b_2_e->compile();
auto bqm = model.to_bqm_with_index(feed_dict);
Linear<uint32_t> expected_linear{{1, 10.0}, {0, 10.0}};
Quadratic<uint32_t> expected_quadratic{
{std::make_pair(0, 1), 4.0},
};
EXPECT_EQ(bqm.get_linear(), expected_linear);
EXPECT_EQ(bqm.get_quadratic(), expected_quadratic);
EXPECT_EQ(bqm.get_offset(), 8.0);
}
TEST(EXPRESS, COMPILE2){
BasePtr a(new Binary("a"));
BasePtr b(new Binary("b"));
BasePtr c(new Binary("c"));
auto H = a->add(b);
auto H2 = b->add(c);
auto C1 = make_shared<SubH>(H, "const_1");
auto C2 = make_shared<SubH>(H2, "const_2");
auto H3 = C1->add(C2);
Encoder encoder = Encoder();
Expanded* expand = H3->expand(encoder);
cout << expand->to_string() << "\n";
auto model = H3->compile(1.0);
cout << model.to_string() << "\n";
vector<Sample<string>> samples = {
{{"a", 1}, {"b", 1}, {"c", 0}}
};
auto dec_samples = model.decode_samples(samples, Vartype::BINARY);
DecodedSolution sol = dec_samples[0];
ASSERT_EQ(sol.subh_values["const_1"], 2.0);
ASSERT_EQ(sol.subh_values["const_2"], 1.0);
ASSERT_EQ(sol.energy, 3.0);
}
TEST(EXPRESS, COMPILE3){
BasePtr a(new Binary("a"));
BasePtr b(new Binary("b"));
class MyWithPenalty: public WithPenalty{
public:
MyWithPenalty(){
this->hamiltonian = make_shared<Binary>("a");
this->penalty = make_shared<Binary>("b");
}
};
auto p = make_shared<MyWithPenalty>();
auto model = p->compile(1.0);
cout << model.to_string() << "\n";
auto qubo = model.to_qubo();
auto quadratic = std::get<0>(qubo);
Quadratic<string> expected_quadratic{
{std::make_pair("a", "a"), 1.0},
{std::make_pair("b", "b"), 1.0}
};
ASSERT_EQ(quadratic, expected_quadratic);
}
TEST(EXPRESS, MAKE_QUADRATIC){
BasePtr a(new Binary("a"));
BasePtr b(new Binary("b"));
BasePtr c(new Binary("c"));
BasePtr d(new Binary("d"));
BasePtr e(new Placeholder("e"));
auto abc = a->mul(b)->mul(c);
auto bcd = b->mul(c)->mul(d);
Encoder encoder = Encoder();
auto H = abc->add(bcd);
auto expanded = H->expand(encoder);
double strength = 2.0;
CoeffPtr strength_coeff = make_shared<CoeffNum>(strength);
Poly* quad_poly = expanded->poly->make_quadratic(encoder, strength_coeff);
cout << "quad_poly" << quad_poly->to_string() << " \n";
auto expected = new Poly();
// original terms
expected->add_term(Prod::create(3, 4), 1.0);
expected->add_term(Prod::create(0, 4), 1.0);
// contraint terms
expected->add_term(Prod::create(1, 4), -2.0 * strength);
expected->add_term(Prod::create(2, 4), -2.0 * strength);
expected->add_term(Prod::create(4), 3.0 * strength);
expected->add_term(Prod::create(1, 2), strength);
EXPECT_TRUE(quad_poly->equal_to(expected));
// check to_bqm_with_index()
auto model = H->compile();
map<std::string, double> feed_dict{{"e", 2.0}};
auto bqm = model.to_bqm_with_index(feed_dict);
Linear<uint32_t> expected_linear{{0, 0.0}, {1, 0.0}, {2, 0.0}, {3, 0.0}, {4, 6.0}};
Quadratic<uint32_t> expected_quadratic{
{std::make_pair(0, 4), 1.0}, {std::make_pair(3, 4), 1.0}, {std::make_pair(2, 4), -4.0},
{std::make_pair(1, 2), 2.0}, {std::make_pair(1, 4), -4.0},
};
EXPECT_EQ(bqm.get_linear(), expected_linear);
EXPECT_EQ(bqm.get_quadratic(), expected_quadratic);
EXPECT_EQ(bqm.get_offset(), 0.0);
// check to_bqm()
model.to_bqm(feed_dict);
}
TEST(COEFF_POLY, EQUALITY){
CoeffProd a = CoeffProd("x", 1);
CoeffProd b = CoeffProd("y", 2);
CoeffProd c = CoeffProd("x", 2);
CoeffProd d = CoeffProd("x", 3);
auto abc = a.mul(b).mul(c);
auto bd = d.mul(b);
EXPECT_EQ(abc, bd);
EXPECT_NE(a, b);
// c, d = constant
CoeffProd e = CoeffProd();
CoeffProd f = CoeffProd();
EXPECT_EQ(e, f);
auto poly1 = new PHMono(a, 2.0); // 2 x
auto poly2 = new PHMono(bd, 3.0); // 3 x^3 y^2
auto poly3 = new PHMono(abc, 3.0); // 3 x^3 y^2
auto poly4 = new PHMono(abc, 2.0); // 2 x^3 y^2
EXPECT_TRUE(poly2->equal_to(poly3));
EXPECT_FALSE(poly3->equal_to(poly4));
auto poly1_2 = (PHPoly*)PlPolyOperation::add(poly1, poly2); // poly1 = 2 x + 3 x^3 y^2
auto poly5 = new PHPoly(); // poly5 = 2 x + 3 x^3 y^2
poly5->add(a, 1.0);
poly5->add(a, 1.0);
poly5->add(abc, 3.0);
EXPECT_TRUE(poly1_2->equal_to(poly5));
poly1_2->add(e, 3.0);
auto poly6 = PlPolyOperation::mul(poly1_2, poly5);
auto poly7 = new PHPoly(); // = 4 x^2 + 12 x^4 y^2 + 9 x^6 y^4 + 6x + 9x^3y^2
poly7->add(a.mul(a), 4.0);
poly7->add(a.mul(abc), 12.0);
poly7->add(abc.mul(abc), 9.0);
poly7->add(a, 6.0);
poly7->add(abc, 9.0);
EXPECT_TRUE(poly6->equal_to(poly7));
// test evaluation
map<string, double> feed_dict;
feed_dict["x"] = 3.0;
feed_dict["y"] = 4.0;
EXPECT_EQ(a.evaluate(feed_dict), 3.0);
EXPECT_EQ(b.evaluate(feed_dict), 16.0);
EXPECT_EQ(abc.evaluate(feed_dict), 432.0);
}
TEST(COEFF, EXPAND){
CoeffPtr a = make_shared<CoeffNum>(2.0);
CoeffPtr b = make_shared<CoeffNum>(3.0);
CoeffPtr ab = a->mul(b);
CoeffPtr expect = make_shared<CoeffNum>(6.0);
EXPECT_TRUE(ab->equal_to(expect));
CoeffPtr x = make_shared<CoeffPlaceholder>("x");
CoeffPtr ax_b = x->mul(a)->add(b);
auto expand_ax_b = ax_b->expand();
auto expect_poly1 = new PHPoly();
CoeffProd x_prod = CoeffProd("x", 1);
expect_poly1->add(x_prod, 2.0);
expect_poly1->add(CoeffProd(), 3.0);
EXPECT_TRUE(expand_ax_b->equal_to(expect_poly1));
CoeffPtr ax_b_2 = ax_b->mul(ax_b);
auto expand_ax_b_2 = ax_b_2->expand();
auto expect_poly2 = new PHPoly();
expect_poly2->add(x_prod, 12.0);
expect_poly2->add(x_prod.mul(x_prod), 4.0);
expect_poly2->add(CoeffProd(), 9.0);
EXPECT_TRUE(expand_ax_b_2->equal_to(expect_poly2));
}
| 32.98 | 95 | 0.620982 | [
"vector",
"model"
] |
fbd722817d157e35daf0fceb365f0475a973bf8c | 1,253 | cpp | C++ | Common/Stylization/atom_element_structure.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/Stylization/atom_element_structure.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/Stylization/atom_element_structure.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "stdafx.h"
#include "atom.h"
#include "atom_element.h"
#include <assert.h>
StructureElement::StructureElement()
: m_pOuter(NULL)
, m_iDepth(0)
, m_eShape(ATOM::Shape::keFlow)
, m_bContinuous(true)
{
}
void StructureElement::SetOuter(StructureElement* pOuter)
{
m_pOuter = pOuter;
m_iDepth = pOuter? pOuter->Depth() + 1 : 0;
}
void StructureElement::SetShape(ATOM::Shape::Type eShape)
{
m_eShape = eShape;
}
void StructureElement::SetContinuous(bool bCont)
{
m_bContinuous = bCont;
}
| 27.23913 | 78 | 0.725459 | [
"shape"
] |
fbd9399c066743077efd18c28622f231bc4efaab | 3,041 | cpp | C++ | src/tests/dray/t_dray_volume_render.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 14 | 2019-12-17T17:40:32.000Z | 2021-12-13T20:32:32.000Z | src/tests/dray/t_dray_volume_render.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 72 | 2019-12-21T16:55:38.000Z | 2022-03-22T20:40:13.000Z | src/tests/dray/t_dray_volume_render.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 3 | 2020-02-21T18:06:57.000Z | 2021-12-03T18:39:48.000Z | // Copyright 2019 Lawrence Livermore National Security, LLC and other
// Devil Ray Developers. See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#include "test_config.h"
#include "gtest/gtest.h"
#include "t_utils.hpp"
#include <dray/rendering/renderer.hpp>
#include <dray/rendering/volume.hpp>
#include <dray/io/blueprint_reader.hpp>
#include <dray/math.hpp>
#include <fstream>
#include <stdlib.h>
TEST (dray_volume_render, dray_volume_render_simple)
{
std::string root_file = std::string (DATA_DIR) + "impeller_p2_000000.root";
std::string output_path = prepare_output_dir ();
std::string output_file =
conduit::utils::join_file_path (output_path, "impeller_vr");
remove_test_image (output_file);
dray::Collection dataset = dray::BlueprintReader::load (root_file);
dray::ColorTable color_table ("Spectral");
color_table.add_alpha (0.f, 0.00f);
color_table.add_alpha (0.1f, 0.00f);
color_table.add_alpha (0.3f, 0.19f);
color_table.add_alpha (0.4f, 0.21f);
color_table.add_alpha (1.0f, 0.9f);
// Camera
const int c_width = 512;
const int c_height = 512;
dray::Camera camera;
camera.set_width (c_width);
camera.set_height (c_height);
camera.reset_to_bounds (dataset.bounds());
std::shared_ptr<dray::Volume> volume
= std::make_shared<dray::Volume>(dataset);
volume->field("diffusion");
volume->color_map().color_table(color_table);
dray::Renderer renderer;
renderer.volume(volume);
dray::Framebuffer fb = renderer.render(camera);
fb.composite_background();
fb.save (output_file);
EXPECT_TRUE (check_test_image (output_file));
}
TEST (dray_volume_render, dray_volume_render_triple)
{
std::string root_file = std::string(DATA_DIR) + "tripple_point/field_dump.cycle_006700.root";
std::string output_path = prepare_output_dir ();
std::string output_file =
conduit::utils::join_file_path (output_path, "triple_vr");
remove_test_image (output_file);
dray::Collection dataset = dray::BlueprintReader::load (root_file);
dray::ColorTable color_table ("Spectral");
color_table.add_alpha (0.f, 0.00f);
color_table.add_alpha (0.1f, 0.20f);
color_table.add_alpha (0.4f, 0.9f);
color_table.add_alpha (0.9f, 0.61f);
color_table.add_alpha (1.0f, 0.9f);
// Camera
const int c_width = 512;
const int c_height = 512;
dray::Camera camera;
camera.set_width (c_width);
camera.set_height (c_height);
camera.azimuth (-60);
camera.reset_to_bounds (dataset.bounds());
dray::Array<dray::Ray> rays;
camera.create_rays (rays);
dray::Framebuffer framebuffer (c_width, c_height);
framebuffer.clear ();
std::shared_ptr<dray::Volume> volume
= std::make_shared<dray::Volume>(dataset);
volume->field("density");
volume->use_lighting(false);
volume->color_map().color_table(color_table);
dray::Renderer renderer;
renderer.volume(volume);
dray::Framebuffer fb = renderer.render(camera);
fb.composite_background();
fb.save (output_file);
EXPECT_TRUE (check_test_image (output_file));
}
| 28.688679 | 95 | 0.729037 | [
"render"
] |
fbe5285ea26b09c8c8176c670a881b6bef47a6a9 | 4,924 | hpp | C++ | src/include/Grid/GridIndexerRange.hpp | foxostro/PinkTopaz | cd8275a93ea34a56f640f915d4b6c769e82e9dc2 | [
"MIT"
] | 1 | 2017-10-30T22:49:06.000Z | 2017-10-30T22:49:06.000Z | src/include/Grid/GridIndexerRange.hpp | foxostro/PinkTopaz | cd8275a93ea34a56f640f915d4b6c769e82e9dc2 | [
"MIT"
] | null | null | null | src/include/Grid/GridIndexerRange.hpp | foxostro/PinkTopaz | cd8275a93ea34a56f640f915d4b6c769e82e9dc2 | [
"MIT"
] | null | null | null | //
// GridIndexerRange.hpp
// PinkTopaz
//
// Created by Andrew Fox on 11/18/17.
//
//
#ifndef GridIndexerRange_hpp
#define GridIndexerRange_hpp
#include "GridIndexer.hpp"
template<typename PointType>
class ExclusiveIterator
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = PointType;
using difference_type = PointType;
using pointer = PointType*;
using reference = PointType&;
ExclusiveIterator() = delete;
ExclusiveIterator(PointType min, PointType max, PointType pos)
: _min(min), _max(max), _pos(pos)
{}
ExclusiveIterator(const ExclusiveIterator<PointType> &a) = default;
ExclusiveIterator<PointType>& operator++()
{
++_pos.y;
if (_pos.y >= _max.y) {
_pos.y = _min.y;
++_pos.x;
if (_pos.x >= _max.x) {
_pos.x = _min.x;
++_pos.z;
if (_pos.z >= _max.z) {
// sentinel value for the end of the sequence
_pos = _max;
}
}
}
return *this;
}
ExclusiveIterator<PointType> operator++(int)
{
ExclusiveIterator<PointType> temp(*this);
operator++();
return temp;
}
PointType operator*()
{
return _pos;
}
PointType* operator->()
{
return &_pos;
}
bool operator==(const ExclusiveIterator<PointType> &a) const
{
return _min == a._min &&
_max == a._max &&
_pos == a._pos;
}
bool operator!=(const ExclusiveIterator<PointType> &a) const
{
return !(*this == a);
}
private:
PointType _min, _max, _pos;
};
template<typename PointType>
class InclusiveIterator
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = PointType;
using difference_type = PointType;
using pointer = PointType*;
using reference = PointType&;
InclusiveIterator() = delete;
InclusiveIterator(PointType min, PointType max,
PointType pos, PointType step,
bool done)
: _min(min), _max(max), _pos(pos), _step(step), _done(done)
{}
InclusiveIterator(const InclusiveIterator<PointType> &a) = default;
InclusiveIterator<PointType>& operator++()
{
if (!_done) {
_pos.y += _step.y;
if (_pos.y > _max.y) {
_pos.y = _min.y;
_pos.x += _step.x;
if (_pos.x > _max.x) {
_pos.x = _min.x;
_pos.z += _step.z;
if (_pos.z > _max.z) {
_pos.z = _min.z;
// sentinel value for the end of the sequence
_done = true;
}
}
}
}
return *this;
}
InclusiveIterator<PointType> operator++(int)
{
InclusiveIterator<PointType> temp(*this);
operator++();
return temp;
}
PointType operator*()
{
return _pos;
}
PointType* operator->()
{
return &_pos;
}
bool operator==(const InclusiveIterator<PointType> &a) const
{
return _min == a._min &&
_max == a._max &&
_pos == a._pos &&
_done == a._done;
}
bool operator!=(const InclusiveIterator<PointType> &a) const
{
return !(*this == a);
}
private:
PointType _min, _max, _pos, _step;
bool _done;
};
template<typename IteratorType>
class Range
{
public:
Range() = delete;
Range(IteratorType a, IteratorType b) : _begin(a), _end(b) {}
IteratorType begin() const
{
return _begin;
}
IteratorType end() const
{
return _end;
}
private:
IteratorType _begin, _end;
};
// Return a Range object which can iterate over a sub-region of the grid.
inline auto slice(const GridIndexer &grid, const AABB ®ion)
{
if constexpr (EnableVerboseBoundsChecking) {
if (!grid.inbounds(region)) {
throw OutOfBoundsException(fmt::format("OutOfBoundsException -- grid.boundingBox={} ; region={}",
grid.boundingBox(), region));
}
}
const auto minCellCoords = grid.cellCoordsAtPoint(region.mins());
const auto maxCellCoords = grid.cellCoordsAtPointRoundUp(region.maxs());
ExclusiveIterator<glm::ivec3> begin(minCellCoords, maxCellCoords, minCellCoords);
ExclusiveIterator<glm::ivec3> end(minCellCoords, maxCellCoords, maxCellCoords);
return Range<ExclusiveIterator<glm::ivec3>>(begin, end);
}
#endif /* GridIndexerRange_hpp */
| 23.78744 | 109 | 0.534931 | [
"object"
] |
fbe73cd91cab8824ec33085618f4a95f44d5f1dc | 1,856 | cpp | C++ | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pG.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pG.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pG.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define REP(i,x) for (int i=0; i<(x); i++)
#define REP1(i,a,b) for (int i=(a); i<=(b); i++)
#ifdef ONLINE_JUDGE
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#else
#define FILEIO(name)
#endif
template<typename A, typename B>
ostream& operator <<(ostream &s, const pair<A,B> &p) {
return s<<"("<<p.first<<","<<p.second<<")";
}
template<typename T>
ostream& operator <<(ostream &s, const vector<T> &c) {
s<<"[ ";
for (auto it : c) s << it << " ";
s<<"]";
return s;
}
// Let's Fight!
#define loop(i, a, b) for (auto (i) = (a); (i) != (b); (i) += (((a) < (b) ? 1 : -1)))
#define int long long
using pts = array<int, 3>;
int A, B, C, N;
vector<pts> ip;
bool inrange(int x, int y, int z) {
if (x < 0 or x >= A) return false;
if (y < 0 or y >= B) return false;
if (z < 0 or z >= C) return false;
return true;
}
bool test(int i, int j) {
pts p1 = ip[i], p2 = ip[j];
return (abs(p1[0]-p2[0]) + abs(p1[1]-p2[1]) + abs(p1[2]-p2[2])) == 1;
}
int outer(int a) {
pts p = ip[a];
int ret = 0;
for (int i=0; i<3; i++)
for (int j=-1; j<=1; j+=2) {
pts q = p;
q[i] += j;
if (not inrange(q[0], q[1], q[2])) ret ++;
}
return ret;
}
int32_t main() {
IOS;
cin>>A>>B>>C>>N;
ip.resize(N);
for (int i=0; i<N; i++) {
int x, y, z;
cin >> x >> y >> z;
ip[i] = pts{x, y, z};
}
int ans = (A*B+B*C+C*A)*2 + 6*N;
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
if (test(i, j)) ans --;
}
ans -= 2*outer(i);
}
cout << ans << endl;
return 0;
}
| 21.090909 | 85 | 0.529634 | [
"vector"
] |
fbeb22f538bcf2d2f43323a7602f2c9f8815bdf6 | 1,348 | cpp | C++ | test/telepath/blas/test_syrk_mat.cpp | tbepler/telepath | 636f7345b6479d5c48dbf03cb17343b14c305c7c | [
"MIT"
] | null | null | null | test/telepath/blas/test_syrk_mat.cpp | tbepler/telepath | 636f7345b6479d5c48dbf03cb17343b14c305c7c | [
"MIT"
] | null | null | null | test/telepath/blas/test_syrk_mat.cpp | tbepler/telepath | 636f7345b6479d5c48dbf03cb17343b14c305c7c | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "telepath/blas/level3/syrk_mat.h"
#include "telepath/matrix.h"
#include <vector>
using namespace telepath;
template< typename T >
class Matrix{
std::vector<T> data_;
std::size_t rows_;
std::size_t cols_;
public:
constexpr Matrix( std::size_t rows, std::size_t cols )
: data_( rows*cols ), rows_( rows ), cols_( cols ) { }
};
TEST( BLAS_SyrkMat, Eval ){
double arrayA[] = { 1, 3, 5, 2, 4, 6 };
/*
1 2
3 4
5 6
*/
matrix<double> A = {
COL_MAJOR,
NONE,
arrayA,
3,
2,
3
};
std::vector<double> arrayC( 9 );
sym_matrix<double> C = {
COL_MAJOR,
NONE,
UPPER,
&arrayC[0],
3,
3,
3
};
std::vector<double> expect = { 5, 0, 0, 11, 25, 0, 17, 39, 61 };
blas::syrk( A, C );
EXPECT_EQ( expect, arrayC );
/*
1 3 5
2 4 6
*/
matrix<double> Atrans = A;
Atrans.trans = TRANS;
std::vector<double> arrayCtrans( 4 );
sym_matrix<double> Ctrans = {
COL_MAJOR,
NONE,
UPPER,
&arrayCtrans[0],
2,
2,
2
};
std::vector<double> expect_trans = { 35, 0, 44, 56 };
blas::syrk( Atrans, Ctrans );
EXPECT_EQ( expect_trans, arrayCtrans );
}
| 18.722222 | 68 | 0.503709 | [
"vector"
] |
fbf58331619e66fc5f41987e7843631f7754c700 | 1,230 | hpp | C++ | sources/Page.hpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | sources/Page.hpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | sources/Page.hpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | #include "Direction.hpp"
#include <map>
#include <vector>
#include <string>
namespace ariel{
class Page{
private:
const static int row_length = 100; // number of max line length
const static int min_num = 0; // number of min row, col, length
const static int char_min = 32; // number of min char possible
const static int char_max = 125; // number of max char possible
std::map<int, std::vector<char>> pg; // a map of number of row and vector of line
public:
Page(){}
void write(int row, int col, ariel::Direction direction, const std::string& text);
std::string read(int row, int col, ariel::Direction direction, int length);
void erase(int row, int col, ariel::Direction direction, int length);
void show();
void write_horizontal(int row, int col, const std::string& text);
void write_vertical(int row, int col, const std::string& text);
std::string read_horizontal(int row, int col, int length);
std::string read_vertical(int row, int col, int length);
void erase_horizontal(int row, int col, int length);
void erase_vertical(int row, int col, int length);
};
} | 41 | 90 | 0.638211 | [
"vector"
] |
fbf9b3db78e4888e5ade1ca9df81e2ebf0db2d6d | 1,949 | cpp | C++ | C++/increasing-decreasing-string.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/increasing-decreasing-string.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/increasing-decreasing-string.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
string sortString(string s) {
string result;
auto count = counter(s);
while(result.length() != s.length()) {
for (int c = 0; c < count.size(); ++c) {
if (count[c]) {
result += ('a' + c);
--count[c];
}
}
for (int c = count.size() - 1; c >= 0; --c) {
if (count[c]) {
result += ('a' + c);
--count[c];
}
}
}
return result;
}
private:
vector<int> counter(const string& word) {
vector<int> count(26);
for (const auto& c : word) {
++count[c - 'a'];
}
return count;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
string sortString(string s) {
string result;
for (auto [count, desc] = tuple{counter(s), false}; !count.empty(); desc = !desc) {
if (!desc) {
for (auto it = begin(count); it != end(count);) {
result.push_back(it->first);
if (!--it->second) {
it = count.erase(it);
} else {
++it;
}
}
} else {
for (auto rit = rbegin(count); rit != rend(count);) {
result.push_back(rit->first);
if (!--rit->second) {
rit = reverse_iterator(count.erase(next(rit).base()));
} else {
++rit;
}
}
}
}
return result;
}
private:
map<int, int> counter(const string& word) {
map<int, int> count;
for (const auto& c : word) {
++count[c];
}
return count;
}
};
| 25.644737 | 91 | 0.366855 | [
"vector"
] |
fbfc6c42cc71036e2638192ea25444e47cfcb778 | 10,827 | cpp | C++ | inetsrv/iis/svcs/staxcore/seo/mimebag.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/svcs/staxcore/seo/mimebag.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/svcs/staxcore/seo/mimebag.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
mimebag.cpp
Abstract:
This module contains the implementation for the Server
Extension Object Registry Property Bag.
Author:
Andy Jacobs (andyj@microsoft.com)
Revision History:
andyj 01/28/97 created
andyj 02/12/97 Converted PropertyBag's to Dictonary's
--*/
// MIMEBAG.cpp : Implementation of CSEOMimeDictionary
#include "stdafx.h"
#include "seodefs.h"
#include "mimeole.h"
#include "MIMEBAG.h"
inline void AnsiToBstr(BSTR &bstr, LPCSTR lpcstr) {
if(bstr) SysFreeString(bstr);
bstr = A2BSTR(lpcstr);
/*
int iSize = lstrlen(lpcstr); // Number of characters to copy
bstr = SysAllocStringLen(NULL, iSize);
MultiByteToWideChar(CP_ACP, 0, lpcstr, -1, bstr, iSize);
*/
}
/////////////////////////////////////////////////////////////////////////////
// CSEOMimeDictionary
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::get_Item(
/* [in] */ VARIANT __RPC_FAR *pvarName,
/* [retval][out] */ VARIANT __RPC_FAR *pvarResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::get_Item"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::put_Item(
/* [in] */ VARIANT __RPC_FAR *pvarName,
/* [in] */ VARIANT __RPC_FAR *pvarValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::put_Item"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::get__NewEnum(
/* [retval][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppunkResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::get__NewEnum"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetVariantA(
/* [in] */ LPCSTR pszName,
/* [retval][out] */ VARIANT __RPC_FAR *pvarResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetVariantA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetVariantW(
/* [in] */ LPCWSTR pszName,
/* [retval][out] */ VARIANT __RPC_FAR *pvarResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetVariantW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetVariantA(
/* [in] */ LPCSTR pszName,
/* [in] */ VARIANT __RPC_FAR *pvarValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetVariantA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetVariantW(
/* [in] */ LPCWSTR pszName,
/* [in] */ VARIANT __RPC_FAR *pvarValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetVariantW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetStringA(
/* [in] */ LPCSTR pszName,
/* [out][in] */ DWORD __RPC_FAR *pchCount,
/* [retval][size_is][out] */ LPSTR pszResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetStringA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetStringW(
/* [in] */ LPCWSTR pszName,
/* [out][in] */ DWORD __RPC_FAR *pchCount,
/* [retval][size_is][out] */ LPWSTR pszResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetStringW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetStringA(
/* [in] */ LPCSTR pszName,
/* [in] */ DWORD chCount,
/* [size_is][in] */ LPCSTR pszValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetStringA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetStringW(
/* [in] */ LPCWSTR pszName,
/* [in] */ DWORD chCount,
/* [size_is][in] */ LPCWSTR pszValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetStringW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetDWordA(
/* [in] */ LPCSTR pszName,
/* [retval][out] */ DWORD __RPC_FAR *pdwResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetDWordA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetDWordW(
/* [in] */ LPCWSTR pszName,
/* [retval][out] */ DWORD __RPC_FAR *pdwResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetDWordW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetDWordA(
/* [in] */ LPCSTR pszName,
/* [in] */ DWORD dwValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetDWordA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetDWordW(
/* [in] */ LPCWSTR pszName,
/* [in] */ DWORD dwValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetDWordW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetInterfaceA(
/* [in] */ LPCSTR pszName,
/* [in] */ REFIID iidDesired,
/* [retval][iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppunkResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetInterfaceA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::GetInterfaceW(
/* [in] */ LPCWSTR pszName,
/* [in] */ REFIID iidDesired,
/* [retval][iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppunkResult)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::GetInterfaceW"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetInterfaceA(
/* [in] */ LPCSTR pszName,
/* [in] */ IUnknown __RPC_FAR *punkValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetInterfaceA"));
}
HRESULT STDMETHODCALLTYPE CSEOMimeDictionary::SetInterfaceW(
/* [in] */ LPCWSTR pszName,
/* [in] */ IUnknown __RPC_FAR *punkValue)
{
ATLTRACENOTIMPL(_T("CSEOMimeDictionary::SetInterfaceW"));
}
/*
STDMETHODIMP CSEOMimePropertyBagEx::Read(LPCOLESTR pszPropName, VARIANT *pVar, IErrorLog *pErrorLog) {
if (!pszPropName || !pVar) return (E_POINTER);
LONG dwIdx;
VARTYPE vtVar = pVar->vt; // Requested type
VariantClear(pVar);
ReadHeader();
/*
if(vtVar == VT_UNKNOWN) || (vtVar == VT_EMPTY)) {
// Look for a matching key
for (dwIdx=0;dwIdx<m_dwKeyCnt;dwIdx++) {
if (_wcsicmp(pszPropName, m_paKey[dwIdx].strName) == 0) {
if(!m_paKey[dwIdx].pKey) { // If object doesn't already exists
HRESULT hrRes = CComObject<CSEORegPropertyBagEx>::CreateInstance(&(m_paKey[dwIdx].pKey));
if (!SUCCEEDED(hrRes)) return (hrRes);
BSTR strTemp = SysAllocStringLen(m_strSubKey, wcslen(m_strSubKey) +
wcslen(m_paKey[dwIdx].strName) + wcslen(PATH_SEP));
if (!strTemp) {
RELEASE_AND_SHREAD_POINTER(m_paKey[dwIdx].pKey);
return (E_OUTOFMEMORY);
}
if(wcslen(strTemp) > 0) wcscat(strTemp, PATH_SEP); // Add separator if needed
wcscat(strTemp,m_paKey[dwIdx].strName);
hrRes = m_paKey[dwIdx].pKey->Load(m_strMachine,(SEO_HKEY) (DWORD) m_hkBaseKey,strTemp,pErrorLog);
SysFreeString(strTemp);
if (!SUCCEEDED(hrRes)) {
RELEASE_AND_SHREAD_POINTER(m_paKey[dwIdx].pKey);
return (hrRes);
}
}
pVar->vt = VT_UNKNOWN;
pVar->punkVal = m_paKey[dwIdx].pKey;
pVar->punkVal->AddRef(); // Increment for the copy we are about to return
return (S_OK);
}
}
if (vtVar != VT_EMPTY) return (E_INVALIDARG); // Didn't find right type to return
}
* /
// Look for a matching value
for (dwIdx = 0; dwIdx < m_dwValueCnt; ++dwIdx) {
if (_wcsicmp(pszPropName, m_paValue[dwIdx].strName) == 0) {
HRESULT hrRes;
VARIANT varResult;
VariantInit(&varResult);
varResult.vt = VT_BSTR; // | VT_BYREF;
varResult.bstrVal = SysAllocString(m_paValue[dwIdx].strData);
if (vtVar == VT_EMPTY) vtVar = varResult.vt;
hrRes = VariantChangeType(pVar, &varResult, 0, vtVar);
VariantClear(&varResult); // Not needed anymore
if (FAILED(hrRes)) {
VariantClear(pVar);
if (pErrorLog) {
// tbd
}
return (hrRes);
}
return (S_OK);
}
}
return (E_INVALIDARG);
}
STDMETHODIMP CSEOMimePropertyBagEx::get_Count(LONG *plResult) {
if(!plResult) return (E_POINTER);
ReadHeader();
*plResult = m_dwValueCnt;
return (S_OK);
}
STDMETHODIMP CSEOMimePropertyBagEx::get_Name(LONG lIndex, BSTR *pstrResult) {
if(!pstrResult) return (E_POINTER);
ReadHeader();
if(lIndex >= m_dwValueCnt) return (E_POINTER);
SysFreeString(*pstrResult); // Free any existing string
*pstrResult = SysAllocString(m_paValue[lIndex].strName);
return (S_OK);
}
STDMETHODIMP CSEOMimePropertyBagEx::get_Type(LONG lIndex, VARTYPE *pvtResult) {
if(!pvtResult) return (E_POINTER);
*pvtResult = VT_BSTR;
return (S_OK);
}
STDMETHODIMP CSEOMimePropertyBagEx::Lock() {
m_csCritSec.Lock();
return (S_OK);
}
STDMETHODIMP CSEOMimePropertyBagEx::Unlock() {
m_csCritSec.Unlock();
return (S_OK);
}
*/
HRESULT CSEOMimeDictionary::FinalConstruct() {
m_dwValueCnt = 0;
m_paValue = NULL;
m_csCritSec.Init();
m_pMessageTree = NULL; // Our copy of aggregated object
m_pMalloc = NULL;
HRESULT hr = E_FAIL;
m_pMessageTree = NULL;
// tbd: Combine these using CoCreateInstanceEx()
hr = CoCreateInstance(CLSID_MIMEOLE, NULL, CLSCTX_ALL,
IID_IMimeOleMalloc, (LPVOID *) &m_pMalloc);
IUnknown *pUnkOuter = this;
hr = CoCreateInstance(CLSID_MIMEOLE, pUnkOuter, CLSCTX_INPROC_SERVER, IID_IMimeMessageTree, (LPVOID *)&m_pMessageTree);
// hr = CoCreateInstance(CLSID_MIMEOLE, this, CLSCTX_ALL,
// IID_IMimeMessageTree, (LPVOID *) &m_pMessageTree);
if (SUCCEEDED(hr)) {
hr = CoCreateFreeThreadedMarshaler(GetControllingUnknown(),&m_pUnkMarshaler.p);
}
return (hr);
}
void CSEOMimeDictionary::FinalRelease() {
// Flush(NULL);
for (LONG dwIdx = 0; dwIdx < m_dwValueCnt; ++dwIdx) {
MySysFreeStringInPlace(&m_paValue[dwIdx].strName);
MySysFreeStringInPlace(&m_paValue[dwIdx].strData);
}
m_dwValueCnt = 0;
MyFreeInPlace(&m_paValue);
RELEASE_AND_SHREAD_POINTER(m_pMessageTree);
RELEASE_AND_SHREAD_POINTER(m_pMalloc);
m_csCritSec.Term();
m_pUnkMarshaler.Release();
}
void CSEOMimeDictionary::ReadHeader() {
if(m_paValue) return; // Already read it
IMimeHeader *pHeader = NULL;
IMimeEnumHeaderLines *pEnum = NULL;
HBODY hBody = 0;
HEADERLINE rgLine[1];
ULONG cLines = 0;
LONG iEntries = 0; // Number of Header lines
HRESULT hr = E_FAIL;
// tbd: Error checking
hr = m_pMessageTree->GetBody(IBL_ROOT, NULL, &hBody);
hr = m_pMessageTree->BindToObject(hBody, IID_IMimeHeader, (LPVOID *) &pHeader);
hr = pHeader->EnumHeaderLines(NULL, &pEnum);
while(SUCCEEDED(hr = pEnum->Next(1, rgLine, &cLines))) {
if(hr == S_FALSE) break;
++iEntries;
// Use rgLine->pszHeader and rgLine->pszLine
m_pMalloc->FreeHeaderLineArray(cLines, rgLine, FALSE);
}
RELEASE_AND_SHREAD_POINTER(pEnum);
m_dwValueCnt = iEntries;
m_paValue = (ValueEntry *) MyMalloc(sizeof(ValueEntry) * m_dwValueCnt);
//if (!m_paValue) return E_FAIL; // Unable to allocate memory
hr = pHeader->EnumHeaderLines(NULL, &pEnum);
iEntries = 0; // Start again
while(SUCCEEDED(hr = pEnum->Next(1, rgLine, &cLines))) {
if(hr == S_FALSE) break;
AnsiToBstr(m_paValue[iEntries].strName, rgLine->pszHeader);
AnsiToBstr(m_paValue[iEntries].strData, rgLine->pszLine);
++iEntries;
m_pMalloc->FreeHeaderLineArray(cLines, rgLine, FALSE);
}
RELEASE_AND_SHREAD_POINTER(pEnum);
RELEASE_AND_SHREAD_POINTER(pHeader);
}
| 28.417323 | 121 | 0.67812 | [
"object"
] |
fbfd66b0595e50b08a5195b1b8cca23351149e09 | 556 | cpp | C++ | Source/Rendering/Model/Model.cpp | elyshaffir/SandboxEngineSandboxEngine | 48f4ee9e77a0049378aa751d53467cb81b6d9d10 | [
"MIT"
] | null | null | null | Source/Rendering/Model/Model.cpp | elyshaffir/SandboxEngineSandboxEngine | 48f4ee9e77a0049378aa751d53467cb81b6d9d10 | [
"MIT"
] | null | null | null | Source/Rendering/Model/Model.cpp | elyshaffir/SandboxEngineSandboxEngine | 48f4ee9e77a0049378aa751d53467cb81b6d9d10 | [
"MIT"
] | null | null | null | #include <Rendering/Model/Model.h>
sandbox::Model::Model(std::vector<Vertex> & vertices) : vertexBuffer(vertices), vertexCount(vertices.size())
{
}
void sandbox::Model::Destroy(VkDevice device)
{
vertexBuffer.Destroy(device);
}
void sandbox::Model::Bind(VkCommandBuffer commandBuffer) const
{
VkBuffer buffers[] = {vertexBuffer.buffer};
VkDeviceSize offsets[] = {0};
vkCmdBindVertexBuffers(commandBuffer, 0, 1, buffers, offsets);
}
void sandbox::Model::Draw(VkCommandBuffer commandBuffer) const
{
vkCmdDraw(commandBuffer, vertexCount, 1, 0, 0);
}
| 24.173913 | 108 | 0.751799 | [
"vector",
"model"
] |
220265970cd9127cfcaa42b4b75da97e55e73b9b | 4,325 | cc | C++ | online_belief_propagation/sbm_graph.cc | xxdreck/google-research | dac724bc2b9362d65c26747a8754504fe4c615f8 | [
"Apache-2.0"
] | 2 | 2022-01-21T18:15:34.000Z | 2022-01-25T15:21:34.000Z | online_belief_propagation/sbm_graph.cc | xxdreck/google-research | dac724bc2b9362d65c26747a8754504fe4c615f8 | [
"Apache-2.0"
] | 110 | 2021-10-01T18:22:38.000Z | 2021-12-27T22:08:31.000Z | online_belief_propagation/sbm_graph.cc | admariner/google-research | 7cee4b22b925581d912e8d993625c180da2a5a4f | [
"Apache-2.0"
] | 1 | 2021-12-01T23:20:45.000Z | 2021-12-01T23:20:45.000Z | // Copyright 2021 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sbm_graph.h"
#include <assert.h>
#include <random>
#include <set>
#include <tuple>
SBMGraph::SBMGraph(int64_t n, int k, double a, double b, int seed) {
// Check that input parameters satisfy all requirements.
assert(n >= 0 && k >= 0 && a >= 0 && b >= 0);
assert(a >= b);
std::default_random_engine generator(seed);
std::uniform_int_distribution<int> random_label(0, k - 1);
std::uniform_int_distribution<int> random_vertex(0, n - 1);
// Insert vertices and assign random community labels.
for (int i = 0; i < n; i++) {
InsertVertex();
ground_truth_communities_.push_back(random_label(generator));
}
// The goal is to sample each of the n*(n-1)/2 potential edges independently.
// If the edge is within a community we call it an 'inside edge' and sample it
// with probability a/n. If the edge is between communities we call it a
// 'cross edge' and sample it with probability b/n.
//
// For efficiency, instead of sampling each edge individually, we sample the
// total number of edges from the appropriate binomial distribution, then
// sample that many edge uniformly at random WITHOUT REPETITION.
//
// Since we don't know ahead of time which edges are inside edges and which
// are cross edges we perform both sampling on the entire collection n*(n-1)/2
// potential edges and narrow it down later. This results in the sample
// distribution as sampling each edge independently with the appropriate
// probability.
//
// To enforce that the edge sampling is done without repetition, we keep the
// candidate edges in a std::set and continue sampling until we reach the
// desired number of candidates.
//
// Sample each potential edge independently with probability a/n.
std::binomial_distribution<int64_t> random_inside_edge_number(
(n * (n - 1)) / 2, a / n);
int64_t inside_edge_number = random_inside_edge_number(generator);
std::set<std::pair<int, int>> inside_edge_candidates;
while (inside_edge_candidates.size() < inside_edge_number) {
// Sample a random potential edge.
int u = random_vertex(generator);
int v = random_vertex(generator);
if (u < v) {
inside_edge_candidates.emplace(u, v);
}
if (v < u) {
inside_edge_candidates.emplace(v, u);
}
// If u = v try again.
}
// Narrow down the candidates to those which are inside edges.
for (const std::pair<int, int>& candidate : inside_edge_candidates) {
int u = candidate.first;
int v = candidate.second;
if (ground_truth_communities_[u] == ground_truth_communities_[v]) {
InsertEdge(u, v);
}
}
// Sample each potential edge independently with probability b/n.
std::binomial_distribution<int64_t> random_cross_edge_number(n * (n - 1) / 2,
b / n);
int64_t cross_edge_number = random_cross_edge_number(generator);
std::set<std::pair<int, int>> cross_edge_candidates;
while (cross_edge_candidates.size() < cross_edge_number) {
// Sample a random potential edge.
int u = random_vertex(generator);
int v = random_vertex(generator);
if (u < v) {
cross_edge_candidates.emplace(u, v);
}
if (v < u) {
cross_edge_candidates.emplace(v, u);
}
// If u = v try again.
}
// Narrow down the candidates to those which are inside edges.
for (const std::pair<int, int>& candidate : cross_edge_candidates) {
int u = candidate.first;
int v = candidate.second;
if (ground_truth_communities_[u] != ground_truth_communities_[v]) {
InsertEdge(u, v);
}
}
}
const std::vector<int>& SBMGraph::GetGroundTruthCommunities() const {
return ground_truth_communities_;
}
| 38.274336 | 80 | 0.690405 | [
"vector"
] |
22065d857f0d42bc13d5bd0230b2da091a6b5017 | 3,166 | cpp | C++ | qrgui/dialogs/subprogram/shapePropertyWidget.cpp | RexTremendaeMajestatis/QREAL | 94786d40e84c18a4407069570588f7d2c4c63aea | [
"Apache-2.0"
] | 39 | 2015-01-26T16:18:43.000Z | 2021-12-20T23:36:41.000Z | qrgui/dialogs/subprogram/shapePropertyWidget.cpp | RexTremendaeMajestatis/QREAL | 94786d40e84c18a4407069570588f7d2c4c63aea | [
"Apache-2.0"
] | 1,248 | 2019-02-21T19:32:09.000Z | 2022-03-29T16:50:04.000Z | qrgui/dialogs/subprogram/shapePropertyWidget.cpp | RexTremendaeMajestatis/QREAL | 94786d40e84c18a4407069570588f7d2c4c63aea | [
"Apache-2.0"
] | 58 | 2015-03-03T12:57:28.000Z | 2020-05-09T15:54:42.000Z | /* Copyright 2015-2016 Kogutich Denis
*
* 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 "shapePropertyWidget.h"
#include <QtGui/QPainter>
#include <qrkernel/settingsManager.h>
using namespace qReal;
using namespace gui;
const int minWidth = 355;
ShapePropertyWidget::ShapePropertyWidget(QWidget *parent)
: QWidget(parent)
, mSelectedShapeIndex(-1)
{
QPalette pal(palette());
pal.setColor(QPalette::Background, Qt::white);
setAutoFillBackground(true);
setPalette(pal);
}
void ShapePropertyWidget::initShapes(const QStringList &shapes, const QString ¤tShape, bool background)
{
qreal x = 0.0;
int index = 0;
bool findedCurrentShape = false;
if (!background) {
/// @todo: Robots images should not be used here.
const QString defaultShape = "images/subprogramRobotsBlock.png";
addShape(index, x, defaultShape, currentShape, findedCurrentShape);
}
for (const QString &shape : shapes) {
addShape(index, x, shape, currentShape, findedCurrentShape);
}
const int width = (index * 75 < minWidth) ? minWidth : index * 75;
setFixedSize(width, 75);
}
QString ShapePropertyWidget::selectedShape() const
{
return mShapes.isEmpty() || mSelectedShapeIndex == -1 ? QString() : mShapes.at(mSelectedShapeIndex)->shape();
}
void ShapePropertyWidget::selectShape(int index)
{
if (!mShapes.isEmpty() && mShapes.size() > index) {
mShapes.at(index)->addSelection();
mSelectedShapeIndex = index;
}
}
void ShapePropertyWidget::paintEvent(QPaintEvent *)
{
mWidthOfGrid = SettingsManager::value("GridWidth").toDouble() / 100;
QPainter painter(this);
painter.setPen(QPen(Qt::black, mWidthOfGrid));
const int indexGrid = SettingsManager::value("IndexGrid").toInt();
mGridDrawer.drawGrid(&painter, rect(), indexGrid);
}
void ShapePropertyWidget::shapeClicked()
{
const int newSelectedIndex = dynamic_cast<ShapeWidget *>(sender())->index();
if (mSelectedShapeIndex != newSelectedIndex) {
if (mSelectedShapeIndex != -1) {
mShapes.at(mSelectedShapeIndex)->removeSelection();
}
mSelectedShapeIndex = newSelectedIndex;
}
}
void ShapePropertyWidget::addShape(int &index, qreal &x, const QString &shape, const QString ¤tShape
, bool &foundCurrentShape)
{
ShapeWidget *shapeWidget = new ShapeWidget(index, this);
shapeWidget->setGeometry(static_cast<int>(x), 0, 0, 0);
mShapes << shapeWidget;
shapeWidget->setShape(shape);
if (!foundCurrentShape && shape == currentShape) {
shapeWidget->addSelection();
mSelectedShapeIndex = index;
foundCurrentShape = true;
}
shapeWidget->show();
connect(shapeWidget, &ShapeWidget::clicked, this, &ShapePropertyWidget::shapeClicked);
++index;
x += 75.0;
}
| 28.781818 | 110 | 0.738471 | [
"shape"
] |
220af0781e2b192465f89c0152c81382d72f378a | 1,323 | cpp | C++ | ctest/tests/geometry/FileOBJ.cpp | mgradysaunders/Precept | 0677c70ac4ed9e0a8c5aad7b049daad22998de9e | [
"BSD-2-Clause"
] | null | null | null | ctest/tests/geometry/FileOBJ.cpp | mgradysaunders/Precept | 0677c70ac4ed9e0a8c5aad7b049daad22998de9e | [
"BSD-2-Clause"
] | null | null | null | ctest/tests/geometry/FileOBJ.cpp | mgradysaunders/Precept | 0677c70ac4ed9e0a8c5aad7b049daad22998de9e | [
"BSD-2-Clause"
] | null | null | null | #include "../../testing.h"
#include <pre/geometry/FileOBJ>
using namespace pre;
static const char* CubeSrc = R"(
# Blender v2.82 (sub 7) OBJ File: ''
# www.blender.org
mtllib Cube.mtl
o Cube
v 1 1 -1
v 1 -1 -1
v 1 1 1
v 1 -1 1
v -1 1 -1
v -1 -1 -1
v -1 1 1
v -1 -1 1
vn 0 1 0
vn 0 0 1
vn -1 0 0
vn 0 -1 0
vn 1 0 0
vn 0 0 -1
vt 0.625 0.500
vt 0.875 0.500
vt 0.875 0.750
vt 0.625 0.750
vt 0.375 0.750
vt 0.625 1.000
vt 0.375 1.000
vt 0.375 0.000
vt 0.625 0.000
vt 0.625 0.250
vt 0.375 0.250
vt 0.125 0.500
vt 0.375 0.500
vt 0.125 0.750
usemtl Material
s off
f 1/1/1 5/2/1 7/3/1 3/4/1
f 4/5/2 3/4/2 7/6/2 8/7/2
f 8/8/3 7/9/3 5/10/3 6/11/3
f 6/12/4 2/13/4 4/5/4 8/14/4
f 2/13/5 1/1/5 3/4/5 4/5/5
f 6/11/6 5/10/6 1/1/6 2/13/6
)";
TEST_CASE("geometry:FileOBJ") {
std::stringstream cubess;
std::stringstream cubess2;
cubess << CubeSrc;
FileOBJ cube;
CHECK_NOTHROW(cube.read(cubess));
CHECK_NOTHROW(cube.write(cubess2));
CHECK_NOTHROW(cube.read(cubess2));
CHECK(cube.positions.v.size() == 8);
CHECK(cube.normals.v.size() == 6);
CHECK(cube.uvs.v.size() == 14);
CHECK(cube.face_sizes.size() == 6);
CHECK(cube.face_materials.size() == 6);
CHECK(cube.material_names.size() == 2);
CHECK(cube.material_names[0] == "default");
CHECK(cube.material_names[1] == "Material");
}
| 19.746269 | 48 | 0.622071 | [
"geometry"
] |
81fcf2e8c739163e15867f70e72b2b680f27f167 | 3,819 | cpp | C++ | src/convert/osm2poi.cpp | malasiot/maplite | 1edeec673110cdd5fa904ff2ff88289b6c3ec324 | [
"MIT"
] | 12 | 2017-05-11T21:44:57.000Z | 2021-12-30T08:35:56.000Z | src/convert/osm2poi.cpp | malasiot/mftools | 1edeec673110cdd5fa904ff2ff88289b6c3ec324 | [
"MIT"
] | 8 | 2016-10-27T10:10:05.000Z | 2019-12-07T21:27:02.000Z | src/convert/osm2poi.cpp | malasiot/mftools | 1edeec673110cdd5fa904ff2ff88289b6c3ec324 | [
"MIT"
] | 5 | 2017-10-17T08:18:58.000Z | 2021-11-12T11:44:23.000Z | #include <fstream>
#include "osm_processor.hpp"
#include "mapsforge_poi_writer.hpp"
#include "poi_categories.hpp"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
using namespace std ;
namespace po = boost::program_options ;
int main(int argc, char *argv[])
{
string filter_config_file, out_poi_file, poi_mapping_file ;
bool has_bbox = false ;
vector<string> osm_files ;
POIWriter writer ;
POIWriteOptions woptions ;
po::options_description desc;
desc.add_options()
("help", "produce help")
("filter", po::value<string>(&filter_config_file)->required()->value_name("path"), "osm tag filter configuration file")
("poi-mapping", po::value<string>(&poi_mapping_file)->required()->value_name("path"), "poi mapping file")
("out", po::value<string>(&out_poi_file)->required()->value_name("path"), "output POI file path")
("bbox", po::value<string>()->notifier(
[&writer, &has_bbox](const string &value) {
BBox box ;
if ( box.fromString(value)) {
writer.setBoundingBox(box);
has_bbox = true ;
}
else throw po::validation_error(po::validation_error::invalid_option_value) ;
})->value_name("<minx miny maxx maxy>"), "map bounding box")
("preferred-languages", po::value<string>()->notifier( [&writer](const string &value) { writer.setPreferredLanguages(value); }), "map prefered languages in ISO")
("comment", po::value<string>()->notifier( [&writer](const string &value) { writer.setComment(value); }), "a comment to write to the file")
("debug", po::value<bool>(&woptions.debug_)->implicit_value(true), "enable debug information in the map file")
;
po::options_description hidden;
hidden.add_options()
("in", po::value<std::vector<std::string>>(&osm_files), "Input files")
;
po::options_description all_options;
all_options.add(desc);
all_options.add(hidden);
po::positional_options_description pd;
pd.add("in", -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(all_options).positional(pd).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "Usage: osm2poi [options] <files>*\n";
cout << desc << endl ;
return 1;
}
}
catch( po::error &e )
{
cerr << e.what() << endl ;
cout << "Usage: osm2poi [options] <files>*\n";
cerr << desc << endl ;
return 0;
}
writer.setCreator("osm2poi") ;
writer.setDate(time(nullptr)) ;
POICategoryContainer categories ;
categories.loadFromXML(poi_mapping_file) ;
OSMProcessor proc ;
TagFilter filter ;
if ( !filter.parse(filter_config_file) ) {
cerr << "Error parsing OSM tag filter configuration file: " << filter_config_file << endl ;
return 0 ;
}
for( const string &fp: osm_files ) {
if ( !proc.processOsmFile(fp, filter) ) {
cerr << "Error while populating temporary spatialite database" << endl ;
return 0 ;
}
}
SQLite::Connection &db = proc.db() ;
if ( !has_bbox )
writer.setBoundingBox(proc.getBoundingBoxFromGeometries());
BBox box = writer.getBoundingBox();
writer.create(out_poi_file) ;
//SQLite::Database db("/tmp/2ed94.sqlite") ;
// SQLite::Database db("/tmp/0a907.sqlite") ;
// SQLite::Database db("/tmp/a157a.sqlite") ;
cout << "encoding file" << endl ;
writer.write(proc, categories, woptions) ;
return 1 ;
}
| 32.092437 | 173 | 0.600419 | [
"vector"
] |
81fd0bc1e048bd5d9e12676a00636a9738f76a37 | 16,991 | cpp | C++ | pushquickview.cpp | net147/Push2Qml | a89b9b573312164ed670ac5e1fc0dd4ee3c5de58 | [
"MIT"
] | 21 | 2015-12-16T22:44:01.000Z | 2022-01-03T03:10:39.000Z | pushquickview.cpp | net147/Push2Qml | a89b9b573312164ed670ac5e1fc0dd4ee3c5de58 | [
"MIT"
] | 1 | 2018-12-10T23:14:26.000Z | 2018-12-11T12:16:59.000Z | pushquickview.cpp | net147/Push2Qml | a89b9b573312164ed670ac5e1fc0dd4ee3c5de58 | [
"MIT"
] | 2 | 2016-12-01T10:24:40.000Z | 2018-11-11T20:12:27.000Z | #include "pushquickview.h"
#include <QQmlEngine>
#include "pushdisplay.h"
#include "RtMidi.h"
#if defined(Q_OS_MAC)
#define PUSH1_INPUT_PORT "Ableton Push User Port"
#define PUSH1_OUTPUT_PORT "Ableton Push User Port"
#define PUSH2_INPUT_PORT "Ableton Push 2 Live Port"
#define PUSH2_OUTPUT_PORT "Ableton Push 2 Live Port"
#elif defined(Q_OS_WIN)
#define PUSH1_INPUT_PORT "MIDIIN2 (Ableton Push)"
#define PUSH1_OUTPUT_PORT "MIDIOUT2 (Ableton Push)"
#define PUSH2_INPUT_PORT "Ableton Push 2"
#define PUSH2_OUTPUT_PORT "Ableton Push 2"
#else
#define PUSH1_INPUT_PORT "Ableton Push MIDI 2"
#define PUSH1_OUTPUT_PORT "Ableton Push MIDI 2"
#define PUSH2_INPUT_PORT "Ableton Push 2 MIDI 1"
#define PUSH2_OUTPUT_PORT "Ableton Push 2 MIDI 1"
#endif
class PushDisplayEvents : public QObject
{
Q_OBJECT
public:
PushDisplayEvents() { }
~PushDisplayEvents() { }
signals:
void clearLine(int index);
void writeLine(int index, const QString &text);
};
static PushDisplayEvents *pushDisplayEvents = 0;
static QObject *pushDisplayEventsProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
if (!pushDisplayEvents)
pushDisplayEvents = new PushDisplayEvents;
return pushDisplayEvents;
}
class PushQuickViewPrivate : public QObject
{
Q_OBJECT
Q_DECLARE_PUBLIC(PushQuickView)
public:
PushQuickViewPrivate(PushQuickView *q_ptr);
~PushQuickViewPrivate();
static void push1MidiOutCallback(double timeStamp, std::vector<uchar> *message, void *userData);
static void push2MidiInCallback(double timeStamp, std::vector<uchar> *message, void *userData);
public slots:
void sceneRendered();
public:
PushDisplay display;
QScopedPointer<RtMidiIn> push1MidiOut;
QScopedPointer<RtMidiOut> push2MidiOut;
QScopedPointer<RtMidiIn> push2MidiIn;
QScopedPointer<RtMidiOut> push1MidiIn;
PushQuickView * const q_ptr;
};
PushQuickViewPrivate::PushQuickViewPrivate(PushQuickView *q_ptr) :
q_ptr(q_ptr)
{
qmlRegisterSingletonType<PushDisplayEvents>("Push2Qml.Emulation", 1, 0, "PushDisplayEvents",
&pushDisplayEventsProvider);
connect(q_ptr, SIGNAL(sceneRendered()), SLOT(sceneRendered()));
push1MidiOut.reset(new RtMidiIn);
push1MidiOut->ignoreTypes(false, false, false);
push1MidiOut->setCallback(&push1MidiOutCallback, this);
for (int i = 0, portCount = push1MidiOut->getPortCount(); i < portCount; ++i) {
if (QString::fromStdString(push1MidiOut->getPortName(i)) == PUSH1_OUTPUT_PORT) {
push1MidiOut->openPort(i);
break;
}
}
push2MidiOut.reset(new RtMidiOut);
for (int i = 0, portCount = push2MidiOut->getPortCount(); i < portCount; ++i) {
if (QString::fromStdString(push2MidiOut->getPortName(i)) == PUSH2_OUTPUT_PORT) {
push2MidiOut->openPort(i);
break;
}
}
push2MidiIn.reset(new RtMidiIn);
push2MidiIn->ignoreTypes(false, false, false);
push2MidiIn->setCallback(&push2MidiInCallback, this);
for (int i = 0, portCount = push2MidiIn->getPortCount(); i < portCount; ++i) {
if (QString::fromStdString(push2MidiIn->getPortName(i)) == PUSH2_INPUT_PORT) {
push2MidiIn->openPort(i);
break;
}
}
push1MidiIn.reset(new RtMidiOut);
for (int i = 0, portCount = push1MidiIn->getPortCount(); i < portCount; ++i) {
if (QString::fromStdString(push1MidiIn->getPortName(i)) == PUSH1_INPUT_PORT) {
push1MidiIn->openPort(i);
break;
}
}
if (push1MidiOut->isPortOpen() && push2MidiOut->isPortOpen()
&& push2MidiIn->isPortOpen() && push1MidiIn->isPortOpen()) {
qDebug("Intercepting SysEx from MIDI input \"" PUSH1_OUTPUT_PORT "\"");
qDebug("Forwarding MIDI input \"" PUSH1_OUTPUT_PORT "\" to MIDI output \"" PUSH2_OUTPUT_PORT "\"");
qDebug("Forwarding MIDI input \"" PUSH2_INPUT_PORT "\" to MIDI output \"" PUSH1_INPUT_PORT "\"");
qDebug("Mapping Volume (CC 114) on Push 1 to Convert button (CC 35) on Push 2");
qDebug("Mapping Pan & Send (CC 115) on Push 1 to Setup button (CC 30) on Push 2");
qDebug("Mapping LED colors and behavior on Push 1 to Push 2");
qDebug("Push 1 display emulation started");
} else {
push1MidiOut.reset();
push2MidiOut.reset();
push2MidiIn.reset();
push1MidiIn.reset();
qDebug("Push 1 display emulation MIDI loopback ports not detected: "
"\"" PUSH1_INPUT_PORT "\" and \"" PUSH1_OUTPUT_PORT "\"");
}
}
PushQuickViewPrivate::~PushQuickViewPrivate()
{
}
void PushQuickViewPrivate::push1MidiOutCallback(double timeStamp, std::vector<uchar> *message, void *userData)
{
Q_UNUSED(timeStamp);
PushQuickViewPrivate *self = static_cast<PushQuickViewPrivate *>(userData);
if (!self)
return;
QByteArray data(reinterpret_cast<const char *>(message->data()), static_cast<int>(message->size()));
const int colorMap[] = {
0, 119, 56, 120, 1, 127, 65, 66,
38, 2, 67, 76, 5, 7, 77, 78,
11, 126, 85, 81, 11, 126, 85, 86,
11, 126, 85, 86, 43, 11, 85, 86,
44, 44, 13, 92, 47, 48, 91, 94,
15, 18, 99, 94, 18, 125, 107, 100,
18, 125, 103, 108, 21, 21, 105, 108,
23, 1, 65, 110, 127, 28, 29, 10,
81, 89, 97, 125, 91, 125, 56, 119,
127, 5, 5, 126, 9, 43, 48, 125,
125, 20, 23, 69, 2, 8, 126, 126,
11, 11, 44, 15, 16, 34, 20, 24,
3, 6, 126, 29, 75, 85, 89, 100,
101, 28, 27, 27, 28, 7, 8, 8,
102, 5, 44, 50, 18, 118, 118, 120,
27, 65, 8, 79, 6, 75, 28, 67
};
if (!data.startsWith(char(0xf0)) || !data.endsWith(char(0xf7))) {
if (self->push2MidiOut) {
int blinkSpeed = 0;
// Map red Automation (CC 29), Record (CC 86) and Stop (CC 89) buttons with white LED (channel 1 only)
// on Push 1 to Push 2
if (data.size() == 3 && data.at(0) == char(0xb0)
&& (data.at(1) == 29 || data.at(1) == 86 || data.at(1) == 89)) {
int index = data.at(2);
if (index == 0)
data[2] = 0; // Off
else if (index >= 1 && index <= 3)
data[2] = colorMap[121]; // Red Dim
else
data[2] = colorMap[120]; // Red
if (index >= 1 && index <= 6)
blinkSpeed = (index - 1) % 3;
// Map green Play button (CC 85) with white LED (channel 1 only) on Push 1 to Push 2
} else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) == 85) {
int index = data.at(2);
if (index == 0)
data[2] = 0; // Off
else if (index >= 1 && index <= 3)
data[2] = colorMap[123]; // Green Dim
else
data[2] = colorMap[122]; // Green
if (index >= 1 && index <= 6)
blinkSpeed = (index - 1) % 3;
// Map blue Solo button (CC 61) with white LED (channel 1 only) on Push 1 to Push 2
} else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) == 61) {
int index = data.at(2);
if (index == 0)
data[2] = 0; // Off
else if (index >= 1 && index <= 3)
data[2] = colorMap[40]; // Blue Dim
else
data[2] = colorMap[45]; // Blue
if (index >= 1 && index <= 6)
blinkSpeed = (index - 1) % 3;
// Map amber Mute buttion (CC 60) with white LED (channel 1 only) on Push 1 to Push 2
} else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) == 60) {
int index = data.at(2);
if (index == 0)
data[2] = 0; // Off
else if (index >= 1 && index <= 3)
data[2] = colorMap[127]; // Amber Dim
else
data[2] = colorMap[126]; // Amber
if (index >= 1 && index <= 6)
blinkSpeed = (index - 1) % 3;
// Map white LEDs (channel 1 only) on Push 1 to Push 2
} else if (data.size() == 3 && data.at(0) == char(0xb0)
&& (
// CC 3
data.at(1) == 3
// CC 9
|| data.at(1) == 9
// CC 28 to CC 29
|| data.at(1) >= 28 && data.at(1) <= 29
// CC 44 to CC 63 (excluding CC 60)
|| data.at(1) >= 44 && data.at(1) <= 63 && data.at(1) != 60
// CC 85 to CC 90
|| data.at(1) >= 85 && data.at(1) <= 90
// CC 110 to CC 119
|| data.at(1) >= 110 && data.at(1) <= 119
)
) {
int index = data.at(2);
if (index == 0)
data[2] = 0; // Off
else if (index >= 1 && index <= 3)
data[2] = 6; // Dim
else
data[2] = 127; // On
if (index >= 1 && index <= 6)
blinkSpeed = (index - 1) % 3;
// Map RG (red/green bi-color) LEDs (channel 1 only) on Push 1 to Push 2
} else if (data.size() == 3 && data.at(0) == char(0xb0)
&& (
// First row of buttons under the display (CC 20 to CC 27)
data.at(1) >= 20 && data.at(1) <= 27
// Time resolution buttons to the right of the pads (CC 36 to CC 43)
|| data.at(1) >= 36 && data.at(1) <= 43)
) {
int index = data.at(2);
if (index == 0)
data[2] = colorMap[0]; // Black
else if (index >= 1 && index <= 3)
data[2] = colorMap[121]; // Red Dim
else if (index >= 4 && index <= 6)
data[2] = colorMap[120]; // Red
else if (index >= 7 && index <= 9)
data[2] = colorMap[127]; // Amber Dim
else if (index >= 10 && index <= 12)
data[2] = colorMap[126]; // Amber
else if (index >= 13 && index <= 15)
data[2] = colorMap[125]; // Yellow Dim
else if (index >= 16 && index <= 18)
data[2] = colorMap[124]; // Yellow
else if (index >= 19 && index <= 21)
data[2] = colorMap[123]; // Green Dim
else if (index >= 22 && index <= 24)
data[2] = colorMap[122]; // Green
else
data[2] = colorMap[122]; // Green
if (index >= 1 && index <= 24)
blinkSpeed = (index - 1) % 3;
// Map RGB LEDs on Push 1 to Push 2
} else if (data.size() == 3
&& (
// Second row of buttons under the display (CC 102 to CC 109)
data.at(0) >= char(0xb0) && data.at(0) <= char(0xbf) && data.at(1) >= 102 && data.at(1) <= 109
// 8x8 pads (note 36 to note 99)
|| data.at(0) >= char(0x90) && data.at(0) <= char(0x9f) && data.at(1) >= 36 && data.at(1) <= 99
)
&& data.at(2) < sizeof(colorMap) / sizeof(*colorMap)
)
data[2] = colorMap[data.at(2)];
// Map Volume (CC 114) on Push 1 to Convert button (CC 35) on Push 2
if (data.size() == 3 && data.at(0) >= char(0xb0) && data.at(0) <= char(0xbf)
&& data.at(1) == 114)
data[1] = char(35);
// Map Pan & Send (CC 115) on Push 1 to Setup button (CC 30) on Push 2
else if (data.size() == 3 && data.at(0) >= char(0xb0) && data.at(0) <= char(0xbf)
&& data.at(1) == 115)
data[1] = char(30);
// Map CC 20-27 on Push 1 to CC 102-109 on Push 2
else if (data.size() == 3 && data.at(0) >= char(0xb0) && data.at(0) <= char(0xbf)
&& data.at(1) >= 20 && data.at(1) <= 27)
data[1] = data.at(1) + (102 - 20);
// Map CC 102-109 on Push 1 to CC 20-27 on Push 2
else if (data.size() == 3 && data.at(0) >= char(0xb0) && data.at(0) <= char(0xbf)
&& data.at(1) >= 102 && data.at(1) <= 109)
data[1] = data.at(1) - (102 - 20);
for (int i = 0; i < (blinkSpeed ? 2 : 1); ++i){
if (i > 0) {
switch (blinkSpeed) {
case 1: // 0.5 seconds on, 0.5 seconds off, ...
data[0] = data.at(0) + 15;
data[2] = 0;
break;
case 2: // 0.25 seconds on, 0.25 seconds off, ...
data[0] = data.at(0) + 14;
data[2] = 0;
break;
default:
break;
}
}
std::vector<uchar> outputMessage(data.constBegin(), data.constEnd());
self->push2MidiOut->sendMessage(&outputMessage);
}
}
}
if (!pushDisplayEvents)
return;
if (data == QByteArray::fromHex("f0477f151c0000f7")) {
emit pushDisplayEvents->clearLine(0);
} else if (data == QByteArray::fromHex("f0477f151d0000f7")) {
emit pushDisplayEvents->clearLine(1);
} else if (data == QByteArray::fromHex("f0477f151e0000f7")) {
emit pushDisplayEvents->clearLine(2);
} else if (data == QByteArray::fromHex("f0477f151f0000f7")) {
emit pushDisplayEvents->clearLine(3);
} else if (data.size() == 77 && data.startsWith(QByteArray::fromHex("f0477f15"))
&& uchar(data.at(4)) >= 24 && uchar(data.at(4)) <= 27
&& data.mid(5, 3) == QByteArray::fromHex("004500")
&& data.endsWith(char(0xf7))) {
int index = uchar(data.at(4)) - 24;
QByteArray lineData = data.mid(8, 68);
QString text;
text.resize(68);
for (int i = 0; i < lineData.size(); ++i)
text[i] = QChar(uchar(lineData[i]));
emit pushDisplayEvents->writeLine(index, text);
}
}
void PushQuickViewPrivate::push2MidiInCallback(double timeStamp, std::vector<uchar> *message, void *userData)
{
Q_UNUSED(timeStamp);
PushQuickViewPrivate *self = static_cast<PushQuickViewPrivate *>(userData);
if (!self)
return;
if (self->push1MidiIn) {
QByteArray data(reinterpret_cast<const char *>(message->data()), static_cast<int>(message->size()));
// Map Convert button (CC 35) on Push 2 to Volume (CC 114) on Push 1
if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) == 35)
data[1] = char(114);
// Map Setup button (CC 30) on Push 2 to Pan & Send (CC 115) on Push 1
else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) == 30)
data[1] = char(115);
// Map CC 102-109 on Push 2 to CC 20-27 on Push 1
else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) >= 102 && data.at(1) <= 109)
data[1] = data.at(1) - (102 - 20);
// Map CC 20-27 on Push 2 to CC 102-109 on Push 1
else if (data.size() == 3 && data.at(0) == char(0xb0) && data.at(1) >= 20 && data.at(1) <= 27)
data[1] = data.at(1) + (102 - 20);
std::vector<uchar> outputMessage(data.constBegin(), data.constEnd());
self->push1MidiIn->sendMessage(&outputMessage);
}
}
void PushQuickViewPrivate::sceneRendered()
{
Q_Q(PushQuickView);
display.drawImage(q->grab());
}
PushQuickView::PushQuickView(const QUrl &url) :
d_ptr(new PushQuickViewPrivate(this))
{
Q_D(PushQuickView);
if (!isOpen())
return;
setGeometry(QRect(QPoint(0, 0), d->display.size()));
setSource(url);
}
PushQuickView::~PushQuickView()
{
}
bool PushQuickView::isOpen() const
{
Q_D(const PushQuickView);
return d->display.isOpen();
}
bool PushQuickView::dithering() const
{
Q_D(const PushQuickView);
return d->display.dithering();
}
void PushQuickView::setDithering(bool value)
{
Q_D(PushQuickView);
if (d->display.dithering() != value) {
d->display.setDithering(value);
emit ditheringChanged();
}
}
#include "pushquickview.moc"
| 37.841871 | 120 | 0.506562 | [
"vector"
] |
c3029197426089129a5323b3f62dae18a8718532 | 1,341 | hpp | C++ | library/number_theory/linear_sieve.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | library/number_theory/linear_sieve.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | library/number_theory/linear_sieve.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | /* 線形篩 */
/*
説明
n 以下のすべての正整数に対して, その最小の素因数を求める
備考
https://cp-algorithms.com/algebra/prime-sieve-linear.html
[ constructor ]
説明
なし
引数
n : 整数
制約
n >= 0
計算量
O(n)
[ primes ]
説明
n 以下の素数のリストを求める
引数
なし
戻り値
n 以下の素数のリスト
制約
なし
計算量
O(1)
[ is_prime ]
説明
a が素数かどうかを判定する
引数
a : 整数
戻り値
a が素数かどうか
制約
a <= n
計算量
O(1)
[ prime_factorize ]
説明
a を素因数分解する
引数
a : 整数
戻り値
a の素因数分解
制約
a <= n
計算量
O(log a)
[ number_of_divisors ]
説明
a の正の約数の個数を求める
引数
a : 整数
戻り値
a の正の約数の個数
制約
a <= n
計算量
O(log a)
*/
class linear_sieve{
vector<int> lpf,p;
public:
linear_sieve(int n):lpf(n+1){
for(int i=2;i<=n;i++){
if(lpf[i]==0){
lpf[i]=i;
p.emplace_back(i);
}
for(int j=0;j<p.size()&&p[j]<=lpf[i]&&i*p[j]<=n;j++) lpf[i*p[j]]=p[j];
}
}
const vector<int>& primes()const{ return p; }
bool is_prime(int a)const{
assert(a<=(int)lpf.size()-1);
return a>0 && lpf[a]==a;
}
map<int,int> prime_factorize(int a)const{
assert(a<=(int)lpf.size()-1);
map<int,int> pf;
for(;a>1;a/=lpf[a]) ++pf[lpf[a]];
return pf;
}
int number_of_divisors(int a)const{
assert(a<=(int)lpf.size()-1);
int res=1,cnt=0,pre=-1;
for(;a>1;a/=lpf[a]){
if(pre==-1 || pre==lpf[a]){
cnt++;
}
else{
res*=cnt+1;
cnt=1;
}
pre=lpf[a];
}
return res*(cnt+1);
}
};
| 12.190909 | 73 | 0.553318 | [
"vector"
] |
c3053901852a959f9154deb92905d96632654ff0 | 6,297 | hpp | C++ | include/initialGuess.hpp | mfkiwl/libparanumal | 6f2382df19b43c02db15536220eab554e99fc539 | [
"MIT"
] | 102 | 2018-07-30T15:45:43.000Z | 2022-02-09T18:38:51.000Z | include/initialGuess.hpp | mfkiwl/libparanumal | 6f2382df19b43c02db15536220eab554e99fc539 | [
"MIT"
] | 65 | 2018-08-01T03:55:02.000Z | 2022-03-29T14:52:58.000Z | include/initialGuess.hpp | mfkiwl/libparanumal | 6f2382df19b43c02db15536220eab554e99fc539 | [
"MIT"
] | 45 | 2018-08-01T02:56:20.000Z | 2022-03-11T20:39:07.000Z | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef INITIALGUESS_HPP
#define INITIALGUESS_HPP
#include "linearSolver.hpp"
// Abstract base class for different initial guess strategies.
class initialGuessStrategy_t {
protected:
platform_t& platform;
settings_t& settings;
MPI_Comm comm;
dlong Ntotal; // Degrees of freedom
public:
initialGuessStrategy_t(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
virtual ~initialGuessStrategy_t();
virtual void FormInitialGuess(occa::memory& o_x, occa::memory& o_rhs) = 0;
virtual void Update(solver_t& solver, occa::memory& o_x, occa::memory& o_rhs) = 0;
};
// Default initial guess strategy: use whatever the user gave us.
class igDefaultStrategy : public initialGuessStrategy_t {
public:
igDefaultStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
void FormInitialGuess(occa::memory& o_x, occa::memory& o_rhs);
void Update(solver_t &solver, occa::memory& o_x, occa::memory& o_rhs);
};
// Zero initial guess strategy: use a zero initial guess.
class igZeroStrategy : public initialGuessStrategy_t {
public:
igZeroStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
void FormInitialGuess(occa::memory& o_x, occa::memory& o_rhs);
void Update(solver_t &solver, occa::memory& o_x, occa::memory& o_rhs);
};
// Initial guess strategies based on RHS projection.
class igProjectionStrategy : public initialGuessStrategy_t {
protected:
dlong curDim; // Current dimension of the initial guess space
dlong maxDim; // Maximum dimension of the initial guess space
occa::memory o_btilde; // vector (e.g., to be added to space)
occa::memory o_xtilde; // Solution vector corresponding to o_btilde
occa::memory o_Btilde; // space (orthogonalized)
occa::memory o_Xtilde; // Solution space corresponding to space
// temporary buffer for basis inner product output
dlong ctmpNblocks;
dfloat *ctmp;
occa::memory o_ctmp;
dfloat *alphas; // Buffers for storing inner products.
dfloat *alphasThisRank;
occa::memory o_alphas;
occa::kernel igBasisInnerProductsKernel;
occa::kernel igReconstructKernel;
occa::kernel igScaleKernel;
occa::kernel igUpdateKernel;
void igBasisInnerProducts(occa::memory& o_x, occa::memory& o_Q, occa::memory& o_c, dfloat *c, dfloat *cThisRank);
void igReconstruct(occa::memory& o_u, dfloat a, occa::memory& o_c, occa::memory& o_Q, occa::memory& o_unew);
public:
igProjectionStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
virtual ~igProjectionStrategy();
virtual void FormInitialGuess(occa::memory& o_x, occa::memory& o_rhs);
virtual void Update(solver_t& solver, occa::memory& o_x, occa::memory& o_rhs) = 0;
};
// "Classic" initial guess strategy from Fischer's 1998 paper.
class igClassicProjectionStrategy : public igProjectionStrategy {
public:
igClassicProjectionStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
void Update(solver_t &solver, occa::memory& o_x, occa::memory& o_rhs);
};
// Rolling QR update for projection history space a la Christensen's thesis.
class igRollingQRProjectionStrategy : public igProjectionStrategy {
private:
dfloat *R; // R factor in QR decomposition (row major)
occa::memory o_R;
occa::kernel igDropQRFirstColumnKernel;
void givensRotation(dfloat a, dfloat b, dfloat *c, dfloat *s);
public:
igRollingQRProjectionStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
~igRollingQRProjectionStrategy();
void Update(solver_t &solver, occa::memory& o_x, occa::memory& o_rhs);
};
// Extrapolation initial guess strategy.
class igExtrapStrategy : public initialGuessStrategy_t {
private:
int Nhistory;
int shift;
int entry;
occa::memory o_xh;
occa::memory o_coeffs;
occa::kernel igExtrapKernel;
occa::kernel igExtrapSparseKernel;
int Nsparse;
occa::memory o_sparseIds;
occa::memory o_sparseCoeffs;
void extrapCoeffs(int m, int M, dfloat *c);
public:
igExtrapStrategy(dlong _N, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
void FormInitialGuess(occa::memory& o_x, occa::memory& o_rhs);
void Update(solver_t &solver, occa::memory& o_x, occa::memory& o_rhs);
};
// Linear solver with successive-RHS initial-guess generation.
class initialGuessSolver_t : public linearSolver_t {
protected:
initialGuessStrategy_t* igStrategy; // The initial guess strategy.
linearSolver_t* linearSolver; // The linearSolver_t that does the solve.
public:
initialGuessSolver_t(dlong _N, dlong _Nhalo, platform_t& _platform, settings_t& _settings, MPI_Comm _comm);
~initialGuessSolver_t();
static initialGuessSolver_t* Setup(dlong _N, dlong _Nhalo,
platform_t& platform, settings_t& settings, MPI_Comm _comm);
int Solve(solver_t& solver, precon_t& precon,
occa::memory& o_x, occa::memory& o_rhs,
const dfloat tol, const int MAXIT, const int verbose);
};
void initialGuessAddSettings(settings_t& settings, const string prefix = "");
#endif /* INITIALGUESS_HPP */
| 36.398844 | 115 | 0.751787 | [
"vector"
] |
c30cc2eba58e38d8cf118c89672ef49a49cf3052 | 3,360 | cpp | C++ | src/Application.cpp | InversePalindrome/Rampancy | e228f8c16f0608b9f20a3904f4c5f19aa2076934 | [
"MIT"
] | 1 | 2018-03-23T02:25:24.000Z | 2018-03-23T02:25:24.000Z | src/Application.cpp | InversePalindrome/Rampancy | e228f8c16f0608b9f20a3904f4c5f19aa2076934 | [
"MIT"
] | null | null | null | src/Application.cpp | InversePalindrome/Rampancy | e228f8c16f0608b9f20a3904f4c5f19aa2076934 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2017 InversePalindrome
Rampancy - Application.cpp
InversePalindrome.com
*/
#include "Application.hpp"
#include "SplashState.hpp"
#include <OGRE/OgreConfigFile.h>
#include <OGRE/OgreResourceGroupManager.h>
Application::Application() :
root(new Ogre::Root()),
window(nullptr),
sceneManager(root->createSceneManager(Ogre::ST_GENERIC)),
camera(nullptr),
gui(new MyGUI::Gui()),
guiPlatform(new MyGUI::OgrePlatform()),
inputManager(eventBus),
stateTransition(StateTransition::None),
games("SavedGames.xml"),
shutdown(false)
{
isConfigured = configure();
if (isConfigured)
{
initialise();
}
else
{
shutdown = true;
}
}
Application::~Application()
{
Ogre::WindowEventUtilities::removeWindowEventListener(window, this);
if (isConfigured)
{
gui->shutdown();
guiPlatform->shutdown();
}
delete gui;
delete guiPlatform;
delete root;
}
void Application::run()
{
while (!this->shutdown)
{
this->handleEvent();
this->update();
this->render();
}
}
void Application::handleEvent()
{
Ogre::WindowEventUtilities::messagePump();
this->inputManager.capture();
}
void Application::update()
{
this->stateMachine.ProcessStateTransitions();
this->stateMachine.UpdateStates();
}
void Application::render()
{
this->root->renderOneFrame();
}
bool Application::configure()
{
if (this->root->showConfigDialog())
{
this->window = this->root->initialise(true, "Rampancy");
return true;
}
return false;
}
void Application::initialise()
{
this->root->addFrameListener(this);
Ogre::WindowEventUtilities::addWindowEventListener(this->window, this);
this->inputManager.setup(window);
this->addCamera();
this->loadResources();
this->guiPlatform->initialise(window, sceneManager);
this->gui->initialise();
this->stateMachine.Initialize<SplashState>(this);
}
void Application::loadResources()
{
Ogre::ConfigFile cf;
Ogre::String resourceFile;
#ifdef _DEBUG
resourceFile = "resources_d.cfg";
#else
resourceFile = "resources.cfg";
#endif
cf.load(resourceFile);
auto seci = cf.getSectionIterator();
while (seci.hasMoreElements())
{
const auto& secName = seci.peekNextKey();
const auto* settings = seci.getNext();
for (const auto& setting : *settings)
{
const auto& typeName = setting.first;
const auto& archName = setting.second;
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
}
}
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
void Application::addCamera()
{
this->camera = this->sceneManager->createCamera("Main");
this->camera->setPosition({ 0, 0, 0 });
this->camera->setNearClipDistance(5);
auto* viewport = this->window->addViewport(camera);
viewport->setBackgroundColour(Ogre::ColourValue(255.f, 255.f, 255.f));
this->camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));
} | 21.538462 | 116 | 0.624107 | [
"render"
] |
c315bfed7d75f016dc06feaa6dadcc70c9da575e | 10,418 | cpp | C++ | examples/model_generate_example.cpp | mahilab/mahi-mpc | 0f778b5884a5cd1b2b05cbfdcc343eecdb140d8c | [
"MIT"
] | null | null | null | examples/model_generate_example.cpp | mahilab/mahi-mpc | 0f778b5884a5cd1b2b05cbfdcc343eecdb140d8c | [
"MIT"
] | null | null | null | examples/model_generate_example.cpp | mahilab/mahi-mpc | 0f778b5884a5cd1b2b05cbfdcc343eecdb140d8c | [
"MIT"
] | null | null | null | #include <Mahi/Mpc/ModelGenerator.hpp>
#include <Mahi/Util.hpp>
using namespace casadi;
using mahi::util::PI;
int main(int argc, char* argv[])
{
mahi::util::Options options("options.exe", "Simple Program Demonstrating Options");
options.add_options()
("d,dll", "Generate new dll.")
("s,s2", "use second timestep.")
("m,ma27", "Runs using MA27 solver. Mumps otherwise")
("l,linear", "Generates linearized model.");
auto result = options.parse(argc, argv);
bool linear = result.count("linear") > 0;
double L = 1.0;
double m = 1.0;
double g = 9.81;
SX qA = SX::sym("qA");
SX qB = SX::sym("qB");
SX qA_dot = SX::sym("qA_dot");
SX qB_dot = SX::sym("qB_dot");
SX TA = SX::sym("TA");
SX TB = SX::sym("TB");
// ODE right hand side
SX qA_ddot = -(TA - TB - TB*cos(qB) + L*L*m*qA_dot*qA_dot*sin(qB) + L*L*m*qB_dot*qB_dot*sin(qB) - 2*L*g*m*cos(qA) + L*L*m*qA_dot*qA_dot*cos(qB)*sin(qB) + 2*L*L*m*qA_dot*qB_dot*sin(qB) + L*g*m*cos(qA + qB)*cos(qB))/(L*L*m*(cos(qB)*cos(qB) - 2));
SX qB_ddot = (TA - 3*TB + TA*cos(qB) - 2*TB*cos(qB) + 2*L*g*m*cos(qA + qB) + 3*L*L*m*qA_dot*qA_dot*sin(qB) + L*L*m*qB_dot*qB_dot*sin(qB) - 2*L*g*m*cos(qA) + 2*L*L*m*qA_dot*qA_dot*cos(qB)*sin(qB) + L*L*m*qB_dot*qB_dot*cos(qB)*sin(qB) - 2*L*g*m*cos(qA)*cos(qB) + 2*L*L*m*qA_dot*qB_dot*sin(qB) + L*g*m*cos(qA + qB)*cos(qB) + 2*L*L*m*qA_dot*qB_dot*cos(qB)*sin(qB))/(L*L*m*(cos(qB)*cos(qB) - 2));
SX x = SX::vertcat({qA,qB,qA_dot,qB_dot});
SX x_dot = SX::vertcat({qA_dot,qB_dot,qA_ddot,qB_ddot});
// control vector
SX u = SX::vertcat({TA,TB});
auto A = jacobian(x_dot,x);
auto B = jacobian(x_dot,u);
casadi::Function get_A = casadi::Function("get_A",{x,u},{A},{"x","u"},{"A"});
casadi::Function get_B = casadi::Function("get_B",{x,u},{B},{"x","u"},{"B"});
casadi::Function get_x_dot_init = casadi::Function("F_get_x_dot_init",{x,u},{x_dot},{"x","u"},{"x_dot_init"});
// Bounds on state
std::vector<double> x_min = {-inf, -inf, -inf, -inf};
std::vector<double> x_max = {inf, inf, inf, inf};
// Bounds for control
std::vector<double> u_min = {-inf, -inf};
std::vector<double> u_max = {inf, inf};
// settings for multiple shooting constructions
mahi::util::Time time_step = mahi::util::milliseconds(2);
mahi::util::Time final_time = mahi::util::milliseconds(50);
//
// ModelGenerator my_generator("old_double_pendulum", x, x_dot, u, final_time, time_step, u_min, u_max, x_min, x_max, linear);
// my_generator.create_model();
// my_generator.generate_c_code();
// if (result.count("dll")) my_generator.compile_model();
// NLP variable bounds and initial guesses
std::vector<double> v_min,v_max,v_init;
// Offset in V --- this is like a counter variable
int offset=0;
int ns = (final_time/time_step);
int nx = x.size1();
int nu = u.size1();
mahi::util::print("{} shooting nodes over {} seconds with {} states, and {} control variables", ns, final_time, nx, nu);
// Bounds on initial state
std::vector<double> x0_min = {0, 0, 0, 0};
std::vector<double> x0_max = {0, 0, 0, 0}; // min and max are the same here
std::vector<double> x_init = {0, 0, 0, 0};
std::vector<double> u_init = {0.0, 0.0};
std::vector<double> xf_min = {-inf, -inf, -inf, -inf};
std::vector<double> xf_max = {inf, inf, inf, inf};
//declare vectors for the state and control at each node
for(int k=0; k<ns; ++k){
// Local state
// X.push_back( V.nz(casadi::Slice(offset,offset+nx)));
if(k==0){
v_min.insert(v_min.end(), x0_min.begin(), x0_min.end());
v_max.insert(v_max.end(), x0_max.begin(), x0_max.end());
} else {
v_min.insert(v_min.end(), x_min.begin(), x_min.end());
v_max.insert(v_max.end(), x_max.begin(), x_max.end());
}
v_init.insert(v_init.end(), x_init.begin(), x_init.end());
// Local Control
// U.push_back(V.nz(casadi::Slice(offset,offset+nu)));
v_min.insert(v_min.end(), u_min.begin(), u_min.end());
v_max.insert(v_max.end(), u_max.begin(), u_max.end());
v_init.insert(v_init.end(), u_init.begin(), u_init.end());
}
v_min.insert(v_min.end(), xf_min.begin(), xf_min.end());
v_max.insert(v_max.end(), xf_max.begin(), xf_max.end());
v_init.insert(v_init.end(), x_init.begin(), x_init.end());
std::cout << "v_min: " << v_min.size() << std::endl;
std::cout << "v_max: " << v_max.size() << std::endl;
std::cout << "v_init: " << v_init.size() << std::endl;
// Bounds and initial guess
casadi::Dict opts;
opts["ipopt.tol"] = 1e-5;
opts["ipopt.max_iter"] = 200;
opts["ipopt.linear_solver"] = result.count("m") ? "ma27" : "mumps";
opts["ipopt.print_level"] = 0;
opts["print_time"] = 0;
opts["ipopt.sb"] = "yes";
std::string dll = (linear ? "linear_" : "nonlinear_") + std::string("double_pendulum.so");
Function solver = nlpsol("nlpsol", "ipopt", dll, opts);
std::map<std::string, casadi::DM> arg, res;
arg["lbx"] = v_min;
arg["ubx"] = v_max;
arg["lbg"] = 0;
arg["ubg"] = 0;
arg["x0"] = v_init;
casadi::SX x_next_euler = x + x_dot*time_step.as_seconds();
casadi::Function F_euler = casadi::Function("F",{x,u},{x_next_euler},{"x","u"},{"x_next_euler"});
casadi::Function x_dot_fun("x_dot_ode",{x,u},{x_dot},{"x","u"},{"x_dot"});
auto sim_time = mahi::util::seconds(0.2);
double curr_sim_time = 0;
std::vector<double> qA_opt,qB_opt,qA_dot_opt,qB_dot_opt;
std::vector<double> TA_opt, TB_opt;
double dt = time_step.as_seconds();
double avg_solve_time = 0;
mahi::util::Clock sim_clock;
std::vector<double> x_next_vec = {0,0,0,0};
std::vector<double> u_curr = {0,0};
while (curr_sim_time < sim_time.as_seconds()){
// update trajectory with new desired
std::vector<double> traj;
double curr_traj_time = curr_sim_time;
for (size_t i = 0; i < ns; i++)
{
traj.push_back(sin(2*PI*curr_traj_time));
traj.push_back(-sin(2*PI*curr_traj_time));
traj.push_back(2*PI*cos(2*PI*curr_traj_time));
traj.push_back(-2*PI*cos(2*PI*curr_traj_time));
curr_traj_time += time_step.as_seconds();
}
if (linear){
// get and add flattened A, B, x_dot_init, x_init
std::vector<double> A_res(get_A(SXDict({{"x",x_next_vec},{"u",u_curr}})).at("A"));
std::vector<double> B_res(get_B(SXDict({{"x",x_next_vec},{"u",u_curr}})).at("B"));
std::vector<double> x_dot_init_res(get_x_dot_init(SXDict({{"x",x_next_vec},{"u",u_curr}})).at("x_dot_init"));
for (const auto &a_ : A_res) traj.push_back(a_);
for (const auto &b_ : B_res) traj.push_back(b_);
for (const auto &x_dot_init_ : x_dot_init_res) traj.push_back(x_dot_init_);
for (const auto &x_next_ : x_next_vec) traj.push_back(x_next_);
for (const auto &u_ : u_curr) traj.push_back(u_);
static bool first_time = true;
if (first_time){
std::cout << A_res << std::endl;
std::cout << B_res << std::endl;
std::cout << x_dot_init_res << std::endl;
}
first_time = false;
}
arg["p"] = traj;
mahi::util::Clock my_clock;
res = solver(arg);
auto solve_time = my_clock.get_elapsed_time().as_milliseconds();
static int iterations = 0;
avg_solve_time = (avg_solve_time*iterations+(double)solve_time)/(iterations+1);
iterations++;
std::vector<double> V_opt(res.at("x"));
arg["x0"] = V_opt;
std::vector<double> x_curr = std::vector<double>(V_opt.begin(),V_opt.begin()+nx); // first 4 indices
u_curr = std::vector<double>(V_opt.begin()+(nx),V_opt.begin()+ (nx + nu)); // 5-6 indices
// begin rk4
auto k1 = x_dot_fun(casadi::SXDict({{"x",x_curr},{"u",u_curr}}));
auto k2 = x_dot_fun(casadi::SXDict({{"x",x_curr+dt/2*k1.at("x_dot")},{"u",u_curr}}));
auto k3 = x_dot_fun(casadi::SXDict({{"x",x_curr+dt/2*k2.at("x_dot")},{"u",u_curr}}));
auto k4 = x_dot_fun(casadi::SXDict({{"x",x_curr+dt*k3.at("x_dot")},{"u",u_curr}}));
x_next_vec = std::vector<double>(x_curr + dt/6*(k1.at("x_dot")+2*k2.at("x_dot")+2*k3.at("x_dot")+k4.at("x_dot")));
// end rk4
std::copy(x_next_vec.begin(),x_next_vec.end(),v_min.begin());
std::copy(x_next_vec.begin(),x_next_vec.end(),v_max.begin());
arg["lbx"] = v_min;
arg["ubx"] = v_max;
qA_opt.push_back(x_curr[0]);
qB_opt.push_back(x_curr[1]);
qA_dot_opt.push_back(x_curr[2]);
qB_dot_opt.push_back(x_curr[3]);
TA_opt.push_back(u_curr[0]);
TB_opt.push_back(u_curr[1]);
curr_sim_time += time_step.as_seconds();
}
mahi::util::print("sim time: {:.2f} s, avg solve time: {:.2f} ms",sim_clock.get_elapsed_time().as_seconds(),avg_solve_time);
mahi::util::disable_realtime();
// Extract the optimal state trajectory
std::ofstream file;
std::string filename = (linear ? "" : "non") + std::string("linear_double_pendulum_mpc_results.m");
file.open(filename.c_str());
file << "% Results from " __FILE__ << std::endl;
file << "% Generated " __DATE__ " at " __TIME__ << std::endl;
file << std::endl;
// Save results
file << "t = linspace(0," << sim_time.as_seconds() << "," << (sim_time/time_step) << ");" << std::endl;
file << "qA = " << qA_opt << ";" << std::endl;
file << "qB = " << qB_opt << ";" << std::endl;
file << "qA_dot = " << qA_dot_opt << ";" << std::endl;
file << "qB_dot = " << qB_dot_opt << ";" << std::endl;
file << "TA = " << TA_opt << ";" << std::endl;
file << "TB = " << TB_opt << ";" << std::endl;
file << "figure;" << std::endl;
file << "hold on;" << std::endl;
file << "plot(t,qA);" << std::endl;
file << "plot(t,qB);" << std::endl;
file << "xlabel('Time (s)');" << std::endl;
file << "ylabel('Position (rad)');" << std::endl;
file << "legend('qA','qB');" << std::endl;
std::cout << "finished" << std::endl;
return 0;
}
| 39.612167 | 395 | 0.571703 | [
"vector",
"model"
] |
c315f5f5ab3f9b30a3f701457fe7775a25891339 | 22,164 | cpp | C++ | engine.cpp | jasonhutchens/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | 4 | 2016-06-05T04:36:12.000Z | 2016-08-21T20:11:49.000Z | engine.cpp | kranzky/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | null | null | null | engine.cpp | kranzky/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | null | null | null | //==============================================================================
#include <engine.hpp>
#include <entity_manager.hpp>
#include <splash.hpp>
#include <credits.hpp>
#include <menu.hpp>
#include <menu_item.hpp>
#include <tutorial.hpp>
#include <game.hpp>
#include <score.hpp>
#include <debug.hpp>
#include <entity.hpp>
#include <viewport.hpp>
#include <hgesprite.h>
#include <hgeresource.h>
#include "resource.h"
//------------------------------------------------------------------------------
Engine * Engine::s_instance( 0 );
//------------------------------------------------------------------------------
Engine::Engine()
:
m_rm( 0 ),
m_pm( 0 ),
m_hge( 0 ),
m_b2d( 0 ),
m_vp( 0 ),
m_em( 0 ),
m_dd( 0 ),
m_overlay( 0 ),
m_contexts(),
m_state( STATE_NONE ),
m_mouse(),
m_controller(),
m_config(),
m_handled_key( false ),
m_paused( false ),
m_running( false ),
m_show_mouse( false ),
m_mouse_sprite( 0 ),
m_time_ratio( 1.0f ),
m_gui( 0 ),
m_stick( false )
{
m_vp = new ViewPort();
m_em = new EntityManager();
}
//------------------------------------------------------------------------------
Engine::~Engine()
{
m_config.fini();
m_controller.fini();
m_gui->DelCtrl( EC_CONTINUE );
m_gui->DelCtrl( EC_QUIT );
delete m_gui;
std::vector< Context * >::iterator i;
for ( i = m_contexts.begin(); i != m_contexts.end(); ++i )
{
Context * context( * i );
context->fini();
delete context;
}
m_contexts.clear();
delete m_pm;
m_pm = 0;
m_rm->Purge();
delete m_rm;
m_rm = 0;
if ( m_hge != 0 )
{
m_hge->System_Shutdown();
m_hge->Release();
m_hge = 0;
}
delete m_b2d;
delete m_dd;
delete m_overlay;
delete m_vp;
delete m_em;
}
//------------------------------------------------------------------------------
bool
Engine::handledKey()
{
return m_handled_key;
}
//------------------------------------------------------------------------------
bool
Engine::isPaused()
{
return m_paused;
}
//------------------------------------------------------------------------------
bool
Engine::isDebug()
{
return m_dd->GetFlags() != 0;
}
//------------------------------------------------------------------------------
float
Engine::getTimeRatio()
{
return m_time_ratio;
}
//------------------------------------------------------------------------------
void
Engine::error( const char * format, ... )
{
char message[1024];
va_list ap;
va_start( ap, format );
vsprintf_s( message, 1024, format, ap );
va_end( ap );
m_hge->System_Log( "Error: %s", message );
MessageBox( NULL, message, "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);
}
//------------------------------------------------------------------------------
void
Engine::start()
{
m_contexts.push_back( new Splash() );
m_contexts.push_back( new Menu() );
m_contexts.push_back( new Tutorial() );
m_contexts.push_back( new Game() );
m_contexts.push_back( new Score() );
m_contexts.push_back( new Credits() );
m_pm = new hgeParticleManager();
_initGraphics();
_initPhysics();
m_controller.init();
if ( m_hge->System_Initiate() )
{
_loadData();
init();
#ifdef _DEBUG
switchContext( STATE_GAME );
#else
switchContext( STATE_SPLASH );
#endif
m_hge->System_Start();
}
else
{
MessageBox( NULL, m_hge->System_GetErrorMessage(), "Error",
MB_OK | MB_ICONERROR | MB_APPLMODAL );
}
}
//------------------------------------------------------------------------------
void
Engine::init()
{
hgeFont * font( m_rm->GetFont( "menu" ) );
m_vp->restore();
m_gui = new hgeGUI();
float cx( 0.5f * m_vp->screen().x );
float cy( 0.5f * m_vp->screen().y );
m_navSnd = m_rm->GetEffect( "menu_nav" );
m_selectSnd = m_rm->GetEffect( "menu_select" );
m_gui->AddCtrl( new MenuItem( EC_CONTINUE, cx, cy - 15, "Continue",
font, m_navSnd ) );
m_gui->AddCtrl( new MenuItem( EC_QUIT, cx, cy + 15 , "Quit", font, m_navSnd ) );
m_gui->SetNavMode( HGEGUI_UPDOWN );
m_gui->SetFocus( 1 );
m_gui->Enter();
m_hge->Random_Seed();
}
//------------------------------------------------------------------------------
void
Engine::switchContext( EngineState state )
{
m_running = false;
if ( m_state != STATE_NONE )
{
m_contexts[m_state]->fini();
}
m_pm->KillAll();
hgeInputEvent event;
while ( m_hge->Input_GetEvent( & event ) );
hideMouse();
m_mouse.clear();
m_controller.clear();
m_stick = false;
m_state = state;
m_paused = false;
m_handled_key = false;
m_time_ratio = 1.0f;
if ( m_state != STATE_NONE )
{
m_contexts[m_state]->init();
}
m_running = true;
}
//------------------------------------------------------------------------------
Context *
Engine::getContext()
{
return m_contexts[m_state];
}
//------------------------------------------------------------------------------
void
Engine::showMouse()
{
m_show_mouse = true;
}
//------------------------------------------------------------------------------
void
Engine::setMouse( const char * name )
{
m_mouse_sprite = m_rm->GetSprite( name );
}
//------------------------------------------------------------------------------
void
Engine::hideMouse()
{
m_show_mouse = false;
}
//------------------------------------------------------------------------------
const Mouse &
Engine::getMouse()
{
return m_mouse;
}
//------------------------------------------------------------------------------
const Controller &
Engine::getController()
{
return m_controller;
}
//------------------------------------------------------------------------------
Config &
Engine::getConfig()
{
return m_config;
}
//------------------------------------------------------------------------------
int
Engine::updateGUI( float dt, hgeGUI * gui, int default_focus, int max )
{
const Controller & pad( Engine::instance()->getController() );
int select( 0 );
if ( pad.isConnected() )
{
int focus( gui->GetFocus() );
if ( pad.buttonDown( XPAD_BUTTON_START ) )
{
focus = default_focus;
gui->SetFocus( focus );
}
if ( pad.buttonDown( XPAD_BUTTON_A ) ||
pad.buttonDown( XPAD_BUTTON_START ) )
{
select = focus;
}
float dy( pad.getStick( XPAD_THUMBSTICK_LEFT ).y );
if ( m_stick && dy < 0.8f && dy > -0.8f )
{
m_stick = false;
}
if ( ( ! m_stick && dy > 0.8f ||
pad.buttonDown( XPAD_BUTTON_DPAD_UP ) ) && focus > 1 )
{
--focus;
gui->SetFocus( focus );
m_stick = true;
}
if ( ( ! m_stick && dy < -0.8f ||
pad.buttonDown( XPAD_BUTTON_DPAD_DOWN ) ) && focus < max )
{
++focus;
gui->SetFocus( focus );
m_stick = true;
}
}
if ( select == 0 )
{
select = static_cast< Control >( gui->Update( dt ) );
}
return select;
}
//------------------------------------------------------------------------------
// physics:
//------------------------------------------------------------------------------
void
Engine::Violation( b2Body * body )
{
m_hge->System_Log( "Body left world" );
Entity * entity( static_cast<Entity *>( body->GetUserData() ) );
}
//------------------------------------------------------------------------------
void
Engine::Add( b2ContactPoint * point )
{
Entity * entity1 =
static_cast< Entity * >( point->shape1->GetBody()->GetUserData() );
Entity * entity2 =
static_cast< Entity * >( point->shape2->GetBody()->GetUserData() );
entity1->collide( entity2, point );
entity2->collide( entity1, point );
}
//------------------------------------------------------------------------------
void
Engine::Persist( b2ContactPoint * point )
{
}
//------------------------------------------------------------------------------
void
Engine::Remove( b2ContactPoint * point )
{
}
//------------------------------------------------------------------------------
bool
Engine::ShouldCollide( b2Shape * shape1, b2Shape * shape2 )
{
if ( ! getContext()->handlesCollisions() )
{
return b2ContactFilter::ShouldCollide( shape1, shape2 );
}
Entity * entity1 =
static_cast< Entity * >( shape1->GetBody()->GetUserData() );
Entity * entity2 =
static_cast< Entity * >( shape2->GetBody()->GetUserData() );
return getContext()->shouldCollide( entity1, entity2 );
}
//------------------------------------------------------------------------------
//static:
//------------------------------------------------------------------------------
Engine *
Engine::instance()
{
if ( s_instance == 0 )
{
s_instance = new Engine;
}
return s_instance;
}
//------------------------------------------------------------------------------
void
Engine::destroy()
{
delete s_instance;
s_instance = 0;
}
//------------------------------------------------------------------------------
HGE *
Engine::hge()
{
return instance()->m_hge;
}
//------------------------------------------------------------------------------
b2World *
Engine::b2d()
{
return instance()->m_b2d;
}
//------------------------------------------------------------------------------
ViewPort *
Engine::vp()
{
return instance()->m_vp;
}
//------------------------------------------------------------------------------
EntityManager *
Engine::em()
{
return instance()->m_em;
}
//------------------------------------------------------------------------------
hgeResourceManager *
Engine::rm()
{
return instance()->m_rm;
}
//------------------------------------------------------------------------------
hgeParticleManager *
Engine::pm()
{
return instance()->m_pm;
}
//------------------------------------------------------------------------------
DebugDraw *
Engine::dd()
{
return instance()->m_dd;
}
//------------------------------------------------------------------------------
//private:
//------------------------------------------------------------------------------
bool
Engine::s_loseFocus()
{
return s_instance->_loseFocus();
}
//------------------------------------------------------------------------------
bool
Engine::s_gainFocus()
{
return s_instance->_gainFocus();
}
//------------------------------------------------------------------------------
bool
Engine::s_restore()
{
return s_instance->_restore();
}
//------------------------------------------------------------------------------
bool
Engine::s_update()
{
return s_instance->_update();
}
//------------------------------------------------------------------------------
bool
Engine::s_render()
{
return s_instance->_render();
}
//------------------------------------------------------------------------------
bool
Engine::s_exit()
{
return s_instance->_exit();
}
//------------------------------------------------------------------------------
bool
Engine::_loseFocus()
{
#ifndef _DEBUG
m_paused = ( m_state == STATE_GAME || m_state == STATE_HELP );
#endif
return false;
}
//------------------------------------------------------------------------------
bool
Engine::_gainFocus()
{
return false;
}
//------------------------------------------------------------------------------
bool
Engine::_restore()
{
_loseFocus();
return m_vp->restore();
}
//------------------------------------------------------------------------------
bool
Engine::_update()
{
float dt( m_hge->Timer_GetDelta() );
if ( m_state == STATE_GAME || m_state == STATE_HELP )
{
if ( m_hge->Input_KeyDown( HGEK_P ) ||
m_hge->Input_KeyDown( HGEK_ESCAPE ) )
{
m_handled_key = true;
m_paused = ! m_paused;
}
if ( m_controller.buttonDown( XPAD_BUTTON_START ) ||
m_controller.buttonDown( XPAD_BUTTON_BACK ) )
{
m_paused = ! m_paused;
m_controller.clear();
}
}
#ifdef _DEBUG
if ( m_hge->Input_KeyDown( HGEK_O ) && m_state != STATE_SCORE )
{
m_handled_key = true;
int flags( b2DebugDraw::e_shapeBit |
b2DebugDraw::e_aabbBit |
b2DebugDraw::e_obbBit );
if ( m_dd->GetFlags() != 0 )
{
m_dd->ClearFlags( flags );
m_time_ratio = 1.0f;
}
else
{
m_dd->SetFlags( flags );
}
}
#endif
if ( m_dd->GetFlags() != 0 )
{
if ( m_hge->Input_KeyDown( HGEK_EQUALS ) )
{
m_time_ratio *= 0.5f;
}
if ( m_hge->Input_KeyDown( HGEK_MINUS ) )
{
m_time_ratio *= 2.0f;
}
}
if ( m_dd->GetFlags() != 0 )
{
m_hge->Gfx_BeginScene();
m_hge->Gfx_Clear( m_contexts[m_state]->getColour() );
m_contexts[m_state]->render();
m_vp->reset();
_drawLetterbox();
}
if ( m_paused )
{
switch ( static_cast< EngineControl >( updateGUI( dt, m_gui,
EC_CONTINUE, 2 ) ) )
{
case EC_CONTINUE:
{
m_hge->Effect_Play(m_selectSnd);
m_paused = false;
m_gui->SetFocus( 1 );
break;
}
case EC_QUIT:
{
m_hge->Effect_Play(m_selectSnd);
m_gui->SetFocus( 1 );
switchContext( STATE_MENU );
return false;
break;
}
}
dt = 0.0f;
}
else
{
dt *= m_time_ratio;
}
m_mouse.update( dt );
m_controller.update( dt );
m_b2d->Step( dt, 10 );
bool retval( m_contexts[m_state]->update( dt ) );
m_pm->Update( dt );
if ( m_dd->GetFlags() != 0 )
{
_pauseOverlay();
m_hge->Gfx_EndScene();
}
return retval;
}
//------------------------------------------------------------------------------
bool
Engine::_render()
{
if ( ! m_running )
{
return false;
}
if ( m_dd->GetFlags() == 0 )
{
m_hge->Gfx_BeginScene();
m_hge->Gfx_Clear( m_contexts[m_state]->getColour() );
m_contexts[m_state]->render();
m_vp->reset();
_drawLetterbox();
if ( m_show_mouse && m_mouse_sprite != 0 )
{
float x( 0.0f );
float y( 0.0f );
m_hge->Input_GetMousePos( & x, & y );
m_mouse_sprite->Render( x, y );
}
_pauseOverlay();
m_hge->Gfx_EndScene();
}
return false;
}
//------------------------------------------------------------------------------
bool
Engine::_exit()
{
return false;
}
//------------------------------------------------------------------------------
void
Engine::_pauseOverlay()
{
if ( ! m_paused && m_dd->GetFlags() == 0 && m_time_ratio == 1.0f )
{
return;
}
hgeFont * font( m_rm->GetFont( "menu" ) );
float width( m_vp->screen().x );
float height( m_vp->screen().y );
if ( m_paused )
{
m_overlay->RenderStretch( 0.0f, 0.0f, width, height );
m_gui->Render();
}
else if ( m_time_ratio != 1.0f )
{
font->SetColor( 0x88FFFFFF );
font->printf( 0.5f * width, 0.0f, HGETEXT_CENTER,
"+++ %2.2f +++", m_time_ratio );
}
if ( m_dd->GetFlags() != 0 )
{
font->SetColor( 0x88FFFFFF );
font->Render( 0.5f * width, height - font->GetHeight(), HGETEXT_CENTER,
"+++ D E B U G +++" );
}
}
//------------------------------------------------------------------------------
void
Engine::_drawLetterbox()
{
m_overlay->SetColor( m_contexts[m_state]->getBorder() );
float width( m_vp->screen().x );
float height( m_vp->screen().y );
float dx( m_vp->getWidthOffset() );
float dy( m_vp->getHeightOffset() );
if ( dx > 0.0f )
{
m_overlay->RenderStretch( -dx, 0.0f, 0.0f, height + 2.0f * dy );
m_overlay->RenderStretch( width, 0.0f, width + dx, height + 2.0f * dy );
}
if ( dy > 0.0f )
{
m_overlay->RenderStretch( 0.0f, -dy, width + 2.0f * dx, 0.0f );
m_overlay->RenderStretch( 0.0f, height, width + 2.0f * dx, height + dy );
}
m_overlay->SetColor( 0xCC000000 );
}
//------------------------------------------------------------------------------
void
Engine::_initGraphics()
{
m_hge = hgeCreate( HGE_VERSION );
m_hge->System_SetState( HGE_LOGFILE, "kranzky.log" );
m_hge->System_SetState( HGE_INIFILE, "kranzky.ini" );
m_hge->System_SetState( HGE_FOCUSLOSTFUNC, s_loseFocus );
m_hge->System_SetState( HGE_FOCUSGAINFUNC, s_gainFocus );
m_hge->System_SetState( HGE_GFXRESTOREFUNC, s_restore );
m_hge->System_SetState( HGE_FRAMEFUNC, s_update );
m_hge->System_SetState( HGE_RENDERFUNC, s_render );
m_hge->System_SetState( HGE_EXITFUNC, s_exit );
m_hge->System_SetState( HGE_TITLE, "+++ P R O J E C T . I C E v0.1 +++" );
m_hge->System_SetState( HGE_ICON, MAKEINTRESOURCE( IDI_ICON1 ) );
m_hge->System_SetState( HGE_SHOWSPLASH, false );
m_hge->System_SetState( HGE_FPS, HGEFPS_UNLIMITED );
m_config.init();
_setBestScreenMode();
m_hge->System_SetState( HGE_SCREENWIDTH, m_config.screenWidth );
m_hge->System_SetState( HGE_SCREENHEIGHT, m_config.screenHeight );
m_hge->System_SetState( HGE_SCREENBPP, m_config.bpp );
m_hge->System_SetState( HGE_USESOUND, m_config.sound );
m_hge->System_SetState( HGE_WINDOWED, ! m_config.fullScreen );
m_vp->screen().x = static_cast<float>( m_config.screenWidth );
m_vp->screen().y = static_cast<float>( ( 9.0f * m_config.screenWidth ) / 16.0f);
//m_vp->screen().y = static_cast<int>( m_config.screenHeight );
m_overlay = new hgeSprite( 0, 0, 0, 1, 1 );
m_overlay->SetColor( 0xCC000000 );
}
//------------------------------------------------------------------------------
void
Engine::_setBestScreenMode()
{
int index = 0;
DEVMODE dm;
ZeroMemory( & dm, sizeof( dm ) );
dm.dmSize = sizeof( dm );
int bpp( 0 );
float width( 0.0f );
float height( 0.0f );
float desired_ratio( 16.0f / 9.0f );
int desired_bpp( m_config.bpp );
while ( EnumDisplaySettings( NULL, index++, & dm ) != 0 )
{
// Don't consider anything less than 800x600
if ( dm.dmPelsWidth < 800 || dm.dmPelsHeight < 600 )
{
continue;
}
// If it's the first time through the loop, or if we find an exact
// match with the settings we want, then remember them.
if ( width <= 0.0f || m_config.bpp == dm.dmBitsPerPel &&
m_config.screenWidth == dm.dmPelsWidth &&
m_config.screenHeight == dm.dmPelsHeight )
{
bool first( width <= 0.0f );
bpp = static_cast<int>( dm.dmBitsPerPel );
width = static_cast<float>( dm.dmPelsWidth );
height = static_cast<float>( dm.dmPelsHeight );
if ( ! first )
{
// No need to continue if we found a perfect match.
break;
}
}
// If we've found a partial match that has the precise width that we
// wanted, then bail now (assumes ordered by increasing width).
if ( width >= m_config.screenWidth &&
static_cast<float>( dm.dmPelsWidth ) > width )
{
break;
}
// Check to see whether the current mode is better than what we're
// currently going to use. This means that either the aspect ratio
// is closer to ideal, or it's the same but the bpp is closer to
// ideal, or that's the same too but the resolution is higher.
float diff( fabs( desired_ratio -
static_cast<float>( dm.dmPelsWidth ) /
static_cast<float>( dm.dmPelsHeight ) ) -
fabs( desired_ratio - width / height ) );
int dpp( abs( desired_bpp - static_cast<int>( dm.dmBitsPerPel ) ) -
abs( desired_bpp - bpp ) );
if ( diff < 0.0f || diff == 0.0f && dpp <= 0 ||
diff == 0.0f && dpp == 0 &&
width > static_cast<float>( dm.dmPelsWidth ) )
{
bpp = static_cast<int>( dm.dmBitsPerPel );
width = static_cast<float>( dm.dmPelsWidth );
height = static_cast<float>( dm.dmPelsHeight );
}
}
// Set the config to what we can support. This will be written to disk.
m_config.bpp = bpp;
m_config.screenWidth = static_cast<int>( width );
m_config.screenHeight = static_cast<int>( height );
}
//------------------------------------------------------------------------------
void
Engine::_initPhysics()
{
b2AABB worldAABB;
worldAABB.lowerBound.Set( -2500.0f, -2500.0f );
worldAABB.upperBound.Set( 2500.0f, 2500.0f );
b2Vec2 gravity( 0.0f, 10.0f );
m_b2d = new b2World( worldAABB, gravity, true );
m_dd = new DebugDraw( m_hge, m_vp );
m_b2d->SetDebugDraw( m_dd );
m_b2d->SetListener( static_cast< b2ContactListener *>( this ) );
m_b2d->SetListener( static_cast< b2BoundaryListener *>( this ) );
m_b2d->SetFilter( static_cast< b2ContactFilter *>( this ) );
}
//------------------------------------------------------------------------------
void
Engine::_loadData()
{
if ( ! m_hge->Resource_AttachPack( "resources.dat" ) )
{
error( "Cannot load '%s'", "resources.dat" );
}
m_rm = new hgeResourceManager( "data.res" );
m_rm->Precache();
m_hge->Resource_RemovePack( "resources.dat" );
}
//==============================================================================
| 25.953162 | 84 | 0.448069 | [
"render",
"vector"
] |
c3160735b90df4b86730dc64715e91cbdcb41299 | 841 | cpp | C++ | Cplus/LargestMultipleofThree.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/LargestMultipleofThree.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/LargestMultipleofThree.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
string largestMultipleOfThree(vector<int> &digits)
{
count = vector<int>(10);
sum = 0;
string res;
for (auto n : digits)
{
++count[n];
sum += n;
}
if (sum % 3 == 1)
{
if (!(f(1) || f(4) || f(7)))
f(2) || f(2) || f(5) || f(5) || f(8) || f(8);
}
else if (sum % 3 == 2)
{
if (!(f(2) || f(5) || f(8)))
f(1) || f(1) || f(4) || f(4) || f(7) || f(7);
}
for (int i = 9; i >= 0; --i)
{
while (--count[i] >= 0)
res.push_back(i + '0');
}
if (res.empty())
return "";
if (res[0] == '0')
return "0";
return res;
}
bool f(int index)
{
if (count[index] > 0)
{
--count[index];
sum -= index % 3;
}
return sum % 3 == 0;
}
private:
int sum;
vector<int> count;
}; | 15.017857 | 51 | 0.464923 | [
"vector"
] |
c31e048a322ffb90eff44f9f7707d74c1a1d33d4 | 4,449 | cpp | C++ | InteractiveGraphics/InteractiveGraphics/cubemap.cpp | centauroWaRRIor/InteractiveGraphics | d37cfc3213b52cf3644980f5461e131e1839e0ee | [
"MIT"
] | 4 | 2015-09-26T03:11:08.000Z | 2020-07-10T04:51:07.000Z | InteractiveGraphics/InteractiveGraphics/cubemap.cpp | centauroWaRRIor/InteractiveGraphics | d37cfc3213b52cf3644980f5461e131e1839e0ee | [
"MIT"
] | null | null | null | InteractiveGraphics/InteractiveGraphics/cubemap.cpp | centauroWaRRIor/InteractiveGraphics | d37cfc3213b52cf3644980f5461e131e1839e0ee | [
"MIT"
] | null | null | null | #include "cubemap.h"
CubeMap::CubeMap(const string & texFilename)
{
Texture masterTexObject(texFilename);
envMapResWidth = masterTexObject.getTexWidth() / 3;
envMapResHeight = masterTexObject.getTexHeight() / 4;
float envMapResHfov = 90.0f;
envMapN = 6;
cubeMapFacesCams = new PPC*[envMapN];
cubeMapFaces = new Texture*[envMapN];
for (unsigned int i = 0; i < envMapN; i++) {
cubeMapFacesCams[i] = new PPC(90.0f, envMapResWidth, envMapResHeight);
}
// build the cube map's six faces and cameras
cubeMapFaces[0] = new Texture(masterTexObject,
2 * envMapResWidth, 3 * envMapResWidth,
1 * envMapResHeight, 2 * envMapResHeight);
cubeMapFacesCams[0]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(1.0f, 0.0f, 0.0f), // look at pos x direction
V3(0.0f, 1.0f, 0.0f),
0.0f);
cubeMapFaces[1] = new Texture(masterTexObject,
0 * envMapResWidth, 1 * envMapResWidth,
1 * envMapResHeight, 2 * envMapResHeight);
cubeMapFacesCams[1]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(-1.0f, 0.0f, 0.0f), // look at neg x direction
V3(0.0f, 1.0f, 0.0f),
0.0f);
cubeMapFaces[2] = new Texture(masterTexObject,
1 * envMapResWidth, 2 * envMapResWidth,
3 * envMapResHeight, 4 * envMapResHeight);
cubeMapFaces[2]->flipAboutX();
cubeMapFaces[2]->flipAboutY();
cubeMapFacesCams[2]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(0.0f, 0.0f, 1.0f), // look at neg z direction
V3(0.0f, 1.0f, 0.0f),
0.0f);
cubeMapFaces[3] = new Texture(masterTexObject,
1 * envMapResWidth, 2 * envMapResWidth,
1 * envMapResHeight, 2 * envMapResHeight);
cubeMapFacesCams[3]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(0.0f, 0.0f, -1.0f), // look at pos z direction
V3(0.0f, 1.0f, 0.0f),
0.0f);
cubeMapFaces[4] = new Texture(masterTexObject,
1 * envMapResWidth, 2 * envMapResWidth,
0 * envMapResHeight, 1 * envMapResHeight);
cubeMapFacesCams[4]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(0.0f, 1.0f, 0.0f), // look at pos y direction
V3(0.0f, 0.0f, 1.0f),
0.0f);
cubeMapFaces[5] = new Texture(masterTexObject,
1 * envMapResWidth, 2 * envMapResWidth,
2 * envMapResHeight, 3 * envMapResHeight);
cubeMapFacesCams[5]->positionRelativeToPoint(
V3(0.0f, 0.0f, 0.0f),
V3(0.0f, -1.0f, 0.0f), // look at neg y direction
V3(0.0f, 0.0f, 1.0f),
0.0f);
// its the same for all cameras so it doesn't matter who
// supplies this value here.
cubeMapFocalLength = cubeMapFacesCams[0]->getFocalLength();
currentLookAtFace = 0;
}
CubeMap::~CubeMap()
{
for (unsigned int i = 0; i < envMapN; i++) {
delete cubeMapFacesCams[i];
delete cubeMapFaces[i];
}
delete[] cubeMapFacesCams;
delete[] cubeMapFaces;
}
Texture * CubeMap::getCubeFace(unsigned int i) const
{
if (i >= 6)
return nullptr;
else
return cubeMapFaces[i];
}
V3 CubeMap::getColor(const V3 & direction)
{
// use direction to create a 3D point at the focal plane.
V3 lookAt3DPoint = cubeMapCenter + (direction * cubeMapFocalLength);
V3 projectedPoint;
unsigned int returnColor;
bool isProjValid = false;
int timesTried = 0;
// find the face that sees this point but start by the one used last time
// to leverage locality principle.
while(timesTried < 6) {
isProjValid = cubeMapFacesCams[currentLookAtFace % 6]->project(lookAt3DPoint, projectedPoint);
// be very strict with the projection: no projection if:
// - point is left of view frustrum or is right of view frustrum
// - or is above view frustrum or is below of view frustrum
if (isProjValid &&
(projectedPoint[0] > 0.0f) && (projectedPoint[0] < envMapResWidth) &&
(projectedPoint[1] > 0.0f) && (projectedPoint[1] < envMapResHeight)) {
// go from x,y to s,t which ranges from [0,1]
float s = projectedPoint[0] / (envMapResWidth - 1.0f);
float t = projectedPoint[1] / (envMapResHeight - 1.0f);
// bilinear interpolation assumes t ranges [0,1] starting from the bottom of texture
// and since y screen goes from top to bottom we need to flip t here as well
t = (envMapResHeight - 1.0f) - t;
returnColor = cubeMapFaces[currentLookAtFace % 6]->sampleTexBilinearTile(s, t);
return V3(returnColor);
}
else {
currentLookAtFace++; // try with a different face of the cube
timesTried++;
}
}
// This should not ever happen. Any ray direction should be contained by a cubemap
return V3(255.0f/255.0f, 0.0f/255.0f, 128.0f/255.0f); // bright pink so its easy to spot if it ever happens (debug)
} | 32.955556 | 116 | 0.693189 | [
"3d"
] |
c329e2c664ba8ef8d367439b97f335c7bfa69bf8 | 1,949 | cpp | C++ | src/voxelization.cpp | dendisuhubdy/MinkowskiEngine | a1cdcba68ef925bfefed2fe161f62e1ec78573b9 | [
"MIT"
] | 1 | 2019-05-12T00:06:10.000Z | 2019-05-12T00:06:10.000Z | src/voxelization.cpp | dendisuhubdy/MinkowskiEngine | a1cdcba68ef925bfefed2fe161f62e1ec78573b9 | [
"MIT"
] | null | null | null | src/voxelization.cpp | dendisuhubdy/MinkowskiEngine | a1cdcba68ef925bfefed2fe161f62e1ec78573b9 | [
"MIT"
] | null | null | null | #include <cstdint>
#include "utils.hpp"
#include "voxelization.cuh"
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
std::vector<py::array_t<int>>
SparseVoxelization(py::array_t<uint64_t, py::array::c_style> keys,
py::array_t<int, py::array::c_style> labels,
int ignore_label, bool has_label) {
py::buffer_info keys_info = keys.request(), labels_info = labels.request();
if (keys_info.size != labels_info.size)
throw std::invalid_argument(
Formatter() << "Size of Keys and Labels mismatch. Size of keys: "
<< std::to_string(keys_info.size) << ", size of labels: "
<< std::to_string(labels_info.size));
int num_points = keys_info.size;
// Input pointers
uint64_t *p_keys = (uint64_t *)keys_info.ptr;
int *p_labels = (int *)labels_info.ptr;
// Return pointers
int *p_return_key_inds, *p_return_labels;
int final_n = sparse_voxelization(p_keys, p_labels, &p_return_key_inds,
&p_return_labels, num_points, ignore_label,
has_label);
py::array_t<int> return_key_inds = py::array_t<int>(final_n);
py::array_t<int> return_labels = py::array_t<int>(final_n);
py::buffer_info return_key_inds_info = return_key_inds.request(),
return_labels_info = return_labels.request();
int *p_py_return_key_inds = (int *)return_key_inds_info.ptr,
*p_py_return_labels = (int *)return_labels_info.ptr;
// Copy the temp outputs to the output numpy arrays
memcpy(p_py_return_key_inds, p_return_key_inds, final_n * sizeof(int));
memcpy(p_py_return_labels, p_return_labels, final_n * sizeof(int));
free(p_return_key_inds);
free(p_return_labels);
// Return a pair
std::vector<py::array_t<int>> return_vec;
return_vec.push_back(return_key_inds);
return_vec.push_back(return_labels);
return return_vec;
}
| 37.480769 | 79 | 0.676244 | [
"vector"
] |
c32e8c68c5787b2489e8a3cdc5f83cb6fcf89008 | 2,574 | cpp | C++ | leetcode/find_minimum_in_rotated_sorted_array/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | leetcode/find_minimum_in_rotated_sorted_array/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | leetcode/find_minimum_in_rotated_sorted_array/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <stack>
using namespace std;
class Solution {
public:
void findMin(vector<int>&nums, int start, int end, int &m)
{
if(start==end)
{
m = min(nums[start], nums[0]);
return;
}
if((start + 1) == end)
{
m = min(nums[start], nums[end]);
m = min(m, nums[0]);
return;
}
int mid = (start + end)/2;
//cout<<mid<<endl;
if((nums[mid] < nums[mid+1])&&(nums[mid]<nums[mid-1]))
{
if(nums[mid]<nums[0])
{
m = nums[mid];
}
else
{
m = nums[0];
}
}
else
{
if(nums[mid] > nums[0])
{
findMin(nums, mid+1, end, m);
}
else
{
findMin(nums, start, mid-1, m);
}
}
}
int findMin(vector<int>& nums) {
#if 0
int size = nums.size();
int ret = 0;
//nums.push_back(INT_MAX);
findMin(nums, 0, size-1, ret);
return ret;
#else
int start=0,end=nums.size()-1;
while (start<end) {
if (nums[start]<nums[end])
return nums[start];
int mid = (start+end)/2;
if (nums[mid]>=nums[start]) {
start = mid+1;
} else {
end = mid-1;
}
}
return nums[start];
#endif
}
};
int main(int argc, char *argv[])
{
Solution *S = new Solution();
int a1[] = {1};
int a2[] = {3,2};
int a3[] = {1,2,3};
int a4[] = {2,3,0,1};
int a5[] = {2,3,4,0,1};
int a6[] = {5,1,2,3,4};
vector<int> v1(a1,a1+1);
vector<int> v2(a2,a2+2);
vector<int> v3(a3,a3+3);
vector<int> v4(a4,a4+4);
vector<int> v5(a5,a5+5);
vector<int> v6(a6,a6+5);
cout << S->findMin(v1) << endl;
cout << S->findMin(v2) << endl;
cout << S->findMin(v3) << endl;
cout << S->findMin(v4) << endl;
cout << S->findMin(v5) << endl;
cout << S->findMin(v6) << endl;
return 0;
}
| 23.614679 | 66 | 0.395882 | [
"vector"
] |
c33b64d95927ef3355a3e97bf5b0cfc0839e5bd4 | 3,520 | cpp | C++ | datasets/github_cpp_10/10/61.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/10/61.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/10/61.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null |
#include "stdafx.h"
#include "CppUnitTest.h"
#include <vector>
#include <algorithm>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
#if 0
namespace SPOJ
{
int EditDistance(const string& first, const string& second)
{
const string& shorter = (first.length() <= second.length()) ? first : second;
const string& longer = (first.length() <= second.length()) ? second : first;
if (shorter.empty()) return longer.length();
vector<int> prev_i(shorter.length(), 0);
for (int k = 0; k < prev_i.size(); k++) prev_i[k] = k + 1;
for (int i = 0; i < longer.length(); i++)
{
vector<int> prev_j(shorter.length(), 0);
prev_j[0] = (shorter[0] == longer[i]) ? i : min(1 + i, 1+prev_i[0]);
for (int j = 1; j < shorter.length(); j++)
{
int cand = 1 + prev_i[j];
cand = min(cand, 1 + prev_j[j-1]);
if (shorter[j] == longer[i]) cand = min(cand, prev_i[j - 1]);
else cand = min(cand, 1 + prev_i[j - 1]);
prev_j[j] = cand;
}
prev_i = prev_j;
}
return prev_i.back();
}
#if 0
int main()
{
int tests;
cin >> tests;
vector<int> results;
for (int i = 0; i < tests; i++)
{
string first, second;
cin >> first;
cin >> second;
results.push_back(EditDistance(first, second));
}
for (auto r : results)
cout << r << endl;
char q;
cin >> q;
return 0;
}
#endif
TEST_CLASS(EDIST)
{
public:
TEST_METHOD(BaseCases)
{
Assert::AreEqual(0, EditDistance("", ""), L"both empty");
Assert::AreEqual(0, EditDistance("a", "a"), L"Equal strings");
Assert::AreEqual(1, EditDistance("a", "b"), L"Different");
}
TEST_METHOD(OneStringEmpty)
{
Assert::AreEqual(1, EditDistance("a", ""));
Assert::AreEqual(2, EditDistance("ab", ""));
Assert::AreEqual(3, EditDistance("", "abc"));
}
TEST_METHOD(SameLength_DifferInLastChar)
{
Assert::AreEqual(1, EditDistance("abc", "abd"));
}
TEST_METHOD(Postfix)
{
Assert::AreEqual(2, EditDistance("a", "abd"));
Assert::AreEqual(4, EditDistance("abd", "abdefgh"));
Assert::AreEqual(5, EditDistance("abdefghi", "abd"));
}
TEST_METHOD(Prefix)
{
Assert::AreEqual(2, EditDistance("d", "abd"));
Assert::AreEqual(3, EditDistance("de", "abcde"));
}
TEST_METHOD(Circumfix)
{
Assert::AreEqual(2, EditDistance("b", "abd"));
Assert::AreEqual(5, EditDistance("b", "axbdyz"));
}
TEST_METHOD(AllDifferent)
{
Assert::AreEqual(7, EditDistance("abcd", "prqstuv"));
}
TEST_METHOD(SameStrings)
{
Assert::AreEqual(0, EditDistance("prqstuv", "prqstuv"));
}
TEST_METHOD(FromSpoj)
{
Assert::AreEqual(4, EditDistance("MONEY", "FOOD"));
}
TEST_METHOD(ShiftedBlocks)
{
Assert::AreEqual(6 + 3, EditDistance("abcdefabcdef", "xyzabcxyzabc"));
Assert::AreEqual(6 + 3 * 3, EditDistance("abcdefabcdefabcdefabcdef", "xyzabcxyzabcxyzabcxyzabc"));
Assert::AreEqual(6 + 3 * 4, EditDistance("abcdefabcdefabcdefabcdefabcdef", "xyzabcxyzabcxyzabcxyzabcxyzabc"));
}
TEST_METHOD(Cycle)
{
Assert::AreEqual(2, EditDistance("ab", "ba"));
Assert::AreEqual(4, EditDistance("abcd", "cdab"));
Assert::AreEqual(6, EditDistance("abcdefghijk", "defghijkabc"));
}
TEST_METHOD(LongStrings)
{
string first = "";
for (int i = 0; i < 200; i++) first.append("abcdefghij");
string second = "";
for (int i = 0; i < 200; i++) second.append("vwxyzabcde");
Assert::AreEqual(0, EditDistance(first, first));
Assert::AreEqual(10 + 5*199, EditDistance(first, second));
}
};
}
#endif | 23.157895 | 113 | 0.623295 | [
"vector"
] |
c34c2cc55f0d1123f1d90621b1b6d5670115b095 | 3,408 | hpp | C++ | library/cgp/files/files.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | library/cgp/files/files.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | 2 | 2022-03-03T16:34:03.000Z | 2022-03-20T13:08:56.000Z | library/cgp/files/files.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | #pragma once
#include "cgp/containers/containers.hpp"
#include <string>
#include <sstream>
#include <fstream>
namespace cgp
{
/** Ensure that a file already exists and is accessible
* Display an error message with some reminder on path setting in case the file cannot be accessed */
void assert_file_exist(std::string const& filename);
/** Return true if the file can be accessed, false otherwise */
bool check_file_exist(std::string const& filename);
/** Return the size in octets of a file*/
size_t file_get_size(std::string const& filename);
/** Read the entire content of a file as binary vector of octets*/
std::vector <char> read_from_file_binary(std::string const& filename);
std::string read_text_file(std::string const& filename);
template <typename T> void read_from_file(std::string const& filename, T& data);
template <typename T> void read_from_file(std::string const& filename, buffer<buffer<T>>& data);
template <typename T> std::istream& read_from_stream(std::istream& stream, T& data);
template <typename T, int N> std::istream& read_from_stream(std::istream& stream, buffer_stack<T,N>& data);
template <typename T> std::istream& read_line_from_stream(std::istream& stream, T& data);
template <typename T> std::istream& read_from_stream(std::istream& stream, buffer<T>& data);
template <typename T> std::istream& read_from_stream_per_line(std::istream& stream, buffer<T>& data);
}
namespace cgp
{
template <typename T>
std::istream& read_from_stream(std::istream& stream, T& data)
{
stream >> data;
return stream;
}
template <typename T, int N>
std::istream& read_from_stream(std::istream& stream, buffer_stack<T, N>& data)
{
for (int k = 0; k < N && stream.good(); ++k)
read_from_stream(stream, data[k]);
return stream;
}
template <typename T>
std::istream& read_line_from_stream(std::istream& stream, T& data)
{
if(stream.good()) {
std::string line;
std::getline(stream, line);
if(stream.good())
{
std::istringstream stream_line(line);
read_from_stream(stream_line, data);
}
}
return stream;
}
template <typename T>
std::istream& read_from_stream(std::istream& stream, buffer<T>& data)
{
while(stream.good()) {
T temp;
read_from_stream(stream, temp);
if(stream)
data.push_back(temp);
}
return stream;
}
template <typename T>
std::istream& read_from_stream_per_line(std::istream& stream, buffer<T>& data)
{
while(stream.good()) {
T temp;
read_line_from_stream(stream, temp);
if(stream.good())
data.push_back(temp);
}
return stream;
}
template <typename T>
void read_from_file(std::string const& filename, T& data)
{
assert_file_exist(filename);
// Open file with pointer at last position
std::ifstream stream(filename);
assert_cgp_no_msg(stream.is_open());
read_from_stream(stream, data);
stream.close();
assert_cgp_no_msg(!stream.is_open());
}
template <typename T>
void read_from_file(std::string const& filename, buffer<buffer<T>>& data)
{
assert_file_exist(filename);
// Open file with pointer at last position
std::ifstream stream(filename);
assert_cgp_no_msg(stream.is_open());
read_from_stream_per_line(stream, data);
stream.close();
assert_cgp_no_msg(!stream.is_open());
}
} | 26.834646 | 109 | 0.685153 | [
"vector"
] |
c35644ebe72beb762d01a36c587b872ae314396c | 197 | cc | C++ | packages/test-addon/test.cc | c0un7-z3r0/goingnative | bfdc437383df849f5f9aab6028933cb490eac272 | [
"MIT"
] | null | null | null | packages/test-addon/test.cc | c0un7-z3r0/goingnative | bfdc437383df849f5f9aab6028933cb490eac272 | [
"MIT"
] | 1 | 2021-09-02T03:00:33.000Z | 2021-09-02T03:00:33.000Z | packages/test-addon/test.cc | c0un7-z3r0/goingnative | bfdc437383df849f5f9aab6028933cb490eac272 | [
"MIT"
] | null | null | null | #include <nan.h>
using namespace v8;
void Init(Handle<Object> exports) {
Nan::Set(exports, Nan::New("test").ToLocalChecked(),
Nan::New("OK").ToLocalChecked());
}
NODE_MODULE(test, Init)
| 17.909091 | 54 | 0.670051 | [
"object"
] |
c35f1584fcb669aa5060d03b5f46728118c39894 | 2,186 | hpp | C++ | Tank/LinuxPWMDriver/LinuxPWMDriverComponentImpl.hpp | joekale/fprime | 2d8231ed43316f886415fad65805f09860bda57a | [
"Apache-2.0"
] | 1 | 2021-04-19T14:06:23.000Z | 2021-04-19T14:06:23.000Z | Tank/LinuxPWMDriver/LinuxPWMDriverComponentImpl.hpp | joekale/fprime | 2d8231ed43316f886415fad65805f09860bda57a | [
"Apache-2.0"
] | null | null | null | Tank/LinuxPWMDriver/LinuxPWMDriverComponentImpl.hpp | joekale/fprime | 2d8231ed43316f886415fad65805f09860bda57a | [
"Apache-2.0"
] | null | null | null | // ======================================================================
// \title LinuxPWMDriverComponentImpl.hpp
// \author joe
// \brief hpp file for LinuxPWMDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef LinuxPWMDriver_HPP
#define LinuxPWMDriver_HPP
#include "Tank/LinuxPWMDriver/LinuxPWMDriverComponentAc.hpp"
#define DEFAULT_PERIOD 10000000
namespace Tank {
class LinuxPWMDriverComponentImpl :
public LinuxPWMDriverComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! configure GPIO
enum PWMPolarity {
PWM_NORMAL, //!< normal
PWM_INVERSE, //!< inverse
};
//! Construct object LinuxPWMDriver
//!
LinuxPWMDriverComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object LinuxPWMDriver
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! open GPIO
bool open(NATIVE_INT_TYPE pwm, PWMPolarity polarity);
//! Destroy object LinuxPWMDriver
//!
~LinuxPWMDriverComponentImpl(void);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for dutyCycleWrite
//!
void dutyCycleWrite_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
F32 duty_cycle /*!< percent of period to set duty cycle between 0 and 1*/
);
U32 period;
PWMPolarity polarity;
NATIVE_INT_TYPE m_fd;
NATIVE_INT_TYPE m_pwm;
};
} // end namespace Tank
#endif
| 27.325 | 83 | 0.518298 | [
"object"
] |
c369ea95209b7f670b534e9cdcbc649de2a133a0 | 1,024 | cpp | C++ | 42.Trapping Rain Water/main.cpp | Kingpie/leetcode | b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f | [
"Apache-2.0"
] | null | null | null | 42.Trapping Rain Water/main.cpp | Kingpie/leetcode | b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f | [
"Apache-2.0"
] | null | null | null | 42.Trapping Rain Water/main.cpp | Kingpie/leetcode | b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f | [
"Apache-2.0"
] | null | null | null | /*Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
//area
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
int s1=0,s2=0,max1=0,max2=0;
int water = 0,sum=0;
for(int i = 0; i < n;++i){
if(height[i]>max1){
max1=height[i];
}
if(height[n-i-1]>max2){
max2 = height[n-i-1];
}
s1 += max1;
s2 += max2;
sum+=height[i];
}
water = s1+s2-max1*n-sum;
return water;
}
};
| 26.947368 | 187 | 0.571289 | [
"vector"
] |
c373ef828e781f6552ce3c5dd6bbdbf50b228e93 | 9,129 | cpp | C++ | test/test_instruction.cpp | stfnwong/z8t | f1721671886d312f23bc34ba48b313f57b0be75c | [
"MIT"
] | null | null | null | test/test_instruction.cpp | stfnwong/z8t | f1721671886d312f23bc34ba48b313f57b0be75c | [
"MIT"
] | null | null | null | test/test_instruction.cpp | stfnwong/z8t | f1721671886d312f23bc34ba48b313f57b0be75c | [
"MIT"
] | null | null | null | /*
* TEST_INSTRUCTION
*/
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include "Instruction.hpp"
TEST_CASE("test_all_instructions", "[sanity]")
{
const std::vector<LineInfo> input_instrs = {
// adds
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "a")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_B, "b")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_C, "c")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_D, "d")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_E, "e")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_H, "h")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_L, "l")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_HL_IND, "(hl)")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_A, "a"), Token(SYM_LITERAL, 128, "128")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_HL, "hl"), Token(SYM_REG, REG_BC, "bc")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_HL, "hl"), Token(SYM_REG, REG_DE, "de")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_HL, "hl"), Token(SYM_REG, REG_HL, "a")),
LineInfo(Token(SYM_INSTR, INSTR_ADD, "add"), Token(SYM_REG, REG_HL, "hl"), Token(SYM_REG, REG_SP, "sp")),
// adc
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "a")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_B, "b")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_C, "c")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_D, "d")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_E, "e")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_H, "h")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_L, "l")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_HL_IND, "(hl)")),
LineInfo(Token(SYM_INSTR, INSTR_ADC, "adc"), Token(SYM_REG, REG_A, "a"), Token(SYM_LITERAL, 128, "128")),
// and
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_AND, "and"), Token(SYM_REG, REG_A, "a"), Token()),
// cp
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_CP, "cp"), Token(SYM_REG, REG_A, "a"), Token()),
// inc
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_INC, "inc"), Token(SYM_REG, REG_A, "a"), Token()),
// jr
LineInfo(Token(SYM_INSTR, INSTR_JR, "jr"), Token(SYM_LITERAL, 64, "64"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_JR, "jr"), Token(SYM_COND, COND_Z, "z"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JR, "jr"), Token(SYM_COND, COND_C, "c"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JR, "jr"), Token(SYM_COND, COND_NZ, "nz"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JR, "jr"), Token(SYM_COND, COND_NC, "nc"), Token(SYM_LITERAL, 32, "32")),
// jp
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_NZ, "nz"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_NC, "nc"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_PO, "po"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_P, "p"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_LITERAL, 196, "196"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_REG, REG_HL_IND, "(hl)"), Token()),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_Z, "z"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_C, "c"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_PE, "pe"), Token(SYM_LITERAL, 32, "32")),
LineInfo(Token(SYM_INSTR, INSTR_JP, "jp"), Token(SYM_COND, COND_M, "m"), Token(SYM_LITERAL, 32, "32")),
// loads (actually not worth doing all the loads, just the more awkward/complex ones)
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "a")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "b")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "c")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "d")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "e")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "h")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_A, "a"), Token(SYM_REG, REG_A, "l")),
// load immediates
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_BC, "bc"), Token(SYM_LITERAL, 200, "200")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_DE, "de"), Token(SYM_LITERAL, 200, "200")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_SP, "sp"), Token(SYM_LITERAL, 200, "200")),
//
//LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_LITERAL_IND, 8, "(8)"), Token(SYM_REG, REG_HL, "hl")),
LineInfo(Token(SYM_INSTR, INSTR_LD, "ld"), Token(SYM_REG, REG_H, "h"), Token(SYM_REG, REG_HL_IND, "(hl)")),
};
std::cout << std::dec << input_instrs.size() << " instructions in test" << std::endl;
for(unsigned int idx = 0; idx < input_instrs.size(); ++idx)
{
uint32_t line_hash = input_instrs[idx].argHash();
auto lookup_val = instr_hash_to_code.find(line_hash);
if(lookup_val == instr_hash_to_code.end())
{
std::cout << "Error in instruction [" << std::dec << idx << "/" << std::dec << input_instrs.size() << "] : "
<< input_instrs[idx].toInstrString() << std::endl;
}
REQUIRE(lookup_val != instr_hash_to_code.end());
}
}
| 75.446281 | 121 | 0.617702 | [
"vector"
] |
c3803833941493ca1f21dada2f61f1a72dd76eaa | 8,441 | cpp | C++ | vtkMAF/Testing/vtkMAFTextActorMeterTest.cpp | FusionBox2/MAF2 | b576955f4f6b954467021f12baedfebcaf79a382 | [
"Apache-2.0"
] | 1 | 2018-01-23T09:13:40.000Z | 2018-01-23T09:13:40.000Z | vtkMAF/Testing/vtkMAFTextActorMeterTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | null | null | null | vtkMAF/Testing/vtkMAFTextActorMeterTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | 3 | 2020-09-24T16:04:53.000Z | 2020-09-24T16:50:30.000Z | /*=========================================================================
Program: MAF2
Module: vtkMAFTextActorMeterTest
Authors: Daniele Giunchi
Copyright (c) B3C
All rights reserved. See Copyright.txt or
http://www.scsitaly.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include <cppunit/config/SourcePrefix.h>
#include "vtkMAFTextActorMeter.h"
#include "vtkMAFTextActorMeterTest.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkMAFSmartPointer.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkWindowToImageFilter.h"
#include "vtkImageMathematics.h"
#include "vtkImageData.h"
#include "vtkJPEGWriter.h"
#include "vtkJPEGReader.h"
#include "vtkPointData.h"
void vtkMAFTextActorMeterTest::setUp()
{
}
void vtkMAFTextActorMeterTest::tearDown()
{
}
void vtkMAFTextActorMeterTest::TestFixture()
{
}
//------------------------------------------------------------
void vtkMAFTextActorMeterTest::RenderData(vtkActor2D *actor)
//------------------------------------------------------------
{
vtkMAFSmartPointer<vtkRenderer> renderer;
renderer->SetBackground(0.0, 0.0, 0.0);
vtkCamera *camera = renderer->GetActiveCamera();
camera->ParallelProjectionOn();
camera->Modified();
vtkMAFSmartPointer<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetSize(640, 480);
renderWindow->SetPosition(100,0);
vtkMAFSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor2D(actor);
renderWindow->Render();
//renderWindowInteractor->Start();
CompareImages(renderWindow);
#ifdef WIN32
Sleep(2000);
#else
usleep(2000*1000);
#endif
}
//------------------------------------------------------------------
void vtkMAFTextActorMeterTest::SetText(vtkMAFTextActorMeter *actor, const char *text, double position[3])
//------------------------------------------------------------------
{
if(actor)
{
actor->SetVisibility(true);
actor->SetText(text);
actor->SetTextPosition(position);
}
}
//------------------------------------------------------------
void vtkMAFTextActorMeterTest::TestDynamicAllocation()
//------------------------------------------------------------
{
vtkMAFTextActorMeter *to = vtkMAFTextActorMeter::New();
to->Delete();
}
//--------------------------------------------
void vtkMAFTextActorMeterTest::TestTextPos1()
//--------------------------------------------
{
m_TestNumber = ID_TEXT_TEST_POS1;
vtkMAFTextActorMeter *actor;
actor = vtkMAFTextActorMeter::New();
std::string text = "String Text Test 1";
double position[3] = {0.1,0.1,0.};
text += " pos->";
text += ConvertDouble(position[0]);
text += " ";
text += ConvertDouble(position[1]);
text += " ";
text += ConvertDouble(position[2]);
SetText(actor, text.c_str(), position);
//test GetText
CPPUNIT_ASSERT(strcmp(actor->GetText(),text.c_str())==0);
RenderData(actor);
actor->Delete();
}
//--------------------------------------------
void vtkMAFTextActorMeterTest::TestTextPos2()
//--------------------------------------------
{
m_TestNumber = ID_TEXT_TEST_POS2;
vtkMAFTextActorMeter *actor;
actor = vtkMAFTextActorMeter::New();
std::string text = "String Text Test 2";
double position[3] = {0.05,0.05,0.};
text += " pos->";
text += ConvertDouble(position[0]);
text += " ";
text += ConvertDouble(position[1]);
text += " ";
text += ConvertDouble(position[2]);
SetText(actor, text.c_str(), position);
//test GetText
CPPUNIT_ASSERT(strcmp(actor->GetText(),text.c_str())==0);
RenderData(actor);
actor->Delete();
}
//--------------------------------------------
void vtkMAFTextActorMeterTest::TestTextColor()
//--------------------------------------------
{
m_TestNumber = ID_TEXT_COLOR_TEST;
vtkMAFTextActorMeter *actor;
actor = vtkMAFTextActorMeter::New();
std::string text = "String Text Test Color";
double position[3] = {0.05,0.05,0.};
text += " pos->";
text += ConvertDouble(position[0]);
text += " ";
text += ConvertDouble(position[1]);
text += " ";
text += ConvertDouble(position[2]);
SetText(actor, text.c_str(), position);
actor->SetColor(1.0, 0.0, 0.0);
RenderData(actor);
actor->Delete();
}
//----------------------------------------------------------------------------
void vtkMAFTextActorMeterTest::CompareImages(vtkRenderWindow * renwin)
//----------------------------------------------------------------------------
{
char *file = __FILE__;
std::string name(file);
std::string path(file);
int slashIndex = name.find_last_of('\\');
name = name.substr(slashIndex+1);
path = path.substr(0,slashIndex);
int pointIndex = name.find_last_of('.');
name = name.substr(0, pointIndex);
std::string controlOriginFile;
controlOriginFile+=(path.c_str());
controlOriginFile+=("\\");
controlOriginFile+=(name.c_str());
controlOriginFile+=("_");
controlOriginFile+=("image");
controlOriginFile+=vtkMAFTextActorMeterTest::ConvertInt(m_TestNumber).c_str();
controlOriginFile+=(".jpg");
fstream controlStream;
controlStream.open(controlOriginFile.c_str());
// visualization control
renwin->OffScreenRenderingOn();
vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
w2i->SetInput(renwin);
//w2i->SetMagnification(magnification);
w2i->Update();
renwin->OffScreenRenderingOff();
//write comparing image
vtkJPEGWriter *w = vtkJPEGWriter::New();
w->SetInput(w2i->GetOutput());
std::string imageFile="";
if(!controlStream)
{
imageFile+=(path.c_str());
imageFile+=("\\");
imageFile+=(name.c_str());
imageFile+=("_");
imageFile+=("image");
}
else
{
imageFile+=(path.c_str());
imageFile+=("\\");
imageFile+=(name.c_str());
imageFile+=("_");
imageFile+=("comp");
}
imageFile+=vtkMAFTextActorMeterTest::ConvertInt(m_TestNumber).c_str();
imageFile+=(".jpg");
w->SetFileName(imageFile.c_str());
w->Write();
if(!controlStream)
{
controlStream.close();
w->Delete();
w2i->Delete();
return;
}
controlStream.close();
//read original Image
vtkJPEGReader *rO = vtkJPEGReader::New();
std::string imageFileOrig="";
imageFileOrig+=(path.c_str());
imageFileOrig+=("\\");
imageFileOrig+=(name.c_str());
imageFileOrig+=("_");
imageFileOrig+=("image");
imageFileOrig+=vtkMAFTextActorMeterTest::ConvertInt(m_TestNumber).c_str();
imageFileOrig+=(".jpg");
rO->SetFileName(imageFileOrig.c_str());
rO->Update();
vtkImageData *imDataOrig = rO->GetOutput();
//read compared image
vtkJPEGReader *rC = vtkJPEGReader::New();
rC->SetFileName(imageFile.c_str());
rC->Update();
vtkImageData *imDataComp = rC->GetOutput();
vtkImageMathematics *imageMath = vtkImageMathematics::New();
imageMath->SetInput1(imDataOrig);
imageMath->SetInput2(imDataComp);
imageMath->SetOperationToSubtract();
imageMath->Update();
double srR[2] = {-1,1};
imageMath->GetOutput()->GetPointData()->GetScalars()->GetRange(srR);
CPPUNIT_ASSERT(srR[0] == 0.0 && srR[1] == 0.0);
// end visualization control
rO->Delete();
rC->Delete();
imageMath->Delete();
w->Delete();
w2i->Delete();
}
//----------------------------------------------------------------------------
void vtkMAFTextActorMeterTest::TestPrintSelf()
//----------------------------------------------------------------------------
{
vtkMAFTextActorMeter *actor;
actor = vtkMAFTextActorMeter::New();
actor->PrintSelf(std::cout, 3);
actor->Delete();
}
//--------------------------------------------------
std::string vtkMAFTextActorMeterTest::ConvertInt(int number)
//--------------------------------------------------
{
std::stringstream stringStream;
stringStream << number;//add number to the stream
return stringStream.str();//return a string with the contents of the stream
}
//--------------------------------------------------
std::string vtkMAFTextActorMeterTest::ConvertDouble(double number)
//--------------------------------------------------
{
std::ostringstream strs;
strs << number;
return strs.str();
}
| 27.229032 | 105 | 0.590451 | [
"render"
] |
c385c85f7f66638b49cdb780ffd6ebaa5f36bcdd | 5,043 | cpp | C++ | Firmware/src/commands.cpp | SFaull/SerialDisplay | 8fb8e6ad34f284d9adb31111ee64d01662ca5245 | [
"Unlicense"
] | null | null | null | Firmware/src/commands.cpp | SFaull/SerialDisplay | 8fb8e6ad34f284d9adb31111ee64d01662ca5245 | [
"Unlicense"
] | null | null | null | Firmware/src/commands.cpp | SFaull/SerialDisplay | 8fb8e6ad34f284d9adb31111ee64d01662ca5245 | [
"Unlicense"
] | null | null | null |
#include <SerialCommand.h>
#include <TFT_eSPI.h> // Hardware-specific library
#include "commands.h"
#include "image.h"
#define DISPLAY_WIDTH 240
#define DISPLAY_HEIGHT 240
#define DISPLAY_PIXELS (DISPLAY_WIDTH * DISPLAY_HEIGHT)
#define MAX_DISPLAY_BLOCK_SIZE 110
#define MAX_DISPLAY_BLOCK_PIXELS (MAX_DISPLAY_BLOCK_SIZE * MAX_DISPLAY_BLOCK_SIZE)
uint16_t display_buffer[MAX_DISPLAY_BLOCK_PIXELS] = {0};
SerialCommand sCmd; // The demo SerialCommand object
TFT_eSPI tft = TFT_eSPI(); // Invoke custom library
static void idn(void);
static void display_set_rotation(void);
static void display_block(void);
static void print_buffer(void);
static void unrecognized(const char *command);
void Commands::init()
{
tft.init();
tft.setSwapBytes(true); // Swap the byte order for pushImage() - corrects endianness
tft.fillScreen(TFT_BLACK);
//tft.pushImage(179,0,DISPLAY_BLOCK_SIZE,DISPLAY_BLOCK_SIZE,image);
sCmd.addCommand("*IDN?", idn); // Echos the string argument back
sCmd.addCommand("DISPLAY", display_block); // Echos the string argument back
sCmd.addCommand("BUFFER?", print_buffer); // Echos the string argument back
sCmd.addCommand("ROTATION", display_set_rotation);
sCmd.setDefaultHandler(unrecognized); // Handler for command that isn't matched (says "What?")
}
void Commands::process()
{
sCmd.readSerial(); // We don't do much, just process serial commands
}
static void idn() {
SerialUSB.println("Xiao");
}
static void display_set_rotation() {
char *arg; // expect 1 arguments
arg = sCmd.next();
if(arg == NULL)
{
SerialUSB.println("Inavlid Args");
return; // any missing args and we exit the function
}
// convert ASCII parameters to integers
int rotation = atoi(arg);
if(rotation < 0 || rotation > 3)
{
SerialUSB.println("Inavlid Args");
return; // any missing args and we exit the function
}
tft.setRotation(rotation);
}
static void display_block() {
const uint8_t argc = 4;
char *arg[argc]; // expect 4 arguments
// Get the next argument from the SerialCommand object buffer
for(uint8_t i = 0 ; i < argc; i++)
{
arg[i] = sCmd.next();
if(arg[i] == NULL)
{
SerialUSB.println("Inavlid Args");
return; // any missing args and we exit the function
}
}
// convert ASCII parameters to integers
int x = atoi(arg[0]);
int y = atoi(arg[1]);
int w = atoi(arg[2]);
int h = atoi(arg[3]);
// check args are in valid range
if(w * h > MAX_DISPLAY_BLOCK_PIXELS)
{
//SerialUSB.println("Too large");
return;
}
#if 0
if(((x + w) >= DISPLAY_WIDTH) || ((y+h) >= DISPLAY_WIDTH))
{
//SerialUSB.println("Too large");
//return;
}
#endif
long pixelsRemaining = w * h;
// workout where in the display buffer we are starting based on the provided offset
//long offset = (y * DISPLAY_WIDTH) + x;
// create a pointer to that position in the buffer
uint16_t * ptr = display_buffer;
// now lets read the raw data into the buffer
while(pixelsRemaining > 0)
{
// read two bytes at a time
char pixel[2];
while(!SerialUSB.available()) {}; // wait until bytes available
uint8_t bytesReceived = SerialUSB.readBytes(pixel, 2);
if(bytesReceived != 2)
{
SerialUSB.println("Error receiving image");
return;
}
// store this in the uint16_t buffer
//*ptr = ( (pixel[0] * 0xFF) | (pixel[1] >> 8) );
*ptr = ((pixel[0]<<8)+pixel[1]);
// increment the buffer and decrement the pixels remaing counter
ptr++;
pixelsRemaining--;
}
//now lets actually display the image
tft.pushImage(x,y,w,h,display_buffer);
#if 0
for(long i = 0; i < (w * h); i++)
{
SerialUSB.print(display_buffer[i], HEX);
if((i % DISPLAY_BLOCK_SIZE) == 59)
SerialUSB.println();
else
SerialUSB.print(",");
}
#endif
}
static void print_buffer()
{
const uint8_t argc = 2;
char *arg[argc]; // expect 2 arguments
// Get the next argument from the SerialCommand object buffer
for(uint8_t i = 0 ; i < argc; i++)
{
arg[i] = sCmd.next();
if(arg[i] == NULL)
{
SerialUSB.println("Inavlid Args");
return; // any missing args and we exit the function
}
}
int offset = atoi(arg[0]);
int len = atoi(arg[1]);
uint16_t * ptr = &display_buffer[offset];
while(len > 0)
{
SerialUSB.print(*ptr, HEX);
ptr++;
len--;
if(len == 0)
SerialUSB.println("");
else
SerialUSB.print(", ");
}
}
// This gets set as the default handler, and gets called when no other command matches.
static void unrecognized(const char *command) {
SerialUSB.println("What?");
}
| 26.129534 | 102 | 0.606583 | [
"object"
] |
c3873745f375a97f91a40492a9dc52e2d8715e90 | 14,632 | cpp | C++ | src/prod/src/api/wrappers/ComInfrastructureServiceAgent.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/api/wrappers/ComInfrastructureServiceAgent.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/api/wrappers/ComInfrastructureServiceAgent.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Api;
using namespace ServiceModel;
// ********************************************************************************************************************
// ComAsyncOperationContext Classes
//
class ComInfrastructureServiceAgent::ComStartInfrastructureTaskAsyncOperation : public ComAsyncOperationContext
{
DENY_COPY(ComStartInfrastructureTaskAsyncOperation);
public:
ComStartInfrastructureTaskAsyncOperation(
__in IInfrastructureServiceAgent & impl,
FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription)
: ComAsyncOperationContext()
, impl_(impl)
, taskDescription_(taskDescription)
, timeout_(TimeSpan::Zero)
{
}
virtual ~ComStartInfrastructureTaskAsyncOperation() { }
HRESULT Initialize(
__in ComponentRootSPtr const & rootSPtr,
__in DWORD timeoutMilliseconds,
__in IFabricAsyncOperationCallback * callback)
{
HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback);
if (SUCCEEDED(hr))
{
timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds);
}
return hr;
}
static HRESULT End(__in IFabricAsyncOperationContext * context)
{
if (context == NULL) { return E_POINTER; }
ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext);
return thisCPtr->End();
}
protected:
virtual void OnStart(AsyncOperationSPtr const & proxySPtr)
{
auto operation = impl_.BeginStartInfrastructureTask(
taskDescription_,
timeout_,
[this](AsyncOperationSPtr const & operation) { this->OnStartInfrastructureTaskComplete(operation, false); },
proxySPtr);
this->OnStartInfrastructureTaskComplete(operation, true);
}
private:
void OnStartInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
ErrorCode error = impl_.EndStartInfrastructureTask(operation);
this->TryComplete(operation->Parent, error.ToHResult());
}
IInfrastructureServiceAgent & impl_;
FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription_;
TimeSpan timeout_;
};
class ComInfrastructureServiceAgent::ComFinishInfrastructureTaskAsyncOperation : public ComAsyncOperationContext
{
DENY_COPY(ComFinishInfrastructureTaskAsyncOperation);
public:
ComFinishInfrastructureTaskAsyncOperation(
__in IInfrastructureServiceAgent & impl,
wstring const & taskId,
uint64 instanceId)
: ComAsyncOperationContext()
, impl_(impl)
, taskId_(taskId)
, instanceId_(instanceId)
, timeout_(TimeSpan::Zero)
{
}
virtual ~ComFinishInfrastructureTaskAsyncOperation() { }
HRESULT Initialize(
__in ComponentRootSPtr const & rootSPtr,
__in DWORD timeoutMilliseconds,
__in IFabricAsyncOperationCallback * callback)
{
HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback);
if (SUCCEEDED(hr))
{
timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds);
}
return hr;
}
static HRESULT End(__in IFabricAsyncOperationContext * context)
{
if (context == NULL) { return E_POINTER; }
ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext);
return thisCPtr->End();
}
protected:
virtual void OnStart(AsyncOperationSPtr const & proxySPtr)
{
auto operation = impl_.BeginFinishInfrastructureTask(
taskId_,
instanceId_,
timeout_,
[this](AsyncOperationSPtr const & operation) { this->OnFinishInfrastructureTaskComplete(operation, false); },
proxySPtr);
this->OnFinishInfrastructureTaskComplete(operation, true);
}
private:
void OnFinishInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
ErrorCode error = impl_.EndFinishInfrastructureTask(operation);
this->TryComplete(operation->Parent, error.ToHResult());
}
IInfrastructureServiceAgent & impl_;
wstring taskId_;
uint64 instanceId_;
TimeSpan timeout_;
};
// {34a16309-07f5-49c6-bac9-626d181a2e52}
static const GUID CLSID_ComQueryInfrastructureTaskAsyncOperation =
{ 0x34a16309, 0x07f5, 0x49c6, { 0xba, 0xc9, 0x62, 0x6d, 0x18, 0x1a, 0x2e, 0x52 } };
class ComInfrastructureServiceAgent::ComQueryInfrastructureTaskAsyncOperation : public ComAsyncOperationContext
{
DENY_COPY(ComQueryInfrastructureTaskAsyncOperation);
COM_INTERFACE_AND_DELEGATE_LIST(
ComQueryInfrastructureTaskAsyncOperation,
CLSID_ComQueryInfrastructureTaskAsyncOperation,
ComQueryInfrastructureTaskAsyncOperation,
ComAsyncOperationContext)
public:
ComQueryInfrastructureTaskAsyncOperation(
__in IInfrastructureServiceAgent & impl)
: ComAsyncOperationContext()
, impl_(impl)
, timeout_(TimeSpan::Zero)
{
}
virtual ~ComQueryInfrastructureTaskAsyncOperation() { }
HRESULT Initialize(
__in ComponentRootSPtr const & rootSPtr,
__in DWORD timeoutMilliseconds,
__in IFabricAsyncOperationCallback * callback)
{
HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback);
if (SUCCEEDED(hr))
{
timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds);
}
return hr;
}
static HRESULT End(__in IFabricAsyncOperationContext * context, __out IFabricInfrastructureTaskQueryResult ** result)
{
if ((context == NULL) || (result == NULL))
{
return E_POINTER;
}
ComPointer<ComQueryInfrastructureTaskAsyncOperation> thisCPtr(context, CLSID_ComQueryInfrastructureTaskAsyncOperation);
auto hr = thisCPtr->Result;
if (SUCCEEDED(hr))
{
vector<InfrastructureTaskQueryResult> resultList;
auto error = thisCPtr->nativeResult_.MoveList(resultList);
if (error.IsSuccess())
{
ComPointer<IFabricInfrastructureTaskQueryResult> cPtr = make_com<ComQueryResult, IFabricInfrastructureTaskQueryResult>(move(resultList));
hr = cPtr->QueryInterface(IID_IFabricInfrastructureTaskQueryResult, reinterpret_cast<void**>(result));
}
else
{
hr = error.ToHResult();
}
}
return hr;
}
protected:
virtual void OnStart(AsyncOperationSPtr const & proxySPtr)
{
auto operation = impl_.BeginQueryInfrastructureTask(
timeout_,
[this](AsyncOperationSPtr const & operation) { this->OnQueryInfrastructureTaskComplete(operation, false); },
proxySPtr);
this->OnQueryInfrastructureTaskComplete(operation, true);
}
private:
void OnQueryInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
auto error = impl_.EndQueryInfrastructureTask(operation, nativeResult_);
this->TryComplete(operation->Parent, error.ToHResult());
}
IInfrastructureServiceAgent & impl_;
QueryResult nativeResult_;
TimeSpan timeout_;
};
class ComInfrastructureServiceAgent::ComQueryResult
: public IFabricInfrastructureTaskQueryResult
, private Common::ComUnknownBase
{
DENY_COPY_ASSIGNMENT(ComQueryResult)
BEGIN_COM_INTERFACE_LIST(ComQueryResult)
COM_INTERFACE_ITEM(IID_IUnknown,IFabricInfrastructureTaskQueryResult)
COM_INTERFACE_ITEM(IID_IFabricInfrastructureTaskQueryResult,IFabricInfrastructureTaskQueryResult)
END_COM_INTERFACE_LIST()
public:
explicit ComQueryResult(vector<InfrastructureTaskQueryResult> && resultList)
{
queryResult_ = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST>();
auto array = heap_.AddArray<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM>(resultList.size());
queryResult_->Count = static_cast<ULONG>(resultList.size());
queryResult_->Items = array.GetRawArray();
for (size_t ix = 0; ix < resultList.size(); ++ix)
{
FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM * arrayItem = &array[ix];
InfrastructureTaskQueryResult const & listItem = resultList[ix];
arrayItem->Description = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION>().GetRawPointer();
listItem.Description.ToPublicApi(heap_, *arrayItem->Description);
arrayItem->State = Management::ClusterManager::InfrastructureTaskState::ToPublicApi(listItem.State);
}
}
const FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST * STDMETHODCALLTYPE get_Result(void)
{
return queryResult_.GetRawPointer();
}
private:
Common::ScopedHeap heap_;
Common::ReferencePointer<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST> queryResult_;
};
// ********************************************************************************************************************
// ComInfrastructureServiceAgent::ComInfrastructureServiceAgent Implementation
//
ComInfrastructureServiceAgent::ComInfrastructureServiceAgent(IInfrastructureServiceAgentPtr const & impl)
: IFabricInfrastructureServiceAgent()
, ComUnknownBase()
, impl_(impl)
{
}
ComInfrastructureServiceAgent::~ComInfrastructureServiceAgent()
{
// Break lifetime cycle between ISAgent and ServiceRoutingAgentProxy
impl_->Release();
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureServiceFactory(
IFabricStatefulServiceFactory * factory)
{
return ComUtility::OnPublicApiReturn(impl_->RegisterInfrastructureServiceFactory(factory).ToHResult());
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureService(
FABRIC_PARTITION_ID partitionId,
FABRIC_REPLICA_ID replicaId,
IFabricInfrastructureService * comInterface,
IFabricStringResult ** serviceAddress)
{
if (serviceAddress == NULL) { return ComUtility::OnPublicApiReturn(E_POINTER); }
wstring serviceAddressResult;
impl_->RegisterInfrastructureService(
partitionId,
replicaId,
WrapperFactory::create_rooted_com_proxy(comInterface),
serviceAddressResult);
auto result = make_com<ComStringResult, IFabricStringResult>(serviceAddressResult);
*serviceAddress = result.DetachNoRelease();
return ComUtility::OnPublicApiReturn(S_OK);
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::UnregisterInfrastructureService(
FABRIC_PARTITION_ID partitionId,
FABRIC_REPLICA_ID replicaId)
{
impl_->UnregisterInfrastructureService(partitionId, replicaId);
return ComUtility::OnPublicApiReturn(S_OK);
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginStartInfrastructureTask(
/* [in] */ FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription,
/* [in] */ DWORD timeoutMilliseconds,
/* [in] */ IFabricAsyncOperationCallback * callback,
/* [out, retval] */ IFabricAsyncOperationContext ** context)
{
auto operation = make_com<ComStartInfrastructureTaskAsyncOperation>(*impl_.get(), taskDescription);
HRESULT hr = operation->Initialize(
impl_.get_Root(),
timeoutMilliseconds,
callback);
if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }
return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context));
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndStartInfrastructureTask(
/* [in] */ IFabricAsyncOperationContext * context)
{
return ComUtility::OnPublicApiReturn(ComStartInfrastructureTaskAsyncOperation::End(context));
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginFinishInfrastructureTask(
/* [in] */ LPCWSTR taskId,
/* [in] */ ULONGLONG instanceId,
/* [in] */ DWORD timeoutMilliseconds,
/* [in] */ IFabricAsyncOperationCallback * callback,
/* [out, retval] */ IFabricAsyncOperationContext ** context)
{
wstring parsedTaskId;
HRESULT hr = StringUtility::LpcwstrToWstring(taskId, false, parsedTaskId);
if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }
auto operation = make_com<ComFinishInfrastructureTaskAsyncOperation>(*impl_.get(), parsedTaskId, instanceId);
hr = operation->Initialize(
impl_.get_Root(),
timeoutMilliseconds,
callback);
if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }
return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context));
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndFinishInfrastructureTask(
/* [in] */ IFabricAsyncOperationContext * context)
{
return ComUtility::OnPublicApiReturn(ComFinishInfrastructureTaskAsyncOperation::End(context));
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginQueryInfrastructureTask(
/* [in] */ DWORD timeoutMilliseconds,
/* [in] */ IFabricAsyncOperationCallback * callback,
/* [out, retval] */ IFabricAsyncOperationContext ** context)
{
auto operation = make_com<ComQueryInfrastructureTaskAsyncOperation>(*impl_.get());
auto hr = operation->Initialize(
impl_.get_Root(),
timeoutMilliseconds,
callback);
if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }
return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context));
}
HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndQueryInfrastructureTask(
/* [in] */ IFabricAsyncOperationContext * context,
/* [out, retval] */ IFabricInfrastructureTaskQueryResult ** result)
{
return ComUtility::OnPublicApiReturn(ComQueryInfrastructureTaskAsyncOperation::End(context, result));
}
| 35.257831 | 153 | 0.704825 | [
"vector"
] |
c3a2bf467cacdb277541deb44b6ad0556e4201e1 | 6,034 | cpp | C++ | framework/areg/base/private/Object.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | framework/areg/base/private/Object.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | framework/areg/base/private/Object.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | /************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/base/private/Object.cpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform Generic Object class
*
************************************************************************/
#include "areg/base/Object.hpp"
#include <new>
//////////////////////////////////////////////////////////////////////////
// Object class implementation
//////////////////////////////////////////////////////////////////////////
inline const Object& Object::self( void ) const
{
return (*this);
}
//////////////////////////////////////////////////////////////////////////
// Constructors / Destructor
//////////////////////////////////////////////////////////////////////////
/**
* \brief Constructor to store pointer to void object
**/
Object::Object( void* objData )
: IEGenericObject( objData )
{
}
/**
* \brief Copy constructor.
**/
Object::Object( const Object& src )
: IEGenericObject( src.mObjData )
{
}
/**
* \brief Move constructor.
**/
Object::Object( Object && src ) noexcept
: IEGenericObject( src.mObjData )
{
src.mObjData = nullptr;
}
//////////////////////////////////////////////////////////////////////////
// Methods
//////////////////////////////////////////////////////////////////////////
/**
* \brief Call to clone object
**/
IEGenericObject* Object::clone( void ) const
{
return static_cast<IEGenericObject *>(DEBUG_NEW Object( self() ));
}
/**
* \brief Destroys created (cloned) object
**/
void Object::destroy( void )
{
delete this;
}
/**
* \brief Checks if object data is similar.
**/
bool Object::isEqual( const IEGenericObject* object ) const
{
return (object != nullptr ? static_cast<const IEGenericObject *>(this) == object || this->mObjData == object->mObjData : false);
}
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
Object & Object::operator = ( const Object& src )
{
if (this != &src)
{
this->mObjData = src.mObjData;
}
return (*this);
}
Object & Object::operator = ( Object && src ) noexcept
{
if ( this != &src )
{
this->mObjData = src.mObjData;
src.mObjData = nullptr;
}
return (*this);
}
/**
* \brief Checks is 2 objects are equal
**/
bool Object::operator == ( const Object& other ) const
{
return isEqual( static_cast<const IEGenericObject *>(&other) );
}
/**
* \brief Checks whether 2 objects are not equal
**/
bool Object::operator != ( const Object & other ) const
{
return (isEqual( static_cast<const IEGenericObject *>(&other) ) == false);
}
/**
* \brief Operator to get integer value of object, mainly used in map
**/
Object::operator unsigned int ( void ) const
{
return MACRO_PTR2INT32(this);
}
/**
* \brief Overloaded new() operator
**/
void * Object::operator new( size_t size )
{
return ::operator new(size);
}
/**
* \brief Overloaded array new operator
**/
void * Object::operator new [] ( size_t size )
{
return ::operator new [] (size);
}
/**
* \brief Overloaded placement new
**/
void * Object::operator new( size_t /*size*/, void * ptr )
{
return ptr;
}
/**
* \brief Overloaded placement new
**/
void * Object::operator new [ ]( size_t /*size*/, void * ptr )
{
return ptr;
}
/**
* \brief Overloaded placement new. Stores block type, file name and line number information
* Used in debugging version. In other versions, only allocates memory without
* containing other information.
**/
#if defined(_DEBUG) && defined(_WINDOWS)
void * Object::operator new( size_t size, int /*block*/, const char * file, int line )
{
return ::operator new(size, 1, file, line);
}
#else // _DEBUG
void * Object::operator new( size_t size, int /*block*/, const char * /*file*/, int /*line*/ )
{
return ::operator new (size);
}
#endif // _DEBUG
/**
* \brief Overloaded placement new. Stores block type, file name and line number information
* Used in debugging version. In other versions, only allocates memory without
* containing other information.
**/
#if defined(_DEBUG) && defined(_WINDOWS)
void * Object::operator new [ ]( size_t size, int /*block*/, const char *file, int line )
{
return ::operator new(size, 1, file, line);
}
#else // _DEBUG
void * Object::operator new [ ]( size_t size, int /*block*/, const char * /*file*/, int /*line*/ )
{
return ::operator new [] (size);
}
#endif // _DEBUG
/**
* \brief Overloaded delete() operator
**/
void Object::operator delete( void * ptr )
{
::operator delete(ptr);
}
/**
* \brief Overloaded delete() operator
**/
void Object::operator delete( void * ptr, size_t /*size*/ )
{
::operator delete(ptr);
}
/**
* \brief Overloaded delete() operator
**/
void Object::operator delete( void * ptr, int, const char *, int )
{
::operator delete (ptr);
}
/**
* \brief Overloaded array delete operator
**/
void Object::operator delete [ ] ( void * ptr )
{
::operator delete [] (ptr);
}
/**
* \brief Overloaded array delete operator
**/
void Object::operator delete [ ] ( void * ptr, size_t /*size*/ )
{
::operator delete [] (ptr);
}
/**
* \brief Overloaded delete [] operator
**/
void Object::operator delete [ ]( void * ptr, int, const char *, int )
{
::operator delete [] (ptr);
}
| 23.662745 | 132 | 0.557839 | [
"object"
] |
c3a3e6b787e7fbf9ebf1a63fad961b7a79bc8952 | 1,578 | hpp | C++ | include/dish2/run/setup_thread_local_random.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 29 | 2019-02-04T02:39:52.000Z | 2022-01-28T10:06:26.000Z | include/dish2/run/setup_thread_local_random.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 95 | 2020-02-22T19:48:14.000Z | 2021-09-14T19:17:53.000Z | include/dish2/run/setup_thread_local_random.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 6 | 2019-11-19T10:13:09.000Z | 2021-03-25T17:35:32.000Z | #pragma once
#ifndef DISH2_RUN_SETUP_THREAD_LOCAL_RANDOM_HPP_INCLUDE
#define DISH2_RUN_SETUP_THREAD_LOCAL_RANDOM_HPP_INCLUDE
#include <iostream>
#include <limits>
#include "../../../third-party/conduit/include/uitsl/debug/safe_cast.hpp"
#include "../../../third-party/conduit/include/uitsl/mpi/comm_utils.hpp"
#include "../../../third-party/Empirical/include/emp/base/vector.hpp"
#include "../../../third-party/Empirical/include/emp/math/Random.hpp"
#include "../../../third-party/Empirical/include/emp/meta/meta.hpp"
#include "../../../third-party/signalgp-lite/include/sgpl/utility/ThreadLocalRandom.hpp"
#include "../config/calc_rng_preseed.hpp"
#include "../config/cfg.hpp"
#include "../config/thread_idx.hpp"
#include "../debug/log_msg.hpp"
#include "../utility/sha256_reduce.hpp"
namespace dish2 {
void setup_thread_local_random() {
const uint32_t preseed = dish2::calc_rng_preseed();
dish2::log_msg( "using rng preseed ", preseed );
const uint32_t hash = dish2::sha256_reduce( emp::vector< uint32_t >{
preseed,
uitsl::safe_cast<uint32_t>( dish2::thread_idx ),
uitsl::safe_cast<uint32_t>( uitsl::get_proc_id() )
} );
dish2::log_msg( "calculated hash ", hash );
// seed >= 1 so that rng is seeded deterministically
const auto seed_addend = hash % ( std::numeric_limits<int32_t>::max() - 1 );
const int32_t seed = uitsl::safe_cast<int32_t>( 1 + seed_addend );
sgpl::tlrand.Initialize( seed );
dish2::log_msg( "applied rng seed ", seed );
}
} // namespace dish2
#endif // #ifndef DISH2_RUN_SETUP_THREAD_LOCAL_RANDOM_HPP_INCLUDE
| 31.56 | 88 | 0.721166 | [
"vector"
] |
c3a48fc946a0786051e7bfe47040d88562d20e85 | 15,999 | cpp | C++ | lib/MemoryAnalysisModules/CallsiteBreadthCombinator.cpp | sgh185/SCAF | 715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018 | [
"MIT"
] | 22 | 2020-08-01T18:09:11.000Z | 2022-03-22T08:56:05.000Z | lib/MemoryAnalysisModules/CallsiteBreadthCombinator.cpp | sgh185/SCAF | 715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018 | [
"MIT"
] | 4 | 2021-02-23T01:27:53.000Z | 2021-04-19T22:11:39.000Z | lib/MemoryAnalysisModules/CallsiteBreadthCombinator.cpp | sgh185/SCAF | 715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018 | [
"MIT"
] | 4 | 2020-09-17T17:24:22.000Z | 2022-03-22T09:12:19.000Z | #define DEBUG_TYPE "callsite-breadth-combinator-aa"
#include "scaf/MemoryAnalysisModules/FindSource.h"
#include "scaf/MemoryAnalysisModules/Introspection.h"
#include "scaf/MemoryAnalysisModules/KillFlow.h"
#include "scaf/MemoryAnalysisModules/LoopAA.h"
#include "scaf/MemoryAnalysisModules/QueryCacheing.h"
#include "scaf/Utilities/CallSiteFactory.h"
#include "scaf/Utilities/CaptureUtil.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::noelle;
using namespace liberty;
STATISTIC(numHitsIF, "Num cache hits (I-F)");
STATISTIC(numHitsFI, "Num cache hits (F-I)");
STATISTIC(numHitsFP, "Num cache hits (F-P)");
STATISTIC(numRecurs, "Num expanded callsites");
STATISTIC(numOps, "Num memory ops within an expanded callsite");
STATISTIC(numKilledOps, "Num killed memory ops within an expanded callsite");
typedef DenseMap<FcnPtrKey, LoopAA::ModRefResult> FcnPtrCache;
typedef DenseMap<InstFcnKey, LoopAA::ModRefResult> InstFcnCache;
typedef DenseMap<FcnInstKey, LoopAA::ModRefResult> FcnInstCache;
typedef Value::const_user_iterator UseIt;
typedef DenseSet<const Value *> ValueSet;
class CallsiteBreadthCombinator : public ModulePass, public liberty::LoopAA {
InstFcnCache instFcnCache;
FcnInstCache fcnInstCache;
FcnPtrCache fcnPtrCache;
const DataLayout *DL;
unsigned countPtrArgs(const Instruction *inst) {
CallSite cs = getCallSite(inst);
unsigned n = 0;
for (User::const_op_iterator i = cs.arg_begin(), e = cs.arg_end(); i != e;
++i) {
const Value *op = *i;
Type *opTy = op->getType();
if (opTy->isIntegerTy() || opTy->isFloatingPointTy())
continue;
++n;
}
return n;
}
ModRefResult recur(const Instruction *op, TemporalRelation Rel,
const Value *p2, unsigned s2, const Loop *L, Remedies &R) {
return getTopAA()->modref(op, Rel, p2, s2, L, R);
}
ModRefResult recur(const Instruction *i1, TemporalRelation Rel,
const Instruction *i2, const Loop *L, Remedies &R) {
return getTopAA()->modref(i1, Rel, i2, L, R);
}
ModRefResult recurLeft(const Function *fcn, TemporalRelation Rel,
const Instruction *i2, const Loop *L, Remedies &R) {
FcnInstKey key(fcn, Rel, i2, L);
if (fcnInstCache.count(key)) {
++numHitsFI;
return fcnInstCache[key];
}
// Avoid infinite recursion. We will put in a more precise answer later.
fcnInstCache[key] = ModRef;
++numRecurs;
ModRefResult result = NoModRef;
// Update the query for non-callsite instructions first.
// We will visit nested callsites later.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// Possibly break early if it can't get worse.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
if (isa<CallInst>(instFromCallee) || isa<InvokeInst>(instFromCallee))
continue;
// Inst is a memory operation.
++numOps;
if (const StoreInst *store = dyn_cast<StoreInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(store->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
}
else if (const LoadInst *load = dyn_cast<LoadInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(load->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
}
ModRefResult old = result;
result = ModRefResult(result | recur(instFromCallee, Rel, i2, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurLeft(" << fcn->getName()
<< ", " << *i2 << ") vs op:\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
// Now the nested callsites.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// possibly break early.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
CallSite nested = getCallSite(instFromCallee);
if (!nested.getInstruction())
continue;
++numOps;
ModRefResult old = result;
result = ModRefResult(result | recur(instFromCallee, Rel, i2, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurLeft(" << fcn->getName()
<< ", " << *i2 << ") vs op:\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
return fcnInstCache[key] = result;
}
ModRefResult recurLeft(const Function *fcn, TemporalRelation Rel,
const Value *p2, unsigned s2, const Loop *L,
Remedies &R) {
FcnPtrKey key(fcn, Rel, p2, s2, L);
if (fcnPtrCache.count(key)) {
++numHitsFP;
return fcnPtrCache[key];
}
// Avoid infinite recursion. We'll put in a more precise
// result later.
fcnPtrCache[key] = ModRef;
++numRecurs;
ModRefResult result = NoModRef;
// Update the query for non-callsite instructions first.
// We will visit nested callsites later.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// Possibly break early if it can't get worse.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
if (isa<CallInst>(instFromCallee) || isa<InvokeInst>(instFromCallee))
continue;
// Inst is a memory operation.
++numOps;
if (const StoreInst *store = dyn_cast<StoreInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(store->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
}
else if (const LoadInst *load = dyn_cast<LoadInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(load->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
}
ModRefResult old = result;
result = ModRefResult(result | recur(instFromCallee, Rel, p2, s2, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurLeft(" << fcn->getName()
<< ", " << *p2 << ") vs ptr:\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
// Now the nested callsites.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// possibly break early.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
CallSite nested = getCallSite(instFromCallee);
if (!nested.getInstruction())
continue;
++numOps;
ModRefResult old = result;
result = ModRefResult(result | recur(instFromCallee, Rel, p2, s2, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurLeft(" << fcn->getName()
<< ", " << *p2 << ") vs ptr:\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
return fcnPtrCache[key] = result;
}
ModRefResult recurRight(const Instruction *i1, TemporalRelation Rel,
const Function *fcn, const Loop *L, Remedies &R) {
InstFcnKey key(i1, Rel, fcn, L);
if (instFcnCache.count(key)) {
++numHitsIF;
return instFcnCache[key];
}
// Avoid infinite recursion. We will put in a more precise answer later.
instFcnCache[key] = ModRef;
KillFlow &killFlow = getAnalysis<KillFlow>();
++numRecurs;
ModRefResult result = NoModRef;
// Update the query for non-callsite instructions first.
// We will visit nested callsites later.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// Possibly break early if it can't get worse.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
if (isa<CallInst>(instFromCallee) || isa<InvokeInst>(instFromCallee))
continue;
++numOps;
if (const StoreInst *store = dyn_cast<StoreInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(store->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
}
else if (const LoadInst *load = dyn_cast<LoadInst>(instFromCallee)) {
if (isa<AllocaInst>(
GetUnderlyingObject(load->getPointerOperand(), *DL, 0))) {
// Allocas are patently local
++numKilledOps;
continue;
}
if (killFlow.pointerKilledBefore(0, load->getPointerOperand(), load)) {
++numKilledOps;
continue;
}
}
// Inst is a memory operation.
ModRefResult old = result;
result = ModRefResult(result | recur(i1, Rel, instFromCallee, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurRight(" << *i1 << ", "
<< fcn->getName() << "):\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
// Now the nested callsites.
for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e;
++i) {
// possibly break early.
if (result == ModRef)
break;
const Instruction *instFromCallee = &*i;
if (!instFromCallee->mayReadFromMemory() &&
!instFromCallee->mayWriteToMemory())
continue;
CallSite nested = getCallSite(instFromCallee);
if (!nested.getInstruction())
continue;
// top-query
++numOps;
ModRefResult old = result;
result = ModRefResult(result | recur(i1, Rel, instFromCallee, L, R));
INTROSPECT(if (result != old) {
errs() << "CallsiteBreadthCombinator: recurRight(" << *i1 << ", "
<< fcn->getName() << "):\n";
errs() << "\tChanged " << old << " => " << result << '\n';
errs() << "\t\t" << *instFromCallee << '\n';
});
}
return instFcnCache[key] = result;
}
const Function *getEligibleFunction(const Instruction *i) const {
CallSite cs = getCallSite(i);
if (!cs.getInstruction())
return 0;
const Function *f = cs.getCalledFunction();
if (!f)
return 0;
if (f->isDeclaration())
return 0;
return f;
}
protected:
virtual void uponStackChange() {
instFcnCache.clear();
fcnInstCache.clear();
fcnPtrCache.clear();
}
public:
static char ID;
CallsiteBreadthCombinator()
: ModulePass(ID), instFcnCache(), fcnInstCache(), fcnPtrCache(), DL() {}
virtual bool runOnModule(Module &M) {
LLVM_DEBUG(errs() << "callsite breadth comb callsites " << WatchCallsitePair
<< " " << FirstCallee << " " << SecondCallee << "\n");
DL = &M.getDataLayout();
InitializeLoopAA(this, *DL);
return false;
}
virtual SchedulingPreference getSchedulingPreference() const {
return SchedulingPreference(Normal - 1);
}
StringRef getLoopAAName() const { return "callsite-breadth-combinator-aa"; }
void getAnalysisUsage(AnalysisUsage &AU) const {
LoopAA::getAnalysisUsage(AU);
AU.addRequired<KillFlow>();
AU.setPreservesAll(); // Does not transform code
}
ModRefResult modref(const Instruction *i1, TemporalRelation Rel,
const Instruction *i2, const Loop *L, Remedies &R) {
const Function *f1 = getEligibleFunction(i1), *f2 = getEligibleFunction(i2);
// Maybe turn-on introspection
bool introspect = false;
if (WatchCallsitePair) {
if (f1 && FirstCallee == f1->getName() && f2 &&
SecondCallee == f2->getName())
introspect = true;
} else if (WatchCallsite2Store) {
const StoreInst *st2 = dyn_cast<StoreInst>(i2);
if (f1 && f1->getName() == FirstCallee)
if (st2 && st2->getPointerOperand()->getName() == StorePtrName)
introspect = true;
}
else if (WatchStore2Callsite) {
const StoreInst *st1 = dyn_cast<StoreInst>(i1);
if (f2 && f2->getName() == SecondCallee)
if (st1 && st1->getPointerOperand()->getName() == StorePtrName)
introspect = true;
}
if (introspect)
enterIntrospectionRegion();
INTROSPECT(ENTER(i1, Rel, i2, L));
ModRefResult result = LoopAA::modref(i1, Rel, i2, L, R);
if (result == NoModRef) {
INTROSPECT(EXIT(i1, Rel, i2, L, result));
return result;
}
if (f1 && f2) {
// We would like to inline one of the two callsites.
// If we can inline both, we must choose.
// Since our major source of imprecision is function
// arguments, we choose to inline the one with
// fewer pointer operands.
if (countPtrArgs(i1) < countPtrArgs(i2))
// We prefer to inline CS1
result = ModRefResult(result & recurLeft(f1, Rel, i2, L, R));
else
// We prefer to inline CS2
result = ModRefResult(result & recurRight(i1, Rel, f2, L, R));
}
else if (f1) {
// We can only inline CS1.
result = ModRefResult(result & recurLeft(f1, Rel, i2, L, R));
}
else if (f2) {
// We can only inline CS2.
result = ModRefResult(result & recurRight(i1, Rel, f2, L, R));
}
INTROSPECT(EXIT(i1, Rel, i2, L, result));
if (introspect)
exitIntrospectionRegion();
return result;
}
ModRefResult modref(const Instruction *i1, TemporalRelation Rel,
const Value *p2, unsigned s2, const Loop *L,
Remedies &R) {
INTROSPECT(ENTER(i1, Rel, p2, s2, L));
ModRefResult result = LoopAA::modref(i1, Rel, p2, s2, L, R);
if (result != NoModRef)
if (const Function *fcn = getEligibleFunction(i1))
result = ModRefResult(result & recurLeft(fcn, Rel, p2, s2, L, R));
INTROSPECT(EXIT(i1, Rel, p2, s2, L, result));
return result;
}
/// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it
/// should override this to adjust the this pointer as needed for the
/// specified pass info.
virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
if (PI == &LoopAA::ID)
return (LoopAA *)this;
return this;
}
};
char CallsiteBreadthCombinator::ID = 0;
static RegisterPass<CallsiteBreadthCombinator>
XX("callsite-breadth-combinator-aa",
"Alias analysis which substitutes body of callees for callsites", false,
true);
static RegisterAnalysisGroup<liberty::LoopAA> Y(XX);
| 31.43222 | 80 | 0.599787 | [
"transform"
] |
c3a4ca60adbbc34a905140f5ffb042c8593aec34 | 9,098 | cpp | C++ | AfxHookGoldSrc/enthack.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 339 | 2018-01-09T13:12:38.000Z | 2022-03-22T21:25:59.000Z | AfxHookGoldSrc/enthack.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 474 | 2018-01-01T18:58:41.000Z | 2022-03-27T11:09:44.000Z | AfxHookGoldSrc/enthack.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 77 | 2018-01-24T11:47:04.000Z | 2022-03-30T12:25:59.000Z | // BEGIN HLSDK includes
//
// HACK: prevent cldll_int.h from messing the HSPRITE definition,
// HLSDK's HSPRITE --> MDTHACKED_HSPRITE
#pragma push_macro("HSPRITE")
#define HSPRITE MDTHACKED_HSPRITE
//
#include <wrect.h>
#include <cl_dll.h>
#include <cdll_int.h>
#include <edict.h>
//
#undef HSPRITE
#pragma pop_macro("HSPRITE")
// END HLSDK includes
//#include <progdefs.h>
#include "cmdregister.h"
#include "hl_addresses.h"
#include <windows.h>
typedef struct enginefuncs_s
{
void (*_UNUSED_pfnPrecacheModel)(void);
void (*_UNUSED_pfnPrecacheSound)(void);
void (*_UNUSED_pfnSetModel)(void);
void (*_UNUSED_pfnModelIndex)(void);
void (*_UNUSED_pfnModelFrames)(void);
void (*_UNUSED_pfnSetSize)(void);
void (*_UNUSED_pfnChangeLevel)(void);
void (*_UNUSED_pfnGetSpawnParms)(void);
void (*_UNUSED_pfnSaveSpawnParms)(void);
void (*_UNUSED_pfnVecToYaw)(void);
void (*_UNUSED_pfnVecToAngles)(void);
void (*_UNUSED_pfnMoveToOrigin)(void);
void (*_UNUSED_pfnChangeYaw)(void);
void (*_UNUSED_pfnChangePitch)(void);
void (*_UNUSED_pfnFindEntityByString)(void);
void (*_UNUSED_pfnGetEntityIllum)(void);
void (*_UNUSED_pfnFindEntityInSphere)(void);
void (*_UNUSED_pfnFindClientInPVS)(void);
void (*_UNUSED_pfnEntitiesInPVS)(void);
void (*_UNUSED_pfnMakeVectors)(void);
void (*_UNUSED_pfnAngleVectors)(void);
void (*_UNUSED_pfnCreateEntity)(void);
void (*pfnRemoveEntity) (edict_t* e);
edict_t* (*pfnCreateNamedEntity) (int className);
void (*_UNUSED_pfnMakeStatic)(void);
void (*_UNUSED_pfnEntIsOnFloor)(void);
void (*_UNUSED_pfnDropToFloor)(void);
void (*_UNUSED_pfnWalkMove)(void);
void (*_UNUSED_pfnSetOrigin)(void);
void (*_UNUSED_pfnEmitSound)(void);
void (*_UNUSED_pfnEmitAmbientSound)(void);
void (*_UNUSED_pfnTraceLine)(void);
void (*_UNUSED_pfnTraceToss)(void);
void (*_UNUSED_pfnTraceMonsterHull)(void);
void (*_UNUSED_pfnTraceHull)(void);
void (*_UNUSED_pfnTraceModel)(void);
void (*_UNUSED_pfnTraceTexture)(void);
void (*_UNUSED_pfnTraceSphere)(void);
void (*_UNUSED_pfnGetAimVector)(void);
void (*_UNUSED_pfnServerCommand)(void);
void (*_UNUSED_pfnServerExecute)(void);
void (*_UNUSED_pfnClientCommand)(void);
void (*_UNUSED_pfnParticleEffect)(void);
void (*_UNUSED_pfnLightStyle)(void);
void (*_UNUSED_pfnDecalIndex)(void);
void (*_UNUSED_pfnPovoidContents)(void);
void (*_UNUSED_pfnMessageBegin)(void);
void (*_UNUSED_pfnMessageEnd)(void);
void (*_UNUSED_pfnWriteByte)(void);
void (*_UNUSED_pfnWriteChar)(void);
void (*_UNUSED_pfnWriteShort)(void);
void (*_UNUSED_pfnWriteLong)(void);
void (*_UNUSED_pfnWriteAngle)(void);
void (*_UNUSED_pfnWriteCoord)(void);
void (*_UNUSED_pfnWriteString)(void);
void (*_UNUSED_pfnWriteEntity)(void);
void (*_UNUSED_pfnCVarRegister)(void);
void (*_UNUSED_pfnCVarGetvoid)(void);
void (*_UNUSED_pfnCVarGetString)(void);
void (*_UNUSED_pfnCVarSetvoid)(void);
void (*_UNUSED_pfnCVarSetString)(void);
void (*_UNUSED_pfnAlertMessage)(void);
void (*_UNUSED_pfnEngineFprvoidf)(void);
void (*_UNUSED_pfnPvAllocEntPrivateData)(void);
void (*_UNUSED_pfnPvEntPrivateData)(void);
void (*_UNUSED_pfnFreeEntPrivateData)(void);
void (*_UNUSED_pfnSzFromIndex)(void);
int (*pfnAllocString) (const char *szValue);
void (*_UNUSED_pfnGetVarsOfEnt)(void);
void (*_UNUSED_pfnPEntityOfEntOffset)(void);
void (*_UNUSED_pfnEntOffsetOfPEntity)(void);
void (*_UNUSED_pfnIndexOfEdict)(void);
void (*_UNUSED_pfnPEntityOfEntIndex)(void);
void (*_UNUSED_pfnFindEntityByVars)(void);
void (*_UNUSED_pfnGetModelPtr)(void);
void (*_UNUSED_pfnRegUserMsg)(void);
void (*_UNUSED_pfnAnimationAutomove)(void);
void (*_UNUSED_pfnGetBonePosition)(void);
void (*_UNUSED_pfnFunctionFromName)(void);
void (*_UNUSED_pfnNameForFunction)(void);
void (*_UNUSED_pfnClientPrvoidf)(void);
void (*_UNUSED_pfnServerPrvoid)(void);
void (*_UNUSED_pfnCmd_Args)(void);
void (*_UNUSED_pfnCmd_Argv)(void);
void (*_UNUSED_pfnCmd_Argc)(void);
void (*_UNUSED_pfnGetAttachment)(void);
void (*_UNUSED_pfnCRC32_Init)(void);
void (*_UNUSED_pfnCRC32_ProcessBuffer)(void);
void (*_UNUSED_pfnCRC32_ProcessByte)(void);
void (*_UNUSED_pfnCRC32_Final)(void);
void (*_UNUSED_pfnRandomLong)(void);
void (*_UNUSED_pfnRandomvoid)(void);
void (*_UNUSED_pfnSetView)(void);
void (*_UNUSED_pfnTime)(void);
void (*_UNUSED_pfnCrosshairAngle)(void);
void (*_UNUSED_pfnLoadFileForMe)(void);
void (*_UNUSED_pfnFreeFile)(void);
void (*_UNUSED_pfnEndSection)(void);
void (*_UNUSED_pfnCompareFileTime)(void);
void (*_UNUSED_pfnGetGameDir)(void);
void (*_UNUSED_pfnCvar_RegisterVariable)(void);
void (*_UNUSED_pfnFadeClientVolume)(void);
void (*_UNUSED_pfnSetClientMaxspeed)(void);
void (*_UNUSED_pfnCreateFakeClient)(void);
void (*_UNUSED_pfnRunPlayerMove)(void);
void (*_UNUSED_pfnNumberOfEntities)(void);
void (*_UNUSED_pfnGetInfoKeyBuffer)(void);
void (*_UNUSED_pfnInfoKeyValue)(void);
void (*_UNUSED_pfnSetKeyValue)(void);
void (*_UNUSED_pfnSetClientKeyValue)(void);
void (*_UNUSED_pfnIsMapValid)(void);
void (*_UNUSED_pfnStaticDecal)(void);
void (*_UNUSED_pfnPrecacheGeneric)(void);
void (*_UNUSED_pfnGetPlayerUserId)(void);
void (*_UNUSED_pfnBuildSoundMsg)(void);
void (*_UNUSED_pfnIsDedicatedServer)(void);
void (*_UNUSED_pfnCVarGetPovoider)(void);
void (*_UNUSED_pfnGetPlayerWONId)(void);
void (*_UNUSED_pfnInfo_RemoveKey)(void);
void (*_UNUSED_pfnGetPhysicsKeyValue)(void);
void (*_UNUSED_pfnSetPhysicsKeyValue)(void);
void (*_UNUSED_pfnGetPhysicsInfoString)(void);
void (*_UNUSED_pfnPrecacheEvent)(void);
void (*_UNUSED_pfnPlaybackEvent)(void);
void (*_UNUSED_pfnSetFatPVS)(void);
void (*_UNUSED_pfnSetFatPAS)(void);
void (*_UNUSED_pfnCheckVisibility )(void);
void (*_UNUSED_pfnDeltaSetField)(void);
void (*_UNUSED_pfnDeltaUnsetField)(void);
void (*_UNUSED_pfnDeltaAddEncoder)(void);
void (*_UNUSED_pfnGetCurrentPlayer)(void);
void (*_UNUSED_pfnCanSkipPlayer)(void);
void (*_UNUSED_pfnDeltaFindField)(void);
void (*_UNUSED_pfnDeltaSetFieldByIndex)(void);
void (*_UNUSED_pfnDeltaUnsetFieldByIndex)(void);
void (*_UNUSED_pfnSetGroupMask)(void);
void (*_UNUSED_pfnCreateInstancedBaseline)(void);
void (*_UNUSED_pfnCvar_DirectSet)(void);
void (*_UNUSED_pfnForceUnmodified)(void);
void (*_UNUSED_pfnGetPlayerStats)(void);
void (*_UNUSED_pfnAddServerCommand)(void);
void (*_UNUSED_pfnVoice_GetClientListening)(void);
void (*_UNUSED_pfnVoice_SetClientListening)(void);
void (*_UNUSED_pfnGetPlayerAuthId)(void);
void (*_UNUSED_pfnSequenceGet)(void);
void (*_UNUSED_pfnSequencePickSentence)(void);
void (*_UNUSED_pfnGetFileSize)(void);
void (*_UNUSED_pfnGetApproxWavePlayLen)(void);
void (*_UNUSED_pfnIsCareerMatch)(void);
void (*_UNUSED_pfnGetLocalizedStringLength)(void);
void (*_UNUSED_pfnRegisterTutorMessageShown)(void);
void (*_UNUSED_pfnGetTimesTutorMessageShown)(void);
void (*_UNUSED_pfnProcessTutorMessageDecayBuffer)(void);
void (*_UNUSED_pfnConstructTutorMessageDecayBuffer)(void);
void (*_UNUSED_pfnResetTutorMessageDecayData)(void);
void (*_UNUSED_pfnQueryClientCvarValue)(void);
void (*_UNUSED_pfnQueryClientCvarValue2);
} enginefuncs_t;
// ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138
// Passed to pfnKeyValue
typedef struct KeyValueData_s
{
char *szClassName; // in: entity classname
char *szKeyName; // in: name of key
char *szValue; // in: value of key
__int32 fHandled; // out: DLL sets to true if key-value pair was understood
} KeyValueData;
enginefuncs_t * pHostFuncs = 0;
globalvars_t *pGlobals = 0;
extern cl_enginefuncs_s *pEngfuncs;
#define STRING(offset) (const char *)(pGlobals->pStringBase + (int)offset)
#define MAKE_STRING(str) ((int)str - (int)STRING(0))
REGISTER_DEBUGCMD_FUNC(wazzup_snow)
{
pHostFuncs = (enginefuncs_t *)HL_ADDR_GET(p_enginefuncs_s);
pGlobals = (globalvars_t *)HL_ADDR_GET(p_globalvars_s);
edict_t * pedict = pHostFuncs->pfnCreateNamedEntity(MAKE_STRING("env_snow"));
if(pedict && pedict->pvPrivateData) {
pEngfuncs->Con_Printf("Created.\n");
//VARS( pent )->origin = pev->origin;
//pent->v.spawnflags |= SF_NORESPAWN;
unsigned int dwClient = (unsigned int)GetModuleHandle("client.dll");
dwClient += 0x2D175F0;
((entvars_t *)&pedict->v)->owner = 0;
((entvars_t *)&pedict->v)->origin = Vector(0, 0, 0);
((entvars_t *)&pedict->v)->angles = Vector(0, 0, 0);
// Dispatch spawn:
__asm {
MOV eax, pedict
PUSH eax
MOV eax, dwClient;
CALL eax;
};
}
else
pEngfuncs->Con_Printf("Creation failed.\n");
//pEntity->pev->owner = pentOwner;
//pEntity->pev->origin = vecOrigin;
//pEntity->pev->angles = vecAngles;
//DispatchSpawn( pEntity->edict() );
//035e4955 68e0d0ce03 push offset hw!vgui::Frame::`vftable'+0x681e1c (03ced0e0)
//035e495a 68f0b96a03 push offset hw!vgui::Frame::`vftable'+0x4072c (036ab9f0)
//035e495f ffd0 call eax
} | 35.818898 | 89 | 0.739173 | [
"vector"
] |
c3abd8ad73d91c37c5946576a1da5a0643b8825d | 1,374 | cpp | C++ | aws-cpp-sdk-fsx/source/model/FileSystemEndpoints.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-fsx/source/model/FileSystemEndpoints.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-fsx/source/model/FileSystemEndpoints.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/fsx/model/FileSystemEndpoints.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FSx
{
namespace Model
{
FileSystemEndpoints::FileSystemEndpoints() :
m_interclusterHasBeenSet(false),
m_managementHasBeenSet(false)
{
}
FileSystemEndpoints::FileSystemEndpoints(JsonView jsonValue) :
m_interclusterHasBeenSet(false),
m_managementHasBeenSet(false)
{
*this = jsonValue;
}
FileSystemEndpoints& FileSystemEndpoints::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Intercluster"))
{
m_intercluster = jsonValue.GetObject("Intercluster");
m_interclusterHasBeenSet = true;
}
if(jsonValue.ValueExists("Management"))
{
m_management = jsonValue.GetObject("Management");
m_managementHasBeenSet = true;
}
return *this;
}
JsonValue FileSystemEndpoints::Jsonize() const
{
JsonValue payload;
if(m_interclusterHasBeenSet)
{
payload.WithObject("Intercluster", m_intercluster.Jsonize());
}
if(m_managementHasBeenSet)
{
payload.WithObject("Management", m_management.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace FSx
} // namespace Aws
| 18.32 | 72 | 0.732169 | [
"model"
] |
c3abdd026371e4cf676d1d8cb8b021dbe826d6cc | 5,945 | hh | C++ | src/objects/object.hh | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | 7 | 2021-06-20T13:40:28.000Z | 2022-01-05T15:49:53.000Z | src/objects/object.hh | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | null | null | null | src/objects/object.hh | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | 1 | 2021-06-27T12:53:20.000Z | 2021-06-27T12:53:20.000Z | #pragma once
// The base object class
#include "gc.hh"
#include "utils.hh"
#include <iterator>
#include <vector>
#include <unordered_map>
struct Type;
struct Object;
// Whether it is a type object
bool is_type(Object *o);
// Function that calls the visitor on all objects to traverse
typedef std::function<void(Object *child)> fn_visit_object_t;
typedef std::function<void(Object *obj, const fn_visit_object_t &visit)>
fn_traverse_objects_t;
struct Object;
// Returns whether this object is a Plain Old Data type,
// that is, it must be copied on various operations
constexpr bool is_pod_object(Object *o) { return false; }
struct Object {
// This attribute describes the type of this object
// It is present also on other classes such as Type
static Type *class_type;
GcData gc_data;
Type *type;
Object(Type *type);
// This static function inits the static attribute class_type
// It is present on other objects such as Type
// This function should be called in init_types
// Can throw for most objects
static void init_class_type();
virtual ~Object();
// Built-in methods, wrappers of Type::fn_*
// See Type::fn_* for more details
// Can throw and return nullptr (except for traverse_objects)
void traverse_objects(const fn_visit_object_t &visit);
Object *add(Object *o);
Object *call(Object *args, Object *kwargs);
// Int type verified (or nullptr)
// Compares references by default
Object *cmp(Object *o);
// Returns this if there is no custom handler
Object *copy();
Object *div(Object *o);
// Either Str or Null
Object *doc();
Object *getattr(Object *name);
Object *getitem(Object *key);
// Returns the reference if there is no custom handler
Object *hash();
Object *idiv(Object *o);
Object *in(Object *value);
Object *iter();
// Int type verified (or nullptr)
Object *len();
Object *mod(Object *o);
Object *mul(Object *o);
Object *neg();
Object *next();
Object *setattr(Object *name, Object *value);
Object *setitem(Object *key, Object *value);
// Str type verified (or nullptr)
// Returns 'ObjectType()' by default
Object *str();
Object *sub(Object *o);
};
// Every type must have a unique instance of this class
struct Type : public Object {
static Type *class_type;
// Unique identifier
unsigned int id;
// Complete name
str_t name;
// This function is called with fn_call
// Can be empty
fn_ternary_t constructor;
// Builtin methods : Use wrappers within Object
// The tp_traverse function
fn_traverse_objects_t fn_traverse_objects;
// + operator, returns the sum
fn_binary_t fn_add;
// Functor call
// If the function doesn't return, null is returned
// (not nullptr)
// The kwargs can be null
fn_ternary_t fn_call;
// <=> operator, compares to another object
// Returns < 0 if lesser or different, > 0 if greater, 0 if equal
// * Should return not equal with null
// * Should return lesser if not equal (if there is no specific order)
fn_binary_t fn_cmp;
// Returns a deep copy of this object
fn_unary_t fn_copy;
// / operator, returns the quotient
fn_binary_t fn_div;
// Returns the documentation of the object
// Returns null if no documentation
fn_unary_t fn_doc;
// Get map attribute (not read only)
fn_binary_t fn_getattr;
// Subscript getter, example : obj[42]
fn_binary_t fn_getitem;
// Used for hash tables etc...
// Returns an Int
fn_unary_t fn_hash;
// Integer / operator, returns the integer quotient
fn_binary_t fn_idiv;
// Whether an object is within a collection
// Returns a Bool
fn_binary_t fn_in;
// Returns the iterator from the first element of the collection
fn_unary_t fn_iter;
// Container length
fn_unary_t fn_len;
// % operator, returns the modulo
fn_binary_t fn_mod;
// * operator, returns the product
fn_binary_t fn_mul;
// - operator (unary), returns the negation, the opposite
fn_unary_t fn_neg;
// Next iter item (or enditer)
fn_unary_t fn_next;
// Set map attribute (not read only)
fn_ternary_t fn_setattr;
// Subscript setter, example : obj[42] = 2
fn_ternary_t fn_setitem;
// String representation
// Returns a Str
fn_unary_t fn_str;
// % operator, returns the modulo
fn_binary_t fn_sub;
// A type is always global
Type(const str_t &name, bool register_type = true);
static void init_class_type();
// Compares the unique identifier
bool operator==(const Type &other) const;
protected:
// Inits all slots
// Not in init_class_type to be called from UserType (inherited)
static void init_slots(Type *type);
};
// Abstract class for dynamic objects / types
struct DynamicModel {
std::unordered_map<str_t, Object*> attrs;
DynamicModel() = default;
virtual ~DynamicModel() = default;
// Returns a copy of itself (@copy slot)
virtual Object *dynamic_model_copy() = 0;
};
// Object with DynamicType as type
// Methods and static attributes can be set
struct DynamicObject : public Object, public DynamicModel {
DynamicObject(Type *type) : Object(type) {}
virtual Object *dynamic_model_copy() override;
// Inits a dynamic object instance
// Can throw
static void init(DynamicObject *o);
};
// Type that has attributes within a map
// Must be bind with a DynamicObject
struct DynamicType : public Type, public DynamicModel {
static Type *class_type;
static DynamicType *New(const str_t &name);
static void default_traverse_objects(Object *self, const fn_visit_object_t &visit);
static void init_class_type();
virtual Object *dynamic_model_copy() override;
private:
DynamicType(const str_t &name);
};
| 24.068826 | 87 | 0.678217 | [
"object",
"vector"
] |
ce79432dfe85c6130a69388950eefda519c5d852 | 754 | cpp | C++ | model/nullmodel.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | 3 | 2017-11-17T11:48:51.000Z | 2018-04-25T14:39:20.000Z | model/nullmodel.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | null | null | null | model/nullmodel.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | null | null | null | #include "nullmodel.h"
#include "model/tactiledisplay.h"
#include <scratchy/positionquery.h>
NullModel::NullModel()
{
}
NullModel::~NullModel()
{
}
void NullModel::initialize(const QStringList& options, PositionQuery* position, QRectF bounds)
{
Q_UNUSED(options)
Q_UNUSED(bounds)
this->position = position;
}
void NullModel::apply(const TactileDisplay* display, QVector<FrequencyTable> &tables)
{
Q_UNUSED(display)
static int cnt = 0;
cnt++;
for(FrequencyTable& tab : tables)
{
for(fixed_q5& frequency : tab.frequency)
frequency = 0.0;
for(fixed_q15& amplitude : tab.amplitude)
amplitude = 0.0;
}
if(cnt % 100 == 0)
{
position->feedback(0,0,0);
}
}
| 17.952381 | 94 | 0.636605 | [
"model"
] |
ce7b84a65ddf2b27c4fe6d3db14fcb45de3cb5b0 | 15,269 | cpp | C++ | c_src/lib/wm_job.cpp | skyworkflows/swm-core | 5e5de1bdb1740d773a5285b352976c5f64a30688 | [
"BSD-3-Clause"
] | 4 | 2021-04-04T18:34:47.000Z | 2021-08-25T13:26:45.000Z | c_src/lib/wm_job.cpp | skyworkflows/swm-core | 5e5de1bdb1740d773a5285b352976c5f64a30688 | [
"BSD-3-Clause"
] | null | null | null | c_src/lib/wm_job.cpp | skyworkflows/swm-core | 5e5de1bdb1740d773a5285b352976c5f64a30688 | [
"BSD-3-Clause"
] | 1 | 2021-08-25T13:26:49.000Z | 2021-08-25T13:26:49.000Z |
#include "wm_entity_utils.h"
#include <iostream>
#include "wm_job.h"
#include <erl_interface.h>
#include <ei.h>
#include "wm_resource.h"
using namespace swm;
SwmJob::SwmJob() {
}
SwmJob::SwmJob(ETERM *term) {
if(!term) {
std::cerr << "Cannot convert ETERM to SwmJob: empty" << std::endl;
return;
}
if(eterm_to_str(term, 2, id)) {
std::cerr << "Could not initialize job paremeter at position 2" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 3, name)) {
std::cerr << "Could not initialize job paremeter at position 3" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 4, cluster_id)) {
std::cerr << "Could not initialize job paremeter at position 4" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 5, nodes)) {
std::cerr << "Could not initialize job paremeter at position 5" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 6, state)) {
std::cerr << "Could not initialize job paremeter at position 6" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 7, start_time)) {
std::cerr << "Could not initialize job paremeter at position 7" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 8, submit_time)) {
std::cerr << "Could not initialize job paremeter at position 8" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 9, end_time)) {
std::cerr << "Could not initialize job paremeter at position 9" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 10, duration)) {
std::cerr << "Could not initialize job paremeter at position 10" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 11, job_stdin)) {
std::cerr << "Could not initialize job paremeter at position 11" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 12, job_stdout)) {
std::cerr << "Could not initialize job paremeter at position 12" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 13, job_stderr)) {
std::cerr << "Could not initialize job paremeter at position 13" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 14, input_files)) {
std::cerr << "Could not initialize job paremeter at position 14" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 15, output_files)) {
std::cerr << "Could not initialize job paremeter at position 15" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 16, workdir)) {
std::cerr << "Could not initialize job paremeter at position 16" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 17, user_id)) {
std::cerr << "Could not initialize job paremeter at position 17" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 18, hooks)) {
std::cerr << "Could not initialize job paremeter at position 18" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_tuple_str_str(term, 19, env)) {
std::cerr << "Could not initialize job paremeter at position 19" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_tuple_atom_str(term, 20, deps)) {
std::cerr << "Could not initialize job paremeter at position 20" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 21, projects)) {
std::cerr << "Could not initialize job paremeter at position 21" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 22, account_id)) {
std::cerr << "Could not initialize job paremeter at position 22" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 23, gang_id)) {
std::cerr << "Could not initialize job paremeter at position 23" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 24, execution_path)) {
std::cerr << "Could not initialize job paremeter at position 24" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 25, script_content)) {
std::cerr << "Could not initialize job paremeter at position 25" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_resource(term, 26, request)) {
std::cerr << "Could not initialize job paremeter at position 26" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_resource(term, 27, resources)) {
std::cerr << "Could not initialize job paremeter at position 27" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 28, container)) {
std::cerr << "Could not initialize job paremeter at position 28" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_atom(term, 29, relocatable)) {
std::cerr << "Could not initialize job paremeter at position 29" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 30, exitcode)) {
std::cerr << "Could not initialize job paremeter at position 30" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 31, signal)) {
std::cerr << "Could not initialize job paremeter at position 31" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 32, priority)) {
std::cerr << "Could not initialize job paremeter at position 32" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_str(term, 33, comment)) {
std::cerr << "Could not initialize job paremeter at position 33" << std::endl;
erl_print_term(stderr, term);
return;
}
if(eterm_to_uint64_t(term, 34, revision)) {
std::cerr << "Could not initialize job paremeter at position 34" << std::endl;
erl_print_term(stderr, term);
return;
}
}
void SwmJob::set_id(const std::string &new_val) {
id = new_val;
}
void SwmJob::set_name(const std::string &new_val) {
name = new_val;
}
void SwmJob::set_cluster_id(const std::string &new_val) {
cluster_id = new_val;
}
void SwmJob::set_nodes(const std::vector<std::string> &new_val) {
nodes = new_val;
}
void SwmJob::set_state(const std::string &new_val) {
state = new_val;
}
void SwmJob::set_start_time(const std::string &new_val) {
start_time = new_val;
}
void SwmJob::set_submit_time(const std::string &new_val) {
submit_time = new_val;
}
void SwmJob::set_end_time(const std::string &new_val) {
end_time = new_val;
}
void SwmJob::set_duration(const uint64_t &new_val) {
duration = new_val;
}
void SwmJob::set_job_stdin(const std::string &new_val) {
job_stdin = new_val;
}
void SwmJob::set_job_stdout(const std::string &new_val) {
job_stdout = new_val;
}
void SwmJob::set_job_stderr(const std::string &new_val) {
job_stderr = new_val;
}
void SwmJob::set_input_files(const std::vector<std::string> &new_val) {
input_files = new_val;
}
void SwmJob::set_output_files(const std::vector<std::string> &new_val) {
output_files = new_val;
}
void SwmJob::set_workdir(const std::string &new_val) {
workdir = new_val;
}
void SwmJob::set_user_id(const std::string &new_val) {
user_id = new_val;
}
void SwmJob::set_hooks(const std::vector<std::string> &new_val) {
hooks = new_val;
}
void SwmJob::set_env(const std::vector<SwmTupleStrStr> &new_val) {
env = new_val;
}
void SwmJob::set_deps(const std::vector<SwmTupleAtomStr> &new_val) {
deps = new_val;
}
void SwmJob::set_projects(const std::vector<uint64_t> &new_val) {
projects = new_val;
}
void SwmJob::set_account_id(const std::string &new_val) {
account_id = new_val;
}
void SwmJob::set_gang_id(const std::string &new_val) {
gang_id = new_val;
}
void SwmJob::set_execution_path(const std::string &new_val) {
execution_path = new_val;
}
void SwmJob::set_script_content(const std::string &new_val) {
script_content = new_val;
}
void SwmJob::set_request(const std::vector<SwmResource> &new_val) {
request = new_val;
}
void SwmJob::set_resources(const std::vector<SwmResource> &new_val) {
resources = new_val;
}
void SwmJob::set_container(const std::string &new_val) {
container = new_val;
}
void SwmJob::set_relocatable(const std::string &new_val) {
relocatable = new_val;
}
void SwmJob::set_exitcode(const uint64_t &new_val) {
exitcode = new_val;
}
void SwmJob::set_signal(const uint64_t &new_val) {
signal = new_val;
}
void SwmJob::set_priority(const uint64_t &new_val) {
priority = new_val;
}
void SwmJob::set_comment(const std::string &new_val) {
comment = new_val;
}
void SwmJob::set_revision(const uint64_t &new_val) {
revision = new_val;
}
std::string SwmJob::get_id() const {
return id;
}
std::string SwmJob::get_name() const {
return name;
}
std::string SwmJob::get_cluster_id() const {
return cluster_id;
}
std::vector<std::string> SwmJob::get_nodes() const {
return nodes;
}
std::string SwmJob::get_state() const {
return state;
}
std::string SwmJob::get_start_time() const {
return start_time;
}
std::string SwmJob::get_submit_time() const {
return submit_time;
}
std::string SwmJob::get_end_time() const {
return end_time;
}
uint64_t SwmJob::get_duration() const {
return duration;
}
std::string SwmJob::get_job_stdin() const {
return job_stdin;
}
std::string SwmJob::get_job_stdout() const {
return job_stdout;
}
std::string SwmJob::get_job_stderr() const {
return job_stderr;
}
std::vector<std::string> SwmJob::get_input_files() const {
return input_files;
}
std::vector<std::string> SwmJob::get_output_files() const {
return output_files;
}
std::string SwmJob::get_workdir() const {
return workdir;
}
std::string SwmJob::get_user_id() const {
return user_id;
}
std::vector<std::string> SwmJob::get_hooks() const {
return hooks;
}
std::vector<SwmTupleStrStr> SwmJob::get_env() const {
return env;
}
std::vector<SwmTupleAtomStr> SwmJob::get_deps() const {
return deps;
}
std::vector<uint64_t> SwmJob::get_projects() const {
return projects;
}
std::string SwmJob::get_account_id() const {
return account_id;
}
std::string SwmJob::get_gang_id() const {
return gang_id;
}
std::string SwmJob::get_execution_path() const {
return execution_path;
}
std::string SwmJob::get_script_content() const {
return script_content;
}
std::vector<SwmResource> SwmJob::get_request() const {
return request;
}
std::vector<SwmResource> SwmJob::get_resources() const {
return resources;
}
std::string SwmJob::get_container() const {
return container;
}
std::string SwmJob::get_relocatable() const {
return relocatable;
}
uint64_t SwmJob::get_exitcode() const {
return exitcode;
}
uint64_t SwmJob::get_signal() const {
return signal;
}
uint64_t SwmJob::get_priority() const {
return priority;
}
std::string SwmJob::get_comment() const {
return comment;
}
uint64_t SwmJob::get_revision() const {
return revision;
}
int swm::eterm_to_job(ETERM* term, int pos, std::vector<SwmJob> &array) {
ETERM* elist = erl_element(pos, term);
if(!ERL_IS_LIST(elist)) {
std::cerr << "Could not parse eterm: not a job list" << std::endl;
return -1;
}
if(ERL_IS_EMPTY_LIST(elist)) {
return 0;
}
const size_t sz = erl_length(elist);
array.reserve(sz);
for(size_t i=0; i<sz; ++i) {
ETERM* e = erl_hd(elist);
array.push_back(SwmJob(e));
elist = erl_tl(elist);
}
return 0;
}
int swm::eterm_to_job(ETERM* eterm, SwmJob &obj) {
obj = SwmJob(eterm);
return 0;
}
void SwmJob::print(const std::string &prefix, const char separator) const {
std::cerr << prefix << id << separator;
std::cerr << prefix << name << separator;
std::cerr << prefix << cluster_id << separator;
if(nodes.empty()) {
std::cerr << prefix << "nodes: []" << separator;
} else {
std::cerr << prefix << "nodes" << ": [";
for(const auto &q: nodes) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
std::cerr << prefix << state << separator;
std::cerr << prefix << start_time << separator;
std::cerr << prefix << submit_time << separator;
std::cerr << prefix << end_time << separator;
std::cerr << prefix << duration << separator;
std::cerr << prefix << job_stdin << separator;
std::cerr << prefix << job_stdout << separator;
std::cerr << prefix << job_stderr << separator;
if(input_files.empty()) {
std::cerr << prefix << "input_files: []" << separator;
} else {
std::cerr << prefix << "input_files" << ": [";
for(const auto &q: input_files) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
if(output_files.empty()) {
std::cerr << prefix << "output_files: []" << separator;
} else {
std::cerr << prefix << "output_files" << ": [";
for(const auto &q: output_files) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
std::cerr << prefix << workdir << separator;
std::cerr << prefix << user_id << separator;
if(hooks.empty()) {
std::cerr << prefix << "hooks: []" << separator;
} else {
std::cerr << prefix << "hooks" << ": [";
for(const auto &q: hooks) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
if(env.empty()) {
std::cerr << prefix << "env: []" << separator;
} else {
std::cerr << prefix << "env" << ": [";
for(const auto &q: env) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
if(deps.empty()) {
std::cerr << prefix << "deps: []" << separator;
} else {
std::cerr << prefix << "deps" << ": [";
for(const auto &q: deps) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
if(projects.empty()) {
std::cerr << prefix << "projects: []" << separator;
} else {
std::cerr << prefix << "projects" << ": [";
for(const auto &q: projects) {
std::cerr << q << ",";
}
std::cerr << "]" << separator;
}
std::cerr << prefix << account_id << separator;
std::cerr << prefix << gang_id << separator;
std::cerr << prefix << execution_path << separator;
std::cerr << prefix << script_content << separator;
if(request.empty()) {
std::cerr << prefix << "request: []" << separator;
} else {
std::cerr << prefix << "request" << ": [";
for(const auto &q: request) {
q.print(prefix, separator);
}
std::cerr << "]" << separator;
}
if(resources.empty()) {
std::cerr << prefix << "resources: []" << separator;
} else {
std::cerr << prefix << "resources" << ": [";
for(const auto &q: resources) {
q.print(prefix, separator);
}
std::cerr << "]" << separator;
}
std::cerr << prefix << container << separator;
std::cerr << prefix << relocatable << separator;
std::cerr << prefix << exitcode << separator;
std::cerr << prefix << signal << separator;
std::cerr << prefix << priority << separator;
std::cerr << prefix << comment << separator;
std::cerr << prefix << revision << separator;
std::cerr << std::endl;
}
| 25.662185 | 82 | 0.643919 | [
"vector"
] |
ce816d45c24d0763d07b99c90b7b661041629001 | 4,885 | cpp | C++ | src/main.cpp | blighli/MyGame | 6cfb7f7e1ceec1ae9f3330eec2115b7733679f06 | [
"MIT"
] | null | null | null | src/main.cpp | blighli/MyGame | 6cfb7f7e1ceec1ae9f3330eec2115b7733679f06 | [
"MIT"
] | null | null | null | src/main.cpp | blighli/MyGame | 6cfb7f7e1ceec1ae9f3330eec2115b7733679f06 | [
"MIT"
] | null | null | null | #include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "WindowManager.h"
#include "ShaderProgram.h"
#include "ModelObject.h"
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <FreeImage/FreeImage.h>
void bindObject(ModelObject& object){
GLuint vao;
glGenVertexArrays(1, &vao);
object.setObjectId(vao);
glBindVertexArray(object.getObjectId());
if(object.getVertices() != NULL) {
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
int vertexBufferSize = sizeof(GLfloat) * object.getVertexCount() * 3;
glBufferData(GL_ARRAY_BUFFER, vertexBufferSize, object.getVertices(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid *) (0));
glEnableVertexAttribArray(0);
}
if(object.getColors() != NULL){
GLuint cbo;
glGenBuffers(1, &cbo);
glBindBuffer(GL_ARRAY_BUFFER, cbo);
int colorBufferSize = sizeof(GLfloat) * object.getVertexCount() * 3;
glBufferData(GL_ARRAY_BUFFER, colorBufferSize, object.getColors(), GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid *) (0));
glEnableVertexAttribArray(1);
}
if(object.getIndices() != NULL){
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
int indexBufferSize = sizeof(int) * object.getIndexCount();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize, object.getIndices(), GL_STATIC_DRAW);
}
}
void drawObject(ModelObject& object) {
glBindVertexArray(object.getObjectId());
if(object.getIndices() == NULL){
glDrawArrays(GL_TRIANGLES, 0, object.getVertexCount());
}
else{
glDrawElements(GL_TRIANGLES, object.getIndexCount(), GL_UNSIGNED_INT, 0);
}
}
int main()
{
WindowManager windowManager(false, 800,600, "Main Window");
windowManager.init();
//只能创建Context后才能初始化glew
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cout<<"Error: "<<glewGetErrorString(err)<< std::endl;
return -1;
}
else{
std::cout<<"Status: Using GLEW"<<glewGetString(GLEW_VERSION)<<std::endl;
}
const char* filename="media/image/demo.jpg";
FreeImage_Initialise();
//image format
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
//pointer to the image, once loaded
FIBITMAP *dib(0);
//pointer to the image data
BYTE* bits(0);
//image width and height
unsigned int width(0), height(0);
//OpenGL's image ID to map to
GLuint gl_texID;
//check the file signature and deduce its format
fif = FreeImage_GetFileType(filename, 0);
//if still unknown, try to guess the file format from the file extension
if(fif == FIF_UNKNOWN)
fif = FreeImage_GetFIFFromFilename(filename);
//if still unkown, return failure
if(fif == FIF_UNKNOWN)
return false;
//check that the plugin has reading capabilities and load the file
if(FreeImage_FIFSupportsReading(fif))
dib = FreeImage_Load(fif, filename);
//if the image failed to load, return failure
if(!dib)
return false;
//retrieve the image data
bits = FreeImage_GetBits(dib);
//get the image width and height
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
std::cout<<"w="<<width<<"h="<<height<<std::endl;
ModelObject object;
object.loadObject("media/object/triangle.txt");
bindObject(object);
ModelObject mat;
mat.createMat();
bindObject(mat);
ShaderProgram program;
program.loadShader(GL_VERTEX_SHADER, "media/shader/vertex.shader");
program.loadShader(GL_FRAGMENT_SHADER, "media/shader/fragment.shader");
program.use();
glEnable(GL_DEPTH_TEST);
//处理事件
while (!glfwWindowShouldClose(windowManager.getWindow()))
{
glfwPollEvents();
static const float bgColor[] = {0.0f, 0.0f, 0.0f, 1.0f};
glClearBufferfv(GL_COLOR, 0, bgColor);
static const float depth = 1.0;
glClearBufferfv(GL_DEPTH, 0, &depth);
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float rot = windowManager.getRot();
//std::cout<<"rot = "<<rot<<std::endl;
glm::mat4 Proj = glm::perspective(glm::radians(45.0f), 4.0f/3.0f, 0.1f, 10.0f);
glm::mat4 View = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 Model = glm::rotate(glm::radians(rot), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 MPV = Proj * View * Model;
GLint loc = glGetUniformLocation(program.getProgram(), "mvp");
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(MPV));
drawObject(object);
drawObject(mat);
glfwSwapBuffers(windowManager.getWindow());
}
return 0;
}
| 31.516129 | 124 | 0.649335 | [
"object",
"model"
] |
ce83aab0246a75871e87ef2448de9ca490e3754e | 2,268 | cpp | C++ | functions.cpp | ronyadin/msse-cpp-lessons | af60944d2a8f28b65f52dea1531b45112ae36d15 | [
"MIT"
] | null | null | null | functions.cpp | ronyadin/msse-cpp-lessons | af60944d2a8f28b65f52dea1531b45112ae36d15 | [
"MIT"
] | null | null | null | functions.cpp | ronyadin/msse-cpp-lessons | af60944d2a8f28b65f52dea1531b45112ae36d15 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <stdexcept>
/*
void say_something(void)
{
std::cout << "Something!" << std::endl;
return; // returns nothing. like void,
}
int main(void)
{
const double pi = 3.1415;
double pi2 = 2.0 * pi;
std::cout << pi2 << std::endl;
return 0;
}
int main(void)
{
const double pi = 3.1415;
const double & rpi = pi;
//double & rpi2 = pi; // this doesn't work
//double * rpi2 = π // pointers don't work either
const double & rpi2 = pi;
std::cout << pi << std::endl << rpi << std::endl << rpi2 << std::endl;
return 0;
}
void convert_ftoc(const double & temperature)
{
temperature = (temperature - 32.0)*(5.0/9.0);
std::cout << "Temperature in function: " << &temperature << std::endl;
}
void convert_ftoc(double * temperature)
{
*temperature = (*temperature - 32.0)*(5.0/9.0);
std::cout << "Temperature in function: " << temperature << std::endl;
}
*/
std::vector<double> convert_ftoc_vec(std::vector<double> temps)
{
// Loop over temps, covert them, store them in another vector
std::vector<double> new_temps;
for (size_t i = 0; i < temps.size(); i++)
{
double new_temp = (temps[i] - 32) * (5.0/9.0);
new_temps.push_back(new_temp);
}
return new_temps;
}
double convert_ftoc( double temperature)
{
const double absolute_zero = -459.67;
if(temperature < absolute_zero)
{
throw std::runtime_error("Given a temperature below absolute zero!");
}
return (temperature - 32.0)*(5.0/9.0);
}
int main(void)
{
/*const double temperature = 68.1;
double new_temperature = convert_ftoc(temperature);
std::cout << "New temperature: " << new_temperature << std::endl;
std::vector<double> temperatures;
temperatures.push_back(212.0);
temperatures.push_back(32.0);
temperatures.push_back(-40.0);
std::vector<double> new_temps = convert_ftoc_vec(temperatures);
std::cout << new_temps[1] << std::endl;
*/
try {
std::cout << convert_ftoc(-600.0) << std::endl;
}
catch(std::exception & ex)
{
std::cout << "Program encountered an error!" << std::endl;
std::cout << ex.what() << std::endl;
return 1;
}
return 0;
} | 24.652174 | 77 | 0.605379 | [
"vector"
] |
ce8419d8680327f322f7920c38ef85b591c2c277 | 2,562 | hpp | C++ | src/ast.hpp | rytar/QiR | d26616c800d02d4a9a10301456d2bb6fcbee02e0 | [
"MIT"
] | null | null | null | src/ast.hpp | rytar/QiR | d26616c800d02d4a9a10301456d2bb6fcbee02e0 | [
"MIT"
] | null | null | null | src/ast.hpp | rytar/QiR | d26616c800d02d4a9a10301456d2bb6fcbee02e0 | [
"MIT"
] | null | null | null | #ifndef QIRAST
#define QIRAST
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include <vector>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/variant.hpp>
using namespace boost::spirit;
namespace phx = boost::phoenix;
namespace ast {
struct lt;
struct lte;
struct gt;
struct gte;
struct eql;
struct neq;
struct add;
struct sub;
struct mul;
struct div;
struct mod;
struct ifstat;
template<typename T>
struct vdec;
template<typename Op>
struct binary_op;
template<typename T>
struct unary_op;
struct var_ref {
std::string id;
var_ref(const std::string& id_) : id(id_) {}
};
struct assign;
using value = boost::variant<
int,
bool,
boost::recursive_wrapper<ifstat>,
boost::recursive_wrapper<vdec<int>>,
boost::recursive_wrapper<vdec<bool>>,
boost::recursive_wrapper<binary_op<lt>>,
boost::recursive_wrapper<binary_op<lte>>,
boost::recursive_wrapper<binary_op<gt>>,
boost::recursive_wrapper<binary_op<gte>>,
boost::recursive_wrapper<binary_op<eql>>,
boost::recursive_wrapper<binary_op<neq>>,
boost::recursive_wrapper<binary_op<add>>,
boost::recursive_wrapper<binary_op<sub>>,
boost::recursive_wrapper<binary_op<mul>>,
boost::recursive_wrapper<binary_op<div>>,
boost::recursive_wrapper<binary_op<mod>>,
boost::recursive_wrapper<var_ref>,
boost::recursive_wrapper<assign>
>;
struct ifstat {
value cond;
std::vector<value> then_stat;
std::vector<value> else_stat;
ifstat(const value& cond_, const std::vector<value>& then_stat_, const std::vector<value>& else_stat_)
: cond(cond_), then_stat(then_stat_), else_stat(else_stat_) {}
};
template<typename T>
struct vdec {
std::string id;
value val;
vdec(std::string& id_, const value& val_) : id(id_), val(val_) {}
};
template<typename Op>
struct binary_op {
value lhs;
value rhs;
binary_op(const value& lhs_, const value& rhs_) : lhs(lhs_), rhs(rhs_) {}
};
template<typename T>
struct unary_op {
value val;
unary_op(const value& val_) : val(val_) {}
};
struct assign {
std::string id;
value val;
assign(std::string& id_, const value& val_) : id(id_), val(val_) {}
};
}
#endif | 23.722222 | 110 | 0.62256 | [
"vector"
] |
ce84af83b6f4cdb0a0e901afc594c5fec6124ca1 | 45,486 | inl | C++ | shared/Base/Utility.inl | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | shared/Base/Utility.inl | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | shared/Base/Utility.inl | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------------------------------------------
#include "Base/Utility.hpp"
#include "Base/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
#include <ctime>
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdarg>
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
#include <windows.h>
#endif // SQMOD_OS_WINDOWS
// ------------------------------------------------------------------------------------------------
#ifndef SQMOD_PLUGIN_API
#include "Library/Numeric/LongInt.hpp"
#include <sqstdstring.h>
#endif // SQMOD_PLUGIN_API
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
PluginFuncs* _Func = nullptr;
PluginCallbacks* _Clbk = nullptr;
PluginInfo* _Info = nullptr;
/* ------------------------------------------------------------------------------------------------
* Common buffers to reduce memory allocations. To be immediately copied upon return!
*/
static SQChar g_Buffer[4096];
static SQChar g_NumBuf[1024];
// ------------------------------------------------------------------------------------------------
SStr GetTempBuff()
{
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
Uint32 GetTempBuffSize()
{
return sizeof(g_Buffer);
}
/* --------------------------------------------------------------------------------------------
* Raw console message output.
*/
static inline void OutputMessageImpl(CCStr msg, va_list args)
{
#ifdef SQMOD_OS_WINDOWS
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csb_before;
GetConsoleScreenBufferInfo( hstdout, &csb_before);
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);
std::printf("[SQMOD] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::vprintf(msg, args);
std::puts("");
SetConsoleTextAttribute(hstdout, csb_before.wAttributes);
#else
std::printf("\033[21;32m[SQMOD]\033[0m");
std::vprintf(msg, args);
std::puts("");
#endif // SQMOD_OS_WINDOWS
}
/* --------------------------------------------------------------------------------------------
* Raw console error output.
*/
static inline void OutputErrorImpl(CCStr msg, va_list args)
{
#ifdef SQMOD_OS_WINDOWS
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csb_before;
GetConsoleScreenBufferInfo( hstdout, &csb_before);
SetConsoleTextAttribute(hstdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::printf("[SQMOD] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::vprintf(msg, args);
std::puts("");
SetConsoleTextAttribute(hstdout, csb_before.wAttributes);
#else
std::printf("\033[21;91m[SQMOD]\033[0m");
std::vprintf(msg, args);
std::puts("");
#endif // SQMOD_OS_WINDOWS
}
// --------------------------------------------------------------------------------------------
void OutputDebug(CCStr msg, ...)
{
#ifdef _DEBUG
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputMessageImpl(msg, args);
// Finalize the arguments list
va_end(args);
#else
SQMOD_UNUSED_VAR(msg);
#endif
}
// --------------------------------------------------------------------------------------------
void OutputMessage(CCStr msg, ...)
{
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputMessageImpl(msg, args);
// Finalize the arguments list
va_end(args);
}
// --------------------------------------------------------------------------------------------
void OutputError(CCStr msg, ...)
{
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputErrorImpl(msg, args);
// Finalize the arguments list
va_end(args);
}
// ------------------------------------------------------------------------------------------------
void SqThrowF(CSStr str, ...)
{
// Initialize the argument list
va_list args;
va_start (args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
// Write a generic message at least
std::strcpy(g_Buffer, "Unknown error has occurred");
}
// Finalize the argument list
va_end(args);
// Throw the exception with the resulted message
throw Sqrat::Exception(g_Buffer);
}
// ------------------------------------------------------------------------------------------------
CSStr FmtStr(CSStr str, ...)
{
// Initialize the argument list
va_list args;
va_start (args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
STHROWF("Failed to run the specified string format");
}
// Finalize the argument list
va_end(args);
// Return the data from the buffer
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
CSStr ToStrF(CSStr str, ...)
{
// Prepare the arguments list
va_list args;
va_start(args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
g_Buffer[0] = '\0'; // Make sure the string is null terminated
}
// Finalize the argument list
va_end(args);
// Return the resulted string
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
CSStr ToStringF(CSStr str, ...)
{
// Acquire a moderately sized buffer
Buffer b(128);
// Prepare the arguments list
va_list args;
va_start (args, str);
// Attempt to run the specified format
if (b.WriteF(0, str, args) == 0)
{
b.At(0) = '\0'; // Make sure the string is null terminated
}
// Finalize the argument list
va_end(args);
// Return the resulted string
return b.Get< SQChar >();
}
// ------------------------------------------------------------------------------------------------
SQRESULT SqThrowErrorF(HSQUIRRELVM vm, CCStr str, ...)
{
// Prepare the arguments list
va_list args;
va_start(args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
return sq_throwerror(vm, _SC("Formatting error occurred while throwing a script error"));
}
// Finalize the argument list
va_end(args);
// Throw the resulted string
return sq_throwerror(vm, g_Buffer);
}
// ------------------------------------------------------------------------------------------------
bool SToB(CSStr str)
{
// Temporary buffer to store the lowercase string
SQChar buffer[8];
// The currently processed character
unsigned i = 0;
// Convert only the necessary characters to lowercase
while (i < 7 && *str != '\0')
{
buffer[i++] = static_cast< SQChar >(std::tolower(*(str++)));
}
// Add the null terminator
buffer[i] = '\0';
// Compare the lowercase string and return the result
return (std::strcmp(buffer, "true") == 0 || std::strcmp(buffer, "yes") == 0 ||
std::strcmp(buffer, "on") == 0 || std::strcmp(buffer, "1") == 0) ? true : false;
}
// ------------------------------------------------------------------------------------------------
StackStrF & DummyStackStrF()
{
static StackStrF s;
s.Release();
return s;
}
// ------------------------------------------------------------------------------------------------
Object & NullObject()
{
static Object o;
o.Release();
return o;
}
// ------------------------------------------------------------------------------------------------
LightObj & NullLightObj()
{
static LightObj o;
o.Release();
return o;
}
// ------------------------------------------------------------------------------------------------
Table & NullTable()
{
static Table t;
t.Release();
return t;
}
// ------------------------------------------------------------------------------------------------
Array & NullArray()
{
static Array a;
a.Release();
return a;
}
// ------------------------------------------------------------------------------------------------
Function & NullFunction()
{
static Function f;
f.Release();
return f;
}
// ------------------------------------------------------------------------------------------------
String & NullString()
{
static String s;
s.resize(0);
return s;
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int8 >::ToStr(Int8 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%d", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Int8 ConvNum< Int8 >::FromStr(CSStr s)
{
return ConvTo< Int8 >::From(std::strtol(s, nullptr, 10));
}
Int8 ConvNum< Int8 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int8 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint8 >::ToStr(Uint8 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%u", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Uint8 ConvNum< Uint8 >::FromStr(CSStr s)
{
return ConvTo< Uint8 >::From(std::strtoul(s, nullptr, 10));
}
Uint8 ConvNum< Uint8 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint8 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int16 >::ToStr(Int16 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%d", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Int16 ConvNum< Int16 >::FromStr(CSStr s)
{
return ConvTo< Int16 >::From(std::strtol(s, nullptr, 10));
}
Int16 ConvNum< Int16 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int16 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint16 >::ToStr(Uint16 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%u", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Uint16 ConvNum< Uint16 >::FromStr(CSStr s)
{
return ConvTo< Uint16 >::From(std::strtoul(s, nullptr, 10));
}
Uint16 ConvNum< Uint16 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint16 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int32 >::ToStr(Int32 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%d", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Int32 ConvNum< Int32 >::FromStr(CSStr s)
{
return ConvTo< Int32 >::From(std::strtol(s, nullptr, 10));
}
Int32 ConvNum< Int32 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int32 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint32 >::ToStr(Uint32 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%u", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Uint32 ConvNum< Uint32 >::FromStr(CSStr s)
{
return ConvTo< Uint32 >::From(std::strtoul(s, nullptr, 10));
}
Uint32 ConvNum< Uint32 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint32 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int64 >::ToStr(Int64 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%lld", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Int64 ConvNum< Int64 >::FromStr(CSStr s)
{
return std::strtoll(s, nullptr, 10);
}
Int64 ConvNum< Int64 >::FromStr(CSStr s, Int32 base)
{
return std::strtoll(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint64 >::ToStr(Uint64 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%llu", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Uint64 ConvNum< Uint64 >::FromStr(CSStr s)
{
return std::strtoull(s, nullptr, 10);
}
Uint64 ConvNum< Uint64 >::FromStr(CSStr s, Int32 base)
{
return std::strtoull(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< LongI >::ToStr(LongI v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%ld", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
LongI ConvNum< LongI >::FromStr(CSStr s)
{
return std::strtol(s, nullptr, 10);
}
LongI ConvNum< LongI >::FromStr(CSStr s, Int32 base)
{
return std::strtol(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Ulong >::ToStr(Ulong v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%lu", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuf;
}
Ulong ConvNum< Ulong >::FromStr(CSStr s)
{
return std::strtoul(s, nullptr, 10);
}
Ulong ConvNum< Ulong >::FromStr(CSStr s, Int32 base)
{
return std::strtoul(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Float32 >::ToStr(Float32 v)
{
// Attempt to convert the value to a string
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%f", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the data from the buffer
return g_NumBuf;
}
Float32 ConvNum< Float32 >::FromStr(CSStr s)
{
return std::strtof(s, nullptr);
}
Float32 ConvNum< Float32 >::FromStr(CSStr s, Int32 /*base*/)
{
return std::strtof(s, nullptr);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Float64 >::ToStr(Float64 v)
{
// Attempt to convert the value to a string
if (std::snprintf(g_NumBuf, sizeof(g_NumBuf), "%f", v) < 0)
{
g_NumBuf[0] = '\0';
}
// Return the data from the buffer
return g_NumBuf;
}
Float64 ConvNum< Float64 >::FromStr(CSStr s)
{
return std::strtod(s, nullptr);
}
Float64 ConvNum< Float64 >::FromStr(CSStr s, Int32 /*base*/)
{
return std::strtod(s, nullptr);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< bool >::ToStr(bool v)
{
if (v)
{
g_NumBuf[0] = 't';
g_NumBuf[1] = 'r';
g_NumBuf[2] = 'u';
g_NumBuf[3] = 'e';
g_NumBuf[4] = '\0';
}
else
{
g_NumBuf[0] = 'f';
g_NumBuf[1] = 'a';
g_NumBuf[2] = 'l';
g_NumBuf[3] = 's';
g_NumBuf[4] = 'e';
g_NumBuf[5] = '\0';
}
return g_NumBuf;
}
bool ConvNum< bool >::FromStr(CSStr s)
{
return (std::strcmp(s, "true") == 0) ? true : false;
}
bool ConvNum< bool >::FromStr(CSStr s, Int32 /*base*/)
{
return (std::strcmp(s, "true") == 0) ? true : false;
}
// ------------------------------------------------------------------------------------------------
CSStr SqTypeName(SQObjectType type)
{
switch (type)
{
case OT_NULL: return _SC("null");
case OT_INTEGER: return _SC("integer");
case OT_FLOAT: return _SC("float");
case OT_BOOL: return _SC("bool");
case OT_STRING: return _SC("string");
case OT_TABLE: return _SC("table");
case OT_ARRAY: return _SC("array");
case OT_USERDATA: return _SC("userdata");
case OT_CLOSURE: return _SC("closure");
case OT_NATIVECLOSURE: return _SC("nativeclosure");
case OT_GENERATOR: return _SC("generator");
case OT_USERPOINTER: return _SC("userpointer");
case OT_THREAD: return _SC("thread");
case OT_FUNCPROTO: return _SC("funcproto");
case OT_CLASS: return _SC("class");
case OT_INSTANCE: return _SC("instance");
case OT_WEAKREF: return _SC("weakref");
case OT_OUTER: return _SC("outer");
default: return _SC("unknown");
}
}
// ------------------------------------------------------------------------------------------------
String SqTypeName(HSQUIRRELVM vm, SQInteger idx)
{
// Remember the current stack size
const StackGuard sg(vm);
// Attempt to retrieve the type name of the specified value
if (SQ_FAILED(sq_typeof(vm, idx)))
{
return _SC("unknown");
}
// Attempt to convert the obtained value to a string
StackStrF val(vm, -1);
// Did the conversion failed?
if (SQ_FAILED(val.Proc(false)))
{
return _SC("unknown");
}
// Return the obtained string value
return String(val.mPtr, val.mLen);
}
// ------------------------------------------------------------------------------------------------
Object BufferToStrObj(const Buffer & b)
{
// Obtain the initial stack size
const StackGuard sg(DefaultVM::Get());
// Push the string onto the stack
sq_pushstring(DefaultVM::Get(), b.Data(), b.Position());
// Obtain the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
// --------------------------------------------------------------------------------------------
Object BufferToStrObj(const Buffer & b, Uint32 size)
{
// Perform a range check on the specified buffer
if (size > b.Capacity())
{
STHROWF("The specified buffer size is out of range: %u >= %u", size, b.Capacity());
}
// Obtain the initial stack size
const StackGuard sg(DefaultVM::Get());
// Push the string onto the stack
sq_pushstring(DefaultVM::Get(), b.Data(), size);
// Obtain the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
// ------------------------------------------------------------------------------------------------
Object MakeSLongObj(Int64 value)
{
// Obtain the default virtual machine
HSQUIRRELVM vm = DefaultVM::Get();
// Obtain the initial stack size
const StackGuard sg(vm);
#ifdef SQMOD_PLUGIN_API
// Push a long integer instance with the requested value on the stack
SqMod_PushSLongObject(vm, value);
#else
// Transform the specified value into a script object
PushVar< SLongInt >(vm, SLongInt(value));
#endif // SQMOD_PLUGIN_API
// Obtain the object from the stack and return it
return Var< Object >(vm, -1).value;
}
// ------------------------------------------------------------------------------------------------
Object MakeULongObj(Uint64 value)
{
// Obtain the default virtual machine
HSQUIRRELVM vm = DefaultVM::Get();
// Obtain the initial stack size
const StackGuard sg(vm);
#ifdef SQMOD_PLUGIN_API
// Push a long integer instance with the requested value on the stack
SqMod_PushULongObject(vm, value);
#else
// Transform the specified value into a script object
PushVar< ULongInt >(vm, ULongInt(value));
#endif // SQMOD_PLUGIN_API
// Obtain the object from the stack and return it
return Var< Object >(vm, -1).value;
}
// ------------------------------------------------------------------------------------------------
Object MakeSLongObj(HSQUIRRELVM vm, Int64 value)
{
// Obtain the initial stack size
const StackGuard sg(vm);
#ifdef SQMOD_PLUGIN_API
// Push a long integer instance with the requested value on the stack
SqMod_PushSLongObject(vm, value);
#else
// Transform the specified value into a script object
PushVar< SLongInt >(vm, SLongInt(value));
#endif // SQMOD_PLUGIN_API
// Obtain the object from the stack and return it
return Var< Object >(vm, -1).value;
}
// ------------------------------------------------------------------------------------------------
Object MakeULongObj(HSQUIRRELVM vm, Uint64 value)
{
// Obtain the initial stack size
const StackGuard sg(vm);
#ifdef SQMOD_PLUGIN_API
// Push a long integer instance with the requested value on the stack
SqMod_PushULongObject(vm, value);
#else
// Transform the specified value into a script object
PushVar< ULongInt >(vm, ULongInt(value));
#endif // SQMOD_PLUGIN_API
// Obtain the object from the stack and return it
return Var< Object >(vm, -1).value;
}
// ------------------------------------------------------------------------------------------------
Int64 FetchSLongObjVal(const Object & value)
{
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Obtain the initial stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Retrieve and return the object value from the stack
return PopStackSLong(vm, -1);
}
// ------------------------------------------------------------------------------------------------
Uint64 FetchULongObjVal(const Object & value)
{
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Obtain the initial stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Retrieve and return the object value from the stack
return PopStackSLong(vm, -1);
}
// ------------------------------------------------------------------------------------------------
SQRESULT FetchDateObjVal(const Object & value, Uint16 & year, Uint8 & month, Uint8 & day)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date components from the date instance
return SqMod_GetDate(vm, -1, &year, &month, &day);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return SQ_ERROR;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
SQMOD_UNUSED_VAR(year);
SQMOD_UNUSED_VAR(month);
SQMOD_UNUSED_VAR(day);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
CSStr FetchDateObjStr(const Object & value)
{
#ifdef SQMOD_PLUGIN_API
static SQChar buffer[32];
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date instance as a string
StackStrF val(vm, -1);
// Validate the result
if (SQ_FAILED(val.Proc(false)))
{
return _SC("1000-01-01");
}
// Copy the string into the common buffer
std::strncpy(buffer, val.mPtr, sizeof(buffer));
// Return the obtained string
return buffer;
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return nullptr;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQRESULT FetchTimeObjVal(const Object & value, Uint8 & hour, Uint8 & minute, Uint8 & second)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date components from the date instance
return SqMod_GetTime(vm, -1, &hour, &minute, &second, nullptr);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return SQ_ERROR;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
SQMOD_UNUSED_VAR(hour);
SQMOD_UNUSED_VAR(minute);
SQMOD_UNUSED_VAR(second);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQRESULT FetchTimeObjVal(const Object & value, Uint8 & hour, Uint8 & minute, Uint8 & second, Uint16 & millisecond)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date components from the date instance
return SqMod_GetTime(vm, -1, &hour, &minute, &second, &millisecond);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return SQ_ERROR;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
SQMOD_UNUSED_VAR(hour);
SQMOD_UNUSED_VAR(minute);
SQMOD_UNUSED_VAR(second);
SQMOD_UNUSED_VAR(millisecond);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
CSStr FetchTimeObjStr(const Object & value)
{
#ifdef SQMOD_PLUGIN_API
static SQChar buffer[32];
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the time instance as a string
StackStrF val(vm, -1);
// Validate the result
if (SQ_FAILED(val.Proc(false)))
{
return _SC("00:00:00");
}
// Copy the string into the common buffer
std::strncpy(buffer, val.mPtr, sizeof(buffer));
// Remove the millisecond part from the string, if any
buffer[8] = '\0';
// Return the obtained string
return buffer;
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return nullptr;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
Int32 FetchTimeObjSeconds(const Object & value)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// The time components
uint8_t h = 0, m = 0, s = 0;
// Grab the time components from the time instance
if (SQ_FAILED(SqMod_GetTime(vm, -1, &h, &m, &s, nullptr)))
{
STHROWF("Unable to obtain the time info");
}
// Return the number of seconds in the specified time
return ((h * (60 * 60)) + (m * 60) + s);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return 0;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQRESULT FetchDatetimeObjVal(const Object & value, Uint16 & year, Uint8 & month, Uint8 & day, Uint8 & hour,
Uint8 & minute, Uint8 & second)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date components from the date instance
return SqMod_GetDatetime(vm, -1, &year, &month, &day, &hour, &minute, &second, nullptr);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return SQ_ERROR;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
SQMOD_UNUSED_VAR(year);
SQMOD_UNUSED_VAR(month);
SQMOD_UNUSED_VAR(day);
SQMOD_UNUSED_VAR(hour);
SQMOD_UNUSED_VAR(minute);
SQMOD_UNUSED_VAR(second);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQRESULT FetchDatetimeObjVal(const Object & value, Uint16 & year, Uint8 & month, Uint8 & day, Uint8 & hour,
Uint8 & minute, Uint8 & second, Uint16 & millisecond)
{
#ifdef SQMOD_PLUGIN_API
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date components from the date instance
return SqMod_GetDatetime(vm, -1, &year, &month, &day, &hour, &minute, &second, &millisecond);
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return SQ_ERROR;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
SQMOD_UNUSED_VAR(year);
SQMOD_UNUSED_VAR(month);
SQMOD_UNUSED_VAR(day);
SQMOD_UNUSED_VAR(hour);
SQMOD_UNUSED_VAR(minute);
SQMOD_UNUSED_VAR(second);
SQMOD_UNUSED_VAR(millisecond);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
CSStr FetchDatetimeObjStr(const Object & value)
{
#ifdef SQMOD_PLUGIN_API
static SQChar buffer[32];
// Grab the associated object virtual machine
HSQUIRRELVM vm = value.GetVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the specified object onto the stack
Var< const Object & >::push(vm, value);
// Grab the date-time instance as a string
StackStrF val(vm, -1);
// Validate the result
if (SQ_FAILED(val.Proc(false)))
{
return _SC("1000-01-01 00:00:00");
}
// Copy the string into the common buffer
std::strncpy(buffer, val.mPtr, sizeof(buffer));
// Remove the millisecond part from the string, if any
buffer[19] = '\0';
// Return the obtained string
return buffer;
#else
STHROWF("This method is only available in modules");
// Should not reach this point
return nullptr;
// Avoid unused parameter warnings
SQMOD_UNUSED_VAR(value);
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQInteger PopStackInteger(HSQUIRRELVM vm, SQInteger idx)
{
#ifdef SQMOD_PLUGIN_API
return SqMod_PopStackInteger(vm, idx);
#else
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return val;
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< SQInteger >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return static_cast< SQInteger >(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return ConvTo< SQInteger >::From(std::strtoll(val, nullptr, 10));
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return sq_getsize(vm, idx);
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< SQInteger >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< SQInteger >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return sq_getsize(vm, idx);
} break;
default: break;
}
// Default to 0
return 0;
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
SQFloat PopStackFloat(HSQUIRRELVM vm, SQInteger idx)
{
#ifdef SQMOD_PLUGIN_API
return SqMod_PopStackFloat(vm, idx);
#else
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return val;
} break;
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return ConvTo< SQFloat >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return ConvTo< SQFloat >::From(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
#ifdef SQUSEDOUBLE
return std::strtod(val, nullptr);
#else
return std::strtof(val, nullptr);
#endif // SQUSEDOUBLE
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return ConvTo< SQFloat >::From(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< SQFloat >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< SQFloat >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return ConvTo< SQFloat >::From(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0.0;
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
{
#ifdef SQMOD_PLUGIN_API
return SqMod_PopStackSLong(vm, idx);
#else
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Int64 >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return std::strtoll(val, nullptr, 10);
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return Var< const SLongInt & >(vm, idx).value.GetNum();
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< Int64 >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0;
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
{
#ifdef SQMOD_PLUGIN_API
return SqMod_PopStackULong(vm, idx);
#else
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return std::strtoull(val, nullptr, 10);
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< Uint64 >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return Var< const ULongInt & >(vm, idx).value.GetNum();
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0;
#endif // SQMOD_PLUGIN_API
}
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_PLUGIN_API
// ------------------------------------------------------------------------------------------------
bool CheckModuleAPIVer(CCStr ver, CCStr mod)
{
// Obtain the numeric representation of the API version
const LongI vernum = std::strtol(ver, nullptr, 10);
// Check against version mismatch
if (vernum == SQMOD_API_VER)
{
return true;
}
// Log the incident
OutputError("API version mismatch on %s", mod);
OutputMessage("=> Requested: %ld Have: %ld", vernum, SQMOD_API_VER);
// Invoker should not attempt to communicate through the module API
return false;
}
// ------------------------------------------------------------------------------------------------
bool CheckModuleOrder(PluginFuncs * vcapi, Uint32 mod_id, CCStr mod)
{
// Make sure a valid server API was provided
if (!vcapi)
{
OutputError("Invalid pointer to server API structure");
// Validation failed!
return false;
}
// Attempt to find the host plug-in identifier
const int plugin_id = vcapi->FindPlugin(SQMOD_HOST_NAME);
// See if our module was loaded after the host plug-in
if (plugin_id < 0)
{
OutputError("%s: could find the host plug-in", mod);
// Validation failed!
return false;
}
// Should never reach this point but just in case
else if (static_cast< Uint32 >(plugin_id) > mod_id)
{
OutputError("%s: loaded after the host plug-in", mod);
// Validation failed!
return false;
}
// Loaded in the correct order
return true;
}
// ------------------------------------------------------------------------------------------------
void ImportModuleAPI(PluginFuncs * vcapi, CCStr mod)
{
// Make sure a valid server API was provided
if (!vcapi)
{
STHROWF("%s: Invalid pointer to server API structure", mod);
}
size_t exports_struct_size;
// Attempt to find the host plug-in identifier
int plugin_id = vcapi->FindPlugin(SQMOD_HOST_NAME);
// Validate the obtained plug-in identifier
if (plugin_id < 0)
{
STHROWF("%s: Unable to obtain the host plug-in identifier", mod);
}
// Attempt to retrieve the host plug-in exports
const void ** raw_plugin_exports = vcapi->GetPluginExports(plugin_id, &exports_struct_size);
// See if the size of the exports structure matches
if (exports_struct_size <= 0)
{
STHROWF("%s: Incompatible host plug-in exports structure", mod);
}
// See if we have any exports from the host plug-in
else if (raw_plugin_exports == nullptr)
{
STHROWF("%s: Unable to obtain pointer host plug-in exports", mod);
}
// Obtain pointer to the exports structure
const SQMODEXPORTS * plugin_exports = *reinterpret_cast< const SQMODEXPORTS ** >(raw_plugin_exports);
// See if we have a valid pointer to the exports structure
if (plugin_exports == nullptr)
{
STHROWF("%s: Invalid pointer to host plug-in exports structure", mod);
}
else if (plugin_exports->PopulateModuleAPI == nullptr || plugin_exports->PopulateSquirrelAPI == nullptr)
{
STHROWF("%s: Invalid pointer to host plug-in import functions", mod);
}
// Prepare a structure to obtain the module API
SQMODAPI sqmodapi;
// Attempt to populate the structure
switch (plugin_exports->PopulateModuleAPI(&sqmodapi, sizeof(SQMODAPI)))
{
case -1: STHROWF("%s: Incompatible module API structure", mod);
// fall through
case 0: STHROWF("%s: Invalid pointer to module API structure", mod);
}
// Prepare a structure to obtain the squirrel API
SQLIBAPI sqlibapi;
// Attempt to populate the structure
switch (plugin_exports->PopulateSquirrelAPI(&sqlibapi, sizeof(SQLIBAPI)))
{
case -1: STHROWF("%s: Incompatible squirrel API structure", mod);
// fall through
case 0: STHROWF("%s: Invalid pointer to squirrel API structure", mod);
}
// Attempt to expand the obtained API
if (!sqmod_api_expand(&sqmodapi))
{
// Collapse the API first
sqmod_api_collapse();
// Now it's safe to throw the exception
STHROWF("%s: Unable to expand module API structure", mod);
}
else if (!sqlib_api_expand(&sqlibapi))
{
// Collapse the API first
sqmod_api_collapse();
sqlib_api_collapse();
// Now it's safe to throw the exception
STHROWF("%s: Unable to expand module API structure", mod);
}
}
#endif // SQMOD_PLUGIN_API
} // Namespace:: SqMod
| 31.261856 | 114 | 0.522798 | [
"object",
"transform"
] |
ce91ab8f08971e31f396d6f39996e21478e48cdf | 16,768 | cpp | C++ | jam/src/SkinnedModel.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | jam/src/SkinnedModel.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | jam/src/SkinnedModel.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | /**********************************************************************************
*
* SkinnedModel.cpp
*
* This file is part of Jam
*
* Copyright (c) 2014-2019 Giovanni Zito.
* Copyright (c) 2014-2019 Jam contributors (cf. AUTHORS.md)
*
* 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 "stdafx.h"
#include <jam/SkinnedModel.h>
#include <jam/Gfx.h>
#include <jam/Application.h>
#include <jam/Scene.h>
#include <jam/Camera.h>
#include <jam/Transform.h>
#include <jam/core/filesystem.h>
#include <jam/core/geom.h>
namespace jam
{
//*******************
//
// Class SkinnedModel
//
//*******************
SkinnedModel::SkinnedModel() :
GameObject(),
m_meshes(),
m_folder(),
m_numBones(0),
m_globalInverseTransform(),
m_boneInfo(),
m_pScene(0),
m_import(),
m_boneMapping(),
m_animMapping()
{
}
SkinnedModel::~SkinnedModel()
{
}
void SkinnedModel::draw()
{
static char buff[32] = {0} ;
Camera* pCam = GetAppMgr().getScene()->getCamera() ;
SkinnedMesh* pMesh = 0 ;
Material* pMaterial = 0 ;
std::vector<Matrix4> transforms;
float runningTime = GetAppMgr().getTotalElapsed() ;
boneTransform(runningTime, 0, transforms);
bool boneTransformSet = false ;
Shader* pProg = nullptr ;
for( size_t i = 0; i < m_meshes.size(); i++ ) {
pMesh = m_meshes[i] ;
pMaterial = pMesh->getMaterial() ;
pProg = pMaterial->getShader() ;
pProg->use();
if( !boneTransformSet ) {
JAM_ASSERT(transforms.size() < 100);
for (unsigned int i = 0 ; i < transforms.size() ; i++) {
sprintf(buff,JAM_PROGRAM_UNIFORM_BONES,i) ;
pProg->setUniform( buff, transforms[i] ) ;
}
boneTransformSet = true ;
}
pProg->setModelMatrix(getTransform().getWorldTformMatrix()) ;
// the 3 following commands are needed if camera is changed since last frame
// OR gpu program / uniforms are uninitialized
pProg->setViewMatrix(pCam->getViewMatrix()) ;
pProg->setProjectionMatrix(pCam->getProjectionMatrix()) ;
pProg->setViewPosition( pCam->getPosition() ) ;
m_meshes[i]->draw();
}
}
void SkinnedModel::load(const String& modelPath)
{
m_pScene = m_import.ReadFile(modelPath.c_str(), aiProcess_LimitBoneWeights | aiProcess_GenNormals | aiProcess_Triangulate | aiProcess_FlipWindingOrder );
if( !m_pScene || m_pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !m_pScene->mRootNode )
{
JAM_ERROR( "assimp error: %s", m_import.GetErrorString() ) ;
return;
}
m_folder = jam::getDirname( modelPath );
// we take the model (root) matrix and invert it
m_globalInverseTransform = glm::inverse( assimpToGlmMatrix(m_pScene->mRootNode->mTransformation) ) ;
if( getNumOfAnimations() == 0 ) {
JAM_ERROR( "No animations found" ) ;
}
storeAnim() ;
processNode(m_pScene->mRootNode);
}
int SkinnedModel::getNumOfAnimations() const
{
return ((m_pScene != 0) ? m_pScene->mNumAnimations : -1) ;
}
void SkinnedModel::boneTransform(float TimeInSeconds, size_t animationIdx, std::vector<Matrix4>& Transforms)
{
Matrix4 Identity(1.0f);
float TicksPerSecond = (float)(m_pScene->mAnimations[animationIdx]->mTicksPerSecond != 0 ? m_pScene->mAnimations[animationIdx]->mTicksPerSecond : 25.0f);
float TimeInTicks = TimeInSeconds * TicksPerSecond;
float AnimationTime = fmod(TimeInTicks, (float)m_pScene->mAnimations[animationIdx]->mDuration);
readNodeHeirarchy(AnimationTime, m_pScene->mRootNode, Identity, animationIdx);
Transforms.resize(m_numBones);
for( size_t i = 0 ; i < m_numBones ; i++ ) {
Transforms[i] = m_boneInfo[i].FinalTransformation;
}
}
void SkinnedModel::processNode(aiNode* node)
{
// process all the node's meshes (if any)
for( size_t i = 0; i < node->mNumMeshes; i++ )
{
aiMesh *mesh = m_pScene->mMeshes[node->mMeshes[i]];
m_meshes.push_back(processMesh(mesh));
}
// then do the same for each of its children
for( size_t i = 0; i < node->mNumChildren; i++ )
{
processNode(node->mChildren[i]);
}
}
SkinnedMesh* SkinnedModel::processMesh(aiMesh* pAiMesh)
{
size_t numOfVertices = pAiMesh->mNumVertices ;
size_t numOfIndices = 0 ;
for( size_t i=0; i<pAiMesh->mNumFaces; i++ ) {
// check that faces are triangles
JAM_ASSERT(pAiMesh->mFaces[i].mNumIndices == 3) ;
numOfIndices += pAiMesh->mFaces[i].mNumIndices ;
}
SkinnedMesh* pMesh = new SkinnedMesh() ;
pMesh->getMaterial()->setShader( GetShaderMgr().getSkinningLit() ) ;
pMesh->create(numOfVertices, numOfIndices) ;
HeapArray<Vector3>& verticesArray = pMesh->getVerticesArray() ;
HeapArray<Vector3>& normalsArray = pMesh->getNormalsArray() ;
HeapArray<Vector2>& texCoordsArray = pMesh->getTexCoordsArray() ;
HeapArray<uint16_t>& elementsArray = pMesh->getElementsArray() ;
aiVector3D* aiVertices = pAiMesh->mVertices ;
aiVector3D* aiNormals = pAiMesh->mNormals ;
size_t bytesize = numOfVertices * sizeof(Vector3) ;
memcpy( verticesArray.data(), aiVertices, bytesize ) ;
memcpy( normalsArray.data(), aiNormals, bytesize ) ;
// get only first set of texture coords (there are a total of 8 sets)
aiVector3D* aiTextureCoords = pAiMesh->mTextureCoords[0] ;
for( size_t i = 0; i <numOfVertices; i++ )
{
texCoordsArray[i].x = aiTextureCoords[i].x ;
texCoordsArray[i].y = aiTextureCoords[i].y ;
}
if( pAiMesh->HasBones() ) {
loadBones( pAiMesh, pMesh ) ;
}
// process indices
unsigned int idx = 0 ;
unsigned int* aiIndices = 0 ;
for(unsigned int i = 0; i < pAiMesh->mNumFaces; i++)
{
aiIndices = pAiMesh->mFaces[i].mIndices;
idx = i*3 ;
elementsArray[idx] = aiIndices[0] ;
elementsArray[idx+1] = aiIndices[1] ;
elementsArray[idx+2] = aiIndices[2] ;
}
// process material
if(pAiMesh->mMaterialIndex >= 0)
{
aiMaterial *pAiMaterial = m_pScene->mMaterials[pAiMesh->mMaterialIndex];
Material* pMaterial = pMesh->getMaterial() ;
float matShininess = 0.0f ;
if( AI_SUCCESS == (pAiMaterial->Get( AI_MATKEY_SHININESS, matShininess )) ) {
pMaterial->setShininess( matShininess ) ;
}
std::vector<Texture2D*> diffuseMaps ;
loadMaterialTextures(pAiMaterial, aiTextureType_DIFFUSE, diffuseMaps);
if( diffuseMaps.size() > 0 ) {
pMaterial->setDiffuseTexture( diffuseMaps[0] ) ;
}
else {
pMaterial->setDiffuseTexture( nullptr ) ;
}
std::vector<Texture2D*> specularMaps ;
loadMaterialTextures(pAiMaterial, aiTextureType_SPECULAR, specularMaps);
if( specularMaps.size() > 0 ) {
pMaterial->setSpecularTexture( specularMaps[0] ) ;
}
else {
pMaterial->setSpecularTexture( nullptr ) ;
}
}
return pMesh ;
}
void SkinnedModel::loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::vector<Texture2D*>& out )
{
unsigned int textureCountForType = mat->GetTextureCount(type) ;
if( textureCountForType > 0 ) {
for( size_t i = 0; i < textureCountForType; i++ )
{
Texture2D* texture = new Texture2D() ;
aiString str;
mat->GetTexture(type, (unsigned int)i, &str);
texture->load( appendPath(m_folder, str.C_Str()) ) ;
out.push_back(texture);
// we wont to load more that 1 texture
break;
}
}
// else {
// Texture2D* texture = new Texture2D() ;
// texture->createDefaultEmpty() ;
// out.push_back(texture);
// }
}
void SkinnedModel::loadBones( const aiMesh* pMesh, SkinnedMesh* pSkinnedMesh )
{
BonesMap::iterator it ;
unsigned int boneId = 0;
size_t vertexIdx = 0 ;
float weight = 0.0f ;
unsigned int i, k ;
size_t j ;
glm::ivec4* pBonesId = pSkinnedMesh->getBonesIdArray().data() ;
glm::vec4* pWeights = pSkinnedMesh->getWeightsArray().data() ;
for ( i = 0 ; i < pMesh->mNumBones ; i++) {
String boneName = pMesh->mBones[i]->mName.data ;
it = m_boneMapping.find(boneName) ;
if( it == m_boneMapping.end() ) {
// Allocate an index for a new bone
boneId = m_numBones;
m_numBones++;
BoneInfo bi;
bi.BoneOffset = assimpToGlmMatrix( pMesh->mBones[i]->mOffsetMatrix );
m_boneInfo.push_back(bi);
m_boneMapping[boneName] = boneId;
}
else {
boneId = it->second ;
}
aiVertexWeight* pAiWeights = pMesh->mBones[i]->mWeights ;
for( j = 0 ; j < pMesh->mBones[i]->mNumWeights ; j++ ) {
vertexIdx = pAiWeights[j].mVertexId;
weight = pAiWeights[j].mWeight;
for( k = 0 ; k < 4 ; k++ ) {
if (pWeights[vertexIdx][k] == 0.0f) {
pBonesId[vertexIdx][k] = boneId ;
pWeights[vertexIdx][k] = weight ;
break ;
}
// should never get here - more bones per vertex than we have space for
if( k == 3 ) {
JAM_ASSERT(0);
}
}
}
}
}
Matrix4 SkinnedModel::assimpToGlmMatrix( const aiMatrix4x4& m )
{
Matrix4 out (
m.a1, m.b1, m.c1, m.d1, // <- first column
m.a2, m.b2, m.c2, m.d2,
m.a3, m.b3, m.c3, m.d3,
m.a4, m.b4, m.c4, m.d4 );
return out ;
}
Matrix4 SkinnedModel::assimpToGlmMatrix( const aiMatrix3x3& m )
{
Matrix4 out (
m.a1, m.b1, m.c1, 0.0f,
m.a2, m.b2, m.c2, 0.0f,
m.a3, m.b3, m.c3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
return out ;
}
size_t SkinnedModel::findPosition(float AnimationTime, const aiNodeAnim* pNodeAnim)
{
for( size_t i = 0 ; i < pNodeAnim->mNumPositionKeys - 1 ; i++ ) {
if( AnimationTime < (float)pNodeAnim->mPositionKeys[i + 1].mTime ) {
return i;
}
}
JAM_ASSERT(0);
return 0;
}
size_t SkinnedModel::findRotation(float AnimationTime, const aiNodeAnim* pNodeAnim)
{
JAM_ASSERT(pNodeAnim->mNumRotationKeys > 0);
for( size_t i = 0 ; i < pNodeAnim->mNumRotationKeys - 1 ; i++ ) {
if( AnimationTime < (float)pNodeAnim->mRotationKeys[i + 1].mTime ) {
return i;
}
}
JAM_ASSERT(0);
return 0;
}
size_t SkinnedModel::findScaling(float AnimationTime, const aiNodeAnim* pNodeAnim)
{
JAM_ASSERT(pNodeAnim->mNumScalingKeys > 0);
for( size_t i = 0 ; i < pNodeAnim->mNumScalingKeys - 1 ; i++ ) {
if( AnimationTime < (float)pNodeAnim->mScalingKeys[i + 1].mTime ) {
return i;
}
}
JAM_ASSERT(0);
return 0;
}
void SkinnedModel::calcInterpolatedPosition(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
{
if( pNodeAnim->mNumPositionKeys == 1 ) {
Out = pNodeAnim->mPositionKeys[0].mValue;
return;
}
size_t PositionIndex = findPosition(AnimationTime, pNodeAnim);
size_t NextPositionIndex = (PositionIndex + 1);
JAM_ASSERT(NextPositionIndex < pNodeAnim->mNumPositionKeys);
float DeltaTime = (float)(pNodeAnim->mPositionKeys[NextPositionIndex].mTime - pNodeAnim->mPositionKeys[PositionIndex].mTime);
float Factor = (AnimationTime - (float)pNodeAnim->mPositionKeys[PositionIndex].mTime) / DeltaTime;
JAM_ASSERT(Factor >= 0.0f && Factor <= 1.0f);
const aiVector3D& Start = pNodeAnim->mPositionKeys[PositionIndex].mValue;
const aiVector3D& End = pNodeAnim->mPositionKeys[NextPositionIndex].mValue;
aiVector3D Delta = End - Start;
Out = Start + Factor * Delta;
}
void SkinnedModel::calcInterpolatedRotation(aiQuaternion& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
{
// we need at least two values to interpolate...
if( pNodeAnim->mNumRotationKeys == 1 ) {
Out = pNodeAnim->mRotationKeys[0].mValue;
return;
}
size_t RotationIndex = findRotation(AnimationTime, pNodeAnim);
size_t NextRotationIndex = (RotationIndex + 1);
JAM_ASSERT(NextRotationIndex < pNodeAnim->mNumRotationKeys);
float DeltaTime = (float)(pNodeAnim->mRotationKeys[NextRotationIndex].mTime - pNodeAnim->mRotationKeys[RotationIndex].mTime);
float Factor = (AnimationTime - (float)pNodeAnim->mRotationKeys[RotationIndex].mTime) / DeltaTime;
JAM_ASSERT(Factor >= 0.0f && Factor <= 1.0f);
const aiQuaternion& StartRotationQ = pNodeAnim->mRotationKeys[RotationIndex].mValue;
const aiQuaternion& EndRotationQ = pNodeAnim->mRotationKeys[NextRotationIndex].mValue;
aiQuaternion::Interpolate(Out, StartRotationQ, EndRotationQ, Factor);
Out = Out.Normalize();
}
void SkinnedModel::calcInterpolatedScaling(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
{
if( pNodeAnim->mNumScalingKeys == 1 ) {
Out = pNodeAnim->mScalingKeys[0].mValue;
return;
}
size_t ScalingIndex = findScaling(AnimationTime, pNodeAnim);
size_t NextScalingIndex = (ScalingIndex + 1);
JAM_ASSERT(NextScalingIndex < pNodeAnim->mNumScalingKeys);
float DeltaTime = (float)(pNodeAnim->mScalingKeys[NextScalingIndex].mTime - pNodeAnim->mScalingKeys[ScalingIndex].mTime);
float Factor = (AnimationTime - (float)pNodeAnim->mScalingKeys[ScalingIndex].mTime) / DeltaTime;
JAM_ASSERT(Factor >= 0.0f && Factor <= 1.0f);
const aiVector3D& Start = pNodeAnim->mScalingKeys[ScalingIndex].mValue;
const aiVector3D& End = pNodeAnim->mScalingKeys[NextScalingIndex].mValue;
aiVector3D Delta = End - Start;
Out = Start + Factor * Delta;
}
void SkinnedModel::readNodeHeirarchy(float AnimationTime, const aiNode* pNode, const Matrix4& ParentTransform, size_t animationIdx)
{
Matrix4 NodeTransformation = assimpToGlmMatrix( pNode->mTransformation );
const aiAnimation* pAnimation = m_pScene->mAnimations[animationIdx];
const char* NodeName = pNode->mName.data ;
const aiNodeAnim* pNodeAnim = findNodeAnim(animationIdx, NodeName);
if( pNodeAnim ) {
// Interpolate scaling and generate scaling transformation matrix
aiVector3D Scaling;
calcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim);
Matrix4 ScalingM(1.0f);
ScalingM = glm::scale(ScalingM,Vector3(Scaling.x, Scaling.y, Scaling.z)) ;
// Interpolate rotation and generate rotation transformation matrix
aiQuaternion RotationQ;
calcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim);
Matrix4 RotationM(1.0f);
RotationM = assimpToGlmMatrix( RotationQ.GetMatrix() );
// Interpolate translation and generate translation transformation matrix
aiVector3D Translation;
calcInterpolatedPosition(Translation, AnimationTime, pNodeAnim);
Matrix4 TranslationM(1.0f);
TranslationM = glm::translate(TranslationM,Vector3(Translation.x, Translation.y, Translation.z)) ;
// Combine the above transformations
NodeTransformation = TranslationM * RotationM * ScalingM ;
}
Matrix4 GlobalTransformation = ParentTransform * NodeTransformation;
if( m_boneMapping.find(NodeName) != m_boneMapping.end() ) {
size_t BoneIndex = m_boneMapping[NodeName];
m_boneInfo[BoneIndex].FinalTransformation = m_globalInverseTransform * GlobalTransformation * m_boneInfo[BoneIndex].BoneOffset;
}
for( size_t i = 0 ; i < pNode->mNumChildren ; i++ ) {
readNodeHeirarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation, animationIdx);
}
}
const aiNodeAnim* SkinnedModel::findNodeAnim(size_t animIdx, const String& NodeName)
{
const aiNodeAnim* out = 0 ;
auto it = m_animMapping[animIdx].find(NodeName) ;
if( it != m_animMapping[animIdx].end() ) {
out = it->second ;
}
return out;
}
void SkinnedModel::storeAnim()
{
size_t numOfAnimations = m_pScene->mNumAnimations ;
m_animMapping.create(numOfAnimations) ;
for( size_t i=0; i<numOfAnimations; i++ ) {
storeNodeAnim( m_pScene->mAnimations[i], m_animMapping[i] ) ;
}
}
void SkinnedModel::storeNodeAnim( const aiAnimation* pAnimation, AnimationsMap& animMap )
{
for( size_t i = 0 ; i < pAnimation->mNumChannels ; i++ ) {
const aiNodeAnim* pNodeAnim = pAnimation->mChannels[i];
if( pNodeAnim->mNodeName.data ) {
animMap[String(pNodeAnim->mNodeName.data)] = pNodeAnim ;
}
}
}
}
| 31.283582 | 156 | 0.681238 | [
"mesh",
"vector",
"model",
"transform"
] |
ce9a1ec047598aca4405068bc8111893b9d36840 | 3,526 | cpp | C++ | examples/04-model/main.cpp | NongusStudios/shard | f5727ad45fd47b03ab93947f401c5c916b65be8a | [
"Apache-2.0"
] | 1 | 2022-03-11T08:54:55.000Z | 2022-03-11T08:54:55.000Z | examples/04-model/main.cpp | NongusStudios/shard | f5727ad45fd47b03ab93947f401c5c916b65be8a | [
"Apache-2.0"
] | null | null | null | examples/04-model/main.cpp | NongusStudios/shard | f5727ad45fd47b03ab93947f401c5c916b65be8a | [
"Apache-2.0"
] | null | null | null | #include <shard/gfx/gfx.hpp>
#include <shard/gfx/model.hpp>
#include <shard/time/time.hpp>
struct UBO{
glm::mat4 proj;
glm::mat4 model;
};
int main(){
shard::Time time = {};
shard::gfx::ModelLoader loader("examples/04-model/model.obj");
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(800, 600, "04-model", NULL, NULL);
// vsync
shard::gfx::Graphics gfx(window, true);
shard::gfx::Model model(gfx, loader.vertices, loader.indices);
auto descriptorPool = gfx.createDescriptorPoolBuilder().addPoolSize(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, shard::gfx::Swapchain::MAX_FRAMES_IN_FLIGHT
).setMaxSets(shard::gfx::Swapchain::MAX_FRAMES_IN_FLIGHT).build();
auto descriptorLayout = gfx.createDescriptorSetLayoutBuilder().addBinding(
0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT
).build();
std::vector<shard::gfx::Buffer> uBuffers;
std::vector<VkDescriptorSet> descSets(shard::gfx::Swapchain::MAX_FRAMES_IN_FLIGHT);
size_t i = 0;
for(auto& descSet : descSets){
uBuffers.push_back(gfx.createUniformBuffer(
sizeof(UBO), VK_SHARING_MODE_EXCLUSIVE, nullptr
));
uBuffers[i].map();
auto descInfo = uBuffers[i].descriptorInfo();
shard::gfx::DescriptorWriter(descriptorLayout, descriptorPool)
.writeBuffer(0, &descInfo)
.build(descSet);
i++;
}
shard::gfx::PipelineConfigInfo config = {};
config.makeDefault();
config.rasterizationInfo.cullMode = VK_CULL_MODE_BACK_BIT;
auto pipelineLayout = gfx.createPipelineLayout({}, {&descriptorLayout});
auto pipeline = gfx.createPipeline(
pipelineLayout,
"examples/04-model/model.vert.spv", "examples/04-model/model.frag.spv",
{shard::gfx::Vertex3D::bindingDesc(VK_VERTEX_INPUT_RATE_VERTEX)}, shard::gfx::Vertex3D::attributeDescs(),
config
);
while(!glfwWindowShouldClose(window)){
glfwPollEvents();
shard::time::updateTime(time);
if(auto commandBuffer = gfx.beginRenderPass(nullptr, {44.0f})){
VkExtent2D windowExtent = shard::getWindowExtent(window);
UBO ubo = {};
ubo.proj = glm::perspective(
glm::radians(45.0f),
float(windowExtent.width)/float(windowExtent.height),
0.1f, 100.0f
);
ubo.model = glm::mat4(1.0f);
float rot = time.elapsed;
glm::vec3 pos = {0.0f, 0.0f, -5.0f};
glm::vec3 scale = {1.0f, 1.0f, 1.0f};
ubo.model = glm::translate(ubo.model, pos);
ubo.model = glm::rotate( ubo.model, rot, {0.0f, 1.0f, 0.0f});
ubo.model = glm::scale( ubo.model, scale);
memcpy(
uBuffers[gfx.frameIndex()].mappedMemory(), &ubo, sizeof(UBO)
);
vkCmdBindDescriptorSets(
commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
pipelineLayout, 0, 1, &descSets[gfx.frameIndex()],
0, VK_NULL_HANDLE
);
pipeline.bind(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS);
model.bind(commandBuffer);
model.draw(commandBuffer);
gfx.endRenderPass();
}
}
gfx.device().waitIdle();
gfx.destroyPipelineLayout(pipelineLayout);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
} | 35.979592 | 113 | 0.614577 | [
"vector",
"model"
] |
ce9e014b6f0deaad38b78d150afafe77ad428c47 | 84 | cpp | C++ | src/TTPInstance.cpp | jakobbossek/TTP | 40c07210a206c80fa710e9ec8fc5ffe767b04d7d | [
"BSD-2-Clause"
] | 1 | 2021-04-01T08:42:05.000Z | 2021-04-01T08:42:05.000Z | src/TTPInstance.cpp | jakobbossek/ttp | 40c07210a206c80fa710e9ec8fc5ffe767b04d7d | [
"BSD-2-Clause"
] | 6 | 2020-04-01T06:48:02.000Z | 2020-04-01T07:00:02.000Z | src/TTPInstance.cpp | jakobbossek/TTP | 40c07210a206c80fa710e9ec8fc5ffe767b04d7d | [
"BSD-2-Clause"
] | null | null | null | #include "TTPInstance.h"
#include <iostream>
#include <vector>
#include <algorithm>
| 16.8 | 24 | 0.75 | [
"vector"
] |
cea0836a7734f4baff0e48d0cda5cb416c61fce1 | 615 | cpp | C++ | tests/OpenGLTriangle.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | tests/OpenGLTriangle.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | tests/OpenGLTriangle.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | // DENG: dynamic engine - small but powerful 3D game engine
// licence: Apache, see LICENCE file
// file: OpenGLTriangle.cpp - Testing application that display's UV mapped triangle using OpenGL backend
// author: Karl-Mihkel Ott
#define USE_OPENGL
#include "TriangleApp.h"
int main() {
DENG::Window win = DENG::Window(WIDTH, HEIGHT, NEKO_HINT_API_OPENGL | NEKO_HINT_RESIZEABLE, "OpenGLTriangle");
win.glMakeCurrent();
DENG::RendererConfig conf = {};
DENG::OpenGLRenderer renderer = DENG::OpenGLRenderer(win, conf);
TriangleApp app = TriangleApp(win, renderer);
app.Run();
return 0;
}
| 34.166667 | 114 | 0.721951 | [
"3d"
] |
cea32dd3266c96ff1fdddeb4e8b68667c9f202ce | 6,601 | hpp | C++ | PSME/common/agent-framework/include/agent-framework/module/model/logical_drive.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/common/agent-framework/include/agent-framework/module/model/logical_drive.hpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | null | null | null | PSME/common/agent-framework/include/agent-framework/module/model/logical_drive.hpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | 1 | 2021-03-24T19:37:58.000Z | 2021-03-24T19:37:58.000Z | /*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @file logical_drive.hpp
* @brief LogicalDrive model interface
* */
#pragma once
#include "agent-framework/module/model/attributes/model_attributes.hpp"
#include "agent-framework/module/model/block_device.hpp"
#include "agent-framework/module/enum/storage.hpp"
#include "agent-framework/module/enum/common.hpp"
namespace agent_framework {
namespace model {
/*! LogicalDrive */
class LogicalDrive : public BlockDevice {
public:
explicit LogicalDrive(const std::string& parent_uuid = {},
enums::Component parent_type = enums::Component::StorageServices);
~LogicalDrive();
LogicalDrive(const LogicalDrive&) = default;
LogicalDrive& operator=(const LogicalDrive&) = default;
LogicalDrive(LogicalDrive&&) = default;
LogicalDrive& operator=(LogicalDrive&&) = default;
/*!
* @brief construct an object of class LogicalDrive from JSON
*
* @param json the Json::Value deserialized to object
*
* @return the newly constructed LogicalDrive object
*/
static LogicalDrive from_json(const Json::Value& json);
/*!
* @brief transform the object to JSon
*
* @return the object serialized to Json::Value
*/
Json::Value to_json() const;
/*!
* @brief Get collection name
*
* @return collection name
*/
static enums::CollectionName get_collection_name() {
return LogicalDrive::collection_name;
}
/*!
* @brief Get component name
*
* @return component name
*/
static enums::Component get_component() {
return LogicalDrive::component;
}
/*!
* Get the type of logical drive
*
* @return LogicalDrive type
* */
const OptionalField<enums::LogicalDriveType> get_type() const {
return m_type;
}
/*!
* @brief Set logical_drive type
*
* @param[in] logical_drive_type LogicalDrive type
* */
void set_type(const OptionalField<enums::LogicalDriveType> logical_drive_type) {
m_type = logical_drive_type;
}
/*!
* Get Logical Drive size in GB
*
* @return Logical Drive size in GB
* */
const OptionalField<double>& get_capacity_gb() const {
return m_capacityGB;
}
/*!
* @brief Set LogicalDrive size in GB
*
* @param[in] logical_drive_capacity_gb LogicalVolume's size in GB
* */
void set_capacity_gb(const OptionalField<double>& logical_drive_capacity_gb) {
m_capacityGB = logical_drive_capacity_gb;
}
/*!
* Get the logical drive mode
*
* @return LogicalDrive mode
* */
const OptionalField<enums::LogicalDriveMode> get_mode() const {
return m_mode;
}
/*!
* @brief Set logical_drive mode
*
* @param[in] logical_drive_mode LogicalDrive mode
* */
void set_mode(const OptionalField<enums::LogicalDriveMode> logical_drive_mode) {
m_mode = logical_drive_mode;
}
/*!
* Get the logical drive master drive uuid
*
* @return LogicalDrive master drive uuid
* */
const OptionalField<std::string>& get_master() const {
return m_master;
}
/*!
* @brief Set logical_drive master drive uuid
*
* @param[in] logical_drive_master LogicalDrive master drive uuid
* */
void set_master(const OptionalField<std::string>& logical_drive_master) {
m_master = logical_drive_master;
}
/*!
* Get information about image populated on the logical drive
*
* @return LogicalDrive image info
* */
const OptionalField<std::string>& get_image() const {
return m_image;
}
/*!
* @brief Set logical_drive image info
*
* @param[in] logical_drive_image LogicalDrive image info
* */
void set_image(const OptionalField<std::string>& logical_drive_image) {
m_image = logical_drive_image;
}
/*!
* Get information if the logical drive is bootable
*
* @return LogicalDrive bootable option
* */
const OptionalField<bool>& get_bootable() const {
return m_bootable;
}
/*!
* @brief Set if the logical_drive is bootable
*
* @param[in] logical_drive_is_bootable LogicalDrive bootable option
* */
void set_bootable(const OptionalField<bool>& logical_drive_is_bootable) {
m_bootable = logical_drive_is_bootable;
}
/*!
* Get information if the logical drive is write/delete protected
*
* @return LogicalDrive protected flag
* */
const OptionalField<bool>& get_protected() const {
return m_protected;
}
/*!
* @brief Set the logical_drive write/delete protection flag
*
* @param[in] logical_drive_is_protected LogicalDrive protected flag
* */
void set_protected(const OptionalField<bool>& logical_drive_is_protected) {
m_protected = logical_drive_is_protected;
}
/*!
* Get information if the logical drive is snapshot
*
* @return LogicalDrive snapshot option
* */
const OptionalField<bool>& is_snapshot() const {
return m_is_snapshot;
}
/*!
* @brief Set if the logical_drive is snapshot
*
* @param[in] snapshot LogicalDrive snapshot option
* */
void set_is_snapshot(const OptionalField<bool>& snapshot) {
m_is_snapshot = snapshot;
}
private:
OptionalField<enums::LogicalDriveType> m_type{enums::LogicalDriveType::LVM};
OptionalField<double> m_capacityGB{};
OptionalField<enums::LogicalDriveMode> m_mode{};
OptionalField<std::string> m_master{};
OptionalField<bool> m_is_snapshot{};
OptionalField<std::string> m_image{};
OptionalField<bool> m_bootable{};
OptionalField<bool> m_protected{};
static const enums::CollectionName collection_name;
static const enums::Component component;
};
}
}
| 23.744604 | 92 | 0.652931 | [
"object",
"model",
"transform"
] |
ceab9bbf2ee79527466cc99a2a4aef8f5d526b6d | 5,337 | cpp | C++ | SOURCES/graphics/objects/drawtrcr_dx.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/graphics/objects/drawtrcr_dx.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/graphics/objects/drawtrcr_dx.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include "TimeMgr.h"
#include "TOD.h"
#include "RenderOW.h"
#include "RViewPnt.h"
#include "Tex.h"
#include "falclib\include\fakerand.h"
#include "Drawtrcr.h"
#include "Draw2d.h"
#include "Graphics\DXEngine\DXTools.h"
#include "Graphics\DXEngine\DXDefines.h"
#include "Graphics\DXEngine\DXEngine.h"
#include "Graphics\DXEngine\DXVBManager.h"
#ifdef USE_SH_POOLS
MEM_POOL DrawableTracer::pool;
#endif
// bleh
extern int sGreenMode, gameCompressionRatio;
/***************************************************************************\
Initialize a tracer
\***************************************************************************/
DXDrawableTracer::DXDrawableTracer( void ) : DrawableTracer()
{
}
/***************************************************************************\
Initialize a tracer
\***************************************************************************/
DXDrawableTracer::DXDrawableTracer( float w ) : DrawableTracer(w)
{
}
/***************************************************************************\
Initialize a tracer
\***************************************************************************/
DXDrawableTracer::DXDrawableTracer( Tpoint *p, float w ) : DrawableTracer( p, w )
{
}
/***************************************************************************\
Remove an instance of a tracer
\***************************************************************************/
DXDrawableTracer::~DXDrawableTracer( void )
{
}
/***************************************************************************\
Remove an instance of a tracer
\***************************************************************************/
void DXDrawableTracer::Update( Tpoint *head, Tpoint *tail )
{
position = *head;
tailEnd = *tail;
}
/***************************************************************************\
Draw this segmented trail on the given renderer.
\***************************************************************************/
//void DrawableTracer::Draw( class RenderOTW *renderer, int LOD )
void DXDrawableTracer::Draw( class RenderOTW *renderer, int)
{
D3DVECTOR v0, v1, v2, v3, v4, v5;
int lineColor, LineEndColor;
float DetailLevel;
D3DVECTOR Vector;
//COUNT_PROFILE("Tracers Nr");
//START_PROFILE("Tracers Time");
// COBRA - RED - Tracers are updated on by the Gun Exec... this makes flying tracers to freeze
// if no more 'driven' by the gun EXEC... they appear stopped at midair
if(LastPos.x==position.x && LastPos.z==position.z && LastPos.y==position.y && gameCompressionRatio) { if(parentList) parentList->RemoveMe(); return; }
// Get the last position for next comparison
LastPos=position;
// Get the Detail level of the drawable
DetailLevel=TheDXEngine.GetDetailLevel((D3DVECTOR*)&position, TRACER_VISIBLE_DISTANCE)/radius;
// Too much far to draw it...
if (DetailLevel > 1.0f) {
//STOP_PROFILE("Tracers Time");
return;
}
// Alpha Check
if ( alpha > 1.0f ) alpha = 1.0f;
// now Alpha is proportional to distance
float LineAlpha=/*alpha * */(1 - DetailLevel * 0.2f);
// Set the Colour
lineColor = ((unsigned int)(LineAlpha*255.0f) << 24) + // alpha
((unsigned int)(r*255.0f) << 16) + // blue
((unsigned int)(g*255.0f) << 8) + // green
((unsigned int)(b*255.0f)); // red
LineEndColor = ((unsigned int)(LineAlpha*32.0f) << 24) + // alpha
((unsigned int)(r*255.0f) << 16) + // blue
((unsigned int)(g*255.0f) << 8) + // green
((unsigned int)(b*255.0f)); // red
if(DetailLevel>0.15f){
TheDXEngine.Draw3DPoint((D3DVECTOR*)&position, lineColor, EMISSIVE);
//STOP_PROFILE("Tracers Time");
return;
}
if(DetailLevel>0.03f){
TheDXEngine.Draw3DLine((D3DVECTOR*)&position, (D3DVECTOR*)&tailEnd, lineColor, LineEndColor, EMISSIVE);
//STOP_PROFILE("Tracers Time");
return;
}
// Get the direction vector
Vector.x=tailEnd.x-position.x;
Vector.y=tailEnd.y-position.y;
Vector.z=tailEnd.z-position.z;
// Normalize the Direction vector
float k=sqrtf(Vector.x*Vector.x+Vector.y*Vector.y+Vector.z*Vector.z);
Vector.x/=k;
Vector.y/=k;
Vector.z/=k;
v0=*(D3DVECTOR*)&position;
v5=*(D3DVECTOR*)&tailEnd;
D3DVECTOR mid(Vector);
mid.x*=0.2f*k; mid.y*=0.2f*k; mid.z*=0.2f*k;
v1.z=mid.z+radius/2*Vector.y;
v1.x=mid.x+radius/2*Vector.z;
v1.y=mid.y+radius/2*Vector.x;
v2.z=mid.z-radius/2*Vector.y;
v2.x=mid.x-radius/2*Vector.z;
v2.y=mid.y-radius/2*Vector.x;
v3.z=mid.z+radius/2*Vector.x;
v3.y=mid.y+radius/2*Vector.z;
v3.x=mid.x+radius/2*Vector.y;
v4.z=mid.z-radius/2*Vector.x;
v4.y=mid.y-radius/2*Vector.z;
v4.x=mid.x-radius/2*Vector.y;
v1.x+=position.x; v1.y+=position.y; v1.z+=position.z;
v2.x+=position.x; v2.y+=position.y; v2.z+=position.z;
v3.x+=position.x; v3.y+=position.y; v3.z+=position.z;
v4.x+=position.x; v4.y+=position.y; v4.z+=position.z;
TheDXEngine.Draw3DLine((D3DVECTOR*)&v0, (D3DVECTOR*)&v5, lineColor, LineEndColor, EMISSIVE);
TheDXEngine.Draw3DLine((D3DVECTOR*)&v0, (D3DVECTOR*)&v1, lineColor, LineEndColor, EMISSIVE);
TheDXEngine.Draw3DLine((D3DVECTOR*)&v0, (D3DVECTOR*)&v2, lineColor, LineEndColor, EMISSIVE);
TheDXEngine.Draw3DLine((D3DVECTOR*)&v0, (D3DVECTOR*)&v3, lineColor, LineEndColor, EMISSIVE);
TheDXEngine.Draw3DLine((D3DVECTOR*)&v0, (D3DVECTOR*)&v4, lineColor, LineEndColor, EMISSIVE);
//STOP_PROFILE("Tracers Time");
}
| 31.394118 | 151 | 0.570358 | [
"vector"
] |
ceacce6992897fc9531eec604ac1f160f60e3328 | 5,296 | cpp | C++ | C++/BitwiseAutomation/src/AutomationExtender.cpp | jimwaschura/Automation | f655feeea74ff22ebe44d8b68374ba6983748f60 | [
"BSL-1.0"
] | null | null | null | C++/BitwiseAutomation/src/AutomationExtender.cpp | jimwaschura/Automation | f655feeea74ff22ebe44d8b68374ba6983748f60 | [
"BSL-1.0"
] | null | null | null | C++/BitwiseAutomation/src/AutomationExtender.cpp | jimwaschura/Automation | f655feeea74ff22ebe44d8b68374ba6983748f60 | [
"BSL-1.0"
] | 1 | 2020-08-16T00:11:55.000Z | 2020-08-16T00:11:55.000Z | /* AutomationExtender.cpp */
//================================================================================
// BOOST SOFTWARE LICENSE
//
// Copyright 2020 BitWise Laboratories Inc.
// Author.......Jim Waschura
// Contact......info@bitwiselabs.com
//
//Permission is hereby granted, free of charge, to any person or organization
//obtaining a copy of the software and accompanying documentation covered by
//this license (the "Software") to use, reproduce, display, distribute,
//execute, and transmit the Software, and to prepare derivative works of the
//Software, and to permit third-parties to whom the Software is furnished to
//do so, all subject to the following:
//
//The copyright notices in the Software and this entire statement, including
//the above license grant, this restriction and the following disclaimer,
//must be included in all copies of the Software, in whole or in part, and
//all derivative works of the Software, unless such copies or derivative
//works are solely in the form of machine-executable object code generated by
//a source language processor.
//
//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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
//SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
//FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
//ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//DEALINGS IN THE SOFTWARE.
//================================================================================
#include <stdarg.h> /* va_list, va_start, va_end */
#include <stdio.h> /* vsnprintf,snprintf,fprintf */
#include <string.h> /* strcmp, strtok */
#include <unistd.h> /* usleep */
#include "AutomationExtender.h"
//================================================================================
//================================================================================
void AutomationExtender::setDebugging(bool newValue)
{
m_Debugging=newValue;
}
bool AutomationExtender::getDebugging()
{
return m_Debugging || getExtender()->getDebugging();
}
void AutomationExtender::SendCommand( const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
getExtender()->SendCommand("%s",Buf);
}
char * AutomationExtender::QueryResponse( char *buffer, int buflen, const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse(buffer,buflen,"%s",Buf);
}
void AutomationExtender::SendBinaryCommand( const char *buffer, int count, const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
getExtender()->SendBinaryCommand(buffer,count,"%s",Buf);
}
char *AutomationExtender::QueryBinaryResponse( int *pcount, const char *command, ... ) /* caller responsible for free(return_value) */
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryBinaryResponse(pcount,"%s",Buf);
}
int AutomationExtender::QueryResponse_int( const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse_int("%s",Buf);
}
long long AutomationExtender::QueryResponse_int64( const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse_int64("%s",Buf);
}
bool AutomationExtender::QueryResponse_bool( const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse_bool("%s",Buf);
return false;
}
double AutomationExtender::QueryResponse_double( const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse_double("%s",Buf);
}
int AutomationExtender::QueryResponse_enum( const char *enum_strings_null_terminated[], const char *command, ... )
{
char Buf[4096];
strncpy(Buf,getPrefix(),4096-1);
va_list argptr;
va_start(argptr,command);
vsnprintf(Buf+getPrefixLength(),4096-getPrefixLength(),command,argptr);
va_end(argptr);
return getExtender()->QueryResponse_enum(enum_strings_null_terminated, "%s",Buf);
}
| 29.422222 | 134 | 0.702039 | [
"object"
] |
ceb1e41301c46cae2292fcb3ef4e04a532dc9f0a | 8,400 | cpp | C++ | min_heap/min_heap.cpp | sammaniamsam/algorithm-drawer | b74848cf3734dbcb1c92656c6f8837538246446f | [
"MIT"
] | null | null | null | min_heap/min_heap.cpp | sammaniamsam/algorithm-drawer | b74848cf3734dbcb1c92656c6f8837538246446f | [
"MIT"
] | null | null | null | min_heap/min_heap.cpp | sammaniamsam/algorithm-drawer | b74848cf3734dbcb1c92656c6f8837538246446f | [
"MIT"
] | null | null | null | //====================================================================
// min_heap.cpp
// Author: sammaniamsam
//====================================================================
#include "min_heap.h"
//---------------------------------
//---------------------------------
//---------------------------------
//--------PRIVATE METHODS----------
//---------------------------------
//---------------------------------
//---------------------------------
//FUNCTION: topDown()
//PURPOSE: Recursive top-down re-heap
//function that compares a child to
//its' parent. Each child must be
//greater than its' parent.
//---------------------------------
void min_heap::topDown(unsigned long position) {
//root
if (position == 1) return;
//not root
else {
//child < parent
if(this->minHeapVector->at(position-1)->key < this->minHeapVector->at((position/2)-1)->key) {
//swap child, parent keys
int tempKey = this->minHeapVector->at(position-1)->key;
this->minHeapVector->at(position-1)->key = this->minHeapVector->at((position/2)-1)->key;
this->minHeapVector->at((position/2)-1)->key = tempKey;
//compare parent w/ new key
this->topDown(position/2);
}
//child > parent
else return;
}
}
//---------------------------------
//FUNCTION: defineNodePtrs()
//PURPOSE: Recursive function that
//iterates backwards over the
//heap and defines every parents'
//ptrs. Since this heap is a complete
//binary tree, nodes at an
//even position are left children, and
//nodes at an odd position are right
//children.
//---------------------------------
void min_heap::defineNodePtrs(unsigned long position) {
//root
if (position == 1) return;
//not root
else {
//left child
if(position % 2 == 0) {
this->minHeapVector->at((position/2)-1)->left = this->minHeapVector->at(position-1);
}
//right child
else {
this->minHeapVector->at((position/2)-1)->right = this->minHeapVector->at(position-1);
}
//define parent
this->minHeapVector->at(position-1)->parent = this->minHeapVector->at((position/2)-1);
//connect next child to parent
this->defineNodePtrs(position-1);
}
}
//---------------------------------
//FUNCTION: setPtrsNull()
//PURPOSE: Sets left and right ptrs
//for each node to NULL.
//---------------------------------
void min_heap::setPtrsNull() {
//define variables
unsigned long i = 0;
std::vector<node *>::iterator it;
//iterate though heap
for (it = this->minHeapVector->begin(); it != this->minHeapVector->end(); ++it, i++) {
//set node ptrs to NULL
this->minHeapVector->at(i)->parent =
this->minHeapVector->at(i)->left =
this->minHeapVector->at(i)->right = NULL;
}
}
//---------------------------------
//FUNCTION: preorderTraversal()
//PURPOSE: Performs a pre-order
//traversal of the heap and stores
//route taken in path queue.
//---------------------------------
void min_heap::preorderTraversal(node *root, std::queue<node *> *path)
{
if(root != NULL)
{
path->push(root);
this->preorderTraversal(root->left, path);
this->preorderTraversal(root->right, path);
}
}
//---------------------------------
//FUNCTION: inorderTraversal()
//PURPOSE: Performs a in-order
//traversal of the heap and stores
//route taken in path queue.
//---------------------------------
void min_heap::inorderTraversal(node *root, std::queue<node *> *path)
{
if(root != NULL)
{
this->inorderTraversal(root->left, path);
path->push(root);
this->inorderTraversal(root->right, path);
}
}
//---------------------------------
//FUNCTION: postorderTraversal()
//PURPOSE: Performs a post-order
//traversal of the heap and stores
//route taken in path queue.
//---------------------------------
void min_heap::postorderTraversal(node *root, std::queue<node *> *path)
{
if(root != NULL)
{
this->postorderTraversal(root->left, path);
this->postorderTraversal(root->right, path);
path->push(root);
}
}
//---------------------------------
//---------------------------------
//--------PUBLIC METHODS-----------
//---------------------------------
//---------------------------------
//---------------------------------
//FUNCTION: min_heap()
//PURPOSE: Initialize private member
//variable
//---------------------------------
min_heap::min_heap() {
this->minHeapVector = new std::vector<node *>;
}
//---------------------------------
//FUNCTION: ~min_heap()
//PURPOSE: Deletes all dynamically
//created instances of node and
//vector
//---------------------------------
min_heap::~min_heap() {
//define variables
node* nPtr;
//set node ptrs to null
this->setPtrsNull();
//deallocate memory to dynamic instances
while(!this->minHeapVector->empty()) {
nPtr = this->minHeapVector->back();
delete nPtr;
this->minHeapVector->pop_back();
}
delete this->minHeapVector; this->minHeapVector = NULL;
}
//---------------------------------
//FUNCTION: insert()
//PURPOSE: Adds key to node and
//inserts node into heap then re-heaps.
//---------------------------------
void min_heap::insert(int& key) {
//define variables
node* newNode;
newNode = new node(key);
//initialize node ptrs to null
this->setPtrsNull();
//add newNode to heap vector
this->minHeapVector->push_back(newNode);
//heapify using top down
this->topDown(this->minHeapVector->size());
//define heap nodes' ptrs
this->defineNodePtrs(this->minHeapVector->size());
}
//---------------------------------
//FUNCTION: removeNode()
//PURPOSE: Deletes the heap's root
//node and then re-heaps.
//Returns false if heap is empty.
//---------------------------------
bool min_heap::removeNode() {
//define variables
node *leaf, *delNode;
//initialize node ptrs to null
this->setPtrsNull();
if(!this->minHeapVector->empty()) {
//get last leaf
leaf = this->minHeapVector->back();
//set leaf ptrs to NULL
leaf->left = leaf->right = NULL;
//swap last leaf and root
delNode = this->minHeapVector->back() = this->minHeapVector->front();
this->minHeapVector->front() = leaf;
//delete last leaf
delNode->left = delNode->right = NULL; delete delNode;
this->minHeapVector->pop_back();
//heapify using top down
this->topDown((this->minHeapVector->size()+1)/2);
//define heap nodes' ptrs
this->defineNodePtrs(this->minHeapVector->size());
return true;
}
//heap is empty
else return false;
}
//---------------------------------
//FUNCTION: search()
//PURPOSE: Searches for key in heap
//and stores traversal route in
//queue. Traversal time O(n).
//Returns false if key is not found.
//---------------------------------
bool min_heap::search(int& key, std::queue<node *> *path) {
//define variables
unsigned long i = 0;
std::vector<node *>::iterator it;
//search for key
for(it = this->minHeapVector->begin(); it != this->minHeapVector->end(); ++it, i++) {
//record search path
path->push(this->minHeapVector->at(i));
//key found
if(this->minHeapVector->at(i)->key == key) return true;
}
//key not found
return false;
}
//---------------------------------
//FUNCTION: preorderTraversal()
//PURPOSE: Passes queue to recursive
//private fctn preorderTraversal()
//---------------------------------
void min_heap::preorderTraversal(std::queue<node *> *path) {
this->preorderTraversal(this->minHeapVector->front(), path);
}
//---------------------------------
//FUNCTION: inorderTraversal()
//PURPOSE: Passes queue to recursive
//private fctn inorderTraversal()
//---------------------------------
void min_heap::inorderTraversal(std::queue<node *> *path) {
this->inorderTraversal(this->minHeapVector->front(), path);
}
//---------------------------------
//FUNCTION: postorderTraversal()
//PURPOSE: Passes queue to recursive
//private fctn postorderTraversal()
//---------------------------------
void min_heap::postorderTraversal(std::queue<node *> *path) {
this->postorderTraversal(this->minHeapVector->front(), path);
}
| 28.965517 | 101 | 0.524286 | [
"vector"
] |
ceb562fe9531407f067ab8b4d111eaac411fd28c | 17,210 | cpp | C++ | src/format/vobj.cpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | 12 | 2020-06-25T13:40:22.000Z | 2021-12-06T04:00:29.000Z | src/format/vobj.cpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | 2 | 2021-02-04T16:19:40.000Z | 2021-06-25T09:39:20.000Z | src/format/vobj.cpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | null | null | null | #include "voxelio/format/vobj.hpp"
#include "voxelio/color.hpp"
#include "voxelio/macro.hpp"
#include "voxelio/stringify.hpp"
#include <cstdint>
#include <cstring>
#include <memory>
#include <unordered_set>
namespace voxelio::vobj {
VobjWriteHelper::OffsetGuard::OffsetGuard(VobjWriteHelper *parent, Vec3i64 offset)
: parent{parent}, offset{std::move(offset)}
{
parent->offset += this->offset;
}
VobjWriteHelper::OffsetGuard::~OffsetGuard()
{
parent->offset -= this->offset;
}
usize VobjWriteHelper::voxelsWritten()
{
return index;
}
void VobjWriteHelper::setBaseOffset(Vec3i64 offset)
{
this->offset = std::move(offset);
}
[[nodiscard]] VobjWriteHelper::OffsetGuard VobjWriteHelper::addGuardedOffset(Vec3i64 offset)
{
return OffsetGuard{this, std::move(offset)};
}
void VobjWriteHelper::setColorFormat(ColorFormat format)
{
this->colorFormat = format;
}
void VobjWriteHelper::resetBuffer(Voxel64 buffer[], usize bufferSize)
{
VXIO_DEBUG_ASSERT_CONSEQUENCE(bufferSize != 0, buffer != nullptr);
this->buffer = buffer;
this->bufferSize = bufferSize;
this->index = 0;
}
bool VobjWriteHelper::canWrite()
{
return index != bufferSize;
}
bool VobjWriteHelper::isFull()
{
return index == bufferSize;
}
void VobjWriteHelper::write(Vec3i64 pos, argb32 color)
{
VXIO_DEBUG_ASSERT_LT(index, bufferSize);
buffer[index++] = Voxel64{pos + offset, {color}};
}
ArrayU8 makeArrayU8(usize size)
{
return std::make_unique<u8[]>(size);
}
ArrayU8 copyArrayU8(const ArrayU8 &array, usize bytes)
{
ArrayU8 result = makeArrayU8(bytes);
std::memcpy(result.get(), array.get(), bytes);
return result;
}
// see http://www.cs.nott.ac.uk/~psarb2/G51MPC/slides/NumberLogic.pdf
u32 divCeil(u32 numerator, u32 denominator)
{
// u64 to ensure overflow safety
u64 newNumerator = u64(numerator) + u64(denominator) - 1;
return static_cast<u32>(newNumerator / denominator);
}
template <typename UInt>
constexpr u64 zeroToMaxPlusOne(UInt num)
{
return (num == 0) ? static_cast<u64>(std::numeric_limits<decltype(num)>::max()) + 1 : num;
}
static const std::unordered_set<std::string> recognizedExtensions{
EXT_DEBUG, EXT_EXISTENCE_ARRAY, EXT_GROUPS, EXT_16_BIT_ARRAY, EXT_32_BIT_ARRAY};
static const std::unordered_set<u8> recognizedColorFormats{RGB24, ARGB32, V8, AV16};
static const std::unordered_set<u8> recognizedDataFormats{EMPTY, LIST, ARRAY_POSITIONED, ARRAY_TILED};
static const std::unordered_set<u8> recognizedPaletteBits{0, 8, 16, 32};
// IReader overrides
[[nodiscard]] ReadResult Reader::init() noexcept
{
VXIO_FORWARD_ERROR(readHeader());
return readContent(false);
}
[[nodiscard]] ReadResult Reader::read(Voxel64 buffer[], usize bufferLength) noexcept
{
VXIO_ASSERT_NOTNULL(buffer);
VXIO_ASSERT_NE(bufferLength, 0u);
if (not initialized) {
auto result = init();
if (result.isBad() || result.isEnd()) return result;
VXIO_DEBUG_ASSERT(initialized);
return result;
}
writeHelper.resetBuffer(buffer, bufferLength);
return readContent(true);
}
// Implementation
bool Reader::pushGroup(GroupHeader group)
{
if (group.name.empty()) {
groupStack.emplace(std::move(group));
}
auto &otherNames = groupStack.top().childNames;
if (otherNames.find(group.name) != otherNames.end()) {
return false;
}
otherNames.emplace(group.name);
groupStack.emplace(std::move(group));
return true;
}
bool Reader::popGroups(usize count)
{
if (count >= groupStack.size()) {
return false;
}
for (usize i = 0; i < count; ++i) {
groupStack.pop();
}
return true;
}
argb32 Reader::decodeColor(u8 data[])
{
switch (colorFormat) {
case RGB24: return Color32{data[0], data[1], data[2], u8{0xFF}};
case ARGB32: return Color32{data[1], data[2], data[3], data[0]};
case V8: return Color32{data[0], data[0], data[0], u8{0xFF}};
case AV16: return Color32{data[1], data[1], data[1], data[0]};
}
VXIO_DEBUG_ASSERT_UNREACHABLE();
return 0;
}
[[nodiscard]] ReadResult Reader::readHeader()
{
std::string magic;
VXIO_FORWARD_ERROR(readString(12, magic));
if (magic != "model/x-vobj") {
return ReadResult::unexpectedMagic(0, magic);
}
VXIO_FORWARD_ERROR(skipString()); // supportUrl
VXIO_FORWARD_ERROR(readExtensions());
VXIO_FORWARD_ERROR(readColorFormat());
VXIO_FORWARD_ERROR(readPalette());
u32 metaSize = stream.readBig<u32>();
VXIO_NO_EOF();
if (metaSize != 0) {
VXIO_FORWARD_ERROR(skipString()); // vendorName
stream.seekRelative(metaSize);
}
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readArrayU8(usize bytes, ArrayU8 &out)
{
static_assert(std::is_same_v<unsigned char, u8>, "reinterpretation of char as u8 impossible");
out = makeArrayU8(bytes);
stream.read(out.get(), bytes);
VXIO_NO_EOF();
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readString(usize length, std::string &out)
{
out.resize(length);
stream.read(reinterpret_cast<u8 *>(out.data()), length);
VXIO_NO_EOF();
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readString(std::string &out)
{
u16 length = stream.readBig<u16>();
VXIO_NO_EOF();
return readString(length, out);
}
[[nodiscard]] ReadResult Reader::skipString()
{
u16 length = stream.readBig<u16>();
VXIO_NO_EOF();
stream.seekRelative(length);
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readExtensions()
{
u16 extensionsSize = stream.readBig<u16>();
VXIO_NO_EOF();
std::unordered_set<std::string> extSet;
for (usize i = 0; i < extensionsSize; ++i) {
std::string extension;
VXIO_FORWARD_ERROR(readString(extension));
if (bool unrecognized = recognizedExtensions.find(extension) != recognizedExtensions.end(); unrecognized) {
return ReadResult::unknownFeature(stream.position(), extension);
}
extSet.insert(std::move(extension));
}
ext.debug = extSet.find(EXT_DEBUG) != extSet.end();
ext.exArr = extSet.find(EXT_EXISTENCE_ARRAY) != extSet.end();
ext.group = extSet.find(EXT_GROUPS) != extSet.end();
ext.arr16 = extSet.find(EXT_16_BIT_ARRAY) != extSet.end();
ext.arr32 = extSet.find(EXT_32_BIT_ARRAY) != extSet.end();
if (ext.arr16 && ext.arr32) {
return ReadResult::parseError(stream.position(), "extension conflict between arr16 and arr32");
}
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readPalette()
{
palette.bits = stream.readU8();
VXIO_NO_EOF();
if (recognizedPaletteBits.find(palette.bits) == recognizedPaletteBits.end()) {
return ReadResult::unexpectedSymbol(stream.position(), "unrecognized palette bits: " + stringify(palette.bits));
}
switch (palette.bits) {
case 0: {
palette.size = 0;
return ReadResult::ok();
}
case 8: {
palette.size = zeroToMaxPlusOne(stream.readU8());
break;
}
case 16: {
palette.size = zeroToMaxPlusOne(stream.readBig<u16>());
break;
}
case 32: {
palette.size = zeroToMaxPlusOne(stream.readBig<u32>());
break;
}
default: {
VXIO_DEBUG_ASSERT_UNREACHABLE();
}
}
VXIO_NO_EOF();
VXIO_FORWARD_ERROR(readArrayU8(palette.size * colorByteCount, palette.content));
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readColorFormat()
{
u8 result = stream.readU8();
VXIO_NO_EOF();
if (recognizedColorFormats.find(result) == recognizedColorFormats.end()) {
return ReadResult::unexpectedSymbol(stream.position(), "unknown color format: 0x" + stringifyHex(result));
}
colorFormat = static_cast<ColorFormat>(result);
colorByteCount = (static_cast<u8>(colorFormat) & u8{0x3f}) / u8{8};
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readDataFormat()
{
u8 result = stream.readU8();
VXIO_NO_EOF();
if (recognizedDataFormats.find(result) == recognizedDataFormats.end()) {
return ReadResult::unexpectedSymbol(stream.position(), "unknown data format: 0x" + stringifyHex(result));
}
state.format = static_cast<DataFormat>(result);
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readDimensions()
{
constexpr auto transform = [](auto num) -> u64 {
return (num == 0) ? static_cast<u64>(std::numeric_limits<decltype(num)>::max()) + 1 : num;
};
static_assert(transform(u8{00}) == 0x100);
static_assert(transform(u16{0}) == 0x10000);
static_assert(transform(u32{0}) == 0x100000000);
if (ext.arr32) {
state.arrDims[0] = transform(stream.readBig<u32>());
state.arrDims[1] = transform(stream.readBig<u32>());
state.arrDims[2] = transform(stream.readBig<u32>());
VXIO_NO_EOF();
// TODO overflow safety
state.arrLim = state.arrDims[0] * state.arrDims[1] * state.arrDims[2];
}
else {
if (ext.arr16) {
state.arrDims[0] = transform(stream.readBig<u16>());
state.arrDims[1] = transform(stream.readBig<u16>());
state.arrDims[2] = transform(stream.readBig<u16>());
}
else {
state.arrDims[0] = transform(stream.readU8());
state.arrDims[1] = transform(stream.readU8());
state.arrDims[2] = transform(stream.readU8());
}
VXIO_NO_EOF();
state.arrLim = state.arrDims[0] * state.arrDims[1] * state.arrDims[2];
}
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readVoxel(argb32 &out)
{
if (palette.bits == 0) {
ArrayU8 result;
VXIO_FORWARD_ERROR(readArrayU8(colorByteCount, result));
out = decodeColor(result.get());
return ReadResult::ok();
}
else if (palette.size == 1) {
out = decodeColor(palette.content.get());
return ReadResult::ok();
}
else {
return readVoxelUsingPalette(out);
}
}
[[nodiscard]] ReadResult Reader::readVoxelUsingPalette(argb32 &out)
{
u32 index;
switch (palette.bits) {
case 8: {
index = stream.readU8();
break;
}
case 16: {
index = stream.readBig<u16>();
break;
}
case 32: {
index = stream.readBig<u32>();
break;
}
default: VXIO_DEBUG_ASSERT_UNREACHABLE();
}
VXIO_NO_EOF();
out = decodeColor(palette.content.get() + index * colorByteCount);
return ReadResult::ok();
}
[[nodiscard]] ReadResult Reader::readContent(bool resume)
{
if (ext.group) {
if (not resume) {
state.grpIndex = 0;
state.grpLim = stream.readBig<u32>();
VXIO_NO_EOF();
}
return state.grpIndex++ < state.grpLim ? readGroup(resume) : ReadResult::end(writeHelper.voxelsWritten());
}
else {
if (not resume) {
VXIO_FORWARD_ERROR(readDataFormat());
}
auto result = readTypedData(resume);
return (result.isBad() || result.type != ResultCode::READ_OBJECT_END) ? result
: ReadResult::end(result.voxelsRead);
}
}
[[nodiscard]] ReadResult Reader::readGroup(bool resume)
{
if (not resume) {
u16 popCount = stream.readBig<u16>();
VXIO_NO_EOF();
if (not popGroups(popCount)) {
return ReadResult::parseError(stream.position(), "too many groups popped (" + stringify(popCount) + ")");
}
std::string groupName;
VXIO_FORWARD_ERROR(readString(groupName));
Vec3i32 pos;
stream.readBig<3>(pos.data());
if (not pushGroup({groupName, pos})) {
return ReadResult::parseError(stream.position(), "duplicate group \"" + groupName + "\"");
}
VXIO_FORWARD_ERROR(readDataFormat());
}
return readTypedData(resume);
}
[[nodiscard]] ReadResult Reader::readTypedData(bool resume)
{
ReadResult result = ReadResult::nextObject();
if (state.format == EMPTY) {
return result;
}
if (not resume) {
if (state.format == ARRAY_TILED) {
VXIO_FORWARD_ERROR(readDimensions());
}
state.datIndex = 0;
state.datLim = stream.readBig<u32>();
VXIO_NO_EOF();
}
// we will always return OK (incomplete read) if there are more arrays or voxels
// if all were read NEXT_OBJECT will be returned
#define DO_READ(function) \
for (; state.datIndex < state.datLim; ++state.datIndex) { \
result = function(resume); \
if (result.isBad() || result.type != ResultCode::READ_OBJECT_END) break; \
resume = false; \
} \
break;
// we handle this here instead of in readPositionedVoxel because it would be too wasteful to make a last-minute
// decision for every voxel
if (not initialized && state.format == LIST) {
initialized = true;
return ReadResult::ok();
}
switch (state.format) {
case LIST: DO_READ(readPositionedVoxel);
case ARRAY_POSITIONED: DO_READ(readPositionedArray);
case ARRAY_TILED: DO_READ(readTiledArray);
case EMPTY: VXIO_DEBUG_ASSERT_UNREACHABLE();
}
return result;
#undef DO_READ
}
[[nodiscard]] ReadResult Reader::readPositionedVoxel(bool)
{
VXIO_DEBUG_ASSERT(initialized);
if (writeHelper.isFull()) {
return ReadResult::ok(writeHelper.voxelsWritten());
}
Vec3i32 pos;
stream.readBig<3>(pos.data());
VXIO_NO_EOF();
argb32 color;
VXIO_FORWARD_ERROR(readVoxel(color));
writeHelper.write(pos.cast<i64>(), color);
return ReadResult::nextObject(writeHelper.voxelsWritten());
}
[[nodiscard]] ReadResult Reader::readPositionedArray(bool resume)
{
if (not resume) {
stream.readBig<3, i64>(state.arrPos.data());
VXIO_NO_EOF();
VXIO_FORWARD_ERROR(readDimensions());
state.arrIndex = 0;
}
return readArrayContent(resume);
}
[[nodiscard]] ReadResult Reader::readTiledArray(bool resume)
{
if (not resume) {
stream.readBig<3, i64>(state.arrPos.data());
VXIO_NO_EOF();
state.arrPos = mul(state.arrPos, state.arrDims.cast<i64>());
}
return readArrayContent(resume);
}
[[nodiscard]] ReadResult Reader::readArrayContent(bool resume)
{
const auto offsetGuard = writeHelper.addGuardedOffset(state.arrPos);
return ext.exArr ? readArrayWithContentExistence(resume) : readArrayContentWithoutExistence(resume);
}
[[nodiscard]] ReadResult Reader::readArrayWithContentExistence(bool resume)
{
if (not resume) {
u32 existenceBytes = divCeil(static_cast<u32>(state.arrLim), 8);
VXIO_FORWARD_ERROR(readArrayU8(existenceBytes, state.existArr));
state.arrLim = stream.readBig<u32>();
VXIO_NO_EOF();
state.arrIndex = 0;
if (not initialized) {
initialized = true;
return ReadResult::ok();
}
}
VXIO_DEBUG_ASSERT(initialized);
const u64 limX = state.arrDims.x();
const u64 limY = state.arrDims.y();
const u64 limZ = state.arrDims.z();
for (; state.arrZ < limZ; ++state.arrZ) {
for (; state.arrY < limY; ++state.arrY) {
for (; state.arrX < limX; ++state.arrX, ++state.arrIndex) {
if (writeHelper.isFull()) {
return ReadResult::ok(writeHelper.voxelsWritten());
}
usize superIndex = state.arrIndex / 8;
u8 maskBit = u8{0b10000000} >> (state.arrIndex % 8);
if ((state.existArr[superIndex] & maskBit) == 0) continue;
argb32 color;
VXIO_FORWARD_ERROR(readVoxel(color));
writeHelper.write({state.arrX, state.arrY, state.arrZ}, color);
}
state.arrX = 0;
}
state.arrY = 0;
}
return ReadResult::nextObject(writeHelper.voxelsWritten());
}
[[nodiscard]] ReadResult Reader::readArrayContentWithoutExistence(bool)
{
if (not initialized) {
initialized = true;
return ReadResult::ok();
}
VXIO_DEBUG_ASSERT(initialized);
const u64 limX = state.arrDims.x();
const u64 limY = state.arrDims.y();
const u64 limZ = state.arrDims.z();
for (; state.arrZ < limZ; ++state.arrZ) {
for (; state.arrY < limY; ++state.arrY) {
for (; state.arrX < limX; ++state.arrX) {
if (writeHelper.isFull()) {
return ReadResult::ok(writeHelper.voxelsWritten());
}
argb32 color;
VXIO_FORWARD_ERROR(readVoxel(color));
writeHelper.write({state.arrX, state.arrY, state.arrZ}, color);
}
state.arrX = 0;
}
state.arrY = 0;
}
return ReadResult::nextObject(writeHelper.voxelsWritten());
}
} // namespace voxelio::vobj
| 28.92437 | 120 | 0.623998 | [
"model",
"transform"
] |
cebf233ec8bcd78c216693e3eefab2ba47fd083e | 522 | cpp | C++ | Visitor/C++/Renderer.cpp | Ghabriel/DesignPatterns | d2a1933e3c75e4f48d0dae52795018012e17d22b | [
"Apache-2.0"
] | null | null | null | Visitor/C++/Renderer.cpp | Ghabriel/DesignPatterns | d2a1933e3c75e4f48d0dae52795018012e17d22b | [
"Apache-2.0"
] | null | null | null | Visitor/C++/Renderer.cpp | Ghabriel/DesignPatterns | d2a1933e3c75e4f48d0dae52795018012e17d22b | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "Renderer.hpp"
#include "DrawableShape.hpp"
#include "Point.hpp"
#include "Line.hpp"
void Renderer::addShape(const DrawableShape& shape) {
shapes.push_back(shape);
}
void Renderer::drawAll() const {
for (auto& shape : shapes) {
shape.get().draw(*this);
}
}
void Renderer::draw(const Point& point) const {
std::cout << "Drawing point " << point << std::endl;
}
void Renderer::draw(const Line& line) const {
std::cout << "Drawing line " << line << std::endl;
}
| 20.076923 | 56 | 0.643678 | [
"shape"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.