hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d571bea53f21a1864f150d1350f703b8d1890b7e | 504 | cpp | C++ | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | // Random Rectangle
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
//Constants, and assigned values
const int MAXHEIGHT = 3;
const int MAX = 40;
unsigned seed = time(0);
srand(seed);
int length = rand();
//Gives length its max value
//the 1 prevents it from outputing nothing
length = rand() % MAX + 1;
//outputs the # rectangle
std::string max;
max.assign(length,'#');
std::cout << max << std::endl;
std::cout << max << std::endl;
std::cout << max << std::endl;
return 0;
}
| 16.8 | 42 | 0.662698 | CSUF-CPSC120-2019F23-24 |
d5775ec94f6960c8745c9549f9b4bf7147d02b6e | 730 | hpp | C++ | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_GUI_IMPL_MAKE_CONTAINER_PAIR_HPP_INCLUDED
#define SGE_GUI_IMPL_MAKE_CONTAINER_PAIR_HPP_INCLUDED
#include <sge/gui/impl/swap_pair.hpp>
#include <sge/gui/widget/reference_alignment_pair.hpp>
#include <sge/gui/widget/reference_alignment_vector.hpp>
namespace sge::gui::impl
{
sge::gui::widget::reference_alignment_vector make_container_pair(
sge::gui::widget::reference_alignment_pair const &,
sge::gui::widget::reference_alignment_pair const &,
sge::gui::impl::swap_pair);
}
#endif
| 30.416667 | 65 | 0.761644 | cpreh |
d57b2e18c1af91ea67aa92a11bb3c0f1c6580aa9 | 3,416 | cpp | C++ | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | #include "descriptor_init.hpp"
#include "tools_runtime.hpp"
namespace nd::src::graphics::vulkan
{
using namespace nd::src::tools;
DescriptorPool
createDescriptorPool(opt<const DescriptorPoolCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto createInfo = VkDescriptorPoolCreateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = cfg.next,
.flags = cfg.flags,
.maxSets = cfg.maxSets,
.poolSizeCount = static_cast<u32>(cfg.sizes.size()),
.pPoolSizes = cfg.sizes.data()};
VkDescriptorPool descriptorPool;
ND_VK_ASSERT(vkCreateDescriptorPool(device, &createInfo, ND_VK_ALLOCATION_CALLBACKS, &descriptorPool));
return descriptorPool;
}
DescriptorSetLayout
createDescriptorSetLayout(opt<const DescriptorSetLayoutCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto createInfo = VkDescriptorSetLayoutCreateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = cfg.next,
.flags = cfg.flags,
.bindingCount = static_cast<u32>(cfg.bindings.size()),
.pBindings = cfg.bindings.data()};
VkDescriptorSetLayout descriptorSetLayout;
ND_VK_ASSERT(vkCreateDescriptorSetLayout(device, &createInfo, ND_VK_ALLOCATION_CALLBACKS, &descriptorSetLayout));
return descriptorSetLayout;
}
DescriptorSetLayoutObjects
createDescriptorSetLayoutObjects(opt<const DescriptorSetLayoutObjectsCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
return {.mesh = createDescriptorSetLayout(cfg.mesh, device)};
}
vec<DescriptorSet>
allocateDescriptorSets(opt<const DescriptorSetCfg>::ref cfg,
opt<const DescriptorPool>::ref descriptorPool,
const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto allocateInfo = VkDescriptorSetAllocateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = cfg.next,
.descriptorPool = descriptorPool,
.descriptorSetCount = static_cast<u32>(cfg.layouts.size()),
.pSetLayouts = cfg.layouts.data()};
auto descriptorSets = vec<DescriptorSet>(cfg.layouts.size());
ND_VK_ASSERT(vkAllocateDescriptorSets(device, &allocateInfo, descriptorSets.data()));
return descriptorSets;
}
} // namespace nd::src::graphics::vulkan
| 46.794521 | 141 | 0.53103 | InspectorSolaris |
d57e24cab5c502dd7faa514aa18dac25dd49dce5 | 4,651 | hh | C++ | include/click/statvector.hh | MassimoGirondi/fastclick | 71b9a3392c2e847a22de3c354be1d9f61216cb5b | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | include/click/statvector.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | include/click/statvector.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | // -*- c-basic-offset: 4 -*-
#ifndef CLICK_STATVECTOR_HH
#define CLICK_STATVECTOR_HH
#include <click/batchelement.hh>
#include <click/multithread.hh>
#include <click/vector.hh>
#include <click/straccum.hh>
#include <click/statvector.hh>
CLICK_DECLS
template <typename T>
class StatVector {
enum{H_MEDIAN,H_AVERAGE,H_DUMP,H_MAX_OBS,H_N_OBS,H_NZ,H_MAX,H_MAX_OBS_VAL};
static String read_handler(Element *e, void *thunk)
{
StatVector *fd = (StatVector*)e->cast("StatVector");
switch ((intptr_t)thunk) {
case H_MAX:
case H_NZ:
case H_MAX_OBS: {
Vector<T> sums(fd->stats.get_value(0).size(),0);
T max_batch_v = -1;
int max_batch_index = -1;
int max_nz = -1;
int nz=0;
for (unsigned j = 0; j < sums.size(); j++) {
for (unsigned i = 0; i < fd->stats.weight(); i++) {
sums[j] += fd->stats.get_value(i)[j];
}
if (sums[j] > max_batch_v) {
max_batch_v = sums[j];
max_batch_index = j;
}
if (sums[j] > 0) {
max_nz = j;
nz++;
}
}
if ((intptr_t)thunk == H_MAX) {
return String(max_nz);
} else if ((intptr_t)thunk == H_NZ) {
return String(nz);
} else
return String(max_batch_index);
}
case H_N_OBS:
case H_MEDIAN: {
Vector<T> sums(fd->stats.get_value(0).size(),0);
T total = 0;
for (unsigned j = 0; j < sums.size(); j++) {
for (unsigned i = 0; i < fd->stats.weight(); i++) {
sums[j] += fd->stats.get_value(i)[j];
}
total += sums[j];
}
if ((intptr_t)thunk == H_N_OBS)
return String(total);
T val = 0;
for (int i = 0; i < sums.size(); i++) {
val += sums[i];
if (val > total/2)
return String(i);
}
return "0";
}
case H_AVERAGE: {
int count = 0;
int total = 0;
for (unsigned i = 0; i < fd->stats.weight(); i++) {
for (unsigned j = 0; j < (unsigned)fd->stats.get_value(i).size(); j++) {
total += fd->stats.get_value(i)[j] * j;
count += fd->stats.get_value(i)[j];
}
}
if (count > 0)
return String((double)total/(double)count);
else
return String(0);
}
case H_DUMP: {
StringAccum s;
Vector<T> sums(fd->stats.get_value(0).size(),0);
for (unsigned i = 0; i < fd->stats.weight(); i++) {
for (unsigned j = 0; j < (unsigned)fd->stats.get_value(i).size(); j++) {
sums[j] += fd->stats.get_value(i)[j];
if (i == fd->stats.weight() - 1 && sums[j] != 0)
s << j << ": " << sums[j] << "\n";
}
}
return s.take_string();
}
default:
return "<error>";
}
}
protected:
per_thread<Vector<T>> stats;
StatVector() {
}
StatVector(Vector<T> v) : stats(v) {
}
void add_stat_handler(Element* e) {
//Value the most seen (gives the value)
e->add_read_handler("most_seen", read_handler, H_MAX_OBS, Handler::f_expensive);
//Value the most seen (gives the frequency of the value)
e->add_read_handler("most_seen_freq", read_handler, H_MAX_OBS_VAL, Handler::f_expensive);
//Maximum value seen
e->add_read_handler("max", read_handler, H_MAX, Handler::f_expensive);
//Number of observations
e->add_read_handler("count", read_handler, H_N_OBS, Handler::f_expensive);
//Number of values that had at least one observations
e->add_read_handler("nval", read_handler, H_NZ, Handler::f_expensive);
//Value for the median number of observations
e->add_read_handler("median", read_handler, H_MEDIAN, Handler::f_expensive);
//Average of value*frequency
e->add_read_handler("average", read_handler, H_AVERAGE, Handler::f_expensive);
e->add_read_handler("avg", read_handler, H_AVERAGE, Handler::f_expensive);
//Dump all value: frequency
e->add_read_handler("dump", read_handler, H_DUMP, Handler::f_expensive);
}
};
CLICK_ENDDECLS
#endif //CLICK_STATVECTOR_HH
| 34.198529 | 97 | 0.500538 | MassimoGirondi |
d58ac31b2fb6c9ddee3b02c404d400ba910ffed0 | 369 | cpp | C++ | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | 1 | 2021-02-26T22:03:18.000Z | 2021-02-26T22:03:18.000Z | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | null | null | null | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | 1 | 2021-04-15T14:14:27.000Z | 2021-04-15T14:14:27.000Z | #include <iostream>
#include <QList>
#include <QString>
#include <cassert>
using namespace std;
int main ()
{
QList<QString> list;
list << "A" << "B" << "C" << "B" << "A";
assert(list.contains("B"));
assert(list.contains("A"));
assert(list.contains("C"));
//assert(list.indexOf("X") == -1); // returns -1
return 0;
}
| 21.705882 | 62 | 0.528455 | vanderson-rocha |
d58b83add753a6374f7748174e813bee36758f80 | 2,092 | cpp | C++ | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
//
// Copyright 2010
//
// This file is part of starlight.
//
// starlight 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.
//
// starlight 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 starlight. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////////
//
// File and Version Information:
// $Rev:: $: revision of last commit
// $Author: jwebb $: author of last commit
// $Date: 2012/11/27 22:27:31 $: date of last commit
//
// Description:
//
//
//
///////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <exception>
#include <cstdlib>
#include "filewriter.h"
using namespace std;
fileWriter::fileWriter()
: _fileName(""),
_fileStream()
{ }
fileWriter::fileWriter(const string& fileName) :
_fileName(fileName)
,_fileStream(fileName.c_str())
{ }
fileWriter::~fileWriter()
{ }
int fileWriter::open()
{
try
{
_fileStream.open(_fileName.c_str());
}
catch (const ios::failure & error)
{
cerr << "I/O exception: " << error.what() << endl;
return EXIT_FAILURE;
}
return 0;
}
int fileWriter::open(const string& fileName)
{
_fileName = fileName;
return open();
}
int fileWriter::close()
{
try
{
_fileStream.close();
}
catch (const ios::failure & error)
{
cerr << "I/O exception: " << error.what() << endl;
return EXIT_FAILURE;
}
return 0;
}
| 22.021053 | 75 | 0.556883 | klendathu2k |
d58cf4d6b06e06529868f891053a04653fe15275 | 9,457 | hpp | C++ | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 1 | 2018-06-15T23:49:37.000Z | 2018-06-15T23:49:37.000Z | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 5 | 2017-04-23T03:25:10.000Z | 2018-02-23T07:48:16.000Z | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | null | null | null | // Vector3.hpp
// A 3d vector class used for defining coordinates in space
#pragma once
#include <cmath>
#include <SFML/System/Vector3.hpp>
namespace fe
{
template <typename dataType>
struct Vector3;
template <typename T>
struct lightVector3;
template<typename dataType, typename vectorType>
Vector3<dataType> operator*(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
Vector3<dataType> operator/(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
void operator*=(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
void operator/=(const dataType &lhs, Vector3<vectorType> &rhs);
template <typename dataType>
struct Vector3
{
dataType x;
dataType y;
dataType z;
Vector3() : x(0), y(0), z(0) {}
Vector3(dataType X, dataType Y, dataType Z) : x(X), y(Y), z(Z) {}
Vector3(const Vector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
Vector3(const lightVector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
Vector3(const sf::Vector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
template <typename otherDataType>
Vector3(const Vector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
template <typename otherDataType>
Vector3(const lightVector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
template <typename otherDataType>
Vector3(const sf::Vector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
Vector3 &operator=(const Vector3<dataType> ©) { if (© != this) { x = copy.x; y = copy.y; z = copy.z; } return *this; }
bool operator==(const Vector3<dataType> &rhs) const { return rhs.x == x && rhs.y == y && rhs.y == y; }
Vector3<dataType> operator+(const Vector3<dataType> &rhs) const { return Vector3<dataType>(rhs.x + x, rhs.y + y, rhs.z + z); }
Vector3<dataType> operator-(const Vector3<dataType> &rhs) const { return Vector3<dataType>(x - rhs.x, y - rhs.y, z - rhs.z); }
Vector3<dataType> operator*(const dataType &rhs) const { return Vector3<dataType>(rhs * x, rhs * y, rhs * z); }
Vector3<dataType> operator/(const dataType &rhs) const { return Vector3<dataType>(x / rhs, y / rhs, z / rhs); }
Vector3<dataType> operator-() const { return Vector3<dataType>(-x, -y, -z); }
template<typename T> Vector3<dataType> operator+(const Vector3<T> &rhs) const { return Vector3<dataType>(static_cast<dataType>(rhs.x) + x, static_cast<dataType>(rhs.y) + y, static_cast<dataType>(rhs.z) + z); }
template<typename T> Vector3<dataType> operator-(const Vector3<T> &rhs) const { return Vector3<dataType>(x - static_cast<dataType>(rhs.x), y - static_cast<dataType>(rhs.y), z - static_cast<dataType>(rhs.z)); }
template<typename T> Vector3<dataType> operator*(const T &rhs) const { return Vector3<dataType>(static_cast<dataType>(rhs) * x, static_cast<dataType>(rhs) * y, static_cast<dataType>(rhs) * z); }
template<typename T> Vector3<dataType> operator/(const T &rhs) const { return Vector3<dataType>(x / static_cast<dataType>(rhs), y / static_cast<dataType>(rhs), z / static_cast<dataType>(rhs)); }
// A way to get the x/y coordinate based on the index provided. Useful in incrementing loops
dataType operator[](const size_t &index) const { if (index == 0) return x; if (index == 1) return y; if (index == 2) return z; return 0.f; }
// A way to get the x/y coordinate based on the index provided. Useful in incrementing loops
dataType operator[](const int &index) const { if (index == 0) return x; if (index == 1) return y; if (index == 2) return z; return 0.f; }
void operator+=(const Vector3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; }
void operator-=(const Vector3 &rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; }
void operator*=(const dataType &rhs){ x *= rhs; y *= rhs; z *= rhs; }
void operator/=(const dataType &rhs){ x /= rhs; y /= rhs; z /= rhs; }
friend Vector3<dataType> operator*(const dataType &lhs, Vector3<dataType> &rhs);
friend Vector3<dataType> operator/(const dataType &lhs, Vector3<dataType> &rhs);
friend void operator*=(const dataType &lhs, Vector3<dataType> &rhs);
friend void operator/=(const dataType &lhs, Vector3<dataType> &rhs);
float magnitude() const { return std::sqrt(x * x + y * y + z * z); }
float magnitudeSqr() const { return x * x + y * y + z * z; }
Vector3<dataType> normalize() const
{
float mag = magnitude();
if (mag != 0.f)
{
return Vector3<dataType>(x / mag, y / mag, z / mag);
}
return Vector3<dataType>();
}
Vector3<dataType> clamp(float max)
{
// max^3 / (x^3 + y^3) = 3 * Modifier
if (max * max > x * x + y * y + z * z) return *this;
float modifier = std::sqrt((max * max) / (x * x + y * y + z * z));
return modifier < 1.f ? fe::Vector3d(x * modifier, y * modifier, z * modifier) : *this;
}
Vector3<dataType> abs() const { return Vector3(std::abs(x), std::abs(y), std::abs(z)); }
Vector3<dataType> normal() const { return Vector3(-y, x, z); }
float dot(const Vector3<dataType> &other) const { return x * other.x + y * other.y + z * other.z; }
Vector3<dataType> cross(const Vector3<dataType> &other) const { return Vector3<dataType>(y * other.y - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); }
Vector3<dataType> project(Vector3<dataType> &other) const
{
float mag = other.magnitudeSqr();
if (mag != 0)
{
return Vector3<dataType>(other * (dot(other) / other.magnitudeSqr()));
}
return Vector3();
}
};
// External functions that are useful for Vector operations
template<typename dataType>
Vector3<dataType> lerp(const Vector3<dataType> &a, const Vector3<dataType> &b, const float &percent)
{
return Vector3<dataType>((dataType(1) - percent) * a + (percent * b));
}
template<typename dataType, typename vectorType>
Vector3<dataType> fe::operator*(const dataType &lhs, Vector3<vectorType> &rhs)
{
return rhs * lhs;
}
template<typename dataType, typename vectorType>
Vector3<dataType> fe::operator/(const dataType &lhs, Vector3<vectorType> &rhs)
{
return rhs / lhs;
}
template<typename dataType, typename vectorType>
void fe::operator*=(const dataType &lhs, Vector3<vectorType> &rhs)
{
rhs *= lhs;
}
template<typename dataType, typename vectorType>
void fe::operator/=(const dataType &lhs, Vector3<vectorType> &rhs)
{
rhs /= lhs;
}
template<typename T>
struct lightVector3
{
T x;
T y;
T z;
lightVector3() : x(T()), y(T()), z(T()) {}
lightVector3(T x, T y, T z) : x(x), y(y), z(z) {}
lightVector3(const fe::Vector3<T> ©) : x(copy.x), y(copy.y), z(copy.z) {}
lightVector3<T> operator-(const lightVector3<T> &rhs) { return fe::lightVector3<T>(x - rhs.x, y - rhs.y, z - rhs.z); }
lightVector3<T> operator+(const lightVector3<T> &rhs) { return fe::lightVector3<T>(x + rhs.x, y + rhs.y, z + rhs.z); }
lightVector3<T> operator-(const fe::Vector3<T> &rhs) { return fe::lightVector3<T>(x - rhs.x, y - rhs.y, z - rhs.z); }
lightVector3<T> operator+(const fe::Vector3<T> &rhs) { return fe::lightVector3<T>(x + rhs.x, y + rhs.y, z + rhs.z); }
lightVector2<T> operator*(T rhs) { return fe::lightVector2<T>(x * rhs, y * rhs, z * rhs); }
lightVector2<T> operator/(T rhs) { return fe::lightVector2<T>(x / rhs, y / rhs, z / rhs); }
};
typedef lightVector3<float> lightVector3d;
typedef Vector3<float> Vector3d;
}
| 55.629412 | 227 | 0.538754 | TheCandianVendingMachine |
d58d16e90aea0760422135219f8e4764a4605170 | 6,152 | hh | C++ | include/psp/libos/su/DispatchSu.hh | maxdml/Pers-phone | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | 2 | 2021-11-13T03:31:33.000Z | 2022-02-20T16:08:50.000Z | include/psp/libos/su/DispatchSu.hh | maxdml/psp | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | null | null | null | include/psp/libos/su/DispatchSu.hh | maxdml/psp | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | null | null | null | #ifndef DISPATCH_SU_H_
#define DISPATCH_SU_H_
#include <arpa/inet.h>
#include <psp/libos/persephone.hh>
#include <psp/libos/Request.hh>
#include <fstream>
#define MAX_CLIENTS 64
#define RESA_SAMPLES_NEEDED 5e4
#define UPDATE_PERIOD 5 * 1e3 //5 usec
#define MAX_WINDOWS 8192
struct profiling_windows {
uint64_t tsc_start;
uint64_t tsc_end;
uint64_t count;
double mean_ns;
uint64_t qlen[MAX_TYPES];
uint64_t counts[MAX_TYPES];
uint32_t group_res[MAX_TYPES];
uint32_t group_steal[MAX_TYPES];
bool do_update;
};
class Dispatcher : public Worker {
/* Dispatch mode */
public: enum dispatch_mode {
DFCFS = 0,
CFCFS,
SJF,
DARC,
EDF,
UNKNOWN
};
public: const char *dp_str[6] = {
"DFCFS",
"CFCFS",
"SJF",
"DARC",
"EDF",
"UNKNOWN"
};
public: static enum dispatch_mode str_to_dp(std::string const &dp) {
if (dp == "CFCFS") {
return dispatch_mode::CFCFS;
} else if (dp == "DFCFS") {
return dispatch_mode::DFCFS;
} else if (dp == "SJF") {
return dispatch_mode::SJF;
} else if (dp == "DARC") {
return dispatch_mode::DARC;
} else if (dp == "EDF") {
return dispatch_mode::EDF;
}
return dispatch_mode::UNKNOWN;
}
public: enum dispatch_mode dp;
// peer ID -> number of "compute slot" available (max= max batch size)
public: uint32_t free_peers = 0; // a bitmask of free workers
private: uint8_t last_peer = 0;
public: RequestType *rtypes[static_cast<int>(ReqType::LAST)];
public: uint32_t n_rtypes;
public: uint32_t type_to_nsorder[static_cast<int>(ReqType::LAST)];
public: uint64_t num_rcvd = 0; /** < Total number of received requests */
private: uint32_t n_drops = 0;
private: uint32_t num_dped = 0;
private: uint64_t peer_dpt_tsc[MAX_WORKERS]; // Record last time we dispatched to a peer
public: uint32_t n_workers = 0;
// DARC parameters
public: uint32_t n_resas;
public: uint32_t n_groups = 0;
public: TypeGroups groups[MAX_TYPES];
private: float delta = 0.2; // Similarity factor
public: bool first_resa_done;
public: bool dynamic;
public: uint32_t update_frequency;
public: profiling_windows windows[MAX_WINDOWS];
private: uint32_t prev_active;
private: uint32_t n_windows = 0;
public: uint32_t spillway = 0;
public: int set_darc();
private: int update_darc();
private: int drain_queue(RequestType *&rtype);
private: int dyn_resa_drain_queue(RequestType *&rtype);
private: int dequeue(unsigned long *payload);
private: int setup() override;
private: int work(int status, unsigned long payload) override;
private: int process_request(unsigned long req) override;
public: int signal_free_worker(int peer_id, unsigned long type);
public: int enqueue(unsigned long req, uint64_t cur_tsc);
public: int dispatch();
private: inline int push_to_rqueue(unsigned long req, RequestType *&rtype, uint64_t cur_tsc);
public: void set_dp(std::string &policy) {
dp = Dispatcher::str_to_dp(policy);
}
public: Dispatcher() : Worker(WorkerType::DISPATCH) {
if (cycles_per_ns == 0)
PSP_WARN("Dispatcher set before system TSC was calibrated. DARC update frequency likely 0.");
update_frequency = UPDATE_PERIOD * cycles_per_ns;
}
public: Dispatcher(int worker_id) : Worker(WorkerType::DISPATCH, worker_id) {
if (cycles_per_ns == 0)
PSP_WARN("Dispatcher set before system TSC was calibrated. DARC update frequency likely 0.");
update_frequency = UPDATE_PERIOD * cycles_per_ns;
}
public: ~Dispatcher() {
PSP_INFO(
"Nested dispatcher received " << num_rcvd << " (" << n_batchs_rcvd << " batches)"
<< " dispatched " << num_dped << " but dropped " << n_drops << " requests"
);
PSP_INFO("Latest windows count: " << windows[n_windows].count << ". Performed " << n_windows << " updates.");
for (uint32_t i = 0; i < n_rtypes; ++i) {
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[i]->type)] << "] has "
<< rtypes[i]->rqueue_head - rtypes[i]->rqueue_tail << " pending items"
);
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[i]->type)] << "] average ns: "
<< rtypes[i]->windows_mean_ns / cycles_per_ns
);
delete rtypes[i];
}
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[type_to_nsorder[0]]->type)] << "] has "
<< rtypes[type_to_nsorder[0]]->rqueue_head - rtypes[type_to_nsorder[0]]->rqueue_tail
<< " pending items"
);
delete rtypes[type_to_nsorder[0]];
if (dp == DARC) {
// Record windows statistics
std::string path = generate_log_file_path(label, "server/windows");
std::cout << "dpt log at " << path << std::endl;
std::ofstream output(path);
if (not output.is_open()) {
PSP_ERROR("COULD NOT OPEN " << path);
} else {
output << "ID\tSTART\tEND\tGID\tRES\tSTEAL\tCOUNT\tUPDATED\tQLEN" << std::endl;
for (size_t i = 0; i < n_windows; ++i) {
auto &w = windows[i];
for (size_t j = 0; j < n_rtypes; ++j) {
output << i << "\t" << std::fixed << w.tsc_start / cycles_per_ns
<< "\t" << std::fixed << w.tsc_end / cycles_per_ns
<< "\t" << j
<< "\t" << w.group_res[j] << "\t" << w.group_steal[j]
<< "\t" << w.counts[j] << "\t" << w.do_update
<< "\t" << w.qlen[j]
<< std::endl;
}
}
output.close();
}
}
}
};
#endif //DISPATCH_SU_H_
| 36.402367 | 117 | 0.569083 | maxdml |
d58f93c1ba82427fc731279cc053a0ad36790def | 91 | cpp | C++ | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | #include <test.inline/test.inline.hpp>
ETAIO_ABI( ETAio::testinline, (reqauth)(forward) )
| 22.75 | 50 | 0.747253 | ETAIO |
d58fba1c1f02154fdefdf22d4e656da6e9a640e8 | 432 | cpp | C++ | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | 2 | 2020-12-11T15:46:26.000Z | 2021-02-02T05:26:11.000Z | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | null | null | null | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | null | null | null | // Copyright Claudio Bantaloukas 2017-2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <throwing/unique_ptr.hpp>
int main() {
// cannot assign from unique_ptr to another (array version)
throwing::unique_ptr<int[]> from;
throwing::unique_ptr<int[]> to;
to = from;
return 0;
}
| 28.8 | 63 | 0.668981 | rockdreamer |
d593acf738b3cfb817b771b1122d7b155f37a0ea | 17,597 | cpp | C++ | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | //MIT License
//Copyright (c) 2020 bexoft GmbH ([email protected])
//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.
#if !defined(WIN32)
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "finalmq/poller/PollerImplEpoll.h"
#include "finalmq/helpers/OperatingSystem.h"
#include "MockIOperatingSystem.h"
using ::testing::_;
using ::testing::Return;
using ::testing::InSequence;
using ::testing::DoAll;
using namespace finalmq;
static const std::string BUFFER = "Hello";
static const int EPOLL_FD = 3;
static const int CONTROLSOCKET_READ = 4;
static const int CONTROLSOCKET_WRITE = 5;
static const int TESTSOCKET = 7;
static const int NUMBER_OF_BYTES_TO_READ = 20;
static const int TIMEOUT = 10;
MATCHER_P(Event, event, "")
{
return (arg->events == event->events &&
arg->data.fd == event->data.fd);
}
class TestEpoll: public testing::Test
{
protected:
virtual void SetUp()
{
m_mockMockOperatingSystem = new MockIOperatingSystem;
OperatingSystem::setInstance(std::unique_ptr<IOperatingSystem>(m_mockMockOperatingSystem));
m_select = std::make_unique<PollerImplEpoll>();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_create1(EPOLL_CLOEXEC)).Times(1)
.WillRepeatedly(Return(EPOLL_FD));
SocketDescriptorPtr sd1 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_READ);
SocketDescriptorPtr sd2 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_WRITE);
EXPECT_CALL(*m_mockMockOperatingSystem, makeSocketPair(_, _)).Times(1)
.WillRepeatedly(DoAll(testing::SetArgReferee<0>(sd1), testing::SetArgReferee<1>(sd2), Return(0)));
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = CONTROLSOCKET_READ;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, CONTROLSOCKET_READ, Event(&evCtl))).Times(1);
m_select->init();
testing::Mock::VerifyAndClearExpectations(m_mockMockOperatingSystem);
}
virtual void TearDown()
{
EXPECT_CALL(*m_mockMockOperatingSystem, close(EPOLL_FD)).Times(1).WillRepeatedly(Return(0));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(_)).WillRepeatedly(Return(0));
m_select = nullptr;
OperatingSystem::setInstance({});
}
MockIOperatingSystem* m_mockMockOperatingSystem = nullptr;
std::unique_ptr<IPoller> m_select;
};
TEST_F(TestEpoll, timeout)
{
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(10);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(_, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableEINTR)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
{
InSequence seq;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
}
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EINTR)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EACCES)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, true);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWaitSocketDescriptorsChanged)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
epoll_event evCtlRemove;
evCtlRemove.events = 0;
evCtlRemove.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_DEL, socket->getDescriptor(), Event(&evCtlRemove))).Times(1);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(
testing::DoAll(
testing::Invoke([this, &socket](int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t* sigmask){
m_select->removeSocket(socket);
}),
testing::SetArgPointee<1>(events),
Return(1)
)
);
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(socket->getDescriptor())).WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectRead)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectEpollError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLERR;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, true);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketIoCtlError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(-1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLOUT;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, true);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisableWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
epoll_event evCtlDisableWrite;
evCtlDisableWrite.events = EPOLLIN;
evCtlDisableWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlDisableWrite))).Times(1);
m_select->disableWrite(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
#endif
| 39.455157 | 151 | 0.697278 | mnaveedb |
d59528abc769a6352fba83bf91ce430152d70e5e | 665 | hpp | C++ | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file default_sentinel.hpp
*
* @brief default_sentinel の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#define BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#include <bksge/fnd/iterator/config.hpp>
#if defined(BKSGE_USE_STD_RANGES_ITERATOR)
namespace bksge
{
using std::default_sentinel_t;
using std::default_sentinel;
} // namespace bksge
#else
#include <bksge/fnd/config.hpp>
namespace bksge
{
struct default_sentinel_t {};
BKSGE_INLINE_VAR BKSGE_CONSTEXPR
default_sentinel_t default_sentinel{};
} // namespace bksge
#endif
#endif // BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
| 16.219512 | 50 | 0.741353 | myoukaku |
d59e02bcb06319d174002a7a7c0b41db85531c6f | 1,992 | cpp | C++ | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | null | null | null | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | 1 | 2021-01-13T01:35:45.000Z | 2021-05-04T15:43:56.000Z | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | 2 | 2021-01-13T01:36:02.000Z | 2021-08-08T10:17:53.000Z | #include "RaZor/Interface/Component/RigidBodyGroup.hpp"
#include "ui_RigidBodyComp.h"
#include <RaZ/Entity.hpp>
#include <RaZ/Physics/RigidBody.hpp>
RigidBodyGroup::RigidBodyGroup(Raz::Entity& entity, AppWindow& appWindow) : ComponentGroup(entity, appWindow) {
Ui::RigidBodyComp rigidBodyComp {};
rigidBodyComp.setupUi(this);
auto& rigidBody = entity.getComponent<Raz::RigidBody>();
// Mass
rigidBodyComp.mass->setValue(static_cast<double>(rigidBody.getMass()));
connect(rigidBodyComp.mass, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setMass(static_cast<float>(val));
});
// Bounciness
rigidBodyComp.bounciness->setValue(static_cast<double>(rigidBody.getBounciness()));
connect(rigidBodyComp.bounciness, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setBounciness(static_cast<float>(val));
});
// Velocity
rigidBodyComp.velocityX->setValue(static_cast<double>(rigidBody.getVelocity().x()));
rigidBodyComp.velocityY->setValue(static_cast<double>(rigidBody.getVelocity().y()));
rigidBodyComp.velocityZ->setValue(static_cast<double>(rigidBody.getVelocity().z()));
const auto updateVelocity = [rigidBodyComp, &rigidBody] (double) {
const auto velocityX = static_cast<float>(rigidBodyComp.velocityX->value());
const auto velocityY = static_cast<float>(rigidBodyComp.velocityY->value());
const auto velocityZ = static_cast<float>(rigidBodyComp.velocityZ->value());
rigidBody.setVelocity(Raz::Vec3f(velocityX, velocityY, velocityZ));
};
connect(rigidBodyComp.velocityX, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityY, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityZ, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
}
void RigidBodyGroup::removeComponent() {
m_entity.removeComponent<Raz::RigidBody>();
}
| 39.058824 | 114 | 0.758032 | Razakhel |
d59e579eb0548c18a88c8e802a4a642410d7988b | 379 | hpp | C++ | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 409 | 2015-01-03T00:08:16.000Z | 2021-11-29T05:42:06.000Z | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 185 | 2015-01-03T14:52:31.000Z | 2021-11-19T20:58:48.000Z | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 74 | 2015-01-12T19:08:54.000Z | 2021-11-22T23:43:59.000Z | // Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0
#pragma once
namespace sf {
class Text;
}
namespace hg::Utils {
[[nodiscard]] float getFontHeight(sf::Text& font);
[[nodiscard]] float getFontHeight(sf::Text& font, const unsigned int charSize);
} // namespace hg::Utils
| 19.947368 | 79 | 0.707124 | duck-37 |
d59fec959c24f6f6ab2cdad16e0476c01013e662 | 3,306 | cpp | C++ | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | null | null | null | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | null | null | null | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | 2 | 2021-06-29T14:28:21.000Z | 2022-01-31T16:45:42.000Z | #include "bullet-event.h"
#include "../../valve_sdk/interfaces/IVRenderBeams.h"
#include "../../features/ragebot/ragebot.h"
#include "../../features/ragebot/resolver/resolver.h"
void BulletImpactEvent::FireGameEvent(IGameEvent *event) {
if (!g_LocalPlayer || !event) return;
static ConVar* sv_showimpacts = g_CVar->FindVar("sv_showimpacts");
if (g_Options.misc_bullet_impacts)
sv_showimpacts->SetValue(1);
else
sv_showimpacts->SetValue(0);
if (g_Options.misc_bullet_tracer) {
if (g_EngineClient->GetPlayerForUserID(event->GetInt("userid")) == g_EngineClient->GetLocalPlayer() && g_LocalPlayer && g_LocalPlayer->IsAlive())
{
float x = event->GetFloat("x"), y = event->GetFloat("y"), z = event->GetFloat("z");
bulletImpactInfo.push_back({ g_GlobalVars->curtime, Vector(x, y, z) });
}
}
int32_t userid = g_EngineClient->GetPlayerForUserID(event->GetInt("userid"));
if (userid == g_EngineClient->GetLocalPlayer()) {
if (RageBot::Get().iTargetID != NULL) {
auto player = C_BasePlayer::GetPlayerByIndex(RageBot::Get().iTargetID);
if (!player) return;
int32_t idx = player->EntIndex();
auto &player_recs = Resolver::Get().ResolveRecord[idx];
if (!player->IsDormant())
{
int32_t tickcount = g_GlobalVars->tickcount;
if (tickcount != tickHitWall)
{
tickHitWall = tickcount;
originalShotsMissed = player_recs.iMissedShots;
if (tickcount != tickHitPlayer) {
tickHitWall = tickcount;
++player_recs.iMissedShots;
}
}
}
}
}
}
int BulletImpactEvent::GetEventDebugID(void)
{
return EVENT_DEBUG_ID_INIT;
}
void BulletImpactEvent::RegisterSelf()
{
g_GameEvents->AddListener(this, "bullet_impact", false);
}
void BulletImpactEvent::UnregisterSelf()
{
g_GameEvents->RemoveListener(this);
}
void BulletImpactEvent::Paint(void)
{
if (!g_Options.misc_bullet_tracer) return;
if (!g_EngineClient->IsInGame() || !g_LocalPlayer || !g_LocalPlayer->IsAlive()) {
bulletImpactInfo.clear();
return;
}
std::vector<BulletImpactInfo> &impacts = bulletImpactInfo;
if (impacts.empty()) return;
Color current_color(g_Options.color_bullet_tracer);
for (size_t i = 0; i < impacts.size(); i++)
{
auto current_impact = impacts.at(i);
BeamInfo_t beamInfo;
beamInfo.m_nType = TE_BEAMPOINTS;
beamInfo.m_pszModelName = "sprites/purplelaser1.vmt";
beamInfo.m_nModelIndex = -1;
beamInfo.m_flHaloScale = 0.0f;
beamInfo.m_flLife = 3.3f;
beamInfo.m_flWidth = 4.f;
beamInfo.m_flEndWidth = 4.f;
beamInfo.m_flFadeLength = 0.0f;
beamInfo.m_flAmplitude = 2.0f;
beamInfo.m_flBrightness = 255.f;
beamInfo.m_flSpeed = 0.2f;
beamInfo.m_nStartFrame = 0;
beamInfo.m_flFrameRate = 0.f;
beamInfo.m_flRed = current_color.r();
beamInfo.m_flGreen = current_color.g();
beamInfo.m_flBlue = current_color.b();
beamInfo.m_nSegments = 2;
beamInfo.m_bRenderable = true;
beamInfo.m_nFlags = FBEAM_ONLYNOISEONCE | FBEAM_NOTILE | FBEAM_HALOBEAM | FBEAM_FADEIN;
beamInfo.m_vecStart = g_LocalPlayer->GetEyePos();
beamInfo.m_vecEnd = current_impact.m_vecHitPos;
auto beam = g_RenderBeam->CreateBeamPoints(beamInfo);
if (beam) g_RenderBeam->DrawBeam(beam);
impacts.erase(impacts.begin() + i);
}
}
void BulletImpactEvent::AddSound(C_BasePlayer *p) {
} | 26.031496 | 147 | 0.705687 | d3dx9tex |
d5a0f6c285e13541ba7d921041ca19929c4d822a | 8,697 | cpp | C++ | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 1,723 | 2015-01-08T19:10:21.000Z | 2022-03-31T16:41:40.000Z | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 471 | 2015-01-02T15:02:34.000Z | 2022-03-26T17:54:10.000Z | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 380 | 2015-01-22T19:06:32.000Z | 2022-03-25T02:20:39.000Z | /**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
/*
* Manipulation of GL extensions.
*
* So far we insert GREMEDY extensions, but in the future we could also clamp
* the GL extensions to core GL versions here.
*/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <map>
#include "glproc.hpp"
#include "gltrace.hpp"
#include "os.hpp"
#include "config.hpp"
namespace gltrace {
typedef std::map<std::string, const char *> ExtensionsMap;
// Cache of the translated extensions strings
static ExtensionsMap extensionsMap;
// Additional extensions to be advertised
static const char *
extraExtension_stringsFull[] = {
"GL_GREMEDY_string_marker",
"GL_GREMEDY_frame_terminator",
"GL_ARB_debug_output",
"GL_AMD_debug_output",
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
"GL_VMWX_map_buffer_debug",
};
static const char *
extraExtension_stringsES[] = {
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
};
// Description of additional extensions we want to advertise
struct ExtensionsDesc
{
unsigned numStrings;
const char **strings;
};
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
const struct ExtensionsDesc
extraExtensionsFull = {
ARRAY_SIZE(extraExtension_stringsFull),
extraExtension_stringsFull
};
const struct ExtensionsDesc
extraExtensionsES = {
ARRAY_SIZE(extraExtension_stringsES),
extraExtension_stringsES
};
const struct ExtensionsDesc *
getExtraExtensions(const Context *ctx)
{
switch (ctx->profile.api) {
case glfeatures::API_GL:
return &extraExtensionsFull;
case glfeatures::API_GLES:
return &extraExtensionsES;
default:
assert(0);
return &extraExtensionsFull;
}
}
/**
* Translate the GL extensions string, adding new extensions.
*/
static const char *
overrideExtensionsString(const char *extensions)
{
const Context *ctx = getContext();
const ExtensionsDesc *desc = getExtraExtensions(ctx);
size_t i;
ExtensionsMap::const_iterator it = extensionsMap.find(extensions);
if (it != extensionsMap.end()) {
return it->second;
}
size_t extensionsLen = strlen(extensions);
size_t extraExtensionsLen = 0;
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
extraExtensionsLen += extraExtensionLen + 1;
}
// We use malloc memory instead of a std::string because we need to ensure
// that extensions strings will not move in memory as the extensionsMap is
// updated.
size_t newExtensionsLen = extensionsLen + 1 + extraExtensionsLen + 1;
char *newExtensions = (char *)malloc(newExtensionsLen);
if (!newExtensions) {
return extensions;
}
if (extensionsLen) {
memcpy(newExtensions, extensions, extensionsLen);
// Add space separator if necessary
if (newExtensions[extensionsLen - 1] != ' ') {
newExtensions[extensionsLen++] = ' ';
}
}
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
memcpy(newExtensions + extensionsLen, extraExtension, extraExtensionLen);
extensionsLen += extraExtensionLen;
newExtensions[extensionsLen++] = ' ';
}
newExtensions[extensionsLen++] = '\0';
assert(extensionsLen <= newExtensionsLen);
extensionsMap[extensions] = newExtensions;
return newExtensions;
}
const GLubyte *
_glGetString_override(GLenum name)
{
const configuration *config = getConfig();
const GLubyte *result;
// Try getting the override string value first
result = getConfigString(config, name);
if (!result) {
// Ask the real GL library
result = _glGetString(name);
}
if (result) {
switch (name) {
case GL_EXTENSIONS:
result = (const GLubyte *)overrideExtensionsString((const char *)result);
break;
default:
break;
}
}
return result;
}
static void
getInteger(const configuration *config,
GLenum pname, GLint *params)
{
// Disable ARB_get_program_binary
switch (pname) {
case GL_NUM_PROGRAM_BINARY_FORMATS:
if (params) {
GLint numProgramBinaryFormats = 0;
_glGetIntegerv(pname, &numProgramBinaryFormats);
if (numProgramBinaryFormats > 0) {
os::log("apitrace: warning: hiding program binary formats (https://git.io/JOM0m)\n");
}
params[0] = 0;
}
return;
case GL_PROGRAM_BINARY_FORMATS:
// params might be NULL here, as we returned 0 for
// GL_NUM_PROGRAM_BINARY_FORMATS.
return;
}
if (params) {
*params = getConfigInteger(config, pname);
if (*params != 0) {
return;
}
}
// Ask the real GL library
_glGetIntegerv(pname, params);
}
/**
* TODO: To be thorough, we should override all glGet*v.
*/
void
_glGetIntegerv_override(GLenum pname, GLint *params)
{
const configuration *config = getConfig();
/*
* It's important to handle params==NULL correctly here, which can and does
* happen, particularly when pname is GL_COMPRESSED_TEXTURE_FORMATS or
* GL_PROGRAM_BINARY_FORMATS and the implementation returns 0 for
* GL_NUM_COMPRESSED_TEXTURE_FORMATS or GL_NUM_PROGRAM_BINARY_FORMATS, as
* the application ends up calling `params = malloc(0)` or `param = new
* GLint[0]` which can yield NULL.
*/
getInteger(config, pname, params);
if (params) {
const Context *ctx;
switch (pname) {
case GL_NUM_EXTENSIONS:
ctx = getContext();
if (ctx->profile.major >= 3) {
const ExtensionsDesc *desc = getExtraExtensions(ctx);
*params += desc->numStrings;
}
break;
case GL_MAX_LABEL_LENGTH:
/* We provide our default implementation of KHR_debug when the
* driver does not. So return something sensible here.
*/
if (params[0] == 0) {
params[0] = 256;
}
break;
case GL_MAX_DEBUG_MESSAGE_LENGTH:
if (params[0] == 0) {
params[0] = 4096;
}
break;
}
}
}
const GLubyte *
_glGetStringi_override(GLenum name, GLuint index)
{
const configuration *config = getConfig();
const Context *ctx = getContext();
const GLubyte *retVal;
if (ctx->profile.major >= 3) {
switch (name) {
case GL_EXTENSIONS:
{
const ExtensionsDesc *desc = getExtraExtensions(ctx);
GLint numExtensions = 0;
getInteger(config, GL_NUM_EXTENSIONS, &numExtensions);
if ((GLuint)numExtensions <= index && index < (GLuint)numExtensions + desc->numStrings) {
return (const GLubyte *)desc->strings[index - (GLuint)numExtensions];
}
}
break;
default:
break;
}
}
retVal = getConfigStringi(config, name, index);
if (retVal)
return retVal;
return _glGetStringi(name, index);
}
} /* namespace gltrace */
| 27.609524 | 105 | 0.634012 | moonlinux |
d5a94e747658932f35f740260bd43d6bb43d329c | 10,282 | cpp | C++ | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 61 | 2017-08-09T15:10:59.000Z | 2022-02-15T21:45:31.000Z | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 462 | 2017-07-31T21:26:46.000Z | 2022-03-30T22:53:50.000Z | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 73 | 2017-08-24T17:39:31.000Z | 2022-03-28T08:37:47.000Z | /**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "csp_solver_tou_block_schedules.h"
#include "csp_solver_util.h"
#include <algorithm>
void C_block_schedule::check_dimensions()
{
// Check that each schedule is a 12x24 matrix
// If not, throw exception
if (mc_weekdays.nrows() != mc_weekends.nrows()
|| mc_weekdays.nrows() != 12
|| mc_weekdays.ncols() != mc_weekends.ncols()
|| mc_weekdays.ncols() != 24 )
{
m_error_msg = "TOU schedules must have 12 rows and 24 columns";
throw C_csp_exception( m_error_msg, "TOU block schedule init" );
}
/*
if( mc_weekdays.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d rows.", (int)mc_weekdays.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekdays.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d columns.", (int)mc_weekdays.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d rows.",(int) mc_weekends.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d columns.", (int)mc_weekends.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
*/
return;
}
void C_block_schedule::size_vv(int n_arrays)
{
mvv_tou_arrays.resize(n_arrays, std::vector<double>(0, std::numeric_limits<double>::quiet_NaN()));
}
void C_block_schedule::check_arrays_for_tous(int n_arrays)
{
// Check that all TOU periods represented in the schedules are available in the tou arrays
int i_tou_min = 1;
int i_tou_max = 1;
int i_tou_day = -1;
int i_tou_end = -1;
int i_temp_max = -1;
int i_temp_min = -1;
for( int i = 0; i < 12; i++ )
{
for( int j = 0; j < 24; j++ )
{
i_tou_day = (int) mc_weekdays(i, j) - 1;
i_tou_end = (int) mc_weekends(i, j) - 1;
i_temp_max = std::max(i_tou_day, i_tou_end);
i_temp_min = std::min(i_tou_day, i_tou_end);
if( i_temp_max > i_tou_max )
i_tou_max = i_temp_max;
if( i_temp_min < i_tou_min )
i_tou_min = i_temp_min;
}
}
if( i_tou_min < 0 )
{
throw(C_csp_exception("Smallest TOU period cannot be less than 1", "TOU block schedule initialization"));
}
for( int k = 0; k < n_arrays; k++ )
{
if( i_tou_max + 1 > (int)mvv_tou_arrays[k].size() )
{
m_error_msg = util::format("TOU schedule contains TOU period = %d, while the %s array contains %d elements", (int)i_temp_max, mv_labels[k].c_str(), mvv_tou_arrays[k].size());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
}
void C_block_schedule::set_hr_tou(bool is_leapyear)
{
/*
This method sets the TOU schedule month by hour for an entire year, so only makes sense in the context of an annual simulation.
*/
if( m_hr_tou != 0 )
delete [] m_hr_tou;
int nhrann = 8760+(is_leapyear?24:0);
m_hr_tou = new double[nhrann];
int nday[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if( is_leapyear )
nday[1] ++;
int wday = 5, i = 0;
for( int m = 0; m<12; m++ )
{
for( int d = 0; d<nday[m]; d++ )
{
bool bWeekend = (wday <= 0);
if( wday >= 0 ) wday--;
else wday = 5;
for( int h = 0; h<24 && i<nhrann && m * 24 + h<288; h++ )
{
if( bWeekend )
m_hr_tou[i] = mc_weekends(m, h); // weekends[m * 24 + h];
else
m_hr_tou[i] = mc_weekdays(m, h); // weekdays[m * 24 + h];
i++;
}
}
}
}
void C_block_schedule::init(int n_arrays, bool is_leapyear)
{
check_dimensions();
check_arrays_for_tous(n_arrays);
set_hr_tou(is_leapyear);
}
C_block_schedule_csp_ops::C_block_schedule_csp_ops()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Turbine Fraction";
mv_is_diurnal = true;
}
C_block_schedule_pricing::C_block_schedule_pricing()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Price Multiplier";
mv_is_diurnal = true;
}
void C_csp_tou_block_schedules::init()
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch( C_csp_exception &csp_exception )
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
// time step initialization of actual price multipliers done in calling compute modules.
// mv_is_diurnal is set to true in constructor
if (ms_params.mc_pricing.mv_is_diurnal)
{
try
{
ms_params.mc_pricing.init(C_block_schedule_pricing::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception &csp_exception)
{
m_error_msg = "The CSP pricing " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
if (ms_params.mc_csp_ops.mv_is_diurnal)
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception& csp_exception)
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
return;
}
// TODO: move this into dispatch some how
void C_csp_tou_block_schedules::call(double time_s, C_csp_tou::S_csp_tou_outputs & tou_outputs)
{
int i_hour = (int)(ceil(time_s/3600.0 - 1.e-6) - 1);
if( i_hour > 8760 - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || i_hour<0 )
{
m_error_msg = util::format("The hour input to the TOU schedule must be from 1 to 8760. The input hour was %d.", i_hour+1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t csp_op_tou = (size_t)ms_params.mc_csp_ops.m_hr_tou[i_hour]; // an 8760-size array of the 1-9 turbine output fraction for the timestep
tou_outputs.m_csp_op_tou = (int)csp_op_tou; // needed for hybrid cooling regardless of turbine output fraction schedule type
if (ms_params.mc_csp_ops.mv_is_diurnal) {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.mvv_tou_arrays[C_block_schedule_csp_ops::TURB_FRAC][csp_op_tou-1]; // an array of size 9 of the different turbine output fractions
}
else {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.timestep_load_fractions.at(i_hour);
}
if (ms_params.mc_pricing.mv_is_diurnal)
{
int pricing_tou = (int)ms_params.mc_pricing.m_hr_tou[i_hour];
tou_outputs.m_pricing_tou = pricing_tou;
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][pricing_tou - 1];
}
else // note limited to hour but can be extended to timestep using size
{
// these can be set in initialize and we may want to include time series inputs for other multipliers and fractions
size_t nrecs = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].size();
if (nrecs <= 0)
{
m_error_msg = util::format("The timestep price multiplier array was empty.");
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t nrecs_per_hour = nrecs / 8760;
int ndx = (int)((ceil(time_s / 3600.0 - 1.e-6) - 1) * nrecs_per_hour);
if (ndx > (int)nrecs - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || ndx<0)
{
m_error_msg = util::format("The index input to the TOU schedule must be from 1 to %d. The input timestep index was %d.", (int)nrecs, ndx + 1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][ndx];
}
}
void C_csp_tou_block_schedules::setup_block_uniform_tod()
{
int nrows = ms_params.mc_csp_ops.mstatic_n_rows;
int ncols = ms_params.mc_csp_ops.mstatic_n_cols;
for( int i = 0; i < ms_params.mc_csp_ops.N_END; i++ )
ms_params.mc_csp_ops.mvv_tou_arrays[i].resize(2, 1.0);
for( int i = 0; i < ms_params.mc_pricing.N_END; i++ )
ms_params.mc_pricing.mvv_tou_arrays[i].resize(2, 1.0);
ms_params.mc_csp_ops.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_csp_ops.mc_weekends.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekends.resize_fill(nrows, ncols, 1.0);
}
| 34.619529 | 188 | 0.71844 | JordanMalan |
d5a9ae7c2b9029df289fdd0f8063e3db2eee9cd7 | 360 | hpp | C++ | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | 2 | 2021-02-12T13:05:02.000Z | 2021-02-22T14:25:00.000Z | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null |
#ifndef __TURBO_ENGINE_DEBUGIMGUI_HPP__
#define __TURBO_ENGINE_DEBUGIMGUI_HPP__
#ifdef __TURBO_USE_IMGUI__
#include <imgui/imgui.h>
#include <imgui/imgui_impl_allegro5.h>
#include "debug_menus/EngineDebug.hpp"
#include "debug_menus/SceneManagerDebug.hpp"
#define ONLYIMGUI(expr) expr;
#else
#define ONLYIMGUI(expr)
#endif
#endif
| 18 | 48 | 0.761111 | mariusvn |
d5b3721c4eac2e2bdb250f4de4c4da0c83f3ff3b | 520 | cpp | C++ | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | null | null | null | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | 7 | 2021-09-02T05:58:24.000Z | 2022-02-27T07:06:43.000Z | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | 2 | 2020-02-06T02:05:15.000Z | 2021-11-25T11:35:14.000Z | #include "../../../platform_graphics.hpp"
#include "../../gl_headers.hpp"
#include "core/util.h"
void initGraphics() {
// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
// glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
}
void initGraphicsExtensions() {
// start GLEW extension handler
// glewExperimental = GL_TRUE;
//
if ( glewInit() != GLEW_OK ) {
LOGE( "Failed to initialize GLEW" );
}
} | 26 | 65 | 0.734615 | 49View |
d5b546d2d04fed03d0c5ab9d67fdeffe41ffb07f | 3,279 | cpp | C++ | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | 1 | 2019-02-12T16:00:45.000Z | 2019-02-12T16:00:45.000Z | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | null | null | null | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | null | null | null |
#include <rendercore-examples/GltfExampleRenderer.h>
#include <cppassist/memory/make_unique.h>
#include <glbinding/gl/gl.h>
#include <rendercore/rendercore.h>
#include <rendercore-gltf/GltfConverter.h>
#include <rendercore-gltf/GltfLoader.h>
#include <rendercore-gltf/Asset.h>
using namespace rendercore::opengl;
using namespace rendercore::gltf;
namespace rendercore
{
namespace examples
{
GltfExampleRenderer::GltfExampleRenderer(GpuContainer * container)
: Renderer(container)
, m_counter(0)
, m_angle(0.0f)
{
// Initialize object transformation
m_transform.setTranslation({ 0.0f, 0.0f, 0.0f });
m_transform.setScale ({ 1.0f, 1.0f, 1.0f });
m_transform.setRotation (glm::angleAxis(0.0f, glm::vec3(0.0f, 1.0f, 0.0f)));
// Create camera
m_camera = cppassist::make_unique<Camera>();
// Load GLTF asset
GltfLoader loader;
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoxAnimated/BoxAnimated.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/TextureCoordinateTest/TextureCoordinateTest.gltf");
auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoomBox/BoomBox.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/PbrTest/PbrTest.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/Taxi/Taxi.gltf");
// Transfer data from GLTF
GltfConverter converter;
converter.convert(*asset.get());
auto & textures = converter.textures();
for (auto & texture : textures) {
texture->setContainer(this);
m_textures.push_back(std::move(texture));
}
auto & materials = converter.materials();
for (auto & material : materials) {
material->setContainer(this);
m_materials.push_back(std::move(material));
}
auto & meshes = converter.meshes();
for (auto & mesh : meshes) {
mesh->setContainer(this);
m_meshes.push_back(std::move(mesh));
}
auto & scenes = converter.scenes();
for (auto & scene : scenes) {
m_scenes.push_back(std::move(scene));
}
// Create mesh renderer
m_sceneRenderer = cppassist::make_unique<SceneRenderer>(this);
}
GltfExampleRenderer::~GltfExampleRenderer()
{
}
void GltfExampleRenderer::onUpdate()
{
// Advance counter
m_counter++;
// Rotate model
m_angle += m_timeDelta * 1.0f;
m_transform.setRotation(glm::angleAxis(m_angle, glm::vec3(0.0f, 1.0f, 0.0f)));
// Animation has been updated, redraw the scene (will also issue another update)
scheduleRedraw();
}
void GltfExampleRenderer::onRender()
{
// Update viewport
gl::glViewport(m_viewport.x, m_viewport.y, m_viewport.z, m_viewport.w);
// Clear screen
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
// Update camera
m_camera->lookAt(glm::vec3(0.0f, 0.0, 9.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
m_camera->perspective(glm::radians(40.0f), glm::ivec2(m_viewport.z, m_viewport.w), 0.1f, 64.0f);
// Render scenes
for (auto & scene : m_scenes) {
m_sceneRenderer->render(*scene.get(), m_transform.transform(), m_camera.get());
}
}
} // namespace examples
} // namespace rendercore
| 28.513043 | 126 | 0.676426 | sbusch42 |
d5b8088798fa7de545854f74e24636c75d645472 | 3,536 | cpp | C++ | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <BlynkSimpleSerialBLE.h>
#include "LOT_adc.h"
#include "LOT_ntc103f397.h"
#define SYSTEM_STATE_VIRTUAL_PIN V0
#define FORCED_FAN_ON_OFF_VIRTUAL_PIN V1
#define NTC103F397_VIRTUAL_PIN V2
#define THRESHOLD_TEMPERATURE_VIRTUAL_PIN V3
#define MOTION_STATE_VIRTUAL_PIN V4
#define MAX_PUSH_TIME_MS 500
#define PARALLEL_RESISTOR 9.85f
#define THRESHOLD_TEMPERATURE_SAFETY_ZONE 0.3f
// AT+BAUD6
// AT+NAMEevaporative
// AT+PIN0000
#define HC_O6_BAUDRATE 38400
char auth[] = "3993b1f88d9e4607b04007cd3ebe8876";
BlynkTimer timer;
volatile uint32_t pushtime = 0;
volatile uint8_t system_state = 0;
uint8_t forced_fan_on_off = 0;
float temperature;
float threshold_temperature = 25.0f;
volatile uint8_t motion_state = 0;
volatile uint32_t motion_capture_time = 0;
void fast_timer( void );
void slow_timer( void );
// app -> nano
BLYNK_WRITE( SYSTEM_STATE_VIRTUAL_PIN )
{
system_state = param.asInt();
}
BLYNK_WRITE( FORCED_FAN_ON_OFF_VIRTUAL_PIN )
{
forced_fan_on_off = param.asInt();
}
BLYNK_WRITE( THRESHOLD_TEMPERATURE_VIRTUAL_PIN )
{
threshold_temperature = param.asFloat();
}
void setup()
{
Serial.begin( HC_O6_BAUDRATE );
Blynk.config( Serial, auth );
// Blynk.begin(Serial, auth);
DDRB |= _BV( DDB5 );
MCUCR &= ~_BV( PUD ); // PULL-UP activate
DDRD &= ~_BV( DDD2 ); // INPUT
PORTD |= _BV( PD2 ); // PULL-UP
EIMSK |= _BV( INT0 ); // interrupt enable
EICRA |= _BV( ISC00 ); // any logical change
LOT_adc_setup();
DDRD &= ~_BV( DDD3 ); // INPUT
PORTD |= _BV( PD3 ); // PULL-UP
EIMSK |= _BV( INT1 ); // interrupt enable
EICRA |= _BV( ISC10 ); // any logical change
DDRD |= _BV( DDD5 ) | _BV( DDD4 ); // OUTPUT
timer.setInterval( 450, fast_timer );
timer.setInterval( 2050, slow_timer );
}
void loop()
{
Blynk.run();
timer.run();
if ( system_state )
{
PORTD |= _BV( PD4 );
if ( forced_fan_on_off )
{
PORTD |= _BV( PD5 );
}
else
{
if ( motion_state && ( temperature > threshold_temperature ) )
{
PORTD |= _BV( PD5 );
}
else if ( ( motion_state && ( temperature < threshold_temperature - THRESHOLD_TEMPERATURE_SAFETY_ZONE ) )
|| ( !motion_state ) )
{
PORTD &= ~_BV( PD5 );
}
}
}
else
{
PORTD &= ~( _BV( PD5 ) | _BV( PD4 ) );
}
float thermistor_R = LOT_adc_read( 0 );
thermistor_R = ( PARALLEL_RESISTOR * thermistor_R ) / ( 1024.0 - thermistor_R );
temperature = LOT_ntc_temperature( thermistor_R );
}
void fast_timer( void )
{
Blynk.virtualWrite( SYSTEM_STATE_VIRTUAL_PIN, system_state );
Blynk.virtualWrite( FORCED_FAN_ON_OFF_VIRTUAL_PIN, forced_fan_on_off );
Blynk.virtualWrite( NTC103F397_VIRTUAL_PIN, temperature );
Blynk.virtualWrite( MOTION_STATE_VIRTUAL_PIN, motion_state );
}
void slow_timer( void )
{
Blynk.virtualWrite( THRESHOLD_TEMPERATURE_VIRTUAL_PIN, threshold_temperature );
}
ISR( INT0_vect )
{
if ( PIND & _BV( PIND2 ) )
{
pushtime = millis();
}
else
{
if ( millis() - pushtime > MAX_PUSH_TIME_MS )
{
system_state ^= 1;
}
}
}
ISR( INT1_vect )
{
if ( PIND & _BV( PIND3 ) )
{
motion_state = 1;
}
else
{
motion_state = 0;
}
} | 23.417219 | 117 | 0.606335 | hhk7734 |
d5bdc08023633e1ad70c97907b5e60dfe585edb3 | 18,848 | cpp | C++ | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rlaed4.cpp,v 1.7 2010/08/07 04:48:32 nakatamaho Exp $
*
* 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 AUTHOR 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 AUTHOR 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.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
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 listed
in this license 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.
*/
#include <mblas.h>
#include <mlapack.h>
#define MTRUE 0
#define MFALSE 1
void Rlaed4(INTEGER n, INTEGER i, REAL * d, REAL * z, REAL * delta, REAL rho, REAL * dlam, INTEGER * info)
{
REAL a, b, c;
INTEGER j;
REAL w;
INTEGER ii;
REAL dw, zz[3];
INTEGER ip1;
REAL del, eta, phi, eps, tau, psi;
INTEGER iim1, iip1;
REAL dphi, dpsi;
INTEGER iter;
REAL temp, prew, temp1, dltlb, dltub, midpt;
INTEGER niter;
INTEGER swtch, swtch3;
INTEGER orgati;
REAL erretm, rhoinv;
REAL Two = 2.0, Three = 3.0, Four = 4.0, One = 1.0, Zero = 0.0, Eight = 8.0, Ten = 10.0;
//Since this routine is called in an inner loop, we do no argument
//checking.
//Quick return for N=1 and 2
*info = 0;
if (n == 1) {
//Presumably, I=1 upon entry
*dlam = d[1] + rho * z[1] * z[1];
delta[1] = One;
return;
}
if (n == 2) {
Rlaed5(i, &d[0], &z[1], &delta[1], rho, dlam);
return;
}
//Compute machine epsilon
eps = Rlamch("Epsilon");
rhoinv = One / rho;
//The case I = N
if (i == n) {
//Initialize some basic variables
ii = n - 1;
niter = 1;
//Calculate initial guess
midpt = rho / Two;
//If ||Z||_2 is not one, then TEMP should be set to
//RHO * ||Z||_2^2 / TWO
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < n - 2; j++) {
psi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi;
w = c + z[ii] * z[ii] / delta[ii] + z[n] * z[n] / delta[n];
if (w <= Zero) {
temp = z[n - 1] * z[n - 1] / (d[n] - d[n - 1] + rho)
+ z[n] * z[n] / rho;
if (c <= temp) {
tau = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
}
//It can be proved that
//D(N)+RHO/2 <= LAMBDA(N) < D(N)+TAU <= D(N)+RHO
dltlb = midpt;
dltub = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
//It can be proved that
//D(N) < D(N)+TAU < LAMBDA(N) < D(N)+RHO/2
dltlb = Zero;
dltub = midpt;
}
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (c < Zero) {
c = abs(c);
}
if (c == Zero) {
//ETA = B/A
//ETA = RHO - TAU
eta = dltub - tau;
} else if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt((abs(a * a - b * Four * c))));
}
//Note, eta should be positive if w is negative, and
//eta should be negative otherwise. However,
//for some reason caused by roundoff, eta*w > 0,
//we simply use one Newton step instead. This way
//will guarantee eta*w < Zero
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt(abs(a * a - b * Four * c)));
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
*dlam = d[i] + tau;
goto L250;
//End for the case I = N
} else {
//The case for I < N
niter = 1;
ip1 = i + 1;
//Calculate initial guess
del = d[ip1] - d[i];
midpt = del / Two;
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < i - 1; j++) {
psi += z[j] * z[j] / delta[j];
}
phi = Zero;
for (j = n; j >= i + 2; j--) {
phi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi + phi;
w = c + z[i] * z[i] / delta[i] + z[ip1] * z[ip1] / delta[ip1];
if (w > Zero) {
//d(i)< the ith eigenvalue < (d(i)+d(i+1))/2
//We choose d(i) as origin.
orgati = MTRUE;
a = c * del + z[i] * z[i] + z[ip1] * z[ip1];
b = z[i] * z[i] * del;
if (a > Zero) {
tau = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
} else {
tau = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
}
dltlb = Zero;
dltub = midpt;
} else {
//(d(i)+d(i+1))/2 <= the ith eigenvalue < d(i+1)
//We choose d(i+1) as origin.
orgati = MFALSE;
a = c * del - z[i] * z[i] - z[ip1] * z[ip1];
b = z[ip1] * z[ip1] * del;
if (a < Zero) {
tau = b * Two / (a - sqrt(abs(a * a + b * Four * c)));
} else {
tau = -(a + sqrt(abs(a * a + b * Four * c))) / (c * Two);
}
dltlb = -midpt;
dltub = Zero;
}
if (orgati) {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
} else {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[ip1] - tau;
}
}
if (orgati) {
ii = i;
} else {
ii = i + 1;
}
iim1 = ii - 1;
iip1 = ii + 1;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
w = rhoinv + phi + psi;
//W is the value of the secular function with
//its ii-th element removed.
swtch3 = MFALSE;
if (orgati) {
if (w < Zero) {
swtch3 = MTRUE;
}
} else {
if (w > Zero) {
swtch3 = MTRUE;
}
}
if (ii == 1 || ii == n) {
swtch3 = MFALSE;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w += temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
if (!swtch3) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * (z[i] / delta[i] * z[i] / delta[i]);
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * (z[ip1] / delta[ip1] * z[ip1] / delta[ip1]);
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1] * dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
/* Interpolation using THREE most relevant poles */
temp = rhoinv + psi + phi;
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1] - d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1] - d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
zz[1] = z[ii] * z[ii];
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
prew = w;
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau + eta) * dw;
swtch = MFALSE;
if (orgati) {
if (-w > abs(prew) / Ten) {
swtch = MTRUE;
}
} else {
if (w > abs(prew) / Ten) {
swtch = MTRUE;
}
}
tau += eta;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
if (!swtch3) {
if (!swtch) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * ((z[i] / delta[i]) * (z[i] / delta[i]));
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * ((z[ip1] / delta[ip1]) * (z[ip1] / delta[ip1]));
}
} else {
temp = z[ii] / delta[ii];
if (orgati) {
dpsi += temp * temp;
} else {
dphi += temp * temp;
}
c = w - delta[i] * dpsi - delta[ip1] * dphi;
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1]
* dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (!swtch) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
} else {
a = delta[i] * delta[i] * dpsi + delta[ip1]
* delta[ip1] * dphi;
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
//Interpolation using THREE most relevant poles
temp = rhoinv + psi + phi;
if (swtch) {
c = temp - delta[iim1] * dpsi - delta[iip1] * dphi;
zz[0] = delta[iim1] * delta[iim1] * dpsi;
zz[2] = delta[iip1] * delta[iip1] * dphi;
} else {
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1]
- d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1]
- d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
}
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
prew = w;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
if (w * prew > Zero && abs(w) > abs(prew) / Ten) {
swtch = !swtch;
}
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
}
L250:
return;
}
| 26.887304 | 106 | 0.524194 | JaegerP |
d5c082e3fe50e130b11d22dbe777878e19d46a82 | 2,098 | cpp | C++ | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null |
// MadronaLib: a C++ framework for DSP applications.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#include "MLReporter.h"
// --------------------------------------------------------------------------------
#pragma mark param viewing
MLPropertyView::MLPropertyView(MLWidget* w, MLSymbol a) :
mpWidget(w),
mAttr(a)
{
}
MLPropertyView::~MLPropertyView()
{
}
void MLPropertyView::view(const MLProperty& p) const
{
mpWidget->setPropertyImmediate(mAttr, p);
/*
// with Widget properties we can remove switch! TODO
switch(p.getType())
{
case MLProperty::kUndefinedProperty:
break;
case MLProperty::kFloatProperty:
mpWidget->setAttribute(mAttr, p.getFloatValue());
break;
case MLProperty::kStringProperty:
mpWidget->setStringAttribute(mAttr, *p.getStringValue());
break;
case MLProperty::kSignalProperty:
mpWidget->setSignalAttribute(mAttr, *p.getSignalValue());
break;
}
*/
}
// --------------------------------------------------------------------------------
#pragma mark MLReporter
MLReporter::MLReporter(MLPropertySet* m) :
MLPropertyListener(m)
{
}
MLReporter::~MLReporter()
{
}
// ----------------------------------------------------------------
// parameter viewing
// add a parameter view.
// when param p changes, attribute attr of Widget w will be set to the param's value.
//
void MLReporter::addPropertyViewToMap(MLSymbol p, MLWidget* w, MLSymbol attr)
{
mPropertyViewsMap[p].push_back(MLPropertyViewPtr(new MLPropertyView(w, attr)));
}
void MLReporter::doPropertyChangeAction(MLSymbol prop, const MLProperty& newVal)
{
// do we have viewers for this parameter?
MLPropertyViewListMap::iterator look = mPropertyViewsMap.find(prop);
if (look != mPropertyViewsMap.end())
{
// run viewers
MLPropertyViewList viewers = look->second;
for(MLPropertyViewList::iterator vit = viewers.begin(); vit != viewers.end(); vit++)
{
MLPropertyViewPtr pv = (*vit);
const MLPropertyView& v = (*pv);
v.view(newVal);
}
}
}
| 24.114943 | 86 | 0.638227 | afofo |
d5c25e539cbb9f6f38b23b843fb68da4f6c5dfe7 | 68,739 | cpp | C++ | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Louis Hobson <[email protected]>. All Rights Reserved.
*
* Distributed under MIT licence as a part of the Chess C++ library.
* For details, see: https://github.com/louishobson/Chess/blob/master/LICENSE
*
* src/chess/chessboard_eval.cpp
*
* Implementation of evaluation methods in include/chess/chessboard.h
*
*/
/* INCLUDES */
#include <louischessx/chessboard.h>
/* BOARD EVALUATION */
/** @name get_check_info
*
* @brief Get information about the check state of a color's king
* @param pc: The color who's king we will look at
* @return check_info_t
*/
chess::chessboard::check_info_t chess::chessboard::get_check_info ( pcolor pc ) const chess_validate_throw
{
/* SETUP */
/* The output check info */
check_info_t check_info;
/* Get the other color */
const pcolor npc = other_color ( pc );
/* Get the friendly and opposing pieces */
const bitboard friendly = bb ( pc );
const bitboard opposing = bb ( npc );
/* Get the king and position of the colored king */
const bitboard king = bb ( pc, ptype::king );
const int king_pos = king.trailing_zeros ();
/* Get the positions of the opposing straight and diagonal pieces */
const bitboard op_straight = bb ( npc, ptype::queen ) | bb ( npc, ptype::rook );
const bitboard op_diagonal = bb ( npc, ptype::queen ) | bb ( npc, ptype::bishop );
/* Get the primary propagator.
* Primary propagator of not opposing means that spans will overlook friendly pieces.
* The secondary propagator will be universe.
*/
const bitboard pp = ~opposing;
const bitboard sp = ~bitboard {};
/* KING, KNIGHTS AND PAWNS */
/* Throw if kings are adjacent (this should never occur) */
#if CHESS_VALIDATE
if ( bitboard::king_attack_lookup ( king_pos ) & bb ( npc, ptype::king ) ) throw std::runtime_error { "Adjacent king found in check_info ()." };
#endif
/* Add checking knights */
check_info.check_vectors |= bitboard::knight_attack_lookup ( king_pos ) & bb ( npc, ptype::knight );
/* Switch depending on pc and add checking pawns */
if ( pc == pcolor::white )
check_info.check_vectors |= king.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn );
else
check_info.check_vectors |= king.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn );
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( king_pos ) & op_straight )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_straight )
{
/* Span the king in the current direction */
const bitboard king_span = king.rook_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_straight;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* Iterate through the diagonal compass to see if those sliding pieces could be attacking */
if ( bitboard::diagonal_attack_lookup ( king_pos ) & op_diagonal )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_diagonal )
{
/* Span the king in the current direction */
const bitboard king_span = king.bishop_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_diagonal;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* SET REMAINING VARIABLES AND RETURN */
/* Get the check count */
check_info.check_count = ( check_info.check_vectors & bb ( npc ) ).popcount ();
/* Set the check vectors along straight and diagonal paths */
check_info.straight_check_vectors = check_info.check_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_check_vectors = check_info.check_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set the pin vectors along straight and diagonal paths */
check_info.straight_pin_vectors = check_info.pin_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_pin_vectors = check_info.pin_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set check_vectors_dep_check_count */
check_info.check_vectors_dep_check_count = check_info.check_vectors.all_if ( check_info.check_count == 0 ).only_if ( check_info.check_count < 2 );
/* Return the info */
return check_info;
}
/** @name is_protected
*
* @brief Returns true if the board position is protected by the player specified.
* There is no restriction on what piece is at the position, since any piece in the position is ignored.
* @param pc: The color who is defending.
* @param pos: The position of the cell to check the defence of.
* @return boolean
*/
bool chess::chessboard::is_protected ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces */
const bitboard fr_straight = bb ( pc, ptype::queen ) | bb ( pc, ptype::rook );
const bitboard fr_diagonal = bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop );
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* KING, KNIGHTS AND PAWNS */
/* Look for an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) ) return true;
/* Look for defending knights */
if ( bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight ) ) return true;
/* Switch depending on pc and look for defending pawns */
if ( pc == pcolor::white )
{ if ( pos_bb.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn ) ) return true; }
else
{ if ( pos_bb.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn ) ) return true; }
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be defending */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
if ( pos_bb.rook_attack ( dir, pp, sp ) & fr_straight ) return true;
}
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
if ( pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal ) return true;
}
/* Return false */
return false;
}
/** @name get_least_valuable_attacker
*
* @brief Takes a color and position and finds the least valuable piece attacking that color.
* @param pc: The color attacking.
* @param pos: The position being attacked.
* @return A pair of ptype and position, no_piece and -1 if no attacker is found.
*/
std::pair<chess::ptype, int> chess::chessboard::get_least_valuable_attacker ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get the check info */
const check_info_t check_info = get_check_info ( pc );
/* If pos is not part of check_vectors_dep_check_count, then no move will leave the king not in check, so no move is possible */
if ( !check_info.check_vectors_dep_check_count.test ( pos ) ) return { ptype::no_piece, 0 };
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces. Disregard straight pieces on diagonal pin vectors and vice versa. */
const bitboard fr_straight = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::rook ) ) & ~check_info.diagonal_pin_vectors;
const bitboard fr_diagonal = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop ) ) & ~check_info.straight_pin_vectors;
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* PAWNS */
{
/* Switch depending on pc and look for attacking pawns */
bitboard attackers = ( pc == pcolor::white ? pos_bb.pawn_any_attack_s () : pos_bb.pawn_any_attack_n () ) & bb ( pc, ptype::pawn );
/* Remove pawns on straight pin vectors */
attackers &= ~check_info.straight_pin_vectors;
/* Remove the pawns on diagonal pin vectors, if they move off of their pin vector */
attackers &= ~( attackers & check_info.diagonal_pin_vectors ).only_if_not ( check_info.diagonal_pin_vectors.test ( pos ) );
/* If there are any pawns left, return one of them */
if ( attackers ) return { ptype::pawn, attackers.trailing_zeros () };
}
/* KNIGHTS */
{
/* Get the attacking knights */
bitboard attackers = bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight );
/* Remove those which are on pin vectors */
attackers &= ~check_info.pin_vectors;
/* If there are any knights left, return one of them */
if ( attackers ) return { ptype::knight, attackers.trailing_zeros () };
}
/* SLIDING PIECES */
/* If an attacking queen is found, the rest of the directions must be checked for lower value pieces.
* Hence keep a variable storing the position of a queen, if found.
*/
int attacking_queen_pos = -1;
/* Iterate through diagonal sliding pieces first, since this way finding a bishop or rook can cause immediate return */
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
{
/* Get the attacker */
bitboard attacker = pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.diagonal_pin_vectors ) && !check_info.diagonal_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a bishop, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::bishop ).test ( attacker_pos ) ) return { ptype::bishop, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
{
/* Get the attackers */
bitboard attacker = pos_bb.rook_attack ( dir, pp, sp ) & fr_straight;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.straight_pin_vectors ) && !check_info.straight_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a rook, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::rook ).test ( attacker_pos ) ) return { ptype::rook, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* If an attacking queen was found, return that */
if ( attacking_queen_pos != -1 ) return { ptype::queen, attacking_queen_pos };
/* KING */
/* Get if there is an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) )
{
/* If pos is not protected by the other color, return the king as attacking */
if ( !is_protected ( other_color ( pc ), pos ) ) return { ptype::king, bb ( pc, ptype::king ).trailing_zeros () };
}
/* NO PIECE */
/* Return no_piece */
return { ptype::no_piece, -1 };
}
/** @name static_exchange_evaluation
*
* @brief Takes a color and position, and returns the possible material gain from the color attacking that position.
* @param pc: The color attacking.
* @param attacked_pos: The position being attacked.
* @param attacked_pt: The piece type to assume that's occupying pos. If no_piece, will be calculated.
* @param attacker_pos: The position of the first piece to attack attacked_pos.
* @param attacker_pt: The piece type that's first attacking attacked_pos. If no_piece, will be set to the least valuable attacker.
* @param prev_gain: A the gain from previous calls. Used internally, should be 0 initially.
* @return An integer, 0 meaning no matierial gain, +/- meaning material gain or loss respectively.
*/
int chess::chessboard::static_exchange_evaluation ( pcolor pc, int attacked_pos, ptype attacked_pt, int attacker_pos, ptype attacker_pt, int prev_gain ) chess_validate_throw
{
/* Create an array of material values for each ptype */
constexpr std::array<int, 7> material_values { 100, 400, 400, 600, 1100, 10000, 0 };
/* Get the attacked type, if required. Return prev_gain if there is no attacked piece. */
if ( attacked_pt == ptype::no_piece ) attacked_pt = find_type ( other_color ( pc ), attacked_pos );
if ( attacked_pt == ptype::no_piece ) return prev_gain;
/* Get the speculative gain */
const int spec_gain = prev_gain + material_values [ cast_penum ( attacked_pt ) ];
/* Possibly cutoff */
if ( std::max ( prev_gain, spec_gain ) < 0 ) return prev_gain;
/* Get the least value piece of this color attacking pos.
* If attacker_pos is set, then find the piece type at that position. Otherwise chose the least valuable attacker.
* Return prev_gain if there is no such piece.
*/
if ( attacker_pt == ptype::no_piece ) if ( attacked_pos != -1 ) attacker_pt = find_type ( pc, attacker_pos ); else
std::tie ( attacker_pt, attacker_pos ) = get_least_valuable_attacker ( pc, attacked_pos );
if ( attacker_pt == ptype::no_piece ) return prev_gain;
/* Make the capture */
get_bb ( pc ).reset ( attacker_pos );
get_bb ( pc, attacker_pt ).reset ( attacker_pos );
get_bb ( pc ).set ( attacked_pos );
get_bb ( pc, attacker_pt ).set ( attacked_pos );
get_bb ( other_color ( pc ) ).reset ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).reset ( attacked_pos );
/* Get the gain from see */
const int gain = std::max ( prev_gain, -static_exchange_evaluation ( other_color ( pc ), attacked_pos, attacker_pt, -1, ptype::no_piece, -spec_gain ) );
/* Unmake the capture */
get_bb ( other_color ( pc ) ).set ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).set ( attacked_pos );
get_bb ( pc ).reset ( attacked_pos );
get_bb ( pc, attacker_pt ).reset ( attacked_pos );
get_bb ( pc ).set ( attacker_pos );
get_bb ( pc, attacker_pt ).set ( attacker_pos );
/* Return the gain */
return gain;
}
/** @name evaluate
*
* @brief Symmetrically evaluate the board state.
* Note that although is non-const, a call to this function will leave the board unmodified.
* @param pc: The color who's move it is next
* @return Integer value, positive for pc, negative for not pc
*/
int chess::chessboard::evaluate ( pcolor pc )
{
/* TERMINOLOGY */
/* Here, a piece refers to any chessman, including pawns and kings.
* Restricted pieces, or restrictives, do not include pawns or kings.
*
* It's important to note the difference between general attacks and legal attacks.
*
* An attack is any position a piece could end up in and potentially capture, regardless of if A) it leaves the king in check, or B) if a friendly piece is in the attack set.
* Legal attacks must be currently possible moves, including A) not leaving the king in check, and B) not attacking friendly pieces, and C) pawns not attacking empty cells.
* Note that a pawn push is not an attack, since a pawn cannot capture by pushing.
*
* A capture is a legal attack on an enemy piece.
* A restricted capture is a legal attack on a restricted enemy piece.
*
* Mobility is the number of distinct strictly legal moves. If a mobility is zero, that means that color is in checkmate.
*/
/* CONSTANTS */
/* Masks */
constexpr bitboard white_center { 0x0000181818000000 }, black_center { 0x0000001818180000 };
constexpr bitboard white_bishop_initial_cells { 0x0000000000000024 }, black_bishop_initial_cells { 0x2400000000000000 };
constexpr bitboard white_knight_initial_cells { 0x0000000000000042 }, black_knight_initial_cells { 0x4200000000000000 };
/* Material values */
constexpr int QUEEN { 1100 }; // 19
constexpr int ROOK { 600 }; // 10
constexpr int BISHOP { 400 }; // 7
constexpr int KNIGHT { 400 }; // 7
constexpr int PAWN { 100 }; // 2
/* Pawns */
constexpr int PAWN_GENERAL_ATTACKS { 1 }; // For every generally attacked cell
constexpr int CENTER_PAWNS { 20 }; // For every pawn
constexpr int PAWN_CENTER_GENERAL_ATTACKS { 10 }; // For every generally attacked cell (in the center)
constexpr int ISOLATED_PAWNS { -10 }; // For every pawn
constexpr int ISOLATED_PAWNS_ON_SEMIOPEN_FILES { -10 }; // For every pawn
constexpr int DOUBLED_PAWNS { -5 }; // Tripled pawns counts as -10 etc.
constexpr int PAWN_GENERAL_ATTACKS_ADJ_OP_KING { 20 }; // For every generally attacked cell
constexpr int PHALANGA { 20 }; // Tripple pawn counts as 40 etc.
constexpr int BLOCKED_PASSED_PAWNS { -15 }; // For each blocked passed pawn
constexpr int STRONG_SQUARES { 20 }; // For each strong square (one attacked by a friendly pawn and not an enemy pawn)
constexpr int BACKWARD_PAWNS { 10 }; // For each pawn behind a strong square (see above)
constexpr int PASSED_PAWNS_DISTANCE { 5 }; // For each passed pawn, for every square away from the 1st rank (since may be queened)
constexpr int LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES { 5 }; // For each attack
/* Sliding pieces */
constexpr int STRAIGHT_PIECES_ON_7TH_RANK { 30 }; // For each piece
constexpr int DOUBLE_BISHOP { 20 }; // If true
constexpr int STRAIGHT_PIECES_ON_OPEN_FILE { 35 }; // For each piece
constexpr int STRAIGHT_PIECES_ON_SEMIOPEN_FILE { 25 }; // For each piece
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES { 10 }; // For every legal attack
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES { 5 }; // For every legal attack
constexpr int STRAIGHT_PIECES_BEHIND_PASSED_PAWNS { 20 }; // For every piece
constexpr int DIAGONAL_PIECE_RESTRICTED_CAPTURES { 15 }; // For every restricted capture on enemy pieces (not including pawns or kings)
constexpr int RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES { 15 }; // For every restrictive, white and black (pieces not including pawns or kings)
/* Knights */
constexpr int CENTER_KNIGHTS { 20 }; // For every knight
/* Bishops and knights */
constexpr int BISHOP_OR_KNIGHT_INITIAL_CELL { -15 }; // For every bishop/knight
constexpr int DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES { 10 }; // For every capture
constexpr int BISHOP_OR_KNIGHT_ON_STRONG_SQUARE { 20 }; // For each piece
/* Mobility and king queen mobility, for every move */
constexpr int MOBILITY { 1 }; // For every legal move
constexpr int KING_QUEEN_MOBILITY { -2 }; // For every non-capture attack, pretending the king is a queen
/* Castling */
constexpr int CASTLE_MADE { 30 }; // If true
constexpr int CASTLE_LOST { -60 }; // If true
/* Other values */
constexpr int KNIGHT_AND_QUEEN_EXIST { 10 }; // If true
constexpr int CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES { 10 }; // For every attack (not including pawns or kings)
constexpr int PINNED_PIECES { -20 }; // For each (friendly) piece
/* Non-symmetrical values */
constexpr int CHECKMATE { 10000 }; // If on the enemy, -10000 if on self
constexpr int KINGS_IN_OPPOSITION { 15 }; // If the kings are one off adjacent
/* SETUP */
/* Get the check info */
const check_info_t white_check_info = get_check_info ( pcolor::white );
const check_info_t black_check_info = get_check_info ( pcolor::black );
/* Get king positions */
const int white_king_pos = bb ( pcolor::white, ptype::king ).trailing_zeros ();
const int black_king_pos = bb ( pcolor::black, ptype::king ).trailing_zeros ();
/* Get the king spans */
const bitboard white_king_span = bitboard::king_attack_lookup ( white_king_pos );
const bitboard black_king_span = bitboard::king_attack_lookup ( black_king_pos );
/* Set legalize_attacks. This is the intersection of not friendly pieces, not the enemy king, and check_vectors_dep_check_count. */
const bitboard white_legalize_attacks = ~bb ( pcolor::white ) & ~bb ( pcolor::black, ptype::king ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_legalize_attacks = ~bb ( pcolor::black ) & ~bb ( pcolor::white, ptype::king ) & black_check_info.check_vectors_dep_check_count;
/* Get the restrictives */
const bitboard white_restrictives = bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::knight );
const bitboard black_restrictives = bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::knight );
const bitboard restrictives = white_restrictives | black_restrictives;
/* Set the primary propagator such that all empty cells are set */
const bitboard pp = ~bb ();
/* Get the white pawn rear span */
const bitboard white_pawn_rear_span = bb ( pcolor::white, ptype::pawn ).span ( compass::s );
const bitboard black_pawn_rear_span = bb ( pcolor::black, ptype::pawn ).span ( compass::n );
/* Get the pawn file fills (from the rear span and forwards fill) */
const bitboard white_pawn_file_fill = white_pawn_rear_span | bb ( pcolor::white, ptype::pawn ).fill ( compass::n );
const bitboard black_pawn_file_fill = black_pawn_rear_span | bb ( pcolor::black, ptype::pawn ).fill ( compass::s );
/* Get the open and semiopen files. White semiopen files contain no white pawns. */
const bitboard open_files = ~( white_pawn_file_fill | black_pawn_file_fill );
const bitboard white_semiopen_files = ~white_pawn_file_fill & black_pawn_file_fill;
const bitboard black_semiopen_files = ~black_pawn_file_fill & white_pawn_file_fill;
/* Get the passed pawns */
const bitboard white_passed_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_pawn_rear_span & black_semiopen_files & black_semiopen_files.shift ( compass::e ) & black_semiopen_files.shift ( compass::w );
const bitboard black_passed_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_pawn_rear_span & white_semiopen_files & white_semiopen_files.shift ( compass::e ) & white_semiopen_files.shift ( compass::w );
/* Get the cells behind passed pawns.
* This is the span between the passed pawns and the next piece back, including the next piece back but not the pawn.
*/
const bitboard white_behind_passed_pawns = white_passed_pawns.span ( compass::s, pp, ~bitboard {} );
const bitboard black_behind_passed_pawns = black_passed_pawns.span ( compass::n, pp, ~bitboard {} );
/* Get the cells in front of passed pawns.
* This is the span between the passed pawns and the opposite end of the board, not including the pawn.
*/
const bitboard white_passed_pawn_trajectories = white_passed_pawns.span ( compass::n );
const bitboard black_passed_pawn_trajectories = black_passed_pawns.span ( compass::s );
/* ACCUMULATORS */
/* The value of the evaluation function */
int value = 0;
/* Mobilities */
int white_mobility = 0, black_mobility = 0;
/* Partial defence unions. Gives cells which are protected by friendly pieces.
* This is found from the union of all general attacks and can be used to determine opposing king's possible moves.
* However, pinned sliding pieces' general attacks are not included in this union (due to complexity to calculate), hence 'partial'.
*/
bitboard white_partial_defence_union, black_partial_defence_union;
/* Accumulate the difference between white and black's straight piece legal attacks on open and semiopen files */
int straight_legal_attacks_open_diff = 0, straight_legal_attacks_semiopen_diff = 0;
/* Accumulate the difference between white and black's attacks the center by restrictives */
int center_legal_attacks_by_restrictives_diff = 0;
/* Accumulate the difference between white and black's number of restricted captures by diagonal pieces */
int diagonal_restricted_captures_diff = 0;
/* Accumulate the restricted pieces attacked by diagonal pieces */
bitboard restrictives_legally_attacked_by_white_diagonal_pieces, restrictives_legally_attacked_by_black_diagonal_pieces;
/* Accumulate bishop or knight captures on enemy straight pieces */
int diagonal_or_knight_captures_on_straight_diff = 0;
/* Accumulate attacks on passed pawn trajectories */
int legal_attacks_on_passed_pawn_trajectories_diff = 0;
/* NON-PINNED SLIDING PIECES */
/* Deal with non-pinned sliding pieces of both colors in one go.
* If in double check, check_vectors_dep_check_count will remove all attacks the attacks.
*/
/* Scope new bitboards */
{
/* Set straight and diagonal pieces */
const bitboard white_straight_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & ~white_check_info.pin_vectors;
const bitboard white_diagonal_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & ~white_check_info.pin_vectors;
const bitboard black_straight_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & ~black_check_info.pin_vectors;
const bitboard black_diagonal_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & ~black_check_info.pin_vectors;
/* Start compasses */
straight_compass straight_dir;
diagonal_compass diagonal_dir;
/* Iterate through the compass to get all queen, rook and bishop attacks */
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( int i = 0; i < 4; ++i )
{
/* Get the compasses */
straight_dir = straight_compass_array [ i ];
diagonal_dir = diagonal_compass_array [ i ];
/* Apply all shifts to get straight and diagonal general attacks (note that sp is universe to get general attacks)
* This allows us to union to the defence set first.
*/
bitboard white_straight_attacks = white_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard white_diagonal_attacks = white_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
bitboard black_straight_attacks = black_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard black_diagonal_attacks = black_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
/* Union defence */
white_partial_defence_union |= white_straight_attacks | white_diagonal_attacks;
black_partial_defence_union |= black_straight_attacks | black_diagonal_attacks;
/* Legalize the attacks */
white_straight_attacks &= white_legalize_attacks;
white_diagonal_attacks &= white_legalize_attacks;
black_straight_attacks &= black_legalize_attacks;
black_diagonal_attacks &= black_legalize_attacks;
/* Sum mobility */
white_mobility += white_straight_attacks.popcount () + white_diagonal_attacks.popcount ();
black_mobility += black_straight_attacks.popcount () + black_diagonal_attacks.popcount ();
/* Sum rook attacks on open files */
straight_legal_attacks_open_diff += ( white_straight_attacks & open_files ).popcount ();
straight_legal_attacks_open_diff -= ( black_straight_attacks & open_files ).popcount ();
/* Sum rook attacks on semiopen files */
straight_legal_attacks_semiopen_diff += ( white_straight_attacks & white_semiopen_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( black_straight_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( white_straight_attacks & white_center ).popcount () + ( white_diagonal_attacks & white_center ).popcount ();
center_legal_attacks_by_restrictives_diff -= ( black_straight_attacks & black_center ).popcount () + ( black_diagonal_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & white_diagonal_attacks;
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & black_diagonal_attacks;
/* Sum the restricted captures by diagonal pieces */
diagonal_restricted_captures_diff += ( white_diagonal_attacks & black_restrictives ).popcount ();
diagonal_restricted_captures_diff -= ( black_diagonal_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( white_diagonal_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
diagonal_or_knight_captures_on_straight_diff -= ( black_diagonal_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_straight_attacks & black_passed_pawn_trajectories ).popcount () + ( white_diagonal_attacks & black_passed_pawn_trajectories ).popcount ();
legal_attacks_on_passed_pawn_trajectories_diff -= ( black_straight_attacks & white_passed_pawn_trajectories ).popcount () + ( black_diagonal_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* PINNED SLIDING PIECES */
/* Pinned pieces are handelled separately for each color.
* Only if that color is not in check will they be considered.
* The flood spans must be calculated separately for straight and diagonal, since otherwise the flood could spill onto adjacent pin vectors.
*/
/* White pinned pieces */
if ( white_check_info.pin_vectors.is_nonempty () & white_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & white_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & white_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( white_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( white_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
white_partial_defence_union |= pinned_attacks | bb ( pcolor::white, ptype::king );
/* Sum mobility */
white_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff += ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff += ( straight_pinned_attacks & white_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( pinned_attacks & white_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff += ( diagonal_pinned_attacks & black_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( diagonal_pinned_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( pinned_attacks & black_passed_pawn_trajectories ).popcount ();
}
}
/* Black pinned pieces */
if ( black_check_info.pin_vectors.is_nonempty () & black_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & black_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & black_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( black_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( black_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
black_partial_defence_union |= pinned_attacks | bb ( pcolor::black, ptype::king );
/* Sum mobility */
black_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff -= ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( straight_pinned_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( pinned_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff -= ( diagonal_pinned_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff -= ( diagonal_pinned_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( pinned_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* GENERAL SLIDING PIECES */
/* Scope new bitboards */
{
/* Get straight pieces */
const bitboard white_straight_pieces = bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen );
const bitboard black_straight_pieces = bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen );
/* Incorperate the material cost into value */
value += BISHOP * ( bb ( pcolor::white, ptype::bishop ).popcount () - bb ( pcolor::black, ptype::bishop ).popcount () );
value += ROOK * ( bb ( pcolor::white, ptype::rook ).popcount () - bb ( pcolor::black, ptype::rook ).popcount () );
value += QUEEN * ( bb ( pcolor::white, ptype::queen ).popcount () - bb ( pcolor::black, ptype::queen ).popcount () );
/* Incorporate straight pieces on 7th (or 2nd) rank into value */
{
const bitboard white_straight_pieces_7th_rank = white_straight_pieces & bitboard { bitboard::masks::rank_7 };
const bitboard black_straight_pieces_2nd_rank = black_straight_pieces & bitboard { bitboard::masks::rank_2 };
value += STRAIGHT_PIECES_ON_7TH_RANK * ( white_straight_pieces_7th_rank.popcount () - black_straight_pieces_2nd_rank.popcount () );
}
/* Incorporate bishops on initial cells into value */
{
const bitboard white_initial_bishops = bb ( pcolor::white, ptype::bishop ) & white_bishop_initial_cells;
const bitboard black_initial_bishops = bb ( pcolor::black, ptype::bishop ) & black_bishop_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_bishops.popcount () - black_initial_bishops.popcount () );
}
/* Incorporate double bishops into value */
value += DOUBLE_BISHOP * ( ( bb ( pcolor::white, ptype::bishop ).popcount () == 2 ) - ( bb ( pcolor::black, ptype::bishop ).popcount () == 2 ) );
/* Incorporate straight pieces and attacks on open/semiopen files into value */
value += STRAIGHT_PIECES_ON_OPEN_FILE * ( ( white_straight_pieces & open_files ).popcount () - ( black_straight_pieces & open_files ).popcount () );
value += STRAIGHT_PIECES_ON_SEMIOPEN_FILE * ( ( white_straight_pieces & white_semiopen_files ).popcount () - ( black_straight_pieces & black_semiopen_files ).popcount () );
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES * straight_legal_attacks_open_diff;
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES * straight_legal_attacks_semiopen_diff;
/* Incorporate straight pieces behind passed pawns into value */
value += STRAIGHT_PIECES_BEHIND_PASSED_PAWNS * ( ( white_straight_pieces & white_behind_passed_pawns ).popcount () - ( black_straight_pieces & black_behind_passed_pawns ).popcount () );
/* Incorporate restrictives attacked by diagonal pieces */
value += RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES * ( restrictives_legally_attacked_by_white_diagonal_pieces.popcount () - restrictives_legally_attacked_by_black_diagonal_pieces.popcount () );
/* Incorporate diagonal pieces restricted captures into value */
value += DIAGONAL_PIECE_RESTRICTED_CAPTURES * diagonal_restricted_captures_diff;
}
/* KNIGHTS */
/* Each color is considered separately in loops */
/* Scope new bitboards */
{
/* Iterate through white knights to get attacks.
* If in double check, white_check_info.check_vectors_dep_check_count will remove all moves.
*/
for ( bitboard white_knights = bb ( pcolor::white, ptype::knight ); white_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = white_knights.trailing_zeros (); white_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
white_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !white_check_info.pin_vectors.test ( pos ) ) & white_legalize_attacks;
/* Sum mobility */
white_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( knight_attacks & white_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff += ( knight_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( knight_attacks & black_passed_pawn_trajectories ).popcount ();
}
/* Iterate through black knights to get attacks */
for ( bitboard black_knights = bb ( pcolor::black, ptype::knight ); black_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = black_knights.trailing_zeros (); black_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
black_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !black_check_info.pin_vectors.test ( pos ) ) & black_legalize_attacks;
/* Sum mobility */
black_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( knight_attacks & black_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff -= ( knight_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( knight_attacks & white_passed_pawn_trajectories ).popcount ();
}
/* Incorperate the number of knights into value */
value += KNIGHT * ( bb ( pcolor::white, ptype::knight ).popcount () - bb ( pcolor::black, ptype::knight ).popcount () );
/* Incorporate knights on initial cells into value */
{
const bitboard white_initial_knights = bb ( pcolor::white, ptype::knight ) & white_knight_initial_cells;
const bitboard black_initial_knights = bb ( pcolor::black, ptype::knight ) & black_knight_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_knights.popcount () - black_initial_knights.popcount () );
}
/* Incorporate knights in the venter into value */
{
const bitboard white_center_knights = bb ( pcolor::white, ptype::knight ) & white_center;
const bitboard black_center_knights = bb ( pcolor::black, ptype::knight ) & black_center;
value += CENTER_KNIGHTS * ( white_center_knights.popcount () - black_center_knights.popcount () );
}
}
/* PAWN MOVES */
/* We can handle both colors, pinned and non-pinned pawns simultaneously, since pawn moves are more simple than sliding pieces and knights.
* Non-pinned pawns can have their moves calculated normally, but pinned pawns must first be checked as to whether they will move along their pin vector.
* There is no if-statement for double check, only check_vectors_dep_check_count is used to mask out all moves if in double check.
* This is because double check is quite unlikely, and pawn move calculations are quite cheap anyway.
*/
/* Scope the new bitboards */
{
/* Get the non-pinned pawns */
const bitboard white_non_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_check_info.pin_vectors;
const bitboard black_non_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_check_info.pin_vectors;
/* Get the straight and diagonal pinned pawns */
const bitboard white_straight_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.straight_pin_vectors;
const bitboard white_diagonal_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.diagonal_pin_vectors;
const bitboard black_straight_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.straight_pin_vectors;
const bitboard black_diagonal_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.diagonal_pin_vectors;
/* Calculations for pawn pushes.
* Non-pinned pawns can push without restriction.
* Pinned pawns can push only if they started and ended within a straight pin vector.
* If in check, ensure that the movements protected the king.
*/
const bitboard white_pawn_pushes = ( white_non_pinned_pawns.pawn_push_n ( pp ) | ( white_straight_pinned_pawns.pawn_push_n ( pp ) & white_check_info.straight_pin_vectors ) ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_pawn_pushes = ( black_non_pinned_pawns.pawn_push_s ( pp ) | ( black_straight_pinned_pawns.pawn_push_s ( pp ) & black_check_info.straight_pin_vectors ) ) & black_check_info.check_vectors_dep_check_count;
/* Get general pawn attacks */
const bitboard white_pawn_attacks = bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ) | bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw );
const bitboard black_pawn_attacks = bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ) | bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw );
/* Get the strong squares.
* These are the squares attacked by a friendly pawn, but not by an enemy pawn.
*/
const bitboard white_strong_squares = white_pawn_attacks & ~black_pawn_attacks;
const bitboard black_strong_squares = black_pawn_attacks & ~white_pawn_attacks;
/* Get pawn captures (legal pawn attacks).
* Non-pinned pawns can attack without restriction.
* Pinned pawns can attack only if they started and ended within a diagonal pin vector.
* If in check, ensure that the movements protected the king.
* En passant will be added later
*/
bitboard white_pawn_captures_e = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::ne ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::ne ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard white_pawn_captures_w = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::nw ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::nw ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard black_pawn_captures_e = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::se ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::se ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
bitboard black_pawn_captures_w = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::sw ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::sw ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
/* Save the en passant target square */
const int en_passant_target = aux_info.en_passant_target;
/* Add white en passant captures if they don't lead to check */
if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 9, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 7, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Add black en passant captures if they don't lead to check */
if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 7, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 9, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Union defence */
white_partial_defence_union |= white_pawn_attacks;
black_partial_defence_union |= black_pawn_attacks;
/* Sum mobility */
white_mobility += white_pawn_pushes.popcount () + white_pawn_captures_e.popcount () + white_pawn_captures_w.popcount ();
black_mobility += black_pawn_pushes.popcount () + black_pawn_captures_e.popcount () + black_pawn_captures_w.popcount ();
/* Incorporate the number of pawns into value */
value += PAWN * ( bb ( pcolor::white, ptype::pawn ).popcount () - bb ( pcolor::black, ptype::pawn ).popcount () );
/* Incorporate the number of cells generally attacked by pawns into value */
value += PAWN_GENERAL_ATTACKS * ( white_pawn_attacks.popcount () - black_pawn_attacks.popcount () );
/* Incorporate strong squares into value */
value += STRONG_SQUARES * ( white_strong_squares.popcount () - black_strong_squares.popcount () );
/* Sum the legal attacks on passed pawn trajectories.
* Use pawn general attacks, since legal captures require there to be a piece present.
*/
legal_attacks_on_passed_pawn_trajectories_diff += ( white_pawn_attacks & black_passed_pawn_trajectories ).popcount () - ( black_pawn_attacks & white_passed_pawn_trajectories ).popcount ();
/* Incorperate the number of pawns in the center to value */
{
const bitboard white_center_pawns = bb ( pcolor::white, ptype::pawn ) & white_center;
const bitboard black_center_pawns = bb ( pcolor::black, ptype::pawn ) & black_center;
value += CENTER_PAWNS * ( white_center_pawns.popcount () - black_center_pawns.popcount () );
}
/* Incororate the number of center cells generally attacked by pawns into value */
{
const bitboard white_center_defence = white_pawn_attacks & white_center;
const bitboard black_center_defence = black_pawn_attacks & black_center;
value += PAWN_CENTER_GENERAL_ATTACKS * ( white_center_defence.popcount () - black_center_defence.popcount () );
}
/* Incorporate isolated pawns, and those on semiopen files, into value */
{
const bitboard white_isolated_pawns = bb ( pcolor::white, ptype::pawn ) & ~( white_pawn_file_fill.shift ( compass::e ) | white_pawn_file_fill.shift ( compass::w ) );
const bitboard black_isolated_pawns = bb ( pcolor::black, ptype::pawn ) & ~( black_pawn_file_fill.shift ( compass::e ) | black_pawn_file_fill.shift ( compass::w ) );
value += ISOLATED_PAWNS * ( white_isolated_pawns.popcount () - black_isolated_pawns.popcount () );
value += ISOLATED_PAWNS_ON_SEMIOPEN_FILES * ( ( white_isolated_pawns & white_semiopen_files ).popcount () - ( black_isolated_pawns & black_semiopen_files ).popcount () );
}
/* Incorporate the number of doubled pawns into value */
{
const bitboard white_doubled_pawns = bb ( pcolor::white, ptype::pawn ) & white_pawn_rear_span;
const bitboard black_doubled_pawns = bb ( pcolor::black, ptype::pawn ) & black_pawn_rear_span;
value += DOUBLED_PAWNS * ( white_doubled_pawns.popcount () - black_doubled_pawns.popcount () );
}
/* Incorporate the number of cells adjacent to enemy king, which are generally attacked by pawns, into value */
{
const bitboard white_pawn_defence_adj_op_king = white_pawn_attacks & black_king_span;
const bitboard black_pawn_defence_adj_op_king = black_pawn_attacks & white_king_span;
value += PAWN_GENERAL_ATTACKS_ADJ_OP_KING * ( white_pawn_defence_adj_op_king.popcount () - black_pawn_defence_adj_op_king.popcount () );
}
/* Incorporate phalanga into value */
{
const bitboard white_phalanga = bb ( pcolor::white, ptype::pawn ) & bb ( pcolor::white, ptype::pawn ).shift ( compass::e );
const bitboard black_phalanga = bb ( pcolor::black, ptype::pawn ) & bb ( pcolor::black, ptype::pawn ).shift ( compass::e );
value += PHALANGA * ( white_phalanga.popcount () - black_phalanga.popcount () );
}
/* Incorporate blocked passed pawns into value */
{
const bitboard white_blocked_passed_pawns = white_behind_passed_pawns.shift ( compass::n ).shift ( compass::n ) & bb ( pcolor::black );
const bitboard black_blocked_passed_pawns = black_behind_passed_pawns.shift ( compass::s ).shift ( compass::s ) & bb ( pcolor::white );
value += BLOCKED_PASSED_PAWNS * ( white_blocked_passed_pawns.popcount () - black_blocked_passed_pawns.popcount () );
}
/* Incorporate backwards pawns into value */
{
const bitboard white_backward_pawns = white_strong_squares.shift ( compass::s ) & bb ( pcolor::white, ptype::pawn );
const bitboard black_backward_pawns = black_strong_squares.shift ( compass::n ) & bb ( pcolor::black, ptype::pawn );
value += BACKWARD_PAWNS * ( white_backward_pawns.popcount () - black_backward_pawns.popcount () );
}
/* Incorporate bishops or knights on strong squares into value */
{
const bitboard white_bishop_or_knight_strong_squares = white_strong_squares & ( bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::knight ) );
const bitboard black_bishop_or_knight_strong_squares = black_strong_squares & ( bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::knight ) );
value += BISHOP_OR_KNIGHT_ON_STRONG_SQUARE * ( white_bishop_or_knight_strong_squares.popcount () - black_bishop_or_knight_strong_squares.popcount () );
}
/* Incorporate passed pawns into value */
{
const bitboard white_passed_pawns_distance = white_passed_pawns.fill ( compass::s );
const bitboard black_passed_pawns_distance = black_passed_pawns.fill ( compass::n );
value += PASSED_PAWNS_DISTANCE * ( white_passed_pawns_distance.popcount () - black_passed_pawns_distance.popcount () );
}
}
/* KING ATTACKS */
/* Use the king position to look for possible attacks.
* As well as using the partial defence union, check any left over king moves for check.
*/
/* Scope the new bitboards */
{
/* Get all the king legal attacks (into empty space or an opposing piece).
* The empty space must not be protected by the opponent, and the kings must not be left adjacent.
* Note that some illegal attacks may be included here, if there are any opposing pinned sliding pieces.
*/
bitboard white_king_attacks = white_king_span & ~black_king_span & ~bb ( pcolor::white ) & ~black_partial_defence_union;
bitboard black_king_attacks = black_king_span & ~white_king_span & ~bb ( pcolor::black ) & ~white_partial_defence_union;
/* Validate the remaining white king moves */
if ( white_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::white ).reset ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).reset ( white_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard white_king_attacks_temp = white_king_attacks; white_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = white_king_attacks_temp.trailing_zeros ();
white_king_attacks.reset_if ( pos, is_protected ( pcolor::black, pos ) );
white_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::white ).set ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).set ( white_king_pos );
}
/* Validate the remaining black king moves */
if ( black_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::black ).reset ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).reset ( black_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard black_king_attacks_temp = black_king_attacks; black_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = black_king_attacks_temp.trailing_zeros ();
black_king_attacks.reset_if ( pos, is_protected ( pcolor::white, pos ) );
black_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::black ).set ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).set ( black_king_pos );
}
/* Calculate king queen fill. Flood fill using pp and queen attack lookup as a propagator. */
const bitboard white_king_queen_fill = bb ( pcolor::white, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( white_king_pos ) & pp )
| bb ( pcolor::white, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( white_king_pos ) & pp );
const bitboard black_king_queen_fill = bb ( pcolor::black, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( black_king_pos ) & pp )
| bb ( pcolor::black, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( black_king_pos ) & pp );
/* Sum mobility */
white_mobility += white_king_attacks.popcount () + can_kingside_castle ( pcolor::white, white_check_info ) + can_queenside_castle ( pcolor::white, white_check_info );
black_mobility += black_king_attacks.popcount () + can_kingside_castle ( pcolor::black, black_check_info ) + can_queenside_castle ( pcolor::black, black_check_info );
/* Incorporate the king queen mobility into value.
* It does not matter that we are using the fills instead of spans, since the fact both the fills include their kings will cancel out.
*/
value += KING_QUEEN_MOBILITY * ( white_king_queen_fill.popcount () - black_king_queen_fill.popcount () );
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_king_span & black_passed_pawn_trajectories ).popcount () - ( black_king_span & white_passed_pawn_trajectories ).popcount ();
}
/* CHECKMATE AND STALEMATE */
/* If one color has no mobility and the other does, return maxima/minima or 0, depending on check count */
if ( ( white_mobility == 0 ) & ( black_mobility != 0 ) ) if ( white_check_info.check_count ) return ( pc == pcolor::white ? -CHECKMATE : CHECKMATE ); else return 0;
if ( ( black_mobility == 0 ) & ( white_mobility != 0 ) ) if ( black_check_info.check_count ) return ( pc == pcolor::white ? CHECKMATE : -CHECKMATE ); else return 0;
/* If neither color has any mobility, return 0 */
if ( white_mobility == 0 && black_mobility == 0 ) return 0;
/* FINISH ADDING TO VALUE */
/* Mobility */
value += MOBILITY * ( white_mobility - black_mobility );
/* Attacks by restrictives on center */
value += CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES * center_legal_attacks_by_restrictives_diff;
/* Captures on straight pieces by diagonal pieces and knights */
value += DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES * diagonal_or_knight_captures_on_straight_diff;
/* Knight and queen exist */
{
const bool white_knight_and_queen_exist = bb ( pcolor::white, ptype::knight ).is_nonempty () & bb ( pcolor::white, ptype::queen ).is_nonempty ();
const bool black_knight_and_queen_exist = bb ( pcolor::black, ptype::knight ).is_nonempty () & bb ( pcolor::black, ptype::queen ).is_nonempty ();
value += KNIGHT_AND_QUEEN_EXIST * ( white_knight_and_queen_exist - black_knight_and_queen_exist );
}
/* Castling */
value += CASTLE_MADE * ( castle_made ( pcolor::white ) - castle_made ( pcolor::black ) );
value += CASTLE_LOST * ( castle_lost ( pcolor::white ) - castle_lost ( pcolor::black ) );
/* Pinned pieces */
{
const bitboard white_pinned_pieces = white_check_info.pin_vectors & bb ( pcolor::white );
const bitboard black_pinned_pieces = black_check_info.pin_vectors & bb ( pcolor::black );
value += PINNED_PIECES * ( white_pinned_pieces.popcount () - black_pinned_pieces.popcount () );
}
/* Attacks on passed pawn trajectories */
value += LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES * legal_attacks_on_passed_pawn_trajectories_diff;
/* Kings in opposition */
value += KINGS_IN_OPPOSITION * ( white_king_span & black_king_span ).is_nonempty () * ( pc == pcolor::white ? +1 : -1 );
/* Return the value */
return ( pc == pcolor::white ? value : -value );
} | 55.079327 | 264 | 0.672704 | louishobson |
d5c613037da92a42adefc3e03b2cf4a88879e4d2 | 16,129 | cpp | C++ | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-05-27T13:12:28.000Z | 2022-03-08T19:04:49.000Z | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-06-15T14:11:11.000Z | 2021-08-17T02:03:07.000Z | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-06-15T14:05:08.000Z | 2022-02-22T08:13:10.000Z | /* Copyright (c) 2021. kms1212(Minsu Kwon)
This file is part of OpenFSL.
OpenFSL and its source code is published over BSD 3-Clause License.
See the BSD-3-Clause for more details.
<https://raw.githubusercontent.com/kms1212/OpenFSL/main/LICENSE>
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <codecvt>
#include <bitset>
#include "openfsl/fslutils.h"
#include "openfsl/fileblockdevice.h"
#include "openfsl/sector.h"
#include "openfsl/fat32/fs_fat32.h"
int readCount = 0;
int writeCount = 0;
size_t split(const std::string &txt, std::vector<std::string>* strs, char ch);
void hexdump(uint8_t* p, size_t offset, size_t len);
std::fstream disk;
int main(int argc, char** argv) {
if (argc != 3) {
std::cout << "usage: " << argv[0] << " [image_file] [test_name]";
return 1;
}
std::string imageFileName = std::string(argv[1]);
std::string testName = std::string(argv[2]);
disk.open(imageFileName, std::ios::in | std::ios::out | std::ios::binary);
openfsl::FileBlockDevice bd;
std::cout << "Reading image file parameter...\n";
std::fstream diskInfo;
diskInfo.open(imageFileName + ".info", std::ios::in);
if (!diskInfo.fail()) {
std::string line;
openfsl::BlockDevice::DiskParameter parameter;
while (getline(diskInfo, line)) {
std::cout << line << "\n";
std::vector<std::string> value;
split(line, &value, ' ');
if (value[0] == "SectorPerTrack") {
parameter.sectorPerTrack = stoi(value[1]);
} else if (value[0] == "HeadPerCylinder") {
parameter.headPerCylinder = stoi(value[1]);
} else if (value[0] == "BytesPerSector") {
parameter.bytesPerSector = stoi(value[1]);
}
}
bd.setDiskParameter(parameter);
diskInfo.close();
} else {
std::cout << "Fail to read disk parameter file. ";
std::cout << "Default values are will be used.\n";
}
bd.initialize(imageFileName, openfsl::FileBlockDevice::OpenMode::RW);
openfsl::FAT32 fat32(&bd, "", "\\/");
error_t result = fat32.initialize();
if (result) {
disk.close();
return result;
}
fat32.enableCache(512);
/////////////////////////////////////////////
// CHDIR TEST
/////////////////////////////////////////////
std::cout << "===========================\n";
std::cout << " CHDIR TEST\n";
std::cout << "===========================\n";
std::vector<std::string> chdirChecklist; // Checklist
chdirChecklist.push_back("::/.");
chdirChecklist.push_back("::/..");
chdirChecklist.push_back("::/directory1");
chdirChecklist.push_back("subdir1");
chdirChecklist.push_back("::");
chdirChecklist.push_back("directory1/subdir2");
chdirChecklist.push_back("../..");
chdirChecklist.push_back("directory9");
for (size_t i = 0; i < chdirChecklist.size(); i++) {
fat32.changeDirectory(chdirChecklist.at(i));
std::cout << "chdir(\"" << chdirChecklist.at(i) << "\") -> "
<< fat32.getPath() << "\n";
}
/////////////////////////////////////////////
// GETDIRLIST TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETDIRLIST TEST\n";
std::cout << "===========================\n";
std::vector<std::string> listDirChecklistDir; // Checklist directories
std::vector<std::vector<std::string>> listDirChecklist; // Checklist
std::vector<std::string> listDirChecklistChilds; // Checklist childs list
listDirChecklistDir.push_back("::"); // Directory ::
listDirChecklistChilds.push_back("DIRECTORY1");
listDirChecklistChilds.push_back("DIRECTORY2");
listDirChecklistChilds.push_back("DIRECTORY3");
listDirChecklistChilds.push_back("DIRECTORY4");
listDirChecklistChilds.push_back("DIRECTORY5");
listDirChecklistChilds.push_back("DIRECTORY6");
listDirChecklistChilds.push_back("DIRECTORY7");
listDirChecklistChilds.push_back("DIRECTORY8");
listDirChecklistChilds.push_back("FILE1.TXT");
listDirChecklistChilds.push_back("FILE2.TXT");
listDirChecklistChilds.push_back("FILE3.TXT");
listDirChecklistChilds.push_back("FILE4.TXT");
listDirChecklistChilds.push_back("FILE5.TXT");
listDirChecklistChilds.push_back("FILE6.TXT");
listDirChecklistChilds.push_back("FILE7.TXT");
listDirChecklistChilds.push_back("FILE8.TXT");
listDirChecklistChilds.push_back("LFNFILENAME1.TXT");
listDirChecklistChilds.push_back("LFNFILENAME2.TXT");
listDirChecklistChilds.push_back("LFNFILENAME3.TXT");
listDirChecklistChilds.push_back("LFNFILENAME4.TXT");
listDirChecklistChilds.push_back("DIRECTORY9");
listDirChecklist.push_back(listDirChecklistChilds);
listDirChecklistChilds.clear();
listDirChecklistDir.push_back("::/directory1"); // Directory ::/directory1
listDirChecklistChilds.push_back(".");
listDirChecklistChilds.push_back("..");
listDirChecklistChilds.push_back("SUBDIR1");
listDirChecklistChilds.push_back("SUBDIR2");
listDirChecklistChilds.push_back("SUBDIR3");
listDirChecklistChilds.push_back("SUBDIR4");
listDirChecklist.push_back(listDirChecklistChilds);
for (size_t j = 0; j < listDirChecklist.size(); j++) {
int result_temp;
fat32.changeDirectory(listDirChecklistDir.at(j));
std::vector<openfsl::FAT32::FileInfo> buf;
fat32.listDirectory(&buf);
result_temp = buf.size() != listDirChecklist.at(j).size();
result += result_temp;
std::cout << "(dirList.size() = " << buf.size()
<< ") != (dirChild.size() = " << listDirChecklist.at(j).size()
<< ") Returns : " << result_temp << "\n";
std::string filename;
for (uint32_t i = 0; i < buf.size(); i++) {
std::cout << buf[i].fileName << ": ";
filename = buf[i].fileName;
for (auto& c : filename) c = static_cast<char>(toupper(c));
if (find(listDirChecklist.at(j).begin(),
listDirChecklist.at(j).end(), filename) ==
listDirChecklist.at(j).end()) {
std::cout << "not found\n";
result++;
} else {
std::cout << "found\n";
}
}
}
/////////////////////////////////////////////
// GETFILEINFORMATION TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETFILEINFORMATION TEST\n";
std::cout << "===========================\n";
std::vector<std::string> finfoChecklist; // Checklist
finfoChecklist.push_back("::/file1.txt");
finfoChecklist.push_back("::/file2.txt");
finfoChecklist.push_back("::/file3.txt");
finfoChecklist.push_back("::/file4.txt");
finfoChecklist.push_back("::/file5.txt");
finfoChecklist.push_back("::/file6.txt");
finfoChecklist.push_back("::/file7.txt");
finfoChecklist.push_back("::/file8.txt");
finfoChecklist.push_back("::/lfnfilename1.txt");
finfoChecklist.push_back("::/lfnfilename2.txt");
finfoChecklist.push_back("::/lfnfilename3.txt");
finfoChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < finfoChecklist.size(); i++) {
std::pair<error_t, openfsl::FAT32::FileInfo> fileInfo =
fat32.getEntryInfo(finfoChecklist.at(i));
if (fileInfo.first) {
result++;
break;
}
std::cout << "getFileInformation(\"" << finfoChecklist.at(i)
<< "\") Returns : \n";
std::cout << " File Name: " << fileInfo.second.fileName << "\n";
std::cout << " File Created Time: "
<< fileInfo.second.fileCreateTime.time_month << "/"
<< fileInfo.second.fileCreateTime.time_day << "/"
<< fileInfo.second.fileCreateTime.time_year << " "
<< fileInfo.second.fileCreateTime.time_hour << ":"
<< fileInfo.second.fileCreateTime.time_min << ":"
<< fileInfo.second.fileCreateTime.time_sec << "."
<< fileInfo.second.fileCreateTime.time_millis << "\n";
std::cout << " File Access Time: "
<< fileInfo.second.fileAccessTime.time_month << "/"
<< fileInfo.second.fileAccessTime.time_day << "/"
<< fileInfo.second.fileAccessTime.time_year << " "
<< fileInfo.second.fileAccessTime.time_hour << ":"
<< fileInfo.second.fileAccessTime.time_min << ":"
<< fileInfo.second.fileAccessTime.time_sec << "."
<< fileInfo.second.fileAccessTime.time_millis << "\n";
std::cout << " File Mod Time: "
<< fileInfo.second.fileModTime.time_month << "/"
<< fileInfo.second.fileModTime.time_day << "/"
<< fileInfo.second.fileModTime.time_year << " "
<< fileInfo.second.fileModTime.time_hour << ":"
<< fileInfo.second.fileModTime.time_min << ":"
<< fileInfo.second.fileModTime.time_sec << "."
<< fileInfo.second.fileModTime.time_millis << "\n";
std::cout << " File Location: " << fileInfo.second.fileLocation << "\n";
std::cout << " File Size: " << fileInfo.second.fileSize << "\n";
std::stringstream ss;
ss << std::hex << (unsigned int)fileInfo.second.fileAttr;
std::cout << " File Attribute: 0x" << ss.str() << "\n";
}
/////////////////////////////////////////////
// FILE TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " FILE TEST\n";
std::cout << "===========================\n";
std::vector<std::string> fileChecklist; // Checklist
fileChecklist.push_back("::/file1.txt");
fileChecklist.push_back("::/file2.txt");
fileChecklist.push_back("::/file3.txt");
fileChecklist.push_back("::/file4.txt");
fileChecklist.push_back("::/file5.txt");
fileChecklist.push_back("::/file6.txt");
fileChecklist.push_back("::/file7.txt");
fileChecklist.push_back("::/file8.txt");
fileChecklist.push_back("::/lfnfilename1.txt");
fileChecklist.push_back("::/lfnfilename2.txt");
fileChecklist.push_back("::/lfnfilename3.txt");
fileChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < fileChecklist.size(); i++) {
std::cout << "Filename: " << finfoChecklist.at(i) << "\n";
openfsl::FAT32::FILE file(&fat32);
if (file.open(fileChecklist.at(i), openfsl::FSL_OpenMode::Read)) {
result++;
continue;
}
std::cout << "openFile(\"" << finfoChecklist.at(i) << "\")\n";
file.seekg(0, openfsl::FSL_SeekMode::SeekEnd);
size_t fileSize = file.tellg();
file.seekg(0, openfsl::FSL_SeekMode::SeekSet);
char* buf = new char[fileSize + 1]();
memset(buf, 0, fileSize + 1);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
buf[fileSize] = 0;
std::string buf_s(buf);
std::string comp_s("Hello, World!\nOpenFSL\n");
std::cout << "file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize);
std::cout << "\n";
if (buf_s != comp_s) {
result++;
}
// Try to read file with seek
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize - 14);
buf_s = std::string(buf);
comp_s = "OpenFSL\n";
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize - 14);
if (buf_s != comp_s) {
result++;
}
// Try to read more than the size of file.
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
size_t ret = file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
if (ret != fileSize - 14)
result++;
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Returned: " << ret << "\n";
file.close();
std::cout << "------------------------------\n";
}
/////////////////////////////////////////////
// MAKE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " MAKE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> mkDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : mkDirChecklist) {
result += fat32.makeDirectory(dirname);
result += fat32.changeDirectory(dirname);
result += fat32.changeDirectory("..");
}
/////////////////////////////////////////////
// REMOVE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " REMOVE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> rmDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : rmDirChecklist) {
result += fat32.remove(dirname,
openfsl::FAT32::FileAttribute::Directory);
if (!fat32.changeDirectory(dirname))
result++;
}
std::cout << "Total read count: " << readCount << std::endl;
std::cout << "Total write count: " << writeCount << std::endl;
disk.close();
return result;
}
size_t split(const std::string &txt,
std::vector<std::string>* strs, char ch) {
std::string temp = txt;
size_t pos = temp.find(ch);
size_t initialPos = 0;
strs->clear();
// Decompose statement
while (pos != std::string::npos) {
if (temp.at(pos - 1) != '\\') {
strs->push_back(temp.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
} else {
temp.erase(temp.begin() + pos - 1);
}
pos = temp.find(ch, pos + 1);
}
// Add the last one
strs->push_back(temp.substr(initialPos,
std::min(pos, temp.size()) - initialPos + 1));
return strs->size();
}
void hexdump(uint8_t* p, size_t offset, size_t len) {
std::ios init(nullptr);
init.copyfmt(std::cout);
size_t address = 0;
size_t row = 0;
std::cout << std::hex << std::setfill('0');
while (1) {
if (address >= len) break;
size_t nread = ((len - address) > 16) ? 16 : (len - address);
// Show the address
std::cout << std::setw(8) << address + offset;
// Show the hex codes
for (size_t i = 0; i < 16; i++) {
if (i % 8 == 0) std::cout << ' ';
if (i < nread)
std::cout << ' ' << std::setw(2)
<< static_cast<int>(p[16 * row + i + offset]);
else
std::cout << " ";
}
// Show printable characters
std::cout << " ";
for (size_t i = 0; i < nread; i++) {
uint8_t ch = p[16 * row + i + offset];
if (ch < 32 || ch > 125) std::cout << '.';
else
std::cout << ch;
}
std::cout << "\n";
address += 16;
row++;
}
std::cout.copyfmt(init);
}
| 35.139434 | 83 | 0.545601 | kms1212 |
d5cac4189391d3a5ab3edbd8333094c6bd8426bf | 320 | hpp | C++ | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "file.hpp"
#include "types.hpp"
namespace gold {
struct texture : public file {
protected:
static object& getPrototype();
public:
texture();
texture(file copy);
texture(path fpath);
texture(binary data);
var load(list args = {});
var bind(list args);
};
} // namespace gold | 16 | 32 | 0.6625 | CoryNull |
d5cdf8882529fd5bc4327631f446d7997755b886 | 959 | hh | C++ | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | #ifndef isnp_facility_component_SpallationTargetMessenger_hh
#define isnp_facility_component_SpallationTargetMessenger_hh
#include <memory>
#include <G4UImessenger.hh>
#include <G4UIdirectory.hh>
#include <G4UIcmdWithABool.hh>
#include <G4UIcmdWith3VectorAndUnit.hh>
#include "isnp/facility/component/SpallationTarget.hh"
namespace isnp {
namespace facility {
namespace component {
class SpallationTargetMessenger: public G4UImessenger {
public:
SpallationTargetMessenger(SpallationTarget& component);
~SpallationTargetMessenger() override;
G4String GetCurrentValue(G4UIcommand* command) override;
void SetNewValue(G4UIcommand*, G4String) override;
private:
SpallationTarget& component;
std::unique_ptr<G4UIdirectory> const directory;
std::unique_ptr<G4UIcmdWithABool> const hasCoolerCmd;
std::unique_ptr<G4UIcmdWith3VectorAndUnit> const rotationCmd, positionCmd;
};
}
}
}
#endif // isnp_facility_component_SpallationTargetMessenger_hh
| 22.302326 | 75 | 0.828989 | andrey-nakin |
d5cff4d5527fecb5bd854b98d73ceae25be84698 | 136 | cpp | C++ | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | #include <RayTracer/render.h>
int main(int, char**) {
render Render;
Render.init();
Render.process();
return 0;
}
| 13.6 | 29 | 0.580882 | Hiro-KE |
d5d24a29410f8602d9b09664fa30cb7009576dcf | 869 | hpp | C++ | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | /*********************************************************************
** Author: Wei-Chien Hsu
** Date: 04/24/18
** Description: A class called Person that has two data members
- a string variable called name and a double variable called age.
It should have a constructor that takes two values and uses them to
initialize the data members.
It should have get methods for both data members (getName and getAge),
but doesn't need any set methods.
*********************************************************************/
#ifndef PERSON_HPP
#define PERSON_HPP
#include <string>
class Person {
private:
std::string name;
double age;
public:
Person();
Person(std::string, double);
std::string getName();
double getAge();
};
#endif | 31.035714 | 89 | 0.50748 | WeiChienHsu |
d5d2b1114c1f6d5a35f3e3d7962cc2699fb8e67c | 473 | cpp | C++ | src/Commands/SelVertexCmd.cpp | PlayMe-Martin/XiMapper | 1926cbd1d13c771d9d60d0d5eb343e059067e0f0 | [
"MIT"
] | 410 | 2015-02-04T22:26:32.000Z | 2022-03-29T00:00:13.000Z | src/Commands/SelVertexCmd.cpp | victorscaff/ofxPiMapper | e79e88e21891abded8388520d4e7f5e6868bfbb7 | [
"MIT"
] | 162 | 2015-01-11T16:09:39.000Z | 2022-03-14T11:24:48.000Z | src/Commands/SelVertexCmd.cpp | victorscaff/ofxPiMapper | e79e88e21891abded8388520d4e7f5e6868bfbb7 | [
"MIT"
] | 100 | 2015-02-09T06:42:31.000Z | 2022-01-01T01:40:36.000Z | #include "SelVertexCmd.h"
namespace ofx {
namespace piMapper {
SelVertexCmd::SelVertexCmd(SurfaceManager * sm, int i){
_surfaceManager = sm;
_newVertexIndex = i;
}
void SelVertexCmd::exec(){
_prevVertexIndex = _surfaceManager->getSelectedVertexIndex();
_surfaceManager->selectVertex(_newVertexIndex);
}
void SelVertexCmd::undo(){
ofLogNotice("SelVertexCmd", "undo");
_surfaceManager->selectVertex(_prevVertexIndex);
}
} // namespace piMapper
} // namespace ofx
| 19.708333 | 62 | 0.761099 | PlayMe-Martin |
d5d498f2c2979ef8d9a980b037d10cf6b0d1031e | 4,323 | cpp | C++ | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | 4 | 2015-03-18T15:00:38.000Z | 2016-01-04T13:09:59.000Z | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | null | null | null | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | null | null | null | #include <unistd.h>
#include <ctime>
#include <vector>
#include "sireen/file_utility.hpp"
#include "sireen/image_feature_extract.hpp"
/*
* Main
*/
int main(int argc, char * argv[]) {
/*********************************************
* Step 0 - optget to receive input option
*********************************************/
char result_buf[256]= "res/llc/caltech101.txt";
char codebook_buf[256]= "res/codebooks/caltech101/cbcaltech101.txt";
char image_dir_buf[256]= "res/images/caltech101";
/* CHECK THE INPUT OPTIONS */
//initialize the arg options
int opt;
while ((opt = getopt(argc, argv, "r:c:i:")) != -1) {
switch (opt) {
case 'r':
sprintf(result_buf, "%s", optarg);
break;
case 'c':
sprintf(codebook_buf, "%s", optarg);
break;
case 'i':
sprintf(image_dir_buf, "%s", optarg);
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [options]\n", argv[0]);
fprintf(stderr, " -i :PATH to image directory\n");
fprintf(stderr, " -r :PATH to result\n");
fprintf(stderr, " -c :PATH to codebook\n");
return -1;
}
}
/* CHECK END */
/*--------------------------------------------
* Path
--------------------------------------------*/
string result_path = string(result_buf);
string image_dir = string(image_dir_buf);
string codebook_path = string(codebook_buf);
/*--------------------------------------------
* PARAMETERS
--------------------------------------------*/
const int CB_SIZE = 500;
/*--------------------------------------------
* VARIABLE READ & WRITE CACHE
--------------------------------------------*/
FILE * outfile;
float *codebook = new float[128 * CB_SIZE];
//counter for reading lines;
unsigned int done=0;
// Initiation
ImageCoder icoder;
/*********************************************
* Step 1 - Loading & Check everything
*********************************************/
// 1. codebook validation
if (access(codebook_path.c_str(), 0)){
cerr << "codebook not found!" << endl;
return -1;
}
char delim[2] = ",";
futil::file_to_pointer(codebook_path.c_str(), codebook,delim);
if (codebook == NULL) {
cerr << "codebook error!" << endl;
return -1;
}
// 1. write file validation
outfile = fopen(result_path.c_str(), "wt+");
//if no file, error report
if ( NULL == outfile) {
cerr << "result file initialize problem!" << endl;
return -1;
}
vector<string> all_images;
string imgfile;
string llcstr;
futil::get_files_in_dir(all_images,image_dir);
/*********************************************
* Step 2 - Traverse the image directory
*********************************************/
clock_t start = clock();
for(unsigned int n = 0; n < all_images.size(); ++n)
{
// load image source to Mat format(opencv2.4.9)
// using the simple llcDescripter interface from
// ImageCoder
imgfile = all_images[n];
try
{
Mat src_image = imread(imgfile,0);
if(!src_image.data)
{
cout << "\tinvalid source image! --> " << imgfile << endl;
continue;
}
llcstr = icoder.llc_sift(src_image, codebook, CB_SIZE, 5);
// cout << llcstr << endl;
}
catch(...)
{
cout << "\tbroken image! --> " << imgfile << endl;
continue;
}
/*********************************************
* Step 4 - write result to file
*********************************************/
// correct file
fprintf(outfile, "%s\t", imgfile.c_str());
fprintf(outfile, "%s\n", llcstr.c_str());
// succeed count
done++;
// print info
if(done % 10== 0){
cout << "\t" << done << " Processed..." << endl;
}
}
cout << "\t" << done << " Processed...(done)"
<< " <Elasped Time: " << float(clock() -start)/CLOCKS_PER_SEC
<< "s>"<< endl;
delete codebook;
fclose(outfile);
}
| 30.020833 | 74 | 0.442979 | Jetpie |
d5d607bcc74262633493aea149afe1accf9e6af5 | 4,854 | cpp | C++ | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// \file StringUtility.cpp
///
///
/// Authors: Chris Peters
/// Copyright 2013, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//---------------------------------------------------------------------- Strings
bool CaseInsensitiveStringLess(StringParam a, StringParam b)
{
StringRange achars = a.All();
StringRange bchars = b.All();
while(!achars.Empty() && !bchars.Empty())
{
Rune aChar = UTF8::ToLower(achars.Front());
Rune bChar = UTF8::ToLower(bchars.Front());
if(aChar < bChar)
return true;
if(aChar > bChar)
return false;
achars.PopFront();
bchars.PopFront();
}
if(achars.Empty() && !bchars.Empty())
return true;
return false;
}
Pair<StringRange,StringRange> SplitOnLast(StringRange input, Rune delimiter)
{
//With empty just return empty String
if(input.Empty())
return Pair<StringRange,StringRange>(input, input);
size_t numRunes = input.ComputeRuneCount();
StringRange lastOf = input.FindLastOf(delimiter);
// Delim found return string and empty
if(lastOf.Empty())
return Pair<StringRange,StringRange>(input, StringRange());
if(lastOf.SizeInBytes() == 0)
return Pair<StringRange, StringRange>(StringRange(), input.SubString(input.Begin(), input.End()));
if(lastOf.SizeInBytes() == numRunes - 1)
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), input.End()), StringRange());
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), lastOf.End()), input.SubString(lastOf.Begin() + 1, lastOf.End()));
}
Pair<StringRange,StringRange> SplitOnFirst(StringRange input, Rune delimiter)
{
StringTokenRange tokenRange(input, delimiter);
StringRange left = tokenRange.Front();
StringRange right = StringRange(left.End(), input.End());
return Pair<StringRange, StringRange>(left, right);
}
StringRange StripBeforeLast(StringRange input, Rune delimiter)
{
Pair<StringRange, StringRange> split = SplitOnLast(input, delimiter);
// If the delimiter was not found the second will be empty
if(split.second.Empty())
return input;
else
return split.second;
}
String JoinStrings(const Array<String>& strings, StringParam delimiter)
{
StringBuilder builder;
for (size_t i = 0; i < strings.Size(); ++i)
{
const String& string = strings[i];
builder.Append(string);
bool isNotLast = (i + 1 != strings.Size());
if (isNotLast)
{
builder.Append(delimiter);
}
}
return builder.ToString();
}
char OnlyAlphaNumeric(char c)
{
if (!isalnum(c))
return '_';
else
return c;
}
//******************************************************************************
// Recursive helper for global string Permute below
static void PermuteRecursive(char *src, size_t start, size_t end, Array<String>& perms)
{
// finished a permutation, add it to the list
if (start == end)
{
perms.PushBack(src);
return;
}
for (size_t i = start; i < end; ++i)
{
// swap to get new head
Swap(src[start], src[i]);
// permute
PermuteRecursive(src, start + 1, end, perms);
// backtrack
Swap(src[start], src[i]);
}
}
//******************************************************************************
void Permute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// recursively calculate permutations
PermuteRecursive(buf, 0, srclen, perms);
}
//******************************************************************************
void SuperPermute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
const char *csrc = src.c_str();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// push the individual elements of the source
StringRange srcRange = src;
for (; !srcRange.Empty(); srcRange.PopFront())
perms.PushBack(String(srcRange.Front()));
for (uint l = 1; l < srclen; ++l)
{
for (uint i = 0; i + l < srclen; ++i)
{
// initialize buffer
memcpy(buf, csrc + i, l);
for (uint j = i + l; j < srclen; ++j)
{
buf[l] = csrc[j];
PermuteRecursive(buf, 0, l + 1, perms);
buf[l] = '\0';
}
}
}
}
}//namespace Zero
| 26.380435 | 138 | 0.568809 | jodavis42 |
d5d8e7be9d5306c7eb0f2aef9fba0c635d0935ca | 628 | cpp | C++ | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | #include "player.h"
#include "raylib.h"
#include <iostream>
bool player::moveTo(const Vector2 & dest)
{
std::cout << "player moving" << std::endl;
return false;
}
void player::takeDamage(int damage)
{
if (health >= 0)
{
health -= damage;
death = false;
}
else
{
death = true;
}
}
player::player(const std::string & fileName)
{
std::cout << "Creating sprite!" << std::endl;
mySprite = LoadTexture(fileName.c_str());
}
player::player()
{
}
player::~player()
{
std::cout << "Destroying sprite!" << std::endl;
UnloadTexture(mySprite);
}
void player::draw(Color h)
{
DrawTexture(mySprite, 375, 225, h);
}
| 13.361702 | 48 | 0.636943 | LegendaryyDoc |
d5daa1639a8aecc7956364b0221bddbdf2321648 | 527 | cpp | C++ | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int C, n, a, b, c, i;
long long m = 0;
cin >> C >> n;
for (i = 1; i <= n; ++i) {
cin >> a >> b >> c;
if (m < a) {
break;
}
m += b - a;
if (m > C) {
break;
}
if (c > 0 && m != C) {
break;
}
}
cout << (i == n + 1 && m == 0 ? "possible" : "impossible");
return 0;
} | 20.269231 | 63 | 0.371917 | tnsgh9603 |
d5e4eaa1f195ed86fbbc103d55e4b37d79d2df24 | 5,015 | hpp | C++ | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | #pragma once
#include "Maths/Vector3.hpp"
#include "Graphics/Buffers/Buffer.hpp"
#include "Resources/Resource.hpp"
namespace acid {
template<typename Base>
class ModelFactory {
public:
using TCreateReturn = std::shared_ptr<Base>;
using TCreateMethodNode = std::function<TCreateReturn(const Node &)>;
using TRegistryMapNode = std::unordered_map<std::string, TCreateMethodNode>;
using TCreateMethodFilename = std::function<TCreateReturn(const std::filesystem::path &)>;
using TRegistryMapFilename = std::unordered_map<std::string, TCreateMethodFilename>;
virtual ~ModelFactory() = default;
/**
* Creates a new model, or finds one with the same values.
* @param node The node to decode values from.
* @return The model with the requested values.
*/
static TCreateReturn Create(const Node &node) {
auto typeName = node["type"].Get<std::string>();
auto it = RegistryNode().find(typeName);
return it == RegistryNode().end() ? nullptr : it->second(node);
}
/**
* Creates a new model, or finds one with the same values.
* @param filename The file to load the model from.
* @return The model loaded from the filename.
*/
static TCreateReturn Create(const std::filesystem::path &filename) {
auto fileExt = filename.extension().string();
auto it = RegistryFilename().find(fileExt);
return it == RegistryFilename().end() ? nullptr : it->second(filename);
}
static TRegistryMapNode &RegistryNode() {
static TRegistryMapNode impl;
return impl;
}
static TRegistryMapFilename &RegistryFilename() {
static TRegistryMapFilename impl;
return impl;
}
/**
* A class used to help register subclasses of Model to the factory.
* Your subclass should have a static Create function taking a Node, or path.
* @tparam T The type that will extend Model.
*/
template<typename T>
class Registrar : public Base {
protected:
template<int Dummy = 0>
static bool Register(const std::string &typeName) {
Registrar::name = typeName;
ModelFactory::RegistryNode()[typeName] = [](const Node &node) -> TCreateReturn {
return T::Create(node);
};
return true;
}
template<int Dummy = 0>
static bool Register(const std::string &typeName, const std::string &extension) {
Register(typeName);
ModelFactory::RegistryFilename()[extension] = [](const std::filesystem::path &filename) -> TCreateReturn {
return T::Create(filename);
};
return true;
}
const Node &Load(const Node &node) override {
return node >> *dynamic_cast<T *>(this);
}
Node &Write(Node &node) const override {
node["type"].Set(name);
return node << *dynamic_cast<const T *>(this);
}
inline static std::string name;
};
friend const Node &operator>>(const Node &node, Base &base) {
return base.Load(node);
}
friend Node &operator<<(Node &node, const Base &base) {
return base.Write(node);
}
protected:
virtual const Node &Load(const Node &node) { return node; }
virtual Node &Write(Node &node) const { return node; }
};
/**
* @brief Resource that represents a model vertex and index buffer.
*/
class ACID_EXPORT Model : public ModelFactory<Model>, public Resource {
public:
/**
* Creates a new empty model.
*/
Model() = default;
/**
* Creates a new model.
* @tparam T The vertex type.
* @param vertices The model vertices.
* @param indices The model indices.
*/
template<typename T>
explicit Model(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {}) :
Model() {
Initialize(vertices, indices);
}
bool CmdRender(const CommandBuffer &commandBuffer, uint32_t instances = 1) const;
template<typename T>
std::vector<T> GetVertices(std::size_t offset = 0) const;
template<typename T>
void SetVertices(const std::vector<T> &vertices);
std::vector<uint32_t> GetIndices(std::size_t offset = 0) const;
void SetIndices(const std::vector<uint32_t> &indices);
std::vector<float> GetPointCloud() const;
const Vector3f &GetMinExtents() const { return m_minExtents; }
const Vector3f &GetMaxExtents() const { return m_maxExtents; }
float GetWidth() const { return m_maxExtents.m_x - m_minExtents.m_x; }
float GetHeight() const { return m_maxExtents.m_y - m_minExtents.m_y; }
float GetDepth() const { return m_maxExtents.m_z - m_minExtents.m_z; }
float GetRadius() const { return m_radius; }
const Buffer *GetVertexBuffer() const { return m_vertexBuffer.get(); }
const Buffer *GetIndexBuffer() const { return m_indexBuffer.get(); }
uint32_t GetVertexCount() const { return m_vertexCount; }
uint32_t GetIndexCount() const { return m_indexCount; }
static VkIndexType GetIndexType() { return VK_INDEX_TYPE_UINT32; }
protected:
template<typename T>
void Initialize(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {});
private:
std::unique_ptr<Buffer> m_vertexBuffer;
std::unique_ptr<Buffer> m_indexBuffer;
uint32_t m_vertexCount = 0;
uint32_t m_indexCount = 0;
Vector3f m_minExtents;
Vector3f m_maxExtents;
float m_radius = 0.0f;
};
}
#include "Model.inl"
| 30.210843 | 109 | 0.714656 | LukePrzyb |
d5e988104d12cb3eb25053a7b6090f42e28be3d8 | 26,239 | cc | C++ | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 11 | 2017-07-26T16:08:58.000Z | 2021-03-02T14:49:32.000Z | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 3 | 2017-07-31T15:51:31.000Z | 2021-06-08T21:16:25.000Z | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 14 | 2017-06-21T20:27:21.000Z | 2021-06-24T18:53:11.000Z | /*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced
under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
Laboratory (LANL), which is operated by Los Alamos National Security, LLC for
the U.S. Department of Energy. The U.S. Government has rights to use,
reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
to produce derivative works, such modified software should be clearly marked,
so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos
National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL
SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "GraphTraverser.hh"
#include "Mat.hh"
#include "Global.hh"
#include "TychoMesh.hh"
#include "Comm.hh"
#include "Timer.hh"
#include <vector>
#include <set>
#include <queue>
#include <utility>
#include <omp.h>
#include <limits.h>
#include <string.h>
using namespace std;
/*
Tuple class
*/
namespace {
class Tuple
{
private:
UINT c_cell;
UINT c_angle;
UINT c_priority;
public:
Tuple(UINT cell, UINT angle, UINT priority)
: c_cell(cell), c_angle(angle), c_priority(priority) {}
UINT getCell() const { return c_cell; }
UINT getAngle() const { return c_angle; }
// Comparison operator to determine relative priorities
// Needed for priority_queue
bool operator<(const Tuple &rhs) const
{
return c_priority < rhs.c_priority;
}
};}
/*
splitPacket
Packet is (global side, angle, data)
*/
static
void splitPacket(char *packet, UINT &globalSide, UINT &angle, char **data)
{
memcpy(&globalSide, packet, sizeof(UINT));
packet += sizeof(UINT);
memcpy(&angle, packet, sizeof(UINT));
packet += sizeof(UINT);
*data = packet;
}
/*
createPacket
Packet is (global side, angle, data)
*/
static
void createPacket(vector<char> &packet, UINT globalSide, UINT angle,
UINT dataSize, const char *data)
{
packet.resize(2 * sizeof(UINT) + dataSize);
char *p = packet.data();
memcpy(p, &globalSide, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, &angle, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, data, dataSize);
}
/*
isIncoming
Determines whether data is incoming to the cell
depending on sweep direction.
*/
static
bool isIncoming(UINT angle, UINT cell, UINT face, Direction direction)
{
if (direction == Direction_Forward)
return g_tychoMesh->isIncoming(angle, cell, face);
else if (direction == Direction_Backward)
return g_tychoMesh->isOutgoing(angle, cell, face);
// Should never get here
Assert(false);
return false;
}
/*
angleGroupIndex
Gets angle groups for angle index.
e.g. 20 angles numbered 0...19 with 3 threads.
Split into 3 angle chunks of size 7,7,6: 0...6 7...13 14...19
If angle in 0...6, return 0
If angle in 7...13, return 1
If angle in 14...19, return 2
*/
UINT angleGroupIndex(UINT angle)
{
UINT numAngles = g_nAngles;
UINT chunkSize = numAngles / g_nThreads;
UINT numChunksBigger = numAngles % g_nThreads;
UINT lowIndex = 0;
// Find angleGroup
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
UINT nextLowIndex = lowIndex + chunkSize;
if (angleGroup < numChunksBigger)
nextLowIndex++;
if (angle < nextLowIndex)
return angleGroup;
lowIndex = nextLowIndex;
}
// Should never get here
Assert(false);
return 0;
}
/*
sendData2Sided
Implements two-sided MPI for sending data.
*/
void GraphTraverser::sendData2Sided(
const vector<vector<char>> &sendBuffers) const
{
vector<MPI_Request> mpiSendRequests;
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
// Send the data
for (UINT index = 0; index < numAdjRanks; index++) {
const vector<char> &sendBuffer = sendBuffers[index];
if (sendBuffer.size() > 0) {
MPI_Request request;
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
recvData2Sided
Implements two-sided MPI for receiving data.
*/
void GraphTraverser::recvData2Sided(vector<char> &dataPackets) const
{
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
for (UINT index = 0; index < numAdjRanks; index++) {
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
int flag = 0;
MPI_Status mpiStatus;
int recvCount;
// Probe for new message
mpiError = MPI_Iprobe(adjRank, tag, MPI_COMM_WORLD, &flag, &mpiStatus);
Insist(mpiError == MPI_SUCCESS, "");
mpiError = MPI_Get_count(&mpiStatus, MPI_BYTE, &recvCount);
Insist(mpiError == MPI_SUCCESS, "");
// Recv message if there is one
if (flag) {
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvCount);
mpiError = MPI_Recv(&dataPackets[originalSize], recvCount,
MPI_BYTE, adjRank, tag, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
}
/*
sendAndRecvData()
The algorithm is
- Irecv data size for all adjacent ranks
- ISend data size and then data (if any)
- Wait on recv of data size, then blocking recv for data if there is any.
Data is sent in two steps to each adjacent rank.
First is the number of bytes of data that will be sent.
Second is the raw data in bytes.
The tag for the first send is 0.
The tag for the second send is 1.
The raw data is made of data packets containing:
globalSide, angle, and data to send.
The data can have different meanings depending on the TraverseData
subclass.
When done traversing local graph, you want to stop all communication.
This is done by setting killComm to true.
To mark killing communication, sendSize is set to UINT64_MAX.
In this event, commDark[rank] is set to true on the receiving rank
so we no longer look for communication from this rank.
*/
void GraphTraverser::sendAndRecvData(const vector<vector<char>> &sendBuffers,
vector<char> &dataPackets,
vector<bool> &commDark,
const bool killComm) const
{
// Check input
Assert(c_adjRankIndexToRank.size() == sendBuffers.size());
Assert(c_adjRankIndexToRank.size() == commDark.size());
// Variables
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
vector<UINT> recvSizes(numAdjRanks);
vector<UINT> sendSizes(numAdjRanks);
vector<MPI_Request> mpiRecvRequests(numAdjRanks);
vector<MPI_Request> mpiSendRequests;
UINT numRecv = numAdjRanks;
// Setup recv of data size
for (UINT index = 0; index < numAdjRanks; index++) {
// No recv if adjRank is no longer communicating
if (commDark[index]) {
mpiRecvRequests[index] = MPI_REQUEST_NULL;
numRecv--;
continue;
}
// Irecv data size
int numDataToRecv = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
mpiError = MPI_Irecv(&recvSizes[index], numDataToRecv, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD,
&mpiRecvRequests[index]);
Insist(mpiError == MPI_SUCCESS, "");
}
// Send data size and data
for (UINT index = 0; index < numAdjRanks; index++) {
// Don't send if adjRank is no longer communicating
if (commDark[index])
continue;
const vector<char> &sendBuffer = sendBuffers[index];
int numDataToSend = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
int tag1 = 1;
// Send data size
MPI_Request request;
sendSizes[index] = sendBuffer.size();
if (killComm)
sendSizes[index] = UINT64_MAX;
mpiError = MPI_Isend(&sendSizes[index], numDataToSend, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
// Send data
if (sendSizes[index] > 0 && sendSizes[index] != UINT64_MAX) {
MPI_Request request;
Assert(sendBuffer.size() < INT_MAX);
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag1,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Recv data size and data
for (UINT numWaits = 0; numWaits < numRecv; numWaits++) {
// Wait for a data size to arrive
int index;
mpiError = MPI_Waitany(mpiRecvRequests.size(), mpiRecvRequests.data(),
&index, MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
// Recv data
if (recvSizes[index] > 0 && recvSizes[index] != UINT64_MAX) {
int adjRank = c_adjRankIndexToRank[index];
int tag1 = 1;
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvSizes[index]);
mpiError = MPI_Recv(&dataPackets[originalSize], recvSizes[index],
MPI_BYTE, adjRank, tag1, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
// Stop communication with this rank
if (recvSizes[index] == UINT64_MAX) {
commDark[index] = true;
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
GraphTraverser
If doComm is true, graph traversal is global.
If doComm is false, each mesh partition is traversed locally with no
consideration for boundaries between partitions.
*/
GraphTraverser::GraphTraverser(Direction direction, bool doComm,
UINT dataSizeInBytes)
: c_direction(direction), c_doComm(doComm),
c_dataSizeInBytes(dataSizeInBytes)
{
// Get adjacent ranks
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK &&
c_adjRankToRankIndex.count(adjRank) == 0)
{
UINT rankIndex = c_adjRankIndexToRank.size();
c_adjRankToRankIndex.insert(make_pair(adjRank, rankIndex));
c_adjRankIndexToRank.push_back(adjRank);
}
}}
// Calc num dependencies for each (cell, angle) pair
c_initNumDependencies.resize(g_nAngles, g_nCells);
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
c_initNumDependencies(angle, cell) = 0;
for (UINT face = 0; face < g_nFacePerCell; face++) {
bool incoming = isIncoming(angle, cell, face, c_direction);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (c_doComm && incoming && adjRank != TychoMesh::BAD_RANK) {
c_initNumDependencies(angle, cell)++;
}
else if (!c_doComm && incoming && adjCell != TychoMesh::BOUNDARY_FACE) {
c_initNumDependencies(angle, cell)++;
}
}
}}
}
/*
traverse
Traverses g_tychoMesh.
*/
void GraphTraverser::traverse(const UINT maxComputePerStep,
TraverseData &traverseData)
{
vector<priority_queue<Tuple>> canCompute(g_nThreads);
Mat2<UINT> numDependencies(g_nAngles, g_nCells);
UINT numCellAnglePairsToCalculate = g_nAngles * g_nCells;
Mat2<vector<char>> sendBuffers;
vector<vector<char>> sendBuffers1;
vector<bool> commDark;
Timer totalTimer;
Timer setupTimer;
Timer commTimer;
Timer sendTimer;
Timer recvTimer;
// Start total timer
totalTimer.start();
setupTimer.start();
// Calc num dependencies for each (cell, angle) pair
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
numDependencies(angle, cell) = c_initNumDependencies(angle, cell);
}}
// Set size of sendBuffers and commDark
UINT numAdjRanks = c_adjRankIndexToRank.size();
sendBuffers.resize(g_nThreads, numAdjRanks);
sendBuffers1.resize(numAdjRanks);
commDark.resize(numAdjRanks, false);
// Initialize canCompute queue
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
UINT angleGroup = angleGroupIndex(angle);
canCompute[angleGroup].push(Tuple(cell, angle, priority));
}
}}
// End setup timer
setupTimer.stop();
// Traverse the graph
while (numCellAnglePairsToCalculate > 0) {
// Do local traversal
#pragma omp parallel
{
UINT stepsTaken = 0;
UINT angleGroup = omp_get_thread_num();
while (canCompute[angleGroup].size() > 0 &&
stepsTaken < maxComputePerStep)
{
// Get cell/angle pair to compute
Tuple cellAnglePair = canCompute[angleGroup].top();
canCompute[angleGroup].pop();
UINT cell = cellAnglePair.getCell();
UINT angle = cellAnglePair.getAngle();
stepsTaken++;
#pragma omp atomic
numCellAnglePairsToCalculate--;
// Get boundary type and adjacent cell/side data for each face
BoundaryType bdryType[g_nFacePerCell];
UINT adjCellsSides[g_nFacePerCell];
bool isOutgoingWrtDirection[g_nFacePerCell];
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
adjCellsSides[face] = adjCell;
if (g_tychoMesh->isOutgoing(angle, cell, face)) {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutExtBdry;
}
else {
bdryType[face] = BoundaryType_OutInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = true;
}
else {
isOutgoingWrtDirection[face] = false;
}
}
else {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InExtBdry;
}
else {
bdryType[face] = BoundaryType_InInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = false;
}
else {
isOutgoingWrtDirection[face] = true;
}
}
}
// Update data for this cell-angle pair
traverseData.update(cell, angle, adjCellsSides, bdryType);
// Update dependency for children
for (UINT face = 0; face < g_nFacePerCell; face++) {
if (isOutgoingWrtDirection[face]) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
if (adjCell != TychoMesh::BOUNDARY_FACE) {
numDependencies(angle, adjCell)--;
if (numDependencies(angle, adjCell) == 0) {
UINT priority =
traverseData.getPriority(adjCell, angle);
Tuple tuple(adjCell, angle, priority);
canCompute[angleGroup].push(tuple);
}
}
else if (c_doComm && adjRank != TychoMesh::BAD_RANK) {
UINT rankIndex = c_adjRankToRankIndex.at(adjRank);
UINT side = g_tychoMesh->getSide(cell, face);
UINT globalSide = g_tychoMesh->getLGSide(side);
vector<char> packet;
createPacket(packet, globalSide, angle,
c_dataSizeInBytes,
traverseData.getData(cell, face, angle));
sendBuffers(angleGroup, rankIndex).insert(
sendBuffers(angleGroup, rankIndex).end(),
packet.begin(), packet.end());
}
}
}
}
}
// Put together sendBuffers from different angleGroups
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].insert(
sendBuffers1[rankIndex].end(),
sendBuffers(angleGroup, rankIndex).begin(),
sendBuffers(angleGroup, rankIndex).end());
}}
// Do communication
commTimer.start();
if (c_doComm) {
// Send/Recv
UINT packetSizeInBytes = 2 * sizeof(UINT) + c_dataSizeInBytes;
vector<char> dataPackets;
if (g_mpiType == MPIType_TychoTwoSided) {
const bool killComm = false;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
else if (g_mpiType == MPIType_CapsaicinTwoSided) {
sendTimer.start();
sendData2Sided(sendBuffers1);
sendTimer.stop();
recvTimer.start();
recvData2Sided(dataPackets);
recvTimer.stop();
}
else {
Insist(false, "MPI type not recognized.");
}
// Clear send buffers for next iteration
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers(angleGroup, rankIndex).clear();
}}
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].clear();
}
// Unpack packets
UINT numPackets = dataPackets.size() / packetSizeInBytes;
Assert(dataPackets.size() % packetSizeInBytes == 0);
for (UINT i = 0; i < numPackets; i++) {
char *packet = &dataPackets[i * packetSizeInBytes];
UINT globalSide;
UINT angle;
char *packetData;
splitPacket(packet, globalSide, angle, &packetData);
UINT localSide = g_tychoMesh->getGLSide(globalSide);
traverseData.setSideData(localSide, angle, packetData);
UINT cell = g_tychoMesh->getSideCell(localSide);
numDependencies(angle, cell)--;
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
Tuple tuple(cell, angle, priority);
canCompute[angleGroupIndex(angle)].push(tuple);
}
}
}
commTimer.stop();
}
// Send kill comm signal to adjacent ranks
if (g_mpiType == MPIType_TychoTwoSided) {
commTimer.start();
if (c_doComm) {
vector<char> dataPackets;
const bool killComm = true;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
commTimer.stop();
}
// Print times
totalTimer.stop();
double totalTime = totalTimer.wall_clock();
Comm::gmax(totalTime);
double setupTime = setupTimer.wall_clock();
Comm::gmax(setupTime);
double commTime = commTimer.sum_wall_clock();
Comm::gmax(commTime);
double sendTime = sendTimer.sum_wall_clock();
Comm::gmax(sendTime);
double recvTime = recvTimer.sum_wall_clock();
Comm::gmax(recvTime);
if (Comm::rank() == 0) {
printf(" Traverse Timer (comm): %fs\n", commTime);
printf(" Traverse Timer (send): %fs\n", sendTime);
printf(" Traverse Timer (recv): %fs\n", recvTime);
printf(" Traverse Timer (setup): %fs\n", setupTime);
printf(" Traverse Timer (total): %fs\n", totalTime);
}
}
| 34.389253 | 84 | 0.548725 | berselius |
d5e9f464b23a5a84da88b2d7b6ac621cb6f56c51 | 5,131 | hpp | C++ | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | 10 | 2015-01-26T16:30:04.000Z | 2022-03-16T14:37:31.000Z | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | null | null | null | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | null | null | null | // This code is put in the public domain by Andrei Alexandrescu
// See http://www.reddit.com/r/programming/comments/14m1tc/andrei_alexandrescu_systematic_error_handling_in/c7etk47
// Some edits by Alexander Kondratskiy.
#ifndef EXPECTED_HPP_TN6DJT51
#define EXPECTED_HPP_TN6DJT51
#include <stdexcept>
#include <algorithm>
template <class T>
class Expected {
union {
std::exception_ptr spam;
T ham;
};
bool gotHam;
Expected() {
// used by fromException below
}
public:
Expected(const T& rhs) : ham(rhs), gotHam(true) {}
Expected(T&& rhs) : ham(std::move(rhs)), gotHam(true) {}
Expected(const Expected& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(rhs.ham);
else new(&spam) std::exception_ptr(rhs.spam);
}
Expected(Expected&& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(std::move(rhs.ham));
else new(&spam) std::exception_ptr(std::move(rhs.spam));
}
void swap(Expected& rhs) {
if (gotHam) {
if (rhs.gotHam) {
using std::swap;
swap(ham, rhs.ham);
} else {
auto t = std::move(rhs.spam);
new(&rhs.ham) T(std::move(ham));
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<T> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (gotHam) ham.~T();
else spam.~exception_ptr();
}
static Expected<T> fromException(std::exception_ptr p) {
Expected<T> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<T> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<T>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<T> fromException() {
return fromException(std::current_exception());
}
template <class U>
static Expected<T> transferException(Expected<U> const& other) {
if (other.valid()) {
throw std::invalid_argument(
"Expected<T>::transferException: other Expected<U> does not contain an exception.");
}
return fromException(other.spam);
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator T&() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
T& get() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
const T& get() const {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
return Expected(fun());
} catch (...) {
return fromException();
}
}
};
// TODO: clean this up
template <>
class Expected<void> {
std::exception_ptr spam;
bool gotHam;
public:
Expected() : gotHam(true) { }
void swap(Expected& rhs) {
if (gotHam) {
if (!rhs.gotHam) {
auto t = std::move(rhs.spam);
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<void> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (!gotHam) spam.~exception_ptr();
}
static Expected<void> fromException(std::exception_ptr p) {
Expected<void> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<void> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<void>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<void> fromException() {
return fromException(std::current_exception());
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator void() {
if (!gotHam) std::rethrow_exception(spam);
}
void get() const {
if (!gotHam) std::rethrow_exception(spam);
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
fun();
return Expected();
} catch (...) {
return fromException();
}
}
};
#endif /* end of include guard: EXPECTED_HPP_TN6DJT51 */
| 21.834043 | 115 | 0.603391 | KholdStare |
d5eb345505ba75f1c5e48d9d375bb67bc53df562 | 666 | cpp | C++ | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 190 | 2021-02-10T17:01:01.000Z | 2022-03-20T00:21:43.000Z | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | null | null | null | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 27 | 2021-03-26T11:35:15.000Z | 2022-03-06T07:34:54.000Z | #include<bits/stdc++.h>
using namespace std;
/*
problem is similar as finding first occurrence
because array is binary and sorted so,
if we find first occurrence of 1, then subtract it from
last index to find count.
*/
int count1s(int a[], int n)//time comp. O(logn)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == 0)
{
low = mid + 1;
}
else
{
if (mid == 0 or a[mid - 1] != a[mid])
{
return (n - mid);
}
else
{
high = mid - 1;
}
}
}
return 0;
}
int main()
{
int a[] = {0, 0, 0, 0, 1, 1, 1};
int n = sizeof(a) / sizeof(int);
cout << count1s(a, n);
return 0;
} | 14.478261 | 55 | 0.545045 | VivekYadav105 |
d5ed8afbb7ae6ba5c91700484eaab897dc2e03ee | 1,040 | cpp | C++ | 10591 Happy Number.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 10591 Happy Number.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 10591 Happy Number.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <iostream>
using namespace std;
enum Status {Unchecked, Checking, IsHappy, NotHappy };
const int HIGHEST = 1000;
Status numbers[HIGHEST];
inline int nextNum(int num)
{
int ret = 0;
while (num)
{
ret += (num % 10) * (num % 10);
num /= 10;
}
return ret;
}
bool isHappy(int num)
{
num = nextNum(num);
if (numbers[num] == Unchecked)
{
numbers[num] = Checking;
bool is = isHappy(num);
numbers[num] = (is ? IsHappy : NotHappy);
}
else if (numbers[num] == Checking)
return false;
return numbers[num] == IsHappy;
}
int main()
{
for (int i = 0; i < HIGHEST; ++i)
numbers[i] = Unchecked;
numbers[1] = IsHappy;
int T;
cin >> T;
for (int t = 1; t <= T; ++t)
{
int num;
cin >> num;
if (isHappy(num))
cout << "Case #" << t << ": " << num << " is a Happy number.\n";
else
cout << "Case #" << t << ": " << num << " is an Unhappy number.\n";
}
}
| 17.333333 | 79 | 0.4875 | zihadboss |
d5f2a4b8dd5f721a7cd9705db193fe2302c6188b | 5,060 | cpp | C++ | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// error_simulation.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
/*
#define DEBUG_DEBUG
*/
#include <ulib/base/utility.h>
#include <ulib/debug/error_simulation.h>
bool USimulationError::flag_init;
char* USimulationError::file_mem;
uint32_t USimulationError::file_size;
union uuvararg USimulationError::var_arg;
/**
* #if defined(HAVE_STRTOF) && !defined(strtof)
* extern "C" { float strtof(const char* nptr, char** endptr); }
* #endif
* #if defined(HAVE_STRTOLD) && !defined(strtold)
* extern "C" { long double strtold(const char* nptr, char** endptr); }
* #endif
*/
void USimulationError::init()
{
U_INTERNAL_TRACE("USimulationError::init()")
int fd = 0;
char* env = getenv("USIMERR");
char file[MAX_FILENAME_LEN];
if ( env &&
*env)
{
flag_init = true;
// format: <file_error_simulation>
// error.sim
(void) sscanf(env, "%254s", file);
fd = open(file, O_RDONLY | O_BINARY, 0666);
if (fd != -1)
{
struct stat st;
if (fstat(fd, &st) == 0)
{
file_size = st.st_size;
if (file_size)
{
file_mem = (char*) mmap(0, file_size, PROT_READ, MAP_SHARED, fd, 0);
if (file_mem == MAP_FAILED) file_size = 0;
}
}
(void) close(fd);
}
}
if (fd <= 0)
{
U_MESSAGE("SIMERR%W<%Woff%W>%W", YELLOW, RED, YELLOW, RESET);
}
else
{
U_MESSAGE("SIMERR%W<%Won%W>: File<%W%s%W>%W", YELLOW, GREEN, YELLOW, CYAN, file, YELLOW, RESET);
}
}
void* USimulationError::checkForMatch(const char* call_name)
{
U_INTERNAL_TRACE("USimulationError::checkForMatch(%s)", call_name);
if (flag_init &&
file_size)
{
const char* ptr = call_name;
while (*ptr && *ptr != '(') ++ptr;
if (*ptr == '(')
{
int len = ptr - call_name;
char* limit = file_mem + file_size - len;
char* file_ptr = file_mem;
// format: <classname>::method <random range> <return type> <return value> <errno value>
// ::lstat 10 i -1 13
bool match = false;
for (; file_ptr <= limit; ++file_ptr)
{
while (u__isspace(*file_ptr)) ++file_ptr;
if (*file_ptr != '#')
{
while (u__isspace(*file_ptr)) ++file_ptr;
U_INTERNAL_PRINT("file_ptr = %.*s", len, file_ptr);
if (u__isspace(file_ptr[len]) &&
memcmp(file_ptr, call_name, len) == 0)
{
match = true;
file_ptr += len;
// manage random testing
uint32_t range = (uint32_t) strtol(file_ptr, &file_ptr, 10);
if (range > 0) match = (u_get_num_random(range) == (range / 2));
break;
}
}
while (*file_ptr != '\n') ++file_ptr;
}
if (match)
{
while (u__isspace(*file_ptr)) ++file_ptr;
char type = *file_ptr++;
switch (type)
{
case 'p': // pointer
{
var_arg.p = (void*) strtol(file_ptr, &file_ptr, 16);
}
break;
case 'l': // long
{
var_arg.l = strtol(file_ptr, &file_ptr, 10);
}
break;
case 'L': // long long
{
# ifdef HAVE_STRTOULL
var_arg.ll = (long long) strtoull(file_ptr, &file_ptr, 10);
# endif
}
break;
case 'f': // float
{
# ifdef HAVE_STRTOF
var_arg.f = strtof(file_ptr, &file_ptr);
# endif
}
break;
case 'd': // double
{
var_arg.d = strtod(file_ptr, &file_ptr);
}
break;
case 'D': // long double
{
# ifdef HAVE_STRTOLD
var_arg.ld = strtold(file_ptr, &file_ptr);
# endif
}
break;
case 'i': // word-size (int)
default:
{
var_arg.i = (int) strtol(file_ptr, &file_ptr, 10);
}
break;
}
errno = atoi(file_ptr);
U_INTERNAL_PRINT("errno = %d var_arg = %d", errno, var_arg.i);
return &var_arg;
}
}
}
return 0;
}
| 24.444444 | 102 | 0.422925 | liftchampion |
d5f3557e2fdaab5141eaa5f83dc185801c3a2a1c | 5,393 | cpp | C++ | Blaze/logger.cpp | Star-Athenaeum/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 1 | 2021-09-29T21:54:54.000Z | 2021-09-29T21:54:54.000Z | Blaze/logger.cpp | Star-Athenaeum/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 44 | 2020-04-17T14:39:36.000Z | 2020-10-14T04:15:48.000Z | Blaze/logger.cpp | Stryxus/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 1 | 2020-09-30T22:56:48.000Z | 2020-09-30T22:56:48.000Z | #include "pch.hpp"
#include "logger.hpp"
bool Logger::is_using_custom_color = false;
Logger::COLOR Logger::global_foregronnd_color = COLOR::BRIGHT_WHITE_FOREGROUND;
void Logger::log_info(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_info(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_nl(int amount)
{
if (amount < 1) amount = 1;
for (int i = 0; i < amount; i++) printf("\n");
}
void Logger::log_divide()
{
string divide = "";
for (int i = 0; i < get_console_buffer_width() - 1; i++) divide += "-";
printf(string("\n" + divide).c_str());
}
void Logger::set_global_foreground_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
global_foregronnd_color = color;
}
/*
void Logger::set_global_background_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
*/
void Logger::set_console_color(COLOR color)
{
is_using_custom_color = true;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::clear_console_color()
{
is_using_custom_color = false;
}
void Logger::set_console_color_internal(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::flush_log_buffer()
{
COORD tl = { 0,0 };
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written = 0;
DWORD cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, ' ', cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
}
void Logger::log_last_error()
{
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
string message(messageBuffer, size);
LocalFree(messageBuffer);
Logger::log_error(message);
}
void Logger::wait()
{
char c;
cin >> std::noskipws;
while (cin >> c) cout << c << std::endl;
}
string Logger::get_date_time_string()
{
time_t now = cr::system_clock::to_time_t(cr::system_clock::now());
tm current_time{};
localtime_s(¤t_time, &now);
string year = to_string(1900 + current_time.tm_year);
string month = current_time.tm_mon > 8 ? to_string(1 + current_time.tm_mon) : "0" + to_string(1 + current_time.tm_mon);
string day = current_time.tm_mday > 8 ? to_string(1 + current_time.tm_mday) : "0" + to_string(1 + current_time.tm_mday);
string hour = current_time.tm_hour != 60 ? current_time.tm_hour > 8 ? to_string(1 + current_time.tm_hour) : "0" + to_string(1 + current_time.tm_hour) : "00";
string minute = current_time.tm_min != 60 ? current_time.tm_min > 8 ? to_string(1 + current_time.tm_min) : "0" + to_string(1 + current_time.tm_min) : "00";
string second = current_time.tm_sec != 60 ? current_time.tm_sec > 8 ? to_string(1 + current_time.tm_sec) : "0" + to_string(1 + current_time.tm_sec) : "00";
string millisecond = to_string((cr::duration_cast<cr::milliseconds>(cr::system_clock::now().time_since_epoch())).count()).substr(10);
return "[" + year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second + "." + millisecond + "]";
}
wstring Logger::get_date_time_wstring()
{
return string_to_wstring_copy(get_date_time_string());
}
int Logger::get_console_buffer_width()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
} | 36.194631 | 220 | 0.749676 | Star-Athenaeum |
d5f7b9bc02d182192c18faf987c2f68cf1eeb6df | 20,947 | cpp | C++ | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 6 | 2021-09-17T01:33:23.000Z | 2022-03-19T05:13:21.000Z | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 1 | 2021-09-17T02:03:02.000Z | 2021-09-17T02:03:02.000Z | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 4 | 2021-09-17T01:33:32.000Z | 2021-09-29T05:12:23.000Z | #include "includes.h"
#define OBF_BEGIN try { obf::next_step __crv = obf::next_step::ns_done; std::shared_ptr<obf::base_rvholder> __rvlocal;
// Data
static LPDIRECT3D9 g_pD3D = NULL;
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp = {};
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void ResetDevice();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool frameRounding = true;
float GUI_Color[4] = { 1.000f, 0.137f, 1.000f, 1.000f };
bool otherBG = true;
namespace features {
int window_key = 45; // insert
bool hideWindow = false;
}
namespace helpers {
// Keymap
const char* keys[256] = {
"",
"",
"",
"",
"",
"MOUSE4",
"MOUSE5",
"",
"BACKSPACE",
"TAB",
"",
"",
"CLEAR",
"ENTER",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"SPACE",
"PGUP",
"PGDOWN",
"END",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"INSERT",
"DELETE",
"",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"",
"",
"",
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"",
"",
"",
"",
"",
"NUM0",
"NUM1",
"NUM2",
"NUM3",
"NUM4",
"NUM5",
"NUM6",
"NUM7",
"NUM8",
"NUM9",
"MULTIPLY",
"ADD",
"SEPARATOR",
"SUBTRACT",
"DECIMAL",
"DIVIDE",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"F13",
"F14",
"F15",
"F16",
"F17",
"F18",
"F19",
"F20",
"F21",
"F22",
"F23",
"F24",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"LSHIFT",
"RSHIFT",
"LCONTROL",
"RCONTROL",
"LMENU",
"RMENU",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"COMMA",
"MINUS",
"PERIOD",
"SLASH",
"TILDA",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"[",
"|",
"]",
"QUOTE",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
};
//
// Gets current key down and returns it
//
int getKeybind()
{
int i = 0;
int n = 0;
while (n == 0) {
for (i = 3; i < 256; i++)
{
if (GetAsyncKeyState((i)))
{
if (i < 256) {
if (!(*keys[i] == 0)) {
n = 1;
return i;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
//
// check if the key is down.
//
bool keyCheck(int key)
{
for (int t = 3; t < 256; t++)
{
if (GetAsyncKeyState(t))
{
if ((keys[key] == keys[t]) & (keys[key] != 0 & keys[t] != 0))
{
return true;
//std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
}
return false;
}
static auto generate_random_float = [](float min, float max) {
float random = ((float)rand()) / (float)RAND_MAX;
float diff = max - min;
float r = random * diff;
return min + r;
};
//
// Implement this as a thread
// takes in a key and a reference to a bool to toggle on or off
// if they key you put in is true it toggles the bool you passed in.
//
void checkThread(int key, bool& toggle)
{
auto future = std::async(helpers::keyCheck, key);
if (future.get()) {
toggle = !toggle;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
}
// Side Panel State
int sidePanel = 0;
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T(" "), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T(" "), WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 500, 335, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Light_compressed_data, Ubuntu_Light_compressed_size, 20);
io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Regular_compressed_data, Ubuntu_Regular_compressed_size, 18);
std::thread clickerThread(features::clickerThread);
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX9_Init(g_pd3dDevice);
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (!features::hideWindow) {
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
else {
// Show the window
::ShowWindow(hwnd, SW_HIDE);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
{
// press the - on Visual Studio to Ignore
{
ImColor mainColor = ImColor(GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3]);
ImColor bodyColor = ImColor(int(24), int(24), int(24), 255);
ImColor fontColor = ImColor(int(255), int(255), int(255), 255);
ImGuiStyle& style = ImGui::GetStyle();
ImVec4 mainColorHovered = ImVec4(mainColor.Value.x + 0.1f, mainColor.Value.y + 0.1f, mainColor.Value.z + 0.1f, mainColor.Value.w);
ImVec4 mainColorActive = ImVec4(mainColor.Value.x + 0.2f, mainColor.Value.y + 0.2f, mainColor.Value.z + 0.2f, mainColor.Value.w);
ImVec4 menubarColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w - 0.8f);
ImVec4 frameBgColor = ImVec4(bodyColor.Value.x + 0.1f, bodyColor.Value.y + 0.1f, bodyColor.Value.z + 0.1f, bodyColor.Value.w + .1f);
ImVec4 tooltipBgColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w + .05f);
style.Alpha = 1.0f;
style.WindowPadding = ImVec2(8, 8);
style.WindowMinSize = ImVec2(32, 32);
style.WindowRounding = 0.0f;
style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
style.ChildRounding = 0.0f;
style.FramePadding = ImVec2(4, 3);
style.FrameRounding = 0.0f;
style.ItemSpacing = ImVec2(4, 3);
style.ItemInnerSpacing = ImVec2(4, 4);
style.TouchExtraPadding = ImVec2(0, 0);
style.IndentSpacing = 21.0f;
style.ColumnsMinSpacing = 3.0f;
style.ScrollbarSize = 8.f;
style.ScrollbarRounding = 0.0f;
style.GrabMinSize = 1.0f;
style.GrabRounding = 0.0f;
style.ButtonTextAlign = ImVec2(0.5f, 0.5f);
style.DisplayWindowPadding = ImVec2(22, 22);
style.DisplaySafeAreaPadding = ImVec2(4, 4);
style.AntiAliasedLines = true;
style.CurveTessellationTol = 1.25f;
style.Colors[ImGuiCol_Text] = fontColor;
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = bodyColor;
style.Colors[ImGuiCol_ChildBg] = ImVec4(.0f, .0f, .0f, .0f);
style.Colors[ImGuiCol_PopupBg] = tooltipBgColor;
style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f);
style.Colors[ImGuiCol_FrameBg] = frameBgColor;
style.Colors[ImGuiCol_FrameBgHovered] = mainColorHovered;
style.Colors[ImGuiCol_FrameBgActive] = mainColorActive;
style.Colors[ImGuiCol_TitleBg] = mainColor;
style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f);
style.Colors[ImGuiCol_TitleBgActive] = mainColor;
style.Colors[ImGuiCol_MenuBarBg] = menubarColor;
style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(frameBgColor.x + .05f, frameBgColor.y + .05f, frameBgColor.z + .05f, frameBgColor.w);
style.Colors[ImGuiCol_ScrollbarGrab] = mainColor;
style.Colors[ImGuiCol_ScrollbarGrabHovered] = mainColorHovered;
style.Colors[ImGuiCol_ScrollbarGrabActive] = mainColorActive;
style.Colors[ImGuiCol_CheckMark] = mainColor;
style.Colors[ImGuiCol_SliderGrab] = mainColorHovered;
style.Colors[ImGuiCol_SliderGrabActive] = mainColorActive;
style.Colors[ImGuiCol_Button] = mainColor;
style.Colors[ImGuiCol_ButtonHovered] = mainColorHovered;
style.Colors[ImGuiCol_ButtonActive] = mainColorActive;
style.Colors[ImGuiCol_Header] = mainColor;
style.Colors[ImGuiCol_HeaderHovered] = mainColorHovered;
style.Colors[ImGuiCol_HeaderActive] = mainColorActive;
style.Colors[ImGuiCol_ResizeGrip] = mainColor;
style.Colors[ImGuiCol_ResizeGripHovered] = mainColorHovered;
style.Colors[ImGuiCol_ResizeGripActive] = mainColorActive;
style.Colors[ImGuiCol_PlotLines] = mainColor;
style.Colors[ImGuiCol_PlotLinesHovered] = mainColorHovered;
style.Colors[ImGuiCol_PlotHistogram] = mainColor;
style.Colors[ImGuiCol_PlotHistogramHovered] = mainColorHovered;
style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f);
}
// check if the keys down for keybinds
helpers::checkThread(features::left_key, features::CLICKER_TOGGLED);
helpers::checkThread(features::right_key, features::rCLICKER_TOGGLED);
helpers::checkThread(features::window_key, features::hideWindow);
// check for frame rounding
if (frameRounding) {
ImGui::GetStyle().FrameRounding = 4.0f;
ImGui::GetStyle().GrabRounding = 3.0f;
}
else { // we do da java
ImGui::GetStyle().FrameRounding = 0.0f;
ImGui::GetStyle().GrabRounding = 0.0f;
}
// Actuall stuff
// Setup tings
ImGui::Begin(xorstr_(" "), NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowSize({ 500, 0 });
ImGui::SetWindowPos({ 0, 0 });
ImGui::End();
// Left Shit
ImGui::Begin(xorstr_("SidePanel"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ -5, -5 });
ImGui::SetWindowSize({ 125, 515 });
ImGui::Text(xorstr_("Vega - Clicker"));
if (ImGui::Button(xorstr_("Clicker"), { 100, 50 })) sidePanel = 0;
if (ImGui::Button(xorstr_("Misc"), { 100, 50 })) sidePanel = 1;
//if (ImGui::Button(xorstr_("Config"), { 100, 50 })) sidePanel = 2;
if (ImGui::Button(xorstr_("Settings"), { 100, 50 })) sidePanel = 3;
ImGui::End();
}
// For drawing the gui
ImGui::Begin(xorstr_("Canvas"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ 115, 5 });
ImGui::SetWindowSize({ 450, 350 });
if (sidePanel == 0) {
// Left
ImGui::Checkbox(xorstr_("Left Toggle"), &features::CLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Left Bind"))) { features::left_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::left_key]);
// drag clicker not done
//if (!features::lDrag) {
// ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
// ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand); ImGui::SameLine();
//}
// ImGui::Checkbox(xorstr_("Drag Click"), &features::lDrag);
ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand);
ImGui::NewLine();
// Right
ImGui::Checkbox(xorstr_("Right Toggle"), &features::rCLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Right Bind"))) { features::right_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::right_key]);
ImGui::SliderFloat(xorstr_("R CPS"), &features::rCPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand "), &features::rExtraRand);
}
if (sidePanel == 1) {
ImGui::Checkbox(xorstr_("Block Hit"), &features::BLOCKHIT); ImGui::SameLine(); ImGui::BulletText(xorstr_("Note: This is only for Left Click"));
ImGui::SliderInt(xorstr_(" "), &features::BLOCK_CHANCE, 1, 25, "%d Chance");
}
if (sidePanel == 2) {
ImGui::Text(xorstr_("NOTHING YET - Configs"));
}
// Settings Tab
if (sidePanel == 3) {
ImGui::ColorEdit4(xorstr_(" "), GUI_Color, ImGuiColorEditFlags_NoBorder | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoPicker);
ImGui::Checkbox(xorstr_("Other Background"), &otherBG); ImGui::SameLine(); ImGui::Checkbox(xorstr_("Rounding"), &frameRounding);
ImGui::Text(xorstr_("Application average %.3f ms/frame (%.1f FPS)"),
1000.0 / double(ImGui::GetIO().Framerate), double(ImGui::GetIO().Framerate));
ImGui::Text(xorstr_("Hide Window: ")); ImGui::SameLine();
if (ImGui::Button(xorstr_("Bind"))) { features::window_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::window_key]);
ImGui::NewLine();
ImGui::Text(xorstr_("Vega - Clicker V2.5\nLGBTQHIV+-123456789 Edition"));
}
ImGui::End();
}
ImGui::Begin(xorstr_("DrawList"), NULL, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowPos({ 0, 0 });
ImGui::SetWindowSize({ 800, 800 });
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddLine({ 107, 0 }, { 107, 400 }, ImGui::GetColorU32(ImVec4{ GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3] }), 3);
ImGui::End();
}
// Rendering (dont touch)
ImGui::EndFrame();
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
D3DCOLOR clear_col_dx;
if (otherBG) clear_col_dx = D3DCOLOR_RGBA((int)(12), (int)(22), (int)(28), (int)(255));
else clear_col_dx = D3DCOLOR_RGBA((int)(27), (int)(22), (int)(22), (int)(255));
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
if (g_pd3dDevice->BeginScene() >= 0)
{
ImGui::Render();
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
g_pd3dDevice->EndScene();
}
HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
// Handle loss of D3D9 device
if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
ResetDevice();
}
clickerThread.detach();
ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
return false;
// Create the D3DDevice
ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
g_d3dpp.Windowed = TRUE;
g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
g_d3dpp.EnableAutoDepthStencil = TRUE;
g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
//g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
return false;
return true;
}
void CleanupDeviceD3D()
{
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; }
}
void ResetDevice()
{
ImGui_ImplDX9_InvalidateDeviceObjects();
HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
if (hr == D3DERR_INVALIDCALL)
IM_ASSERT(0);
ImGui_ImplDX9_CreateDeviceObjects();
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
g_d3dpp.BackBufferWidth = LOWORD(lParam);
g_d3dpp.BackBufferHeight = HIWORD(lParam);
ResetDevice();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
#define OBF_END } catch(std::shared_ptr<obf::base_rvholder>& r) { return *r; } catch (...) {throw;}
| 29.881598 | 263 | 0.532009 | qualk |
d5fa1d60b0d0efac056ab516c51fc4448961e201 | 4,555 | cpp | C++ | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 1 | 2021-01-28T18:36:35.000Z | 2021-01-28T18:36:35.000Z | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 2 | 2020-12-09T19:52:34.000Z | 2022-03-21T12:11:08.000Z | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 11 | 2020-11-11T16:55:57.000Z | 2022-03-28T13:46:57.000Z | #include "Affichage4DigitsBase.h"
#include "OptimiserEntreesSorties.h"
static const byte valeurSegments[] = {
// Segements ABCDEFGP
0b11111100, // 0 '0' AAA
0b01100000, // 1 '1' F B
0b11011010, // 2 '2' F B
0b11110010, // 3 '3' GGG
0b01100110, // 4 '4' E C
0b10110110, // 5 '5' E C
0b10111110, // 6 '6' DDD P
0b11100000, // 7 '7'
0b11111110, // 8 '8'
0b11110110, // 9 '9'
0b11101110, // 10 'A'
0b00111110, // 11 'b'
0b10011100, // 12 'C'
0b01111010, // 13 'd'
0b10011110, // 14 'E'
0b10001110, // 15 'F'
0b00000010, // 16 '-'
0b00000000, // 17 ' '
0b10000000, // 18 '¨' Trop grand
0b00010000, // 19 '_' Trop petit
};
static const int nombreConfigurations = sizeof(valeurSegments);
static const int blanc = 17;
static const int tropGrand = 18;
static const int tropPetit = 19;
static const int moins = 16;
Affichage4DigitsBase::Affichage4DigitsBase(const int &p_pinD1, const int &p_pinD2, const int &p_pinD3, const int &p_pinD4, const bool &p_cathodeCommune)
: m_pinD{p_pinD1, p_pinD2, p_pinD3, p_pinD4}
{
if (p_cathodeCommune)
{
this->m_digitOff = HIGH;
this->m_digitOn = LOW;
this->m_segmentOff = LOW;
this->m_segmentOn = HIGH;
}
else
{
this->m_digitOff = LOW;
this->m_digitOn = HIGH;
this->m_segmentOff = HIGH;
this->m_segmentOn = LOW;
}
for (size_t digitIndex = 0; digitIndex < 4; digitIndex++)
{
pinMode(this->m_pinD[digitIndex], OUTPUT);
}
}
const byte valeurSegmentTropGrand = valeurSegments[tropGrand];
const byte valeurSegmentTropPetit = valeurSegments[tropPetit];
const byte valeurSegmentBlanc = valeurSegments[blanc];
const byte valeurSegmentMoins = valeurSegments[moins];
// Affichage des 4 digits en 4 cycle d'appel et utilisation d'une cache
// Idées cache et afficher digit / digit prises de la très bonne vidéo de Cyrob : https://www.youtube.com/watch?v=CS4t0j1yzH0
void Affichage4DigitsBase::Afficher(const int &p_valeur, const int &p_base) const
{
if (p_valeur != this->m_valeurCache || p_base != this->m_baseCache)
{
this->m_valeurCache = p_valeur;
this->m_baseCache = p_base;
if (p_base == DEC && p_valeur > 9999)
{
this->m_cache[0] = valeurSegmentTropGrand;
this->m_cache[1] = valeurSegmentTropGrand;
this->m_cache[2] = valeurSegmentTropGrand;
this->m_cache[3] = valeurSegmentTropGrand;
}
else if (p_base == DEC && p_valeur < -999)
{
this->m_cache[0] = valeurSegmentTropPetit;
this->m_cache[1] = valeurSegmentTropPetit;
this->m_cache[2] = valeurSegmentTropPetit;
this->m_cache[3] = valeurSegmentTropPetit;
}
else
{
switch (p_base)
{
case HEX:
this->m_cache[0] = valeurSegments[(byte)(p_valeur >> 12 & 0x0F)];
this->m_cache[1] = valeurSegments[(byte)((p_valeur >> 8) & 0x0F)];
this->m_cache[2] = valeurSegments[(byte)((p_valeur >> 4) & 0x0F)];
this->m_cache[3] = valeurSegments[(byte)(p_valeur & 0x0F)];
break;
case DEC: // par défault décimale. Autres bases non gérées.
default:
{
int valeur = p_valeur < 0 ? -p_valeur : p_valeur;
int index = 3;
while (valeur != 0 && index >= 0)
{
this->m_cache[index] = valeurSegments[valeur % 10];
valeur /= 10;
--index;
}
while (index >= 0)
{
this->m_cache[index] = valeurSegmentBlanc;
--index;
}
if (p_valeur < 0)
{
this->m_cache[0] = valeurSegmentMoins;
}
}
break;
}
}
}
}
void Affichage4DigitsBase::Executer() const
{
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOff);
++this->m_digitCourant;
#if !OPTIMISE_MODULO
this->m_digitCourant %= 4;
#else
if (this->m_digitCourant > 3)
{
this->m_digitCourant = 0;
}
#endif
this->EnvoyerValeur(this->m_cache[this->m_digitCourant]);
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOn);
}
| 31.19863 | 152 | 0.554336 | monkTrapist |
91067fa19469909ffe22bf89389e71dae6d1be7e | 2,372 | hpp | C++ | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | // Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#ifndef ITL_ASYNC_EXECUTOR_INCLUDE
#define ITL_ASYNC_EXECUTOR_INCLUDE
#include <thread>
#include <boost/numeric/itl/iteration/interruptible_iteration.hpp>
namespace itl {
template <typename Solver>
class async_executor
{
public:
async_executor(const Solver& solver) : my_solver(solver), my_iter(), my_thread() {}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
void start_solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
my_iter.set_iter(iter);
// my_thread= std::thread(&Solver::solve, &my_solver, b, x, my_iter);
my_thread= std::thread([this, &x, &b]() { my_solver.solve(x, b, my_iter);});
}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
start_solve(x, b, iter);
return wait();
}
/// Perform one iteration on linear system
template < typename HilbertSpaceX, typename HilbertSpaceB >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b) const
{
itl::basic_iteration<double> iter(x, 1, 0, 0);
return solve(x, b, iter);
}
int wait()
{
my_thread.join();
return my_iter.error_code();
}
bool is_finished() const { return !my_thread.joinable(); }
int interrupt() { my_iter.interrupt(); return wait(); }
private:
Solver my_solver;
mutable interruptible_iteration my_iter;
mutable std::thread my_thread;
};
template <typename Solver>
inline async_executor<Solver> make_async_executor(const Solver& solver)
{
return async_executor<Solver>(solver);
}
} // namespace itl
#endif // ITL_ASYNC_EXECUTOR_INCLUDE
| 30.025316 | 94 | 0.677487 | lit-uriy |
5103455a2ad81cf0f3ed55dad96c5de5ed3414f1 | 18,644 | cpp | C++ | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | 1 | 2021-06-14T15:35:13.000Z | 2021-06-14T15:35:13.000Z | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | null | null | null | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | null | null | null | /*
* ShapeSweepUtils.cpp
* nlivarot
*
* Created by fred on Wed Jun 18 2003.
*
*/
#include "Shape.h"
#include "MyMath.h"
SweepEvent::SweepEvent()
{
MakeNew(NULL,NULL,0,0,0,0);
}
SweepEvent::~SweepEvent(void)
{
MakeDelete();
}
void
SweepEvent::MakeNew(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr)
{
ind=-1;
posx=px;
posy=py;
tl=itl;
tr=itr;
leftSweep=iLeft;
rightSweep=iRight;
leftSweep->rightEvt=this;
rightSweep->leftEvt=this;
}
void
SweepEvent::MakeDelete(void)
{
if ( leftSweep ) {
if ( leftSweep->src->aretes[leftSweep->bord].st < leftSweep->src->aretes[leftSweep->bord].en ) {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].en].pending--;
} else {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].st].pending--;
}
leftSweep->rightEvt=NULL;
}
if ( rightSweep ) {
if ( rightSweep->src->aretes[rightSweep->bord].st < rightSweep->src->aretes[rightSweep->bord].en ) {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].en].pending--;
} else {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].st].pending--;
}
rightSweep->leftEvt=NULL;
}
leftSweep=rightSweep=NULL;
}
void SweepEvent::CreateQueue(SweepEventQueue &queue,int size)
{
queue.nbEvt=0;
queue.maxEvt=size;
queue.events=(SweepEvent*)malloc(queue.maxEvt*sizeof(SweepEvent));
queue.inds=(int*)malloc(queue.maxEvt*sizeof(int));
}
void SweepEvent::DestroyQueue(SweepEventQueue &queue)
{
if ( queue.events ) free(queue.events);
if ( queue.inds ) free(queue.inds);
queue.nbEvt=queue.maxEvt=0;
queue.inds=NULL;
queue.events=NULL;
}
SweepEvent* SweepEvent::AddInQueue(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr,SweepEventQueue &queue)
{
if ( queue.nbEvt >= queue.maxEvt ) return NULL;
int n=queue.nbEvt++;
queue.events[n].MakeNew(iLeft,iRight,px,py,itl,itr);
if ( iLeft->src->aretes[iLeft->bord].st < iLeft->src->aretes[iLeft->bord].en ) {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].en].pending++;
} else {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].st].pending++;
}
if ( iRight->src->aretes[iRight->bord].st < iRight->src->aretes[iRight->bord].en ) {
iRight->src->pData[iRight->src->aretes[iRight->bord].en].pending++;
} else {
iRight->src->pData[iRight->src->aretes[iRight->bord].st].pending++;
}
queue.events[n].ind=n;
queue.inds[n]=n;
int curInd=n;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[n].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=n;
queue.inds[curInd]=no;
} else {
break;
}
curInd=half;
}
return queue.events+n;
}
void SweepEvent::SupprFromQueue(SweepEventQueue &queue)
{
if ( queue.nbEvt <= 1 ) {
MakeDelete();
queue.nbEvt=0;
return;
}
int n=ind;
int to=queue.inds[n];
MakeDelete();
queue.events[--queue.nbEvt].Relocate(queue,to);
int moveInd=queue.nbEvt;
if ( moveInd == n ) return;
to=queue.inds[moveInd];
queue.events[to].ind=n;
queue.inds[n]=to;
int curInd=n;
float px=queue.events[to].posx;
float py=queue.events[to].posy;
bool didClimb=false;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[to].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=to;
queue.inds[curInd]=no;
didClimb=true;
} else {
break;
}
curInd=half;
}
if ( didClimb ) return;
while ( 2*curInd+1 < queue.nbEvt ) {
int son1=2*curInd+1;
int son2=son1+1;
int no1=queue.inds[son1];
int no2=queue.inds[son2];
if ( son2 < queue.nbEvt ) {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
if ( queue.events[no2].posy > queue.events[no1].posy || ( queue.events[no2].posy == queue.events[no1].posy && queue.events[no2].posx > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
curInd=son1;
} else {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
}
} else {
if ( py > queue.events[no2].posy || ( py == queue.events[no2].posy && px > queue.events[no2].posx ) ) {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
} else {
break;
}
}
} else {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
}
break;
}
}
}
bool SweepEvent::PeekInQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
return true;
}
bool SweepEvent::ExtractFromQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
queue.events[queue.inds[0]].SupprFromQueue(queue);
return true;
}
void SweepEvent::Relocate(SweepEventQueue &queue,int to)
{
if ( queue.inds[ind] == to ) return; // j'y suis deja
queue.events[to].posx=posx;
queue.events[to].posy=posy;
queue.events[to].tl=tl;
queue.events[to].tr=tr;
queue.events[to].leftSweep=leftSweep;
queue.events[to].rightSweep=rightSweep;
leftSweep->rightEvt=queue.events+to;
rightSweep->leftEvt=queue.events+to;
queue.events[to].ind=ind;
queue.inds[ind]=to;
}
/*
*
*/
SweepTree::SweepTree(void)
{
src=NULL;
bord=-1;
startPoint=-1;
leftEvt=rightEvt=NULL;
sens=true;
// invDirLength=1;
}
SweepTree::~SweepTree(void)
{
MakeDelete();
}
void
SweepTree::MakeNew(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
AVLTree::MakeNew();
ConvertTo(iSrc,iBord,iWeight,iStartPoint);
}
void
SweepTree::ConvertTo(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
src=iSrc;
bord=iBord;
leftEvt=rightEvt=NULL;
startPoint=iStartPoint;
if ( src->aretes[bord].st < src->aretes[bord].en ) {
if ( iWeight >= 0 ) sens=true; else sens=false;
} else {
if ( iWeight >= 0 ) sens=false; else sens=true;
}
// invDirLength=src->eData[bord].isqlength;
// invDirLength=1/sqrt(src->aretes[bord].dx*src->aretes[bord].dx+src->aretes[bord].dy*src->aretes[bord].dy);
}
void
SweepTree::MakeDelete(void)
{
if ( leftEvt ) {
leftEvt->rightSweep=NULL;
}
if ( rightEvt ) {
rightEvt->leftSweep=NULL;
}
leftEvt=rightEvt=NULL;
AVLTree::MakeDelete();
}
void SweepTree::CreateList(SweepTreeList &list,int size)
{
list.nbTree=0;
list.maxTree=size;
list.trees=(SweepTree*)malloc(list.maxTree*sizeof(SweepTree));
list.racine=NULL;
}
void SweepTree::DestroyList(SweepTreeList &list)
{
if ( list.trees ) free(list.trees);
list.trees=NULL;
list.nbTree=list.maxTree=0;
list.racine=NULL;
}
SweepTree* SweepTree::AddInList(Shape* iSrc,int iBord,int iWeight,int iStartPoint,SweepTreeList &list,Shape* iDst)
{
if ( list.nbTree >= list.maxTree ) return NULL;
int n=list.nbTree++;
list.trees[n].MakeNew(iSrc,iBord,iWeight,iStartPoint);
return list.trees+n;
}
int SweepTree::Find(float px,float py,SweepTree* newOne,SweepTree* &insertL,SweepTree* &insertR,bool sweepSens)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
// if ( startPoint == newOne->startPoint ) {
// y=0;
// } else {
y=Cross(bNorm,diff);
// }
// y*=invDirLength;
if ( fabs(y) < 0.000001 ) {
// prendre en compte les directions
vec2d nNorm;
nNorm.x=newOne->src->eData[newOne->bord].rdx;
nNorm.y=newOne->src->eData[newOne->bord].rdy;
if ( newOne->src->aretes[newOne->bord].st > newOne->src->aretes[newOne->bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
RotCCW(nNorm);
if ( sweepSens ) {
y=Dot(bNorm,nNorm);
} else {
y=Dot(nNorm,bNorm);
}
if ( y == 0 ) {
y=Cross(bNorm,nNorm);
if ( y == 0 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
}
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
int SweepTree::Find(float px,float py,SweepTree* &insertL,SweepTree* &insertR)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
y=Cross(bNorm,diff);
if ( fabs(y) < 0.000001 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,insertL,insertR);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,insertL,insertR);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
void SweepTree::RemoveEvents(SweepEventQueue &queue)
{
RemoveEvent(queue,true);
RemoveEvent(queue,false);
}
void SweepTree::RemoveEvent(SweepEventQueue &queue,bool onLeft)
{
if ( onLeft ) {
if ( leftEvt ) {
leftEvt->SupprFromQueue(queue);
// leftEvt->MakeDelete(); // fait dans SupprFromQueue
}
leftEvt=NULL;
} else {
if ( rightEvt ) {
rightEvt->SupprFromQueue(queue);
// rightEvt->MakeDelete(); // fait dans SupprFromQueue
}
rightEvt=NULL;
}
}
int SweepTree::Remove(SweepTreeList &list,SweepEventQueue &queue,bool rebalance)
{
RemoveEvents(queue);
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Remove(tempR,rebalance);
list.racine=static_cast <SweepTree*> (tempR);
MakeDelete();
if ( list.nbTree <= 1 ) {
list.nbTree=0;
list.racine=NULL;
} else {
if ( list.racine == list.trees+(list.nbTree-1) ) list.racine=this;
list.trees[--list.nbTree].Relocate(this);
}
return err;
}
int SweepTree::Insert(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,int iAtPoint,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
int insertion=list.racine->Find(iDst->pts[iAtPoint].x,iDst->pts[iAtPoint].y,this,insertL,insertR,sweepSens);
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
int SweepTree::InsertAt(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,SweepTree* insNode,int fromPt,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
vec2 fromP;
fromP.x=src->pData[fromPt].rx;
fromP.y=src->pData[fromPt].ry;
vec2d nNorm;
nNorm.x=src->aretes[bord].dx;
nNorm.y=src->aretes[bord].dy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
if ( sweepSens == false ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
vec2d bNorm;
bNorm.x=insNode->src->aretes[insNode->bord].dx;
bNorm.y=insNode->src->aretes[insNode->bord].dy;
if ( insNode->src->aretes[insNode->bord].st > insNode->src->aretes[insNode->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
double ang=Dot(bNorm,nNorm);
if ( ang == 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
} else if ( ang > 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertL ) {
if ( insertL->src == src ) {
if ( insertL->src->aretes[insertL->bord].st != fromPt && insertL->src->aretes[insertL->bord].en != fromPt ) {
break;
}
} else {
int ils=insertL->src->aretes[insertL->bord].st;
int ile=insertL->src->aretes[insertL->bord].en;
if ( ( insertL->src->pData[ils].rx != fromP.x || insertL->src->pData[ils].ry != fromP.y ) &&
( insertL->src->pData[ile].rx != fromP.x || insertL->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertL->src->aretes[insertL->bord].dx;
bNorm.y=insertL->src->aretes[insertL->bord].dy;
if ( insertL->src->aretes[insertL->bord].st > insertL->src->aretes[insertL->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang <= 0 ) {
break;
}
insertR=insertL;
insertL=static_cast <SweepTree*> (insertR->leftElem);
}
} else if ( ang < 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertR ) {
if ( insertR->src == src ) {
if ( insertR->src->aretes[insertR->bord].st != fromPt && insertR->src->aretes[insertR->bord].en != fromPt ) {
break;
}
} else {
int ils=insertR->src->aretes[insertR->bord].st;
int ile=insertR->src->aretes[insertR->bord].en;
if ( ( insertR->src->pData[ils].rx != fromP.x || insertR->src->pData[ils].ry != fromP.y ) &&
( insertR->src->pData[ile].rx != fromP.x || insertR->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertR->src->aretes[insertR->bord].dx;
bNorm.y=insertR->src->aretes[insertR->bord].dy;
if ( insertR->src->aretes[insertR->bord].st > insertR->src->aretes[insertR->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang > 0 ) {
break;
}
insertL=insertR;
insertR=static_cast <SweepTree*> (insertL->rightElem);
}
}
int insertion=found_between;
if ( insertL == NULL ) insertion=found_on_left;
if ( insertR == NULL ) insertion=found_on_right;
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
void SweepTree::Relocate(SweepTree* to)
{
if ( this == to ) return;
AVLTree::Relocate(to);
to->src=src;
to->bord=bord;
to->sens=sens;
to->leftEvt=leftEvt;
to->rightEvt=rightEvt;
to->startPoint=startPoint;
if ( src->swsData ) src->swsData[bord].misc=to;
if ( src->swrData ) src->swrData[bord].misc=to;
if ( leftEvt ) leftEvt->rightSweep=to;
if ( rightEvt ) rightEvt->leftSweep=to;
}
void SweepTree::SwapWithRight(SweepTreeList &list,SweepEventQueue &queue)
{
SweepTree* tL=this;
SweepTree* tR=static_cast <SweepTree*> (rightElem);
tL->src->swsData[tL->bord].misc=tR;
tR->src->swsData[tR->bord].misc=tL;
{Shape* swap=tL->src;tL->src=tR->src;tR->src=swap;}
{int swap=tL->bord;tL->bord=tR->bord;tR->bord=swap;}
{int swap=tL->startPoint;tL->startPoint=tR->startPoint;tR->startPoint=swap;}
// {float swap=tL->invDirLength;tL->invDirLength=tR->invDirLength;tR->invDirLength=swap;}
{bool swap=tL->sens;tL->sens=tR->sens;tR->sens=swap;}
}
void SweepTree::Avance(Shape* dstPts,int curPoint,Shape* a,Shape* b)
{
return;
/* if ( curPoint != startPoint ) {
int nb=-1;
if ( sens ) {
// nb=dstPts->AddEdge(startPoint,curPoint);
} else {
// nb=dstPts->AddEdge(curPoint,startPoint);
}
if ( nb >= 0 ) {
dstPts->swsData[nb].misc=(void*)((src==b)?1:0);
int wp=waitingPoint;
dstPts->eData[nb].firstLinkedPoint=waitingPoint;
waitingPoint=-1;
while ( wp >= 0 ) {
dstPts->pData[wp].edgeOnLeft=nb;
wp=dstPts->pData[wp].nextLinkedPoint;
}
}
startPoint=curPoint;
}*/
}
| 27.744048 | 167 | 0.64734 | manjukiran |
5107892e5a1d972fb443ea1ce54bf6e01ae87b6c | 3,235 | cc | C++ | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2017-2018 Baidu Robotic Vision Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "timer.h"
#include <glog/logging.h>
#ifndef __DEVELOPMENT_DEBUG_MODE__
#define __HELPER_TIMER_NO_DEBUG__
#endif
namespace XP {
ScopedMicrosecondTimer::ScopedMicrosecondTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedMicrosecondTimer::~ScopedMicrosecondTimer() {
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "ScopedTimer " << text_id_ << "=["
<< std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count()
<< "] microseconds";
#endif
}
ScopedLoopProfilingTimer::ScopedLoopProfilingTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedLoopProfilingTimer::~ScopedLoopProfilingTimer() {
using namespace std::chrono;
// print timing info even if in release mode
if (VLOG_IS_ON(vlog_level_)) {
VLOG(vlog_level_)
<< "ScopedLoopProfilingTimer " << text_id_ << " start_end=["
<< duration_cast<microseconds>(t_start_.time_since_epoch()).count()
<< " "
<< duration_cast<microseconds>(steady_clock::now().time_since_epoch())
.count()
<< "]";
}
}
MicrosecondTimer::MicrosecondTimer(const std::string& text_id, int vlog_level)
: has_ended_(false), text_id_(text_id), vlog_level_(vlog_level) {
t_start_ = std::chrono::steady_clock::now();
}
MicrosecondTimer::MicrosecondTimer()
: has_ended_(false), text_id_(""), vlog_level_(99) {
t_start_ = std::chrono::steady_clock::now();
}
int MicrosecondTimer::end() {
CHECK(!has_ended_);
has_ended_ = true;
int micro_sec_passed = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count();
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "Timer " << text_id_ << "=[" << micro_sec_passed
<< "] microseconds";
#endif
return micro_sec_passed;
}
MicrosecondTimer::~MicrosecondTimer() {
if (!has_ended_) {
VLOG(vlog_level_) << "MicrosecondTimer " << text_id_ << " is not used";
}
}
} // namespace XP
| 38.058824 | 79 | 0.619165 | TongLing916 |
510c52aaeb3ff95cdb61f442a869f2d5cc10769a | 1,972 | cpp | C++ | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | #include "Environment.h"
#include <cstdlib>
// create environment
Environment environment;
int xpos = environment.getW()/2 - 50;
int ypos = environment.getH()/2 - 50;
int xvel = 0;
int yvel = 0;
int xtarget = 0;
int ytarget = 0;
drawRects() {
// render black square
environment.setRenderColor(0x00, 0x00, 0x00, 0xFF);
environment.drawRectangle(xpos, ypos, 100, 100);
// render green square
environment.setRenderColor(0x00, 200, 0x00, 0xFF);
environment.drawRectangle(xtarget - 5, ytarget - 5, 10, 10);
}
int chooseRandomX() {
return rand() % environment.getW();
}
int chooseRandomY() {
return rand() % environment.getH();
}
changeRectVel() {
// if left, go right
if (xpos < xtarget) {
xvel = 1;
}
// if right, go left
if (xpos > xtarget) {
xvel = -1;
}
// if up, go down
if (ypos < ytarget) {
yvel = 1;
}
// if down, go up
if (ypos > ytarget) {
yvel = -1;
}
// if reached, stop
if (xpos == xtarget) {
xvel = 0;
}
if (ypos == ytarget) {
yvel = 0;
}
if (xpos == xtarget && ypos == ytarget) {
xtarget = chooseRandomX();
ytarget = chooseRandomY();
}
}
changeRectPos() {
xpos += xvel;
ypos += yvel;
}
int main(int argc, char* args[]) {
// set title
environment.setTitle("Environment Test 5");
// set width and height of the screen
environment.setScreenWidth(700);
environment.setScreenHeight(700);
// initialize
environment.init();
// load media
environment.loadMedia();
// main loop
while (environment.isRunning()) {
while (environment.pollEvent() != 0) {
if (environment.getEvent()->type == SDL_QUIT) {
environment.setRunning(false);
}
}
// clear environment
environment.setRenderColor(0xFF, 0xFF, 0xFF, 0XFF);
environment.clear();
// draw rectangle
drawRects();
// change velocity
changeRectVel();
// change x and y
changeRectPos();
// present environment
environment.present();
}
// clean up environment
environment.cleanUp();
} | 17 | 61 | 0.639452 | Preponderous-Software |
510fa8b52b24bb8c9fd6df0eb31fdab90e79b353 | 11,216 | cpp | C++ | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <Foundation/FoundationPCH.h>
#include <Foundation/Logging/Log.h>
#include <Foundation/Profiling/Profiling.h>
#include <Foundation/Threading/Implementation/TaskGroup.h>
#include <Foundation/Threading/Implementation/TaskSystemState.h>
#include <Foundation/Threading/Implementation/TaskWorkerThread.h>
#include <Foundation/Threading/Lock.h>
#include <Foundation/Threading/TaskSystem.h>
ezTaskGroupID ezTaskSystem::CreateTaskGroup(ezTaskPriority::Enum Priority, ezOnTaskGroupFinishedCallback callback)
{
EZ_LOCK(s_TaskSystemMutex);
ezUInt32 i = 0;
// this search could be speed up with a stack of free groups
for (; i < s_State->m_TaskGroups.GetCount(); ++i)
{
if (!s_State->m_TaskGroups[i].m_bInUse)
{
goto foundtaskgroup;
}
}
// no free group found, create a new one
s_State->m_TaskGroups.ExpandAndGetRef();
s_State->m_TaskGroups[i].m_uiTaskGroupIndex = static_cast<ezUInt16>(i);
foundtaskgroup:
s_State->m_TaskGroups[i].Reuse(Priority, callback);
ezTaskGroupID id;
id.m_pTaskGroup = &s_State->m_TaskGroups[i];
id.m_uiGroupCounter = s_State->m_TaskGroups[i].m_uiGroupCounter;
return id;
}
void ezTaskSystem::AddTaskToGroup(ezTaskGroupID groupID, const ezSharedPtr<ezTask>& pTask)
{
EZ_ASSERT_DEBUG(pTask != nullptr, "Cannot add nullptr tasks.");
EZ_ASSERT_DEV(pTask->IsTaskFinished(), "The given task is not finished! Cannot reuse a task before it is done.");
EZ_ASSERT_DEBUG(!pTask->m_sTaskName.IsEmpty(), "Every task should have a name");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
pTask->Reset();
pTask->m_BelongsToGroup = groupID;
groupID.m_pTaskGroup->m_Tasks.PushBack(pTask);
}
void ezTaskSystem::AddTaskGroupDependency(ezTaskGroupID groupID, ezTaskGroupID DependsOn)
{
EZ_ASSERT_DEBUG(DependsOn.IsValid(), "Invalid dependency");
EZ_ASSERT_DEBUG(groupID.m_pTaskGroup != DependsOn.m_pTaskGroup || groupID.m_uiGroupCounter != DependsOn.m_uiGroupCounter, "Group cannot depend on itselfs");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
groupID.m_pTaskGroup->m_DependsOnGroups.PushBack(DependsOn);
}
void ezTaskSystem::AddTaskGroupDependencyBatch(ezArrayPtr<const ezTaskGroupDependency> batch)
{
#if EZ_ENABLED(EZ_COMPILE_FOR_DEBUG)
// lock here once to reduce the overhead of ezTaskGroup::DebugCheckTaskGroup inside AddTaskGroupDependency
EZ_LOCK(s_TaskSystemMutex);
#endif
for (const ezTaskGroupDependency& dep : batch)
{
AddTaskGroupDependency(dep.m_TaskGroup, dep.m_DependsOn);
}
}
void ezTaskSystem::StartTaskGroup(ezTaskGroupID groupID)
{
EZ_ASSERT_DEV(s_ThreadState->m_Workers[ezWorkerThreadType::ShortTasks].GetCount() > 0, "No worker threads started.");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
ezInt32 iActiveDependencies = 0;
{
EZ_LOCK(s_TaskSystemMutex);
ezTaskGroup& tg = *groupID.m_pTaskGroup;
tg.m_bStartedByUser = true;
for (ezUInt32 i = 0; i < tg.m_DependsOnGroups.GetCount(); ++i)
{
if (!IsTaskGroupFinished(tg.m_DependsOnGroups[i]))
{
ezTaskGroup& Dependency = *tg.m_DependsOnGroups[i].m_pTaskGroup;
// add this task group to the list of dependencies, such that when that group finishes, this task group can get woken up
Dependency.m_OthersDependingOnMe.PushBack(groupID);
// count how many other groups need to finish before this task group can be executed
++iActiveDependencies;
}
}
if (iActiveDependencies != 0)
{
// atomic integers are quite slow, so do not use them in the loop, where they are not yet needed
tg.m_iNumActiveDependencies = iActiveDependencies;
}
}
if (iActiveDependencies == 0)
{
ScheduleGroupTasks(groupID.m_pTaskGroup, false);
}
}
void ezTaskSystem::StartTaskGroupBatch(ezArrayPtr<const ezTaskGroupID> batch)
{
EZ_LOCK(s_TaskSystemMutex);
for (const ezTaskGroupID& group : batch)
{
StartTaskGroup(group);
}
}
bool ezTaskSystem::IsTaskGroupFinished(ezTaskGroupID Group)
{
// if the counters differ, the task group has been reused since the GroupID was created, so that group has finished
return (Group.m_pTaskGroup == nullptr) || (Group.m_pTaskGroup->m_uiGroupCounter != Group.m_uiGroupCounter);
}
void ezTaskSystem::ScheduleGroupTasks(ezTaskGroup* pGroup, bool bHighPriority)
{
if (pGroup->m_Tasks.IsEmpty())
{
pGroup->m_iNumRemainingTasks = 1;
// "finish" one task -> will finish the task group and kick off dependent groups
TaskHasFinished(nullptr, pGroup);
return;
}
ezInt32 iRemainingTasks = 0;
// add all the tasks to the task list, so that they will be processed
{
EZ_LOCK(s_TaskSystemMutex);
// store how many tasks from this groups still need to be processed
for (auto pTask : pGroup->m_Tasks)
{
iRemainingTasks += ezMath::Max(1u, pTask->m_uiMultiplicity);
pTask->m_iRemainingRuns = ezMath::Max(1u, pTask->m_uiMultiplicity);
}
pGroup->m_iNumRemainingTasks = iRemainingTasks;
for (ezUInt32 task = 0; task < pGroup->m_Tasks.GetCount(); ++task)
{
auto& pTask = pGroup->m_Tasks[task];
for (ezUInt32 mult = 0; mult < ezMath::Max(1u, pTask->m_uiMultiplicity); ++mult)
{
TaskData td;
td.m_pBelongsToGroup = pGroup;
td.m_pTask = pTask;
td.m_pTask->m_bTaskIsScheduled = true;
td.m_uiInvocation = mult;
if (bHighPriority)
s_State->m_Tasks[pGroup->m_Priority].PushFront(td);
else
s_State->m_Tasks[pGroup->m_Priority].PushBack(td);
}
}
// send the proper thread signal, to make sure one of the correct worker threads is awake
switch (pGroup->m_Priority)
{
case ezTaskPriority::EarlyThisFrame:
case ezTaskPriority::ThisFrame:
case ezTaskPriority::LateThisFrame:
case ezTaskPriority::EarlyNextFrame:
case ezTaskPriority::NextFrame:
case ezTaskPriority::LateNextFrame:
case ezTaskPriority::In2Frames:
case ezTaskPriority::In3Frames:
case ezTaskPriority::In4Frames:
case ezTaskPriority::In5Frames:
case ezTaskPriority::In6Frames:
case ezTaskPriority::In7Frames:
case ezTaskPriority::In8Frames:
case ezTaskPriority::In9Frames:
{
WakeUpThreads(ezWorkerThreadType::ShortTasks, iRemainingTasks);
break;
}
case ezTaskPriority::LongRunning:
case ezTaskPriority::LongRunningHighPriority:
{
WakeUpThreads(ezWorkerThreadType::LongTasks, iRemainingTasks);
break;
}
case ezTaskPriority::FileAccess:
case ezTaskPriority::FileAccessHighPriority:
{
WakeUpThreads(ezWorkerThreadType::FileAccess, iRemainingTasks);
break;
}
case ezTaskPriority::SomeFrameMainThread:
case ezTaskPriority::ThisFrameMainThread:
case ezTaskPriority::ENUM_COUNT:
// nothing to do for these enum values
break;
}
}
}
void ezTaskSystem::DependencyHasFinished(ezTaskGroup* pGroup)
{
// remove one dependency from the group
if (pGroup->m_iNumActiveDependencies.Decrement() == 0)
{
// if there are no remaining dependencies, kick off all tasks in this group
ScheduleGroupTasks(pGroup, true);
}
}
ezResult ezTaskSystem::CancelGroup(ezTaskGroupID Group, ezOnTaskRunning::Enum OnTaskRunning)
{
if (ezTaskSystem::IsTaskGroupFinished(Group))
return EZ_SUCCESS;
EZ_PROFILE_SCOPE("CancelGroup");
EZ_LOCK(s_TaskSystemMutex);
ezResult res = EZ_SUCCESS;
auto TasksCopy = Group.m_pTaskGroup->m_Tasks;
// first cancel ALL the tasks in the group, without waiting for anything
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
if (CancelTask(TasksCopy[task], ezOnTaskRunning::ReturnWithoutBlocking) == EZ_FAILURE)
{
res = EZ_FAILURE;
}
}
// if all tasks could be removed without problems, we do not need to try it again with blocking
if (OnTaskRunning == ezOnTaskRunning::WaitTillFinished && res == EZ_FAILURE)
{
// now cancel the tasks in the group again, this time wait for those that are already running
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
CancelTask(TasksCopy[task], ezOnTaskRunning::WaitTillFinished).IgnoreResult();
}
}
return res;
}
void ezTaskSystem::WaitForGroup(ezTaskGroupID Group)
{
EZ_PROFILE_SCOPE("WaitForGroup");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!ezTaskSystem::IsTaskGroupFinished(Group))
{
if (!HelpExecutingTasks(Group))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
Group.m_pTaskGroup->WaitForFinish(Group);
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
void ezTaskSystem::WaitForCondition(ezDelegate<bool()> condition)
{
EZ_PROFILE_SCOPE("WaitForCondition");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!condition())
{
if (!HelpExecutingTasks(ezTaskGroupID()))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
while (!condition())
{
// TODO: busy loop for now
ezThreadUtils::YieldTimeSlice();
}
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
EZ_STATICLINK_FILE(Foundation, Foundation_Threading_Implementation_TaskSystemGroups);
| 31.069252 | 222 | 0.711751 | Tekh-ops |
5110e7dcb11d6a211544dbca488947c8c99a01c1 | 1,565 | cpp | C++ | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=155 lang=cpp
*
* [155] Min Stack
*
* https://leetcode.com/problems/min-stack/description/
*
* algorithms
* Easy (35.38%)
* Total Accepted: 269.9K
* Total Submissions: 756.8K
* Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]'
*
*
* Design a stack that supports push, pop, top, and retrieving the minimum
* element in constant time.
*
*
* push(x) -- Push element x onto stack.
*
*
* pop() -- Removes the element on top of the stack.
*
*
* top() -- Get the top element.
*
*
* getMin() -- Retrieve the minimum element in the stack.
*
*
*
*
* Example:
*
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> Returns -3.
* minStack.pop();
* minStack.top(); --> Returns 0.
* minStack.getMin(); --> Returns -2.
*
*
*/
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (x <= min_) {
s_.push(min_);
min_ = x;
}
s_.push(x);
}
void pop() {
if (s_.top() == min_) {
s_.pop();
min_ = s_.top();
s_.pop();
}
else {
s_.pop();
}
}
int top() {
return s_.top();
}
int getMin() {
return min_;
}
private:
stack<int> s_;
int min_ = INT_MAX;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
| 16.648936 | 119 | 0.557827 | jtcheng |
51150480081cae85b33c08a4b31f2dc9e9fcc218 | 25,801 | cpp | C++ | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cassert>
#include <cmath>
#include <cfloat>
#include "vapor/LayeredGrid.h"
using namespace std;
using namespace VAPoR;
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim
) : RegularGrid(bs,min,max,extents,periodic,blks) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
//
// Periodic, varying dimensions are not supported
//
if (periodic[_varying_dim]) SetPeriodic(periodic);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim,
float missing_value
) : RegularGrid(bs,min,max,extents,periodic,blks, missing_value) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
assert(periodic[_varying_dim] == false);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::~LayeredGrid() {
if (_coords) delete [] _coords;
}
void LayeredGrid::GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
size_t mymin[] = {min[0],min[1],min[2]};
size_t mymax[] = {max[0],max[1],max[2]};
//
// Don't stop until we find valid extents. When missing values
// are present it's possible that the missing value dimension has
// an entire plane of missing values
//
bool done = false;
while (! done) {
done = true;
_GetBoundingBox(mymin, mymax, extents);
if (_varying_dim == 0) {
if (extents[0] == FLT_MAX && mymin[0]<mymax[0]) {
mymin[0] = mymin[0]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[0]>mymin[0]) {
mymax[0] = mymax[0]-1;
done = false;
}
}
else if (_varying_dim == 1) {
if (extents[1] == FLT_MAX && mymin[1]<mymax[1]) {
mymin[1] = mymin[1]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[1]>mymin[1]) {
mymax[1] = mymax[1]-1;
done = false;
}
}
else if (_varying_dim == 2) {
if (extents[2] == FLT_MAX && mymin[2]<mymax[2]) {
mymin[2] = mymin[2]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[2]>mymin[2]) {
mymax[2] = mymax[2]-1;
done = false;
}
}
}
}
void LayeredGrid::_GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
// Get extents of non-varying dimension. Values returned for
// varying dimension are coordinates for first and last grid
// point, respectively, which in general are not the extents
// of the bounding box.
//
RegularGrid::GetUserCoordinates(
min[0], min[1], min[2], &(extents[0]), &(extents[1]), &(extents[2])
);
RegularGrid::GetUserCoordinates(
max[0], max[1], max[2], &(extents[3]), &(extents[4]), &(extents[5])
);
// Initialize min and max coordinates of varying dimension with
// coordinates of "first" and "last" grid point. Coordinates of
// varying dimension are stored as values of a scalar function
// sampling the coordinate space.
//
float mincoord = FLT_MAX;
float maxcoord = -FLT_MAX;
float mv = GetMissingValue();
assert(_varying_dim >= 0 && _varying_dim <= 2);
bool flip = (
_AccessIJK(_coords, 0, 0, min[_varying_dim]) >
_AccessIJK(_coords, 0, 0, max[_varying_dim])
);
// Now find the extreme values of the varying dimension's coordinates
//
if (_varying_dim == 0) { // I plane
// Find min coordinate in first plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, min[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
// Find max coordinate in last plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, max[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else if (_varying_dim == 1) { // J plane
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,min[1],k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,max[1],k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else { // _varying_dim == 2 (K plane)
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,min[2]);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,max[2]);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
extents[_varying_dim] = mincoord;
extents[_varying_dim+3] = maxcoord;
}
void LayeredGrid::GetEnclosingRegion(
const double minu[3], const double maxu[3],
size_t min[3], size_t max[3]
) const {
assert (_varying_dim == 2); // Only z varying dim currently supported
//
// Get coords for non-varying dimension
//
RegularGrid::GetEnclosingRegion(minu, maxu, min, max);
// we have the correct results
// for X and Y dimensions, but the Z levels may not be completely
// contained in the box. We need to verify and possibly expand
// the min and max Z values.
//
size_t dims[3];
GetDimensions(dims);
bool done;
double z;
if (maxu[2] >= minu[2]) {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > minu[2]) {
done = false;
}
}
}
}
}
else {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
}
}
float LayeredGrid::GetValue(double x, double y, double z) const {
_ClampCoord(x,y,z);
if (! InsideGrid(x,y,z)) return(GetMissingValue());
size_t dims[3];
GetDimensions(dims);
// Get the indecies of the cell containing the point
//
size_t i0, j0, k0;
size_t i1, j1, k1;
GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Get user coordinates of cell containing point
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
//
// Calculate interpolation weights. We always interpolate along
// the varying dimension last (the kwgt)
//
double iwgt, jwgt, kwgt;
if (_varying_dim == 0) {
// We have to interpolate coordinate of varying dimension
//
x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (x1!=x0) kwgt = fabs((x-x0) / (x1-x0));
else kwgt = 0.0;
}
else if (_varying_dim == 1) {
y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (y1!=y0) kwgt = fabs((y-y0) / (y1-y0));
else kwgt = 0.0;
}
else {
z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
if (z1!=z0) kwgt = fabs((z-z0) / (z1-z0));
else kwgt = 0.0;
}
if (GetInterpolationOrder() == 0) {
if (iwgt>0.5) i0++;
if (jwgt>0.5) j0++;
if (kwgt>0.5) k0++;
return(AccessIJK(i0,j0,k0));
}
//
// perform tri-linear interpolation
//
double p0,p1,p2,p3,p4,p5,p6,p7;
p0 = AccessIJK(i0,j0,k0);
if (p0 == GetMissingValue()) return (GetMissingValue());
if (iwgt!=0.0) {
p1 = AccessIJK(i1,j0,k0);
if (p1 == GetMissingValue()) return (GetMissingValue());
}
else p1 = 0.0;
if (jwgt!=0.0) {
p2 = AccessIJK(i0,j1,k0);
if (p2 == GetMissingValue()) return (GetMissingValue());
}
else p2 = 0.0;
if (iwgt!=0.0 && jwgt!=0.0) {
p3 = AccessIJK(i1,j1,k0);
if (p3 == GetMissingValue()) return (GetMissingValue());
}
else p3 = 0.0;
if (kwgt!=0.0) {
p4 = AccessIJK(i0,j0,k1);
if (p4 == GetMissingValue()) return (GetMissingValue());
}
else p4 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0) {
p5 = AccessIJK(i1,j0,k1);
if (p5 == GetMissingValue()) return (GetMissingValue());
}
else p5 = 0.0;
if (kwgt!=0.0 && jwgt!=0.0) {
p6 = AccessIJK(i0,j1,k1);
if (p6 == GetMissingValue()) return (GetMissingValue());
}
else p6 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0 && jwgt!=0.0) {
p7 = AccessIJK(i1,j1,k1);
if (p7 == GetMissingValue()) return (GetMissingValue());
}
else p7 = 0.0;
double c0 = p0+iwgt*(p1-p0) + jwgt*((p2+iwgt*(p3-p2))-(p0+iwgt*(p1-p0)));
double c1 = p4+iwgt*(p5-p4) + jwgt*((p6+iwgt*(p7-p6))-(p4+iwgt*(p5-p4)));
return(c0+kwgt*(c1-c0));
}
void LayeredGrid::_GetUserExtents(double extents[6]) const {
size_t dims[3];
GetDimensions(dims);
size_t min[3] = {0,0,0};
size_t max[3] = {dims[0]-1, dims[1]-1, dims[2]-1};
LayeredGrid::GetBoundingBox(min, max, extents);
}
int LayeredGrid::GetUserCoordinates(
size_t i, size_t j, size_t k,
double *x, double *y, double *z
) const {
// First get coordinates of non-varying dimensions
// The varying dimension coordinate returned is ignored
//
int rc = RegularGrid::GetUserCoordinates(i,j,k,x,y,z);
if (rc<0) return(rc);
// Now get coordinates of varying dimension
//
if (_varying_dim == 0) {
*x = _GetVaryingCoord(i,j,k);
}
else if (_varying_dim == 1) {
*y = _GetVaryingCoord(i,j,k);
}
else {
*z = _GetVaryingCoord(i,j,k);
}
return(0);
}
void LayeredGrid::GetIJKIndex(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
RegularGrid::GetIJKIndex(x,y,z, i,j,k);
size_t dims[3];
GetDimensions(dims);
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (i0 == dims[0]-1) { // on boundary
*i = i0;
return;
}
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i0+1,j0,k0,x,y,z);
if (fabs(x-x0) < fabs(x-x1)) {
*i = i0;
}
else {
*i = i0+1;
}
}
else if (_varying_dim == 1) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (j0 == dims[1]-1) { // on boundary
*j = j0;
return;
}
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j0+1,k0,x,y,z);
if (fabs(y-y0) < fabs(y-y1)) {
*j = j0;
}
else {
*j = j0+1;
}
}
else if (_varying_dim == 2) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (k0 == dims[2]-1) { // on boundary
*k = k0;
return;
}
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k0+1,x,y,z);
if (fabs(z-z0) < fabs(z-z1)) {
*k = k0;
}
else {
*k = k0+1;
}
}
}
void LayeredGrid::GetIJKIndexFloor(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
size_t i0, j0, k0;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
*j = j0; *k = k0;
i0 = 0;
i1 = dims[0]-1;
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((x-x0) * (x-x1) >= 0.0) {
if (x0<=x1) {
if (x<=x0) *i = 0;
else if (x>=x1) *i = dims[0]-1;
}
else {
if (x>=x0) *i = 0;
else if (x<=x1) *i = dims[0]-1;
}
return;
}
//
// X-coord of point must be between x0 and x1
//
while (i1-i0 > 1) {
x1 = _interpolateVaryingCoord((i0+i1)>>1,j0,k0,x,y,z);
if (x1 == x) { // pathological case
//*i = (i0+i1)>>1;
i0 = (i0+i1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between x0 and x1
//
if ((x-x0) * (x-x1) <= 0.0) {
i1 = (i0+i1)>>1;
}
else {
i0 = (i0+i1)>>1;
x0 = x1;
}
}
*i = i0;
}
else if (_varying_dim == 1) {
*i = i0; *k = k0;
// Now search for the closest point
//
j0 = 0;
j1 = dims[1]-1;
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((y-y0) * (y-y1) >= 0.0) {
if (y0<=y1) {
if (y<=y0) *j = 0;
else if (y>=y1) *j = dims[1]-1;
}
else {
if (y>=y0) *j = 0;
else if (y<=y1) *j = dims[1]-1;
}
return;
}
//
// Y-coord of point must be between y0 and y1
//
while (j1-j0 > 1) {
y1 = _interpolateVaryingCoord(i0,(j0+j1)>>1,k0,x,y,z);
if (y1 == y) { // pathological case
//*j = (j0+j1)>>1;
j0 = (j0+j1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between y0 and y1
//
if ((y-y0) * (y-y1) <= 0.0) {
j1 = (j0+j1)>>1;
}
else {
j0 = (j0+j1)>>1;
y0 = y1;
}
}
*j = j0;
}
else { // _varying_dim == 2
*i = i0; *j = j0;
// Now search for the closest point
//
k0 = 0;
k1 = dims[2]-1;
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
// see if point is outside grid or on boundary
//
if ((z-z0) * (z-z1) >= 0.0) {
if (z0<=z1) {
if (z<=z0) *k = 0;
else if (z>=z1) *k = dims[2]-1;
}
else {
if (z>=z0) *k = 0;
else if (z<=z1) *k = dims[2]-1;
}
return;
}
//
// Z-coord of point must be between z0 and z1
//
while (k1-k0 > 1) {
z1 = _interpolateVaryingCoord(i0,j0,(k0+k1)>>1,x,y,z);
if (z1 == z) { // pathological case
//*k = (k0+k1)>>1;
k0 = (k0+k1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between z0 and z1
//
if ((z-z0) * (z-z1) <= 0.0) {
k1 = (k0+k1)>>1;
}
else {
k0 = (k0+k1)>>1;
z0 = z1;
}
}
*k = k0;
}
}
int LayeredGrid::Reshape(
const size_t min[3],
const size_t max[3],
const bool periodic[3]
) {
int rc = RegularGrid::Reshape(min,max,periodic);
if (rc<0) return(-1);
_GetUserExtents(_extents);
return(0);
}
void LayeredGrid::SetPeriodic(const bool periodic[3]) {
bool pvec[3];
for (int i=0; i<3; i++) pvec[i] = periodic[i];
pvec[_varying_dim] = false;
RegularGrid::SetPeriodic(pvec);
}
bool LayeredGrid::InsideGrid(double x, double y, double z) const {
// Clamp coordinates on periodic boundaries to reside within the
// grid extents (vary-dimensions can not have periodic boundaries)
//
_ClampCoord(x,y,z);
// Do a quick check to see if the point is completely outside of
// the grid bounds.
//
double extents[6];
GetUserExtents(extents);
if (extents[0] < extents[3]) {
if (x<extents[0] || x>extents[3]) return (false);
}
else {
if (x>extents[0] || x<extents[3]) return (false);
}
if (extents[1] < extents[4]) {
if (y<extents[1] || y>extents[4]) return (false);
}
else {
if (y>extents[1] || y<extents[4]) return (false);
}
if (extents[2] < extents[5]) {
if (z<extents[2] || z>extents[5]) return (false);
}
else {
if (z>extents[2] || z<extents[5]) return (false);
}
// If we get to here the point's non-varying dimension coordinates
// must be inside the grid. It is only the varying dimension
// coordinates that we need to check
//
// Get the indecies of the cell containing the point
// Only the indecies for the non-varying dimensions are correctly
// returned by GetIJKIndexFloor()
//
size_t dims[3];
GetDimensions(dims);
size_t i0, j0, k0;
size_t i1, j1, k1;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
//
// See if the varying dimension coordinate of the point is
// completely above or below all of the corner points in the first (last)
// cell in the column of cells containing the point
//
double t00, t01, t10, t11; // varying dimension coord of "top" cell
double b00, b01, b10, b11; // varying dimension coord of "bottom" cell
double vc; // varying coordinate value
if (_varying_dim == 0) {
t00 = _GetVaryingCoord( dims[0]-1, j0, k0);
t01 = _GetVaryingCoord( dims[0]-1, j1, k0);
t10 = _GetVaryingCoord( dims[0]-1, j0, k1);
t11 = _GetVaryingCoord( dims[0]-1, j1, k1);
b00 = _GetVaryingCoord( 0, j0, k0);
b01 = _GetVaryingCoord( 0, j1, k0);
b10 = _GetVaryingCoord( 0, j0, k1);
b11 = _GetVaryingCoord( 0, j1, k1);
vc = x;
}
else if (_varying_dim == 1) {
t00 = _GetVaryingCoord( i0, dims[1]-1, k0);
t01 = _GetVaryingCoord( i1, dims[1]-1, k0);
t10 = _GetVaryingCoord( i0, dims[1]-1, k1);
t11 = _GetVaryingCoord( i1, dims[1]-1, k1);
b00 = _GetVaryingCoord( i0, 0, k0);
b01 = _GetVaryingCoord( i1, 0, k0);
b10 = _GetVaryingCoord( i0, 0, k1);
b11 = _GetVaryingCoord( i1, 0, k1);
vc = y;
}
else { // _varying_dim == 2
t00 = _GetVaryingCoord( i0, j0, dims[2]-1);
t01 = _GetVaryingCoord( i1, j0, dims[2]-1);
t10 = _GetVaryingCoord( i0, j1, dims[2]-1);
t11 = _GetVaryingCoord( i1, j1, dims[2]-1);
b00 = _GetVaryingCoord( i0, j0, 0);
b01 = _GetVaryingCoord( i1, j0, 0);
b10 = _GetVaryingCoord( i0, j1, 0);
b11 = _GetVaryingCoord( i1, j1, 0);
vc = z;
}
if (b00<t00) {
// If coordinate is between all of the cell's top and bottom
// coordinates the point must be in the grid
//
if (b00<vc && b01<vc && b10<vc && b11<vc &&
t00>vc && t01>vc && t10>vc && t11>vc) {
return(true);
}
//
// if coordinate is above or below all corner points
// the input point must be outside the grid
//
if (b00>vc && b01>vc && b10>vc && b11>vc) return(false);
if (t00<vc && t01<vc && t10<vc && t11<vc) return(false);
}
else {
if (b00>vc && b01>vc && b10>vc && b11>vc &&
t00<vc && t01<vc && t10<vc && t11<vc) {
return(true);
}
if (b00<vc && b01<vc && b10<vc && b11<vc) return(false);
if (t00>vc && t01>vc && t10>vc && t11>vc) return(false);
}
// If we get this far the point is either inside or outside of a
// boundary cell on the varying dimension. Need to interpolate
// the varying coordinate of the cell
// Varying dimesion coordinate value returned by GetUserCoordinates
// is not valid
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double t = t00+iwgt*(t01-t00) + jwgt*((t10+iwgt*(t11-t10))-(t00+iwgt*(t01-t00)));
double b = b00+iwgt*(b01-b00) + jwgt*((b10+iwgt*(b11-b10))-(b00+iwgt*(b01-b00)));
if (b<t) {
if (vc<b || vc>t) return(false);
}
else {
if (vc>b || vc<t) return(false);
}
return(true);
}
void LayeredGrid::GetMinCellExtents(double *x, double *y, double *z) const {
//
// Get X and Y dimension minimums
//
RegularGrid::GetMinCellExtents(x,y,z);
size_t dims[3];
GetDimensions(dims);
if (dims[2] < 2) return;
double tmp;
*z = fabs(_extents[5] - _extents[3]);
for (int k=0; k<dims[2]-1; k++) {
for (int j=0; j<dims[1]; j++) {
for (int i=0; i<dims[0]; i++) {
float z0 = _GetVaryingCoord(i,j,k);
float z1 = _GetVaryingCoord(i,j,k+1);
tmp = fabs(z1-z0);
if (tmp<*z) *z = tmp;
}
}
}
}
double LayeredGrid::_GetVaryingCoord(size_t i, size_t j, size_t k) const {
double mv = GetMissingValue();
double c = _AccessIJK(_coords, i, j, k);
if (c != mv) return (c);
assert (c != mv);
size_t dims[3];
GetDimensions(dims);
//
// Varying coordinate for i,j,k is missing. Look along varying dimension
// axis for first grid point with non-missing value. First search
// below, then above. If no valid coordinate is found, use the
// grid minimum extent
//
if (_varying_dim == 0) {
size_t ii = i;
while (ii>0 && (c=_AccessIJK(_coords,ii-1,j,k)) == mv) ii--;
if (c!=mv) return (c);
ii = i;
while (ii<dims[0]-1 && (c=_AccessIJK(_coords,ii+1,j,k)) == mv) ii++;
if (c!=mv) return (c);
return(_extents[0]);
} else if (_varying_dim == 1) {
size_t jj = j;
while (jj>0 && (c=_AccessIJK(_coords,i,jj-1,k)) == mv) jj--;
if (c!=mv) return (c);
jj = j;
while (jj<dims[1]-1 && (c=_AccessIJK(_coords,i, jj+1,k)) == mv) jj++;
if (c!=mv) return (c);
return(_extents[1]);
} else if (_varying_dim == 2) {
size_t kk = k;
while (kk>0 && (c=_AccessIJK(_coords,i,j,kk-1)) == mv) kk--;
if (c!=mv) return (c);
kk = k;
while (kk<dims[2]-1 && (c=_AccessIJK(_coords,i,j,kk+1)) == mv) kk++;
if (c!=mv) return (c);
return(_extents[2]);
}
return(0.0);
}
double LayeredGrid::_interpolateVaryingCoord(
size_t i0, size_t j0, size_t k0,
double x, double y, double z) const {
// varying dimension coord at corner grid points of cell face
//
double c00, c01, c10, c11;
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Coordinates of grid points for non-varying dimensions
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
// Now get user coordinates of vary-dimension grid point
// N.B. Could just call LayeredGrid:GetUserCoordinates() for
// each of the four points but this is more efficient
//
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i0, j1, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i0, j1, k1);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i1, j0, k1);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else { // _varying_dim == 2
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j1, k0);
c11 = _AccessIJK(_coords, i1, j1, k0);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double c = c00+iwgt*(c01-c00) + jwgt*((c10+iwgt*(c11-c10))-(c00+iwgt*(c01-c00)));
return(c);
}
| 23.476797 | 82 | 0.586218 | yyr |
5119450791c9c70e8f3501fa1f5c6ae74244ed2a | 738 | hpp | C++ | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | #ifndef GUI_ABILITY_HPP_INCLUDED
#define GUI_ABILITY_HPP_INCLUDED
/**
* Contains all the information about an ability, for the GUI part. For
* example the icone to use, the activate callback (it can execute the
* ability directly, or change the LeftClick structure, which only involves
* the GUI)
*/
#include <gui/screen/left_click.hpp>
#include <functional>
class GuiAbility
{
public:
GuiAbility() = default;
~GuiAbility() = default;
LeftClick left_click;
std::function<void()> callback;
private:
GuiAbility(const GuiAbility&) = delete;
GuiAbility(GuiAbility&&) = delete;
GuiAbility& operator=(const GuiAbility&) = delete;
GuiAbility& operator=(GuiAbility&&) = delete;
};
#endif /* GUI_ABILITY_HPP_INCLUDED */
| 23.806452 | 75 | 0.738482 | louiz |
511c4044a743e00aa56c998735284dfc1fd86f47 | 243 | hpp | C++ | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | null | null | null | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | null | null | null | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | 1 | 2022-01-08T07:03:58.000Z | 2022-01-08T07:03:58.000Z | #pragma once
#include <mutex>
#include <thread>
typedef void (*die_handler_func)(int);
struct MutexStore {
public:
std::mutex podman, podman_sched, podman_sock;
MutexStore(die_handler_func die_handler);
};
extern MutexStore mutex;
| 13.5 | 47 | 0.748971 | oskarirauta |
511d7daa914d64fcc4ae8455aad714116a838029 | 246 | cpp | C++ | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | 1 | 2016-03-16T17:08:54.000Z | 2016-03-16T17:08:54.000Z | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | null | null | null | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include "isPrime.hpp"
using namespace std;
int main() {
long int sum = 0;
for(int i = 2; i < 2000000; i++) {
if(isPrime(i) == true)
sum += i;
}
cout << sum << endl;
}
| 13.666667 | 38 | 0.50813 | montyanderson |
512308bd3bfb58307a904a5d872518cf11ac8f01 | 578 | cpp | C++ | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vi arr(n);
int acc = 0, flag = 0;
for(int i=1; i<=n; ++i){
cin >> arr[i-1];
if(arr[i-1] == i)
flag = 0;
else if(!flag){
flag = 1;
acc++;
}
}
if(acc == 0)
cout << 0 << endl;
else if(acc == 1)
cout << 1 << endl;
else
cout << 2 << endl;
}
return 0;
}
| 19.266667 | 32 | 0.316609 | tysm |
5124d128b166defd1236b752cab620cdaef99725 | 2,969 | cpp | C++ | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 890 | 2019-03-08T08:04:10.000Z | 2022-03-30T03:07:44.000Z | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 583 | 2019-03-11T10:27:42.000Z | 2022-03-29T01:41:28.000Z | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 385 | 2019-03-08T07:50:13.000Z | 2022-03-29T06:36:28.000Z | // Copyright (C) <2021> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "InternalClient.h"
#include "RawTransport.h"
namespace owt_base {
DEFINE_LOGGER(InternalClient, "owt.InternalClient");
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
Listener* listener)
: m_client(new TransportClient(this))
, m_streamId(streamId)
, m_ready(false)
, m_listener(listener)
{
}
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
const std::string& ip,
unsigned int port,
Listener* listener)
: InternalClient(streamId, protocol, listener)
{
if (!TransportSecret::getPassphrase().empty()) {
m_client->enableSecure();
}
m_client->createConnection(ip, port);
}
InternalClient::~InternalClient()
{
m_client->close();
m_client.reset();
}
void InternalClient::connect(const std::string& ip, unsigned int port)
{
m_client->createConnection(ip, port);
}
void InternalClient::onFeedback(const FeedbackMsg& msg)
{
if (!m_ready && msg.cmd != INIT_STREAM_ID) {
return;
}
ELOG_DEBUG("onFeedback ");
uint8_t sendBuffer[512];
sendBuffer[0] = TDT_FEEDBACK_MSG;
memcpy(&sendBuffer[1],
reinterpret_cast<uint8_t*>(const_cast<FeedbackMsg*>(&msg)),
sizeof(FeedbackMsg));
m_client->sendData((uint8_t*)sendBuffer, sizeof(FeedbackMsg) + 1);
}
void InternalClient::onConnected()
{
ELOG_DEBUG("On Connected %s", m_streamId.c_str());
if (m_listener) {
m_listener->onConnected();
}
if (!m_streamId.empty()) {
FeedbackMsg msg(VIDEO_FEEDBACK, INIT_STREAM_ID);
if (m_streamId.length() > 128) {
ELOG_WARN("Too long streamId:%s, will be resized",
m_streamId.c_str());
m_streamId.resize(128);
}
memcpy(&msg.buffer.data[0], m_streamId.c_str(), m_streamId.length());
msg.buffer.len = m_streamId.length();
onFeedback(msg);
}
m_ready = true;
}
void InternalClient::onData(uint8_t* buf, uint32_t len)
{
Frame* frame = nullptr;
MetaData* metadata = nullptr;
if (len <= 1) {
ELOG_DEBUG("Skip onData len: %u", (unsigned int)len);
return;
}
switch ((char) buf[0]) {
case TDT_MEDIA_FRAME:
frame = reinterpret_cast<Frame*>(buf + 1);
frame->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(Frame));
deliverFrame(*frame);
break;
case TDT_MEDIA_METADATA:
metadata = reinterpret_cast<MetaData*>(buf + 1);
metadata->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(MetaData));
deliverMetaData(*metadata);
break;
default:
break;
}
}
void InternalClient::onDisconnected()
{
if (m_listener) {
m_listener->onDisconnected();
}
}
} /* namespace owt_base */
| 25.376068 | 87 | 0.624453 | yfdandy |
5127aea9d1bba2efd60678830c1013b6cfbe718f | 8,199 | hpp | C++ | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: ShowHideAnimationController
class ShowHideAnimationController;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::ShowHideAnimationController);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::ShowHideAnimationController*, "", "ShowHideAnimationController");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: ShowHideAnimationController
// [TokenAttribute] Offset: FFFFFFFF
class ShowHideAnimationController : public ::UnityEngine::MonoBehaviour {
public:
// Nested type: ::GlobalNamespace::ShowHideAnimationController::$DeactivateSelfAfterDelayCoroutine$d__9
class $DeactivateSelfAfterDelayCoroutine$d__9;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public UnityEngine.Animator _animator
// Size: 0x8
// Offset: 0x18
::UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(::UnityEngine::Animator*) == 0x8);
// public System.Boolean _deactivateSelfAfterDelay
// Size: 0x1
// Offset: 0x20
bool deactivateSelfAfterDelay;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: deactivateSelfAfterDelay and: deactivationDelay
char __padding1[0x3] = {};
// public System.Single _deactivationDelay
// Size: 0x4
// Offset: 0x24
float deactivationDelay;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _show
// Size: 0x1
// Offset: 0x28
bool show;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: show and: showAnimatorParam
char __padding3[0x3] = {};
// private System.Int32 _showAnimatorParam
// Size: 0x4
// Offset: 0x2C
int showAnimatorParam;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: public UnityEngine.Animator _animator
::UnityEngine::Animator*& dyn__animator();
// Get instance field reference: public System.Boolean _deactivateSelfAfterDelay
bool& dyn__deactivateSelfAfterDelay();
// Get instance field reference: public System.Single _deactivationDelay
float& dyn__deactivationDelay();
// Get instance field reference: private System.Boolean _show
bool& dyn__show();
// Get instance field reference: private System.Int32 _showAnimatorParam
int& dyn__showAnimatorParam();
// public System.Boolean get_Show()
// Offset: 0x29D63D4
bool get_Show();
// public System.Void set_Show(System.Boolean value)
// Offset: 0x29D6274
void set_Show(bool value);
// protected System.Void Awake()
// Offset: 0x29D63DC
void Awake();
// private System.Collections.IEnumerator DeactivateSelfAfterDelayCoroutine(System.Single delay)
// Offset: 0x29D6458
::System::Collections::IEnumerator* DeactivateSelfAfterDelayCoroutine(float delay);
// public System.Void .ctor()
// Offset: 0x29D6504
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ShowHideAnimationController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::ShowHideAnimationController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ShowHideAnimationController*, creationType>()));
}
}; // ShowHideAnimationController
#pragma pack(pop)
static check_size<sizeof(ShowHideAnimationController), 44 + sizeof(int)> __GlobalNamespace_ShowHideAnimationControllerSizeCheck;
static_assert(sizeof(ShowHideAnimationController) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::get_Show
// Il2CppName: get_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::get_Show)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "get_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::set_Show
// Il2CppName: set_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)(bool)>(&GlobalNamespace::ShowHideAnimationController::set_Show)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "set_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine
// Il2CppName: DeactivateSelfAfterDelayCoroutine
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (GlobalNamespace::ShowHideAnimationController::*)(float)>(&GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine)> {
static const MethodInfo* get() {
static auto* delay = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "DeactivateSelfAfterDelayCoroutine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{delay});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 47.393064 | 248 | 0.731919 | RedBrumbler |
512eb0cb8c6ad7662d5123ae67ecd2e42d58b987 | 1,525 | cpp | C++ | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | 2 | 2020-08-02T02:11:27.000Z | 2020-08-30T16:15:50.000Z | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | null | null | null | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | null | null | null | #include <iostream>
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "HelperTest.h"
#include "MagmaDevice.h"
#include "mbmagma.h"
using namespace MagmaBinding;
#include "GSVTests.h"
#include "SVDTests.h"
#include "LSSTests.h"
#include "EIGENTests.h"
#include "MatrixTest.h"
int main(int argc, char** argv)
{
mv2sgemm_test_magma_col_01();
mv2sgemm_test_magma_row_01();
mv2sgemm_test_magma_row();
mv2sgemm_test_magma_col();
mv2sgemm_test_lapack_col_01();
mv2sgemm_test_lapack_row_01();
mv2sgemm_test_lapack_row();
mv2sgemm_test_lapack_col();
mv2dgemm_test_magma_col_01();
mv2dgemm_test_magma_row_01();
mv2dgemm_test_magma_row();
mv2dgemm_test_magma_col();
mv2dgemm_test_lapack_col_01();
mv2dgemm_test_lapack_row_01();
mv2dgemm_test_lapack_row();
mv2dgemm_test_lapack_col();
mbv2getdevice_arch();
//EIGEN
mv2sgeevs_cpu_test();
mv2sgeevs_test();
mv2sgeev_cpu_test();
mv2sgeev_test();
mv2dgeevs_cpu_test();
mv2dgeevs_test();
mv2dgeev_cpu_test();
mv2dgeev_test();
//LSS
mv2sgels_cpu_test();
mv2sgels_test();
mv2sgels_gpu_test();
mv2dgels_cpu_test();
mv2dgels_test();
mv2dgels_gpu_test();
//GSV tests
mv2dgesv_cpu_test();
mv2dgesv_test();
mv2dgesv_gpu_test();
mv2sgesv_cpu_test();
mv2sgesv_test();
mv2sgesv_gpu_test();
//SVD
mv2sgesvd_cpu_test();
mv2sgesvds_cpu_test();
mv2sgesvds_test();
mv2sgesvd_test();
mv2dgesvd_cpu_test();
mv2dgesvds_cpu_test();
mv2dgesvds_test();
mv2dgesvd_test();
return 0;
}
| 17.329545 | 31 | 0.756721 | bhrnjica |
512eea02b2150f4c75cdc9bc70f54ea5376c2147 | 5,252 | cpp | C++ | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | #include "TicTacToeGame.hpp"
void TicTacToeGame::setup()
{
createBoard();
createText();
m_board.clear();
m_crntPlayer = CellValue::Cross; // todo: set this randomly
}
void TicTacToeGame::createText()
{
m_textEntities.clear();
m_headingText = std::make_shared<sf::Text>();
m_headingText->setFont(shared::font);
m_headingText->setCharacterSize(m_topBarHeight - 15);
m_headingText->setFillColor(m_textColor);
// m_drawables.push_back(m_headingText);
}
void TicTacToeGame::createBoard()
{
m_board = TicTacToeBoard();
}
void TicTacToeGame::update()
{
calcBoardSize();
switch (m_gamePhase)
{
case Playing:
drawCellBorders();
drawCells();
updateText();
break;
case ShowingWinner:
drawCellBorders();
drawCells();
updateText();
if (! m_showWinnerTimer.running) m_showWinnerTimer.start();
if (m_showWinnerTimer.isFinished()) gameManager->queueLoadScene("TitleScreen");
break;
}
}
void TicTacToeGame::handleEvent(sf::Event& event)
{
if (event.type == sf::Event::MouseButtonPressed)
{
switch (m_gamePhase)
{
case Playing:
setCellContents(event);
break;
}
}
}
void TicTacToeGame::updateText()
{
// Yes this is a big and convoluted nested switch-case
// But I couldn't find a way to put this into a table lookup because of the differing
// data types
std::string headingTextContent = "Error: no text supplied for this heading";
switch (m_gamePhase)
{
case Playing:
switch (m_crntPlayer)
{
case CellValue::Nought:
headingTextContent = "Noughts turn";
break;
case CellValue::Cross:
headingTextContent = "Crosses turn";
break;
}
break;
case ShowingWinner:
switch (m_winner)
{
case Winner::Nought:
headingTextContent = "Noughts wins";
break;
case Winner::Cross:
headingTextContent = "Crosses wins";
break;
case Winner::Draw:
headingTextContent = "Draw";
break;
}
break;
}
m_headingText->setString(headingTextContent);
miniengine::utils::centerAlignText(*m_headingText);
m_headingText->setPosition(gameManager->width / 2, m_topBarHeight / 2);
}
void TicTacToeGame::calcBoardSize()
{
int availableHeight = gameManager->height - m_topBarHeight - m_bottomBarHeight;
m_boardSize = std::min(availableHeight, gameManager->width) - m_windowPadding * 2;
m_cellSize = m_boardSize / 3;
m_boardLeft = std::max(gameManager->width - m_boardSize, 1) / 2;
m_boardTop = std::max(gameManager->height - m_boardSize, 1) / 2;
}
void TicTacToeGame::drawCellBorders()
{
sf::RectangleShape rectangle;
rectangle.setFillColor(m_cellBorderColor);
int cellBorderWidth = m_cellBorderWidthProportion * m_boardSize;
rectangle.setSize(sf::Vector2f(m_boardSize, cellBorderWidth));
rectangle.setOrigin(m_boardSize / 2, cellBorderWidth / 2);
// Do the horizontal borders
for (int y = 1; y < BOARD_SIZE; y ++)
{
rectangle.setPosition(m_boardLeft + m_boardSize / 2,
m_boardTop + y * m_cellSize);
gameManager->window.draw(rectangle);
}
// Do the vertical borders
rectangle.setRotation(90);
for (int x = 1; x < BOARD_SIZE; x ++)
{
rectangle.setPosition(m_boardLeft + x * m_cellSize,
m_boardTop + m_boardSize / 2);
gameManager->window.draw(rectangle);
}
}
void TicTacToeGame::drawCells()
{
int cellPadding = m_cellPaddingProportion * m_cellSize;
NoughtGraphic nought((m_cellSize - cellPadding) / 2);
CrossGraphic cross((m_cellSize - cellPadding) / 2);
for (int x = 0; x < BOARD_SIZE; x ++)
{
for (int y = 0; y < BOARD_SIZE; y ++)
{
int xPos = x * m_cellSize + m_cellSize / 2 + m_boardLeft;
int yPos = y * m_cellSize + m_cellSize / 2 + m_boardTop;
if (m_board.getCell(x, y) == CellValue::Nought)
nought.draw(xPos, yPos, gameManager->window, m_backgroundColor);
else if (m_board.getCell(x, y) == CellValue::Cross)
cross.draw(xPos, yPos, gameManager->window);
}
}
}
void TicTacToeGame::setCellContents(sf::Event event)
{
// First calculate board pos of click
int xCoord = (event.mouseButton.x - m_boardLeft) / m_cellSize;
int yCoord = (event.mouseButton.y - m_boardTop) / m_cellSize;
// If click is on board, do game logic
if (xCoord >= 0 && xCoord < BOARD_SIZE &&
yCoord >= 0 && yCoord < BOARD_SIZE)
{
if (m_board.getCell(xCoord, yCoord) == CellValue::Empty)
{
m_board.setCell(xCoord, yCoord, m_crntPlayer);
m_winner = m_board.findWinner();
if (m_winner == Winner::GameNotFinished)
{
if (m_crntPlayer == CellValue::Nought) m_crntPlayer = CellValue::Cross;
else m_crntPlayer = CellValue::Nought;
}
else
{
m_gamePhase = ShowingWinner;
}
}
}
}
| 29.177778 | 89 | 0.609863 | That-Cool-Coder |
51318153f254555c64f9201de6ecb0142f915259 | 7,122 | cpp | C++ | DearPyGui/src/core/AppItems/mvAppItemState.cpp | htnminh/DearPyGui | bfbcb297f287295fae9766b21a53a99fbb0fe756 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/mvAppItemState.cpp | htnminh/DearPyGui | bfbcb297f287295fae9766b21a53a99fbb0fe756 | [
"MIT"
] | 1 | 2021-08-16T02:39:32.000Z | 2021-08-16T02:39:32.000Z | DearPyGui/src/core/AppItems/mvAppItemState.cpp | Jah-On/DearPyGui | 0e4f5d05555f950670e01bb2a647fb8b0b9a106f | [
"MIT"
] | null | null | null | #include "mvAppItemState.h"
#include <imgui.h>
#include "mvAppItem.h"
#include "mvApp.h"
#include "mvPyObject.h"
namespace Marvel {
void mvAppItemState::reset()
{
_hovered = false;
_active = false;
_focused = false;
_leftclicked = false;
_rightclicked = false;
_middleclicked = false;
_visible = false;
_edited = false;
_activated = false;
_deactivated = false;
_deactivatedAfterEdit = false;
_toggledOpen = false;
}
void mvAppItemState::update()
{
_lastFrameUpdate = mvApp::s_frame;
_hovered = ImGui::IsItemHovered();
_active = ImGui::IsItemActive();
_focused = ImGui::IsItemFocused();
_leftclicked = ImGui::IsItemClicked();
_rightclicked = ImGui::IsItemClicked(1);
_middleclicked = ImGui::IsItemClicked(2);
_visible = ImGui::IsItemVisible();
_edited = ImGui::IsItemEdited();
_activated = ImGui::IsItemActivated();
_deactivated = ImGui::IsItemDeactivated();
_deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit();
_toggledOpen = ImGui::IsItemToggledOpen();
_rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y };
_rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y };
_rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y };
_contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y };
}
void mvAppItemState::getState(PyObject* dict)
{
if (dict == nullptr)
return;
bool valid = _lastFrameUpdate == mvApp::s_frame;
PyDict_SetItemString(dict, "ok", mvPyObject(ToPyBool(_ok)));
PyDict_SetItemString(dict, "pos", mvPyObject(ToPyPairII(_pos.x, _pos.y)));
if(_applicableState & MV_STATE_HOVER) PyDict_SetItemString(dict, "hovered", mvPyObject(ToPyBool(valid ? _hovered : false)));
if(_applicableState & MV_STATE_ACTIVE) PyDict_SetItemString(dict, "active", mvPyObject(ToPyBool(valid ? _active : false)));
if(_applicableState & MV_STATE_FOCUSED) PyDict_SetItemString(dict, "focused", mvPyObject(ToPyBool(valid ? _focused : false)));
if (_applicableState & MV_STATE_CLICKED)
{
PyDict_SetItemString(dict, "clicked", mvPyObject(ToPyBool(valid ? _leftclicked || _rightclicked || _middleclicked : false)));
PyDict_SetItemString(dict, "left_clicked", mvPyObject(ToPyBool(valid ? _leftclicked : false)));
PyDict_SetItemString(dict, "right_clicked", mvPyObject(ToPyBool(valid ? _rightclicked : false)));
PyDict_SetItemString(dict, "middle_clicked", mvPyObject(ToPyBool(valid ? _middleclicked : false)));
}
if(_applicableState & MV_STATE_VISIBLE) PyDict_SetItemString(dict, "visible", mvPyObject(ToPyBool(valid ? _visible : false)));
if(_applicableState & MV_STATE_EDITED) PyDict_SetItemString(dict, "edited", mvPyObject(ToPyBool(valid ? _edited : false)));
if(_applicableState & MV_STATE_ACTIVATED) PyDict_SetItemString(dict, "activated", mvPyObject(ToPyBool(valid ? _activated : false)));
if(_applicableState & MV_STATE_DEACTIVATED) PyDict_SetItemString(dict, "deactivated", mvPyObject(ToPyBool(valid ? _deactivated : false)));
if(_applicableState & MV_STATE_DEACTIVATEDAE) PyDict_SetItemString(dict, "deactivated_after_edit", mvPyObject(ToPyBool(valid ? _deactivatedAfterEdit : false)));
if(_applicableState & MV_STATE_TOGGLED_OPEN) PyDict_SetItemString(dict, "toggled_open", mvPyObject(ToPyBool(valid ? _toggledOpen : false)));
if(_applicableState & MV_STATE_RECT_MIN) PyDict_SetItemString(dict, "rect_min", mvPyObject(ToPyPairII(_rectMin.x, _rectMin.y)));
if(_applicableState & MV_STATE_RECT_MAX) PyDict_SetItemString(dict, "rect_max", mvPyObject(ToPyPairII(_rectMax.x, _rectMax.y)));
if(_applicableState & MV_STATE_RECT_SIZE) PyDict_SetItemString(dict, "rect_size", mvPyObject(ToPyPairII(_rectSize.x, _rectSize.y)));
if(_applicableState & MV_STATE_CONT_AVAIL) PyDict_SetItemString(dict, "content_region_avail", mvPyObject(ToPyPairII(_contextRegionAvail.x, _contextRegionAvail.y)));
}
bool mvAppItemState::isItemHovered(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _hovered;
}
bool mvAppItemState::isItemActive(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _active;
}
bool mvAppItemState::isItemFocused(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _focused;
}
bool mvAppItemState::isItemLeftClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _leftclicked;
}
bool mvAppItemState::isItemRightClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _rightclicked;
}
bool mvAppItemState::isItemMiddleClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _middleclicked;
}
bool mvAppItemState::isItemVisible(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _visible;
}
bool mvAppItemState::isItemEdited(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _edited;
}
bool mvAppItemState::isItemActivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _activated;
}
bool mvAppItemState::isItemDeactivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivated;
}
bool mvAppItemState::isItemDeactivatedAfterEdit(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivatedAfterEdit;
}
bool mvAppItemState::isItemToogledOpen(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _toggledOpen;
}
bool mvAppItemState::isOk() const
{
return _ok;
}
mvVec2 mvAppItemState::getItemRectMin() const
{
return _rectMin;
}
mvVec2 mvAppItemState::getItemRectMax() const
{
return _rectMax;
}
mvVec2 mvAppItemState::getItemRectSize() const
{
return _rectSize;
}
mvVec2 mvAppItemState::getItemPos() const
{
return _pos;
}
mvVec2 mvAppItemState::getContextRegionAvail() const
{
return _contextRegionAvail;
}
} | 36.901554 | 172 | 0.659927 | htnminh |
5133bba43106ad19491cc409206c5b9064cfd136 | 5,366 | cpp | C++ | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 1 | 2019-07-31T01:32:17.000Z | 2019-07-31T01:32:17.000Z | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 47 | 2017-11-04T02:04:42.000Z | 2018-06-16T01:00:48.000Z | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 2 | 2018-06-10T21:58:49.000Z | 2019-06-18T17:21:03.000Z | /******************************************************************************
Helper methods, including configuration management.
Author: Noah Strong
Project: Crab Tracker
Created: 2018-02-19
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "config.h"
/******************************************************************************
CONFIGURATION FUNCTIONS AND VARIABLES
Configuration works as follows: on program startup, the initalize() function
should be called. This will look for and load the `.conf` file whose location
is specificed in CONFIG.H (generally `/etc/crab-tracker.conf`). The .conf file
will be parsed and any key/value pairs whose keys we expect to see will be
read in and saved. The keys we "expect to see" are those that are listed in the
entries[] array below. Initially, entries[] contains the default values for all
parameters we expect to come across; unless new values for those parameters are
found in the .conf file, those values will be used.
******************************************************************************/
/* Basically a key/value store for configuration options */
struct config_entry{
const char* param;
int value;
int isset;
};
/* An exhaustive set of all configuration options. Default values given here */
config_entry entries[] = { {"DISPLAY_PINGS", 1, 0},
{"DISPLAY_RAW_SPI", 0, 0},
{"R_USER", 1, 0},
{"HPHONE_DIST_CM", 300, 0}};
int num_entries = sizeof(entries) / sizeof(config_entry);
/**
* "Public" way for getting a configuration. Looks through entries and returns
* (via an out param) the value of that config option.
* @param param The name of the parameter to look for
* @param result The value of the parameter, if found [OUT PARAM]
* @return 1 if param was found, else 0
*/
int get_param(char* param, int* result){
for(int i=0; i<num_entries; i++){
if(!strcmp(param, entries[i].param)){
*result = entries[i].value;
return 1;
}
}
return 0;
}
/* Rather than include math.h, here's a quick integer min() */
int min(int a, int b){ return a > b ? b : a; }
/**
* Loads the .conf file on the machine and then stores the values of any known
* configuration parameters.
* @return 0 if config loaded successfully, else 1.
*/
int initialize_util(){
printf("Loading configuration... ");
FILE* fp;
char* line = NULL;
char buf[120];
size_t linecap = 0;
ssize_t len;
int n, m, n_found = 0, int_param = 0;
/* Load the `.conf` file, if it exists */
fp = fopen(CONFIG_FILE_PATH, "r");
if (fp == NULL){
perror("fopen");
fprintf(stderr, "Unable to load configuration file\n");
return 1;
}
/* Now we go through every line in the config file */
while ((len = getline(&line, &linecap, fp)) != -1) {
for(int i=0; i<len; i++){
/* Strip out comments (denoted by a hash (#)) */
if(line[i] == '#'){ line[i] = '\0'; i=len; };
}
/* See if any of our parameters are found in this line */
for(int j=0; j<num_entries; j++){
/* Set `buf = entries[j].param + " %d";` */
m = min(strlen(entries[j].param), 115);
strncpy(buf, entries[j].param, m);
strcpy(&buf[m], " %d\0");
n = sscanf(line, buf, &int_param);
if(n > 0){
/* Found the parameter! Store it */
n_found++;
entries[j].value = int_param;
entries[j].isset = 1;
j = num_entries; /* Break out of loop early */
}
}
}
/* Clean up! */
fclose(fp);
if (line) free(line);
printf("successfully read %d configuration parameters\n", n_found);
return 0;
}
/******************************************************************************
DISPLAY AND OTHER HELPER FUNCTIONS
These are mostly simple helper functions, such as binary print functions.
******************************************************************************/
/**
* Print a 32-bit number as binary.
* Written by Zach McGrew (WWU Comptuer Science Graduate Student)
* @param number The number to print
*/
void print_bin(int32_t number) {
uint32_t bit_set = (uint32_t) 1 << 31;
int32_t bit_pos;
for (bit_pos = 31; bit_pos >= 0; --bit_pos, bit_set >>= 1) {
printf("%c", ((uint32_t)number & bit_set ? '1' : '0'));
}
}
/**
* Print an 8-bit unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_8(uint8_t number){
uint8_t bit_set = (uint8_t) 1 << 7;
int bit_pos;
for(bit_pos = 7; bit_pos >= 0; --bit_pos){
printf("%c", ((uint8_t)number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
/**
* Print a long unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_ulong(unsigned long number){
unsigned long bit_set = (unsigned long) 1 << 31;
int bit_pos;
for(bit_pos = 31; bit_pos >= 0; --bit_pos){
printf("%c", (number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
| 32.131737 | 80 | 0.549758 | 31337H4X0R |
51350ef7d52628847601f5a0ec6fa701d333df3a | 324 | hpp | C++ | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | /* Common logging functionality.
author: andreasl
*/
#pragma once
#include <ostream>
namespace barn {
namespace bbm {
/* Severity levels for logging.*/
enum Severity {
INFO,
WARN,
ERROR
};
/* Write a log message to console.*/
std::ostream& log(const Severity level);
} // namespace bbm
} // namespace barn
| 13.5 | 40 | 0.675926 | langenhagen |
5135b5e0813ed68e19a88286b59accf0a2449e62 | 45,832 | cpp | C++ | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | 1 | 2022-02-14T03:16:05.000Z | 2022-02-14T03:16:05.000Z | /*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: WSQ - Grayscale Image Compression
FILE: UTIL.C
AUTHORS: Craig Watson
Michael Garris
DATE: 11/24/1999
UPDATED: 02/24/2005 by MDG
Contains gernal routines responsible for supporting WSQ
image compression.
ROUTINES:
#cat: conv_img_2_flt_ret - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: Returns on error.
#cat: conv_img_2_flt - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: conv_img_2_uchar - Converts an image's floating point pixels
#cat: unsigned character pixels.
#cat: variance - Calculates the variances within image subbands.
#cat:
#cat: quantize - Quantizes the image's wavelet subbands.
#cat:
#cat: quant_block_sizes - Quantizes an image's subband block.
#cat:
#cat: unquantize - Unquantizes an image's wavelet subbands.
#cat:
#cat: wsq_decompose - Computes the wavelet decomposition of an input image.
#cat:
#cat: get_lets - Compute the wavelet subband decomposition for the image.
#cat:
#cat: wsq_reconstruct - Reconstructs a lossy floating point pixmap from
#cat: a WSQ compressed datastream.
#cat: join_lets - Reconstruct the image from the wavelet subbands.
#cat:
#cat: int_sign - Get the sign of the sythesis filter coefficients.
#cat:
#cat: image_size - Computes the size in bytes of a WSQ compressed image
#cat: file, including headers, tables, and parameters.
#cat: init_wsq_decoder_resources - Initializes memory resources used by the
#cat: WSQ decoder
#cat: free_wsq_decoder_resources - Deallocates memory resources used by the
#cat: WSQ decoder
***********************************************************************/
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <wsq.h>
#include <defs.h>
#include <dataio.h>
/******************************************************************/
/* The routines in this file do numerous things */
/* related to the WSQ algorithm such as: */
/* converting the image data from unsigned char */
/* to float and integer to unsigned char, */
/* splitting the image into the subbands as well */
/* the rejoining process, subband variance */
/* calculations, and quantization. */
/******************************************************************/
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 This function returns on error. */
/******************************************************************/
int conv_img_2_flt_ret(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at %d\n", cnt);
return(-91);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
return(0);
}
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 */
/******************************************************************/
void conv_img_2_flt(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at pixel %d\n", cnt);
exit(-1);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
}
/*********************************************************/
/* Routine to convert image from float to unsigned char. */
/*********************************************************/
void conv_img_2_uchar(
unsigned char *data, /* uchar image pointer */
float *img, /* image pointer */
const int width, /* image width */
const int height, /* image height */
const float m_shift, /* shifting parameter */
const float r_scale) /* scaling parameter */
{
int r, c; /* row/column counters */
float img_tmp; /* temp image data store */
for (r = 0; r < height; r++) {
for (c = 0; c < width; c++) {
img_tmp = (*img * r_scale) + m_shift;
img_tmp += 0.5;
if (img_tmp < 0.0)
*data = 0; /* neg pix poss after quantization */
else if (img_tmp > 255.0)
*data = 255;
else
*data = (unsigned char)img_tmp;
++img;
++data;
}
}
}
/**********************************************************/
/* This routine calculates the variances of the subbands. */
/**********************************************************/
void variance(
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* length of q_tree */
float *fip, /* image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fp; /* temp image pointer */
int cvr; /* subband counter */
int lenx = 0, leny = 0; /* dimensions of area to calculate variance */
int skipx, skipy; /* pixels to skip to get to area for
variance calculation */
int row, col; /* dimension counters */
float ssq; /* sum of squares */
float sum2; /* variance calculation parameter */
float sum_pix; /* sum of pixels */
float vsum; /* variance sum for subbands 0-3 */
vsum = 0.0;
for(cvr = 0; cvr < 4; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
vsum += quant_vals->var[cvr];
}
if(vsum < 20000.0) {
for(cvr = 0; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
lenx = q_tree[cvr].lenx;
leny = q_tree[cvr].leny;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
else {
for(cvr = 4; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
}
/************************************************/
/* This routine quantizes the wavelet subbands. */
/************************************************/
int quantize(
short **osip, /* quantized output */
int *ocmp_siz, /* size of quantized output */
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* size of q_tree */
float *fip, /* floating point image pointer */
const int width, /* image width */
const int height) /* image height */
{
int i; /* temp counter */
int j; /* interation index */
float *fptr; /* temp image pointer */
short *sip, *sptr; /* pointers to quantized image */
int row, col; /* temp image characteristic parameters */
int cnt; /* subband counter */
float zbin; /* zero bin size */
float A[NUM_SUBBANDS]; /* subband "weights" for quantization */
float m[NUM_SUBBANDS]; /* subband size to image size ratios */
/* (reciprocal of FBI spec for 'm') */
float m1, m2, m3; /* reciprocal constants for 'm' */
float sigma[NUM_SUBBANDS]; /* square root of subband variances */
int K0[NUM_SUBBANDS]; /* initial list of subbands w/variance >= thresh */
int K1[NUM_SUBBANDS]; /* working list of subbands */
int *K, *nK; /* pointers to sets of subbands */
int NP[NUM_SUBBANDS]; /* current subbounds with nonpositive bit rates. */
int K0len; /* number of subbands in K0 */
int Klen, nKlen; /* number of subbands in other subband lists */
int NPlen; /* number of subbands flagged in NP */
float S; /* current frac of subbands w/positive bit rate */
float q; /* current proportionality constant */
float P; /* product of 'q/Q' ratios */
/* Set up 'A' table. */
for(cnt = 0; cnt < STRT_SUBBAND_3; cnt++)
A[cnt] = 1.0;
A[cnt++ /*52*/] = 1.32;
A[cnt++ /*53*/] = 1.08;
A[cnt++ /*54*/] = 1.42;
A[cnt++ /*55*/] = 1.08;
A[cnt++ /*56*/] = 1.32;
A[cnt++ /*57*/] = 1.42;
A[cnt++ /*58*/] = 1.08;
A[cnt++ /*59*/] = 1.08;
for(cnt = 0; cnt < MAX_SUBBANDS; cnt++) {
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 0.0;
}
/* Set up 'Q1' (prime) table. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(quant_vals->var[cnt] < VARIANCE_THRESH)
quant_vals->qbss[cnt] = 0.0;
else
/* NOTE: q has been taken out of the denominator in the next */
/* 2 formulas from the original code. */
if(cnt < STRT_SIZE_REGION_2 /*4*/)
quant_vals->qbss[cnt] = 1.0;
else
quant_vals->qbss[cnt] = 10.0 / (A[cnt] *
(float)log(quant_vals->var[cnt]));
}
/* Set up output buffer. */
if((sip = (short *) calloc(width*height, sizeof(short))) == NULL) {
fprintf(stderr,"ERROR : quantize : calloc : sip\n");
return(-90);
}
sptr = sip;
/* Set up 'm' table (these values are the reciprocal of 'm' in */
/* the FBI spec). */
m1 = 1.0/1024.0;
m2 = 1.0/256.0;
m3 = 1.0/16.0;
for(cnt = 0; cnt < STRT_SIZE_REGION_2; cnt++)
m[cnt] = m1;
for(cnt = STRT_SIZE_REGION_2; cnt < STRT_SIZE_REGION_3; cnt++)
m[cnt] = m2;
for(cnt = STRT_SIZE_REGION_3; cnt < NUM_SUBBANDS; cnt++)
m[cnt] = m3;
j = 0;
/* Initialize 'K0' and 'K1' lists. */
K0len = 0;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++){
if(quant_vals->var[cnt] >= VARIANCE_THRESH){
K0[K0len] = cnt;
K1[K0len++] = cnt;
/* Compute square root of subband variance. */
sigma[cnt] = sqrt(quant_vals->var[cnt]);
}
}
K = K1;
Klen = K0len;
while(1){
/* Compute new 'S' */
S = 0.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
S += m[K[i]];
}
/* Compute product 'P' */
P = 1.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
P *= pow((sigma[K[i]] / quant_vals->qbss[K[i]]), m[K[i]]);
}
/* Compute new 'q' */
q = (pow(2.0f,(float)((quant_vals->r/S)-1.0))/2.5) / pow(P, (float)(1.0/S));
/* Flag subbands with non-positive bitrate. */
memset(NP, 0, NUM_SUBBANDS * sizeof(int));
NPlen = 0;
for(i = 0; i < Klen; i++){
if((quant_vals->qbss[K[i]] / q) >= (5.0*sigma[K[i]])){
NP[K[i]] = TRUE;
NPlen++;
}
}
/* If list of subbands with non-positive bitrate is empty ... */
if(NPlen == 0){
/* Then we are done, so break from while loop. */
break;
}
/* Assign new subband set to previous set K minus subbands in set NP. */
nK = K1;
nKlen = 0;
for(i = 0; i < Klen; i++){
if(!NP[K[i]])
nK[nKlen++] = K[i];
}
/* Assign new set as K. */
K = nK;
Klen = nKlen;
/* Bump iteration counter. */
j++;
}
/* Flag subbands that are in set 'K0' (the very first set). */
nK = K1;
memset(nK, 0, NUM_SUBBANDS * sizeof(int));
for(i = 0; i < K0len; i++){
nK[K0[i]] = TRUE;
}
/* Set 'Q' values. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(nK[cnt])
quant_vals->qbss[cnt] /= q;
else
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 1.2 * quant_vals->qbss[cnt];
}
/* Now ready to compute and store bin widths for subbands. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
if(quant_vals->qbss[cnt] != 0.0) {
zbin = quant_vals->qzbs[cnt] / 2.0;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(-zbin <= *fptr && *fptr <= zbin)
*sptr = 0;
else if(*fptr > 0.0)
*sptr = (short)(((*fptr-zbin)/quant_vals->qbss[cnt]) + 1.0);
else
*sptr = (short)(((*fptr+zbin)/quant_vals->qbss[cnt]) - 1.0);
sptr++;
fptr++;
}
}
}
else if(debug > 0)
fprintf(stderr, "%d -> %3.6f\n", cnt, quant_vals->qbss[cnt]);
}
*osip = sip;
*ocmp_siz = sptr - sip;
return(0);
}
/************************************************************************/
/* Compute quantized WSQ subband block sizes. */
/************************************************************************/
void quant_block_sizes(int *oqsize1, int *oqsize2, int *oqsize3,
QUANT_VALS *quant_vals,
W_TREE w_tree[], const int w_treelen,
Q_TREE q_tree[], const int q_treelen)
{
int qsize1, qsize2, qsize3;
int node;
/* Compute temporary sizes of 3 WSQ subband blocks. */
qsize1 = w_tree[14].lenx * w_tree[14].leny;
qsize2 = (w_tree[5].leny * w_tree[1].lenx) +
(w_tree[4].lenx * w_tree[4].leny);
qsize3 = (w_tree[2].lenx * w_tree[2].leny) +
(w_tree[3].lenx * w_tree[3].leny);
/* Adjust size of quantized WSQ subband blocks. */
for (node = 0; node < STRT_SUBBAND_2; node++)
if(quant_vals->qbss[node] == 0.0)
qsize1 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_2; node < STRT_SUBBAND_3; node++)
if(quant_vals->qbss[node] == 0.0)
qsize2 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_3; node < STRT_SUBBAND_DEL; node++)
if(quant_vals->qbss[node] == 0.0)
qsize3 -= (q_tree[node].lenx * q_tree[node].leny);
*oqsize1 = qsize1;
*oqsize2 = qsize2;
*oqsize3 = qsize3;
}
/*************************************/
/* Routine to unquantize image data. */
/*************************************/
int unquantize(
float **ofip, /* floating point image pointer */
const DQT_TABLE *dqt_table, /* quantization table structure */
Q_TREE q_tree[], /* quantization table structure */
const int q_treelen, /* size of q_tree */
short *sip, /* quantized image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fip; /* floating point image */
int row, col; /* cover counter and row/column counters */
float C; /* quantizer bin center */
float *fptr; /* image pointers */
short *sptr;
int cnt; /* subband counter */
if((fip = (float *) calloc(width*height, sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : unquantize : calloc : fip\n");
return(-91);
}
if(dqt_table->dqt_def != 1) {
fprintf(stderr,
"ERROR: unquantize : quantization table parameters not defined!\n");
return(-92);
}
sptr = sip;
C = dqt_table->bin_center;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(dqt_table->q_bin[cnt] == 0.0)
continue;
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(*sptr == 0)
*fptr = 0.0;
else if(*sptr > 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr - C))
+ (dqt_table->z_bin[cnt] / 2.0);
else if(*sptr < 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr + C))
- (dqt_table->z_bin[cnt] / 2.0);
else {
fprintf(stderr,
"ERROR : unquantize : invalid quantization pixel value\n");
return(-93);
}
fptr++;
sptr++;
}
}
}
*ofip = fip;
return(0);
}
/************************************************************************/
/* WSQ decompose the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_decompose(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
float *hifilt, const int hisz,
float *lofilt, const int losz)
{
int num_pix, node;
float *fdata1, *fdata_bse;
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_decompose : malloc : fdata1\n");
return(-94);
}
/* Compute the Wavelet image decomposition. */
for(node = 0; node < w_treelen; node++) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
get_lets(fdata1, fdata_bse, w_tree[node].leny, w_tree[node].lenx,
width, 1, hifilt, hisz, lofilt, losz, w_tree[node].inv_rw);
get_lets(fdata_bse, fdata1, w_tree[node].lenx, w_tree[node].leny,
1, width, hifilt, hisz, lofilt, losz, w_tree[node].inv_cl);
}
free(fdata1);
return(0);
}
/************************************************************/
/************************************************************/
void get_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lopass, *hipass; /* pointers of where to put lopass
and hipass filter outputs */
float *p0,*p1; /* pointers to image pixels used */
int pix, rw_cl; /* pixel counter and row/column counter */
int i, da_ev; /* even or odd row/column of pixels */
int fi_ev;
int loc, hoc, nstr, pstr;
int llen, hlen;
int lpxstr, lspxstr;
float *lpx, *lspx;
int hpxstr, hspxstr;
float *hpx, *hspx;
int olle, ohle;
int olre, ohre;
int lle, lle2;
int lre, lre2;
int hle, hle2;
int hre, hre2;
da_ev = len2 % 2;
fi_ev = lsz % 2;
if(fi_ev) {
loc = (lsz-1)/2;
hoc = (hsz-1)/2 - 1;
olle = 0;
ohle = 0;
olre = 0;
ohre = 0;
}
else {
loc = lsz/2 - 2;
hoc = hsz/2 - 2;
olle = 1;
ohle = 1;
olre = 1;
ohre = 1;
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
for(rw_cl = 0; rw_cl < len1; rw_cl++) {
if(inv) {
hipass = ne + rw_cl * pitch;
lopass = hipass + hlen * stride;
}
else {
lopass = ne + rw_cl * pitch;
hipass = lopass + llen * stride;
}
p0 = old + rw_cl * pitch;
p1 = p0 + (len2-1) * stride;
lspx = p0 + (loc * stride);
lspxstr = nstr;
lle2 = olle;
lre2 = olre;
hspx = p0 + (hoc * stride);
hspxstr = nstr;
hle2 = ohle;
hre2 = ohre;
for(pix = 0; pix < hlen; pix++) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
hpxstr = hspxstr;
hpx = hspx;
hle = hle2;
hre = hre2;
*hipass = *hpx * hi[0];
for(i = 1; i < hsz; i++) {
if(hpx == p0){
if(hle) {
hpxstr = 0;
hle = 0;
}
else
hpxstr = pstr;
}
if(hpx == p1){
if(hre) {
hpxstr = 0;
hre = 0;
}
else
hpxstr = nstr;
}
hpx += hpxstr;
*hipass += *hpx * hi[i];
}
hipass += stride;
for(i = 0; i < 2; i++) {
if(lspx == p0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
if(hspx == p0){
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else
hspxstr = pstr;
}
hspx += hspxstr;
}
}
if(da_ev) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
}
}
if(!fi_ev) {
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
}
/************************************************************************/
/* WSQ reconstructs the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_reconstruct(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
const DTT_TABLE *dtt_table)
{
int num_pix, node;
float *fdata1, *fdata_bse;
if(dtt_table->lodef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Lopass filter coefficients not defined\n");
return(-95);
}
if(dtt_table->hidef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Hipass filter coefficients not defined\n");
return(-96);
}
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_reconstruct : malloc : fdata1\n");
return(-97);
}
/* Reconstruct floating point pixmap from wavelet subband data. */
for (node = w_treelen - 1; node >= 0; node--) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
join_lets(fdata1, fdata_bse, w_tree[node].lenx, w_tree[node].leny,
1, width,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_cl);
join_lets(fdata_bse, fdata1, w_tree[node].leny, w_tree[node].lenx,
width, 1,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_rw);
}
free(fdata1);
return(0);
}
/****************************************************************/
void join_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lp0, *lp1;
float *hp0, *hp1;
float *lopass, *hipass; /* lo/hi pass image pointers */
float *limg, *himg;
int pix, cl_rw; /* pixel counter and column/row counter */
int i, da_ev; /* if "scanline" is even or odd and */
int loc, hoc;
int hlen, llen;
int nstr, pstr;
int tap;
int fi_ev;
int olle, ohle, olre, ohre;
int lle, lle2, lre, lre2;
int hle, hle2, hre, hre2;
float *lpx, *lspx;
int lpxstr, lspxstr;
int lstap, lotap;
float *hpx, *hspx;
int hpxstr, hspxstr;
int hstap, hotap;
int asym, fhre = 0, ofhre;
float ssfac, osfac, sfac;
da_ev = len2 % 2;
fi_ev = lsz % 2;
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
if(fi_ev) {
asym = 0;
ssfac = 1.0;
ofhre = 0;
loc = (lsz-1)/4;
hoc = (hsz+1)/4 - 1;
lotap = ((lsz-1)/2) % 2;
hotap = ((hsz+1)/2) % 2;
if(da_ev) {
olle = 0;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 0;
olre = 1;
ohle = 1;
ohre = 0;
}
}
else {
asym = 1;
ssfac = -1.0;
ofhre = 2;
loc = lsz/4 - 1;
hoc = hsz/4 - 1;
lotap = (lsz/2) % 2;
hotap = (hsz/2) % 2;
if(da_ev) {
olle = 1;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 1;
olre = 1;
ohle = 1;
ohre = 1;
}
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
for (cl_rw = 0; cl_rw < len1; cl_rw++) {
limg = ne + cl_rw * pitch;
himg = limg;
*himg = 0.0;
*(himg + stride) = 0.0;
if(inv) {
hipass = old + cl_rw * pitch;
lopass = hipass + stride * hlen;
}
else {
lopass = old + cl_rw * pitch;
hipass = lopass + stride * llen;
}
lp0 = lopass;
lp1 = lp0 + (llen-1) * stride;
lspx = lp0 + (loc * stride);
lspxstr = nstr;
lstap = lotap;
lle2 = olle;
lre2 = olre;
hp0 = hipass;
hp1 = hp0 + (hlen-1) * stride;
hspx = hp0 + (hoc * stride);
hspxstr = nstr;
hstap = hotap;
hle2 = ohle;
hre2 = ohre;
osfac = ssfac;
for(pix = 0; pix < hlen; pix++) {
for(tap = lstap; tap >=0; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(lspx == lp0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
lstap = 1;
for(tap = hstap; tap >=0; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
fhre = ofhre;
sfac = osfac;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
if(hspx == hp0) {
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else {
hspxstr = pstr;
osfac = 1.0;
}
}
hspx += hspxstr;
hstap = 1;
}
if(da_ev)
if(lotap)
lstap = 1;
else
lstap = 0;
else
if(lotap)
lstap = 2;
else
lstap = 1;
for(tap = 1; tap >= lstap; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(da_ev) {
if(hotap)
hstap = 1;
else
hstap = 0;
if(hsz == 2) {
hspx -= hspxstr;
fhre = 1;
}
}
else
if(hotap)
hstap = 2;
else
hstap = 1;
for(tap = 1; tap >= hstap; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
sfac = osfac;
if(hsz != 2)
fhre = ofhre;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
}
if(!fi_ev)
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
/*****************************************************/
/* Routine to execute an integer sign determination */
/*****************************************************/
int int_sign(
const int power) /* "sign" power */
{
int cnt, num = -1; /* counter and sign return value */
if(power == 0)
return 1;
for(cnt = 1; cnt < power; cnt++)
num *= -1;
return num;
}
/*************************************************************/
/* Computes size of compressed image file including headers, */
/* tables, and parameters. */
/*************************************************************/
int image_size(
const int blocklen, /* length of the compressed blocks */
short *huffbits1, /* huffman table parameters */
short *huffbits2)
{
int tot_size, cnt;
tot_size = blocklen; /* size of three compressed blocks */
tot_size += 58; /* size of transform table */
tot_size += 389; /* size of quantization table */
tot_size += 17; /* size of frame header */
tot_size += 3; /* size of block 1 */
tot_size += 3; /* size of block 2 */
tot_size += 3; /* size of block 3 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits1[cnt]; /* size of huffvalues1 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits2[cnt]; /* size of huffvalues2 */
tot_size += 20; /* SOI,SOF,SOB(3),DTT,DQT,DHT(2),EOI */
return tot_size;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Initializes memory used by the WSQ decoder. */
/*************************************************************/
void init_wsq_decoder_resources()
{
/* Added 02-24-05 by MDG */
/* Init dymanically allocated members to NULL */
/* for proper memory management in: */
/* read_transform_table() */
/* getc_transform_table() */
/* free_wsq_resources() */
dtt_table.lofilt = (float *)NULL;
dtt_table.hifilt = (float *)NULL;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Deallocates memory used by the WSQ decoder. */
/*************************************************************/
void free_wsq_decoder_resources()
{
if(dtt_table.lofilt != (float *)NULL){
free(dtt_table.lofilt);
dtt_table.lofilt = (float *)NULL;
}
if(dtt_table.hifilt != (float *)NULL){
free(dtt_table.hifilt);
dtt_table.hifilt = (float *)NULL;
}
}
/************************************************************************
#cat: delete_comments_wsq - Deletes all comments in a WSQ compressed file.
*************************************************************************/
/*****************************************************************/
int delete_comments_wsq(unsigned char **ocdata, int *oclen,
unsigned char *idata, const int ilen)
{
int ret, nlen, nalloc, stp;
unsigned short marker, length;
unsigned char m1, m2, *ndata, *cbufptr, *ebufptr;
nalloc = ilen;
/* Initialize current filled length to 0. */
nlen = 0;
/* Allocate new compressed byte stream. */
if((ndata = (unsigned char *)malloc(nalloc * sizeof(unsigned char)))
== (unsigned char *)NULL){
fprintf(stderr, "ERROR : delete_comments_wsq : malloc : ndata\n");
return(-2);
}
cbufptr = idata;
ebufptr = idata + ilen;
/* Parse SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* Copy SOI */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
/* Read Next Marker */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
while(marker != EOI_WSQ) {
if(marker != COM_WSQ) {
/* Copy Marker and Data */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("Copying Marker %04X and Data (Length = %d)\n", marker, length);
*/
if((ret = putc_ushort(length, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_bytes(cbufptr, length-2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
cbufptr += (length-2);
if(marker == SOB_WSQ) {
stp = 0;
while(!stp) {
if((ret = getc_byte(&m1, &cbufptr, ebufptr))) {
free(ndata);
return(ret);
}
if(m1 == 0xFF) {
if((ret = getc_byte(&m2, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
if(m2 == 0x00) {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_byte(m2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
else {
cbufptr -= 2;
stp = 1;
}
}
else {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
}
}
}
else {
/* Don't Copy Comments. Print to stdout. */
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("COMMENT (Length %d):\n", length-2);
for(i = 0; i < length-2; i++)
printf("%c", *(cbufptr+i));
printf("\n");
*/
cbufptr += length-2;
}
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
}
/* Copy EOI Marker */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
*ocdata = ndata;
*oclen = nlen;
return(0);
}
| 30.595461 | 82 | 0.448202 | mahizhvannan |
51388507df9298375b670a75a0448f730e9b882a | 1,291 | hh | C++ | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | 2 | 2021-07-05T02:26:11.000Z | 2022-01-11T10:37:20.000Z | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | null | null | null | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | 1 | 2022-01-11T10:39:01.000Z | 2022-01-11T10:39:01.000Z | //===- WordLineDriver.hh --------------------------------------------------===//
//
// The CIM Hardware Simulator Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#pragma once
#include "types.hh"
#include "CrossBarArray.hh"
namespace cimHW {
class WordLineDriver {
public:
WordLineDriver(const unsigned maxWordlines, const unsigned integerLen, const unsigned fractionLen) noexcept;
void setInput(const VectorXnum &inputVector, const unsigned OUSize);
CrossBarArray::WordLineVector getNextWordLine();
virtual RowVectorXui quantize2TwoComplement(const numType x) const;
void reset();
private:
// basic property of a wordline driver
const unsigned m_maxWordlines;
const unsigned m_integerLen;
const unsigned m_fractionLen;
const unsigned m_nBits;
// internal cursor
unsigned m_wordlines;
unsigned m_bitsIndex;
unsigned m_OUSize;
unsigned m_OUIndex;
MatrixXuiRowMajor m_buffer;
};
} // namespace cimHW
| 33.102564 | 110 | 0.522076 | ONNC |
513da54bf06620d5fd47c5a679cbfdfeab902860 | 47,571 | cc | C++ | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 38 | 2017-07-26T14:48:12.000Z | 2022-03-24T23:48:55.000Z | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 74 | 2017-03-15T21:07:34.000Z | 2022-03-18T07:53:11.000Z | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 43 | 2017-03-10T15:27:28.000Z | 2022-03-05T10:55:38.000Z | /*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include <algorithm>
#include "messagebox.h"
#include "schedule_list.h"
#include "line_management_gui.h"
#include "components/gui_convoiinfo.h"
#include "components/gui_divider.h"
#include "line_item.h"
#include "simwin.h"
#include "../simcolor.h"
#include "../simdepot.h"
#include "../simhalt.h"
#include "../simworld.h"
#include "../simevent.h"
#include "../display/simgraph.h"
#include "../simskin.h"
#include "../simconvoi.h"
#include "../vehicle/vehicle.h"
#include "../simlinemgmt.h"
#include "../simmenu.h"
#include "../utils/simstring.h"
#include "../player/simplay.h"
#include "../gui/line_class_manager.h"
#include "../bauer/vehikelbauer.h"
#include "../dataobj/schedule.h"
#include "../dataobj/translator.h"
#include "../dataobj/livery_scheme.h"
#include "../dataobj/environment.h"
#include "../boden/wege/kanal.h"
#include "../boden/wege/maglev.h"
#include "../boden/wege/monorail.h"
#include "../boden/wege/narrowgauge.h"
#include "../boden/wege/runway.h"
#include "../boden/wege/schiene.h"
#include "../boden/wege/strasse.h"
#include "../unicode.h"
#include "minimap.h"
#include "halt_info.h"
uint16 schedule_list_gui_t::livery_scheme_index = 0;
static const char *cost_type[MAX_LINE_COST] =
{
"Free Capacity",
"Transported",
"Distance",
"Average speed",
// "Maxspeed",
"Comfort",
"Revenue",
"Operation",
"Refunds",
"Road toll",
"Profit",
"Convoys",
"Departures",
"Scheduled"
};
const uint8 cost_type_color[MAX_LINE_COST] =
{
COL_FREE_CAPACITY,
COL_TRANSPORTED,
COL_DISTANCE,
COL_AVERAGE_SPEED,
COL_COMFORT,
COL_REVENUE,
COL_OPERATION,
COL_CAR_OWNERSHIP,
COL_TOLL,
COL_PROFIT,
COL_VEHICLE_ASSETS,
//COL_COUNVOI_COUNT,
COL_MAXSPEED,
COL_LILAC
};
static uint32 bFilterStates = 0;
static uint8 tabs_to_lineindex[8];
static uint8 max_idx=0;
static uint8 statistic[MAX_LINE_COST]={
LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_DISTANCE, LINE_AVERAGE_SPEED, LINE_COMFORT, LINE_REVENUE, LINE_OPERATIONS, LINE_REFUNDS, LINE_WAYTOLL, LINE_PROFIT, LINE_CONVOIS, LINE_DEPARTURES, LINE_DEPARTURES_SCHEDULED
//std LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_REVENUE, LINE_OPERATIONS, LINE_PROFIT, LINE_CONVOIS, LINE_DISTANCE, LINE_MAXSPEED, LINE_WAYTOLL
};
static uint8 statistic_type[MAX_LINE_COST]={
STANDARD, STANDARD, STANDARD, STANDARD, STANDARD, MONEY, MONEY, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD
//std STANDARD, STANDARD, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD, MONEY
};
static const char * line_alert_helptexts[5] =
{
"line_nothing_moved",
"line_missing_scheduled_slots",
"line_has_obsolete_vehicles",
"line_overcrowded",
"line_has_upgradeable_vehicles"
};
enum sort_modes_t { SORT_BY_NAME=0, SORT_BY_ID, SORT_BY_PROFIT, SORT_BY_TRANSPORTED, SORT_BY_CONVOIS, SORT_BY_DISTANCE, MAX_SORT_MODES };
static uint8 current_sort_mode = 0;
#define LINE_NAME_COLUMN_WIDTH ((D_BUTTON_WIDTH*3)+11+4)
#define SCL_HEIGHT (min(L_DEFAULT_WINDOW_HEIGHT/2+D_TAB_HEADER_HEIGHT,(15*LINESPACE)))
#define L_DEFAULT_WINDOW_HEIGHT max(305, 24*LINESPACE)
/// selected convoy tab
static uint8 selected_convoy_tab = 0;
/// selected line tab per player
static uint8 selected_tab[MAX_PLAYER_COUNT] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/// selected line per tab (static)
linehandle_t schedule_list_gui_t::selected_line[MAX_PLAYER_COUNT][simline_t::MAX_LINE_TYPE];
// selected convoy list display mode
static uint8 selected_cnvlist_mode[MAX_PLAYER_COUNT] = {0};
// sort stuff
schedule_list_gui_t::sort_mode_t schedule_list_gui_t::sortby = by_name;
static uint8 default_sortmode = 0;
bool schedule_list_gui_t::sortreverse = false;
const char *schedule_list_gui_t::sort_text[SORT_MODES] = {
"cl_btn_sort_name",
"cl_btn_sort_schedule",
"cl_btn_sort_income",
"cl_btn_sort_loading_lvl",
"cl_btn_sort_max_speed",
"cl_btn_sort_power",
"cl_btn_sort_value",
"cl_btn_sort_age",
"cl_btn_sort_range"
};
gui_line_waiting_status_t::gui_line_waiting_status_t(linehandle_t line_)
{
line = line_;
set_table_layout(1, 0);
set_spacing(scr_size(1, 0));
init();
}
void gui_line_waiting_status_t::init()
{
remove_all();
if (line.is_bound()) {
schedule = line->get_schedule();
if( !schedule->get_count() ) return; // nothing to show
uint8 cols; // table cols
cols = line->get_goods_catg_index().get_count()+show_name+1;
add_table(cols, 0);
{
// header
new_component<gui_empty_t>();
if (show_name) {
new_component<gui_label_t>("stations");
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index) ) {
add_table(2,1);
{
new_component<gui_image_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_symbol(), 0, ALIGN_NONE, true);
new_component<gui_label_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_name());
}
end_table();
}
}
// border
new_component<gui_empty_t>();
for (uint8 i = 1; i < cols; ++i) {
new_component<gui_border_t>();
}
uint8 entry_idx = 0;
FORX(minivec_tpl<schedule_entry_t>, const& i, schedule->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, line->get_owner());
if( !halt.is_bound() ) { continue; }
const bool is_interchange = (halt->registered_lines.get_count() + halt->registered_convoys.get_count()) > 1;
new_component<gui_schedule_entry_number_t>(entry_idx, halt->get_owner()->get_player_color1(),
is_interchange ? gui_schedule_entry_number_t::number_style::interchange : gui_schedule_entry_number_t::number_style::halt,
scr_size(D_ENTRY_NO_WIDTH, max(D_POS_BUTTON_HEIGHT, D_ENTRY_NO_HEIGHT)),
halt->get_basis_pos3d()
);
if (show_name) {
gui_label_buf_t *lb = new_component<gui_label_buf_t>();
lb->buf().append(halt->get_name());
lb->update();
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index)) {
new_component<gui_halt_waiting_catg_t>(halt, catg_index);
}
}
}
}
end_table();
}
}
void gui_line_waiting_status_t::draw(scr_coord offset)
{
if (line.is_bound()) {
if (!line->get_schedule()->matches(world(), schedule)) {
init();
}
}
set_size(get_size());
gui_aligned_container_t::draw(offset);
}
schedule_list_gui_t::schedule_list_gui_t(player_t *player_) :
gui_frame_t(translator::translate("Line Management"), player_),
player(player_),
scrolly_convois(&cont),
cont_haltlist(linehandle_t()),
scrolly_haltestellen(&cont_tab_haltlist, true, true),
scroll_times_history(&cont_times_history, true, true),
scrolly_line_info(&cont_line_info, true, true),
scl(gui_scrolled_list_t::listskin, line_scrollitem_t::compare),
lbl_filter("Line Filter"),
cont_line_capacity_by_catg(linehandle_t(), convoihandle_t()),
convoy_infos(),
halt_entry_origin(-1), halt_entry_dest(-1),
routebar_middle(player_->get_player_color1(), gui_colored_route_bar_t::downward)
{
selection = -1;
schedule_filter[0] = 0;
old_schedule_filter[0] = 0;
last_schedule = NULL;
old_player = NULL;
line_goods_catg_count = 0;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
// init scrolled list
scl.set_pos(scr_coord(0,1));
scl.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT-18));
scl.set_highlight_color(color_idx_to_rgb(player->get_player_color1()+1));
scl.add_listener(this);
// tab panel
tabs.set_pos(scr_coord(11,5));
tabs.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT));
tabs.add_tab(&scl, translator::translate("All"));
max_idx = 0;
tabs_to_lineindex[max_idx++] = simline_t::line;
// now add all specific tabs
if(maglev_t::default_maglev) {
tabs.add_tab(&scl, translator::translate("Maglev"), skinverwaltung_t::maglevhaltsymbol, translator::translate("Maglev"));
tabs_to_lineindex[max_idx++] = simline_t::maglevline;
}
if(monorail_t::default_monorail) {
tabs.add_tab(&scl, translator::translate("Monorail"), skinverwaltung_t::monorailhaltsymbol, translator::translate("Monorail"));
tabs_to_lineindex[max_idx++] = simline_t::monorailline;
}
if(schiene_t::default_schiene) {
tabs.add_tab(&scl, translator::translate("Train"), skinverwaltung_t::zughaltsymbol, translator::translate("Train"));
tabs_to_lineindex[max_idx++] = simline_t::trainline;
}
if(narrowgauge_t::default_narrowgauge) {
tabs.add_tab(&scl, translator::translate("Narrowgauge"), skinverwaltung_t::narrowgaugehaltsymbol, translator::translate("Narrowgauge"));
tabs_to_lineindex[max_idx++] = simline_t::narrowgaugeline;
}
if (!vehicle_builder_t::get_info(tram_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Tram"), skinverwaltung_t::tramhaltsymbol, translator::translate("Tram"));
tabs_to_lineindex[max_idx++] = simline_t::tramline;
}
if(strasse_t::default_strasse) {
tabs.add_tab(&scl, translator::translate("Truck"), skinverwaltung_t::autohaltsymbol, translator::translate("Truck"));
tabs_to_lineindex[max_idx++] = simline_t::truckline;
}
if (!vehicle_builder_t::get_info(water_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Ship"), skinverwaltung_t::schiffshaltsymbol, translator::translate("Ship"));
tabs_to_lineindex[max_idx++] = simline_t::shipline;
}
if(runway_t::default_runway) {
tabs.add_tab(&scl, translator::translate("Air"), skinverwaltung_t::airhaltsymbol, translator::translate("Air"));
tabs_to_lineindex[max_idx++] = simline_t::airline;
}
tabs.add_listener(this);
add_component(&tabs);
// editable line name
inp_name.add_listener(this);
inp_name.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH+23, D_MARGIN_TOP));
inp_name.set_visible(false);
add_component(&inp_name);
// sort button on convoy list, define this first to prevent overlapping
sortedby.set_pos(scr_coord(BUTTON1_X, 2));
sortedby.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
sortedby.set_max_size(scr_size(D_BUTTON_WIDTH * 1.5, LINESPACE * 8));
for (int i = 0; i < SORT_MODES; i++) {
sortedby.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(sort_text[i]), SYSCOL_TEXT);
}
sortedby.set_selection(default_sortmode);
sortedby.add_listener(this);
cont_convoys.add_component(&sortedby);
// convoi list
cont.set_size(scr_size(200, 80));
cont.set_pos(scr_coord(D_H_SPACE, D_V_SPACE));
scrolly_convois.set_pos(scr_coord(0, D_BUTTON_HEIGHT+D_H_SPACE));
scrolly_convois.set_show_scroll_y(true);
scrolly_convois.set_scroll_amount_y(40);
scrolly_convois.set_visible(false);
cont_convoys.add_component(&scrolly_convois);
scrolly_line_info.set_visible(false);
cont_line_info.set_table_layout(1,0);
cont_line_info.add_table(2,0)->set_spacing(scr_size(D_H_SPACE, 0));
{
cont_line_info.add_component(&halt_entry_origin);
cont_line_info.add_component(&lb_line_origin);
cont_line_info.add_component(&routebar_middle);
cont_line_info.new_component<gui_empty_t>();
cont_line_info.add_component(&halt_entry_dest);
cont_line_info.add_component(&lb_line_destination);
}
cont_line_info.end_table();
cont_line_info.add_table(3,1);
{
cont_line_info.add_component(&lb_travel_distance);
if (skinverwaltung_t::service_frequency) {
cont_line_info.new_component<gui_image_t>(skinverwaltung_t::service_frequency->get_image_id(0), 0, ALIGN_NONE, true)->set_tooltip(translator::translate("Service frequency"));
}
else {
cont_line_info.new_component<gui_label_t>("Service frequency");
}
cont_line_info.add_component(&lb_service_frequency);
}
cont_line_info.end_table();
cont_line_info.add_table(2,1);
{
cont_line_info.add_component(&lb_convoy_count);
bt_withdraw_line.init(button_t::box_state, "Withdraw All", scr_coord(0, 0), scr_size(D_BUTTON_WIDTH+18,D_BUTTON_HEIGHT));
bt_withdraw_line.set_tooltip("Convoi is sold when all wagons are empty.");
if (skinverwaltung_t::alerts) {
bt_withdraw_line.set_image(skinverwaltung_t::alerts->get_image_id(2));
}
bt_withdraw_line.add_listener(this);
cont_line_info.add_component(&bt_withdraw_line);
}
cont_line_info.end_table();
cont_line_info.new_component<gui_divider_t>();
cont_line_info.add_component(&cont_line_capacity_by_catg);
scrolly_line_info.set_pos(scr_coord(0, 8 + SCL_HEIGHT + D_BUTTON_HEIGHT + D_BUTTON_HEIGHT + 2));
add_component(&scrolly_line_info);
// filter lines by
lbl_filter.set_pos( scr_coord( 11, 7+SCL_HEIGHT+2 ) );
add_component(&lbl_filter);
inp_filter.set_pos( scr_coord( 11+D_BUTTON_WIDTH, 7+SCL_HEIGHT ) );
inp_filter.set_size( scr_size( D_BUTTON_WIDTH*2- D_BUTTON_HEIGHT *3, D_EDIT_HEIGHT ) );
inp_filter.set_text( schedule_filter, lengthof(schedule_filter) );
// inp_filter.set_tooltip("Only show lines containing");
inp_filter.add_listener(this);
add_component(&inp_filter);
filter_btn_all_pas.init(button_t::roundbox_state, NULL, scr_coord(inp_filter.get_pos() + scr_coord(inp_filter.get_size().w, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_pas.set_image(skinverwaltung_t::passengers->get_image_id(0));
filter_btn_all_pas.set_tooltip("filter_pas_line");
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
add_component(&filter_btn_all_pas);
filter_btn_all_pas.add_listener(this);
filter_btn_all_mails.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_pas.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_mails.set_image(skinverwaltung_t::mail->get_image_id(0));
filter_btn_all_mails.set_tooltip("filter_mail_line");
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
filter_btn_all_mails.add_listener(this);
add_component(&filter_btn_all_mails);
filter_btn_all_freights.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_mails.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_freights.set_image(skinverwaltung_t::goods->get_image_id(0));
filter_btn_all_freights.set_tooltip("filter_freight_line");
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
filter_btn_all_freights.add_listener(this);
add_component(&filter_btn_all_freights);
// normal buttons edit new remove
bt_new_line.init(button_t::roundbox, "New Line", scr_coord(11, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_new_line.add_listener(this);
add_component(&bt_new_line);
bt_edit_line.init(button_t::roundbox, "Update Line", scr_coord(11+D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_edit_line.set_tooltip("Modify the selected line");
bt_edit_line.add_listener(this);
bt_edit_line.disable();
add_component(&bt_edit_line);
bt_delete_line.init(button_t::roundbox, "Delete Line", scr_coord(11+2*D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_delete_line.set_tooltip("Delete the selected line (if without associated convois).");
bt_delete_line.add_listener(this);
bt_delete_line.disable();
add_component(&bt_delete_line);
int offset_y = D_MARGIN_TOP + D_BUTTON_HEIGHT*2;
bt_line_class_manager.init(button_t::roundbox_state, "line_class_manager", scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y), D_BUTTON_SIZE);
bt_line_class_manager.set_tooltip("change_the_classes_for_the_entire_line");
bt_line_class_manager.set_visible(false);
bt_line_class_manager.add_listener(this);
add_component(&bt_line_class_manager);
offset_y += D_BUTTON_HEIGHT;
// Select livery
livery_selector.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y));
livery_selector.set_focusable(false);
livery_selector.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
livery_selector.set_max_size(scr_size(D_BUTTON_WIDTH - 8, LINESPACE * 8 + 2 + 16));
livery_selector.set_highlight_color(1);
livery_selector.clear_elements();
livery_selector.add_listener(this);
add_component(&livery_selector);
// sort asc/desc switching button
sort_order.set_typ(button_t::sortarrow_state); // NOTE: This dialog is not yet auto-aligned, so we need to pre-set the typ to calculate the size
sort_order.init(button_t::sortarrow_state, "", scr_coord(BUTTON1_X + D_BUTTON_WIDTH * 1.5 + D_H_SPACE, 2), sort_order.get_min_size());
sort_order.set_tooltip(translator::translate("cl_btn_sort_order"));
sort_order.add_listener(this);
sort_order.pressed = sortreverse;
cont_convoys.add_component(&sort_order);
bt_mode_convois.init(button_t::roundbox, gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]], scr_coord(BUTTON3_X, 2), scr_size(D_BUTTON_WIDTH+15, D_BUTTON_HEIGHT));
bt_mode_convois.add_listener(this);
cont_convoys.add_component(&bt_mode_convois);
info_tabs.add_tab(&cont_convoys, translator::translate("Convoys"));
offset_y += D_BUTTON_HEIGHT;
// right tabs
info_tabs.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH-4, offset_y));
info_tabs.add_listener(this);
info_tabs.set_size(scr_size(get_windowsize().w- LINE_NAME_COLUMN_WIDTH+4+D_MARGIN_RIGHT, get_windowsize().h-offset_y));
add_component(&info_tabs);
//CHART
chart.set_dimension(12, 1000);
chart.set_pos( scr_coord(68, LINESPACE) );
chart.set_seed(0);
chart.set_background(SYSCOL_CHART_BACKGROUND);
chart.set_ltr(env_t::left_to_right_graphs);
cont_charts.add_component(&chart);
// add filter buttons
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].init(button_t::box_state,cost_type[i],scr_coord(0,0), D_BUTTON_SIZE);
filterButtons[i].add_listener(this);
filterButtons[i].background_color = color_idx_to_rgb(cost_type_color[i]);
cont_charts.add_component(filterButtons + i);
}
info_tabs.add_tab(&cont_charts, translator::translate("Chart"));
info_tabs.set_active_tab_index(selected_convoy_tab);
cont_times_history.set_table_layout(1,0);
info_tabs.add_tab(&scroll_times_history, translator::translate("times_history"));
cont_tab_haltlist.set_table_layout(1,0);
bt_show_halt_name.init(button_t::square_state, "show station names");
bt_show_halt_name.set_tooltip("helptxt_show_station_name");
bt_show_halt_name.pressed=true;
bt_show_halt_name.add_listener(this);
cont_tab_haltlist.add_component(&bt_show_halt_name);
cont_tab_haltlist.add_component(&cont_haltlist);
info_tabs.add_tab(&scrolly_haltestellen, translator::translate("waiting_status"));
// recover last selected line
int index = 0;
for( uint i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i] == selected_tab[player->get_player_nr()] ) {
line = selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]];
// check owner here: selected_line[][] is not reset between games, so line could have another player as owner
if (line.is_bound() && line->get_owner() != player) {
line = linehandle_t();
}
index = i;
break;
}
}
selected_tab[player->get_player_nr()] = tabs_to_lineindex[index]; // reset if previous selected tab is not there anymore
tabs.set_active_tab_index(index);
if(index>0) {
bt_new_line.enable();
}
else {
bt_new_line.disable();
}
update_lineinfo( line );
// resize button
set_min_windowsize(scr_size(LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*3 + D_MARGIN_LEFT*2, L_DEFAULT_WINDOW_HEIGHT));
set_resizemode(diagonal_resize);
resize(scr_coord(0,0));
resize(scr_coord(D_BUTTON_WIDTH, LINESPACE*3+D_V_SPACE)); // suitable for 4 buttons horizontally and 5 convoys vertically
build_line_list(index);
}
schedule_list_gui_t::~schedule_list_gui_t()
{
delete last_schedule;
// change line name if necessary
rename_line();
}
/**
* Mouse clicks are hereby reported to the GUI-Components
*/
bool schedule_list_gui_t::infowin_event(const event_t *ev)
{
if(ev->ev_class == INFOWIN) {
if(ev->ev_code == WIN_CLOSE) {
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
else if( (ev->ev_code==WIN_OPEN || ev->ev_code==WIN_TOP) && line.is_bound() ) {
if( line->count_convoys()>0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( line->get_convoy(0) );
}
else {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
}
}
return gui_frame_t::infowin_event(ev);
}
bool schedule_list_gui_t::action_triggered( gui_action_creator_t *comp, value_t v )
{
if(comp == &bt_edit_line) {
if(line.is_bound()) {
create_win( new line_management_gui_t(line, player), w_info, (ptrdiff_t)line.get_rep() );
}
}
else if(comp == &bt_new_line) {
// create typed line
assert( tabs.get_active_tab_index() > 0 && tabs.get_active_tab_index()<max_idx );
// update line schedule via tool!
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
int type = tabs_to_lineindex[tabs.get_active_tab_index()];
buf.printf( "c,0,%i,0,0|%i|", type, type );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
else if(comp == &bt_delete_line) {
if(line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "d,%i", line.get_id() );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
}
else if(comp == &bt_withdraw_line) {
bt_withdraw_line.pressed ^= 1;
if (line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "w,%i,%i", line.get_id(), bt_withdraw_line.pressed );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &bt_line_class_manager)
{
create_win(20, 20, new line_class_manager_t(line), w_info, magic_line_class_manager + line.get_id());
return true;
}
else if (comp == &sortedby) {
int tmp = sortedby.get_selection();
if (tmp >= 0 && tmp < sortedby.count_elements())
{
sortedby.set_selection(tmp);
set_sortierung((sort_mode_t)tmp);
}
else {
sortedby.set_selection(0);
set_sortierung(by_name);
}
default_sortmode = (uint8)tmp;
update_lineinfo(line);
}
else if (comp == &sort_order) {
set_reverse(!get_reverse());
update_lineinfo(line);
sort_order.pressed = sortreverse;
}
else if (comp == &bt_mode_convois) {
selected_cnvlist_mode[player->get_player_nr()] = (selected_cnvlist_mode[player->get_player_nr()] + 1) % gui_convoy_formation_t::CONVOY_OVERVIEW_MODES;
bt_mode_convois.set_text(gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]]);
update_lineinfo(line);
}
else if(comp == &livery_selector)
{
sint32 livery_selection = livery_selector.get_selection();
if(livery_selection < 0)
{
livery_selector.set_selection(0);
livery_selection = 0;
}
livery_scheme_index = livery_scheme_indices.empty()? 0 : livery_scheme_indices[livery_selection];
if (line.is_bound())
{
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "V,%i,%i", line.get_id(), livery_scheme_index );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &tabs) {
int const tab = tabs.get_active_tab_index();
uint8 old_selected_tab = selected_tab[player->get_player_nr()];
selected_tab[player->get_player_nr()] = tabs_to_lineindex[tab];
if( old_selected_tab == simline_t::line && selected_line[player->get_player_nr()][0].is_bound() && selected_line[player->get_player_nr()][0]->get_linetype() == selected_tab[player->get_player_nr()] ) {
// switching from general to same waytype tab while line is seletced => use current line instead
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = selected_line[player->get_player_nr()][0];
}
update_lineinfo( selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] );
build_line_list(tab);
if (tab>0) {
bt_new_line.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
else {
bt_new_line.disable();
}
}
else if(comp == &info_tabs){
selected_convoy_tab = (uint8)info_tabs.get_active_tab_index();
if (selected_convoy_tab == 3) {
cont_haltlist.init();
}
}
else if (comp == &scl) {
if( line_scrollitem_t *li=(line_scrollitem_t *)scl.get_element(v.i) ) {
update_lineinfo( li->get_line() );
}
else {
// no valid line
update_lineinfo(linehandle_t());
}
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = line;
selected_line[player->get_player_nr()][0] = line; // keep these the same in overview
}
else if (comp == &inp_filter) {
if( strcmp(old_schedule_filter,schedule_filter) ) {
build_line_list(tabs.get_active_tab_index());
strcpy(old_schedule_filter,schedule_filter);
}
}
else if (comp == &inp_name) {
rename_line();
}
else if (comp == &filter_btn_all_pas) {
line_type_flags ^= (1 << simline_t::all_pas);
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_mails) {
line_type_flags ^= (1 << simline_t::all_mail);
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_freights) {
line_type_flags ^= (1 << simline_t::all_freight);
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &bt_show_halt_name) {
bt_show_halt_name.pressed = !bt_show_halt_name.pressed;
cont_haltlist.set_show_name( bt_show_halt_name.pressed );
}
else {
if (line.is_bound()) {
for ( int i = 0; i<MAX_LINE_COST; i++) {
if (comp == &filterButtons[i]) {
bFilterStates ^= (1 << i);
if(bFilterStates & (1 << i)) {
chart.show_curve(i);
}
else {
chart.hide_curve(i);
}
break;
}
}
}
}
return true;
}
void schedule_list_gui_t::reset_line_name()
{
// change text input of selected line
if (line.is_bound()) {
tstrncpy(old_line_name, line->get_name(), sizeof(old_line_name));
tstrncpy(line_name, line->get_name(), sizeof(line_name));
inp_name.set_text(line_name, sizeof(line_name));
}
}
void schedule_list_gui_t::rename_line()
{
if (line.is_bound()
&& ((player == welt->get_active_player() && !welt->get_active_player()->is_locked()) || welt->get_active_player() == welt->get_public_player())) {
const char *t = inp_name.get_text();
// only change if old name and current name are the same
// otherwise some unintended undo if renaming would occur
if( t && t[0] && strcmp(t, line->get_name()) && strcmp(old_line_name, line->get_name())==0) {
// text changed => call tool
cbuffer_t buf;
buf.printf( "l%u,%s", line.get_id(), t );
tool_t *tmp_tool = create_tool( TOOL_RENAME | SIMPLE_TOOL );
tmp_tool->set_default_param( buf );
welt->set_tool( tmp_tool, line->get_owner() );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
// do not trigger this command again
tstrncpy(old_line_name, t, sizeof(old_line_name));
}
}
}
void schedule_list_gui_t::draw(scr_coord pos, scr_size size)
{
if( old_line_count != player->simlinemgmt.get_line_count() ) {
show_lineinfo( line );
}
if( old_player != welt->get_active_player() ) {
// deativate buttons, if not curretn player
old_player = welt->get_active_player();
const bool activate = (old_player == player || old_player == welt->get_player( 1 )) && !welt->get_active_player()->is_locked();
bt_delete_line.enable( activate );
bt_edit_line.enable( activate );
bt_new_line.enable( activate && tabs.get_active_tab_index() > 0);
bt_withdraw_line.set_visible( activate );
livery_selector.enable( activate );
}
// if search string changed, update line selection
if( strcmp( old_schedule_filter, schedule_filter ) ) {
build_line_list(tabs.get_active_tab_index());
strcpy( old_schedule_filter, schedule_filter );
}
gui_frame_t::draw(pos, size);
if( line.is_bound() ) {
if( (!line->get_schedule()->empty() && !line->get_schedule()->matches( welt, last_schedule )) || last_vehicle_count != line->count_convoys() || line->get_goods_catg_index().get_count() != line_goods_catg_count ) {
update_lineinfo( line );
}
// line type symbol
display_color_img(line->get_linetype_symbol(), pos.x + LINE_NAME_COLUMN_WIDTH -23, pos.y + D_TITLEBAR_HEIGHT + D_MARGIN_TOP - 42 + FIXED_SYMBOL_YOFF, 0, false, false);
PUSH_CLIP( pos.x + 1, pos.y + D_TITLEBAR_HEIGHT, size.w - 2, size.h - D_TITLEBAR_HEIGHT);
display(pos);
POP_CLIP();
}
for (int i = 0; i < MAX_LINE_COST; i++) {
filterButtons[i].pressed = ((bFilterStates & (1 << i)) != 0);
}
}
#define GOODS_SYMBOL_CELL_WIDTH 14 // TODO: This will be used in common with halt detail in the future
void schedule_list_gui_t::display(scr_coord pos)
{
uint32 icnv = line->count_convoys();
cbuffer_t buf;
char ctmp[128];
int top = D_TITLEBAR_HEIGHT + D_MARGIN_TOP + D_EDIT_HEIGHT + D_V_SPACE;
int left = LINE_NAME_COLUMN_WIDTH;
sint64 profit = line->get_finance_history(0,LINE_PROFIT);
uint32 line_total_vehicle_count=0;
for (uint32 i = 0; i<icnv; i++) {
convoihandle_t const cnv = line->get_convoy(i);
// we do not want to count the capacity of depot convois
if (!cnv->in_depot()) {
line_total_vehicle_count += cnv->get_vehicle_count();
}
}
if (last_schedule != line->get_schedule() && origin_halt.is_bound()) {
uint8 halt_symbol_style = gui_schedule_entry_number_t::halt;
lb_line_origin.buf().append(origin_halt->get_name());
if ((origin_halt->registered_lines.get_count() + origin_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_origin.init(halt_entry_idx[0], origin_halt->get_owner()->get_player_color1(), halt_symbol_style, origin_halt->get_basis_pos3d());
if (destination_halt.is_bound()) {
halt_symbol_style = gui_schedule_entry_number_t::halt;
if ((destination_halt->registered_lines.get_count() + destination_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_dest.init(halt_entry_idx[1], destination_halt->get_owner()->get_player_color1(), halt_symbol_style, destination_halt->get_basis_pos3d());
if (line->get_schedule()->is_mirrored()) {
routebar_middle.set_line_style(gui_colored_route_bar_t::doubled);
}
else {
routebar_middle.set_line_style(gui_colored_route_bar_t::downward);
}
lb_line_destination.buf().append(destination_halt->get_name());
lb_travel_distance.buf().printf("%s: %.1fkm ", translator::translate("travel_distance"), (float)(line->get_travel_distance()*world()->get_settings().get_meters_per_tile()/1000.0));
lb_travel_distance.update();
}
}
lb_line_origin.update();
lb_line_destination.update();
// convoy count
if (line->get_convoys().get_count()>1) {
lb_convoy_count.buf().printf(translator::translate("%d convois"), icnv);
}
else {
lb_convoy_count.buf().append(line->get_convoys().get_count() == 1 ? translator::translate("1 convoi") : translator::translate("no convois"));
}
if (icnv && line_total_vehicle_count>1) {
lb_convoy_count.buf().printf(translator::translate(", %d vehicles"), line_total_vehicle_count);
}
lb_convoy_count.update();
// Display service frequency
const sint64 service_frequency = line->get_service_frequency();
if(service_frequency)
{
char as_clock[32];
welt->sprintf_ticks(as_clock, sizeof(as_clock), service_frequency);
lb_service_frequency.buf().printf(" %s", as_clock);
lb_service_frequency.set_color(line->get_state() & simline_t::line_missing_scheduled_slots ? color_idx_to_rgb(COL_DARK_TURQUOISE) : SYSCOL_TEXT);
lb_service_frequency.set_tooltip(line->get_state() & simline_t::line_missing_scheduled_slots ? translator::translate(line_alert_helptexts[1]) : "");
}
else {
lb_service_frequency.buf().append("--:--");
}
lb_service_frequency.update();
int len2 = display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH, pos.y+top, translator::translate("Gewinn"), ALIGN_LEFT, SYSCOL_TEXT, true );
money_to_string(ctmp, profit/100.0);
len2 += display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH+len2+5, pos.y+top, ctmp, ALIGN_LEFT, profit>=0?MONEY_PLUS:MONEY_MINUS, true );
bt_line_class_manager.disable();
for (unsigned convoy = 0; convoy < line->count_convoys(); convoy++)
{
convoihandle_t cnv = line->get_convoy(convoy);
for (unsigned veh = 0; veh < cnv->get_vehicle_count(); veh++)
{
vehicle_t* v = cnv->get_vehicle(veh);
if (v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_PAS || v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_MAIL)
{
bt_line_class_manager.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
}
}
top += D_BUTTON_HEIGHT + LINESPACE + 1;
left = LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*1.5 + D_V_SPACE;
buf.clear();
// show the state of the line, if interresting
if (line->get_state() & simline_t::line_nothing_moved) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(2), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[0]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else {
buf.append(translator::translate(line_alert_helptexts[0]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_upgradeable_vehicles) {
if (skinverwaltung_t::upgradable) {
display_color_img_with_tooltip(skinverwaltung_t::upgradable->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[4]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[4]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_obsolete_vehicles) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[2]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len()) {
buf.append(translator::translate(line_alert_helptexts[2]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_overcrowded) {
if (skinverwaltung_t::pax_evaluation_icons) {
display_color_img_with_tooltip(skinverwaltung_t::pax_evaluation_icons->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[3]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_DARK_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[3]));
}
}
if (buf.len() > 0) {
display_proportional_clip_rgb(pos.x + left, pos.y + top, buf, ALIGN_LEFT, line->get_state_color(), true);
}
cont_line_info.set_size(cont_line_info.get_size());
}
void schedule_list_gui_t::set_windowsize(scr_size size)
{
gui_frame_t::set_windowsize(size);
int rest_width = get_windowsize().w-LINE_NAME_COLUMN_WIDTH;
int button_per_row=max(1,rest_width/(D_BUTTON_WIDTH+D_H_SPACE));
int button_rows= MAX_LINE_COST/button_per_row + ((MAX_LINE_COST%button_per_row)!=0);
scrolly_line_info.set_size( scr_size(LINE_NAME_COLUMN_WIDTH-4, get_client_windowsize().h - scrolly_line_info.get_pos().y-1) );
info_tabs.set_size( scr_size(rest_width+2, get_windowsize().h-info_tabs.get_pos().y-D_TITLEBAR_HEIGHT-1) );
scrolly_convois.set_size( scr_size(info_tabs.get_size().w+1, info_tabs.get_size().h - scrolly_convois.get_pos().y - D_H_SPACE-1) );
chart.set_size(scr_size(rest_width-68-D_MARGIN_RIGHT, SCL_HEIGHT-14-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))));
inp_name.set_size(scr_size(rest_width - 31, D_EDIT_HEIGHT));
int y=SCL_HEIGHT-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))+18;
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].set_pos( scr_coord((i%button_per_row)*(D_BUTTON_WIDTH+D_H_SPACE)+D_H_SPACE, y+(i/button_per_row)*(D_BUTTON_HEIGHT+D_H_SPACE)) );
}
}
void schedule_list_gui_t::build_line_list(int selected_tab)
{
sint32 sel = -1;
scl.clear_elements();
player->simlinemgmt.get_lines(tabs_to_lineindex[selected_tab], &lines, get_filter_type_bits(), true);
FOR(vector_tpl<linehandle_t>, const l, lines) {
// search name
if( utf8caseutf8(l->get_name(), schedule_filter) ) {
scl.new_component<line_scrollitem_t>(l);
if ( line == l ) {
sel = scl.get_count() - 1;
}
}
}
scl.set_selection( sel );
line_scrollitem_t::sort_mode = (line_scrollitem_t::sort_modes_t)current_sort_mode;
scl.sort( 0 );
scl.set_size(scl.get_size());
old_line_count = player->simlinemgmt.get_line_count();
}
/* hides show components */
void schedule_list_gui_t::update_lineinfo(linehandle_t new_line)
{
// change line name if necessary
if (line.is_bound()) {
rename_line();
}
if(new_line.is_bound()) {
const bool activate = (old_player == player || old_player == welt->get_player(1)) && !welt->get_active_player()->is_locked();
// ok, this line is visible
scrolly_convois.set_visible(true);
scrolly_haltestellen.set_visible(true);
scrolly_line_info.set_visible(new_line->get_schedule()->get_count()>0);
inp_name.set_visible(true);
livery_selector.set_visible(true);
cont_line_capacity_by_catg.set_line(new_line);
cont_times_history.set_visible(true);
cont_times_history.remove_all();
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), false);
if (!new_line->get_schedule()->is_mirrored()) {
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), true);
}
cont_haltlist.set_visible(true);
cont_haltlist.set_line(new_line);
resize(scr_size(0,0));
livery_selector.set_visible(true);
// fill container with info of line's convoys
// we do it here, since this list needs only to be
// refreshed when the user selects a new line
line_convoys.clear();
line_convoys = new_line->get_convoys();
sort_list();
uint32 i, icnv = 0;
line_goods_catg_count = new_line->get_goods_catg_index().get_count();
icnv = new_line->count_convoys();
// display convoys of line
cont.remove_all();
while (!convoy_infos.empty()) {
delete convoy_infos.pop_back();
}
convoy_infos.resize(icnv);
scr_coord_val ypos = 0;
for(i = 0; i<icnv; i++ ) {
gui_convoiinfo_t* const cinfo = new gui_convoiinfo_t(line_convoys.get_element(i), false);
cinfo->set_pos(scr_coord(0, ypos-D_MARGIN_TOP));
scr_size csize = cinfo->get_min_size();
cinfo->set_size(scr_size(400, csize.h-D_MARGINS_Y));
cinfo->set_mode(selected_cnvlist_mode[player->get_player_nr()]);
cinfo->set_switchable_label(sortby);
convoy_infos.append(cinfo);
cont.add_component(cinfo);
ypos += csize.h - D_MARGIN_TOP-D_V_SPACE*2;
}
cont.set_size(scr_size(600, ypos));
bt_delete_line.disable();
bt_withdraw_line.set_visible(false);
if( icnv>0 ) {
bt_withdraw_line.set_visible(true);
}
else {
bt_delete_line.enable( activate );
}
bt_edit_line.enable( activate );
bt_withdraw_line.pressed = new_line->get_withdraw();
bt_withdraw_line.background_color = color_idx_to_rgb( bt_withdraw_line.pressed ? COL_DARK_YELLOW-1 : COL_YELLOW );
bt_withdraw_line.text_color = color_idx_to_rgb(bt_withdraw_line.pressed ? COL_WHITE : COL_BLACK);
livery_selector.set_focusable(true);
livery_selector.clear_elements();
livery_scheme_indices.clear();
if( icnv>0 ) {
// build available livery schemes list for this line
if (new_line->count_convoys()) {
const uint16 month_now = welt->get_timeline_year_month();
vector_tpl<livery_scheme_t*>* schemes = welt->get_settings().get_livery_schemes();
ITERATE_PTR(schemes, i)
{
bool found = false;
livery_scheme_t* scheme = schemes->get_element(i);
if (scheme->is_available(month_now))
{
for (uint32 j = 0; j < new_line->count_convoys(); j++)
{
convoihandle_t const cnv_in_line = new_line->get_convoy(j);
for (int k = 0; k < cnv_in_line->get_vehicle_count(); k++) {
const vehicle_desc_t *desc = cnv_in_line->get_vehicle(k)->get_desc();
if (desc->get_livery_count()) {
const char* test_livery = scheme->get_latest_available_livery(month_now, desc);
if (test_livery) {
if (scheme->is_contained(test_livery, month_now)) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(scheme->get_name()), SYSCOL_TEXT);
livery_scheme_indices.append(i);
found = true;
break;
}
}
}
}
if (found) {
livery_selector.set_selection(livery_scheme_indices.index_of(i));
break;
}
}
}
}
}
}
if(livery_scheme_indices.empty()) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate("No livery"), SYSCOL_TEXT);
livery_selector.set_selection(0);
}
uint8 entry_idx = 0;
halt_entry_idx[0] = 255;
halt_entry_idx[1] = 255;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
FORX(minivec_tpl<schedule_entry_t>, const& i, new_line->get_schedule()->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, player);
if (halt.is_bound()) {
if (halt_entry_idx[0] == 255) {
halt_entry_idx[0] = entry_idx;
origin_halt = halt;
}
else {
halt_entry_idx[1] = entry_idx;
destination_halt = halt;
}
}
}
// chart
chart.remove_curves();
for(i=0; i<MAX_LINE_COST; i++) {
chart.add_curve(color_idx_to_rgb(cost_type_color[i]), new_line->get_finance_history(), MAX_LINE_COST, statistic[i], MAX_MONTHS, statistic_type[i], filterButtons[i].pressed, true, statistic_type[i]*2 );
if (bFilterStates & (1 << i)) {
chart.show_curve(i);
}
}
chart.set_visible(true);
// has this line a single running convoi?
if( new_line.is_bound() && new_line->count_convoys() > 0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( new_line->get_convoy(0) );
}
else {
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
delete last_schedule;
last_schedule = new_line->get_schedule()->copy();
last_vehicle_count = new_line->count_convoys();
}
else if( inp_name.is_visible() ) {
// previously a line was visible
// thus the need to hide everything
line_convoys.clear();
cont.remove_all();
cont_times_history.remove_all();
cont_line_capacity_by_catg.set_line(linehandle_t());
scrolly_convois.set_visible(false);
scrolly_haltestellen.set_visible(false);
livery_selector.set_visible(false);
scrolly_line_info.set_visible(false);
inp_name.set_visible(false);
cont_times_history.set_visible(false);
cont_haltlist.set_visible(false);
scl.set_selection(-1);
bt_delete_line.disable();
bt_edit_line.disable();
for(int i=0; i<MAX_LINE_COST; i++) {
chart.hide_curve(i);
}
chart.set_visible(true);
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
delete last_schedule;
last_schedule = NULL;
last_vehicle_count = 0;
}
line = new_line;
bt_line_class_manager.set_visible(line.is_bound());
reset_line_name();
}
void schedule_list_gui_t::show_lineinfo(linehandle_t line)
{
update_lineinfo(line);
if( line.is_bound() ) {
// rebuilding line list will also show selection
for( uint8 i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i]==line->get_linetype() ) {
tabs.set_active_tab_index( i );
build_line_list( i );
break;
}
}
}
}
bool schedule_list_gui_t::compare_convois(convoihandle_t const cnv1, convoihandle_t const cnv2)
{
sint32 cmp = 0;
switch (sortby) {
default:
case by_name:
cmp = strcmp(cnv1->get_internal_name(), cnv2->get_internal_name());
break;
case by_schedule:
cmp = cnv1->get_schedule()->get_current_stop() - cnv2->get_schedule()->get_current_stop();
break;
case by_profit:
cmp = sgn(cnv1->get_jahresgewinn() - cnv2->get_jahresgewinn());
break;
case by_loading_lvl:
cmp = cnv1->get_loading_level() - cnv2->get_loading_level();
break;
case by_max_speed:
cmp = cnv1->get_min_top_speed() - cnv2->get_min_top_speed();
break;
case by_power:
cmp = cnv1->get_sum_power() - cnv2->get_sum_power();
break;
case by_age:
cmp = cnv1->get_average_age() - cnv2->get_average_age();
break;
case by_value:
cmp = sgn(cnv1->get_purchase_cost() - cnv2->get_purchase_cost());
break;
}
return sortreverse ? cmp > 0 : cmp < 0;
}
// sort the line convoy list
void schedule_list_gui_t::sort_list()
{
if (!line_convoys.get_count()) {
return;
}
std::sort(line_convoys.begin(), line_convoys.end(), compare_convois);
}
void schedule_list_gui_t::update_data(linehandle_t changed_line)
{
if (changed_line.is_bound()) {
const uint16 i = tabs.get_active_tab_index();
if (tabs_to_lineindex[i] == simline_t::line || tabs_to_lineindex[i] == changed_line->get_linetype()) {
// rebuilds the line list, but does not change selection
build_line_list(i);
}
// change text input of selected line
if (changed_line.get_id() == line.get_id()) {
reset_line_name();
}
}
}
uint32 schedule_list_gui_t::get_rdwr_id()
{
return magic_line_management_t+player->get_player_nr();
}
void schedule_list_gui_t::rdwr( loadsave_t *file )
{
scr_size size;
sint32 cont_xoff, cont_yoff, halt_xoff, halt_yoff;
if( file->is_saving() ) {
size = get_windowsize();
cont_xoff = scrolly_convois.get_scroll_x();
cont_yoff = scrolly_convois.get_scroll_y();
halt_xoff = scrolly_haltestellen.get_scroll_x();
halt_yoff = scrolly_haltestellen.get_scroll_y();
}
size.rdwr( file );
simline_t::rdwr_linehandle_t(file, line);
int chart_records = line_cost_t::MAX_LINE_COST;
if( file->is_version_less(112, 8) ) {
chart_records = 8;
}
else if (file->get_extended_version() < 14 || (file->get_extended_version() == 14 && file->get_extended_revision() < 25)) {
chart_records = 12;
}
for (int i=0; i<chart_records; i++) {
bool b = filterButtons[i].pressed;
file->rdwr_bool( b );
filterButtons[i].pressed = b;
}
file->rdwr_long( cont_xoff );
file->rdwr_long( cont_yoff );
file->rdwr_long( halt_xoff );
file->rdwr_long( halt_yoff );
// open dialogue
if( file->is_loading() ) {
show_lineinfo( line );
set_windowsize( size );
resize( scr_coord(0,0) );
scrolly_convois.set_scroll_position( cont_xoff, cont_yoff );
scrolly_haltestellen.set_scroll_position( halt_xoff, halt_yoff );
}
}
| 35.580404 | 223 | 0.734817 | chris-nada |
51416c8e10df51850d6fb404a2ba6e0e0dff40c8 | 395 | cpp | C++ | engine/generators/settlements/sector/source/SectorFeature.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/generators/settlements/sector/source/SectorFeature.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/generators/settlements/sector/source/SectorFeature.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "SectorFeature.hpp"
#include "CoordUtils.hpp"
using namespace std;
bool SectorFeature::generate(MapPtr map, const Coordinate& start_coord, const Coordinate& end_coord)
{
bool generated = false;
if (map && CoordUtils::is_in_range(map->size(), start_coord, end_coord))
{
generated = generate_feature(map, start_coord, end_coord);
}
return generated;
}
| 21.944444 | 101 | 0.703797 | sidav |
5143ffaee250fada2155680e07a710901a7e2add | 9,281 | cpp | C++ | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | #include "lexer.hpp"
void skip_spaces(std::string const& in, int& pos) {
while(pos < (int)in.size() && in[pos] == ' ') ++pos;
}
void skip_spaces(std::vector<std::string> const& in, int& x) {
while(x < (int)in[0].size()) {
bool all_space = true;
for(int y = 0; y < (int)in.size(); ++y) {
all_space &= in[y][x] == '0';
}
if(!all_space) break;
++x;
}
}
auto trim_input(std::vector<std::string> const& in) {
int x = 0;
std::vector<std::vector<std::string>> res;
while(true) {
skip_spaces(in, x);
if(x == (int)in[0].size()) break;
std::vector<std::string> tmp(in.size());
// scanning
while(x < (int)in[0].size()) {
bool exists_one = false;
for(int y = 0; y < (int)in.size(); ++y) {
exists_one |= in[y][x] == '1';
}
if(!exists_one) break;
for(int y = 0; y < (int)in.size(); ++y) {
tmp[y].push_back(in[y][x]);
}
++x;
}
// trim top/bottom
tmp.erase(std::remove_if(tmp.begin(), tmp.end(),
[] (auto const& s) { return s.find_first_of('1') == std::string::npos; }),
tmp.end());
res.push_back(std::move(tmp));
}
return res;
}
Token dict_operator(const ll id) {
if(id == 0) return app;
if(id == 1) return {TokenType::I, 0};
if(id == 2) return {TokenType::True, 0};
if(id == 5) return comb_b;
if(id == 6) return comb_c;
if(id == 7) return {TokenType::S, 0};
if(id == 8) return {TokenType::False, 0};
if(id == 10) return {TokenType::Negate, 0};
if(id == 12) return {TokenType::Equality, 0};
if(id == 14) return nil;
if(id == 15) return {TokenType::IsNil, 0};
if(id == 40) return {TokenType::Division, 0};
if(id == 146) return {TokenType::Product, 0};
if(id == 170) return {TokenType::Modulate, 0};
if(id == 174) return {TokenType::Send, 0};
if(id == 341) return {TokenType::Demod, 0};
if(id == 365) return sum;
if(id == 401) return {TokenType::Pred, 0};
if(id == 416) return {TokenType::Lt, 0};
if(id == 417) return {TokenType::Succ, 0};
if(id == 448) return {TokenType::Eq, 0};
if(id == 64170) return cons;
if(id == 64171) return {TokenType::Cdr, 0};
if(id == 64174) return {TokenType::Car, 0};
if(id == 17043521) return cons;
throw std::runtime_error("dict_operator: not supported " + std::to_string(id));
}
ll calc_number_part(std::vector<std::string> const& symbol) {
const int n = std::min(symbol.size(), symbol[0].size()) - 1;
ll res = 0;
for(int y = 0; y < n; ++y) {
for(int x = 0; x < n; ++x) {
if(symbol[y + 1][x + 1] == '1') {
res += 1LL << (y * n + x);
}
}
}
return res;
}
ll calc_var_number_part(std::vector<std::string> const& symbol) {
assert(symbol.size() == symbol[0].size());
const int n = symbol.size();
ll res = 0;
for(int y = 0; y < n - 3; ++y) {
for(int x = 0; x < n - 3; ++x) {
if(symbol[y + 2][x + 2] == '0') {
res += 1LL << (y * (n - 3) + x);
}
}
}
return res;
}
bool is_lparen(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 3u) return false;
bool res = true;
for(int x = 0; x < 3; ++x) {
for(int y = 2 - x; y <= 2 + x; ++y) {
res &= symbol[y][x] == '1';
}
}
return res;
}
bool is_rparen(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 3u) return false;
bool res = true;
for(int x = 0; x < 3; ++x) {
for(int y = x; y <= 4 - x; ++y) {
res &= symbol[y][x] == '1';
}
}
return res;
}
bool is_list_sep(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 2u) return false;
bool res = true;
for(auto const& s : symbol) {
for(auto const c : s) {
res &= c == '1';
}
}
return res;
}
bool is_variable(std::vector<std::string> const& symbol) {
if(symbol.size() != symbol[0].size()) return false;
if(symbol.size() < 4u) return false;
if(symbol[1][1] == '0') return false;
const int n = symbol.size();
for(int i = 2; i < n - 1; ++i) {
if(symbol[1][i] == '1' || symbol[i][1] == '1') return false;
}
bool res = true;
for(int i = 0; i < n; ++i) {
res &= symbol[0][i] == '1' && symbol[i][0] == '1' && symbol[n - 1][i] == '1' && symbol[i][n - 1] == '1';
}
return res;
}
Token tokenize_one(std::vector<std::string> const& symbol) {
if(is_lparen(symbol)) {
throw std::runtime_error("tokenize_one: not implemented lparen");
} else if(is_rparen(symbol)) {
throw std::runtime_error("tokenize_one: not implemented rparen");
} else if(is_list_sep(symbol)) {
throw std::runtime_error("tokenize_one: not implemented list_sep");
} else if(is_variable(symbol)) {
const ll id = calc_var_number_part(symbol);
std::cout << ("x" + std::to_string(id)) << std::endl;
//throw std::runtime_error("not supported");
} else if(symbol[0][0] == '0') { // number
const ll num = calc_number_part(symbol);
if(symbol.size() == symbol[0].size()) { // positive
return number(num);
} else {
return number(-num);
}
} else if(symbol[0][0] == '1') { // operator
return dict_operator(calc_number_part(symbol));
}
throw std::runtime_error("tokenize_one: not implmented");
}
std::vector<Token> tokenize(std::vector<std::string> const& input) {
std::vector<Token> res;
for(auto&& v : trim_input(input)) {
res.push_back(tokenize_one(std::move(v)));
}
return res;
}
bool is_number(std::string const& s) {
bool res = true;
for(int i = s[0] == '-'; i < (int)s.size(); ++i) {
res &= (bool)isdigit(s[i]);
}
return res;
}
// require: all tokens are separated by spaces
std::vector<Token> tokenize(std::string const& input) {
std::vector<Token> res;
std::string cur;
int pos = 0;
while(true) {
skip_spaces(input, pos);
if(pos >= (int)input.size()) return res;
while(pos < (int)input.size() && input[pos] != ' ') cur += input[pos++];
if(cur == "ap") res.push_back(app);
else if(cur[0] == ':') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))}); // todo
else if(is_number(cur)) res.push_back(number(std::stoll(cur)));
else if(cur == "inc") res.push_back({TokenType::Succ, 0});
else if(cur == "dec") res.push_back({TokenType::Pred, 0});
else if(cur == "add") res.push_back(sum);
else if(cur == "=") res.push_back({TokenType::Equality, 0});
else if(cur[0] == 'x') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))});
else if(cur == "mul") res.push_back({TokenType::Product, 0});
else if(cur == "div") res.push_back({TokenType::Division, 0});
else if(cur == "eq") res.push_back({TokenType::Eq, 0});
else if(cur == "lt") res.push_back({TokenType::Lt, 0});
else if(cur == "mod") res.push_back({TokenType::Modulate, 0});
else if(cur == "dem") res.push_back({TokenType::Demod, 0});
else if(cur == "send") res.push_back({TokenType::Send, 0});
else if(cur == "neg") res.push_back({TokenType::Negate, 0});
else if(cur == "s") res.push_back({TokenType::S, 0});
else if(cur == "c") res.push_back({TokenType::C, 0});
else if(cur == "b") res.push_back({TokenType::B, 0});
else if(cur == "t") res.push_back({TokenType::True, 0});
else if(cur == "f") res.push_back({TokenType::False, 0});
else if(cur == "i") res.push_back({TokenType::I, 0});
else if(cur == "pwr2") res.push_back({TokenType::Pwr2, 0}); // ???
else if(cur == "cons") res.push_back(cons);
else if(cur == "car") res.push_back({TokenType::Car, 0});
else if(cur == "cdr") res.push_back({TokenType::Cdr, 0});
else if(cur == "nil") res.push_back(nil);
else if(cur == "isnil") res.push_back({TokenType::IsNil, 0});
else if(cur == "(") throw std::runtime_error("not implemented");
else if(cur == ",") throw std::runtime_error("not implemented");
else if(cur == ")") throw std::runtime_error("not implemented");
else if(cur == "vec") res.push_back(cons);
else if(cur == "draw") throw std::runtime_error("not implemented draw");
else if(cur == "interact") throw std::runtime_error("not implemented: interact");
else throw std::runtime_error("error lexing: " + cur);
cur.clear();
}
}
| 38.35124 | 113 | 0.504579 | kmc-jp |
51462164b90de054864b36b9771f835aacfdc382 | 196 | hpp | C++ | src/fwd/sln.hpp | PiotrOstrow/eoserv | 73253dcc711368a94942b0cfab86f3d42b88b999 | [
"Zlib"
] | 21 | 2020-01-22T10:42:26.000Z | 2022-02-15T19:45:43.000Z | src/fwd/sln.hpp | eoserv/mainclone-eoserv | e18e87f169140b6c0da80b9d866f672e8f6dced5 | [
"Zlib"
] | 12 | 2019-12-10T21:47:57.000Z | 2020-11-06T06:01:52.000Z | src/fwd/sln.hpp | eoserv/mainclone-eoserv | e18e87f169140b6c0da80b9d866f672e8f6dced5 | [
"Zlib"
] | 11 | 2020-04-01T21:46:07.000Z | 2022-03-07T10:50:43.000Z |
/* $Id$
* EOSERV is released under the zlib license.
* See LICENSE.txt for more info.
*/
#ifndef FWD_SLN_HPP_INCLUDED
#define FWD_SLN_HPP_INCLUDED
class SLN;
#endif // FWD_SLN_HPP_INCLUDED
| 15.076923 | 45 | 0.744898 | PiotrOstrow |
5146f18a203e00e16d60dc73391b8ce36cadcdd8 | 3,606 | cpp | C++ | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 13 | 2015-01-28T21:05:09.000Z | 2021-11-03T22:21:11.000Z | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | null | null | null | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 4 | 2018-11-16T08:33:33.000Z | 2021-12-11T19:40:46.000Z | // Copyright (c) 2011 Andrew Green. MIT License. http://www.zoolib.org
#include "zoolib/ValPred/Expr_Bool_ValPred.h"
namespace ZooLib {
// =================================================================================================
#pragma mark - Expr_Bool_ValPred
Expr_Bool_ValPred::Expr_Bool_ValPred(const ValPred& iValPred)
: fValPred(iValPred)
{}
Expr_Bool_ValPred::~Expr_Bool_ValPred()
{}
void Expr_Bool_ValPred::Accept(const Visitor& iVisitor)
{
if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor))
this->Accept_Expr_Bool_ValPred(*theVisitor);
else
inherited::Accept(iVisitor);
}
void Expr_Bool_ValPred::Accept_Expr_Op0(Visitor_Expr_Op0_T<Expr_Bool>& iVisitor)
{
if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor))
this->Accept_Expr_Bool_ValPred(*theVisitor);
else
inherited::Accept_Expr_Op0(iVisitor);
}
int Expr_Bool_ValPred::Compare(const ZP<Expr>& iOther)
{
if (ZP<Expr_Bool_ValPred> other = iOther.DynamicCast<Expr_Bool_ValPred>())
return sCompare_T(this->GetValPred(), other->GetValPred());
return Expr::Compare(iOther);
}
ZP<Expr_Bool> Expr_Bool_ValPred::Self()
{ return this; }
ZP<Expr_Bool> Expr_Bool_ValPred::Clone()
{ return this; }
void Expr_Bool_ValPred::Accept_Expr_Bool_ValPred(Visitor_Expr_Bool_ValPred& iVisitor)
{ iVisitor.Visit_Expr_Bool_ValPred(this); }
const ValPred& Expr_Bool_ValPred::GetValPred() const
{ return fValPred; }
// =================================================================================================
#pragma mark - Visitor_Expr_Bool_ValPred
void Visitor_Expr_Bool_ValPred::Visit_Expr_Bool_ValPred(const ZP<Expr_Bool_ValPred >& iExpr)
{ this->Visit_Expr_Op0(iExpr); }
// =================================================================================================
#pragma mark - Operators
ZP<Expr_Bool> sExpr_Bool(const ValPred& iValPred)
{ return new Expr_Bool_ValPred(iValPred); }
ZP<Expr_Bool> operator~(const ValPred& iValPred)
{ return new Expr_Bool_Not(sExpr_Bool(iValPred)); }
ZP<Expr_Bool> operator&(bool iBool, const ValPred& iValPred)
{
if (iBool)
return sExpr_Bool(iValPred);
return sFalse();
}
ZP<Expr_Bool> operator&(const ValPred& iValPred, bool iBool)
{
if (iBool)
return sExpr_Bool(iValPred);
return sFalse();
}
ZP<Expr_Bool> operator|(bool iBool, const ValPred& iValPred)
{
if (iBool)
return sTrue();
return sExpr_Bool(iValPred);
}
ZP<Expr_Bool> operator|(const ValPred& iValPred, bool iBool)
{
if (iBool)
return sTrue();
return sExpr_Bool(iValPred);
}
ZP<Expr_Bool> operator&(const ValPred& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_And(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); }
ZP<Expr_Bool> operator&(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS)
{ return new Expr_Bool_And(sExpr_Bool(iLHS), iRHS); }
ZP<Expr_Bool> operator&(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_And(iLHS, sExpr_Bool(iRHS)); }
ZP<Expr_Bool>& operator&=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS)
{ return ioLHS = ioLHS & iRHS; }
ZP<Expr_Bool> operator|(const ValPred& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_Or(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); }
ZP<Expr_Bool> operator|(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS)
{ return new Expr_Bool_Or(sExpr_Bool(iLHS), iRHS); }
ZP<Expr_Bool> operator|(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_Or(iLHS, sExpr_Bool(iRHS)); }
ZP<Expr_Bool>& operator|=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS)
{ return ioLHS = ioLHS | iRHS; }
} // namespace ZooLib
| 29.801653 | 100 | 0.691625 | ElectricMagic |
514786e45bfa78af864d4f97ff08ceae21f9fbcd | 2,542 | cpp | C++ | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | /* Tariq ahmed khan - Daffodil */
#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0); // I/O optimization
#define pi 2*acos(0.0)
#define scan(x) scanf("%d",&x)
#define sf scanf
#define pf printf
#define pb push_back
#define memoclr(n,x) memset(n,x,sizeof(n) )
#define INF 1 << 30
typedef long long LLI;
typedef unsigned long long LLU;
template<class T> T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);}
template<class T> T lcm(T x, T y){return ((x/gcd(x,y))*y);}
template<class T> T maxt(T x, T y){if (x > y) return x; else return y;}
template<class T> T mint(T x, T y){if (x < y) return x; else return y;}
template<class T> T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;}
template<class T> T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=(a*a)%mod;y>>=1;}return res;}
int dir[8][2]={{-1,0}
,{1,0}
,{0,-1}
,{0,1}
,{-1,-1}
,{-1,1}
,{1,-1}
,{1,1}};
using namespace std;
struct node{
int st,ed,len;
};
node edge[300];
bool comp(const node &a , const node &b){
if(a.len < b.len)
return true;
return false;
}
int up[300],dow[300];
int main() {
#ifdef partho222
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
int test,kase=0;
scan(test);
while(test--)
{
int n,wk,x,y;
scan(n); scan(wk);
pf("Case %d:\n",++kase);
for(int i=0 ; i<wk ; i++)
{
scanf("%d %d %d",&edge[i].st,&edge[i].ed,&edge[i].len);
if(i < n-1)
{
pf("-1\n");
continue;
}
memoclr(up,-1);
memoclr(dow,-1);
sort(edge+0,edge+(i+1),comp);
int res = 0,all=0;
for(int j=0 ; j<= i && all != n-1 ; j++)
{
if( dow[ edge[j].ed ] == -1 || up[ edge[j].st ] == -1 )
{
//cout << edge[j].st << " -> " << edge[j].ed << " = " << edge[j].len << endl;
up[ edge[j].st ] = 0 ; dow[ edge[j].ed ] = 0;
//up[ edge[j].ed ] = 0 ; dow[ edge[j].st ] = 0;
res += edge[j].len;
all++;
}
}
//cout << res << endl;
if( all == n-1)
pf("%d\n",res);
else
pf("-1\n");
}
}
return 0;
}
| 23.537037 | 120 | 0.434304 | partho222 |
5147b6b5966663e3288f8cec47347c937a866519 | 954 | cpp | C++ | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 2 | 2017-06-03T01:07:16.000Z | 2017-07-14T17:49:16.000Z | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 5 | 2017-04-24T20:29:04.000Z | 2017-06-26T17:40:53.000Z | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | null | null | null | /*
* Biquad_Filter.cpp
*
* Created on: 24. 6. 2017
* Author: michp
*/
#include <Biquad_Filter.h>
namespace flyhero {
Biquad_Filter::Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency) {
double K = std::tan(this->PI * cut_frequency / sample_frequency);
double Q = 1.0 / std::sqrt(2); // let Q be 1 / sqrt(2) for Butterworth
double norm;
switch (type) {
case FILTER_LOW_PASS:
norm = 1.0 / (1 + K / Q + K * K);
this->a0 = K * K * norm;
this->a1 = 2 * this->a0;
this->a2 = this->a0;
this->b1 = 2 * (K * K - 1) * norm;
this->b2 = (1 - K / Q + K * K) * norm;
break;
case FILTER_NOTCH:
norm = 1.0 / (1 + K / Q + K * K);
this->a0 = (1 + K * K) * norm;
this->a1 = 2 * (K * K - 1) * norm;
this->a2 = this->a0;
this->b1 = this->a1;
this->b2 = (1 - K / Q + K * K) * norm;
break;
}
this->z1 = 0;
this->z2 = 0;
}
} /* namespace flyhero */
| 20.73913 | 94 | 0.524109 | michprev |
514ca2cb3acec8c2b0b53fb1c22ade80fbb6b6f6 | 17,331 | hpp | C++ | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 71 | 2020-05-28T07:19:39.000Z | 2022-02-14T02:48:01.000Z | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 4 | 2021-02-20T13:49:53.000Z | 2022-03-24T16:39:08.000Z | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 9 | 2017-11-22T01:25:32.000Z | 2021-12-25T11:28:34.000Z | /**
* ============================================================================
* MIT License
*
* Copyright (c) 2016 Eric Phillips
*
* 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.
* ============================================================================
*
*
* This file implements a series of math functions for manipulating a
* 2D vector.
*
* Created by Eric Phillips on October 15, 2016.
*/
#pragma once
#define _USE_MATH_DEFINES
#include <math.h>
struct Vector2
{
union
{
struct
{
double X;
double Y;
};
double data[2];
};
/**
* Constructors.
*/
inline Vector2();
inline Vector2(double data[]);
inline Vector2(double value);
inline Vector2(double x, double y);
/**
* Constants for common vectors.
*/
static inline Vector2 Zero();
static inline Vector2 One();
static inline Vector2 Right();
static inline Vector2 Left();
static inline Vector2 Up();
static inline Vector2 Down();
/**
* Returns the angle between two vectors in radians.
* @param a: The first vector.
* @param b: The second vector.
* @return: A scalar value.
*/
static inline double Angle(Vector2 a, Vector2 b);
/**
* Returns a vector with its magnitude clamped to maxLength.
* @param vector: The target vector.
* @param maxLength: The maximum length of the return vector.
* @return: A new vector.
*/
static inline Vector2 ClampMagnitude(Vector2 vector, double maxLength);
/**
* Returns the component of a in the direction of b (scalar projection).
* @param a: The target vector.
* @param b: The vector being compared against.
* @return: A scalar value.
*/
static inline double Component(Vector2 a, Vector2 b);
/**
* Returns the distance between a and b.
* @param a: The first point.
* @param b: The second point.
* @return: A scalar value.
*/
static inline double Distance(Vector2 a, Vector2 b);
/**
* Returns the dot product of two vectors.
* @param lhs: The left side of the multiplication.
* @param rhs: The right side of the multiplication.
* @return: A scalar value.
*/
static inline double Dot(Vector2 lhs, Vector2 rhs);
/**
* Converts a polar representation of a vector into cartesian
* coordinates.
* @param rad: The magnitude of the vector.
* @param theta: The angle from the X axis.
* @return: A new vector.
*/
static inline Vector2 FromPolar(double rad, double theta);
/**
* Returns a vector linearly interpolated between a and b, moving along
* a straight line. The vector is clamped to never go beyond the end points.
* @param a: The starting point.
* @param b: The ending point.
* @param t: The interpolation value [0-1].
* @return: A new vector.
*/
static inline Vector2 Lerp(Vector2 a, Vector2 b, double t);
/**
* Returns a vector linearly interpolated between a and b, moving along
* a straight line.
* @param a: The starting point.
* @param b: The ending point.
* @param t: The interpolation value [0-1] (no actual bounds).
* @return: A new vector.
*/
static inline Vector2 LerpUnclamped(Vector2 a, Vector2 b, double t);
/**
* Returns the magnitude of a vector.
* @param v: The vector in question.
* @return: A scalar value.
*/
static inline double Magnitude(Vector2 v);
/**
* Returns a vector made from the largest components of two other vectors.
* @param a: The first vector.
* @param b: The second vector.
* @return: A new vector.
*/
static inline Vector2 Max(Vector2 a, Vector2 b);
/**
* Returns a vector made from the smallest components of two other vectors.
* @param a: The first vector.
* @param b: The second vector.
* @return: A new vector.
*/
static inline Vector2 Min(Vector2 a, Vector2 b);
/**
* Returns a vector "maxDistanceDelta" units closer to the target. This
* interpolation is in a straight line, and will not overshoot.
* @param current: The current position.
* @param target: The destination position.
* @param maxDistanceDelta: The maximum distance to move.
* @return: A new vector.
*/
static inline Vector2 MoveTowards(Vector2 current, Vector2 target,
double maxDistanceDelta);
/**
* Returns a new vector with magnitude of one.
* @param v: The vector in question.
* @return: A new vector.
*/
static inline Vector2 Normalized(Vector2 v);
/**
* Creates a new coordinate system out of the two vectors.
* Normalizes "normal" and normalizes "tangent" and makes it orthogonal to
* "normal"..
* @param normal: A reference to the first axis vector.
* @param tangent: A reference to the second axis vector.
*/
static inline void OrthoNormalize(Vector2 &normal, Vector2 &tangent);
/**
* Returns the vector projection of a onto b.
* @param a: The target vector.
* @param b: The vector being projected onto.
* @return: A new vector.
*/
static inline Vector2 Project(Vector2 a, Vector2 b);
/**
* Returns a vector reflected about the provided line.
* This behaves as if there is a plane with the line as its normal, and the
* vector comes in and bounces off this plane.
* @param vector: The vector traveling inward at the imaginary plane.
* @param line: The line about which to reflect.
* @return: A new vector pointing outward from the imaginary plane.
*/
static inline Vector2 Reflect(Vector2 vector, Vector2 line);
/**
* Returns the vector rejection of a on b.
* @param a: The target vector.
* @param b: The vector being projected onto.
* @return: A new vector.
*/
static inline Vector2 Reject(Vector2 a, Vector2 b);
/**
* Rotates vector "current" towards vector "target" by "maxRadiansDelta".
* This treats the vectors as directions and will linearly interpolate
* between their magnitudes by "maxMagnitudeDelta". This function does not
* overshoot. If a negative delta is supplied, it will rotate away from
* "target" until it is pointing the opposite direction, but will not
* overshoot that either.
* @param current: The starting direction.
* @param target: The destination direction.
* @param maxRadiansDelta: The maximum number of radians to rotate.
* @param maxMagnitudeDelta: The maximum delta for magnitude interpolation.
* @return: A new vector.
*/
static inline Vector2 RotateTowards(Vector2 current, Vector2 target,
double maxRadiansDelta,
double maxMagnitudeDelta);
/**
* Multiplies two vectors component-wise.
* @param a: The lhs of the multiplication.
* @param b: The rhs of the multiplication.
* @return: A new vector.
*/
static inline Vector2 Scale(Vector2 a, Vector2 b);
/**
* Returns a vector rotated towards b from a by the percent t.
* Since interpolation is done spherically, the vector moves at a constant
* angular velocity. This rotation is clamped to 0 <= t <= 1.
* @param a: The starting direction.
* @param b: The ending direction.
* @param t: The interpolation value [0-1].
*/
static inline Vector2 Slerp(Vector2 a, Vector2 b, double t);
/**
* Returns a vector rotated towards b from a by the percent t.
* Since interpolation is done spherically, the vector moves at a constant
* angular velocity. This rotation is unclamped.
* @param a: The starting direction.
* @param b: The ending direction.
* @param t: The interpolation value [0-1].
*/
static inline Vector2 SlerpUnclamped(Vector2 a, Vector2 b, double t);
/**
* Returns the squared magnitude of a vector.
* This is useful when comparing relative lengths, where the exact length
* is not important, and much time can be saved by not calculating the
* square root.
* @param v: The vector in question.
* @return: A scalar value.
*/
static inline double SqrMagnitude(Vector2 v);
/**
* Calculates the polar coordinate space representation of a vector.
* @param vector: The vector to convert.
* @param rad: The magnitude of the vector.
* @param theta: The angle from the X axis.
*/
static inline void ToPolar(Vector2 vector, double &rad, double &theta);
/**
* Operator overloading.
*/
inline struct Vector2& operator+=(const double rhs);
inline struct Vector2& operator-=(const double rhs);
inline struct Vector2& operator*=(const double rhs);
inline struct Vector2& operator/=(const double rhs);
inline struct Vector2& operator+=(const Vector2 rhs);
inline struct Vector2& operator-=(const Vector2 rhs);
};
inline Vector2 operator-(Vector2 rhs);
inline Vector2 operator+(Vector2 lhs, const double rhs);
inline Vector2 operator-(Vector2 lhs, const double rhs);
inline Vector2 operator*(Vector2 lhs, const double rhs);
inline Vector2 operator/(Vector2 lhs, const double rhs);
inline Vector2 operator+(const double lhs, Vector2 rhs);
inline Vector2 operator-(const double lhs, Vector2 rhs);
inline Vector2 operator*(const double lhs, Vector2 rhs);
inline Vector2 operator/(const double lhs, Vector2 rhs);
inline Vector2 operator+(Vector2 lhs, const Vector2 rhs);
inline Vector2 operator-(Vector2 lhs, const Vector2 rhs);
inline bool operator==(const Vector2 lhs, const Vector2 rhs);
inline bool operator!=(const Vector2 lhs, const Vector2 rhs);
/*******************************************************************************
* Implementation
*/
Vector2::Vector2() : X(0), Y(0) {}
Vector2::Vector2(double data[]) : X(data[0]), Y(data[1]) {}
Vector2::Vector2(double value) : X(value), Y(value) {}
Vector2::Vector2(double x, double y) : X(x), Y(y) {}
Vector2 Vector2::Zero() { return Vector2(0, 0); }
Vector2 Vector2::One() { return Vector2(1, 1); }
Vector2 Vector2::Right() { return Vector2(1, 0); }
Vector2 Vector2::Left() { return Vector2(-1, 0); }
Vector2 Vector2::Up() { return Vector2(0, 1); }
Vector2 Vector2::Down() { return Vector2(0, -1); }
double Vector2::Angle(Vector2 a, Vector2 b)
{
double v = Dot(a, b) / (Magnitude(a) * Magnitude(b));
v = fmax(v, -1.0);
v = fmin(v, 1.0);
return acos(v);
}
Vector2 Vector2::ClampMagnitude(Vector2 vector, double maxLength)
{
double length = Magnitude(vector);
if (length > maxLength)
vector *= maxLength / length;
return vector;
}
double Vector2::Component(Vector2 a, Vector2 b)
{
return Dot(a, b) / Magnitude(b);
}
double Vector2::Distance(Vector2 a, Vector2 b)
{
return Vector2::Magnitude(a - b);
}
double Vector2::Dot(Vector2 lhs, Vector2 rhs)
{
return lhs.X * rhs.X + lhs.Y * rhs.Y;
}
Vector2 Vector2::FromPolar(double rad, double theta)
{
Vector2 v;
v.X = rad * cos(theta);
v.Y = rad * sin(theta);
return v;
}
Vector2 Vector2::Lerp(Vector2 a, Vector2 b, double t)
{
if (t < 0) return a;
else if (t > 1) return b;
return LerpUnclamped(a, b, t);
}
Vector2 Vector2::LerpUnclamped(Vector2 a, Vector2 b, double t)
{
return (b - a) * t + a;
}
double Vector2::Magnitude(Vector2 v)
{
return sqrt(SqrMagnitude(v));
}
Vector2 Vector2::Max(Vector2 a, Vector2 b)
{
double x = a.X > b.X ? a.X : b.X;
double y = a.Y > b.Y ? a.Y : b.Y;
return Vector2(x, y);
}
Vector2 Vector2::Min(Vector2 a, Vector2 b)
{
double x = a.X > b.X ? b.X : a.X;
double y = a.Y > b.Y ? b.Y : a.Y;
return Vector2(x, y);
}
Vector2 Vector2::MoveTowards(Vector2 current, Vector2 target,
double maxDistanceDelta)
{
Vector2 d = target - current;
double m = Magnitude(d);
if (m < maxDistanceDelta || m == 0)
return target;
return current + (d * maxDistanceDelta / m);
}
Vector2 Vector2::Normalized(Vector2 v)
{
double mag = Magnitude(v);
if (mag == 0)
return Vector2::Zero();
return v / mag;
}
void Vector2::OrthoNormalize(Vector2 &normal, Vector2 &tangent)
{
normal = Normalized(normal);
tangent = Reject(tangent, normal);
tangent = Normalized(tangent);
}
Vector2 Vector2::Project(Vector2 a, Vector2 b)
{
double m = Magnitude(b);
return Dot(a, b) / (m * m) * b;
}
Vector2 Vector2::Reflect(Vector2 vector, Vector2 planeNormal)
{
return vector - 2 * Project(vector, planeNormal);
}
Vector2 Vector2::Reject(Vector2 a, Vector2 b)
{
return a - Project(a, b);
}
Vector2 Vector2::RotateTowards(Vector2 current, Vector2 target,
double maxRadiansDelta,
double maxMagnitudeDelta)
{
double magCur = Magnitude(current);
double magTar = Magnitude(target);
double newMag = magCur + maxMagnitudeDelta *
((magTar > magCur) - (magCur > magTar));
newMag = fmin(newMag, fmax(magCur, magTar));
newMag = fmax(newMag, fmin(magCur, magTar));
double totalAngle = Angle(current, target) - maxRadiansDelta;
if (totalAngle <= 0)
return Normalized(target) * newMag;
else if (totalAngle >= M_PI)
return Normalized(-target) * newMag;
double axis = current.X * target.Y - current.Y * target.X;
axis = axis / fabs(axis);
if (!(1 - fabs(axis) < 0.00001))
axis = 1;
current = Normalized(current);
Vector2 newVector = current * cos(maxRadiansDelta) +
Vector2(-current.Y, current.X) * sin(maxRadiansDelta) * axis;
return newVector * newMag;
}
Vector2 Vector2::Scale(Vector2 a, Vector2 b)
{
return Vector2(a.X * b.X, a.Y * b.Y);
}
Vector2 Vector2::Slerp(Vector2 a, Vector2 b, double t)
{
if (t < 0) return a;
else if (t > 1) return b;
return SlerpUnclamped(a, b, t);
}
Vector2 Vector2::SlerpUnclamped(Vector2 a, Vector2 b, double t)
{
double magA = Magnitude(a);
double magB = Magnitude(b);
a /= magA;
b /= magB;
double dot = Dot(a, b);
dot = fmax(dot, -1.0);
dot = fmin(dot, 1.0);
double theta = acos(dot) * t;
Vector2 relativeVec = Normalized(b - a * dot);
Vector2 newVec = a * cos(theta) + relativeVec * sin(theta);
return newVec * (magA + (magB - magA) * t);
}
double Vector2::SqrMagnitude(Vector2 v)
{
return v.X * v.X + v.Y * v.Y;
}
void Vector2::ToPolar(Vector2 vector, double &rad, double &theta)
{
rad = Magnitude(vector);
theta = atan2(vector.Y, vector.X);
}
struct Vector2& Vector2::operator+=(const double rhs)
{
X += rhs;
Y += rhs;
return *this;
}
struct Vector2& Vector2::operator-=(const double rhs)
{
X -= rhs;
Y -= rhs;
return *this;
}
struct Vector2& Vector2::operator*=(const double rhs)
{
X *= rhs;
Y *= rhs;
return *this;
}
struct Vector2& Vector2::operator/=(const double rhs)
{
X /= rhs;
Y /= rhs;
return *this;
}
struct Vector2& Vector2::operator+=(const Vector2 rhs)
{
X += rhs.X;
Y += rhs.Y;
return *this;
}
struct Vector2& Vector2::operator-=(const Vector2 rhs)
{
X -= rhs.X;
Y -= rhs.Y;
return *this;
}
Vector2 operator-(Vector2 rhs) { return rhs * -1; }
Vector2 operator+(Vector2 lhs, const double rhs) { return lhs += rhs; }
Vector2 operator-(Vector2 lhs, const double rhs) { return lhs -= rhs; }
Vector2 operator*(Vector2 lhs, const double rhs) { return lhs *= rhs; }
Vector2 operator/(Vector2 lhs, const double rhs) { return lhs /= rhs; }
Vector2 operator+(const double lhs, Vector2 rhs) { return rhs += lhs; }
Vector2 operator-(const double lhs, Vector2 rhs) { return rhs -= lhs; }
Vector2 operator*(const double lhs, Vector2 rhs) { return rhs *= lhs; }
Vector2 operator/(const double lhs, Vector2 rhs) { return rhs /= lhs; }
Vector2 operator+(Vector2 lhs, const Vector2 rhs) { return lhs += rhs; }
Vector2 operator-(Vector2 lhs, const Vector2 rhs) { return lhs -= rhs; }
bool operator==(const Vector2 lhs, const Vector2 rhs)
{
return lhs.X == rhs.X && lhs.Y == rhs.Y;
}
bool operator!=(const Vector2 lhs, const Vector2 rhs)
{
return !(lhs == rhs);
}
| 30.620141 | 80 | 0.63724 | LiangJy123 |
515437bc433e9c841957d5e61e63a18afde2dd41 | 2,903 | cc | C++ | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | 1 | 2020-12-30T23:50:01.000Z | 2020-12-30T23:50:01.000Z | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | // *************************************************************
// File: memory_manager.cc
// Author: Novoselov Anton @ 2018
// URL: https://github.com/ans-hub/gdm_framework
// *************************************************************
#include "memory_manager.h"
#include <memory/memory_tracker.h>
#include <memory/defines.h>
#include <math/general.h>
#include <system/assert_utils.h>
#if defined (_WIN32)
#include <malloc.h>
#else
#include <cstdlib>
#endif
// --public
void* gdm::MemoryManager::Allocate(size_t bytes, MemoryTagValue tag)
{
return AllocateAligned(bytes, GetDefaultAlignment(), tag);
}
void* gdm::MemoryManager::AllocateAligned(size_t bytes, size_t align, MemoryTagValue tag)
{
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined (_WIN32)
void* ptr = _aligned_malloc(bytes, align);
#else
void* ptr = std::aligned_alloc(size, align);
#endif
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(ptr, align));
return ptr;
}
void* gdm::MemoryManager::Reallocate(void* ptr, size_t new_bytes, MemoryTagValue tag)
{
return ReallocateAligned(ptr, new_bytes, GetDefaultAlignment(), tag);
}
void* gdm::MemoryManager::ReallocateAligned(void* ptr, size_t new_bytes, size_t align, MemoryTagValue tag)
{
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined (_WIN32)
MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align));
void* new_ptr = _aligned_realloc(ptr, new_bytes, align);
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align));
#else
void* new_ptr = Allocate(new_bytes, align);
memcpy(new_mem, ptr, GetPointerSize(ptr, align));
Deallocate(ptr, align);
#endif
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align));
return new_ptr;
}
void gdm::MemoryManager::Deallocate(void* ptr, MemoryTagValue tag)
{
DeallocateAligned(ptr, GetDefaultAlignment(), tag);
}
void gdm::MemoryManager::DeallocateAligned(void* ptr, size_t align, MemoryTagValue tag)
{
MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align));
#if defined (_WIN32)
_aligned_free(ptr);
#else
std::free(mem);
#endif
}
size_t gdm::MemoryManager::GetPointerSize(void* ptr, size_t align)
{
if (!ptr)
return 0;
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined(_WIN32)
return _aligned_msize(ptr, align, 0);
#else
return malloc_usabe_size(ptr);
#endif
}
auto gdm::MemoryManager::GetTagUsage(MemoryTagValue tag) -> size_t
{
return MemoryTracker::GetInstance().GetTagUsage(tag);
}
auto gdm::MemoryManager::GetTagName(MemoryTagValue tag) -> const char*
{
return MemoryTracker::GetInstance().GetTagName(tag);
}
| 27.647619 | 106 | 0.704099 | ans-hub |
51557d33621fe7cfed967ce3a7394e8251002639 | 3,118 | hpp | C++ | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __KF_DEPLOY_SERVER_MODULE_H__
#define __KF_DEPLOY_SERVER_MODULE_H__
/************************************************************************
// @Module : 部署Server
// @Author : __凌_痕__
// @QQ : 7969936
// @Mail : [email protected]
// @Date : 2018-7-2
************************************************************************/
#include "KFProtocol/KFProtocol.h"
#include "KFDeployServerInterface.h"
#include "KFMySQL/KFMySQLInterface.h"
#include "KFMessage/KFMessageInterface.h"
#include "KFDelayed/KFDelayedInterface.h"
#include "KFTcpServer/KFTcpServerInterface.h"
#include "KFHttpServer/KFHttpServerInterface.h"
#include "KFHttpClient/KFHttpClientInterface.h"
namespace KFrame
{
class KFAgentData
{
public:
KFAgentData()
{
_port = 0;
status = 0;
}
public:
// 服务器id
std::string _agent_id;
// 局域网地址
std::string _local_ip;
// 名字
std::string _name;
// 类型
std::string _type;
// 服务
std::string _service;
// 端口
uint32 _port;
// 状态
uint32 status;
};
class KFDeployServerModule : public KFDeployServerInterface
{
public:
KFDeployServerModule() = default;
~KFDeployServerModule() = default;
// 逻辑
virtual void BeforeRun();
virtual void PrepareRun();
// 关闭
virtual void ShutDown();
protected:
// 连接丢失
__KF_NET_EVENT_FUNCTION__( OnServerLostClient );
// 启动服务器
__KF_HTTP_FUNCTION__( HandleDeployCommand );
// 部署命令
__KF_DELAYED_FUNCTION__( OnHttpDeployCommandToAgent );
__KF_DELAYED_FUNCTION__( OnTcpDeployCommandToAgent );
protected:
// 注册Agent
__KF_MESSAGE_FUNCTION__( HandleRegisterAgentToServerReq );
// 执行sql语句
__KF_MESSAGE_FUNCTION__( HandleExecuteMySQLReq );
// 查询sql语句
__KF_MESSAGE_FUNCTION__( HandleQueryMySQLReq );
// 查询sql语句
__KF_MESSAGE_FUNCTION__( HandleDeleteMySQLReq );
// 部署命令
__KF_MESSAGE_FUNCTION__( HandleDeployToolCommandReq );
// 日志
__KF_MESSAGE_FUNCTION__( HandleDeployLogToServerReq );
// 查询toolid
__KF_MESSAGE_FUNCTION__( HandleDeployQueryToolIdReq );
protected:
// 更新Agnet状态
void UpdateAgentToDatabase( KFAgentData* kfagent, uint32 status );
// 回发日志消息
template<typename... P>
void LogDeploy( uint64 agentid, const char* myfmt, P&& ... args )
{
auto msg = __FORMAT__( myfmt, std::forward<P>( args )... );
return SendLogMessage( agentid, msg );
}
void SendLogMessage( uint64 agentid, const std::string& msg );
private:
KFMySQLDriver* _mysql_driver{ nullptr };
// Agent列表
KFHashMap< std::string, const std::string&, KFAgentData > _agent_list;
// 定时任务id
uint64 _delayed_id = 0u;
// web列表
std::string _web_deploy_url;
};
}
#endif | 23.801527 | 78 | 0.570558 | 282951387 |
515bdedef961afeb3573601aa52e151ec83104d1 | 706 | cpp | C++ | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
// GCStallError.cpp
//
/////////////////////////////////////////////////////
#include "GCStallError.h"
BOOL GCStallError::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_ID), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCStallError::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_ID), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCStallError::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCStallErrorHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 16.045455 | 62 | 0.610482 | viticm |
515c0f991d826f7014190d628854a375aba1a70d | 1,624 | cpp | C++ | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | //
// ae_pasteboard_types.cpp
//
#include "ae_pasteboard_types.h"
#include <audio_editor_core/ae_pasteboard_constants.h>
#include <audio_editor_core/ae_pasteboard_utils.h>
using namespace yas;
using namespace yas::ae;
using namespace yas::ae::pasteboard_constants;
std::string pasting_file_module::data() const {
std::map<std::string, std::string> map{{file_module_key::kind, file_module_kind::value},
{file_module_key::file_frame, std::to_string(this->file_frame)},
{file_module_key::length, std::to_string(this->length)}};
return pasteboard_utils::to_data_string(map);
}
std::optional<pasting_file_module> pasting_file_module::make_value(std::string const &data) {
auto const map = pasteboard_utils::to_data_map(data);
if (map.contains(file_module_key::kind) && map.at(file_module_key::kind) == file_module_kind::value &&
map.contains(file_module_key::file_frame) && map.contains(file_module_key::length)) {
auto const file_frame_string = map.at(file_module_key::file_frame);
auto const length_string = map.at(file_module_key::length);
return pasting_file_module{.file_frame = std::stoll(file_frame_string), .length = std::stoul(length_string)};
}
return std::nullopt;
}
std::string yas::to_string(ae::pasting_file_module const &module) {
return "{" + std::to_string(module.file_frame) + "," + std::to_string(module.length) + "}";
}
std::ostream &operator<<(std::ostream &os, yas::ae::pasting_file_module const &value) {
os << to_string(value);
return os;
}
| 38.666667 | 117 | 0.692118 | objective-audio |
515fdcb124524d54694735ebf2de3286716ca302 | 920 | cpp | C++ | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "StateRoot_EnemyE4.h"
#include "StateMng_EnemyE4.h"
UStateRoot_EnemyE4::UStateRoot_EnemyE4()
{
}
UStateRoot_EnemyE4::~UStateRoot_EnemyE4()
{
}
void UStateRoot_EnemyE4::Init(class UStateMng_GC* pMng)
{
Super::Init(pMng);
m_pStateMng_Override = Cast<UStateMng_EnemyE4>(pMng);
if (m_pStateMng_Override == nullptr)
{
ULOG(TEXT("m_pStateMng_Override is nullptr"));
}
}
void UStateRoot_EnemyE4::Enter()
{
Super::Enter();
}
void UStateRoot_EnemyE4::Exit()
{
Super::Exit();
}
void UStateRoot_EnemyE4::Update(float fDeltaTime)
{
Super::Update(fDeltaTime);
}
void UStateRoot_EnemyE4::StateMessage(FString sMessage)
{
Super::StateMessage(sMessage);
}
AEnemyE4* UStateRoot_EnemyE4::GetRootChar()
{
if (m_pStateMng_Override == nullptr)
{
return nullptr;
}
return m_pStateMng_Override->GetRootCharacter_Override();
}
| 16.727273 | 78 | 0.755435 | Bornsoul |
51637f2c62188dae57e1f0a21870117260bcf1c9 | 813 | hpp | C++ | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #pragma once
#ifndef _WORLDLOADER_WORLDDATATAGS_HPP_
#define _WORLDLOADER_WORLDDATATAGS_HPP_
/*
Define the tags which make up the entities in an xml world file.
*/
#define WORLD_TAG "World"
#define ASSETS_TAG "Assets"
#define ENTITIES_TAG "Entities"
#define ENTITY_TAG "Entity"
#define NAME_TAG "Name"
#define COMPONENTS_TAG "Components"
#define NODES_TAG "Nodes"
/*
<!-- An example of the structure of an xml world file -->
<World>
<Entity>
<Name>
"The entity's name"
<Name/>
<Components>
<!--
A list of
components
stored in
the entity.
-->
<Components/>
<Nodes>
<!--
A list of
nodes stored
in the entity.
-->
<Nodes/>
<Entity/>
<!--
More entities
....
-->
<World/>
*/
#endif | 15.339623 | 66 | 0.597786 | jordanlittlefair |
5164f4efc116badb10d2b6ddc9de96185a4dd22c | 966 | cpp | C++ | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
/*
Laboratory 5 Ex 6
Write a program to generate two-dimentional array with random numbers and find maximum element in the whole array.
Print array and maximum element.
*/
int main() {
srand (time(NULL));
int array1[3][3];
int row = 3, column = 3;
// Generating Random two-dimensional array
for (int i = 0; i < column; i++)
{
for(int j = 0; j < row; j++)
{
array1[i][j] = rand() % 10;
}
}
//Printing Array
for (int i = 0; i < column; i++)
{
for(int j = 0; j < row; j++)
{
cout << array1[i][j] << " ";
}
cout << "\n";
}
//Finding maximum element in the Array
int maxElement;
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
if (array1[i][j] > maxElement)
{
maxElement = array1[i][j];
}
}
}
cout << "Maximum element is "<< maxElement << endl;
return 0;
}
| 19.714286 | 116 | 0.546584 | nuriyevanar0 |
5165566847d1911f4bc07185ae61e0d32f02d691 | 5,813 | cc | C++ | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 35 | 2016-05-20T03:59:10.000Z | 2022-02-21T09:59:14.000Z | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 7 | 2020-11-22T04:53:24.000Z | 2021-04-18T02:14:09.000Z | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 4 | 2017-02-15T04:26:37.000Z | 2020-11-21T02:29:23.000Z | // Copyright (c) 2018, the Newspeak project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h" // NOLINT
#if defined(OS_ANDROID) || defined(OS_LINUX)
#include "vm/message_loop.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include "vm/lockers.h"
#include "vm/os.h"
namespace psoup {
static bool SetBlockingHelper(intptr_t fd, bool blocking) {
intptr_t status;
status = fcntl(fd, F_GETFL);
if (status < 0) {
perror("fcntl(F_GETFL) failed");
return false;
}
status = blocking ? (status & ~O_NONBLOCK) : (status | O_NONBLOCK);
if (fcntl(fd, F_SETFL, status) < 0) {
perror("fcntl(F_SETFL, O_NONBLOCK) failed");
return false;
}
return true;
}
EPollMessageLoop::EPollMessageLoop(Isolate* isolate)
: MessageLoop(isolate),
mutex_(),
head_(NULL),
tail_(NULL),
wakeup_(0) {
int result = pipe(interrupt_fds_);
if (result != 0) {
FATAL("Failed to create pipe");
}
if (!SetBlockingHelper(interrupt_fds_[0], false)) {
FATAL("Failed to set pipe fd non-blocking\n");
}
timer_fd_ = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
if (timer_fd_ == -1) {
FATAL("Failed to creater timer_fd");
}
epoll_fd_ = epoll_create(64);
if (epoll_fd_ == -1) {
FATAL("Failed to create epoll");
}
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = interrupt_fds_[0];
int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupt_fds_[0], &event);
if (status == -1) {
FATAL("Failed to add pipe to epoll");
}
event.events = EPOLLIN;
event.data.fd = timer_fd_;
status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &event);
if (status == -1) {
FATAL("Failed to add timer_fd to epoll");
}
}
EPollMessageLoop::~EPollMessageLoop() {
close(epoll_fd_);
close(timer_fd_);
close(interrupt_fds_[0]);
close(interrupt_fds_[1]);
}
intptr_t EPollMessageLoop::AwaitSignal(intptr_t fd, intptr_t signals) {
struct epoll_event event;
event.events = EPOLLRDHUP | EPOLLET;
if (signals & (1 << kReadEvent)) {
event.events |= EPOLLIN;
}
if (signals & (1 << kWriteEvent)) {
event.events |= EPOLLOUT;
}
event.data.fd = fd;
int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
if (status == -1) {
FATAL("Failed to add to epoll");
}
return fd;
}
void EPollMessageLoop::CancelSignalWait(intptr_t wait_id) {
UNIMPLEMENTED();
}
void EPollMessageLoop::MessageEpilogue(int64_t new_wakeup) {
wakeup_ = new_wakeup;
struct itimerspec it;
memset(&it, 0, sizeof(it));
if (new_wakeup != 0) {
it.it_value.tv_sec = new_wakeup / kNanosecondsPerSecond;
it.it_value.tv_nsec = new_wakeup % kNanosecondsPerSecond;
}
timerfd_settime(timer_fd_, TFD_TIMER_ABSTIME, &it, NULL);
if ((open_ports_ == 0) && (wakeup_ == 0)) {
Exit(0);
}
}
void EPollMessageLoop::Exit(intptr_t exit_code) {
exit_code_ = exit_code;
isolate_ = NULL;
}
void EPollMessageLoop::PostMessage(IsolateMessage* message) {
MutexLocker locker(&mutex_);
if (head_ == NULL) {
head_ = tail_ = message;
Notify();
} else {
tail_->next_ = message;
tail_ = message;
}
}
void EPollMessageLoop::Notify() {
uword message = 0;
ssize_t written = write(interrupt_fds_[1], &message, sizeof(message));
if (written != sizeof(message)) {
FATAL("Failed to atomically write notify message");
}
}
IsolateMessage* EPollMessageLoop::TakeMessages() {
MutexLocker locker(&mutex_);
IsolateMessage* message = head_;
head_ = tail_ = NULL;
return message;
}
intptr_t EPollMessageLoop::Run() {
while (isolate_ != NULL) {
static const intptr_t kMaxEvents = 16;
struct epoll_event events[kMaxEvents];
int result = epoll_wait(epoll_fd_, events, kMaxEvents, -1);
if (result <= 0) {
if ((errno != EWOULDBLOCK) && (errno != EINTR)) {
FATAL("epoll_wait failed");
}
} else {
for (int i = 0; i < result; i++) {
if (events[i].data.fd == interrupt_fds_[0]) {
// Interrupt fd.
uword message = 0;
ssize_t red = read(interrupt_fds_[0], &message, sizeof(message));
if (red != sizeof(message)) {
FATAL("Failed to atomically write notify message");
}
} else if (events[i].data.fd == timer_fd_) {
int64_t value;
ssize_t ignore = read(timer_fd_, &value, sizeof(value));
(void)ignore;
DispatchWakeup();
} else {
intptr_t fd = events[i].data.fd;
intptr_t pending = 0;
if (events[i].events & EPOLLERR) {
pending |= 1 << kErrorEvent;
}
if (events[i].events & EPOLLIN) {
pending |= 1 << kReadEvent;
}
if (events[i].events & EPOLLOUT) {
pending |= 1 << kWriteEvent;
}
if (events[i].events & EPOLLHUP) {
pending |= 1 << kCloseEvent;
}
if (events[i].events & EPOLLRDHUP) {
pending |= 1 << kCloseEvent;
}
DispatchSignal(fd, 0, pending, 0);
}
}
}
IsolateMessage* message = TakeMessages();
while (message != NULL) {
IsolateMessage* next = message->next_;
DispatchMessage(message);
message = next;
}
}
if (open_ports_ > 0) {
PortMap::CloseAllPorts(this);
}
while (head_ != NULL) {
IsolateMessage* message = head_;
head_ = message->next_;
delete message;
}
return exit_code_;
}
void EPollMessageLoop::Interrupt() {
Exit(SIGINT);
Notify();
}
} // namespace psoup
#endif // defined(OS_ANDROID) || defined(OS_LINUX)
| 25.384279 | 80 | 0.62429 | Outcue |
5169c78622a0ad2debdf3bee0f2f1700c8106601 | 1,232 | cpp | C++ | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | #include "Frame.h"
#include "mbed.h"
Frame::Frame(char * data)
{
this->data = data;
memset(id, 0x00, 32);
}
Frame::~Frame(void)
{
}
void Frame::decode(void)
{
len = data[2];
idd = data[3];
tmp = (data[4] << 8) + data[5];;
pwm = data[6];
tun = data[7];
for(int i = 8; i < (strlen(data) - 3); i++) {
id[i-8] = data[i];
}
crc = data[strlen(data)-4];
}
void Frame::checkCRC(void)
{
}
void Frame::calculateCRC(void)
{
}
void Frame::generate(char * data)
{
memset(data, 0x00, 256);
data[0] = FRAME_SOF_1;
data[1] = FRAME_SOF_2;
data[2] = len;
data[3] = idd;
data[4] = 1;
data[5] = 203;
// data[4] = tmp >> 8;
// data[5] = tmp & 0xFF;
data[6] = pwm;
data[7] = tun;
// for(int i = 0; i < (strlen(id)); i++) {
// data[7 + i] = id[i];
// }
data[8] = 108;
data[9] = crc;
data[10] = FRAME_EOF_1;
data[11] = FRAME_EOF_2;
// data[6 + strlen(id) + 1] = 109;
// data[6 + strlen(id) + 2] = crc;
// data[6 + strlen(id) + 3] = FRAME_EOF_1;
// data[6 + strlen(id) + 4] = FRAME_EOF_2;
for(int i = 0; i < (strlen(data)); i++) {
printf("Data[%i]: %i\n\r", i, data[i]);
}
}
| 16.648649 | 49 | 0.474026 | MichelDequick |
5174d524b9373318061ff23bb5bc8dc555f6ea5e | 217 | cpp | C++ | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // && operator: if the left operand is flase, there is no need to compute the right operand
// || operator: if the left operand is true, there is no need to compute the right operand
// == operator: there is no order
| 54.25 | 91 | 0.723502 | zero4drift |
5176f73ee52bf7a3246e4672abf3bd45bbd3d757 | 1,560 | cpp | C++ | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | 1 | 2020-03-31T05:53:38.000Z | 2020-03-31T05:53:38.000Z | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep1(i, n) for (int i = 1; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1001001001;
const int mod = 1000000007;
struct mint {
ll x;
mint(ll x=0):x((x%mod+mod)%mod){}
mint operator-() const { return mint(-x);}
mint& operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint& operator-=(const mint a) {
if ((x += mod-a.x) >= mod) x -= mod;
return *this;
}
mint& operator*=(const mint a) {
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const {
mint res(*this);
return res+=a;
}
mint operator-(const mint a) const {
mint res(*this);
return res-=a;
}
mint operator*(const mint a) const {
mint res(*this);
return res*=a;
}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t>>1);
a *= a;
if (t&1) a *= *this;
return a;
}
// for prime mod
mint inv() const {
return pow(mod-2);
}
mint& operator/=(const mint a) {
return (*this) *= a.inv();
}
mint operator/(const mint a) const {
mint res(*this);
return res/=a;
}
};
int main() {
int N;
cin >> N;
ll A[N];
rep(i,N) cin >> A[i];
mint ans = 0;
rep(k,60) {
mint n1 = 0;
rep(i,N) {
if((A[i] >> k) & 1) n1+=1;
}
ans += n1*(mint(N)-n1)*mint(2).pow(k);
}
cout << ans.x << endl;
return 0;
}
| 18.795181 | 48 | 0.527564 | kitoko552 |
517854476b5e9fdff130edbcaef0775d56a1532c | 232 | cpp | C++ | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | #ifdef _OPENMP
#include <omp.h>
#endif
#ifdef _WIN32
#include <DxLib.h>
#ifndef __DXLIB
#define __DXLIB
#endif
#ifndef __WINDOWS__
#define __WINDOWS__
#endif
#else
#include <Siv3D.hpp>
#endif
#include <Sample/UseAsLib2/Sample1.hpp>
| 14.5 | 39 | 0.767241 | AsPJT |
5178f25f4875cdbef934fb4fc3337045663a5abb | 26,635 | cpp | C++ | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
/*
Although the code is original, many of the ideas for the profiler were borrowed from
"Real-Time In-Game Profiling" by Steve Rabin which can be found in Game Programming
Gems 1.
This code can easily be adapted to your own non-Ogre project. The only code that is
Ogre-dependent is in the visualization/logging routines and the use of the Timer class.
Enjoy!
*/
#include "OgreProfiler.h"
#include "OgreLogManager.h"
#include "OgreRenderSystem.h"
#include "OgreRoot.h"
#include "OgreTimer.h"
namespace Ogre
{
//-----------------------------------------------------------------------
// PROFILE DEFINITIONS
//-----------------------------------------------------------------------
template <>
Profiler *Singleton<Profiler>::msSingleton = 0;
Profiler *Profiler::getSingletonPtr() { return msSingleton; }
Profiler &Profiler::getSingleton()
{
assert( msSingleton );
return ( *msSingleton );
}
//-----------------------------------------------------------------------
Profile::Profile( const String &profileName, ProfileSampleFlags::ProfileSampleFlags flags,
uint32 groupID ) :
mName( profileName ),
mGroupID( groupID )
{
Ogre::Profiler::getSingleton().beginProfile( profileName, groupID, flags );
}
//-----------------------------------------------------------------------
Profile::~Profile() { Ogre::Profiler::getSingleton().endProfile( mName, mGroupID ); }
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// PROFILER DEFINITIONS
//-----------------------------------------------------------------------
Profiler::Profiler() :
mCurrent( &mRoot ),
mLast( NULL ),
mRoot(),
mInitialized( false ),
mUpdateDisplayFrequency( 10 ),
mCurrentFrame( 0 ),
mTimer( 0 ),
mTotalFrameTime( 0 ),
mEnabled( OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE ),
mUseStableMarkers( false ),
mNewEnableState( false ),
mProfileMask( 0xFFFFFFFF ),
mMaxTotalFrameTime( 0 ),
mAverageFrameTime( 0 ),
mResetExtents( false )
#if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
,
mRemotery( 0 )
#endif
{
mRoot.hierarchicalLvl = std::numeric_limits<uint>::max();
}
//-----------------------------------------------------------------------
ProfileInstance::ProfileInstance() :
parent( NULL ),
frameNumber( 0 ),
accum( 0 ),
hierarchicalLvl( 0 )
{
history.numCallsThisFrame = 0;
history.totalTimePercent = 0;
history.totalTimeMillisecs = 0;
history.totalCalls = 0;
history.maxTimePercent = 0;
history.maxTimeMillisecs = 0;
history.minTimePercent = 1;
history.minTimeMillisecs = 100000;
history.currentTimePercent = 0;
history.currentTimeMillisecs = 0;
frame.frameTime = 0;
frame.calls = 0;
}
ProfileInstance::~ProfileInstance() { destroyAllChildren(); }
//-----------------------------------------------------------------------
Profiler::~Profiler()
{
if( !mRoot.children.empty() )
{
// log the results of our profiling before we quit
logResults();
}
// clear all our lists
mDisabledProfiles.clear();
#if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
if( mRemotery )
{
Root::getSingleton().getRenderSystem()->deinitGPUProfiling();
rmt_DestroyGlobalInstance( mRemotery );
mRemotery = 0;
}
#endif
}
//-----------------------------------------------------------------------
void Profiler::setTimer( Timer *t ) { mTimer = t; }
//-----------------------------------------------------------------------
Timer *Profiler::getTimer()
{
assert( mTimer && "Timer not set!" );
return mTimer;
}
//-----------------------------------------------------------------------
void Profiler::setEnabled( bool enabled )
{
#if OGRE_PROFILING != OGRE_PROFILING_INTERNAL_OFFLINE
if( !mInitialized && enabled )
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->initializeSession();
# if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
rmtSettings *settings = rmt_Settings();
settings->messageQueueSizeInBytes *= 10;
settings->maxNbMessagesPerUpdate *= 10;
rmt_CreateGlobalInstance( &mRemotery );
rmt_SetCurrentThreadName( "Main Ogre Thread" );
Root::getSingleton().getRenderSystem()->initGPUProfiling();
# endif
mInitialized = true;
}
else if( mInitialized )
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->finializeSession();
mInitialized = false;
mEnabled = false;
# if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
Root::getSingleton().getRenderSystem()->deinitGPUProfiling();
if( mRemotery )
{
rmt_DestroyGlobalInstance( mRemotery );
mRemotery = 0;
}
# endif
}
#else
mEnabled = enabled;
mOfflineProfiler.setPaused( !enabled );
#endif
// We store this enable/disable request until the frame ends
// (don't want to screw up any open profiles!)
mNewEnableState = enabled;
}
//-----------------------------------------------------------------------
bool Profiler::getEnabled() const { return mEnabled; }
//-----------------------------------------------------------------------
void Profiler::setUseStableMarkers( bool useStableMarkers ) { mUseStableMarkers = useStableMarkers; }
//-----------------------------------------------------------------------
bool Profiler::getUseStableMarkers() const { return mUseStableMarkers; }
//-----------------------------------------------------------------------
void Profiler::changeEnableState()
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->changeEnableState( mNewEnableState );
mEnabled = mNewEnableState;
}
//-----------------------------------------------------------------------
void Profiler::disableProfile( const String &profileName )
{
// even if we are in the middle of this profile, endProfile() will still end it.
mDisabledProfiles.insert( profileName );
}
//-----------------------------------------------------------------------
void Profiler::enableProfile( const String &profileName ) { mDisabledProfiles.erase( profileName ); }
//-----------------------------------------------------------------------
void Profiler::beginProfile( const String &profileName, uint32 groupID,
ProfileSampleFlags::ProfileSampleFlags flags )
{
#if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE
mOfflineProfiler.profileBegin( profileName.c_str(), flags );
#else
// regardless of whether or not we are enabled, we need the application's root profile (ie the
// first profile started each frame) we need this so bogus profiles don't show up when users
// enable profiling mid frame so we check
// if the profiler is enabled
if( !mEnabled )
return;
// mask groups
if( ( groupID & mProfileMask ) == 0 )
return;
// we only process this profile if isn't disabled
if( mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() )
return;
// empty string is reserved for the root
// not really fatal anymore, however one shouldn't name one's profile as an empty string anyway.
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
// this would be an internal error.
assert( mCurrent );
// need a timer to profile!
assert( mTimer && "Timer not set!" );
ProfileInstance *&instance = mCurrent->childrenMap[profileName];
if( instance )
{ // found existing child.
// Sanity check.
assert( instance->name == profileName );
if( instance->frameNumber != mCurrentFrame )
{ // new frame, reset stats
instance->frame.calls = 0;
instance->frame.frameTime = 0;
instance->frameNumber = mCurrentFrame;
}
}
else
{ // new child!
instance = OGRE_NEW ProfileInstance();
instance->name = profileName;
instance->parent = mCurrent;
instance->hierarchicalLvl = mCurrent->hierarchicalLvl + 1;
mCurrent->children.push_back( instance );
}
instance->frameNumber = mCurrentFrame;
mCurrent = instance;
// we do this at the very end of the function to get the most
// accurate timing results
mCurrent->currTime = mTimer->getMicroseconds();
#endif
}
//-----------------------------------------------------------------------
void Profiler::endProfile( const String &profileName, uint32 groupID )
{
#if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE
mOfflineProfiler.profileEnd();
#else
if( !mEnabled )
{
// if the profiler received a request to be enabled or disabled
if( mNewEnableState != mEnabled )
{ // note mNewEnableState == true to reach this.
changeEnableState();
// NOTE we will be in an 'error' state until the next begin. ie endProfile will likely
// get invoked using a profileName that was never started. even then, we can't be sure
// that the next beginProfile will be the true start of a new frame
}
return;
}
else
{
if( mNewEnableState != mEnabled )
{ // note mNewEnableState == false to reach this.
changeEnableState();
// unwind the hierarchy, should be easy enough
mCurrent = &mRoot;
mLast = NULL;
}
if( &mRoot == mCurrent && mLast )
{ // profiler was enabled this frame, but the first subsequent beginProfile was NOT the
// beinging of a new frame as we had hoped.
// we have a bogus ProfileInstance in our hierarchy, we will need to remove it, then
// update the overlays so as not to confuse ze user
// we could use mRoot.children.find() instead of this, except we'd be compairing strings
// instead of a pointer. the string way could be faster, but i don't believe it would.
ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end();
for( ; it != endit; ++it )
{
if( mLast == *it )
{
mRoot.childrenMap.erase( ( *it )->name );
mRoot.children.erase( it );
break;
}
}
// with mLast == NULL we won't reach this code, in case this isn't the end of the top
// level profile
ProfileInstance *last = mLast;
mLast = NULL;
OGRE_DELETE last;
processFrameStats();
displayResults();
}
}
if( &mRoot == mCurrent )
return;
// mask groups
if( ( groupID & mProfileMask ) == 0 )
return;
// need a timer to profile!
assert( mTimer && "Timer not set!" );
// get the end time of this profile
// we do this as close the beginning of this function as possible
// to get more accurate timing results
const uint64 endTime = mTimer->getMicroseconds();
// empty string is reserved for designating an empty parent
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
// we only process this profile if isn't disabled
// we check the current instance name against the provided profileName as a guard against
// disabling a profile name /after/ said profile began
if( mCurrent->name != profileName &&
mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() )
return;
// calculate the elapsed time of this profile
const uint64 timeElapsed = endTime - mCurrent->currTime;
// update parent's accumulator if it isn't the root
if( &mRoot != mCurrent->parent )
{
// add this profile's time to the parent's accumlator
mCurrent->parent->accum += timeElapsed;
}
mCurrent->frame.frameTime += timeElapsed;
++mCurrent->frame.calls;
mLast = mCurrent;
mCurrent = mCurrent->parent;
if( &mRoot == mCurrent )
{
// the stack is empty and all the profiles have been completed
// we have reached the end of the frame so process the frame statistics
// we know that the time elapsed of the main loop is the total time the frame took
mTotalFrameTime = timeElapsed;
if( timeElapsed > mMaxTotalFrameTime )
mMaxTotalFrameTime = timeElapsed;
// we got all the information we need, so process the profiles
// for this frame
processFrameStats();
// we display everything to the screen
displayResults();
}
#endif
}
//-----------------------------------------------------------------------
void Profiler::beginGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->beginProfileEvent( event );
}
//-----------------------------------------------------------------------
void Profiler::endGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->endProfileEvent();
}
//-----------------------------------------------------------------------
void Profiler::markGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->markProfileEvent( event );
}
//-----------------------------------------------------------------------
void Profiler::beginGPUSample( const String &name, uint32 *hashCache )
{
Root::getSingleton().getRenderSystem()->beginGPUSampleProfile( name, hashCache );
}
//-----------------------------------------------------------------------
void Profiler::endGPUSample( const String &name )
{
Root::getSingleton().getRenderSystem()->endGPUSampleProfile( name );
}
//-----------------------------------------------------------------------
void Profiler::processFrameStats( ProfileInstance *instance, Real &maxFrameTime )
{
// calculate what percentage of frame time this profile took
const Real framePercentage = (Real)instance->frame.frameTime / (Real)mTotalFrameTime;
const Real frameTimeMillisecs = (Real)instance->frame.frameTime / 1000.0f;
// update the profile stats
instance->history.currentTimePercent = framePercentage;
instance->history.currentTimeMillisecs = frameTimeMillisecs;
if( mResetExtents )
{
instance->history.totalTimePercent = framePercentage;
instance->history.totalTimeMillisecs = frameTimeMillisecs;
instance->history.totalCalls = 1;
}
else
{
instance->history.totalTimePercent += framePercentage;
instance->history.totalTimeMillisecs += frameTimeMillisecs;
instance->history.totalCalls++;
}
instance->history.numCallsThisFrame = instance->frame.calls;
// if we find a new minimum for this profile, update it
if( frameTimeMillisecs < instance->history.minTimeMillisecs || mResetExtents )
{
instance->history.minTimePercent = framePercentage;
instance->history.minTimeMillisecs = frameTimeMillisecs;
}
// if we find a new maximum for this profile, update it
if( frameTimeMillisecs > instance->history.maxTimeMillisecs || mResetExtents )
{
instance->history.maxTimePercent = framePercentage;
instance->history.maxTimeMillisecs = frameTimeMillisecs;
}
if( instance->frame.frameTime > maxFrameTime )
maxFrameTime = (Real)instance->frame.frameTime;
ProfileChildrenVec::iterator it = instance->children.begin(), endit = instance->children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
// we set the number of times each profile was called per frame to 0
// because not all profiles are called every frame
child->history.numCallsThisFrame = 0;
if( child->frame.calls > 0 )
{
processFrameStats( child, maxFrameTime );
}
}
}
//-----------------------------------------------------------------------
void Profiler::processFrameStats()
{
Real maxFrameTime = 0;
ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
// we set the number of times each profile was called per frame to 0
// because not all profiles are called every frame
child->history.numCallsThisFrame = 0;
if( child->frame.calls > 0 )
{
processFrameStats( child, maxFrameTime );
}
}
// Calculate whether the extents are now so out of date they need regenerating
if( mCurrentFrame == 0 )
mAverageFrameTime = maxFrameTime;
else
mAverageFrameTime = ( mAverageFrameTime + maxFrameTime ) * 0.5f;
if( (Real)mMaxTotalFrameTime > mAverageFrameTime * 4 )
{
mResetExtents = true;
mMaxTotalFrameTime = (ulong)mAverageFrameTime;
}
else
mResetExtents = false;
}
//-----------------------------------------------------------------------
void Profiler::displayResults()
{
// if its time to update the display
if( !( mCurrentFrame % mUpdateDisplayFrequency ) )
{
// ensure the root won't be culled
mRoot.frame.calls = 1;
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->displayResults( mRoot, mMaxTotalFrameTime );
}
++mCurrentFrame;
}
//-----------------------------------------------------------------------
bool Profiler::watchForMax( const String &profileName )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForMax( profileName );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForMax( const String &profileName )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForMax() ) ||
child->watchForMax( profileName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
bool Profiler::watchForMin( const String &profileName )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForMin( profileName );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForMin( const String &profileName )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForMin() ) ||
child->watchForMin( profileName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
bool Profiler::watchForLimit( const String &profileName, Real limit, bool greaterThan )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForLimit( profileName, limit, greaterThan );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForLimit( const String &profileName, Real limit, bool greaterThan )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForLimit( limit, greaterThan ) ) ||
child->watchForLimit( profileName, limit, greaterThan ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
void Profiler::logResults()
{
LogManager::getSingleton().logMessage(
"----------------------Profiler Results----------------------" );
for( ProfileChildrenVec::iterator it = mRoot.children.begin(); it != mRoot.children.end(); ++it )
{
( *it )->logResults();
}
LogManager::getSingleton().logMessage(
"------------------------------------------------------------" );
}
//-----------------------------------------------------------------------
void ProfileInstance::logResults()
{
// create an indent that represents the hierarchical order of the profile
String indent = "";
for( uint i = 0; i < hierarchicalLvl; ++i )
{
indent = indent + "\t";
}
LogManager::getSingleton().logMessage(
indent + "Name " + name + " | Min " + StringConverter::toString( history.minTimePercent ) +
" | Max " + StringConverter::toString( history.maxTimePercent ) + " | Avg " +
StringConverter::toString( history.totalTimePercent / history.totalCalls ) );
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
( *it )->logResults();
}
}
//-----------------------------------------------------------------------
void Profiler::reset( bool deleteAll )
{
mRoot.reset();
mMaxTotalFrameTime = 0;
if( deleteAll )
mRoot.destroyAllChildren();
}
//-----------------------------------------------------------------------
void ProfileInstance::destroyAllChildren()
{
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
ProfileInstance *instance = *it;
OGRE_DELETE instance;
}
children.clear();
childrenMap.clear();
}
//-----------------------------------------------------------------------
void ProfileInstance::reset()
{
history.currentTimePercent = history.maxTimePercent = history.totalTimePercent = 0;
history.currentTimeMillisecs = history.maxTimeMillisecs = history.totalTimeMillisecs = 0;
history.numCallsThisFrame = history.totalCalls = 0;
history.minTimePercent = 1;
history.minTimeMillisecs = 100000;
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
( *it )->reset();
}
}
//-----------------------------------------------------------------------
void Profiler::setUpdateDisplayFrequency( uint freq ) { mUpdateDisplayFrequency = freq; }
//-----------------------------------------------------------------------
uint Profiler::getUpdateDisplayFrequency() const { return mUpdateDisplayFrequency; }
//-----------------------------------------------------------------------
void Profiler::addListener( ProfileSessionListener *listener ) { mListeners.push_back( listener ); }
//-----------------------------------------------------------------------
void Profiler::removeListener( ProfileSessionListener *listener )
{
mListeners.erase( std::find( mListeners.begin(), mListeners.end(), listener ) );
}
//-----------------------------------------------------------------------
} // namespace Ogre
| 39.635417 | 105 | 0.516689 | FreeNightKnight |
51829af04373ec22127a695a60160a8edfa14157 | 1,099 | cpp | C++ | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | null | null | null | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | null | null | null | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | 1 | 2018-03-29T12:00:15.000Z | 2018-03-29T12:00:15.000Z | #include <iostream>
#include <climits>
#include <cmath>
using namespace std;
int main(){
const int N = 7;
int dp[N];
int M = 30;
int cost[N][N];
int G[N];
for(int i = 0; i < N; ++i){
cin >> G[i];
}
int temp;
for(int i = 0; i < N; ++i){
for(int j = i; j < N; ++j){
if(i == j)
cost[i][j] = G[j];
else
cost[i][j] = cost[i][j - 1] + G[j] + 1;
}
}
int last;
for(int i = 0; i < N; ++i){
dp[i] = INT_MAX;
for(int j = 0; j <= i; ++j){
if(cost[j][i] > M){
temp = INT_MAX;
continue;
}
else if(i == N - 1){
temp = j == 0? 0 : dp[j - 1];
}
else if(j == 0){
temp = M - cost[j][i];
}
else{
temp = dp[j - 1] + M - cost[j][i];
}
if(temp < dp[i]){
dp[i] = temp;
last = j;
}
}
}
cout << dp[N - 1] << endl;
return 0;
} | 22.895833 | 55 | 0.312102 | ftxj |
51835c5df2de4879756205d30600687a501c29c4 | 3,573 | cpp | C++ | src/couchdb/couchview.cpp | jpnurmi/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 2 | 2020-12-12T03:15:03.000Z | 2022-01-03T11:11:58.000Z | src/couchdb/couchview.cpp | CELLINKAB/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 3 | 2020-11-28T10:53:10.000Z | 2020-11-28T14:00:29.000Z | src/couchdb/couchview.cpp | jpnurmi/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 2 | 2021-02-13T14:38:58.000Z | 2022-02-21T15:42:26.000Z | #include "couchview.h"
#include "couchclient.h"
#include "couchdatabase.h"
#include "couchdesigndocument.h"
#include "couchrequest.h"
#include "couchresponse.h"
class CouchViewPrivate
{
Q_DECLARE_PUBLIC(CouchView)
public:
CouchResponse *response(CouchResponse *response)
{
Q_Q(CouchView);
QObject::connect(response, &CouchResponse::errorOccurred, [=](const CouchError &error) {
emit q->errorOccurred(error);
});
return response;
}
CouchView *q_ptr = nullptr;
QString name;
CouchDesignDocument *designDocument = nullptr;
};
CouchView::CouchView(QObject *parent)
: CouchView(QString(), nullptr, parent)
{
}
CouchView::CouchView(const QString &name, CouchDesignDocument *designDocument, QObject *parent)
: QObject(parent),
d_ptr(new CouchViewPrivate)
{
Q_D(CouchView);
d->q_ptr = this;
d->name = name;
setDesignDocument(designDocument);
}
CouchView::~CouchView()
{
}
QUrl CouchView::url() const
{
Q_D(const CouchView);
if (!d->designDocument || d->name.isEmpty())
return QUrl();
return Couch::viewUrl(d->designDocument->url(), d->name);
}
QString CouchView::name() const
{
Q_D(const CouchView);
return d->name;
}
void CouchView::setName(const QString &name)
{
Q_D(CouchView);
if (d->name == name)
return;
d->name = name;
emit urlChanged(url());
emit nameChanged(name);
}
CouchClient *CouchView::client() const
{
Q_D(const CouchView);
if (!d->designDocument)
return nullptr;
return d->designDocument->client();
}
CouchDatabase *CouchView::database() const
{
Q_D(const CouchView);
if (!d->designDocument)
return nullptr;
return d->designDocument->database();
}
CouchDesignDocument *CouchView::designDocument() const
{
Q_D(const CouchView);
return d->designDocument;
}
void CouchView::setDesignDocument(CouchDesignDocument *designDocument)
{
Q_D(CouchView);
if (d->designDocument == designDocument)
return;
QUrl oldUrl = url();
CouchClient *oldClient = client();
CouchDatabase *oldDatabase = database();
if (d->designDocument)
d->designDocument->disconnect(this);
if (designDocument) {
connect(designDocument, &CouchDesignDocument::urlChanged, this, &CouchView::urlChanged);
connect(designDocument, &CouchDesignDocument::clientChanged, this, &CouchView::clientChanged);
connect(designDocument, &CouchDesignDocument::databaseChanged, this, &CouchView::databaseChanged);
}
d->designDocument = designDocument;
if (oldUrl != url())
emit urlChanged(url());
if (oldClient != client())
emit clientChanged(client());
if (oldDatabase != database())
emit databaseChanged(database());
emit designDocumentChanged(designDocument);
}
CouchResponse *CouchView::listRowIds()
{
return queryRows(CouchQuery());
}
CouchResponse *CouchView::listFullRows()
{
return queryRows(CouchQuery::full());
}
CouchResponse *CouchView::queryRows(const CouchQuery &query)
{
Q_D(CouchView);
CouchClient *client = d->designDocument ? d->designDocument->client() : nullptr;
if (!client)
return nullptr;
CouchRequest request = Couch::queryRows(url(), query);
CouchResponse *response = client->sendRequest(request);
if (!response)
return nullptr;
connect(response, &CouchResponse::received, [=](const QByteArray &data) {
emit rowsListed(Couch::toDocumentList(data));
});
return d->response(response);
}
| 23.662252 | 106 | 0.671425 | jpnurmi |
3d601d61551912a675c10715d1120966d560daf2 | 506 | cpp | C++ | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | #include "gearpch.h"
#include "VertexBuffer.h"
#include <glad/glad.h>
VertexBuffer::VertexBuffer(const void* data, unsigned int size) {
glGenBuffers(1, &m_RendererId);
glBindBuffer(GL_ARRAY_BUFFER, m_RendererId);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
}
VertexBuffer::~VertexBuffer() {
glDeleteBuffers(1, &m_RendererId);
}
void VertexBuffer::bind() const {
glBindBuffer(GL_ARRAY_BUFFER, m_RendererId);
}
void VertexBuffer::unbind() const {
glBindBuffer(GL_ARRAY_BUFFER, 0);
} | 23 | 65 | 0.764822 | RustyGuard |
3d693dac6cbf4bafac99f7da2535618067b5fb6a | 1,553 | cc | C++ | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 28 | 2015-04-11T10:20:25.000Z | 2021-04-28T15:48:36.000Z | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 1 | 2016-11-25T06:10:13.000Z | 2016-11-25T06:10:13.000Z | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 18 | 2015-04-10T08:25:48.000Z | 2022-01-25T11:22:31.000Z |
#include "Utility.h"
Utility::Utility(void)
{
}
Utility::~Utility(void)
{
}
bool Utility::checking_prime_integer(uint32_t v)
{
for (int i = 2; i < v; i++)
{
if (v % i == 0)
{
return 0;
}
}
return 1;
}
uint32_t Utility::find_smallest_prime_integer(uint32_t v)
{
bool r = 0;
uint32_t prime = v;
r = checking_prime_integer(prime);
while(r == 0)
{
prime++;
r = checking_prime_integer(prime);
}
//prime--;
return prime;
}
ublas::vector<uint8_t> Utility::matrix_row_XOR(ublas::vector<uint8_t> row_1, ublas::vector<uint8_t> row_2)
{
if (row_1.size() != row_2.size())
{
std::cout << "The columns are not the same in two rows!" << std::endl;
exit(-1);
}
ublas::vector<uint8_t> r(row_1.size());
for (int i = 0; i < row_1.size(); ++i)
{
r(i) = row_1(i) ^ row_2(i);
}
return r;
}
// template<class T>
// bool Utility::InvertMatrix (const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse)
// {
// using namespace boost::numeric::ublas;
// typedef permutation_matrix<std::size_t> pmatrix;
// // create a working copy of the input
// matrix<T> A(input);
// // create a permutation matrix for the LU-factorization
// pmatrix pm(A.size1());
// // perform LU-factorization
// int res = lu_factorize(A,pm);
// if( res != 0 ) return false;
// // create identity matrix of "inverse"
// inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));
// // backsubstitute to get the inverse
// lu_substitute(A, pm, inverse);
// return true;
// } | 16.521277 | 120 | 0.631037 | RabbitNick |
3d6c20b45a546f37ae10e83a2456432c8c3ded8d | 7,016 | cpp | C++ | src/chatroomwindow.cpp | Alpha-Incorporated/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 2 | 2019-02-27T12:02:16.000Z | 2019-02-27T15:29:49.000Z | src/chatroomwindow.cpp | Alien-Inc/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 2 | 2020-11-19T08:39:52.000Z | 2020-11-19T08:50:19.000Z | src/chatroomwindow.cpp | Alpha-Incorporated/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 1 | 2020-02-21T04:26:13.000Z | 2020-02-21T04:26:13.000Z | #include "chatroomwindow.h"
using namespace chat_room;
ChatRoomWindow::ChatRoomWindow() : QMainWindow(nullptr), initialized(false)
{
// Set up Window
this->setGeometry(150, 150, 640, 480);
setWindowTitle(tr("Chat"));
setMinimumSize(640, 480);
// Menu Bar
exit_chat_action = new QAction(QString("Exit"), this);
chat_menu = menuBar()->addMenu(tr("Chat"));
chat_menu->addAction(exit_chat_action);
connect(exit_chat_action, &QAction::triggered, this, &ChatRoomWindow::exitCurrentChat);
menuBar()->hide();
// Conversation List
conversation_model = new ConversationModel(this);
conversation_list = new QListView(this);
conversation_list->setModel(conversation_model);
conversation_list->setGeometry(0, 0, 640, 480);
connect(conversation_list, &QListView::clicked, this, &ChatRoomWindow::onConversationListClicked);
// Additional set-up
app_data_directory = QString(getenv("LOCALAPPDATA")) + QString("/ChatApp/");
connect(client_socket, &QWebSocket::textMessageReceived, this, &ChatRoomWindow::onTextMessageReceived);
connect(client_socket, &QWebSocket::binaryMessageReceived, this, &ChatRoomWindow::onBinaryMessageReceived);
std::clog << "Chat : ChatRoomWindow set up!" << std::endl;
}
ChatRoomWindow::~ChatRoomWindow()
{
if (message_list) {
delete message_list;
}
if (conversation_list) {
delete conversation_list;
}
if (message_model) {
delete message_model;
}
if (conversation_model) {
delete conversation_model;
}
if (send_text_button) {
delete send_text_button;
}
if (message_input_box) {
delete message_input_box;
}
if (chat_menu_bar) {
delete chat_menu_bar;
}
if (chat_menu) {
delete chat_menu;
}
if (exit_chat_action) {
delete exit_chat_action;
}
}
void ChatRoomWindow::onConversationListClicked(const QModelIndex& model_index)
{
std::clog << "Chat : ChatRoomWindow - Chat list item clicked" << std::endl;
unsigned int index = model_index.row();
User clicked_user = user_list[index];
current_receiver = clicked_user;
// Open the particular conversation
this->setUpChatRoom();
// Add pending messages
std::stringstream file_name_stream;
file_name_stream << current_receiver << current_user;
std::string file_name;
std::getline(file_name_stream, file_name);
std::ifstream pending_message_file(file_name);
if (pending_message_file.is_open())
{
Message message;
while (!(pending_message_file >> message).eof()) {
message_model->addMessage(message);
}
pending_message_file.close();
std::remove(file_name.c_str());
}
initialized = true;
}
void ChatRoomWindow::onSendTextButtonClicked()
{
std::clog << "Chat : ChatRoomWindow - Send text button clicked" << std::endl;
QString text = message_input_box->text();
message_input_box->setText(QString(""));
if (!text.isEmpty()) {
Message message(current_user, current_receiver, text.toStdString());
message_model->addMessage(message);
std::stringstream message_stream;
message_stream << message;
std::string data;
std::getline(message_stream, data);
client_socket->sendTextMessage(QString(data.c_str()));
}
}
void ChatRoomWindow::onReturnKeyPressed()
{
std::clog << "Chat : ChatRoom - Return key pressed" << std::endl;
QString text = message_input_box->text();
message_input_box->setText(QString(""));
if (!text.isEmpty()) {
Message message(current_user, current_receiver, text.toStdString());
message_model->addMessage(message);
std::stringstream message_stream;
message_stream << message;
std::string data;
std::getline(message_stream, data);
client_socket->sendTextMessage(QString(data.c_str()));
}
}
void ChatRoomWindow::onTextMessageReceived(const QString &data)
{
std::clog << "Chat : ChatRoomWindow - New message received" << std::endl;
std::stringstream data_stream(data.toStdString());
User from, to;
std::string text;
std::getline(data_stream >> from >> to, text);
Message message(from, to, text);
if (!text.empty()) {
if (from == current_receiver) {
message_model->addMessage(message);
}
else {
std::stringstream file_name_stream;
file_name_stream >> from >> to;
std::string file_name;
std::getline(file_name_stream, file_name);
std::ofstream pending_messages_file(file_name, std::ios::app);
pending_messages_file << message << std::endl;
}
}
}
void ChatRoomWindow::onBinaryMessageReceived(const QByteArray &byte_stream)
{
std::clog << "Chat : ChatRoomWindow - Binary data received from server" << std::endl;
std::stringstream data_stream(byte_stream.toStdString());
std::string type;
data_stream >> type;
if (type == "userlist")
{
User user;
user_list.erase(user_list.begin(), user_list.end());
while (!(data_stream >> user).eof())
{
user_list.push_back(user);
}
conversation_model->updateUserList(user_list);
}
else if (type == "userdata") {
data_stream >> current_user;
std::clog << "Chat : ChatRoomWindow - Current user data populated" << std::endl;
}
}
void ChatRoomWindow::setUpChatRoom()
{
conversation_list->hide();
send_text_button = new QPushButton(SEND_TEXT_BUTTON_TEXT, this);
message_input_box = new QLineEdit(this);
message_list = new QListView(this);
send_text_button->setGeometry(540, 460, 80, 40);
message_input_box->setGeometry(0, 440, 560, 40);
message_input_box->setFont(QFont("Default", 15));
message_model = new MessageModel(this);
message_list->setModel(message_model);
message_list->setGeometry(0, 25, 640, 415);
message_list->setFont(QFont("Default", 15));
menuBar()->show();
send_text_button->show();
message_input_box->show();
message_list->show();
connect(send_text_button, &QPushButton::clicked, this, &ChatRoomWindow::onSendTextButtonClicked);
connect(message_input_box, &QLineEdit::returnPressed, this, &ChatRoomWindow::onReturnKeyPressed);
}
void ChatRoomWindow::exitCurrentChat()
{
std::clog << "Chat : ChatRoom - Current chat exited" << std::endl;
send_text_button->disconnect();
message_input_box->disconnect();
message_list->disconnect();
delete send_text_button;
delete message_input_box;
delete message_list;
menuBar()->hide();
conversation_list->show();
}
| 28.064 | 112 | 0.638683 | Alpha-Incorporated |
3d70329e7cbc40ded3bdfda45592de5854d0ae37 | 677 | cpp | C++ | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | /*
* TASK : AwitCat34
* AUTHOR : Hydrolyzed~
* LANG : C
* SCHOOL : RYW
* */
#include<stdio.h>
#include<string.h>
char a[510];
char *ptr;
int main (){
int i,q,ch,ch2,len;
gets(a);
sscanf(a,"%d",&q);
while(q--)
{
gets(a);
if(a[strlen(a)-1]=='\r')
a[strlen(a)-1]='\0';
ptr = strtok(a," ");
ch = 1;
while(ptr!= NULL)
{
len = strlen(ptr);
if(len%4==0){
for(i=0,ch2=1;i<len;i+=4){
if(strncmp("meow",&ptr[i],4)){
ch2=0;
break;
}
}
if(ch2){
printf("YES\n"); ch= 0; break;
}
}
ptr = strtok(NULL," ");
}
if(ch){
printf("NO\n");
}
}
}
| 14.104167 | 36 | 0.423929 | MasterIceZ |
3d723a663ce7d5148bc1a2e3f308422cc832ea65 | 286 | cpp | C++ | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | //
// Created by sebas on 7/11/19.
//
#include "PuntuacionJugadores.h"
void
PuntuacionJugadores::setPuntuacion (string jugador, int puntuacion)
{
puntuaciones[jugador] = puntuacion;
}
unordered_map < string, int >
PuntuacionJugadores::getPuntuaciones ()
{
return puntuaciones;
}
| 15.888889 | 67 | 0.744755 | humbertodias |
3d73ddf3050c562588f8e6fa6b3e018b6ae3d663 | 494 | hpp | C++ | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | //
// FactoryBuilder.hpp
// DesignPatterns
//
// Created by Shen Lu on 2018/8/18.
// Copyright © 2018 Shen Lu. All rights reserved.
//
#ifndef FactoryBuilder_hpp
#define FactoryBuilder_hpp
#include <memory>
namespace ls {
typedef enum FactoryType {
Factory1 = 0,
Factory2 = 1
}FactoryType;
class Factory;
class FactoryBuilder {
public:
static std::shared_ptr<Factory> createFactory(FactoryType type);
};
}
#endif /* FactoryBuilder_hpp */
| 18.296296 | 72 | 0.663968 | ludaye123 |
3d74c2e8973c303968c154b02ea4a55a0df334c6 | 160 | cpp | C++ | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 1 | 2017-10-24T21:43:43.000Z | 2017-10-24T21:43:43.000Z | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 3 | 2017-12-02T08:15:29.000Z | 2018-06-05T19:35:56.000Z | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | null | null | null | #include "randomFactory.hpp"
RandomFactory::RandomFactory()
: gen_((std::random_device())())
{}
unsigned int RandomFactory::operator()() {
return gen_();
}
| 16 | 42 | 0.69375 | uncerso |
3d74fd41ee998d04b737d0e3cc6ccb61e8cdff43 | 4,051 | cpp | C++ | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | 32 | 2020-04-17T22:48:53.000Z | 2021-06-15T13:13:28.000Z | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | null | null | null | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | 2 | 2020-06-05T15:51:31.000Z | 2021-08-31T15:09:26.000Z | //
// Window.cpp -- implementation of the various function window classes
// See the copyright notice and acknowledgment of authors in the file COPYRIGHT
//
#include "Window.h"
#include <math.h>
using namespace csl;
Window::Window() : UnitGenerator(), mGain(1) {
this->setSize(CGestalt::blockSize());
}
// Gain is optional and defaults to 1 when not specified.
Window::Window(unsigned windowSize, float gain) : UnitGenerator(), mGain(gain) {
this->setSize(windowSize);
}
Window::~Window() {
mWindowBuffer.freeBuffers();
}
void Window::setGain(float gain) {
mGain = gain;
fillWindow(); // Re-caluclate window using new gain value.
}
void Window::setSize(unsigned windowSize) {
mWindowBufferPos = 0;
mWindowSize = windowSize;
// If previously allocated, free me first.
mWindowBuffer.freeBuffers();
mWindowBuffer.setSize(1, mWindowSize); // Allocate memory to store the window.
mWindowBuffer.allocateBuffers();
fillWindow(); // Fill the buffer with the window data.
}
void Window::nextBuffer(Buffer &outputBuffer, unsigned outBufNum) throw (CException) {
/// get everything into registers
unsigned numFrames = outputBuffer.mNumFrames;
sample* outputBufferPtr = outputBuffer.buffer(outBufNum);
sample* windowBufferPtr = mWindowBuffer.buffer(0);
unsigned windowBufferPos = mWindowBufferPos;
unsigned windowBufferSize = mWindowSize;
#ifdef CSL_DEBUG
logMsg("Window::nextBuffer");
#endif
for (unsigned i = 0; i < numFrames; i++) {
if (windowBufferPos > windowBufferSize)
windowBufferPos = 0;
*outputBufferPtr++ = windowBufferPtr[windowBufferPos++];
}
mWindowBufferPos = windowBufferPos;
}
void Window::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
// create the window -- I make a Hamming window, subclasses may override
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.54 - 0.46*cos(CSL_TWOPI*i/(mWindowSize - 1) ));
}
void RectangularWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
for (unsigned i = 0; i < mWindowSize; i++ ) // create the window
*windowBufferPtr++ = mGain;
}
void TriangularWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
float accum = 0.0f;
unsigned winHalf = mWindowSize / 2;
float step = 1.0f / ((float) winHalf);
for (unsigned i = 0; i < winHalf; i++ ) { // create the rising half
*windowBufferPtr++ = accum;
accum += step;
}
for (unsigned i = winHalf; i < mWindowSize; i++ ) { // create the falling half
*windowBufferPtr++ = accum;
accum -= step;
}
}
void HammingWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.54 - 0.46*cos(i * increment));
}
void HannWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = 0.5 * (1 - cos(i * increment)) * mGain;
}
void BlackmanWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.42 - 0.5 * cos(i * increment) + 0.08 * cos(2 * i * increment)) * mGain;
}
void BlackmanHarrisWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.35875 - 0.48829 * cos(i * increment)
+ 0.14128 * cos(2 * i * increment)
- 0.01168 * cos(3 * i * increment)) * mGain;
}
void WelchWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = 2.f/(mWindowSize - 1);
sample phase = -1.f;
for (unsigned i = 0; i < mWindowSize; i++ ) { // create the window
*windowBufferPtr++ = (1.f - phase * phase) * mGain;
phase += increment;
}
}
void Window::dump() {
logMsg("Window of size: %d samples", mWindowSize);
}
| 30.458647 | 97 | 0.690941 | eriser |
3d7c3af74d836e566f95a05cb69cb62848074c79 | 5,123 | hpp | C++ | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | null | null | null | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | 18 | 2019-12-13T15:52:26.000Z | 2020-01-17T14:51:33.000Z | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | 1 | 2021-12-23T05:53:22.000Z | 2021-12-23T05:53:22.000Z | #ifndef STRF_DETAIL_PRINTERS_TUPLE_HPP
#define STRF_DETAIL_PRINTERS_TUPLE_HPP
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <strf/detail/facets/encoding.hpp>
namespace strf {
namespace detail {
template <typename Arg>
using opt_val_or_cref = std::conditional_t
< std::is_array<Arg>::value, const Arg&, Arg > ;
template <std::size_t I, typename T>
struct indexed_obj
{
constexpr STRF_HD indexed_obj(const T& cp)
: obj(cp)
{
}
T obj;
};
struct simple_tuple_from_args {};
template <typename ISeq, typename ... T>
class simple_tuple_impl;
template <std::size_t ... I, typename ... T>
class simple_tuple_impl<std::index_sequence<I...>, T...>
: private indexed_obj<I, T> ...
{
template <std::size_t J, typename U>
static constexpr STRF_HD const indexed_obj<J, U>& _get(const indexed_obj<J, U>& r)
{
return r;
}
public:
static constexpr std::size_t size = sizeof...(T);
template <typename ... Args>
constexpr STRF_HD explicit simple_tuple_impl(simple_tuple_from_args, Args&& ... args)
: indexed_obj<I, T>(args)...
{
}
template <std::size_t J>
constexpr STRF_HD const auto& get() const
{
return _get<J>(*this).obj;
}
};
template <typename ... T>
class simple_tuple
: public strf::detail::simple_tuple_impl
< std::make_index_sequence<sizeof...(T)>, T...>
{
using strf::detail::simple_tuple_impl
< std::make_index_sequence<sizeof...(T)>, T...>
::simple_tuple_impl;
};
template <typename ... Args>
constexpr STRF_HD strf::detail::simple_tuple
< strf::detail::opt_val_or_cref<Args>... >
make_simple_tuple(const Args& ... args)
{
return strf::detail::simple_tuple
< strf::detail::opt_val_or_cref<Args>... >
{ strf::detail::simple_tuple_from_args{}, args... };
}
template <std::size_t J, typename ... T>
constexpr STRF_HD const auto& get(const simple_tuple<T...>& tp)
{
return tp.template get<J>();
}
template <std::size_t I, typename Printer>
struct indexed_printer
{
using char_type = typename Printer::char_type;
template <typename FPack, typename Preview, typename Arg>
STRF_HD indexed_printer( const FPack& fp
, Preview& preview
, const Arg& arg )
: printer(make_printer<char_type>(strf::rank<5>(), fp, preview, arg))
{
}
STRF_HD indexed_printer(const indexed_printer& other)
: printer(other.printer)
{
}
STRF_HD indexed_printer(indexed_printer&& other)
: printer(other.printer)
{
}
Printer printer;
};
template < typename CharT
, typename ISeq
, typename ... Printers >
class printers_tuple_impl;
template < typename CharT
, std::size_t ... I
, typename ... Printers >
class printers_tuple_impl<CharT, std::index_sequence<I...>, Printers...>
: private detail::indexed_printer<I, Printers> ...
{
template <std::size_t J, typename T>
static STRF_HD const indexed_printer<J, T>& _get(const indexed_printer<J, T>& r)
{
return r;
}
public:
using char_type = CharT;
static constexpr std::size_t size = sizeof...(Printers);
template < typename FPack, typename Preview, typename ... Args >
STRF_HD printers_tuple_impl
( const FPack& fp
, Preview& preview
, const strf::detail::simple_tuple<Args...>& args )
: indexed_printer<I, Printers>(fp, preview, args.template get<I>()) ...
{
}
template <std::size_t J>
STRF_HD const auto& get() const
{
return _get<J>(*this).printer;
}
};
template< typename CharT, std::size_t ... I, typename ... Printers >
STRF_HD void write( strf::basic_outbuf<CharT>& ob
, const strf::detail::printers_tuple_impl
< CharT, std::index_sequence<I...>, Printers... >& printers )
{
strf::detail::write_args<CharT>(ob, printers.template get<I>()...);
}
template < typename CharT, typename ... Printers >
using printers_tuple = printers_tuple_impl
< CharT
, std::make_index_sequence<sizeof...(Printers)>
, Printers... >;
template < typename CharT
, typename FPack
, typename Preview
, typename ISeq
, typename ... Args >
class printers_tuple_alias
{
template <typename Arg>
using _printer
= decltype(make_printer<CharT>( strf::rank<5>()
, std::declval<const FPack&>()
, std::declval<Preview&>()
, std::declval<const Arg&>()));
public:
using type = printers_tuple_impl<CharT, ISeq, _printer<Args>...>;
};
template < typename CharT, typename FPack, typename Preview, typename ... Args >
using printers_tuple_from_args
= typename printers_tuple_alias
< CharT, FPack, Preview, std::make_index_sequence<sizeof...(Args)>, Args... >
:: type;
} // namespace detail
} // namespace strf
#endif // STRF_DETAIL_PRINTERS_TUPLE_HPP
| 26.407216 | 89 | 0.632637 | eyalroz |
3d806e9c34580c43acc589461acae24f252ae99b | 1,175 | cpp | C++ | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Reflection
// Name: AssemblyVersionAttribute
// C++ Typed Name: mscorlib::System::Reflection::AssemblyVersionAttribute
#include <gtest/gtest.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Reflection
{
//Constructors Tests
//AssemblyVersionAttribute(mscorlib::System::String version)
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,Constructor_1)
{
}
//Public Methods Tests
//Public Properties Tests
// Property Version
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_Version_Test)
{
}
// Property TypeId
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_TypeId_Test)
{
}
}
}
}
| 20.614035 | 91 | 0.728511 | brunolauze |
3d8472edd22f2fd255f7b698bea9a011461a382b | 31,155 | cpp | C++ | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | AppliedAutonomyOffenburg/AADC_2015_A2O | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2018-09-09T21:39:29.000Z | 2018-09-09T21:39:29.000Z | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | null | null | null | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2016-04-05T06:34:08.000Z | 2016-04-05T06:34:08.000Z | /**
Copyright (c)
Audi Autonomous Driving Cup. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.
4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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.
**********************************************************************
* $Author:: spiesra $ $Date:: 2015-05-13 08:29:07#$ $Rev:: 35003 $
**********************************************************************/
#include "stdafx.h"
#include "coder_description.h"
#include "cJuryModule.h"
#include "QFileDialog"
#include "QMessageBox"
#include "QDomDocument"
#include "QTimer"
cJuryConnectionThread::cJuryConnectionThread() : m_pJuryModule(NULL)
{
}
void cJuryConnectionThread::run()
{
if (m_pJuryModule)
{
// if jury module is set, call the connect/disconnect method
m_pJuryModule->ConnectDisconnectNetworkClients();
}
}
tResult cJuryConnectionThread::RegisterJuryModule(cJuryModule* pJuryModule)
{
m_pJuryModule = pJuryModule;
RETURN_NOERROR;
}
cJuryModule::cJuryModule(QWidget *parent) :
QWidget(parent),
m_i16LastDriverEntryId(-1),
m_pDataRemoteSystemData(NULL),
m_pDataSystemDataSender(NULL),
m_pLocalSystemSender(NULL),
m_pRemoteSystem(NULL),
m_pNetwork(NULL),
m_bConnected(false),
m_oLastReceiveTimestamp(QTime()),
m_pWidget(new Ui::cDisplayWidget),
m_strManeuverList("")
{
// setup the widget
m_pWidget->setupUi(this);
// initialize the Qt connections
Init();
// set the jury module pointer
m_oConnectionThread.RegisterJuryModule(this);
}
void cJuryModule::OnCloseWindows()
{
close();
}
cJuryModule::~cJuryModule()
{
// delete the widget
if (m_pWidget != NULL)
{
delete m_pWidget;
m_pWidget = NULL;
}
// cleanup any network conection
CleanUpNetwork();
}
tResult cJuryModule::Init()
{
// connect the widgets and methods
connect(m_pWidget->m_btnFileSelection, SIGNAL(released()), this, SLOT(OnManeuverListButton()));
connect(m_pWidget->m_btnFileSelectionDescr, SIGNAL(released()), this, SLOT(OnDescriptionFileButton()));
connect(m_pWidget->m_edtManeuverFile, SIGNAL(returnPressed()), this, SLOT(OnManeuverListSelected()));
connect(m_pWidget->m_edtManeuverFile, SIGNAL(editingFinished()), this, SLOT(OnManeuverListSelected()));
connect(m_pWidget->m_btnEmergencyStop, SIGNAL(released()), this, SLOT(OnEmergencyStop()));
connect(m_pWidget->m_btnStart, SIGNAL(released()), this, SLOT(OnStart()));
connect(m_pWidget->m_btnStop, SIGNAL(released()), this, SLOT(OnStop()));
connect(m_pWidget->m_btnRequest, SIGNAL(released()), this, SLOT(OnRequestReady()));
connect(m_pWidget->m_btnConnectDisconnect, SIGNAL(released()), this, SLOT(OnConnectDisconnect()));
connect(m_pWidget->m_btnManeuverlist, SIGNAL(released()), this, SLOT(SendManeuverList()));
connect(this, SIGNAL(SetDriverState(int, int)), this, SLOT(OnDriverState(int, int)));
connect(this, SIGNAL(SetLogText(QString)), this, SLOT(OnAppendText(QString)));
connect(this, SIGNAL(SetConnectionState()), this, SLOT(OnConnectionStateChange()));
connect(this, SIGNAL(SetControlState()), this, SLOT(OnControlState()));
connect(m_pWidget->m_comboSector, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboSectionBoxChanged(int)));
connect(m_pWidget->m_comboManeuver, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboActionBoxChanged(int)));
connect(m_pWidget->m_cbxLocalHost, SIGNAL(stateChanged(int)), this, SLOT(OnLocalhostCheckChanged(int)));
connect(m_pWidget->m_btnOpenTerminal, SIGNAL(released()), this, SLOT(OnOpenTerminalProcess()));
connect(&m_oTerminalProcess, SIGNAL(started()), this, SLOT(OnProcessStarted()));
connect(&m_oTerminalProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(OnProcessFinished(int,QProcess::ExitStatus)));
connect(&m_oTerminalProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnProcessError(QProcess::ProcessError)));
// set the connection and control state
SetConnectionState();
SetControlState();
RETURN_NOERROR;
}
void cJuryModule::OnConnectionStateChange()
{
if(m_pWidget)
{
// control the button text and background
if (m_bConnected)
{
m_pWidget->m_btnConnectDisconnect->setText("disconnect");
m_pWidget->m_btnConnectDisconnect->setStyleSheet("background:green");
}
else
{
m_pWidget->m_btnConnectDisconnect->setText("connect");
m_pWidget->m_btnConnectDisconnect->setStyleSheet("");
}
SetControlState();
}
}
void cJuryModule::OnControlState()
{
// control the emergency button and the maneuver control group
tBool bEnabled = false;
if (m_bConnected && !m_strManeuverList.empty())
{
bEnabled = true;
}
m_pWidget->grpManeuverCtrl->setEnabled(bEnabled);
m_pWidget->m_btnEmergencyStop->setEnabled(m_bConnected);
}
tResult cJuryModule::CleanUpNetwork()
{
// delete the network
m_pLocalSystemSender = NULL;
m_pRemoteSystem = NULL;
m_pDataSystemDataSender = NULL;
m_pDataRemoteSystemData = NULL;
if (m_pNetwork)
{
delete m_pNetwork;
m_pNetwork = NULL;
}
RETURN_NOERROR;
}
tResult cJuryModule::ConnectDisconnectNetworkClients()
{
if (m_pNetwork)
{
// network is present, so we have to disconnect
QString strText = QString("Disconnecting...");
SetLogText(strText);
m_bConnected = false;
SetConnectionState();
m_pNetwork->DestroySystem(m_pLocalSystemSender);
m_pNetwork->DestroySystem(m_pRemoteSystem);
CleanUpNetwork();
strText = QString("Disconnected");
SetLogText(strText);
RETURN_NOERROR;
}
// network is not present, connect
QString strText = QString("Trying to connect to ") + QString(GetIpAdress().c_str()) + QString(" ...");
SetLogText(strText);
// create new network
m_pNetwork = new cNetwork("");
cNetwork::SetLogLevel(cNetwork::eLOG_LVL_ERROR);
//Initialize the network
tResult nRes = m_pNetwork->Init();
if (ERR_NOERROR != nRes) //Never forget the error check
{
CleanUpNetwork();
return nRes;
}
const tInt nFlags = 0;
tString strIp = GetIpAdress();
//Create one local system which is part of the network
//this is to send data to the world !!
const tString strDataSendUrl("tcp://" + strIp + ":5000");
m_pLocalSystemSender = NULL; //Gets assigned while created
const tString strLocalSystemNameData("JuryModuleData"); //Name of the first system
nRes = m_pNetwork->CreateLocalSystem(&m_pLocalSystemSender,
strLocalSystemNameData,
strDataSendUrl,
nFlags);//if not given, default = 0
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//the system can also have some data available
nRes = m_pLocalSystemSender->GetDataServer(&m_pDataSystemDataSender);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
// check if there is a description file set, otherwise use the coded description
QString strDescriptionFile = m_pWidget->m_edtDescriptionFile->text();
tString strMyDDLDefinitionAsString;
if (!QFile::exists(strDescriptionFile))
{
SetLogText("No valid media description file set. Will use the internal description.");
strMyDDLDefinitionAsString = CONNLIB_JURY_MODULE_DDL_AS_STRING;
}
else
{
SetLogText(QString("Using media description file ") + strDescriptionFile);
strMyDDLDefinitionAsString = strDescriptionFile.toStdString();
}
nRes = m_pDataSystemDataSender->AddDDL(strMyDDLDefinitionAsString);
if (ERR_NOERROR != nRes)
{
SetLogText("Media description not valid. Please set a valid file.");
CleanUpNetwork();
return nRes;
}
// define the description of outgoing data
tDataDesc sDescEmergencyStopRaw;
sDescEmergencyStopRaw.strName = CONLIB_OUT_PORT_NAME_EMERGENCY_STOP;
sDescEmergencyStopRaw.strDescriptionComment = "The emergency stop struct in raw mode";
sDescEmergencyStopRaw.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_EMERGENCY_STOP, sDescEmergencyStopRaw);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
tDataDesc sDescJuryStruct;
sDescJuryStruct.strName = CONLIB_OUT_PORT_NAME_JURY_STRUCT;
sDescJuryStruct.strDescriptionComment = "the jury data as struct";
sDescJuryStruct.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_JURY_STRUCT, sDescJuryStruct);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
tDataDesc sDescManeuverList;
sDescManeuverList.strName = CONLIB_OUT_PORT_NAME_MANEUVER_LIST;
sDescManeuverList.strDescriptionComment = "the Manuverlist as string";
sDescManeuverList.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_MANEUVER_LIST, sDescManeuverList);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//this is to receive data from a specific sender!!
//Create one local system which is part of the network
const tString strDataUrl("tcp://" + strIp + ":5000");
m_pRemoteSystem = NULL; //Gets assigned while created
const tString strSystemNameData("ADTFData"); //Name of the first system
nRes = m_pNetwork->CreateRemoteSystem(&m_pRemoteSystem,
strSystemNameData,
strDataUrl,
nFlags);//if not given, default = 0
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
nRes = m_pRemoteSystem->GetDataServer(&m_pDataRemoteSystemData);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//this is only required if you subscribe to raw data, otherwise the DDL will be transmitted by the sender.
m_pDataRemoteSystemData->AddDDL(strMyDDLDefinitionAsString);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_DRIVER_STRUCT, CONLIB_STREAM_NAME_DRIVER_STRUCT, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK, CONLIB_STREAM_NAME_JURY_STRUCT, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK, CONLIB_STREAM_NAME_EMERGENCY_STOP, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_MANEUVER_LIST, CONLIB_STREAM_NAME_MANEUVER_LIST, this);
// set the connection state in ui
strText = QString("Connected to ") + QString(GetIpAdress().c_str());
SetLogText(strText);
m_bConnected = true;
SetConnectionState();
RETURN_NOERROR;
}
void cJuryModule::OnManeuverListButton()
{
// open file dialog to get the maneuver list file
QString strManeuverFile = QFileDialog::getOpenFileName(this, tr("Open Maneuver List"), m_strManeuverFile, tr("AADC Maneuver List (*.xml)"));
if(!strManeuverFile.isEmpty())
{
m_pWidget->m_edtManeuverFile->setText(strManeuverFile);
emit OnManeuverListSelected();
}
}
void cJuryModule::OnDescriptionFileButton()
{
// open a file dialog to get the description file
QString strDescriptionFile = QFileDialog::getOpenFileName(this, tr("Open media description file"), "", tr("ADTF media description file (*.description)"));
if(!strDescriptionFile.isEmpty())
{
m_pWidget->m_edtDescriptionFile->setText(strDescriptionFile);
}
}
tResult cJuryModule::OnOpenTerminalProcess()
{
// start the given terminal process (detached because otherwise no terminal window will be opened
if(m_oTerminalProcess.startDetached(m_pWidget->m_edtTerminalProgram->text() ))
{
OnProcessStarted();
}
else
{
OnProcessError(m_oTerminalProcess.error());
}
RETURN_NOERROR;
}
void cJuryModule::OnProcessStarted()
{
// set text in log
SetLogText("Terminal program started");
}
void cJuryModule::OnProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
// set text in log
SetLogText(QString("Process finished with ") + QString::number(exitCode) + QString("and state ") + QString(exitStatus));
}
void cJuryModule::OnProcessError(QProcess::ProcessError error)
{
// set text in log
SetLogText(QString("Process failed with error code ") + QString::number(error) + QString(": ") + m_oTerminalProcess.errorString());
}
void cJuryModule::OnManeuverListSelected()
{
// get the maneuver file from edit field
QString strManeuverFile = m_pWidget->m_edtManeuverFile->text();
if (!strManeuverFile.isEmpty())
{
// check if file exists
if (QFile::exists(strManeuverFile) && strManeuverFile.contains(".xml"))
{
// load the file
m_strManeuverFile = strManeuverFile;
LoadManeuverList();
}
else
{
// file not found, show message box
QMessageBox::critical(this, tr("File not found or valid"), tr("The given Maneuver List can not be found or is not valid."));
m_pWidget->m_edtManeuverFile->setFocus();
}
}
else
{
// do nothing
}
}
tResult cJuryModule::OnDataUpdate(const tString& strName, const tVoid* pData, const tSize& szSize)
{
// called from the connection lib on new data
// check data size
RETURN_IF_POINTER_NULL(pData);
if (szSize <= 0)
{
RETURN_ERROR(ERR_INVALID_ARG);
}
// check the name of the data
if (strName == CONLIB_IN_PORT_NAME_DRIVER_STRUCT)
{
// data from driver
const tDriverStruct* sDriverData = (const tDriverStruct*) pData;
//update the gui
emit SetDriverState(sDriverData->i8StateID, sDriverData->i16ManeuverEntry);
//update the timeline
if (m_i16LastDriverEntryId < sDriverData->i16ManeuverEntry || m_i16LastDriverEntryId == -1 || sDriverData->i8StateID == -1 || sDriverData->i8StateID == 2)
{
// set the first time manually
if (m_oLastReceiveTimestamp.isNull())
{
m_oLastReceiveTimestamp = QTime::currentTime();
m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
}
// calc the time diff
tTimeStamp timeDiff = (m_oLastReceiveTimestamp.msecsTo(QTime::currentTime())); //time in milliseconds
QString Message;
switch (stateCar(sDriverData->i8StateID))
{
case stateCar_READY:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Ready";
break;
case stateCar_RUNNING:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: OK";
break;
case stateCar_COMPLETE:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Complete";
break;
case stateCar_ERROR:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Error";
break;
case stateCar_STARTUP:
break;
}
// set the last time
m_oLastReceiveTimestamp = QTime::currentTime();
m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
//update the ui
SetLogText(Message);
}
}
else if (strName == CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK)
{
// data from jury loopback
const tJuryStruct* sJuryLoopbackData = (const tJuryStruct*) pData;
QString strText = QString("Loopback Jury: Received jury struct loopback with action ");
switch(juryActions(sJuryLoopbackData->i8ActionID))
{
case action_GETREADY:
strText += "GETREADY ";
break;
case action_START:
strText += "START ";
break;
case action_STOP:
strText += "STOP ";
break;
default:
strText += "UNKNOWN ";
break;
}
strText += QString(" and maneuver ") + QString::number(sJuryLoopbackData->i16ManeuverEntry);
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
else if (strName == CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK)
{
// data from emergency loopback
const tJuryEmergencyStop* sJuryLoopbackData = (const tJuryEmergencyStop*) pData;
QString strText = QString("Loopback Emergency: Received emergency loopback with ");
strText += (sJuryLoopbackData->bEmergencyStop == true) ? QString("true") : QString("false");
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
else if (strName == CONLIB_IN_PORT_NAME_MANEUVER_LIST)
{
// data from maneuverlist loopback
const tInt32* i32DataSize = (const tInt32*) pData;
const tChar* pcString = (const tChar*) ((tChar*)pData + sizeof(tInt32));
tString strManeuver(pcString);
QString strText = QString("Loopback ManeuverList received");
// check the data content
if(*i32DataSize != (m_strManeuverList.size() + sizeof(char)))
{
strText += QString(" size does not match");
}
if(strManeuver != m_strManeuverList)
{
strText += QString(" content does not match");
}
strText += "!!!";
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
RETURN_NOERROR;
}
tResult cJuryModule::OnPlainDataDescriptionUpdate(const tChar* strDataName, const tChar* strStructName, const tChar* strDDL)
{
// will be called, if we are using NON-RAW-Mode
// write text to log (just for checking the connection)
SetLogText(QString("Received description update for ") + QString(strDataName));
RETURN_NOERROR;
}
tResult cJuryModule::OnEmergencyStop()
{
// emergency stop button pressed
// send emergency stop 3 times
m_nEmergencyCounter = 3;
QTimer::singleShot(0, this, SLOT(SendEmergencyStop()));
RETURN_NOERROR;
}
tResult cJuryModule::OnRequestReady()
{
// request button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_GETREADY;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnStop()
{
// stop button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_STOP;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnStart()
{
// start button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_START;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnLocalhostCheckChanged(int nState)
{
// localhost checkbox state changed
bool bEnable = false;
if (nState == 0)
{
bEnable = true;
}
// enable/disable ip settings
m_pWidget->m_spinBoxIP1->setEnabled(bEnable);
m_pWidget->m_spinBoxIP2->setEnabled(bEnable);
m_pWidget->m_spinBoxIP3->setEnabled(bEnable);
m_pWidget->m_spinBoxIP4->setEnabled(bEnable);
RETURN_NOERROR;
}
tResult cJuryModule::LoadManeuverList()
{
// load the maneuver list
// clear old list
m_strManeuverList.clear();
// use QDom for parsing
QDomDocument oDoc("maneuver_list");
QFile oFile(m_strManeuverFile);
// open file
if(!oFile.open(QIODevice::ReadOnly))
{
RETURN_ERROR(ERR_FILE_NOT_FOUND);
}
if (!oDoc.setContent(&oFile))
{
oFile.close();
RETURN_ERROR(ERR_INVALID_FILE);
}
// get the root element
QDomElement oRoot = oDoc.documentElement();
// get all sectors from DOM
QDomNodeList lstSectors = oRoot.elementsByTagName("AADC-Sector");
// iterate over all sectors
for (int nIdxSectors = 0; nIdxSectors < lstSectors.size(); ++nIdxSectors)
{
// get the ids and maneuver from sector
QDomNode oNodeSector = lstSectors.item(nIdxSectors);
QDomElement oElementSector = oNodeSector.toElement();
QString strIdSector = oElementSector.attribute("id");
tSector sSector;
sSector.id = strIdSector.toInt();
QDomNodeList lstManeuver = oElementSector.elementsByTagName("AADC-Maneuver");
// iterate over all maneuver
for (int nIdxManeuver = 0; nIdxManeuver < lstManeuver.size(); ++nIdxManeuver)
{
// get the id and the action
QDomNode oNodeManeuver = lstManeuver.item(nIdxManeuver);
QDomElement oElementManeuver = oNodeManeuver.toElement();
QString strIdManeuver = oElementManeuver.attribute("id");
tAADC_Maneuver sManeuver;
sManeuver.nId = strIdManeuver.toInt();
sManeuver.action = oElementManeuver.attribute("action").toStdString();
// fill the internal maneuver list
sSector.lstManeuvers.push_back(sManeuver);
}
// fill the internal sector list
m_lstSections.push_back(sSector);
}
// check sector list
if (m_lstSections.size() > 0)
{
SetLogText("Jury Module: Loaded Maneuver file successfully.");
}
else
{
SetLogText("Jury Module: no valid Maneuver Data found!");
}
// fill the combo boxes
FillComboBoxes();
// get the xml string for transmission
m_strManeuverList = oDoc.toString().toStdString();
// set the controls (enable/disable)
SetControlState();
RETURN_NOERROR;
}
tResult cJuryModule::SendEmergencyStop()
{
// the signal was transmitted as long as emergency counter is set
if(m_nEmergencyCounter > 0)
{
tJuryEmergencyStop sEmergencyStop;
sEmergencyStop.bEmergencyStop = true;
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_EMERGENCY_STOP, &sEmergencyStop, sizeof(sEmergencyStop));
--m_nEmergencyCounter;
QTimer::singleShot(1000, this, SLOT(SendEmergencyStop()));
}
RETURN_NOERROR;
}
tResult cJuryModule::SendJuryStruct()
{
// the signal was transmitted as long as jury struct counter is set
if (m_iJuryStructCounter > 0)
{
tJuryStruct sJury;
sJury.i8ActionID = m_actionID;
sJury.i16ManeuverEntry = m_i16ManeuverEntry;
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_JURY_STRUCT, &sJury, sizeof(sJury));
--m_iJuryStructCounter;
QTimer::singleShot(1000, this, SLOT(SendJuryStruct()));
}
RETURN_NOERROR;
}
tResult cJuryModule::SendManeuverList()
{
// only if maneuver file is set it will be transmitted
if (!m_strManeuverList.empty())
{
// hack to transmit data with dynamic size
tInt32 i32StringSize = (tInt32) (m_strManeuverList.size() + sizeof(tChar)); // plus one more char for terminating /0
tSize szBufferSize = i32StringSize * sizeof(char) + sizeof(i32StringSize); // buffer size is string size plus also transmitted size-value
// create a buffer
tUInt8 *pui8Buffer = new tUInt8[szBufferSize];
tInt32* pi32SizeInBuffer = (tInt32*) pui8Buffer;
// set the string size (needed for serialization/deserialization)
*pi32SizeInBuffer = i32StringSize;
// copy the maneuverlist string into the buffer
memcpy(pui8Buffer + sizeof(i32StringSize), m_strManeuverList.c_str(), i32StringSize * sizeof(char));
// transmit the data buffer
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_MANEUVER_LIST, pui8Buffer, szBufferSize);
// cleanup
delete [] pui8Buffer;
//QTimer::singleShot(1000, this, SLOT(SendManeuverList()));
}
RETURN_NOERROR;
}
void cJuryModule::OnDriverState(int state, int entryId)
{
// set the driver state
SetDriverManeuverID(entryId);
switch (stateCar(state))
{
case stateCar_ERROR:
SetDriverStateError();
break;
case stateCar_READY:
SetDriverStateReady();
break;
case stateCar_RUNNING:
SetDriverStateRun();
break;
case stateCar_COMPLETE:
SetDriverStateComplete();
break;
case stateCar_STARTUP:
break;
}
}
void cJuryModule::OnAppendText(QString text)
{
// append the given text to the log field
if(m_pWidget)
{
m_pWidget->m_edtLogField->append(text);
}
}
void cJuryModule::OnComboActionBoxChanged(int index)
{
// search for the right section entry
for(unsigned int nIdxSection = 0; nIdxSection < m_lstSections.size(); nIdxSection++)
{
for(unsigned int nIdxManeuver = 0; nIdxManeuver < m_lstSections[nIdxSection].lstManeuvers.size(); nIdxManeuver++)
{
if(index == m_lstSections[nIdxSection].lstManeuvers[nIdxManeuver].nId)
{
m_pWidget->m_comboSector->setCurrentIndex(nIdxSection);
break;
}
}
}
}
void cJuryModule::OnComboSectionBoxChanged(int index)
{
//get the action id from selected section and write it to action combo box
m_pWidget->m_comboManeuver->setCurrentIndex(m_lstSections[index].lstManeuvers[0].nId);
}
void cJuryModule::SetDriverStateError()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,0,0);");
m_pWidget->m_lblState->setText("Error");
}
void cJuryModule::SetDriverStateRun()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,255,0);");
m_pWidget->m_lblState->setText("Running");
}
void cJuryModule::SetDriverStateReady()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,255,0);");
m_pWidget->m_lblState->setText("Ready");
}
void cJuryModule::SetDriverStateComplete()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,0,255);");
m_pWidget->m_lblState->setText("Complete");
}
tString cJuryModule::GetIpAdress()
{
// get the ip adress from the spinners or if localhost checkbox is checked use "localhost"
if (m_pWidget->m_cbxLocalHost->isChecked())
{
m_strIPAdress = "localhost";
}
else
{
QString strIp1 = m_pWidget->m_spinBoxIP1->text();
QString strIp2 = m_pWidget->m_spinBoxIP2->text();
QString strIp3 = m_pWidget->m_spinBoxIP3->text();
QString strIp4 = m_pWidget->m_spinBoxIP4->text();
m_strIPAdress = strIp1.toStdString() + "." + strIp2.toStdString() + "." + strIp3.toStdString() + "." + strIp4.toStdString();
}
return m_strIPAdress;
}
void cJuryModule::OnConnectDisconnect()
{
// connect / disconnect button pressed
// check for already running connection thread
if (!m_oConnectionThread.isRunning())
{
m_oConnectionThread.start();
}
// the timer will use the main thread which freezes the UI while connecting
//QTimer::singleShot(0, this, SLOT(ConnectDisconnectNetworkClients()));
}
void cJuryModule::SetDriverManeuverID(tInt16 id)
{
// set the id from received driver struct
m_pWidget->m_lblDriverManeuverID->setText(QString::number(id));
}
void cJuryModule::FillComboBoxes()
{
int nLastManeuverId = 0;
int nLastSectionId = 0;
// vector of maneuver names to fill the combobox also with names
std::vector<std::string> lstManeuverNames;
// find the last maneuver and section id
for(unsigned int i = 0; i < m_lstSections.size(); i++)
{
nLastSectionId++;
for(unsigned int j = 0; j < m_lstSections[i].lstManeuvers.size(); j++)
{
nLastManeuverId++;
lstManeuverNames.push_back(m_lstSections[i].lstManeuvers[j].action);
}
}
// clear the old entries
m_pWidget->m_comboManeuver->clear();
m_pWidget->m_comboSector->clear();
// fill the combo boxes
for(int i = 0; i < nLastManeuverId; i++)
{
m_pWidget->m_comboManeuver->addItem(QString::number(i) + QString(" - ") + QString(lstManeuverNames[i].c_str()));
}
for(int i = 0; i < nLastSectionId; i++)
{
m_pWidget->m_comboSector->addItem(QString::number(i));
}
}
| 33.717532 | 728 | 0.670647 | AppliedAutonomyOffenburg |
3d967d74a56a02f98bf1629c747b63e56e076687 | 25,002 | cpp | C++ | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 15 | 2017-11-01T16:11:46.000Z | 2020-08-18T14:20:12.000Z | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 11 | 2020-02-16T12:45:33.000Z | 2022-02-10T07:20:47.000Z | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 7 | 2017-11-01T18:32:31.000Z | 2021-01-11T17:55:59.000Z | #include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "io.h"
// Note that stat() is very slow. We've replaced the call to stat() with
// a call to open().
bool FileExists(const char *filename) {
int fd = open(filename, O_RDONLY, 0);
if (fd == -1) {
if (errno == ENOENT) {
// I believe this is what happens when there is no such file
return false;
}
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
} else {
close(fd);
return true;
}
#if 0
struct stat stbuf;
int ret = stat(filename, &stbuf);
if (ret == -1) {
return false;
} else {
return true;
}
#endif
}
long long int FileSize(const char *filename) {
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
fprintf(stderr, "FileSize: Couldn't access: %s\n", filename);
exit(-1);
}
return stbuf.st_size;
}
void Reader::OpenFile(const char *filename) {
filename_ = filename;
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
fprintf(stderr, "Reader::OpenFile: Couldn't access: %s\n", filename);
exit(-1);
}
file_size_ = stbuf.st_size;
remaining_ = file_size_;
fd_ = open(filename, O_RDONLY, 0);
if (fd_ == -1) {
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
}
overflow_size_ = 0;
byte_pos_ = 0;
}
Reader::Reader(const char *filename) {
OpenFile(filename);
buf_size_ = kBufSize;
if (remaining_ < buf_size_) buf_size_ = remaining_;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_read_ = buf_.get();
if (! Refresh()) {
fprintf(stderr, "Warning: empty file: %s\n", filename);
}
}
// This constructor for use by NewReaderMaybe(). Doesn't call stat().
// I should clean up this code to avoid redundancy.
Reader::Reader(const char *filename, long long int file_size) {
filename_ = filename;
file_size_ = file_size;
remaining_ = file_size;
fd_ = open(filename, O_RDONLY, 0);
if (fd_ == -1) {
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
}
overflow_size_ = 0;
byte_pos_ = 0;
buf_size_ = kBufSize;
if (remaining_ < buf_size_) buf_size_ = remaining_;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_read_ = buf_.get();
if (! Refresh()) {
fprintf(stderr, "Warning: empty file: %s\n", filename);
}
}
// Returns NULL if no file by this name exists
Reader *NewReaderMaybe(const char *filename) {
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
return NULL;
}
long long int file_size = stbuf.st_size;
return new Reader(filename, file_size);
}
Reader::~Reader(void) {
close(fd_);
}
bool Reader::AtEnd(void) const {
// This doesn't work for CompressedReader
// return byte_pos_ == file_size_;
return (buf_ptr_ == end_read_ && remaining_ == 0 && overflow_size_ == 0);
}
void Reader::SeekTo(long long int offset) {
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
remaining_ = file_size_ - offset;
overflow_size_ = 0;
byte_pos_ = offset;
Refresh();
}
bool Reader::Refresh(void) {
if (remaining_ == 0 && overflow_size_ == 0) return false;
if (overflow_size_ > 0) {
memcpy(buf_.get(), overflow_, overflow_size_);
}
buf_ptr_ = buf_.get();
unsigned char *read_into = buf_.get() + overflow_size_;
int to_read = buf_size_ - overflow_size_;
if (to_read > remaining_) to_read = remaining_;
int ret;
if ((ret = read(fd_, read_into, to_read)) != to_read) {
fprintf(stderr, "Read returned %i not %i\n", ret, to_read);
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "remaining_ %lli\n", remaining_);
exit(-1);
}
remaining_ -= to_read;
end_read_ = read_into + to_read;
overflow_size_ = 0;
return true;
}
bool Reader::GetLine(string *s) {
s->clear();
while (true) {
if (buf_ptr_ == end_read_) {
if (! Refresh()) {
return false;
}
}
if (*buf_ptr_ == '\r') {
++buf_ptr_;
++byte_pos_;
continue;
}
if (*buf_ptr_ == '\n') {
++buf_ptr_;
++byte_pos_;
break;
}
s->push_back(*buf_ptr_);
++buf_ptr_;
++byte_pos_;
}
return true;
}
bool Reader::ReadInt(int *i) {
if (buf_ptr_ + sizeof(int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
char my_buf[4];
my_buf[0] = *buf_ptr_++;
my_buf[1] = *buf_ptr_++;
my_buf[2] = *buf_ptr_++;
my_buf[3] = *buf_ptr_++;
byte_pos_ += 4;
int *int_ptr = reinterpret_cast<int *>(my_buf);
*i = *int_ptr;
return true;
}
int Reader::ReadIntOrDie(void) {
int i;
if (! ReadInt(&i)) {
fprintf(stderr, "Couldn't read int; file %s byte pos %lli\n",
filename_.c_str(), byte_pos_);
exit(-1);
}
return i;
}
bool Reader::ReadUnsignedInt(unsigned int *u) {
if (buf_ptr_ + sizeof(int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
char my_buf[4];
my_buf[0] = *buf_ptr_++;
my_buf[1] = *buf_ptr_++;
my_buf[2] = *buf_ptr_++;
my_buf[3] = *buf_ptr_++;
byte_pos_ += 4;
unsigned int *u_int_ptr = reinterpret_cast<unsigned int *>(my_buf);
*u = *u_int_ptr;
return true;
}
unsigned int Reader::ReadUnsignedIntOrDie(void) {
unsigned int u;
if (! ReadUnsignedInt(&u)) {
fprintf(stderr, "Couldn't read unsigned int\n");
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "Byte pos: %lli\n", byte_pos_);
exit(-1);
}
return u;
}
bool Reader::ReadLong(long long int *l) {
if (buf_ptr_ + sizeof(long long int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*l = *(long long int *)buf_ptr_;
buf_ptr_ += sizeof(long long int);
byte_pos_ += sizeof(long long int);
return true;
}
long long int Reader::ReadLongOrDie(void) {
long long int l;
if (! ReadLong(&l)) {
fprintf(stderr, "Couldn't read long\n");
exit(-1);
}
return l;
}
bool Reader::ReadUnsignedLong(unsigned long long int *u) {
if (buf_ptr_ + sizeof(unsigned long long int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned long long int *)buf_ptr_;
buf_ptr_ += sizeof(unsigned long long int);
byte_pos_ += sizeof(unsigned long long int);
return true;
}
unsigned long long int Reader::ReadUnsignedLongOrDie(void) {
unsigned long long int u;
if (! ReadUnsignedLong(&u)) {
fprintf(stderr, "Couldn't read unsigned long\n");
exit(-1);
}
return u;
}
bool Reader::ReadShort(short *s) {
if (buf_ptr_ + sizeof(short) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
// Possible alignment issue?
*s = *(short *)buf_ptr_;
buf_ptr_ += sizeof(short);
byte_pos_ += sizeof(short);
return true;
}
short Reader::ReadShortOrDie(void) {
short s;
if (! ReadShort(&s)) {
fprintf(stderr, "Couldn't read short\n");
exit(-1);
}
return s;
}
bool Reader::ReadUnsignedShort(unsigned short *u) {
if (buf_ptr_ + sizeof(unsigned short) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned short *)buf_ptr_;
buf_ptr_ += sizeof(unsigned short);
byte_pos_ += sizeof(unsigned short);
return true;
}
unsigned short Reader::ReadUnsignedShortOrDie(void) {
unsigned short s;
if (! ReadUnsignedShort(&s)) {
fprintf(stderr, "Couldn't read unsigned short; file %s byte pos %lli "
"file_size %lli\n", filename_.c_str(), byte_pos_, file_size_);
exit(-1);
}
return s;
}
bool Reader::ReadChar(char *c) {
if (buf_ptr_ + sizeof(char) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*c = *(char *)buf_ptr_;
buf_ptr_ += sizeof(char);
byte_pos_ += sizeof(char);
return true;
}
char Reader::ReadCharOrDie(void) {
char c;
if (! ReadChar(&c)) {
fprintf(stderr, "Couldn't read char\n");
exit(-1);
}
return c;
}
bool Reader::ReadUnsignedChar(unsigned char *u) {
if (buf_ptr_ + sizeof(unsigned char) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned char *)buf_ptr_;
buf_ptr_ += sizeof(unsigned char);
byte_pos_ += sizeof(unsigned char);
return true;
}
unsigned char Reader::ReadUnsignedCharOrDie(void) {
unsigned char u;
if (! ReadUnsignedChar(&u)) {
fprintf(stderr, "Couldn't read unsigned char\n");
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "Byte pos: %lli\n", byte_pos_);
exit(-1);
}
return u;
}
void Reader::ReadOrDie(unsigned char *c) {
*c = ReadUnsignedCharOrDie();
}
void Reader::ReadOrDie(unsigned short *s) {
*s = ReadUnsignedShortOrDie();
}
void Reader::ReadOrDie(unsigned int *u) {
*u = ReadUnsignedIntOrDie();
}
void Reader::ReadOrDie(int *i) {
*i = ReadIntOrDie();
}
void Reader::ReadOrDie(double *d) {
*d = ReadDoubleOrDie();
}
void Reader::ReadNBytesOrDie(unsigned int num_bytes, unsigned char *buf) {
for (unsigned int i = 0; i < num_bytes; ++i) {
if (buf_ptr_ + 1 > end_read_) {
if (! Refresh()) {
fprintf(stderr, "Couldn't read %i bytes\n", num_bytes);
fprintf(stderr, "Filename: %s\n", filename_.c_str());
fprintf(stderr, "File size: %lli\n", file_size_);
fprintf(stderr, "Before read byte pos: %lli\n", byte_pos_);
fprintf(stderr, "Overflow size: %i\n", overflow_size_);
fprintf(stderr, "i %i\n", i);
exit(-1);
}
}
buf[i] = *buf_ptr_++;
++byte_pos_;
}
}
void Reader::ReadEverythingLeft(unsigned char *data) {
unsigned long long int data_pos = 0ULL;
unsigned long long int left = file_size_ - byte_pos_;
while (left > 0) {
unsigned long long int num_bytes = end_read_ - buf_ptr_;
memcpy(data + data_pos, buf_ptr_, num_bytes);
buf_ptr_ = end_read_;
data_pos += num_bytes;
if (data_pos > left) {
fprintf(stderr, "ReadEverythingLeft: read too much?!?\n");
exit(-1);
} else if (data_pos == left) {
break;
}
if (! Refresh()) {
fprintf(stderr, "ReadEverythingLeft: premature EOF?!?\n");
exit(-1);
}
}
}
bool Reader::ReadCString(string *s) {
*s = "";
while (true) {
if (buf_ptr_ + 1 > end_read_) {
if (! Refresh()) {
return false;
}
}
char c = *buf_ptr_++;
++byte_pos_;
if (c == 0) return true;
*s += c;
}
}
string Reader::ReadCStringOrDie(void) {
string s;
if (! ReadCString(&s)) {
fprintf(stderr, "Couldn't read string\n");
exit(-1);
}
return s;
}
bool Reader::ReadDouble(double *d) {
if (buf_ptr_ + sizeof(double) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*d = *(double *)buf_ptr_;
buf_ptr_ += sizeof(double);
byte_pos_ += sizeof(double);
return true;
}
double Reader::ReadDoubleOrDie(void) {
double d;
if (! ReadDouble(&d)) {
fprintf(stderr, "Couldn't read double: file %s byte pos %lli\n",
filename_.c_str(), byte_pos_);
exit(-1);
}
return d;
}
bool Reader::ReadFloat(float *f) {
if (buf_ptr_ + sizeof(float) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*f = *(float *)buf_ptr_;
buf_ptr_ += sizeof(float);
byte_pos_ += sizeof(float);
return true;
}
float Reader::ReadFloatOrDie(void) {
float f;
if (! ReadFloat(&f)) {
fprintf(stderr, "Couldn't read float: file %s\n", filename_.c_str());
exit(-1);
}
return f;
}
// Identical to ReadDouble()
bool Reader::ReadReal(double *d) {
if (buf_ptr_ + sizeof(double) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*d = *(double *)buf_ptr_;
buf_ptr_ += sizeof(double);
byte_pos_ += sizeof(double);
return true;
}
// Identical to ReadFloat()
bool Reader::ReadReal(float *f) {
if (buf_ptr_ + sizeof(float) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*f = *(float *)buf_ptr_;
buf_ptr_ += sizeof(float);
byte_pos_ += sizeof(float);
return true;
}
void Writer::Init(const char *filename, bool modify, int buf_size) {
filename_ = filename;
if (modify) {
fd_ = open(filename, O_WRONLY, 0666);
if (fd_ < 0 && errno == ENOENT) {
// If file doesn't exist, open it with creat()
fd_ = creat(filename, 0666);
}
} else {
// creat() is supposedly equivalent to passing
// O_WRONLY|O_CREAT|O_TRUNC to open().
fd_ = creat(filename, 0666);
}
if (fd_ < 0) {
// Is this how errors are indicated?
fprintf(stderr, "Couldn't open %s for writing (errno %i)\n", filename,
errno);
exit(-1);
}
buf_size_ = buf_size;
buf_.reset(new unsigned char[buf_size_]);
end_buf_ = buf_.get() + buf_size_;
buf_ptr_ = buf_.get();
}
Writer::Writer(const char *filename, int buf_size) {
Init(filename, false, buf_size);
}
Writer::Writer(const char *filename, bool modify) {
Init(filename, modify, kBufSize);
}
Writer::Writer(const char *filename) {
Init(filename, false, kBufSize);
}
Writer::~Writer(void) {
Flush();
close(fd_);
}
// Generally write() writes everything in one call. Haven't seen any cases
// that justify the loop I do below. Could take it out.
void Writer::Flush(void) {
if (buf_ptr_ > buf_.get()) {
int left_to_write = (int)(buf_ptr_ - buf_.get());
while (left_to_write > 0) {
int written = write(fd_, buf_.get(), left_to_write);
if (written < 0) {
fprintf(stderr,
"Error in flush: tried to write %i, return of %i; errno %i; "
"fd %i\n", left_to_write, written, errno, fd_);
exit(-1);
} else if (written == 0) {
// Stall for a bit to avoid busy loop
sleep(1);
}
left_to_write -= written;
}
}
buf_ptr_ = buf_.get();
}
// Only makes sense to call if we created the Writer with modify=true
void Writer::SeekTo(long long int offset) {
Flush();
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
}
long long int Writer::Tell(void) {
Flush();
return lseek(fd_, 0LL, SEEK_CUR);
}
void Writer::WriteInt(int i) {
if (buf_ptr_ + sizeof(int) > end_buf_) {
Flush();
}
// Couldn't we have an alignment issue if we write a char and then an int,
// for example?
// *(int *)buf_ptr_ = i;
memcpy(buf_ptr_, (void *)&i, sizeof(int));
buf_ptr_ += sizeof(int);
}
void Writer::WriteUnsignedInt(unsigned int u) {
if (buf_ptr_ + sizeof(unsigned int) > end_buf_) {
Flush();
}
*(unsigned int *)buf_ptr_ = u;
buf_ptr_ += sizeof(unsigned int);
}
void Writer::WriteLong(long long int l) {
if (buf_ptr_ + sizeof(long long int) > end_buf_) {
Flush();
}
*(long long int *)buf_ptr_ = l;
buf_ptr_ += sizeof(long long int);
}
void Writer::WriteUnsignedLong(unsigned long long int u) {
if (buf_ptr_ + sizeof(unsigned long long int) > end_buf_) {
Flush();
}
*(unsigned long long int *)buf_ptr_ = u;
buf_ptr_ += sizeof(unsigned long long int);
}
void Writer::WriteShort(short s) {
if (buf_ptr_ + sizeof(short) > end_buf_) {
Flush();
}
*(short *)buf_ptr_ = s;
buf_ptr_ += sizeof(short);
}
void Writer::WriteChar(char c) {
if (buf_ptr_ + sizeof(char) > end_buf_) {
Flush();
}
*(char *)buf_ptr_ = c;
buf_ptr_ += sizeof(char);
}
void Writer::WriteUnsignedChar(unsigned char c) {
if (buf_ptr_ + sizeof(unsigned char) > end_buf_) {
Flush();
}
*(unsigned char *)buf_ptr_ = c;
buf_ptr_ += sizeof(unsigned char);
}
void Writer::WriteUnsignedShort(unsigned short s) {
if (buf_ptr_ + sizeof(unsigned short) > end_buf_) {
Flush();
}
*(unsigned short *)buf_ptr_ = s;
buf_ptr_ += sizeof(unsigned short);
}
void Writer::WriteFloat(float f) {
if (buf_ptr_ + sizeof(float) > end_buf_) {
Flush();
}
*(float *)buf_ptr_ = f;
buf_ptr_ += sizeof(float);
}
void Writer::WriteDouble(double d) {
if (buf_ptr_ + sizeof(double) > end_buf_) {
Flush();
}
*(double *)buf_ptr_ = d;
buf_ptr_ += sizeof(double);
}
// Identical to WriteFloat()
void Writer::WriteReal(float f) {
if (buf_ptr_ + sizeof(float) > end_buf_) {
Flush();
}
*(float *)buf_ptr_ = f;
buf_ptr_ += sizeof(float);
}
// Identical to WriteDouble()
void Writer::WriteReal(double d) {
if (buf_ptr_ + sizeof(double) > end_buf_) {
Flush();
}
*(double *)buf_ptr_ = d;
buf_ptr_ += sizeof(double);
}
void Writer::Write(unsigned char c) {
WriteUnsignedChar(c);
}
void Writer::Write(unsigned short s) {
WriteUnsignedShort(s);
}
void Writer::Write(int i) {
WriteInt(i);
}
void Writer::Write(unsigned int u) {
WriteUnsignedInt(u);
}
void Writer::Write(double d) {
WriteDouble(d);
}
void Writer::WriteCString(const char *s) {
int len = strlen(s);
if (buf_ptr_ + len + 1 > end_buf_) {
Flush();
}
memcpy(buf_ptr_, s, len);
buf_ptr_[len] = 0;
buf_ptr_ += len + 1;
}
// Does not write num_bytes into file
void Writer::WriteNBytes(unsigned char *bytes, unsigned int num_bytes) {
if ((int)num_bytes > buf_size_) {
Flush();
while ((int)num_bytes > buf_size_) {
buf_size_ *= 2;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_buf_ = buf_.get() + buf_size_;
}
}
if (buf_ptr_ + num_bytes > end_buf_) {
Flush();
}
memcpy(buf_ptr_, bytes, num_bytes);
buf_ptr_ += num_bytes;
}
void Writer::WriteBytes(unsigned char *bytes, int num_bytes) {
WriteInt(num_bytes);
if (num_bytes > buf_size_) {
Flush();
while (num_bytes > buf_size_) {
buf_size_ *= 2;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_buf_ = buf_.get() + buf_size_;
}
}
if (buf_ptr_ + num_bytes > end_buf_) {
Flush();
}
memcpy(buf_ptr_, bytes, num_bytes);
buf_ptr_ += num_bytes;
}
void Writer::WriteText(const char *s) {
int len = strlen(s);
if (buf_ptr_ + len + 1 > end_buf_) {
Flush();
}
memcpy(buf_ptr_, s, len);
buf_ptr_ += len;
}
unsigned int Writer::BufPos(void) {
return (unsigned int)(buf_ptr_ - buf_.get());
}
ReadWriter::ReadWriter(const char *filename) {
filename_ = filename;
fd_ = open(filename, O_RDWR, 0666);
if (fd_ < 0 && errno == ENOENT) {
fprintf(stderr, "Can only create a ReadWriter on an existing file\n");
fprintf(stderr, "Filename: %s\n", filename);
exit(-1);
}
}
ReadWriter::~ReadWriter(void) {
close(fd_);
}
void ReadWriter::SeekTo(long long int offset) {
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
}
int ReadWriter::ReadIntOrDie(void) {
int i, ret;
if ((ret = read(fd_, &i, 4)) != 4) {
fprintf(stderr, "ReadWriter::ReadInt returned %i not 4\n", ret);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
return i;
}
void ReadWriter::WriteInt(int i) {
int written = write(fd_, &i, 4);
if (written != 4) {
fprintf(stderr, "Error: tried to write 4 bytes, return of %i; fd %i\n",
written, fd_);
exit(-1);
}
}
bool IsADirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0) return 0;
return S_ISDIR(statbuf.st_mode);
}
// Filenames in listing returned are full paths
void GetDirectoryListing(const char *dir, vector<string> *listing) {
int dirlen = strlen(dir);
bool ends_in_slash = (dir[dirlen - 1] == '/');
listing->clear();
DIR *dfd = opendir(dir);
if (dfd == NULL) {
fprintf(stderr, "GetDirectoryListing: could not open directory %s\n", dir);
exit(-1);
}
dirent *dp;
while ((dp = readdir(dfd))) {
if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, "..")) {
string full_path = dir;
if (! ends_in_slash) {
full_path += "/";
}
full_path += dp->d_name;
listing->push_back(full_path);
}
}
closedir(dfd);
}
static void RecursivelyDelete(const string &path) {
if (! IsADirectory(path.c_str())) {
// fprintf(stderr, "Removing file %s\n", path.c_str());
RemoveFile(path.c_str());
return;
}
vector<string> listing;
GetDirectoryListing(path.c_str(), &listing);
unsigned int num = listing.size();
for (unsigned int i = 0; i < num; ++i) {
RecursivelyDelete(listing[i]);
}
// fprintf(stderr, "Removing dir %s\n", path.c_str());
RemoveFile(path.c_str());
}
void RecursivelyDeleteDirectory(const char *dir) {
if (! IsADirectory(dir)) {
fprintf(stderr, "Path supplied is not a directory: %s\n", dir);
return;
}
vector<string> listing;
GetDirectoryListing(dir, &listing);
unsigned int num = listing.size();
for (unsigned int i = 0; i < num; ++i) {
RecursivelyDelete(listing[i]);
}
// fprintf(stderr, "Removing dir %s\n", dir);
RemoveFile(dir);
}
// Gives read/write/execute permissions to everyone
void Mkdir(const char *dir) {
int ret = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
if (ret != 0) {
if (errno == 17) {
// File or directory by this name already exists. We'll just assume
// it's a directory and return successfully.
return;
}
fprintf(stderr, "mkdir returned %i; errno %i\n", ret, errno);
fprintf(stderr, "Directory: %s\n", dir);
exit(-1);
}
}
// FileExists() calls stat() which is very expensive. Try calling
// remove() without a preceding FileExists() check.
void RemoveFile(const char *filename) {
int ret = remove(filename);
if (ret) {
// ENOENT just signifies that there is no file by the given name
if (errno != ENOENT) {
fprintf(stderr, "Error removing file: %i; errno %i\n", ret, errno);
exit(-1);
}
}
}
// How is this different from RemoveFile()?
void UnlinkFile(const char *filename) {
int ret = unlink(filename);
if (ret) {
// ENOENT just signifies that there is no file by the given name
if (errno != ENOENT) {
fprintf(stderr, "Error unlinking file: %i; errno %i\n", ret, errno);
exit(-1);
}
}
}
void MoveFile(const char *old_location, const char *new_location) {
if (! FileExists(old_location)) {
fprintf(stderr, "MoveFile: old location \"%s\" does not exist\n",
old_location);
exit(-1);
}
if (FileExists(new_location)) {
fprintf(stderr, "MoveFile: new location \"%s\" already exists\n",
new_location);
exit(-1);
}
int ret = rename(old_location, new_location);
if (ret != 0) {
fprintf(stderr, "MoveFile: rename() returned %i\n", ret);
fprintf(stderr, "Old location: %s\n", old_location);
fprintf(stderr, "New location: %s\n", new_location);
exit(-1);
}
}
void CopyFile(const char *old_location, const char *new_location) {
Reader reader(old_location);
Writer writer(new_location);
unsigned char uc;
while (reader.ReadUnsignedChar(&uc)) {
writer.WriteUnsignedChar(uc);
}
}
| 24.297376 | 79 | 0.62191 | ericgjackson |
3d999d5f0d448760b952954f732fe32a95e06901 | 3,021 | hpp | C++ | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeHomeBasePower
struct UResults_PlayerScoreRow_C_InitializeHomeBasePower_Params
{
struct FUniqueNetIdRepl PlayerID; // (Parm)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializePlayerName
struct UResults_PlayerScoreRow_C_InitializePlayerName_Params
{
class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int ScoreReportReferece; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeScores
struct UResults_PlayerScoreRow_C_InitializeScores_Params
{
class UFortUIScoreReport* InScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int InScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeBackground
struct UResults_PlayerScoreRow_C_InitializeBackground_Params
{
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Initialize
struct UResults_PlayerScoreRow_C_Initialize_Params
{
class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int ScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Manual Pre Construct
struct UResults_PlayerScoreRow_C_Manual_Pre_Construct_Params
{
bool bIsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.PreConstruct
struct UResults_PlayerScoreRow_C_PreConstruct_Params
{
bool* IsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.ExecuteUbergraph_Results_PlayerScoreRow
struct UResults_PlayerScoreRow_C_ExecuteUbergraph_Results_PlayerScoreRow_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 41.958333 | 152 | 0.572327 | Milxnor |
3d9a34a2b9f721db162195c2eea5ade04f3d56c0 | 36,728 | hpp | C++ | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | 1 | 2021-06-26T17:08:24.000Z | 2021-06-26T17:08:24.000Z | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null | /*
* Interactive disassembler (IDA).
* Copyright (c) 1990-97 by Ilfak Guilfanov.
* ALL RIGHTS RESERVED.
* E-mail: [email protected]
* FIDO: 2:5020/209
*
*/
#ifndef _LOADER_HPP
#define _LOADER_HPP
#pragma pack(push, 1) // IDA uses 1 byte alignments!
//
// This file contains:
// - definitions of IDP, LDR, PLUGIN module interfaces.
// - functions to load files into the database
// - functions to generate output files
// - high level functions to work with the database (open, save, close)
//
// The LDR interface consists of one structure loader_t
// The IDP interface consists of one structure processor_t (see idp.hpp)
// The PLUGIN interface consists of one structure plugin_t
//
// Modules can't use standard FILE* functions.
// They must use functions from <fpro.h>
//
// Modules can't use standard memory allocation functions.
// They must use functions from <pro.h>
//
// The exported entry #1 in the module should point to the
// the appropriate structure. (loader_t for LDR module, for example)
//
//----------------------------------------------------------------------
// DEFINITION OF LDR MODULES
//----------------------------------------------------------------------
class linput_t; // loader input source. see diskio.hpp for the functions
// Loader description block - must be exported from the loader module
#define MAX_FILE_FORMAT_NAME 64
struct loader_t
{
ulong version; // api version, should be IDP_INTERFACE_VERSION
ulong flags; // loader flags
#define LDRF_RELOAD 0x0001 // loader recognizes NEF_RELOAD flag
//
// check input file format. if recognized, then return 1
// and fill 'fileformatname'.
// otherwise return 0
// This function will be called many times till it returns !=0.
// 'n' parameter will be incremented after each call.
// Initially, n==0 for each loader.
// This function may return a unique file format number instead of 1.
// To get this unique number, please contact the author.
//
// If the return value is ORed with ACCEPT_FIRST, then this format
// should be placed first in the "load file" dialog box
//
#define ACCEPT_FIRST 0x8000
int (idaapi* accept_file)(linput_t *li,
char fileformatname[MAX_FILE_FORMAT_NAME],
int n);
//
// load file into the database.
// fp - pointer to file positioned at the start of the file
// fileformatname - name of type of the file (it was returned
// by the accept_file)
// neflags - user-supplied flags. They determine how to
// load the file.
// in the case of failure loader_failure() should be called
//
void (idaapi* load_file)(linput_t *li,
ushort neflags,
const char *fileformatname);
#define NEF_SEGS 0x0001 // Create segments
#define NEF_RSCS 0x0002 // Load resources
#define NEF_NAME 0x0004 // Rename entries
#define NEF_MAN 0x0008 // Manual load
#define NEF_FILL 0x0010 // Fill segment gaps
#define NEF_IMPS 0x0020 // Create imports section
#define NEF_TIGHT 0x0040 // Don't align segments (OMF)
#define NEF_FIRST 0x0080 // This is the first file loaded
// into the database.
#define NEF_CODE 0x0100 // for load_binary_file:
// load as a code segment
#define NEF_RELOAD 0x0200 // reload the file at the same place:
// don't create segments
// don't create fixup info
// don't import segments
// etc
// load only the bytes into the base.
// a loader should have LDRF_RELOAD
// bit set
#define NEF_FLAT 0x0400 // Autocreate FLAT group (PE)
#define NEF_MINI 0x0800 // Create mini database (do not copy
#define NEF_LOPT 0x1000 // Display additional loader options dialog
//
// create output file from the database.
// this function may be absent.
// if fp == NULL, then this function returns:
// 0 - can't create file of this type
// 1 - ok, can create file of this type
// if fp != NULL, then this function should create the output file
//
int (idaapi* save_file)(FILE *fp, const char *fileformatname);
// take care of a moved segment (fix up relocations, for example)
// this function may be absent.
// from - previous linear address of the segment
// to - current linear address of the segment
// size - size of the moved segment
// fileformatname - the file format
// a special calling method move_segm(BADADDR, delta, 0, formatname)
// means that the whole program has been moved in the memory (rebased) by delta bytes
// returns: 1-ok, 0-failure
int (idaapi* move_segm)(ea_t from,
ea_t to,
asize_t size,
const char *fileformatname);
// initialize user configurable options based on the input file.
// this function may be absent.
// fp - pointer to file positioned at the start of the file
// This function is called as soon as a loader is selected, and allow the loader
// to populate XML variables, select a default processor, ...
// returns: true-ok, false-cancel
bool (idaapi* init_loader_options)(linput_t *li);
};
#ifdef __BORLANDC__
#if sizeof(loader_t) % 4
#error "Size of loader_t is incorrect"
#endif
#endif
extern "C" loader_t LDSC; // (declaration for loaders)
// Display a message about a loader failure and stop the loading process
// The kernel will destroy the database
// If format == NULL, no message will be displayed
// This function does not return (it longjumps)!
// It may be called only from loader_t.load_file()
idaman void ida_export vloader_failure(const char *format, va_list va);
inline void loader_failure(const char *format=NULL, ...)
{
va_list va;
va_start(va, format);
vloader_failure(format, va);
va_end(va);
}
//----------------------------------------------------------------------
// LDR module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define LOADER_EXT "x64"
#else
#define LOADER_EXT "l64"
#endif
#else
#define LOADER_EXT "ldw"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define LOADER_EXT "llx64"
#else
#define LOADER_EXT "llx"
#endif
#endif
#ifdef __EA64__
#define LOADER_DLL "*64." LOADER_EXT
#else
#define LOADER_DLL "*." LOADER_EXT
#endif
//----------------------------------------------------------------------
// Functions for the UI to load files
//----------------------------------------------------------------------
struct load_info_t // List of loaders
{
load_info_t *next;
char dllname[QMAXPATH];
char ftypename[MAX_FILE_FORMAT_NAME];
filetype_t ftype;
int pri; // 1-place first, 0-normal priority
};
// Build list of potential loaders
idaman load_info_t *ida_export build_loaders_list(linput_t *li);
// Free the list of loaders
idaman void ida_export free_loaders_list(load_info_t *list);
// Get name of loader from its DLL file.
// (for example, for PE files we will get "PE")
idaman char *ida_export get_loader_name_from_dll(char *dllname);
// Get name of loader used to load the input file into the database
// If no external loader was used, returns -1
// Otherwise copies the loader file name without the extension in the buf
// and returns its length
// (for example, for PE files we will get "PE")
idaman ssize_t ida_export get_loader_name(char *buf, size_t bufsize);
// Initialize user configurable options from the given loader
// based on the input file.
idaman bool ida_export init_loader_options(linput_t *li, load_info_t *loader);
// Load a binary file into the database.
// This function usually is called from ui.
// filename - the name of input file as is
// (if the input file is from library, then
// this is the name from the library)
// li - loader input source
// _neflags - see NEF_.. constants. For the first file
// the flag NEF_FIRST must be set.
// fileoff - Offset in the input file
// basepara - Load address in paragraphs
// binoff - Load offset (load_address=(basepara<<4)+binoff)
// nbytes - Number of bytes to load from the file
// 0 - up to the end of the file
// If nbytes is bigger than the number of
// bytes rest, the kernel will load as much
// as possible
// Returns: 1-ok, 0-failed (couldn't open the file)
idaman bool ida_export load_binary_file(
const char *filename,
linput_t *li,
ushort _neflags,
long fileoff,
ea_t basepara,
ea_t binoff,
ulong nbytes);
// Load a non-binary file into the database.
// This function usually is called from ui.
// filename - the name of input file as is
// (if the input file is from library, then
// this is the name from the library)
// li - loader input source
// sysdlldir - a directory with system dlls. Pass "." if unknown.
// _neflags - see NEF_.. constants. For the first file
// the flag NEF_FIRST must be set.
// loader - pointer to load_info_t structure.
// If the current IDP module has ph.loader != NULL
// then this argument is ignored.
// Returns: 1-ok, 0-failed
idaman bool ida_export load_nonbinary_file(
const char *filename,
linput_t *li,
const char *sysdlldir,
ushort _neflags,
load_info_t *loader);
//--------------------------------------------------------------------------
// Output file types:
typedef int ofile_type_t;
const ofile_type_t
OFILE_MAP = 0, // MAP file
OFILE_EXE = 1, // Executable file
OFILE_IDC = 2, // IDC file
OFILE_LST = 3, // Disassembly listing
OFILE_ASM = 4, // Assembly
OFILE_DIF = 5; // Difference
// Callback functions to output lines:
typedef int idaapi html_header_cb_t(FILE *fp);
typedef int idaapi html_footer_cb_t(FILE *fp);
typedef int idaapi html_line_cb_t(FILE *fp,
const char *line,
bgcolor_t prefix_color,
bgcolor_t bg_color);
#define gen_outline_t html_line_cb_t
//------------------------------------------------------------------
// Generate an output file
// otype - type of output file.
// fp - the output file handle
// ea1 - start address. For some file types this argument is ignored
// ea2 - end address. For some file types this argument is ignored
// as usual in ida, the end address of the range is not included
// flags - bit combination of GENFLG_...
// returns: number of the generated lines.
// -1 if an error occured
// ofile_exe: 0-can't generate exe file, 1-ok
idaman int ida_export gen_file(ofile_type_t otype, FILE *fp, ea_t ea1, ea_t ea2, int flags);
// 'flag' is a combination of the following:
#define GENFLG_MAPSEG 0x0001 // map: generate map of segments
#define GENFLG_MAPNAME 0x0002 // map: include dummy names
#define GENFLG_MAPDMNG 0x0004 // map: demangle names
#define GENFLG_MAPLOC 0x0008 // map: include local names
#define GENFLG_IDCTYPE 0x0008 // idc: gen only information about types
#define GENFLG_ASMTYPE 0x0010 // asm&lst: gen information about types too
#define GENFLG_GENHTML 0x0020 // asm&lst: generate html (ui_genfile_callback will be used)
#define GENFLG_ASMINC 0x0040 // asm&lst: gen information only about types
//----------------------------------------------------------------------
// Helper functions for the loaders & ui
//----------------------------------------------------------------------
// Load portion of file into the database
// This function will include (ea1..ea2) into the addressing space of the
// program (make it enabled)
// li - pointer ot input source
// pos - position in the file
// (ea1..ea2) - range of destination linear addresses
// patchable - should the kernel remember correspondance of
// file offsets to linear addresses.
// returns: 1-ok,0-read error, a warning is displayed
idaman int ida_export file2base(linput_t *li,
long pos,
ea_t ea1,
ea_t ea2,
int patchable);
#define FILEREG_PATCHABLE 1 // means that the input file may be
// patched (i.e. no compression,
// no iterated data, etc)
#define FILEREG_NOTPATCHABLE 0 // the data is kept in some encoded
// form in the file.
// Load database from the memory.
// memptr - pointer to buffer with bytes
// (ea1..ea2) - range of destination linear addresses
// fpos - position in the input file the data is taken from.
// if == -1, then no file position correspond to the data.
// This function works for wide byte processors too.
// returns: always 1
idaman int ida_export mem2base(const void *memptr,ea_t ea1,ea_t ea2,long fpos);
// Unload database to a binary file.
// fp - pointer to file
// pos - position in the file
// (ea1..ea2) - range of source linear addresses
// This function works for wide byte processors too.
// returns: 1-ok(always), write error leads to immediate exit
idaman int ida_export base2file(FILE *fp,long pos,ea_t ea1,ea_t ea2);
// Load information from DBG file into the database
// li - handler to opened input. If NULL, then fname is checked
// lname - name of loader module without extension and path
// fname - name of file to load (only if fp == NULL)
// is_remote - is the file located on a remote computer with
// the debugger server?
// Returns: 1-ok, 0-error (message is displayed)
idaman int ida_export load_loader_module(linput_t *li,
const char *lname,
const char *fname,
bool is_remote);
// Add long comment at inf.minEA:
// Input file: ....
// File format: ....
// This function should be called only from the loader to describe the input file.
idaman void ida_export create_filename_cmt(void);
// Get the input file type
// This function can recognize libraries and zip files.
idaman filetype_t ida_export get_basic_file_type(linput_t *li);
// Get name of the current file type
// The current file type is kept in inf.filetype.
// buf - buffer for the file type name
// bufsize - its size
// Returns: size of answer, this function always succeeds
idaman size_t ida_export get_file_type_name(char *buf, size_t bufsize);
//----------------------------------------------------------------------
// Work with IDS files: read and use information from them
//
// This structure is used in import_module():
struct impinfo_t
{
const char *dllname;
void (idaapi*func)(uval_t num, const char *name, uval_t node);
uval_t node;
};
// Find and import DLL module.
// This function adds information to the database (renames functions, etc)
// module - name of DLL
// windir - system directory with dlls
// modnode - node with information about imported entries
// imports by ordinals:
// altval(ord) contains linear address
// imports by name:
// supval(ea) contains the imported name
// Either altval or supval arrays may be absent.
// The node should never be deleted.
// importer- callback function (may be NULL):
// check dll module
// call 'func' for all exported entries in the file
// fp - pointer to file opened in binary mode.
// file position is 0.
// ud - pointer to impinfo_t structure
// this function checks that 'dllname' match the name of module
// if not, it returns 0
// otherwise it calls 'func' for each exported entry
// if dllname==NULL then 'func' will be called with num==0 and name==dllname
// and returns:
// 0 - dllname doesn't match, should continue
// 1 - ok
// ostype - type of operating system (subdir name)
// NULL means the IDS directory itself (not recommended)
idaman void ida_export import_module(const char *module,
const char *windir,
uval_t modnode,
int (idaapi*importer)(linput_t *li,impinfo_t *ii),
const char *ostype);
// Load and apply IDS file
// fname - name of file to apply
// This function loads the specified IDS file and applies it to the database
// If the program imports functions from a module with the same name
// as the name of the ids file being loaded, then only functions from this
// module will be affected. Otherwise (i.e. when the program does not import
// a module with this name) any function in the program may be affected.
// Returns:
// 1 - ok
// 0 - some error (a message is displayed)
// if the ids file does not exist, no message is displayed
idaman int ida_export load_ids_module(char *fname);
//----------------------------------------------------------------------
// DEFINITION OF PLUGIN MODULES
//----------------------------------------------------------------------
// A plugin is a module in plugins subdirectory which can be called by
// pressing a hotkey. It usually performs an action asked by the user.
class plugin_t
{
public:
int version; // Should be equal to IDP_INTERFACE_VERSION
int flags; // Features of the plugin:
#define PLUGIN_MOD 0x0001 // Plugin changes the database.
// IDA won't call the plugin if
// the processor prohibited any changes
// by setting PR_NOCHANGES in processor_t.
#define PLUGIN_DRAW 0x0002 // IDA should redraw everything after calling
// the plugin
#define PLUGIN_SEG 0x0004 // Plugin may be applied only if the
// current address belongs to a segment
#define PLUGIN_UNL 0x0008 // Unload the plugin immediately after
// calling 'run'.
// This flag may be set anytime.
// The kernel checks it after each call to 'run'
// The main purpose of this flag is to ease
// the debugging of new plugins.
#define PLUGIN_HIDE 0x0010 // Plugin should not appear in the Edit, Plugins menu
// This flag is checked at the start
#define PLUGIN_DBG 0x0020 // A debugger plugin. init() should put
// the address of debugger_t to dbg
// See idd.hpp for details
#define PLUGIN_PROC 0x0040 // Load plugin when a processor module is loaded and keep it
// until the processor module is unloaded
#define PLUGIN_FIX 0x0080 // Load plugin when IDA starts and keep it in the
// memory until IDA stops
int (idaapi* init)(void); // Initialize plugin
#define PLUGIN_SKIP 0 // Plugin doesn't want to be loaded
#define PLUGIN_OK 1 // Plugin agrees to work with the current database
// It will be loaded as soon as the user presses the hotkey
#define PLUGIN_KEEP 2 // Plugin agrees to work with the current database
// and wants to stay in the memory
void (idaapi* term)(void); // Terminate plugin. This function will be called
// when the plugin is unloaded. May be NULL.
void (idaapi* run)(int arg); // Invoke plugin
char *comment; // Long comment about the plugin
// it could appear in the status line
// or as a hint
char *help; // Multiline help about the plugin
char *wanted_name; // The preferred short name of the plugin
char *wanted_hotkey; // The preferred hotkey to run the plugin
};
extern "C" plugin_t PLUGIN; // (declaration for plugins)
//--------------------------------------------------------------------------
// A plugin can hook to the notification point and receive notifications
// of all major events in IDA. The callback function will be called
// for each event. The parameters of the callback:
// user_data - data supplied in call to hook_to_notification_point()
// notification_code - idp_notify or ui_notification_t code, depending on
// the hoot type
// va - additional parameters supplied with the notification
// see the event descriptions for information
// The callback should return:
// 0 - ok, the event should be processed further
// !=0 - the event is blocked and should be discarded
// in the case of processor modules, the returned value is used
// as the return value of notify()
typedef int idaapi hook_cb_t(void *user_data, int notification_code, va_list va);
enum hook_type_t
{
HT_IDP, // Hook to the processor module.
// The callback will receive all idp_notify events.
// See file idp.hpp for the list of events.
HT_UI, // Hook to the user interface.
// The callback will receive all ui_notification_t events.
// See file kernwin.hpp for the list of events.
HT_DBG, // Hook to the debugger.
// The callback will receive all dbg_notification_t events.
// See file dbg.hpp for the list of events.
HT_GRAPH, // Hook to the graph events
// The callback will receive all graph_notification_t events.
// See file graph.hpp for the list of events.
HT_LAST
};
idaman bool ida_export hook_to_notification_point(hook_type_t hook_type,
hook_cb_t *cb,
void *user_data);
// The plugin should unhook before being unloaded:
// (preferably in its termination function)
// Returns number of unhooked functions.
// If different callbacks have the same callback function pointer
// and user_data is not NULL, only the callback whose associated
// user defined data matchs will be removed.
idaman int ida_export unhook_from_notification_point(hook_type_t hook_type,
hook_cb_t *cb,
void *user_data = NULL);
// A well behaved processor module should call this function
// in his notify() function. If this function returns 0, then
// the processor module should process the notification itself
// Otherwise the code should be returned to the caller, like this:
//
// int code = invoke_callbacks(HT_IDP, what, va);
// if ( code ) return code;
// ...
//
idaman int ida_export invoke_callbacks(hook_type_t hook_type, int notification_code, va_list va);
// Method to generate graph notifications:
inline int idaapi grcall(int code, ...)
{
va_list va;
va_start(va, code);
int result = invoke_callbacks(HT_GRAPH, code, va);
va_end(va);
return result;
}
// Get plugin options from the command line
// If the user has specified the options in the -Oplugin_name:options
// format, them this function will return the 'options' part of it
// The 'plugin' parameter should denote the plugin name
// Returns NULL if there we no options specified
idaman const char *ida_export get_plugin_options(const char *plugin);
//--------------------------------------------------------------------------
// PLUGIN module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define PLUGIN_EXT "x64"
#else
#define PLUGIN_EXT "p64"
#endif
#else
#define PLUGIN_EXT "plw"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define PLUGIN_EXT "plx64"
#else
#define PLUGIN_EXT "plx"
#endif
#endif
#define PLUGIN_DLL "*." PLUGIN_EXT
//----------------------------------------------------------------------
// LOW LEVEL DLL LOADING FUNCTIONS
// Only the kernel should use these functions!
#define LNE_MAXSEG 10 // Max number of segments
#if 0
extern char dlldata[4096]; // Reserved place for DLL data
#define DLLDATASTART 0xA0 // Absolute offset of dlldata
extern char ldrdata[64]; // Reserved place for LOADER data
#define LDRDATASTART (DLLDATASTART+sizeof(dlldata)) // Absolute offset of ldrdata
#endif
struct idadll_t
{
void *dllinfo[LNE_MAXSEG];
void *entry; // first entry point of DLL
bool is_loaded(void) const { return dllinfo[0] != NULL; }
};
int load_dll(const char *file, idadll_t *dllmem);
// dllmem - allocated segments
// dos: segment 1 (data) isn't allocated
// Returns 0 - ok, else:
#define RE_NOFILE 1 /* No such file */
#define RE_NOTIDP 2 /* Not IDP file */
#define RE_NOPAGE 3 /* Can't load: bad segments */
#define RE_NOLINK 4 /* No linkage info */
#define RE_BADRTP 5 /* Bad relocation type */
#define RE_BADORD 6 /* Bad imported ordinal */
#define RE_BADATP 7 /* Bad relocation atype */
#define RE_BADMAP 8 /* DLLDATA offset is invalid */
void load_dll_or_die(const char *file, idadll_t *dllmem);
idaman int ida_export load_dll_or_say(const char *file, idadll_t *dllmem);
idaman void ida_export free_dll(idadll_t *dllmem);
// The processor description string should be at the offset 0x80 of the IDP file
// (the string consists of the processor types separated by colons)
#define IDP_DESC_START 0x80
#define IDP_DESC_END 0x200
idaman char *ida_export get_idp_desc(const char *file, char *buf, size_t bufsize); // Get IDP module name
//--------------------------------------------------------------------------
// IDP module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define IDP_EXT "x64"
#else
#define IDP_EXT "w64"
#endif
#else
#define IDP_EXT "w32"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define IDP_EXT "ilx64"
#else
#define IDP_EXT "ilx"
#endif
#endif
#ifdef __EA64__
#define IDP_DLL "*64." IDP_EXT
#else
#define IDP_DLL "*." IDP_EXT
#endif
//--------------------------------------------------------------------------
// Plugin information in IDA is stored in the following structure:
struct plugin_info_t
{
plugin_info_t *next; // next plugin information
char *path; // full path to the plugin
char *org_name; // original short name of the plugin
char *name; // short name of the plugin
// it will appear in the menu
ushort org_hotkey; // original hotkey to run the plugin
ushort hotkey; // current hotkey to run the plugin
int arg; // argument used to call the plugin
plugin_t *entry; // pointer to the plugin if it is already loaded
idadll_t dllmem;
int flags; // a copy of plugin_t.flags
};
// Get pointer to the list of plugins (some plugins might be listed several times
// in the list - once for each configured argument)
idaman plugin_info_t *ida_export get_plugins(void);
// Load a user-defined plugin
// name - short plugin name without path and extension
// or absolute path to the file name
// Returns: pointer to plugin description block
idaman plugin_t *ida_export load_plugin(const char *name);
// Run a loaded plugin with the specified argument
// ptr - pointer to plugin description block
// arg - argument to run with
idaman bool ida_export run_plugin(plugin_t *ptr, int arg);
// Load & run a plugin
inline bool idaapi load_and_run_plugin(const char *name, int arg)
{
return run_plugin(load_plugin(name), arg);
}
// Run a plugin as configured
// ptr - pointer to plugin information block
idaman bool ida_export invoke_plugin(plugin_info_t *ptr);
// Information for the user interface about available debuggers
struct dbg_info_t
{
plugin_info_t *pi;
struct debugger_t *dbg;
dbg_info_t(plugin_info_t *_pi, struct debugger_t *_dbg) : pi(_pi), dbg(_dbg) {}
};
idaman size_t ida_export get_debugger_plugins(const dbg_info_t **array);
// Initialize plugins with the specified flag
idaman void ida_export init_plugins(int flag);
// Terminate plugins with the specified flag
idaman void ida_export term_plugins(int flag);
//------------------------------------------------------------------------
//
// work with file regions (for patching)
//
void init_fileregions(void); // called by the kernel
void term_fileregions(void); // called by the kernel
inline void save_fileregions(void) {} // called by the kernel
void add_fileregion(ea_t ea1,ea_t ea2,long fpos); // called by the kernel
void move_fileregions(ea_t from, ea_t to, asize_t size);// called by the kernel
// Get offset in the input file which corresponds to the given ea
// If the specified ea can't be mapped into the input file offset,
// return -1.
idaman long ida_export get_fileregion_offset(ea_t ea);
// Get linear address which corresponds to the specified input file offset.
// If can't be found, then return BADADDR
idaman ea_t ida_export get_fileregion_ea(long offset);
//------------------------------------------------------------------------
// Generate an exe file (unload the database in binary form)
// fp - the output file handle
// if fp == NULL then returns:
// 1 - can generate an executable file
// 0 - can't generate an executable file
// returns: 1-ok, 0-failed
idaman int ida_export gen_exe_file(FILE *fp);
//------------------------------------------------------------------------
// Reload the input file
// This function reloads the byte values from the input file
// It doesn't modify the segmentation, names, comments, etc.
// file - name of the input file
// if file == NULL then returns:
// 1 - can reload the input file
// 0 - can't reload the input file
// is_remote - is the file located on a remote computer with
// the debugger server?
// returns: 1-ok, 0-failed
idaman int ida_export reload_file(const char *file, bool is_remote);
//------------------------------------------------------------------------
// Generate an IDC file (unload the database in text form)
// fp - the output file handle
// onlytypes - if true then generate idc about enums, structs and
// other type definitions used in the program
// returns: 1-ok, 0-failed
int local_gen_idc_file(FILE *fp, ea_t ea1, ea_t ea2, bool onlytypes);
//------------------------------------------------------------------------
// Output to a file all lines controlled by place 'pl'
// These functions are for the kernel only.
class place_t;
long print_all_places(FILE *fp,place_t *pl, html_line_cb_t *line_cb = NULL);
extern html_line_cb_t save_text_line;
long idaapi print_all_structs(FILE *fp, html_line_cb_t *line_cb = NULL);
long idaapi print_all_enums(FILE *fp, html_line_cb_t *line_cb = NULL);
//--------------------------------------------------------------------------
//
// KERNEL ONLY functions & data
//
idaman ida_export_data char command_line_file[QMAXPATH]; // full path to the file specified in the command line
idaman ida_export_data char database_idb[QMAXPATH]; // full path of IDB file
extern char database_id0[QMAXPATH]; // full path of original ID0 file (not exported)
idaman bool ida_export is_database_ext(const char *ext); // check the file extension
extern ulong ida_database_memory; // Database buffer size in bytes.
idaman ulong ida_export_data database_flags; // close_database() will:
#define DBFL_KILL 0x01 // delete unpacked database
#define DBFL_COMP 0x02 // compress database
#define DBFL_BAK 0x04 // create backup file
// (only if idb file is created)
#define DBFL_TEMP 0x08 // temporary database
inline bool is_temp_database(void) { return (database_flags & DBFL_TEMP) != 0; }
extern bool pe_create_idata;
extern bool pe_load_resources;
extern bool pe_create_flat_group;
// database check codes
typedef int dbcheck_t;
const dbcheck_t
DBCHK_NONE = 0, // database doesn't exist
DBCHK_OK = 1, // database exists
DBCHK_BAD = 2, // database exists but we can't use it
DBCHK_NEW = 3; // database exists but we the user asked to destroy it
dbcheck_t check_database(const char *file);
int open_database(bool isnew, const char *file, ulong input_size, bool is_temp_database);
// returns 'waspacked'
idaman int ida_export flush_buffers(void); // Flush buffers to disk
idaman void ida_export save_database(const char *outfile, bool delete_unpacked);
// Flush buffers and make
// a copy of database
void close_database(void); // see database_flags
bool compress_btree(const char *btree_file); // (internal) compress .ID0
bool get_input_file_from_archive(char *filename, size_t namesize, bool is_remote, char **temp_file_ptr);
bool loader_move_segm(ea_t from, ea_t to, asize_t size, bool keep);
int generate_ida_copyright(FILE *fp, const char *cmt, html_line_cb_t *line_cb);
bool is_in_loader(void);
void get_ids_filename(char *buf,
size_t bufsize,
const char *idsname,
const char *ostype,
bool *use_ordinals,
char **autotils,
int maxtils);
#pragma pack(pop)
#endif
| 40.183807 | 113 | 0.577135 | erithion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.