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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
853b0a18ec8a70ae2b7be35776b998dea2b8c39c | 5,139 | cpp | C++ | Applied/CCore/src/FileName.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/FileName.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/FileName.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | /* FileName.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 4.01
//
// Tag: Applied
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2020 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/FileName.h>
#include <CCore/inc/OutBuf.h>
namespace CCore {
/* class FileName */
struct FileName::PathUp : PathBase
{
StrLen path;
ulen up;
bool ok;
PathUp(StrLen path,ulen up) // path ends (if non-empty) with '/' or '\\' or ':'
: ok(false)
{
SplitPath split_dev(path);
ulen len=split_dev.path.len;
for(; len && up ;up--)
{
SplitName split({split_dev.path.ptr,len-1});
switch( split.getNameType() )
{
case Name :
{
len=split.path.len;
}
break;
case DotDotName :
{
set(path.prefix(split_dev.dev.len+len),up);
}
return;
default: return;
}
}
set(path.prefix(split_dev.dev.len+len),up);
}
void set(StrLen path_,ulen up_)
{
path=path_;
up=up_;
ok=true;
}
};
struct FileName::InspectPath
{
DynArray<StrLen> list;
ulen up = 0 ;
bool root = false ;
bool ok = false ;
explicit InspectPath(SplitPathName split_file)
: list(DoReserve,10)
{
list.append_copy(split_file.name);
StrLen path=split_file.path;
for(;;)
{
SplitPathName split_path(path);
switch( split_path.getNameType() )
{
case SplitPathName::Name :
{
if( up )
up--;
else
list.append_copy(split_path.name);
}
break;
case SplitPathName::EmptyName :
{
if( !!split_path || up ) return;
root=true;
}
break;
case SplitPathName::DotName :
{
// skip
}
break;
case SplitPathName::DotDotName :
{
up++;
}
break;
}
if( !split_path ) break;
path=split_path.path;
}
ok=true;
}
bool shrink(StrLen &path)
{
if( up )
{
PathUp path_up(path,up);
if( !path_up.ok ) return false;
path=path_up.path;
up=path_up.up;
}
return true;
}
template <class T,class S>
void put(T &out,S set) const
{
if( root ) out('/');
for(ulen count=up; count ;count--) out('.','.','/');
auto r=RangeReverse(list);
for(; r.len>1 ;++r) out(*r,'/');
set();
out(*r);
}
ulen countLen(ulen &off,ulen len) const
{
OutCount<ulen,char> counter(len);
put(counter, [&] () { off=counter; } );
return counter;
}
ULenSat countLenSat(ulen &off,ulen len) const
{
OutCount<ULenSat,char> counter(len);
put(counter, [&] () { off=ULenSat(counter).value; } );
return counter;
}
void put(OutBuf<char> &out) const
{
put(out, [] () {} );
}
};
class FileName::Out : public OutBuf<char>
{
public:
Out(DynArray<char> &buf,ulen len) : OutBuf<char>(buf.extend_raw(len).ptr) {}
};
void FileName::setAbs(StrLen file_name,SplitPath split_dev,SplitPathName split_file)
{
if( !split_file )
{
buf.extend_copy(file_name);
off=split_dev.dev.len;
}
else
{
// inspect
InspectPath inspect(split_file);
if( !inspect.ok ) return;
// count len
ulen len=inspect.countLen(off,split_dev.dev.len);
// build
Out out(buf,len);
out(split_dev.dev);
inspect.put(out);
}
ok=true;
}
void FileName::setRel(StrLen path,SplitPathName split_file)
{
if( !split_file )
{
ulen len=LenAdd(path.len,split_file.name.len);
Out out(buf,len);
out(path,split_file.name);
off=path.len;
}
else
{
// inspect
InspectPath inspect(split_file);
if( !inspect.ok || inspect.root ) return;
if( !inspect.shrink(path) ) return;
// count len
ulen off_;
ULenSat len=inspect.countLenSat(off_,path.len);
if( !len ) return;
off=off_;
// build
Out out(buf,len.value);
out(path);
inspect.put(out);
}
ok=true;
}
FileName::FileName(StrLen file_name)
{
SplitPath split_dev(file_name);
SplitPathName split_file(split_dev.path);
if( split_file.getNameType()==SplitPathName::Name )
{
setAbs(file_name,split_dev,split_file);
}
}
FileName::FileName(StrLen path,StrLen file_name)
{
SplitPath split_dev(file_name);
SplitPathName split_file(split_dev.path);
if( split_file.getNameType()==SplitPathName::Name )
{
if( !split_dev && !PathIsRooted(file_name) )
{
setRel(path,split_file);
}
else
{
setAbs(file_name,split_dev,split_file);
}
}
}
} // namespace CCore
| 17.13 | 90 | 0.526562 | SergeyStrukov |
853cd933cd66cd7622490591b70fa693c08ff795 | 558 | hpp | C++ | src/Jogo/GUI/EventHandler.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/GUI/EventHandler.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/GUI/EventHandler.hpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | //
// EventHandler.hpp
// Jogo-SFML
//
// Created by Matheus Kunnen Ledesma on 11/5/19.
// Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved.
//
#ifndef EventHandler_hpp
#define EventHandler_hpp
#include "base_gui_includes.hpp"
namespace GUI {
namespace Events {
enum Type {CLICK, HOVER, ENABLED, DISABLED};
}
class EventHandler{
public:
// Constructor & Destructor
EventHandler();
virtual ~EventHandler();
// Methods
virtual void onGuiEvent(int id, Events::Type event_id) = 0;
};
}
#endif /* EventHandler_hpp */
| 18 | 65 | 0.695341 | MatheusKunnen |
853d0f79142828a35817ae677b9c4030ca469793 | 464 | cpp | C++ | src/keycreate/keycreate.cpp | fusor-io/fusor-state-machine | d52f96e7067aecb19088c9d59c57bdb7cba55504 | [
"MIT"
] | null | null | null | src/keycreate/keycreate.cpp | fusor-io/fusor-state-machine | d52f96e7067aecb19088c9d59c57bdb7cba55504 | [
"MIT"
] | null | null | null | src/keycreate/keycreate.cpp | fusor-io/fusor-state-machine | d52f96e7067aecb19088c9d59c57bdb7cba55504 | [
"MIT"
] | null | null | null | #include <string.h>
#include "keycreate.h"
char *KeyCreate::withScope(const char *scopeId, const char *name)
{
strncpy(_buffer, scopeId, MAX_VAR_NAME_LEN - 1);
strncat(_buffer, ".", MAX_VAR_NAME_LEN - strlen(_buffer) - 1);
strncat(_buffer, name, MAX_VAR_NAME_LEN - strlen(_buffer) - 1);
return _buffer;
}
const char *KeyCreate::createKey(const char *name)
{
char *buff = new char[strlen(name) + 1];
strcpy(buff, name);
return buff;
}
| 25.777778 | 67 | 0.678879 | fusor-io |
8547fcd6076b24448a7bec1e939241764501064f | 2,097 | cpp | C++ | rendering/Pipeline.cpp | broecker/gfx1993 | d0390cdf6bd7b864dd86c99fa4d79cb31c00fa2f | [
"MIT"
] | null | null | null | rendering/Pipeline.cpp | broecker/gfx1993 | d0390cdf6bd7b864dd86c99fa4d79cb31c00fa2f | [
"MIT"
] | null | null | null | rendering/Pipeline.cpp | broecker/gfx1993 | d0390cdf6bd7b864dd86c99fa4d79cb31c00fa2f | [
"MIT"
] | null | null | null | #include "Pipeline.h"
#include <glm/glm.hpp>
using glm::vec4;
namespace render {
VertexOut &&lerp(const VertexOut &a, const VertexOut &b, float d) {
VertexOut result;
result.clipPosition = glm::mix(a.clipPosition, b.clipPosition, d);
result.worldPosition = glm::mix(a.worldPosition, b.worldPosition, d);
result.worldNormal = glm::mix(a.worldNormal, b.worldNormal, d);
result.color = glm::mix(a.color, b.color, d);
result.texcoord = glm::mix(a.texcoord, b.texcoord, d);
return std::move(result);
}
ShadingGeometry &&interpolate(const ShadingGeometry &a,
const ShadingGeometry &b, float d) {
ShadingGeometry result;
result.position = mix(a.position, b.position, d);
result.normal = normalize(mix(a.normal, b.normal, d));
result.color = mix(a.color, b.color, d);
result.windowCoord = mix(a.windowCoord, b.windowCoord, d);
return std::move(result);
}
ShadingGeometry &&PointPrimitive::rasterize() const {
ShadingGeometry result;
result.position = p.worldPosition;
result.normal = p.worldNormal;
result.color = p.color;
result.texcoord = p.texcoord;
return std::move(result);
}
ShadingGeometry &&LinePrimitive::rasterize(float d) const {
ShadingGeometry result;
result.position = mix(a.worldPosition, b.worldPosition, d);
result.normal = normalize(mix(a.worldNormal, b.worldNormal, d));
result.color = mix(a.color, b.color, d);
result.texcoord = mix(a.texcoord, b.texcoord, d);
return std::move(result);
}
ShadingGeometry &&TrianglePrimitive::rasterize(const glm::vec3 &bary) const {
float bsum = bary.x + bary.y + bary.z;
ShadingGeometry sgeo;
sgeo.position = a.worldPosition * bary.x + b.worldPosition * bary.y +
c.worldPosition * bary.z / bsum;
sgeo.normal = a.worldNormal * bary.x + b.worldNormal * bary.y +
c.worldNormal * bary.z / bsum;
sgeo.color = a.color * bary.x + b.color * bary.y + c.color * bary.z / bsum;
sgeo.texcoord =
a.texcoord * bary.x + b.texcoord * bary.y + c.texcoord * bary.z / bsum;
return std::move(sgeo);
}
} // namespace render
| 32.261538 | 77 | 0.679542 | broecker |
854e2d0eada09c5c96b778e9d74865f6e0a55284 | 848 | cpp | C++ | Source/MapEditorModule/DetailsCustomisation/MapActorDetailCustomization.cpp | benoitestival/MapModuleEditor | 3a7d72d0dc3761bd61f19df1e5af46081a791356 | [
"MIT"
] | null | null | null | Source/MapEditorModule/DetailsCustomisation/MapActorDetailCustomization.cpp | benoitestival/MapModuleEditor | 3a7d72d0dc3761bd61f19df1e5af46081a791356 | [
"MIT"
] | null | null | null | Source/MapEditorModule/DetailsCustomisation/MapActorDetailCustomization.cpp | benoitestival/MapModuleEditor | 3a7d72d0dc3761bd61f19df1e5af46081a791356 | [
"MIT"
] | 1 | 2021-07-07T09:22:28.000Z | 2021-07-07T09:22:28.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "MapActorDetailCustomization.h"
#include "Editor/PropertyEditor/Public/PropertyEditorModule.h"
#include "MapGenerator/MapActor.h"
#include "Modules/ModuleManager.h"
TSharedRef<IDetailCustomization> MapActorDetailCustomization::MakeInstance() {
return MakeShareable(new MapActorDetailCustomization);
}
void MapActorDetailCustomization::RegisterDetailsCustomization() {
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.RegisterCustomClassLayout("MapActor", FOnGetDetailCustomizationInstance::CreateStatic(&MapActorDetailCustomization::MakeInstance));
}
void MapActorDetailCustomization::CustomizeDetails(IDetailLayoutBuilder& DetailBuilder) {
//TODO
//AMapActor*
}
| 33.92 | 147 | 0.837264 | benoitestival |
8556297f0b4422ad12dc45a3b3f36a85b70e6142 | 801 | hpp | C++ | lib/index.hpp | cirossmonteiro/tensor | 6ece78825535188fba6dbe62ae4be0521381c026 | [
"Unlicense"
] | 1 | 2019-03-31T05:23:20.000Z | 2019-03-31T05:23:20.000Z | lib/index.hpp | cirossmonteiro/tensor | 6ece78825535188fba6dbe62ae4be0521381c026 | [
"Unlicense"
] | null | null | null | lib/index.hpp | cirossmonteiro/tensor | 6ece78825535188fba6dbe62ae4be0521381c026 | [
"Unlicense"
] | null | null | null | #pragma once
#ifndef INDEX_HPP
#define INDEX_HPP
#include <cstddef>
#include <iostream>
using namespace std;
class Index {
unsigned int size = 0;
unsigned int *values = NULL;
public:
~Index(); // done
Index(); // to do
Index(unsigned int new_size); // done
Index(unsigned int new_size, unsigned int *new_values); // done
Index(Index &index); // done
void check_internals() const;
// void copy(Index &new_index); // done
unsigned int get_size(); // done
unsigned int *get_values();
unsigned int &operator[](int index) const; // done
friend string &operator<<(string &ac, Index &index);// done
friend ostream &operator<<(ostream& out, Index &index);// done
void print(); // done
string get_string(); // done
void set_zero();
};
#endif | 26.7 | 67 | 0.649189 | cirossmonteiro |
85563c3c4cf38752082c149c6ad400bbc57b34db | 11,166 | hpp | C++ | src/mirrage/utils/include/mirrage/utils/ranges.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 14 | 2017-10-26T08:45:54.000Z | 2021-04-06T11:44:17.000Z | src/mirrage/utils/include/mirrage/utils/ranges.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 17 | 2017-10-09T20:11:58.000Z | 2018-11-08T22:05:14.000Z | src/mirrage/utils/include/mirrage/utils/ranges.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 1 | 2018-09-26T23:10:06.000Z | 2018-09-26T23:10:06.000Z | /** simple wrappers for iterator pairs ***************************************
* *
* Copyright (c) 2018 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include <tuple>
#include <utility>
#include <vector>
namespace mirrage::util {
template <class Iter>
class iter_range {
public:
iter_range() noexcept {}
iter_range(Iter begin, Iter end) noexcept : b(begin), e(end) {}
bool operator==(const iter_range& o) noexcept { return b == o.b && e == o.e; }
Iter begin() const noexcept { return b; }
Iter end() const noexcept { return e; }
std::size_t size() const noexcept { return std::distance(b, e); }
private:
Iter b, e;
};
template <class T>
using vector_range = iter_range<typename std::vector<T>::iterator>;
template <class T>
using cvector_range = iter_range<typename std::vector<T>::const_iterator>;
template <class Range>
class skip_range {
public:
skip_range() noexcept {}
skip_range(std::size_t skip, Range range) noexcept : _skip(skip), _range(std::move(range)) {}
bool operator==(const skip_range& o) noexcept { return _range == o._range; }
auto begin() const noexcept
{
auto i = _range.begin();
auto skipped = std::size_t(0);
while(i != _range.end() && skipped++ < _skip)
++i;
return i;
}
auto end() const noexcept { return _range.end(); }
std::size_t size() const noexcept
{
auto s = _range.size();
return s > _skip ? s - _skip : 0;
}
private:
std::size_t _skip;
Range _range;
};
template <class Range>
auto skip(std::size_t skip, Range&& range)
{
return skip_range<std::remove_reference_t<Range>>(skip, std::forward<Range>(range));
}
namespace detail {
struct deref_join {
template <class... Iter>
[[maybe_unused]] auto operator()(Iter&&... iter) const
{
return std::tuple<decltype(*iter)...>(*iter...);
}
};
template <typename T>
class proxy_holder {
public:
proxy_holder(const T& value) : value(value) {}
T* operator->() { return &value; }
T& operator*() { return value; }
private:
T value;
};
} // namespace detail
template <class... Iter>
class join_iterator {
public:
join_iterator() = default;
template <class... T>
join_iterator(std::size_t index, T&&... iters) : _iters(std::forward<T>(iters)...), _index(index)
{
}
auto operator==(const join_iterator& rhs) const { return _index == rhs._index; }
auto operator!=(const join_iterator& rhs) const { return !(*this == rhs); }
auto operator*() const { return std::apply(detail::deref_join{}, _iters); }
auto operator-> () const { return proxy_holder(**this); }
auto operator++()
{
foreach_in_tuple(_iters, [](auto, auto& iter) { ++iter; });
++_index;
}
auto operator++(int)
{
auto v = *this;
++*this;
return v;
}
private:
std::tuple<Iter...> _iters;
std::size_t _index;
};
namespace detail {
struct get_join_begin {
template <class... Range>
[[maybe_unused]] auto operator()(Range&&... ranges) const
{
return join_iterator<std::remove_reference_t<decltype(ranges.begin())>...>(0,
ranges.begin()...);
}
};
struct get_join_iterator {
template <class... Range>
[[maybe_unused]] auto operator()(std::size_t offset, Range&&... ranges) const
{
return join_iterator<std::remove_reference_t<decltype(ranges.begin())>...>(
offset, (ranges.begin() + offset)...);
}
};
} // namespace detail
template <class... Range>
class join_range {
public:
join_range() noexcept {}
template <class... T>
join_range(T&&... ranges) noexcept : _ranges(std::forward<T>(ranges)...), _size(min(ranges.size()...))
{
}
auto begin() const noexcept { return std::apply(detail::get_join_begin{}, _ranges); }
auto begin() noexcept { return std::apply(detail::get_join_begin{}, _ranges); }
auto end() const noexcept
{
return std::apply(detail::get_join_iterator{}, std::tuple_cat(std::make_tuple(_size), _ranges));
}
auto end() noexcept
{
return std::apply(detail::get_join_iterator{}, std::tuple_cat(std::make_tuple(_size), _ranges));
}
auto size() const noexcept { return _size; }
private:
std::tuple<Range...> _ranges;
std::size_t _size;
};
template <class... Range>
auto join(Range&&... range)
{
return join_range<std::remove_reference_t<Range>...>(std::forward<Range>(range)...);
}
namespace detail {
template <class Arg>
auto construct_index_tuple(std::int64_t index, Arg arg)
{
return std::tuple<std::int64_t, Arg>(index, arg);
}
template <class, class... Args>
auto construct_index_tuple(std::int64_t index, std::tuple<Args...> arg)
{
return std::tuple<std::int64_t, Args...>(index, std::get<Args>(arg)...);
}
template <class BaseIter>
class indexing_range_iterator {
public:
indexing_range_iterator(BaseIter&& iter, std::int64_t index) : iter(iter), index(index) {}
auto operator==(const indexing_range_iterator& rhs) const { return iter == rhs.iter; }
auto operator!=(const indexing_range_iterator& rhs) const { return !(*this == rhs); }
auto operator*() { return construct_index_tuple<decltype(*iter)>(index, *iter); }
auto operator-> () { return proxy_holder(**this); }
auto operator*() const { return construct_index_tuple<decltype(*iter)>(index, *iter); }
auto operator-> () const { return proxy_holder(**this); }
auto operator++()
{
++iter;
++index;
}
auto operator++(int)
{
auto v = *this;
++*this;
return v;
}
private:
BaseIter iter;
std::int64_t index;
};
template <class BaseIter>
auto make_indexing_range_iterator(BaseIter&& iter, std::int64_t index)
{
return indexing_range_iterator<std::remove_reference_t<BaseIter>>(std::forward<BaseIter>(iter),
index);
}
} // namespace detail
template <class Range>
class indexing_range {
public:
indexing_range(Range&& range) noexcept : range(std::move(range)) {}
bool operator==(const indexing_range& rhs) noexcept { return range == rhs.range; }
auto begin() noexcept { return detail::make_indexing_range_iterator(range.begin(), 0u); }
auto end() noexcept { return detail::make_indexing_range_iterator(range.end(), std::int64_t(-1)); }
auto begin() const noexcept { return detail::make_indexing_range_iterator(range.begin(), 0u); }
auto end() const noexcept
{
return detail::make_indexing_range_iterator(range.end(), std::int64_t(-1));
}
private:
Range range;
};
template <class Range>
auto with_index(Range&& r) -> indexing_range<std::remove_reference_t<Range>>
{
return {std::move(r)};
}
template <class Range>
class indexing_range_view {
public:
indexing_range_view(Range& range) noexcept : range(&range) {}
bool operator==(const indexing_range_view& rhs) noexcept { return *range == *rhs.range; }
auto begin() noexcept { return detail::make_indexing_range_iterator(range->begin(), 0u); }
auto end() noexcept { return detail::make_indexing_range_iterator(range->end(), std::int64_t(-1)); }
auto begin() const noexcept { return detail::make_indexing_range_iterator(range->begin(), 0u); }
auto end() const noexcept
{
return detail::make_indexing_range_iterator(range->end(), std::int64_t(-1));
}
private:
Range* range;
};
template <class Range>
auto with_index(Range& r) -> indexing_range_view<std::remove_reference_t<Range>>
{
return {r};
}
template <class T>
class numeric_range {
struct iterator {
using iterator_category = std::random_access_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
T p;
T s;
constexpr iterator(T v, T s = 1) noexcept : p(v), s(s) {}
constexpr iterator(const iterator&) noexcept = default;
constexpr iterator(iterator&&) noexcept = default;
iterator& operator++() noexcept
{
p += s;
return *this;
}
iterator operator++(int) noexcept
{
auto t = *this;
*this ++;
return t;
}
iterator& operator--() noexcept
{
p -= s;
return *this;
}
iterator operator--(int) noexcept
{
auto t = *this;
*this --;
return t;
}
bool operator==(const iterator& rhs) const noexcept { return p == rhs.p; }
bool operator!=(const iterator& rhs) const noexcept { return p != rhs.p; }
const T& operator*() const noexcept { return p; }
};
using const_iterator = iterator;
public:
constexpr numeric_range() noexcept {}
constexpr numeric_range(T begin, T end, T step = 1) noexcept : b(begin), e(end), s(step) {}
constexpr numeric_range(numeric_range&&) noexcept = default;
constexpr numeric_range(const numeric_range&) noexcept = default;
numeric_range& operator=(const numeric_range&) noexcept = default;
numeric_range& operator=(numeric_range&&) noexcept = default;
bool operator==(const numeric_range& o) noexcept { return b == o.b && e == o.e; }
constexpr iterator begin() const noexcept { return b; }
constexpr iterator end() const noexcept { return e; }
private:
T b, e, s;
};
template <class Iter, typename = std::enable_if_t<!std::is_arithmetic<Iter>::value>>
constexpr iter_range<Iter> range(Iter b, Iter e)
{
return {b, e};
}
template <class B, class E, typename = std::enable_if_t<std::is_arithmetic<B>::value>>
constexpr auto range(B b, E e, std::common_type_t<B, E> s = 1)
{
using T = std::common_type_t<B, E>;
return numeric_range<T>{T(b), std::max(T(e + 1), T(b)), T(s)};
}
template <class T, typename = std::enable_if_t<std::is_arithmetic<T>::value>>
constexpr numeric_range<T> range(T num)
{
return {0, static_cast<T>(num)};
}
template <class Container, typename = std::enable_if_t<!std::is_arithmetic<Container>::value>>
auto range(Container& c) -> iter_range<typename Container::iterator>
{
using namespace std;
return {begin(c), end(c)};
}
template <class Container, typename = std::enable_if_t<!std::is_arithmetic<Container>::value>>
auto range(const Container& c) -> iter_range<typename Container::const_iterator>
{
using namespace std;
return {begin(c), end(c)};
}
template <class Container, typename = std::enable_if_t<!std::is_arithmetic<Container>::value>>
auto range_reverse(Container& c) -> iter_range<typename Container::reverse_iterator>
{
using namespace std;
return {rbegin(c), rend(c)};
}
template <class Container, typename = std::enable_if_t<!std::is_arithmetic<Container>::value>>
auto range_reverse(const Container& c) -> iter_range<typename Container::const_reverse_iterator>
{
using namespace std;
return {rbegin(c), rend(c)};
}
} // namespace mirrage::util
| 29.307087 | 104 | 0.632814 | lowkey42 |
855a6cbddf47fbd3cfde60a54ae772f0997434e7 | 5,516 | hpp | C++ | library/src/main/jni/openslmediaplayer/include/oslmp/OpenSLMediaPlayerContext.hpp | cirnoftw/android-openslmediaplayer | 6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583 | [
"Apache-2.0"
] | 435 | 2015-01-16T14:36:07.000Z | 2022-02-11T02:32:19.000Z | library/src/main/jni/openslmediaplayer/include/oslmp/OpenSLMediaPlayerContext.hpp | cirnoftw/android-openslmediaplayer | 6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583 | [
"Apache-2.0"
] | 59 | 2015-02-12T22:21:49.000Z | 2021-06-16T11:48:15.000Z | library/src/main/jni/openslmediaplayer/include/oslmp/OpenSLMediaPlayerContext.hpp | cirnoftw/android-openslmediaplayer | 6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583 | [
"Apache-2.0"
] | 104 | 2015-01-16T14:36:07.000Z | 2021-05-24T03:32:54.000Z | //
// Copyright (C) 2014 Haruki Hasegawa
//
// 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.
//
#ifndef OPENSLMEDIAPLAYERCONTEXT_HPP_
#define OPENSLMEDIAPLAYERCONTEXT_HPP_
#include <jni.h> // for JNIEnv
#include <oslmp/OpenSLMediaPlayerAPICommon.hpp>
// constants
#define OSLMP_CONTEXT_OPTION_USE_BASSBOOST (1 << 0) // NOTE: low-latency playback is disabled if specified this option
#define OSLMP_CONTEXT_OPTION_USE_VIRTUALIZER (1 << 1) // NOTE: low-latency playback is disabled if specified this option
#define OSLMP_CONTEXT_OPTION_USE_EQUALIZER (1 << 2) // NOTE: low-latency playback is disabled if specified this option
#define OSLMP_CONTEXT_OPTION_USE_ENVIRONMENAL_REVERB \
(1 << 8) // NOTE: low-latency playback is disabled if specified this option
#define OSLMP_CONTEXT_OPTION_USE_PRESET_REVERB \
(1 << 9) // NOTE: low-latency playback is disabled if specified this option
#define OSLMP_CONTEXT_OPTION_USE_VISUALIZER (1 << 16)
#define OSLMP_CONTEXT_OPTION_USE_HQ_EQUALIZER (1 << 17)
#define OSLMP_CONTEXT_OPTION_USE_PREAMP (1 << 18)
#define OSLMP_CONTEXT_OPTION_USE_HQ_VISUALIZER (1 << 19)
// resampler quality specifier
#define OSLMP_CONTEXT_RESAMPLER_QUALITY_LOW 0
#define OSLMP_CONTEXT_RESAMPLER_QUALITY_MIDDLE 1
#define OSLMP_CONTEXT_RESAMPLER_QUALITY_HIGH 2
// HQEqualizer implementation type specifier
#define OSLMP_CONTEXT_HQ_EQUALIZER_IMPL_BASIC_PEAKING_FILTER 0
#define OSLMP_CONTEXT_HQ_EQUALIZER_IMPL_FLAT_GAIN_RESPONSE 1
// Sink backend implementation type specifier
#define OSLMP_CONTEXT_SINK_BACKEND_TYPE_OPENSL 0
#define OSLMP_CONTEXT_SINK_BACKEND_TYPE_AUDIO_TRACK 1
//
// forward declarations
//
namespace oslmp {
namespace impl {
class OpenSLMediaPlayerInternalContext;
} // namespace impl
} // namespace oslmp
namespace oslmp {
class OpenSLMediaPlayerContext : public virtual android::RefBase {
friend class impl::OpenSLMediaPlayerInternalContext;
public:
class InternalThreadEventListener;
struct create_args_t {
uint32_t system_out_sampling_rate; // [millihertz]
uint32_t system_out_frames_per_buffer; // [frames]
bool system_supports_low_latency;
bool system_supports_floating_point;
uint32_t options;
int stream_type;
uint32_t short_fade_duration; // Fade duration used to avoid audio artifacts (unit: [ms])
uint32_t long_fade_duration; // Fade duration used when calling start(), pause() and seek() (unit: [ms])
uint32_t resampler_quality;
uint32_t hq_equalizer_impl_type;
uint32_t sink_backend_type;
bool use_low_latency_if_available;
bool use_floating_point_if_available;
InternalThreadEventListener *listener;
create_args_t() OSLMP_API_ABI : system_out_sampling_rate(44100000),
system_out_frames_per_buffer(512),
system_supports_low_latency(false),
system_supports_floating_point(false),
options(0),
stream_type(3), // 3 = STREAM_MUSIC
short_fade_duration(25),
long_fade_duration(1500),
listener(nullptr),
resampler_quality(OSLMP_CONTEXT_RESAMPLER_QUALITY_MIDDLE),
hq_equalizer_impl_type(OSLMP_CONTEXT_HQ_EQUALIZER_IMPL_BASIC_PEAKING_FILTER),
sink_backend_type(OSLMP_CONTEXT_SINK_BACKEND_TYPE_OPENSL),
use_low_latency_if_available(false),
use_floating_point_if_available(true)
{
}
};
public:
virtual ~OpenSLMediaPlayerContext() OSLMP_API_ABI;
static android::sp<OpenSLMediaPlayerContext> create(JNIEnv *env, const create_args_t &args) noexcept OSLMP_API_ABI;
InternalThreadEventListener *getInternalThreadEventListener() const noexcept OSLMP_API_ABI;
int32_t getAudioSessionId() const noexcept OSLMP_API_ABI;
private:
class Impl;
OpenSLMediaPlayerContext(Impl *impl);
impl::OpenSLMediaPlayerInternalContext &getInternal() const noexcept OSLMP_API_ABI;
private:
Impl *impl_; // NOTE: do not use unique_ptr to avoid cxxporthelper dependencies
};
class OpenSLMediaPlayerContext::InternalThreadEventListener : public virtual android::RefBase {
public:
virtual ~InternalThreadEventListener() {}
virtual void onEnterInternalThread(OpenSLMediaPlayerContext *context) noexcept OSLMP_API_ABI = 0;
virtual void onLeaveInternalThread(OpenSLMediaPlayerContext *context) noexcept OSLMP_API_ABI = 0;
};
} // namespace oslmp
#endif // OPENSLMEDIAPLAYERCONTEXT_HPP_
| 42.430769 | 120 | 0.687999 | cirnoftw |
855eff19f12f55dbac9886aa25d8181539af2efe | 3,220 | cpp | C++ | Container.cpp | nirry78/codegen | 9c538533ea899c8e9bb4a5f2f0851c0680708c82 | [
"MIT"
] | null | null | null | Container.cpp | nirry78/codegen | 9c538533ea899c8e9bb4a5f2f0851c0680708c82 | [
"MIT"
] | null | null | null | Container.cpp | nirry78/codegen | 9c538533ea899c8e9bb4a5f2f0851c0680708c82 | [
"MIT"
] | null | null | null | #include "Container.h"
Container::Container(json& object):
mFieldCount(0)
{
for (auto& [key, value] : object.items())
{
if (!key.compare("name"))
{
mName = value.get<std::string>();
LOGD(" Name: %s\n", mName.c_str());
}
else if (!key.compare("parameters"))
{
if (value.is_array())
{
ParseParameters(value);
}
else
{
LOGE("Parameters must be an array\n");
}
}
else if (!key.compare("group"))
{
mGroup = value.get<std::string>();
LOGD(" Group: %s\n", mGroup.c_str());
}
else
{
LOGE("Container has unregonized key: %s\n", key.c_str());
}
}
ForeachFieldReset(NULL);
}
Container::~Container()
{
}
bool Container::ForeachFieldReset(Tag *tag)
{
bool result = false;
mFieldIterator = mFieldList.begin();
mIteratorTag = tag;
if (mFieldIterator != mFieldList.end())
{
if (tag)
{
if (!(*mFieldIterator).AcceptNameAndGroup(tag))
{
result = ForeachFieldNext();
}
else
{
result = true;
}
}
else
{
result = true;
}
}
mFieldCount = 0;
LOGD("<Container::ForeachFieldReset> count: %u, result: %u\n",
mFieldCount, result);
return result;
}
bool Container::ForeachFieldNext()
{
bool result = false;
++mFieldIterator;
if (mIteratorTag)
{
while (mFieldIterator != mFieldList.end())
{
result = (*mFieldIterator).AcceptNameAndGroup(mIteratorTag);
if (result)
{
break;
}
++mFieldIterator;
}
}
else
{
result = (mFieldIterator != mFieldList.end());
}
if (result)
{
mFieldCount++;
}
LOGD("<Container::ForeachFieldNext> count: %u, result: %u\n",
mFieldCount, result);
return result;
}
void Container::Output(Document* document, std::string& name, Tag* tag, uint32_t count)
{
LOGD("<Container::Output> name: %s, count: %u\n", name.c_str(), count);
if (StringCompare(name, "name"))
{
if (tag)
{
tag->Output(document, mName);
}
else
{
document->Output(mName);
}
}
else if (StringCompare(name, "count") && tag)
{
tag->Output(document, "%u", count);
}
}
void Container::OutputField(Document* document, std::string& name, Tag* tag)
{
if (mFieldIterator != mFieldList.end())
{
mFieldIterator->Output(document, name, tag, mFieldCount);
}
}
void Container::ParseParameters(json& object)
{
for (auto& [key, value] : object.items())
{
(void)key;
if (value.is_object())
{
mFieldList.push_back(Field(value));
}
else
{
LOGE("Expecting object");
}
}
}
bool Container::IsValid()
{
return true;
}
| 19.634146 | 87 | 0.476708 | nirry78 |
856056ee5d6517a7e2eff6c71d9352575e1caebb | 38,794 | cpp | C++ | SerialPrograms/Source/NintendoSwitch/TestProgramSwitch.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/NintendoSwitch/TestProgramSwitch.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/NintendoSwitch/TestProgramSwitch.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | /* Test Program (Switch)
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <cmath>
//#include <QSystemTrayIcon>
#include <QProcess>
#include "Common/Cpp/Exceptions.h"
#include "Common/Cpp/PrettyPrint.h"
#include "Common/Cpp/AlignedVector.h"
#include "Common/Cpp/SIMDDebuggers.h"
#include "Common/Qt/QtJsonTools.h"
#include "ClientSource/Libraries/Logging.h"
#include "CommonFramework/PersistentSettings.h"
#include "CommonFramework/Tools/StatsTracking.h"
#include "CommonFramework/Tools/StatsDatabase.h"
#include "CommonFramework/Tools/InterruptableCommands.h"
#include "CommonFramework/Inference/InferenceThrottler.h"
#include "CommonFramework/Inference/AnomalyDetector.h"
#include "CommonFramework/Inference/StatAccumulator.h"
#include "CommonFramework/Inference/TimeWindowStatTracker.h"
#include "CommonFramework/InferenceInfra/VisualInferenceSession.h"
#include "CommonFramework/InferenceInfra/InferenceRoutines.h"
#include "CommonFramework/Inference/FrozenImageDetector.h"
#include "CommonFramework/Inference/BlackScreenDetector.h"
#include "CommonFramework/ImageTools/SolidColorTest.h"
#include "CommonFramework/ImageMatch/FilterToAlpha.h"
#include "CommonFramework/ImageMatch/ImageDiff.h"
#include "CommonFramework/ImageMatch/ImageCropper.h"
#include "CommonFramework/ImageMatch/ImageDiff.h"
#include "CommonFramework/OCR/OCR_RawOCR.h"
#include "CommonFramework/OCR/OCR_Filtering.h"
#include "CommonFramework/OCR/OCR_StringNormalization.h"
#include "CommonFramework/OCR/OCR_TextMatcher.h"
#include "CommonFramework/OCR/OCR_LargeDictionaryMatcher.h"
#include "CommonFramework/ImageMatch/ExactImageDictionaryMatcher.h"
#include "CommonFramework/ImageMatch/CroppedImageDictionaryMatcher.h"
#include "CommonFramework/Inference/ImageMatchDetector.h"
#include "CommonFramework/Notifications/ProgramNotifications.h"
#include "CommonFramework/Tools/ErrorDumper.h"
#include "NintendoSwitch/NintendoSwitch_Settings.h"
#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h"
#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h"
#include "Pokemon/Resources/Pokemon_PokemonNames.h"
#include "PokemonSwSh/ShinyHuntTracker.h"
#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h"
#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h"
#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h"
#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h"
#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h"
#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h"
#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h"
#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h"
#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h"
#include "PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h"
#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h"
#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h"
#include "PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h"
#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h"
#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h"
#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h"
#include "PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h"
#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h"
#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h"
#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h"
#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h"
#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h"
#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h"
#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h"
#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h"
#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h"
#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h"
#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h"
#include "PokemonSwSh/Programs/PokemonSwSh_Internet.h"
#include "PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h"
#include "Kernels/Kernels_x64_SSE41.h"
#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h"
//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h"
#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h"
#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h"
#include "Kernels/Kernels_Alignment.h"
//#include "Kernels/Waterfill/Kernels_Waterfill_Intrinsics_SSE4.h"
//#include "Kernels/Waterfill/Kernels_Waterfill_FillQueue.h"
//#include "Kernels/BinaryImage/Kernels_BinaryImage_Default.h"
//#include "Kernels/BinaryImage/Kernels_BinaryImage_x64_SSE42.h"
#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h"
#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h"
//#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h"
//#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h"
#include "Kernels/Waterfill/Kernels_Waterfill.h"
#include "CommonFramework/BinaryImage/BinaryImage_FilterRgb32.h"
#include "Integrations/DiscordWebhook.h"
#include "Pokemon/Pokemon_Notification.h"
#include "PokemonSwSh/Programs/PokemonSwSh_StartGame.h"
#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h"
#include "PokemonBDSP/PokemonBDSP_Settings.h"
#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h"
#include "CommonFramework/ImageTools/ColorClustering.h"
#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h"
#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h"
#include "PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h"
#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h"
#include "PokemonBDSP/Inference/PokemonBDSP_MapDetector.h"
#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h"
#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h"
#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h"
#include "PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h"
#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h"
#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h"
#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h"
#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h"
#include "PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h"
#include "PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h"
#include "PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h"
#include "PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h"
#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IVCheckerReader.h"
//#include "CommonFramework/BinaryImage/BinaryImage.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h"
#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h"
#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h"
#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h"
#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h"
#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h"
#include "PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h"
#include "CommonFramework/ImageMatch/SubObjectTemplateMatcher.h"
#include "CommonFramework/Inference/BlackBorderDetector.h"
#include "PokemonLA/Programs/PokemonLA_GameEntry.h"
#include "PokemonLA/PokemonLA_Settings.h"
#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h"
#include "PokemonLA/Inference/PokemonLA_MountDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h"
#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h"
#include "CommonFramework/Tools/InterruptableCommands.h"
#include "CommonFramework/Tools/SuperControlSession.h"
#include "PokemonLA/Programs/PokemonLA_FlagNavigationAir.h"
#include "CommonFramework/ImageMatch/WaterfillTemplateMatcher.h"
#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h"
#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h"
#include "PokemonLA/Inference/PokemonLA_NotificationReader.h"
#include "PokemonLA/Inference/PokemonLA_OutbreakReader.h"
#include "PokemonLA/Inference/PokemonLA_SelectedRegionDetector.h"
#include "PokemonLA/Inference/PokemonLA_MapDetector.h"
#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h"
#include "PokemonLA/Programs/PokemonLA_TradeRoutines.h"
#include "PokemonLA/Inference/PokemonLA_DialogDetector.h"
#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h"
#include "CommonFramework/Tools/MultiConsoleErrors.h"
#include "PokemonLA/Inference/PokemonLA_UnderAttackDetector.h"
#include "PokemonLA/Programs/PokemonLA_EscapeFromAttack.h"
#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h"
#include "CommonFramework/Inference/SpectrogramMatcher.h"
#include "CommonFramework/ImageMatch/WaterfillTemplateMatcher.h"
#include "TestProgramSwitch.h"
#include <immintrin.h>
#include <fstream>
#include <QHttpMultiPart>
#include <QFile>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
//#include <Windows.h>
#include <iostream>
using std::cout;
using std::endl;
//#include "../Internal/SerialPrograms/NintendoSwitch_Commands_ScalarButtons.h"
using namespace PokemonAutomation::Kernels;
using namespace PokemonAutomation::Kernels::Waterfill;
namespace PokemonAutomation{
namespace NintendoSwitch{
TestProgram_Descriptor::TestProgram_Descriptor()
: MultiSwitchProgramDescriptor(
"NintendoSwitch:TestProgram",
"Nintendo Switch", "Test Program (Switch)",
"",
"Test Program (Switch)",
FeedbackType::OPTIONAL_, true,
PABotBaseLevel::PABOTBASE_12KB,
1, 4, 1
)
{}
TestProgram::TestProgram(const TestProgram_Descriptor& descriptor)
: MultiSwitchProgramInstance(descriptor)
, LANGUAGE(
"<b>OCR Language:</b>",
{ Language::English }
)
, NOTIFICATION_TEST("Test", true, true, ImageAttachmentMode::JPG)
, NOTIFICATIONS({
&NOTIFICATION_TEST,
// &NOTIFICATION_ERROR_RECOVERABLE,
// &NOTIFICATION_ERROR_FATAL,
})
{
PA_ADD_OPTION(LANGUAGE);
PA_ADD_OPTION(NOTIFICATIONS);
}
//using namespace Kernels;
//using namespace Kernels::Waterfill;
using namespace PokemonLA;
void TestProgram::program(MultiSwitchProgramEnvironment& env){
using namespace Kernels;
using namespace Kernels::Waterfill;
using namespace OCR;
using namespace Pokemon;
// using namespace PokemonSwSh;
// using namespace PokemonBDSP;
using namespace PokemonLA;
LoggerQt& logger = env.logger();
ConsoleHandle& console = env.consoles[0];
BotBase& botbase = env.consoles[0];
VideoFeed& feed = env.consoles[0];
VideoOverlay& overlay = env.consoles[0];
#if 0
for (size_t c = 0; c < 10; c++){
QImage image("Digit-" + QString::number(c) + "-Original.png");
image = image.convertToFormat(QImage::Format::Format_ARGB32);
uint32_t* ptr = (uint32_t*)image.bits();
size_t words = image.bytesPerLine() / sizeof(uint32_t);
for (int r = 0; r < image.height(); r++){
for (int c = 0; c < image.width(); c++){
uint32_t& pixel = ptr[r * words + c];
uint32_t red = qRed(pixel);
uint32_t green = qGreen(pixel);
uint32_t blue = qBlue(pixel);
if (red < 0xa0 || green < 0xa0 || blue < 0xa0){
pixel = 0x00000000;
}
}
}
image.save("Digit-" + QString::number(c) + "-Template.png");
}
#endif
// QImage image("Distance-test.png");
QImage frame = feed.snapshot();
FlagTracker tracker(console, console);
tracker.process_frame(frame, std::chrono::system_clock::now());
double distance, flag_x, flag_y;
tracker.get(distance, flag_x, flag_y);
#if 0
ImageFloatBox box(flag_x - 0.017, flag_y - 0.055, 0.032, 0.025);
QImage image = extract_box(frame, box);
int c = 0;
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff);
// PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xffd0d0d0, 0xffffffff);
WaterFillIterator finder(matrix, 30);
WaterfillObject object;
while (finder.find_next(object)){
// Skip anything that touches the edge.
if (object.min_x == 0 || object.min_y == 0 ||
object.max_x + 1 == matrix.width() || object.max_y + 1 == matrix.height()
){
continue;
}
// extract_box(image, object).save("image-" + QString::number(c++) + ".png");
read_digit(image, object);
}
#endif
// goto_camp_from_jubilife(env, console, WarpSpot::ICELANDS_ICEPEAK_ARENA);
#if 0
QImage image("screenshot-20220309-005426729947.png");
MountDetector detector;
detector.detect(image);
#endif
#if 0
pbf_move_left_joystick(console, 0, 0, 50, 0);
pbf_press_button(console, BUTTON_B, 20, 250);
pbf_mash_button(console, BUTTON_ZL, 250);
pbf_press_button(console, BUTTON_HOME, 20, 230);
#endif
#if 0
{
QImage image("screenshot-20220306-163207833403.png");
// QImage image("screenshot-20220306-172029164014.png");
DialogSurpriseDetector detector(logger, overlay, true);
detector.process_frame(image, std::chrono::system_clock::now());
}
#endif
#if 0
{
QImage image("screenshot-20220302-094034596712.png");
DialogDetector detector(logger, overlay, true);
detector.process_frame(image, std::chrono::system_clock::now());
}
{
QImage image("screenshot-Gin");
DialogDetector detector(logger, overlay, true);
detector.process_frame(image, std::chrono::system_clock::now());
}
#endif
#if 0
InferenceBoxScope box0(console, {0.925, 0.100, 0.014, 0.030});
// QImage screen("screenshot-20220228-121927882824.png");
QImage screen = feed.snapshot();
QImage image = extract_box(screen, box0);
ImageStats stats = image_stats(image);
cout << stats.average << stats.stddev << endl;
bool ok = is_white(stats);
cout << ok << endl;
#endif
// throw UserSetupError(env.logger(), "asdf");
// throw OperationFailedException(env.logger(), "asdf");
// FlagNavigationAir session(env, console);
// session.run_session();
// goto_camp_from_overworld(env, console);
// InferenceBoxScope box(console, {0.450, 0.005, 0.040, 0.010});
// ImageStats stats = image_stats(extract_box(console.video().snapshot(), box));
// cout << stats.average << stats.stddev << endl;
#if 0
pbf_press_dpad(console, DPAD_UP, 20, 480);
pbf_press_button(console, BUTTON_A, 20, 480);
pbf_press_button(console, BUTTON_B, 20, 230);
pbf_press_button(console, BUTTON_B, 20, 230);
#endif
#if 0
auto& context = console;
pbf_move_left_joystick(context, 0, 212, 50, 0);
pbf_press_button(context, BUTTON_B, 500, 80);
pbf_move_left_joystick(context, 224, 0, 50, 0);
pbf_press_button(context, BUTTON_B, 350, 80);
pbf_move_left_joystick(context, 0, 64, 50, 0);
pbf_press_button(context, BUTTON_B, 250, 80);
pbf_move_left_joystick(context, 0, 96, 50, 0);
pbf_press_button(context, BUTTON_B, 500, 0);
#endif
#if 0
VideoOverlaySet set(overlay);
DialogDetector detector(console, console);
detector.make_overlays(set);
detector.process_frame(feed.snapshot(), std::chrono::system_clock::now());
#endif
#if 0
InferenceBoxScope box0(overlay, {0.010, 0.700, 0.050, 0.100});
QImage image = extract_box(feed.snapshot(), box0);
ArcPhoneDetector detector(console, console, std::chrono::milliseconds(200), true);
detector.process_frame(image, std::chrono::system_clock::now());
wait_until(
env, console, std::chrono::seconds(10),
{ &detector }
);
#endif
// from_professor_return_to_jubilife(env, console);
// InferenceBoxScope box0(overlay, {0.900, 0.955, 0.080, 0.045});
// InferenceBoxScope box1(overlay, {0.500, 0.621, 0.300, 0.043});
// EscapeFromAttack session(env, console);
// session.run_session();
// cout << "Done escaping!" << endl;
#if 0
MapDetector detector;
VideoOverlaySet overlays(overlay);
detector.make_overlays(overlays);
#endif
#if 0
ButtonDetector detector(
console, console,
ButtonType::ButtonA,
{0.55, 0.40, 0.20, 0.40},
std::chrono::milliseconds(200), true
);
VideoOverlaySet overlays(overlay);
detector.make_overlays(overlays);
detector.process_frame(feed.snapshot(), std::chrono::system_clock::now());
#endif
#if 0
UnderAttackWatcher watcher;
wait_until(
env, console,
std::chrono::seconds(60),
{ &watcher }
);
#endif
// InferenceBoxScope box(overlay, 0.49, 0.07, 0.02, 0.03);
// ImageStats stats = image_stats(extract_box(feed.snapshot(), box));
// cout << stats.average << stats.stddev << endl;
// return_to_jubilife_from_overworld(env, console);
#if 0
pbf_move_right_joystick(console, 0, 128, 145, 0);
pbf_move_left_joystick(console, 128, 0, 50, 0);
pbf_press_button(console, BUTTON_B, 500, 125);
pbf_move_right_joystick(console, 255, 128, 45, 0);
pbf_move_left_joystick(console, 128, 0, 50, 0);
pbf_press_button(console, BUTTON_B, 420, 125);
pbf_move_right_joystick(console, 0, 128, 100, 0);
pbf_move_left_joystick(console, 128, 0, 50, 0);
pbf_press_button(console, BUTTON_B, 420, 125);
#endif
#if 0
TradeNameReader reader(console, LANGUAGE, console);
reader.read(feed.snapshot());
InferenceBoxScope box(overlay, {0.920, 0.100, 0.020, 0.030});
QImage image = extract_box(feed.snapshot(), box);
ImageStats stats = image_stats(image);
cout << stats.average << stats.stddev << endl;
// is_white()
// std::map<std::string, int> catch_count;
#endif
#if 0
TradeStats stats;
MultiConsoleErrorState error_state;
env.run_in_parallel([&](ConsoleHandle& console){
trade_current_pokemon(env, console, error_state, stats);
});
#endif
// trade_current_pokemon(env, console, error_state, stats);
#if 0
QImage image("screenshot-20220213-141558364230.png");
// CenterAButtonTracker tracker;
// WhiteObjectWatcher detector(console, {0.40, 0.50, 0.40, 0.50}, {{tracker, false}});
// detector.process_frame(image, std::chrono::system_clock::now());
ButtonDetector detector(console, console, ButtonType::ButtonA, {0.40, 0.50, 0.40, 0.50});
AsyncVisualInferenceSession visual(env, console, console, console);
visual += detector;
#endif
// InferenceBoxScope box(overlay, 0.40, 0.50, 0.40, 0.50);
// cout << std::chrono::system_clock::time_point::min() - std::chrono::system_clock::now() << endl;
// pbf_move_right_joystick(console, 0, 128, 45, 0);
#if 0
pbf_move_right_joystick(console, 128, 255, 200, 0);
pbf_move_right_joystick(console, 128, 0, 200, 0);
pbf_move_right_joystick(console, 128, 255, 80, 0);
pbf_move_right_joystick(console, 0, 128, 400, 0);
pbf_move_right_joystick(console, 128, 255, 120, 0);
pbf_move_right_joystick(console, 0, 128, 400, 0);
pbf_move_right_joystick(console, 128, 0, 200, 0);
pbf_move_right_joystick(console, 0, 128, 400, 0);
#endif
#if 0
FlagTracker flag(logger, overlay);
MountTracker mount(logger);
{
AsyncVisualInferenceSession visual(env, console, console, console);
visual += flag;
visual += mount;
AsyncCommandSession commands(env, console.botbase());
while (true){
// commands.dispatch([=](const BotBaseContext& context){
// pbf_move_right_joystick(context, 0, 128, 5 * TICKS_PER_SECOND, 0);
// });
// commands.wait();
double flag_distance, flag_x, flag_y;
bool flag_ok = flag.get(flag_distance, flag_x, flag_y);
if (flag_ok && 0.4 < flag_x && flag_x < 0.6 && flag_y > 0.6){
commands.dispatch([=](const BotBaseContext& context){
pbf_press_button(context, BUTTON_B, 300 * TICKS_PER_SECOND, 0);
});
}
}
commands.stop_session();
visual.stop();
}
#endif
#if 0
MountDetector mount_detector;
FlagDetector flags;
WhiteObjectWatcher watcher(console, {{flags, false}});
QImage image(feed.snapshot());
MountState mount_state = mount_detector.detect(image);
cout << MOUNT_STATE_STRINGS[(int)mount_state] << endl;
// watcher.process_frame(image, std::chrono::system_clock::now());
// flags.detections()
#endif
#if 0
QImage image("screenshot-20220211-023701107827.png");
FlagDetector flags;
WhiteObjectWatcher watcher(
console,
{{flags, false}}
);
watcher.process_frame(image, std::chrono::system_clock::now());
#endif
#if 0
QImage image(feed.snapshot());
// QImage image("screenshot-20220210-231922898436.png");
// QImage image("screenshot-20220211-005950586653.png");
// QImage image("screenshot-20220211-012426947705.png");
// QImage image("screenshot-20220211-014247032114.png");
// QImage image("screenshot-20220211-022344759878.png");
HmDetector detector(overlay);
cout << HM_STATE_STRINGS[(int)detector.detect(image)] << endl;
#endif
#if 0
InferenceBoxScope box(overlay, 0.905, 0.65, 0.08, 0.13);
QImage image = extract_box(feed.snapshot(), box);
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(
image,
192, 255,
192, 255,
0, 255
);
std::vector<WaterfillObject> objects = find_objects_inplace(matrix, 20, false);
ImagePixelBox result;
for (const WaterfillObject& object : objects){
int c = 0;
for (const auto& object : objects){
extract_box(image, object).save("test-" + QString::number(c++) + ".png");
}
if (HmWyrdeerMatcher::on().matches(result, image, object)){
cout << "Wyrdeer On" << endl;
}
#if 0
if (HmWyrdeerMatcher::off().matches(result, image, object)){
cout << "Wyrdeer Off" << endl;
}
if (HmWyrdeerMatcher::on().matches(result, image, object)){
cout << "Wyrdeer On" << endl;
}
if (HmUrsalunaMatcher::off().matches(result, image, object)){
cout << "Ursaluna Off" << endl;
}
if (HmUrsalunaMatcher::on().matches(result, image, object)){
cout << "Ursaluna On" << endl;
}
if (HmSneaslerMatcher::off().matches(result, image, object)){
cout << "Sneasler Off" << endl;
}
if (HmSneaslerMatcher::on().matches(result, image, object)){
cout << "Sneasler On" << endl;
}
if (HmBraviaryMatcher::off().matches(result, image, object)){
cout << "Braviary Off" << endl;
}
if (HmBraviaryMatcher::on().matches(result, image, object)){
cout << "Braviary On" << endl;
}
#endif
}
#endif
#if 0
InferenceBoxScope box(overlay, 0.905, 0.65, 0.08, 0.13);
QImage image = extract_box(feed.snapshot(), box);
// QImage image("test.png");
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(
image,
128, 255,
128, 255,
0, 255
);
std::vector<WaterfillObject> objects = find_objects_inplace(matrix, 20, false);
cout << objects.size() << endl;
// int c = 0;
// for (const auto& object : objects){
// extract_box(image, object).save("test-" + QString::number(c++) + ".png");
// }
#if 1
WaterfillObject object;
for (const WaterfillObject& obj : objects){
object.merge_assume_no_overlap(obj);
}
ImagePixelBox sbox(object.min_x, object.min_y, object.max_x, object.max_y);
extract_box(image, sbox).save("test.png");
#endif
#endif
// QImage image("2054071609223400_s.jpg");
// SelectionArrowFinder arrow_detector(console, ImageFloatBox(0.350, 0.450, 0.500, 0.400));
// arrow_detector.detect(image);
#if 0
// ArcWatcher arcs(overlay);
// BubbleWatcher bubbles(overlay);
BubbleDetector bubbles;
ArcDetector arcs;
QuestMarkDetector quest_marks;
WhiteObjectWatcher watcher(
overlay,
{{bubbles, false}, {arcs, false}, {quest_marks, false}}
);
// watcher.process_frame(feed.snapshot(), std::chrono::system_clock::now());
#if 1
{
VisualInferenceSession session(env, logger, feed, overlay);
session += watcher;
session.run();
}
#endif
#endif
#if 0
// InferenceBoxScope box(overlay, 0.40, 0.50, 0.40, 0.50);
InferenceBoxScope box(overlay, 0.010, 0.700, 0.050, 0.100);
QImage image(feed.snapshot());
image = extract_box(image, box);
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(
image,
128, 255,
128, 255,
128, 255
);
std::vector<WaterfillObject> objects = find_objects_inplace(matrix, 20, false);
cout << objects.size() << endl;
int c = 0;
for (const auto& object : objects){
extract_box(image, object).save("test-" + QString::number(c++) + ".png");
}
#endif
// ShinySymbolWatcher watcher(overlay, SHINY_SYMBOL_BOX_BOTTOM);
// watcher.process_frame(feed.snapshot(), std::chrono::system_clock::now());
// ArcDetector detector;
// QImage image("screenshot-20220124-212851483502.png");
// QImage image(feed.snapshot());
// find_arcs(image);
#if 0
QImage image0("test-image.png");
QImage image1("test-sprite.png");
for (int r = 0; r < image0.height(); r++){
for (int c = 0; c < image0.width(); c++){
uint32_t pixel1 = image1.pixel(c, r);
if ((pixel1 >> 24) == 0){
image0.setPixel(c, r, 0xff00ff00);
}
}
}
image0.save("test.png");
#endif
#if 0
QImage image("screenshot-20220124-212851483502.png");
InferenceBoxScope box(overlay, 0.4, 0.4, 0.2, 0.2);
image = extract_box(image, box);
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(
image,
128, 255,
128, 255,
128, 255
);
std::vector<WaterfillObject> objects = find_objects_inplace(matrix, 20, false);
cout << objects.size() << endl;
int c = 0;
for (const auto& object : objects){
extract_box(image, object).save("test-" + QString::number(c++) + ".png");
}
// WaterfillObject object = objects[1];
// object.merge_assume_no_overlap(objects[2]);
// extract_box(image, object).save("test.png");
#endif
#if 0
QImage image("MountOn-Wyrdeer-Template.png");
image = image.convertToFormat(QImage::Format::Format_ARGB32);
uint32_t* ptr = (uint32_t*)image.bits();
size_t words = image.bytesPerLine() / sizeof(uint32_t);
for (int r = 0; r < image.height(); r++){
for (int c = 0; c < image.width(); c++){
uint32_t& pixel = ptr[r * words + c];
uint32_t red = qRed(pixel);
uint32_t green = qGreen(pixel);
uint32_t blue = qBlue(pixel);
if (red < 0xa0 || green < 0xa0 || blue < 0xa0){
pixel = 0x00000000;
}
}
}
image.save("MountOn-Wyrdeer-Template-1.png");
#endif
#if 0
QImage image("screenshot-20220123-225755803973.png");
InferenceBoxScope box(overlay, 0.32, 0.87, 0.03, 0.04);
image = extract_box(image, box);
PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(
image,
128, 255,
128, 255,
128, 255
);
std::vector<WaterfillObject> objects = find_objects_inplace(matrix, 20, false);
cout << objects.size() << endl;
// int c = 0;
// for (const auto& object : objects){
// extract_box(image, object).save("test-" + QString::number(c++) + ".png");
// }
WaterfillObject object = objects[0];
object.merge_assume_no_overlap(objects[1]);
extract_box(image, object).save("Sparkle.png");
#endif
#if 0
BlackBorderDetector detector;
VideoOverlaySet overlays(overlay);
detector.make_overlays(overlays);
detector.detect(feed.snapshot());
#endif
#if 0
ExperienceGainDetector detector;
VideoOverlaySet overlays(overlay);
detector.make_overlays(overlays);
detector.detect(feed.snapshot());
#endif
#if 0
ShinyEncounterTracker tracker(logger, overlay, BattleType::STANDARD);
{
VisualInferenceSession session(env, console, feed, overlay);
session += tracker;
session.run();
}
DoublesShinyDetection wild_result;
ShinyDetectionResult your_result;
determine_shiny_status(
logger,
wild_result, your_result,
tracker.dialog_tracker(),
tracker.sparkles_wild_overall(),
tracker.sparkles_wild_left(),
tracker.sparkles_wild_right(),
tracker.sparkles_own()
);
#if 0
determine_shiny_status(
logger,
SHINY_BATTLE_REGULAR,
tracker.dialog_timer(),
tracker.sparkles_wild()
);
#endif
#endif
#if 0
VisualInferenceSession session(env, feed, overlay);
ShinySparkleTracker tracker(overlay);
session += tracker;
session.run();
#endif
#if 0
QImage image = feed.snapshot();
PokemonSwSh::SparkleSet sparkles = PokemonSwSh::find_sparkles(image);
VideoOverlaySet overlays(overlay);
sparkles.draw_boxes(overlays, image, {0, 0, 1, 1});
#endif
#if 0
Kernels::PackedBinaryMatrix matrix0;
matrix0 = compress_rgb32_to_binary_min(image, 192, 192, 0);
// std::vector<WaterfillObject> objects = find_objects_inplace(matrix0, 10, false);
WaterFillIterator finder(matrix0, 20);
WaterfillObject object;
size_t c = 0;
VideoOverlaySet overlays(overlay);
while (finder.find_next(object)){
image.copy(object.min_x, object.min_y, object.width(), object.height()).save("test-" + QString::number(c) + ".png");
cout << c++ << endl;
PokemonSwSh::RadialSparkleDetector radial(object);
if (radial.is_ball()){
overlays.add(
COLOR_GREEN,
translate_to_parent(
image, {0, 0, 1, 1},
{object.min_x, object.min_y, object.max_x, object.max_y}
)
);
continue;
}
if (radial.is_star()){
overlays.add(
COLOR_BLUE,
translate_to_parent(
image, {0, 0, 1, 1},
{object.min_x, object.min_y, object.max_x, object.max_y}
)
);
continue;
}
if (PokemonSwSh::is_line_sparkle(object, image.width() * 0.25)){
overlays.add(
COLOR_YELLOW,
translate_to_parent(
image, {0, 0, 1, 1},
{object.min_x, object.min_y, object.max_x, object.max_y}
)
);
continue;
}
if (PokemonSwSh::is_square_sparkle(object)){
overlays.add(
COLOR_MAGENTA,
translate_to_parent(
image, {0, 0, 1, 1},
{object.min_x, object.min_y, object.max_x, object.max_y}
)
);
}
}
#endif
// PokemonSwSh::SelectionArrowFinder finder(overlay, ImageFloatBox(0.640, 0.600, 0.055, 0.380));
// QImage image("screenshot-20220108-185053570093.png");
// cout << finder.detect(image) << endl;
// QImage image("20220111-124433054843-PathPartyReader-ReadHP.png");
// QImage image("20220116-044701249467-ReadPathSide.png");
// cout << (int)PokemonSwSh::MaxLairInternal::read_side(image) << endl;
#if 0
QImage image("20220116-053836954926-ReadPath.png");
std::multimap<double, std::pair<PokemonType, ImagePixelBox>> candidates = PokemonSwSh::find_symbols(image, 0.20);
// std::deque<InferenceBoxScope> hits;
// hits.clear();
cout << "---------------" << endl;
for (const auto& item : candidates){
cout << get_type_slug(item.second.first) << ": " << item.first << endl;
// hits.emplace_back(overlay, translate_to_parent(screen, box, item.second.second), COLOR_GREEN);
}
#endif
// QImage image("20220111-124433054843-PathPartyReader-ReadHP.png");
// NintendoSwitch::PokemonSwSh::MaxLairInternal::PathReader detector(overlay, 0);
// double hp[4];
// detector.read_hp(logger, image, hp);
#if 0
MapDetector detector;
VideoOverlaySet set(overlay);
detector.make_overlays(set);
cout << detector.detect(feed.snapshot()) << endl;
#endif
// QImage image("screenshot-20220108-185053570093.png");
// PokemonSwSh::MaxLairInternal::BattleMenuReader reader(overlay, Language::English);
// cout << reader.can_dmax(image) << endl;
// SelectionArrowFinder detector(overlay, {0.50, 0.58, 0.40, 0.10}, COLOR_RED);
// detector.detect(feed.snapshot());
// InferenceBoxScope box(overlay, {0.23, 0.30, 0.35, 0.30});
#if 0
QImage image("screenshot-20220103-011451179122.png");
PackedBinaryMatrix matrix = filter_rgb32_range(
image,
192, 255,
0, 160,
0, 192
);
std::vector<WaterfillObject> objects = find_objects(matrix, 100, false);
VideoOverlaySet set(overlay);
size_t c = 0;
for (const WaterfillObject& object : objects){
ImagePixelBox box(object.min_x, object.min_y, object.max_x, object.max_y);
ImageFloatBox fbox = translate_to_parent(image, {0, 0, 1, 1}, box);
set.add(COLOR_RED, fbox);
image.copy(object.min_x, object.min_y, object.width(), object.height()).save("test-" + QString::number(c++) + ".png");
}
#endif
#if 0
QImage image("ExclamationTop-0.png");
for (int r = 0; r < image.height(); r++){
for (int c = 0; c < image.width(); c++){
uint32_t pixel = image.pixel(c, r);
cout << "(" << qRed(pixel) << "," << qGreen(pixel) << "," << qBlue(pixel) << ")";
}
cout << endl;
}
#endif
#if 0
QImage image("QuestionTop-0.png");
image = image.convertToFormat(QImage::Format_ARGB32);
uint32_t* ptr = (uint32_t*)image.bits();
size_t words = image.bytesPerLine() / sizeof(uint32_t);
for (int r = 0; r < image.height(); r++){
for (int c = 0; c < image.width(); c++){
uint32_t pixel = ptr[r*words + c];
if (qRed(pixel) + qGreen(pixel) + qBlue(pixel) < 50){
ptr[r*words + c] = 0;
}
}
}
image.save("QuestionTop-1.png");
#endif
#if 0
cout << std::hex << QColor("green").rgb() << endl;
cout << std::hex << QColor(Qt::green).rgb() << endl;
cout << std::hex << QColor(Qt::darkGreen).rgb() << endl;
cout << std::hex << QColor(Qt::darkCyan).rgb() << endl;
#endif
#if 0
QImage image("screenshot-20211227-082121670685.png");
image = extract_box(image, ImageFloatBox({0.95, 0.10, 0.05, 0.10}));
image.save("test.png");
BinaryImage binary_image = filter_rgb32_range(
image,
255, 255,
128, 255,
0, 128,
0, 128
);
cout << binary_image.dump() << endl;
#endif
#if 0
ShortDialogDetector detector;
OverlaySet overlays(overlay);
detector.make_overlays(overlays);
cout << detector.detect(QImage("20211228-013942613330.jpg")) << endl;
// cout << detector.detect(feed.snapshot()) << endl;
#endif
#if 0
BoxShinyDetector detector;
cout << detector.detect(QImage("20211226-031611120900.jpg")) << endl;
// pbf_mash_button(console, BUTTON_X, 10 * TICKS_PER_SECOND);
#endif
#if 0
BattleMenuDetector detector(BattleType::WILD);
OverlaySet overlays(overlay);
detector.make_overlays(overlays);
#endif
env.wait_for(std::chrono::seconds(60));
}
}
}
| 31.134831 | 127 | 0.6617 | BlizzardHero |
856472542cd47e4ec940c97e2ba7719c79562fe7 | 1,484 | cc | C++ | CodeChef/SHORT/COOK65/Problem B/B.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | CodeChef/SHORT/COOK65/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | CodeChef/SHORT/COOK65/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define func __FUNCTION__
#define line __LINE__
using namespace std;
template<typename S, typename T>
ostream& operator<<(ostream& out, pair<S, T> const& p){out<<'('<<p.fi<<", "<<p.se<<')'; return out;}
template<typename T>
ostream& operator<<(ostream& out, vector<T> const & v){
int l = v.size(); for(int i = 0; i < l-1; i++) out<<v[i]<<' '; if(l>0) out<<v[l-1]; return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
typedef long long ll;
typedef pair<int,int> pii;
const int M = (1<<27);
const ll MOD = (1ll<<32);
int q;
ll s, a, b, sum;
short h[M];
int main(){
sd(q);
sd3(s,a,b);
int tmp, x, y;
while(q--){
tmp = s >> 1;
x = tmp >> 27;
y = (tmp&(M-1));
if(s&1){
if(((h[y]>>x)&1) == 0){
h[y] ^= (1<<x);
sum += tmp;
}
}
else{
if(((h[y]>>x)&1) > 0){
h[y] ^= (1<<x);
sum -= tmp;
}
}
s = (s*a + b)%MOD;
}
printf("%lld\n", sum);
return 0;
}
| 20.328767 | 100 | 0.557951 | VastoLorde95 |
8566a3fc64a064df90c9167e4d1799fd8b24e576 | 768 | cpp | C++ | Topics/2015_05_03/quiz.cpp | TelerikAcademy/C-Beginner | a4d5a8beb870da910f74da41362b02f0d754ee51 | [
"MIT"
] | null | null | null | Topics/2015_05_03/quiz.cpp | TelerikAcademy/C-Beginner | a4d5a8beb870da910f74da41362b02f0d754ee51 | [
"MIT"
] | null | null | null | Topics/2015_05_03/quiz.cpp | TelerikAcademy/C-Beginner | a4d5a8beb870da910f74da41362b02f0d754ee51 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
bool is_prime(long long a){
long long x=sqrt(a), i;
if (a%2==0){
if (a==2) {return true;}
else {return false;}
}
for (i=3; i<=x; i=i+2){
if (a%i==0) {return false;}
}
return true;
}
int main () {
long long n,m,i,j,brc,st10;
long long kcifri[4]={1,3,7,9};
cin >> n;
for (i=0;i<4;i=i+1) {
m=n*10+kcifri[i];
if (is_prime(m)) {
cout << m << endl;
return 0;
}
}
for (brc=1, st10=10;true;brc=brc+1,st10=st10*10){
for (j=0;j<st10; j=j+1){
for (i=0;i<4;i=i+1) {
m=(n*st10+j)*10+kcifri[i];
if (is_prime(m)) {
cout << m << endl;
return 0;
}
}
}
}
}
| 18.285714 | 52 | 0.451823 | TelerikAcademy |
85676711a5e512403a8f0422642f1b0912792d53 | 1,045 | cpp | C++ | 500 problems pepcoding/Subarray with given sum.cpp | shikhar8434/OJ-problems | 7e787b41fd8b6342f73ee59066e2a324608c511d | [
"MIT"
] | 2 | 2020-10-13T12:37:15.000Z | 2020-10-28T14:29:15.000Z | 500 problems pepcoding/Subarray with given sum.cpp | shikhar8434/OJ-problems | 7e787b41fd8b6342f73ee59066e2a324608c511d | [
"MIT"
] | null | null | null | 500 problems pepcoding/Subarray with given sum.cpp | shikhar8434/OJ-problems | 7e787b41fd8b6342f73ee59066e2a324608c511d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define ll long long int
#define vi vector<int>
#define vii vector<int, int>
#define vc vector<char>
#define vl vector<ll>
#define mod 1000000007
#define INF 1000000009
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--) {
int n, k;
cin >> n >> k;
vi A(n);
for(int i = 0 ; i < n; i++) {
cin >> A[i];
}
int l = 0, r = 0;
int curr_sum = A[0];
bool flag = 0;
for(int i = 1 ; i <= n; i++) {
while(curr_sum > k and l < i-1) {
curr_sum -= A[l];
l++;
}
if(curr_sum == k) {
cout << l + 1 << " " << i << "\n";
flag =1;
break;
}
if(i < n) {
curr_sum += A[i];
}
}
if(!flag)
cout << "-1\n";
}
return 0;
} | 18.017241 | 43 | 0.42488 | shikhar8434 |
85677ce7bc7152934b8d1ae4e3bc98f3c6353c32 | 3,470 | hpp | C++ | include/Xyz/LineClipping.hpp | jebreimo/Xyz | 654e22412fc505c5f6a385992a6f5c7e6ab3cc3c | [
"BSD-2-Clause"
] | null | null | null | include/Xyz/LineClipping.hpp | jebreimo/Xyz | 654e22412fc505c5f6a385992a6f5c7e6ab3cc3c | [
"BSD-2-Clause"
] | null | null | null | include/Xyz/LineClipping.hpp | jebreimo/Xyz | 654e22412fc505c5f6a385992a6f5c7e6ab3cc3c | [
"BSD-2-Clause"
] | null | null | null | //****************************************************************************
// Copyright © 2017 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 24.04.2017.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#pragma once
#include <utility>
#include "LineSegment.hpp"
#include "Rectangle.hpp"
namespace Xyz
{
constexpr unsigned OUTCODE_INSIDE = 0;
constexpr unsigned OUTCODE_LEFT = 0b0001;
constexpr unsigned OUTCODE_RIGHT = 0b0010;
constexpr unsigned OUTCODE_BOTTOM = 0b0100;
constexpr unsigned OUTCODE_TOP = 0b1000;
template <typename T>
unsigned computeClippingOutcode(const Rectangle<T>& rectangle,
const Vector<T, 2>& point)
{
auto [x, y] = point;
auto [x0, y0] = rectangle.min();
auto [x1, y1] = rectangle.max();
unsigned code = OUTCODE_INSIDE;
if (x1 < x)
code = OUTCODE_RIGHT;
else if (x < x0)
code = OUTCODE_LEFT;
if (y1 < y)
code += OUTCODE_TOP;
else if (y < y0)
code += OUTCODE_BOTTOM;
return code;
}
/** @brief Returns the relative start and end positions of @a line
* inside @a rectangle.
*
* Uses the Cohen-Sutherland algorithm to compute the relative positions.
*
* @tparam T a numeric type.
* @param rectangle the clipping rectangle.
* @param line the line that will be clipped.
* @return the relative start and end positions of the part of @a line
* that lies inside @a rectangle. Both positions will be between
* 0 and 1, unless @a line is completely outside @a rectangle in
* which case both positions are -1.
*/
template <typename T>
std::pair<double, double> getClippingPositions(
const Rectangle<T>& rectangle, const LineSegment<T, 2>& line)
{
auto startCode = computeClippingOutcode(rectangle, line.start());
auto endCode = computeClippingOutcode(rectangle, line.end());
double tStart = 0.0, tEnd = 1.0;
for (;;)
{
if (!(startCode | endCode))
return {tStart, tEnd};
if (startCode & endCode)
return {-1.0, -1.0};
auto start = line.start();
auto vector = line.end() - line.start();
auto bottomLeft = rectangle.min();
auto topRight = rectangle.max();
unsigned code = startCode ? startCode : endCode;
double t;
if (code & OUTCODE_TOP)
t = (get<1>(topRight) - get<1>(start)) / get<1>(vector);
else if (code & OUTCODE_BOTTOM)
t = (get<1>(bottomLeft) - get<1>(start)) / get<1>(vector);
else if (code & OUTCODE_LEFT)
t = (get<0>(bottomLeft) - get<0>(start)) / get<0>(vector);
else
t = (get<0>(topRight) - get<0>(start)) / get<0>(vector);
auto point = start + t * vector;
if (code == startCode)
{
tStart = t;
startCode = computeClippingOutcode(rectangle, point);
}
else
{
tEnd = t;
endCode = computeClippingOutcode(rectangle, point);
}
}
}
}
| 34.356436 | 78 | 0.52853 | jebreimo |
85696b81b51a00bf54ab18b733ba63df7b15bcd2 | 1,710 | hpp | C++ | include/put.hpp | Leonardo2718/btrio | 67941bc4a5b1d6bc637e3b1ffd75cdbcaddbdba7 | [
"BSL-1.0"
] | null | null | null | include/put.hpp | Leonardo2718/btrio | 67941bc4a5b1d6bc637e3b1ffd75cdbcaddbdba7 | [
"BSL-1.0"
] | null | null | null | include/put.hpp | Leonardo2718/btrio | 67941bc4a5b1d6bc637e3b1ffd75cdbcaddbdba7 | [
"BSL-1.0"
] | null | null | null | /**
* Copyright Leonardo Banderali 2017 - 2017.
* 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 PUT_HPP
#define PUT_HPP
#include "format.hpp"
#include "put_utils.hpp"
#include "basic_put.hpp"
#include <cstdio>
#define USE_PPUT 0
namespace btrio {
//~ iput ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename OutputIterator, typename T, typename F = btrio::default_format>
OutputIterator iput(OutputIterator begin, OutputIterator end, T arg) {
auto cursor = begin;
return basic_put<F>(arg, [&](auto c){ *cursor = c; ++cursor; return cursor; }, [&](auto i){ return i == end; }, cursor);
}
template <typename OutputIterator, typename T, typename F>
OutputIterator iput(OutputIterator begin, OutputIterator end, btrio::formatted_value<F, T> arg) {
auto cursor = begin;
return basic_put<F>(arg.value, [&](auto c){ *cursor = c; ++cursor; return cursor; }, [&](auto i){ return i == end; }, cursor);
}
//~ fput ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename T, typename F = btrio::default_format>
auto fput(T&& arg, FILE* f) {
return basic_put<F>(std::forward<T>(arg), std::putc, [](auto r){ return r == EOF; }, 0, f);
}
template <typename T, typename F>
auto fput(btrio::formatted_value<F, T> arg, FILE* f) {
return basic_put<F>(arg.value, std::putc, [](auto r){ return r == EOF; }, 0, f);
}
//~ put ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename T> void put(T arg) { put(arg, stdout); }
}
#endif // PUT_HPP
| 31.666667 | 130 | 0.580117 | Leonardo2718 |
856a124ab0f9a59e5777d742161ef3d253753311 | 2,143 | hpp | C++ | gearoenix/render/engine/gx-rnd-eng-configuration.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/render/engine/gx-rnd-eng-configuration.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/render/engine/gx-rnd-eng-configuration.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_RENDER_ENGINE_CONFIGURATION_HPP
#define GEAROENIX_RENDER_ENGINE_CONFIGURATION_HPP
#include "../../core/gx-cr-build-configuration.hpp"
#include "../../core/gx-cr-static.hpp"
#include "../../math/gx-math-numeric.hpp"
#include "../../system/gx-sys-log.hpp"
#include <cstdint>
namespace gearoenix::render::engine {
struct Configuration {
GX_GETSET_VAL_PRV(std::int8_t, shadow_cascades_count, GX_MAX_SHADOW_CASCADES)
GX_GETSET_VAL_PRV(std::uint16_t, runtime_reflection_environment_resolution, GX_DEFAULT_RUNTIME_REFLECTION_ENVIRONMENT_RESOLUTION)
GX_GETSET_VAL_PRV(std::uint16_t, runtime_reflection_irradiance_resolution, GX_DEFAULT_RUNTIME_REFLECTION_IRRADIANCE_RESOLUTION)
GX_GETSET_VAL_PRV(std::uint32_t, maximum_cpu_render_memory_size, 512 * 1024 * 1024)
GX_GETSET_VAL_PRV(std::uint32_t, maximum_gpu_render_memory_size, 256 * 1024 * 1024)
GX_GETSET_VAL_PRV(std::uint32_t, maximum_gpu_buffer_size, 64 * 1024 * 1024)
GX_GETSET_VAL_PRV(std::uint16_t, brdflut_resolution, GX_DEFAULT_BRDFLUT_RESOLUTION)
GX_GET_VAL_PRV(std::uint16_t, runtime_reflection_radiance_resolution, GX_DEFAULT_RUNTIME_REFLECTION_RADIANCE_RESOLUTION)
GX_GET_VAL_PRV(std::uint8_t, runtime_reflection_radiance_levels, 1)
constexpr Configuration() noexcept
{
set_runtime_reflection_radiance_resolution(runtime_reflection_radiance_resolution);
}
constexpr void set_runtime_reflection_radiance_resolution(const std::uint16_t r) noexcept
{
runtime_reflection_radiance_resolution = r;
runtime_reflection_radiance_levels = static_cast<std::uint8_t>(math::Numeric::floor_log2(r) - 2);
}
static int compute_runtime_reflection_radiance_levels(const int r) noexcept
{
#ifdef GX_DEBUG_MODE
if (r <= 0) {
GXLOGF("Resolution(" << r << ") can not be equal or less than zero.")
}
#endif
const auto l = math::Numeric::floor_log2(r);
#ifdef GX_DEBUG_MODE
if (l <= 2) {
GXLOGF("Logarithm of 2 of Resolution(" << r << ") = " << l << " can not be equal or less than 2.")
}
#endif
return l - 2;
}
};
}
#endif | 43.734694 | 133 | 0.74475 | Hossein-Noroozpour |
856a8b2d450d1f93a9bdf07f813386f156422476 | 360 | cc | C++ | src/gb/utils/test.cc | jonatan-ekstrom/FreshBoy | 228302e720f4a8fe4bf5c911e86588e412c0ce0a | [
"MIT"
] | 3 | 2021-11-30T20:37:33.000Z | 2022-01-06T20:26:52.000Z | src/gb/utils/test.cc | jonatan-ekstrom/FreshBoy | 228302e720f4a8fe4bf5c911e86588e412c0ce0a | [
"MIT"
] | null | null | null | src/gb/utils/test.cc | jonatan-ekstrom/FreshBoy | 228302e720f4a8fe4bf5c911e86588e412c0ce0a | [
"MIT"
] | null | null | null | #include "types.h"
namespace {
/* Compile time test to verify that integers are at least 32-bits wide. */
using namespace gb;
constexpr uint BitCount() {
auto i{static_cast<uint>(-1)};
uint count{0};
while (i != 0) {
i >>= 1;
++count;
}
return count;
}
static_assert(BitCount() >= 32, "16-bit ints not supported.");
}
| 16.363636 | 74 | 0.594444 | jonatan-ekstrom |
85701f1cad53f89ee8392100a78788862b8f9e2e | 568 | cpp | C++ | mytools/asm/SymbolTable.cpp | kingnak/nand2tetris | 120be8f04251b88e519f1bac838c40fd4c1b68e1 | [
"MIT"
] | null | null | null | mytools/asm/SymbolTable.cpp | kingnak/nand2tetris | 120be8f04251b88e519f1bac838c40fd4c1b68e1 | [
"MIT"
] | null | null | null | mytools/asm/SymbolTable.cpp | kingnak/nand2tetris | 120be8f04251b88e519f1bac838c40fd4c1b68e1 | [
"MIT"
] | null | null | null | #include "SymbolTable.h"
using namespace std;
void SymbolTable::addFixedEntry(const string &symbol, int16_t address)
{
m_map.insert(make_pair(symbol, address));
}
int16_t SymbolTable::addVariableEntry(const std::string &symbol)
{
m_map.insert(make_pair(symbol, m_nextVariable));
return m_nextVariable++;
}
bool SymbolTable::contains(const string &symbol) const
{
return m_map.find(symbol) != m_map.cend();
}
int16_t SymbolTable::getAddress(const string &symbol) const
{
auto it = m_map.find(symbol);
if (it == m_map.cend()) return -1;
return it->second;
}
| 21.037037 | 70 | 0.742958 | kingnak |
8572d407a4dd363db5f244fdc0af278010b6e859 | 7,484 | hpp | C++ | src/v8bind/class.hpp | ayles/V8Bind | 1ed1bf8b87f9a1f52d510e4ece77f3ff17a944d1 | [
"MIT"
] | 1 | 2021-12-30T15:08:40.000Z | 2021-12-30T15:08:40.000Z | src/v8bind/class.hpp | ayles/V8Bind | 1ed1bf8b87f9a1f52d510e4ece77f3ff17a944d1 | [
"MIT"
] | 1 | 2020-02-05T21:52:17.000Z | 2020-02-07T19:21:37.000Z | src/v8bind/class.hpp | ayles/v8bind | 1ed1bf8b87f9a1f52d510e4ece77f3ff17a944d1 | [
"MIT"
] | null | null | null | //
// Created by selya on 01.09.2019.
//
#ifndef SANDWICH_V8B_CLASS_HPP
#define SANDWICH_V8B_CLASS_HPP
#include <v8bind/type_info.hpp>
#include <v8.h>
#include <unordered_map>
#include <type_traits>
#include <memory>
#include <vector>
#include <cstddef>
#include <tuple>
#define V8B_IMPL inline
namespace v8b {
class PointerManager {
friend class ClassManager;
protected:
virtual void EndObjectManage(void *ptr) = 0;
public:
template<typename T>
static std::enable_if_t<std::is_base_of_v<PointerManager, T>, T &> GetInstance() {
static T instance;
return instance;
}
};
class ClassManager : public PointerManager {
public:
const TypeInfo type_info;
using ConstructorFunction = void * (*)(const v8::FunctionCallbackInfo<v8::Value> &);
using DestructorFunction = void (*)(v8::Isolate *, void *);
ClassManager(v8::Isolate *isolate, const TypeInfo &type_info);
~ClassManager();
// Delete unwanted constructors and operators
ClassManager(const ClassManager &) = delete;
ClassManager &operator=(const ClassManager &) = delete;
ClassManager &operator=(ClassManager &&) = delete;
// Leave constructor with move semantics
ClassManager(ClassManager &&) = default;
void RemoveObject(void *ptr);
void RemoveObjects();
v8::Local<v8::Object> FindObject(void *ptr) const;
v8::Local<v8::Object> WrapObject(void *ptr, bool take_ownership);
v8::Local<v8::Object> WrapObject(void *ptr, PointerManager *pointer_manager);
void SetPointerManager(void *ptr, PointerManager *pointer_manager);
void *UnwrapObject(v8::Local<v8::Value> value);
[[nodiscard]]
v8::Local<v8::FunctionTemplate> GetFunctionTemplate() const;
void SetBase(const TypeInfo &type_info,
void *(*base_to_this)(void *), void *(*this_to_base)(void *));
void SetConstructor(ConstructorFunction constructor_function);
void SetDestructor(DestructorFunction destructor_function);
void SetAutoWrap(bool auto_wrap = true);
[[nodiscard]]
bool IsAutoWrapEnabled() const;
[[nodiscard]]
v8::Isolate *GetIsolate() const;
protected:
void EndObjectManage(void *ptr) override;
private:
struct WrappedObject {
void *ptr;
v8::Global<v8::Object> wrapped_object;
PointerManager *pointer_manager;
};
WrappedObject &FindWrappedObject(void *ptr, void **base_ptr_ptr = nullptr) const;
void ResetObject(WrappedObject &object);
std::unordered_map<void *, WrappedObject> objects;
v8::Isolate *isolate;
v8::Persistent<v8::FunctionTemplate> function_template;
ConstructorFunction constructor_function;
DestructorFunction destructor_function;
struct BaseClassInfo {
ClassManager *base_class_manager = nullptr;
void *(*base_to_this)(void *) = nullptr;
void *(*this_to_base)(void *) = nullptr;
};
BaseClassInfo base_class_info;
std::vector<ClassManager *> derived_class_managers;
bool auto_wrap;
};
class ClassManagerPool {
public:
template<typename T>
static ClassManager &Get(v8::Isolate *isolate);
static ClassManager &Get(v8::Isolate *isolate, const TypeInfo &type_info);
static void Remove(v8::Isolate *isolate, const TypeInfo &type_info);
static void RemoveAll(v8::Isolate *isolate);
private:
std::vector<std::unique_ptr<ClassManager>> managers;
static std::unordered_map<v8::Isolate *, ClassManagerPool> pools;
static ClassManagerPool &GetInstance(v8::Isolate *isolate);
static void RemoveInstance(v8::Isolate *isolate);
};
template<typename T>
class Class {
ClassManager &class_manager;
public:
explicit Class(v8::Isolate *isolate);
// Set this as inherited from B
template<typename B>
Class &Inherit();
// Set constructor signatures as tuples of arguments
template<typename ...Args>
Class &Constructor();
// Set factory functions
template<typename ...F>
Class &Constructor(F&&... f);
template<typename U>
Class &InnerClass(const std::string &name, const v8b::Class<U> &cl);
template<typename U>
Class &Value(const std::string &name, U &&value);
template<typename U>
Class &Const(const std::string &name, U &&value);
template<typename Member>
Class &Var(const std::string &name, Member &&ptr);
template<typename Getter, typename Setter = std::nullptr_t>
Class &Property(const std::string &name, Getter &&getter, Setter &&setter = nullptr);
template<typename Getter, typename Setter = std::nullptr_t>
Class &Indexer(Getter &&getter, Setter &&setter = nullptr);
template<typename ...F>
Class &Function(const std::string &name, F&&... f);
template<typename U>
Class &StaticValue(const std::string &name, U &&value);
template<typename U>
Class &StaticConst(const std::string &name, U &&value);
template<typename V>
Class &StaticVar(const std::string &name, V &&v);
template<typename Getter, typename Setter = std::nullptr_t>
Class &StaticProperty(const std::string &name, Getter &&getter, Setter &&setter = nullptr);
template<typename ...F>
Class &StaticFunction(const std::string &name, F&&... f);
Class &AutoWrap(bool auto_wrap = true);
[[nodiscard]]
v8::Local<v8::FunctionTemplate> GetFunctionTemplate() const;
static T *UnwrapObject(v8::Isolate *isolate, v8::Local<v8::Value> value);
static v8::Local<v8::Object> WrapObject(v8::Isolate *isolate, T *ptr, bool take_ownership);
static v8::Local<v8::Object> WrapObject(v8::Isolate *isolate, T *ptr, PointerManager *pointer_manager);
static v8::Local<v8::Object> FindObject(v8::Isolate *isolate, T *ptr);
static void SetPointerManager(v8::Isolate *isolate, T *ptr, PointerManager *pointerManager);
private:
static bool initialized;
};
template<typename T>
class SharedPointerManager : public PointerManager {
std::unordered_map<T *, std::shared_ptr<T>> pointers;
public:
V8B_IMPL static v8::Local<v8::Object> WrapObject(v8::Isolate *isolate, const std::shared_ptr<T> &ptr) {
auto &instance = PointerManager::GetInstance<SharedPointerManager>();
auto res = Class<T>::WrapObject(isolate, ptr.get(), &instance);
instance.pointers.emplace(ptr.get(), ptr);
return res;
}
V8B_IMPL static v8::Local<v8::Object> FindObject(v8::Isolate *isolate, const std::shared_ptr<T> &ptr) {
auto &instance = PointerManager::GetInstance<SharedPointerManager>();
auto object = Class<T>::FindObject(isolate, ptr.get());
if (instance.pointers.find(ptr.get()) == instance.pointers.end()) {
Class<T>::SetPointerManager(isolate, ptr.get(), &instance);
instance.pointers.emplace(ptr.get(), ptr);
}
return object;
}
V8B_IMPL static std::shared_ptr<T> UnwrapObject(v8::Isolate *isolate, v8::Local<v8::Value> value) {
auto &instance = PointerManager::GetInstance<SharedPointerManager>();
auto ptr = Class<T>::UnwrapObject(isolate, value);
if (instance.pointers.find(ptr) == instance.pointers.end()) {
Class<T>::SetPointerManager(isolate, ptr, &instance);
instance.pointers.emplace(ptr, std::shared_ptr<T>(ptr));
}
return instance.pointers.find(ptr)->second;
}
protected:
V8B_IMPL void EndObjectManage(void *ptr) override {
pointers.erase(static_cast<T *>(ptr));
}
};
}
#endif //SANDWICH_V8B_CLASS_HPP
| 30.672131 | 107 | 0.685863 | ayles |
85750cdbde250c45b6e2d90232d5dc0ee76e96d3 | 97 | hpp | C++ | led-blink/src/main.hpp | ikapoz/stm32 | 9efc2a099f55bddaf85b68cc51fb6a31b48538b7 | [
"MIT"
] | null | null | null | led-blink/src/main.hpp | ikapoz/stm32 | 9efc2a099f55bddaf85b68cc51fb6a31b48538b7 | [
"MIT"
] | null | null | null | led-blink/src/main.hpp | ikapoz/stm32 | 9efc2a099f55bddaf85b68cc51fb6a31b48538b7 | [
"MIT"
] | null | null | null | #pragma once
#ifdef __cplusplus
extern "C" {
#endif
int app_main();
#ifdef __cplusplus
}
#endif | 9.7 | 18 | 0.721649 | ikapoz |
8577dbdb44873d3aeac351497f36cae3f4e7427f | 7,204 | cpp | C++ | build/moc/moc_QGeoMapReplyQGC.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | 1 | 2018-11-07T06:10:53.000Z | 2018-11-07T06:10:53.000Z | build/moc/moc_QGeoMapReplyQGC.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | null | null | null | build/moc/moc_QGeoMapReplyQGC.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | 1 | 2018-11-07T06:10:47.000Z | 2018-11-07T06:10:47.000Z | /****************************************************************************
** Meta object code from reading C++ file 'QGeoMapReplyQGC.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/QtLocationPlugin/QGeoMapReplyQGC.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'QGeoMapReplyQGC.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_QGeoTiledMapReplyQGC_t {
QByteArrayData data[16];
char stringdata0[208];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QGeoTiledMapReplyQGC_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QGeoTiledMapReplyQGC_t qt_meta_stringdata_QGeoTiledMapReplyQGC = {
{
QT_MOC_LITERAL(0, 0, 20), // "QGeoTiledMapReplyQGC"
QT_MOC_LITERAL(1, 21, 11), // "terrainDone"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 13), // "responseBytes"
QT_MOC_LITERAL(4, 48, 27), // "QNetworkReply::NetworkError"
QT_MOC_LITERAL(5, 76, 5), // "error"
QT_MOC_LITERAL(6, 82, 20), // "networkReplyFinished"
QT_MOC_LITERAL(7, 103, 17), // "networkReplyError"
QT_MOC_LITERAL(8, 121, 10), // "cacheReply"
QT_MOC_LITERAL(9, 132, 13), // "QGCCacheTile*"
QT_MOC_LITERAL(10, 146, 4), // "tile"
QT_MOC_LITERAL(11, 151, 10), // "cacheError"
QT_MOC_LITERAL(12, 162, 20), // "QGCMapTask::TaskType"
QT_MOC_LITERAL(13, 183, 4), // "type"
QT_MOC_LITERAL(14, 188, 11), // "errorString"
QT_MOC_LITERAL(15, 200, 7) // "timeout"
},
"QGeoTiledMapReplyQGC\0terrainDone\0\0"
"responseBytes\0QNetworkReply::NetworkError\0"
"error\0networkReplyFinished\0networkReplyError\0"
"cacheReply\0QGCCacheTile*\0tile\0cacheError\0"
"QGCMapTask::TaskType\0type\0errorString\0"
"timeout"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QGeoTiledMapReplyQGC[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 44, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
6, 0, 49, 2, 0x08 /* Private */,
7, 1, 50, 2, 0x08 /* Private */,
8, 1, 53, 2, 0x08 /* Private */,
11, 2, 56, 2, 0x08 /* Private */,
15, 0, 61, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QByteArray, 0x80000000 | 4, 3, 5,
// slots: parameters
QMetaType::Void,
QMetaType::Void, 0x80000000 | 4, 5,
QMetaType::Void, 0x80000000 | 9, 10,
QMetaType::Void, 0x80000000 | 12, QMetaType::QString, 13, 14,
QMetaType::Void,
0 // eod
};
void QGeoTiledMapReplyQGC::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
QGeoTiledMapReplyQGC *_t = static_cast<QGeoTiledMapReplyQGC *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->terrainDone((*reinterpret_cast< QByteArray(*)>(_a[1])),(*reinterpret_cast< QNetworkReply::NetworkError(*)>(_a[2]))); break;
case 1: _t->networkReplyFinished(); break;
case 2: _t->networkReplyError((*reinterpret_cast< QNetworkReply::NetworkError(*)>(_a[1]))); break;
case 3: _t->cacheReply((*reinterpret_cast< QGCCacheTile*(*)>(_a[1]))); break;
case 4: _t->cacheError((*reinterpret_cast< QGCMapTask::TaskType(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
case 5: _t->timeout(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QNetworkReply::NetworkError >(); break;
}
break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QNetworkReply::NetworkError >(); break;
}
break;
case 3:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QGCCacheTile* >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (QGeoTiledMapReplyQGC::*_t)(QByteArray , QNetworkReply::NetworkError );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&QGeoTiledMapReplyQGC::terrainDone)) {
*result = 0;
return;
}
}
}
}
const QMetaObject QGeoTiledMapReplyQGC::staticMetaObject = {
{ &QGeoTiledMapReply::staticMetaObject, qt_meta_stringdata_QGeoTiledMapReplyQGC.data,
qt_meta_data_QGeoTiledMapReplyQGC, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *QGeoTiledMapReplyQGC::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QGeoTiledMapReplyQGC::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_QGeoTiledMapReplyQGC.stringdata0))
return static_cast<void*>(this);
return QGeoTiledMapReply::qt_metacast(_clname);
}
int QGeoTiledMapReplyQGC::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGeoTiledMapReply::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
}
return _id;
}
// SIGNAL 0
void QGeoTiledMapReplyQGC::terrainDone(QByteArray _t1, QNetworkReply::NetworkError _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 37.520833 | 143 | 0.619933 | UNIST-ESCL |
8579f3e5972a232be71939234deb4ac789e9a895 | 2,938 | cpp | C++ | VEngine/src/VEngine/renderer/Camera.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | VEngine/src/VEngine/renderer/Camera.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | VEngine/src/VEngine/renderer/Camera.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | #include "precheader.h"
#include "Camera.h"
#include "events/Input.h"
#include "events/MouseEvents.h"
#include "events/WindowEvents.h"
namespace vengine
{
Camera::Camera(const float fov, const float near_z, const float far_z) :
m_fov(fov), m_near_z(near_z), m_far_z(far_z)
{
m_view = glm::lookAt(m_eye, m_target, m_up);
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
void Camera::on_event(const Event& event)
{
switch (event.get_type())
{
case EventType::WINDOW_RESIZED:
{
const auto window_resize_event = *static_cast<const WindowResizedEvent*>(&event);
m_aspect_ratio = (float)window_resize_event.get_width() / window_resize_event.get_height();
recalculate_projection();
break;
}
case EventType::MOUSE_SCROLLED:
{
const auto scroll_event = *static_cast<const MouseScrollEvent*>(&event);
const glm::vec3 direction = glm::normalize(m_eye - m_target);
m_eye -= direction * scroll_event.get_yoffset();
recalculate_view();
break;
}
case EventType::MOUSE_MOVED:
{
const auto move_event = *static_cast<const MouseMoveEvent*>(&event);
if(Input::is_pressed(KeyCode::MIDDLE_MOUSE_BTN))
{
orbit(move_event.get_xoffset() * mouse_sensitivity, move_event.get_yoffset() * mouse_sensitivity);
}
else if(Input::is_pressed(KeyCode::LEFT_SHIFT))
{
m_target += glm::vec3(move_event.get_xoffset() * mouse_sensitivity,
move_event.get_yoffset() * mouse_sensitivity,
move_event.get_xoffset() * mouse_sensitivity);
recalculate_view();
}
break;
}
}
}
void Camera::orbit(const float delta_x, const float delta_y)
{
glm::vec4 position{ m_eye.x, m_eye.y, m_eye.z, 1 };
const glm::vec4 pivot{ m_target.x, m_target.y, m_target.z, 1 };
glm::mat4 rotation_matrix_x{1.0f};
rotation_matrix_x = glm::rotate(rotation_matrix_x, glm::radians(delta_x), m_up);
position = (rotation_matrix_x * (position - pivot)) + pivot;
const glm::vec3 right_vector{ m_view[0][0], m_view[0][1], m_view[0][2] };
glm::mat4 rotation_matrix_y{ 1.0f };
rotation_matrix_y = glm::rotate(rotation_matrix_y, glm::radians(delta_y), right_vector);
m_eye = rotation_matrix_y * (position - pivot) + pivot;
recalculate_view();
}
void Camera::set_position(const glm::vec3& position)
{
m_eye = position;
recalculate_view();
}
void Camera::set_aspect_ratio(float scene_view_ratio)
{
m_aspect_ratio = scene_view_ratio;
recalculate_projection();
}
void Camera::set_projection(const float fov, const float aspect_ratio, const float near_z, const float far_z)
{
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
void Camera::recalculate_view()
{
m_view = glm::lookAt(m_eye, m_target, m_up);
}
void Camera::recalculate_projection()
{
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
}
| 27.203704 | 110 | 0.711368 | Parsif |
857ae7cf007fc227368d641f38355a3595b44729 | 9,406 | cpp | C++ | Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 143 | 2015-11-18T01:06:03.000Z | 2022-03-30T03:08:54.000Z | Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 1 | 2019-10-23T13:00:40.000Z | 2019-10-23T13:00:40.000Z | Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 45 | 2015-11-18T01:17:59.000Z | 2022-03-05T12:29:45.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaCorePreCompiled.h"
#include "SirenCustomClass.h"
#include "Core/Log/Log.h"
#include "Core/Siren/Schema/SirenTextParser.h"
#include "Core/Siren/Schema/SirenAssembly.h"
#include "SirenCustomEnum.h"
#include "Core/IO/Stream/IStream.h"
MEDUSA_BEGIN;
SirenCustomClass::SirenCustomClass()
{
}
SirenCustomClass::~SirenCustomClass(void)
{
SAFE_DELETE_DICTIONARY_VALUE(mTypes);
SAFE_DELETE_DICTIONARY_VALUE(mFields);
}
bool SirenCustomClass::SetAttribute(const StringRef& val)
{
return mAttribute.Load(val);
}
BaseSirenCustomType* SirenCustomClass::FindType(const StringRef& name) const
{
if (name.Contains('.'))
{
List<StringRef> outPaths;
StringParser::Split(name, ".", outPaths, false);
if (outPaths.Count() <= 1)
{
return nullptr;
}
auto* rootType = mTypes.GetOptional(outPaths[0], nullptr);
if (rootType == nullptr || !rootType->IsCustomClass())
{
return nullptr;
}
SirenCustomClass* parentType = (SirenCustomClass*)rootType;
for (size_t i = 1; i < outPaths.Count(); ++i)
{
auto* childType = parentType->FindType(outPaths[i]);
if (childType == nullptr || !childType->IsCustomClass())
{
return nullptr;
}
parentType = (SirenCustomClass*)childType;
}
return parentType;
}
else
{
return mTypes.GetOptional(name, nullptr);
}
}
bool SirenCustomClass::HasType(const StringRef& name) const
{
return mTypes.ContainsKey(name);
}
size_t SirenCustomClass::GetFieldCountRecursively() const
{
if (mBaseType != nullptr)
{
return mBaseType->GetFieldCountRecursively() + mFields.Count();
}
return mFields.Count();
}
bool SirenCustomClass::Link(SirenAssembly& assembly)
{
if (!mBaseTypeName.IsEmpty() && mBaseType == nullptr)
{
ISirenType* baseType = assembly.FindTypeWithReference(mBaseTypeName);
if (baseType == nullptr)
{
Log::FormatError("Cannot find base class:{}", mBaseTypeName);
return false;
}
if (!baseType->IsCustomClass())
{
Log::FormatError("{} cannot be a base class", mBaseTypeName);
return false;
}
mBaseType = (SirenCustomClass*)baseType;
}
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
RETURN_FALSE_IF_FALSE(type->Link(assembly));
}
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
RETURN_FALSE_IF_FALSE(field->Link(assembly));
TryAddIncludeType(field->Type());
TryAddIncludeType(field->KeyType());
TryAddIncludeType(field->ValueType());
}
return true;
}
bool SirenCustomClass::IsCompleted() const
{
RETURN_FALSE_IF(!mBaseTypeName.IsEmpty() && mBaseType == nullptr);
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
RETURN_FALSE_IF_FALSE(type->IsCompleted());
}
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
RETURN_FALSE_IF_FALSE(field->IsCompleted());
}
return true;
}
bool SirenCustomClass::Merge(const BaseSirenCustomType& other)
{
if (!other.IsCustomClass())
{
return false;
}
SirenCustomClass& otherCustom = (SirenCustomClass&)other;
for (auto& typePair : otherCustom.mTypes)
{
auto* curType = FindType(typePair.Key);
if (curType == nullptr)
{
AddType((BaseSirenCustomType*)typePair.Value->Clone());
}
else
{
auto* otherType = typePair.Value;
if (!curType->Merge(*otherType))
{
Log::FormatError("Cannot merge class:{}", typePair.Key);
return false;
}
}
}
return true;
}
SirenCustomClass* SirenCustomClass::Clone() const
{
SirenCustomClass* clone = new SirenCustomClass();
clone->mName = mName;
clone->mFullName = mFullName;
clone->mBaseTypeName = mBaseTypeName;
for (auto filePair : mFields)
{
clone->mFields.Add(filePair.Key, filePair.Value->Clone());
}
for (auto typePair : mTypes)
{
clone->mTypes.Add(typePair.Key, (BaseSirenCustomType*)typePair.Value->Clone());
}
return clone;
}
bool SirenCustomClass::LoadFrom(IStream& stream)
{
RETURN_FALSE_IF_FALSE(BaseSirenCustomType::LoadFrom(stream));
RETURN_FALSE_IF_FALSE(mAttribute.LoadFrom(stream));
mBaseTypeName = stream.ReadString();
//types
uint typeCount = stream.Read<uint32>();
FOR_EACH_SIZE(i, typeCount)
{
char isClass = (char)stream.ReadChar();
if (isClass == 1)
{
std::unique_ptr<SirenCustomClass> type(new SirenCustomClass());
RETURN_FALSE_IF_FALSE(type->LoadFrom(stream));
type->SetParentType(this);
mTypes.Add(type->Name(), type.get());
type.release();
}
else
{
std::unique_ptr<SirenCustomEnum> type(new SirenCustomEnum());
RETURN_FALSE_IF_FALSE(type->LoadFrom(stream));
type->SetParentType(this);
mTypes.Add(type->Name(), type.get());
type.release();
}
}
//fields
uint fieldCount = stream.Read<uint32>();
FOR_EACH_SIZE(i, fieldCount)
{
std::unique_ptr<SirenField> field(new SirenField());
RETURN_FALSE_IF_FALSE(field->LoadFrom(stream));
field->SetParentType(this);
mFields.Add(field->Name(), field.get());
field->SetIndex((ushort)mFields.Count() - 1);
field.release();
}
return true;
}
bool SirenCustomClass::SaveTo(IStream& stream) const
{
RETURN_FALSE_IF_FALSE(BaseSirenCustomType::SaveTo(stream));
RETURN_FALSE_IF_FALSE(mAttribute.SaveTo(stream));
stream.WriteString(mBaseTypeName);
//types
uint typeCount = (uint)mTypes.Count();
stream.Write(typeCount);
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
char isClass = type->IsCustomClass() ? 1 : 0;
stream.WriteChar(isClass);
type->SaveTo(stream);
}
//fields
uint fieldCount = (uint)mFields.Count();
stream.Write(fieldCount);
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
field->SaveTo(stream);
}
return true;
}
bool SirenCustomClass::AddField(SirenField* val)
{
if (mFields.TryAdd(val->Name(), val))
{
val->SetIndex((ushort)mFields.Count() - 1);
val->SetParentType(this);
return true;
}
Log::FormatError("Duplicate property name:{}", val->Name());
return false;
}
bool SirenCustomClass::AddType(BaseSirenCustomType* val)
{
if (mTypes.TryAdd(val->Name(), val))
{
val->SetParentType(this);
return true;
}
Log::FormatError("Duplicate child class name:{}", val->Name());
return false;
}
bool SirenCustomClass::TryAddIncludeType(ISirenType* val)
{
RETURN_FALSE_IF_NULL(val);
if (val->IsBuildIn())
{
return false;
}
BaseSirenCustomType* customType = (BaseSirenCustomType*)val;
mIncludeTypes.TryAdd(customType);
return true;
}
bool SirenCustomClass::AddAttribute(StringRef name, StringRef val)
{
return mAttribute.AddAttribute(name, val);
}
bool SirenCustomClass::Parse(SirenAssembly& assembly, StringRef& refProto)
{
mName = SirenTextParser::ReadToken(refProto);
if (mName.IsEmpty())
{
Log::Error("Cannot get class name");
return false;
}
char c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
if (c == ':')
{
//may has base class
mBaseTypeName = SirenTextParser::ReadTypeName(refProto);
if (mBaseTypeName.IsEmpty())
{
Log::Error("Cannot get base class.");
return false;
}
c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
}
if (c == '[')
{
StringRef attributeStr = SirenTextParser::ReadAttribute(refProto);
if (attributeStr.IsEmpty())
{
Log::Error("Cannot get attribute.");
return false;
}
if (!SetAttribute(attributeStr))
{
Log::FormatError("Invalid class attribute:{}", attributeStr);
return false;
}
c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
}
if (c == '{')
{
while (true)
{
StringRef token = SirenTextParser::ReadTypeName(refProto);
if (token.IsEmpty())
{
break;
}
if (token == SirenTextParser::EnumKeyword)
{
std::unique_ptr<SirenCustomEnum> child(new SirenCustomEnum());
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse enum.");
return false;
}
}
else if (token == SirenTextParser::ClassKeyword )
{
std::unique_ptr<SirenCustomClass> child(new SirenCustomClass());
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse class.");
return false;
}
}
else if (token == SirenTextParser::StructKeyword)
{
std::unique_ptr<SirenCustomClass> child(new SirenCustomClass());
child->MutableAttribute().AddMode(SirenClassGenerateMode::Struct);
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse class.");
return false;
}
}
else
{
//properties
std::unique_ptr<SirenField> field(new SirenField());
if (field->Parse(assembly, this, token, refProto))
{
RETURN_FALSE_IF_FALSE(AddField(field.get()));
field.release();
}
else
{
Log::Error("Failed to parse property.");
return false;
}
}
}
}
else
{
Log::Error("Invalid class declare");
return false;
}
return SirenTextParser::EndType(refProto);
}
MEDUSA_END; | 20.995536 | 81 | 0.683606 | tony2u |
858156c4a69e019492ae396a919ada2eeb498a54 | 10,215 | cp | C++ | Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// Source for CNamespaceDialog class
#include "CNamespaceDialog.h"
#include "CDrawUtils.h"
#include "CIconLoader.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSDIFrame.h"
#include "CUnicodeUtils.h"
#include "resource1.h"
#include <WIN_LTableMultiGeometry.h>
/////////////////////////////////////////////////////////////////////////////
// CNamespaceDialog dialog
CNamespaceDialog::CNamespaceDialog(CWnd* pParent /*=NULL*/)
: CHelpDialog(IDD_NAMESPACE, pParent)
{
//{{AFX_DATA_INIT(CNamespaceDialog)
mDoAuto = FALSE;
mUserItems = _T("");
//}}AFX_DATA_INIT
}
CNamespaceDialog::~CNamespaceDialog()
{
// Must unsubclass table
mTitles.Detach();
mTable.Detach();
}
void CNamespaceDialog::DoDataExchange(CDataExchange* pDX)
{
CHelpDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CNamespaceDialog)
DDX_UTF8Text(pDX, IDC_NAMESPACE_HELP, mHelpText);
DDX_Check(pDX, IDC_NAMESPACE_AUTO, mDoAuto);
DDX_UTF8Text(pDX, IDC_NAMESPACE_PLACES, mUserItems);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CNamespaceDialog, CHelpDialog)
//{{AFX_MSG_MAP(CNamespaceDialog)
ON_BN_CLICKED(IDC_NAMESPACE_PERSONAL, OnSelectPersonalBtn)
ON_BN_CLICKED(IDC_NAMESPACE_SHARED, OnSelectSharedBtn)
ON_BN_CLICKED(IDC_NAMESPACE_PUBLIC, OnSelectPublicBtn)
ON_BN_CLICKED(IDC_NAMESPACE_ALL, OnSelectAllBtn)
ON_BN_CLICKED(IDC_NAMESPACE_NONE, OnSelectNoneBtn)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNamespaceDialog message handlers
BOOL CNamespaceDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
// Subclass table
mTable.SubclassDlgItem(IDC_NAMESPACECHOICE, this);
mTable.InitTable();
mTable.SetServerList(*mServs, *mServitems);
// Subclass titles
mTitles.SubclassDlgItem(IDC_NAMESPACECHOICETITLES, this);
mTitles.SyncTable(&mTable, true);
mTitles.LoadTitles("UI::Titles::Namespace", 3);
if (!mServitems->size())
HideServerItems();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
#pragma mark ____________________________Static Processing
bool CNamespaceDialog::PoseDialog(CMboxProtocol::SNamespace& server,
boolvector& servitems,
cdstrvect& items, bool& do_auto)
{
bool result = false;
// Create the dialog
CNamespaceDialog dlog(CSDIFrame::GetAppTopWindow());
dlog.SetItems(items, server, servitems, do_auto);
// Let Dialog process events
if (dlog.DoModal() == IDOK)
{
dlog.GetItems(items, do_auto);
// Flag success
result = true;
}
return result;
}
// Set namespaces
void CNamespaceDialog::SetItems(const cdstrvect& items, CMboxProtocol::SNamespace& servs, boolvector& servitems, bool do_auto)
{
mUserItems.clear();
for(cdstrvect::const_iterator iter = items.begin(); iter != items.end(); iter++)
{
mUserItems += (*iter).c_str();
mUserItems += os_endl;
}
// Hide server items if none available (i.e. no NAMESPACE support)
mServs = &servs;
mServitems = &servitems;
mDoAuto = do_auto;
// Reset help text
cdstring temp;
temp.FromResource(servitems.size() ? "UI::Namespace::Help1" : "UI::Namespace::Help2");
mHelpText = temp;
}
// Get selected items
void CNamespaceDialog::GetItems(cdstrvect& items, bool& do_auto)
{
// Copy handle to text with null terminator
char* s = ::strtok(mUserItems.c_str_mod(), "\r\n");
items.clear();
while(s)
{
cdstring copyStr(s);
items.push_back(copyStr);
s = ::strtok(NULL, "\r\n");
}
do_auto = mDoAuto;
}
void CNamespaceDialog::HideServerItems()
{
CRect rect1;
GetDlgItem(IDC_NAMESPACE_SERVER)->GetWindowRect(rect1);
CRect rect2;
GetDlgItem(IDC_NAMESPACE_PLACESTITLE)->GetWindowRect(rect2);
int resizeby = rect1.top - rect2.top;
GetDlgItem(IDC_NAMESPACE_SERVER)->ShowWindow(SW_HIDE);
mTable.ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_SELECTTITLE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_PERSONAL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_SHARED)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_PUBLIC)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_ALL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_NONE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_AUTO)->ShowWindow(SW_HIDE);
::MoveWindowBy(GetDlgItem(IDC_NAMESPACE_PLACESTITLE), 0, resizeby);
::MoveWindowBy(GetDlgItem(IDC_NAMESPACE_PLACES), 0, resizeby);
::ResizeWindowBy(this, 0, resizeby);
}
void CNamespaceDialog::OnSelectPersonalBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Personal);
}
void CNamespaceDialog::OnSelectSharedBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Shared);
}
void CNamespaceDialog::OnSelectPublicBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Public);
}
void CNamespaceDialog::OnSelectAllBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_All);
}
void CNamespaceDialog::OnSelectNoneBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_None);
}
#pragma mark -
// __________________________________________________________________________________________________
// C L A S S __ C R E P L Y C H O O S E T A B L E
// __________________________________________________________________________________________________
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Constructor from stream
CNamespaceTable::CNamespaceTable()
{
mData = NULL;
mDataOn = NULL;
mTableGeometry = new LTableMultiGeometry(this, 256, 16);
// Prevent selection being displayed
//SetDrawRowSelection(false);
}
// Default destructor
CNamespaceTable::~CNamespaceTable()
{
}
BEGIN_MESSAGE_MAP(CNamespaceTable, CTable)
//{{AFX_MSG_MAP(CNamespaceTable)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CNamespaceTable::InitTable()
{
// Create columns
CRect frame;
GetClientRect(frame);
InsertCols(3, 1);
SetColWidth(32, 1, 1);
SetColWidth(100, 3, 3);
SetColWidth(frame.Width() - 16 - 132, 2, 2);
// Load strings
cdstring s;
mTypeItems.push_back(s.FromResource("UI::Namespace::Personal"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Shared"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Public"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Entire"));
}
// Draw a cell
void CNamespaceTable::DrawCell(CDC* pDC,
const STableCell& inCell,
const CRect& inLocalRect)
{
StDCState save(pDC);
// Draw selection
DrawCellSelection(pDC, inCell);
// Get data
int descriptor = 0;
cdstring name;
if (inCell.row > mData->offset(CMboxProtocol::ePublic))
{
descriptor = 2;
name = mData->mItems[CMboxProtocol::ePublic].at(inCell.row - 1 - mData->offset(CMboxProtocol::ePublic)).first;
}
else if (inCell.row > mData->offset(CMboxProtocol::eShared))
{
descriptor = 1;
name = mData->mItems[CMboxProtocol::eShared].at(inCell.row - 1 - mData->offset(CMboxProtocol::eShared)).first;
}
else
{
descriptor = 0;
name = mData->mItems[CMboxProtocol::ePersonal].at(inCell.row - 1).first;
}
if (name.empty())
name = mTypeItems[3];
switch(inCell.col)
{
case 1:
{
CRect iconRect;
iconRect.left = inLocalRect.left + 3;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom;
iconRect.top = iconRect.bottom - 16;
// Check for tick
CIconLoader::DrawIcon(pDC, inLocalRect.left + 6, inLocalRect.top, mDataOn->at(inCell.row - 1) ? IDI_DIAMONDTICKED : IDI_DIAMOND, 16);
break;
}
case 2:
// Write address
::DrawClippedStringUTF8(pDC, name, CPoint(inLocalRect.left + 4, inLocalRect.top), inLocalRect, eDrawString_Left);
break;
case 3: // Will not get this if no original column
pDC->SelectObject(CMulberryApp::sAppFontBold);
::DrawClippedStringUTF8(pDC, mTypeItems[descriptor], CPoint(inLocalRect.left + 4, inLocalRect.top), inLocalRect, eDrawString_Left);
break;
default:
break;
}
}
// Click in the cell
void CNamespaceTable::LClickCell(const STableCell& inCell, UINT nFlags)
{
switch(inCell.col)
{
case 1:
mDataOn->at(inCell.row - 1) = !mDataOn->at(inCell.row - 1);
RefreshRow(inCell.row);
break;
default:
// Do nothing
return;
}
}
// Set namespaces
void CNamespaceTable::SetServerList(CMboxProtocol::SNamespace& servs, boolvector& servitems)
{
// Insert rows
mDataOn = &servitems;
mData = &servs;
InsertRows(mDataOn->size(), 1, nil, 0, false);
}
void CNamespaceTable::ChangeSelection(ENamespaceSelect select)
{
// Iterator over each element
unsigned long ctr = 1;
for(boolvector::iterator iter = mDataOn->begin(); iter != mDataOn->end(); iter++, ctr++)
{
switch(select)
{
case eNamespace_Personal:
if (ctr <= mData->offset(CMboxProtocol::eShared))
*iter = true;
break;
case eNamespace_Shared:
if ((ctr > mData->offset(CMboxProtocol::eShared)) && (ctr <= mData->offset(CMboxProtocol::ePublic)))
*iter = true;
break;
case eNamespace_Public:
if (ctr > mData->offset(CMboxProtocol::ePublic))
*iter = true;
break;
case eNamespace_All:
*iter = true;
break;
case eNamespace_None:
*iter = false;
break;
}
}
// Force redraw
RedrawWindow();
}
| 26.671018 | 136 | 0.697112 | mulberry-mail |
3fecdd79de1733a32cee4b0aeeb25f3540d62d3d | 59 | hpp | C++ | common/gl.hpp | Legion-Engine/Test_GL | 43e08fd92d2a2a903beea45440f4b4e170d72c6d | [
"MIT"
] | null | null | null | common/gl.hpp | Legion-Engine/Test_GL | 43e08fd92d2a2a903beea45440f4b4e170d72c6d | [
"MIT"
] | null | null | null | common/gl.hpp | Legion-Engine/Test_GL | 43e08fd92d2a2a903beea45440f4b4e170d72c6d | [
"MIT"
] | null | null | null | #pragma once
#include <glad/glad.h>
#include <glfw/glfw3.h> | 19.666667 | 23 | 0.728814 | Legion-Engine |
3ff64f73d4f352d9cf6f49c55efff6685977e14e | 3,143 | hpp | C++ | include/abc/tagged_type.hpp | mabaro/abc | db636953f3438e6861458c0aa33642381bc4711d | [
"MIT"
] | null | null | null | include/abc/tagged_type.hpp | mabaro/abc | db636953f3438e6861458c0aa33642381bc4711d | [
"MIT"
] | 3 | 2020-10-18T00:06:28.000Z | 2020-10-18T00:10:14.000Z | include/abc/tagged_type.hpp | mabaro/abc | db636953f3438e6861458c0aa33642381bc4711d | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <type_traits>
namespace abc
{
template <typename T, typename TTag, int64_t DefaultValue>
class tagged_type
{
static_assert(std::is_trivial<T>::value, "Only trivial types are supported");
T m_value;
public:
using value_t = T;
using this_t = tagged_type<T, TTag, DefaultValue>;
static constexpr T default_value = DefaultValue;
public:
tagged_type(uninitialized_t) {}
tagged_type() : m_value(default_value) {}
explicit tagged_type(const T i_value) : m_value(i_value) {}
tagged_type(const this_t& i_other) : m_value(i_other.m_value) {}
tagged_type(this_t&& i_other) : m_value(std::move(i_other.m_value)) {}
~tagged_type() = default;
this_t& operator=(const this_t& i_other) noexcept
{
m_value = i_other.m_value;
return *this;
}
this_t& operator=(this_t&& i_other) noexcept
{
m_value = std::move(i_other.m_value);
return *this;
}
explicit constexpr operator T&() noexcept { return m_value; }
explicit constexpr operator const T&() const noexcept { return m_value; }
constexpr const T& value() const noexcept { return m_value; }
T& value() noexcept { return m_value; }
bool operator==(const this_t& other) const noexcept { return m_value == other.m_value; }
bool operator!=(const this_t& other) const noexcept { return !operator==(other); }
using enable_for_arithmetic = std::enable_if<std::is_arithmetic<T>::value, this_t>;
typename enable_for_arithmetic::type operator+(const this_t& other) const
{
return this_t(m_value + other.m_value);
}
typename enable_for_arithmetic::type operator-(const this_t& other) const
{
return this_t(m_value - other.m_value);
}
typename enable_for_arithmetic::type operator*(const this_t& other) const
{
return this_t(m_value * other.m_value);
}
typename enable_for_arithmetic::type operator/(const this_t& other) const
{
return this_t(m_value / other.m_value);
}
typename enable_for_arithmetic::type& operator+=(const this_t& other)
{
m_value += other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator-=(const this_t& other)
{
m_value -= other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator*=(const this_t& other)
{
m_value *= other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator/=(const this_t& other)
{
m_value /= other.m_value;
return *this;
}
};
} // namespace abc
//#define ABC_NAMED_TYPE_INTEGRAL(NAME, TYPE, DEFAULT_VALUE) \
//struct ##NAME_traits \
//{ \
// static const TYPE default_value; \
//}; \
//const TYPE ##NAME_traits::default_value = DEFAULT_VALUE; \
//using NAME = abc::tagged_type<TYPE, struct ##NAME_tag, ##NAME_traits>;
| 31.747475 | 92 | 0.620108 | mabaro |
3ff7fec602af276513c5a52036f5d5617a70dd3e | 3,451 | hpp | C++ | include/snd/misc.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 18 | 2020-08-26T11:33:50.000Z | 2021-04-13T15:57:28.000Z | include/snd/misc.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 1 | 2021-05-16T17:11:57.000Z | 2021-05-16T17:25:17.000Z | include/snd/misc.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | null | null | null | #pragma once
#ifndef _USE_MATH_DEFINES
# define _USE_MATH_DEFINES
#endif
#include <algorithm>
#include <cmath>
#pragma warning(push, 0)
#include <DSP/MLDSPOps.h>
#pragma warning(pop)
#include "convert.hpp"
namespace snd {
constexpr auto PI = 3.14159265358979f;
constexpr float DENORMAL_DC = 1e-25f;
inline void flush_denormal_to_zero(float& x)
{
x += DENORMAL_DC;
x -= DENORMAL_DC;
}
template <size_t ROWS>
inline ml::DSPVectorArray<ROWS> flush_denormal_to_zero(const ml::DSPVectorArray<ROWS>& in)
{
ml::DSPVectorArray<ROWS> out;
for (int i = 0; i < kFloatsPerDSPVector; i++)
{
out = in;
out[i] += DENORMAL_DC;
out[i] -= DENORMAL_DC;
}
return out;
}
template <class T>
T tan_rational(T in)
{
auto a = (in * T(-0.0896638f)) + T(0.0388452f);
auto b = (in * T(-0.430871f)) + T(0.0404318f);
auto c = (a * in) + T(1.00005f);
auto d = (b * in) + T(1.f);
return (c * in) / d;
}
template <class T>
T blt_prewarp_rat_0_08ct_sr_div_2(int SR, const T& freq)
{
return tan_rational(ml::min(T(1.50845f), (T(PI) / float(SR)) * freq));
}
template <class T>
constexpr T lerp(T a, T b, T x)
{
return (x * (b - a)) + a;
}
template <class T>
constexpr T inverse_lerp(T a, T b, T x)
{
return (x - a) / (b - a);
}
template <class T> T quadratic_sequence(T step, T start, T n)
{
auto a = T(0.5) * step;
auto b = start - (T(3.0) * a);
return (a * std::pow(n + 1, 2)) + (b * (n + 1)) - (start - 1) + (step - 1);
}
template <class T> T quadratic_formula(T a, T b, T c, T n)
{
return (a * (n * n)) + (b * n) + c;
}
template <class T> T holy_fudge(T f0, T f1, T N, T n, T C)
{
auto accel = (f1 - f0) / (T(2) * N);
return quadratic_formula(accel, f0, C, n);
}
template <class T> T distance_traveled(T start, T speed, T acceleration, T n)
{
return (speed * n) + (T(0.5) * acceleration) * (n * n) + start;
}
template <class T> T ratio(T min, T max, T distance)
{
return std::pow(T(2), ((max - min) / distance) / T(12));
}
template <class T> T sum_of_geometric_series(T first, T ratio, T n)
{
return first * ((T(1) - std::pow(ratio, n)) / (T(1) - ratio));
}
template <class T> T holy_grail(T min, T max, T distance, T n)
{
auto r = ratio(min, max, distance);
if (std::abs(T(1) - r) <= T(0))
{
return n * convert::P2FF(min);
}
return sum_of_geometric_series(convert::P2FF(min), r, n);
}
template <class T> T holy_grail_ff(T min, T max, T distance, T n)
{
return convert::P2FF(min) * std::pow(ratio(min, max, distance), n);
}
template <class T>
T dn_cancel(T value)
{
if (std::fpclassify(value) != FP_NORMAL)
{
return std::numeric_limits<T>().min();
}
return value;
}
template <class T>
T dn_cancel(T value, T min)
{
if (value < min)
{
return min;
}
return value;
}
template <class T>
inline T wrap(T x, T y)
{
x = std::fmod(x, y);
if (x < T(0)) x += y;
return x;
}
inline int wrap(int x, int y)
{
x = x % y;
if (x < 0) x += y;
return x;
}
template <size_t ROWS>
bool clip_check(const ml::DSPVectorArray<ROWS>& x, float limit = 1.0f)
{
for (int r = 0; r < ROWS; r++)
{
const auto min_value = ml::min(x.constRow(r));
const auto max_value = ml::max(x.constRow(r));
if (min_value < -limit) return true;
if (max_value > limit) return true;
}
return false;
}
template <class Iterator>
bool clip_check(Iterator begin, Iterator end, float limit = 1.0f)
{
for (auto pos = begin; pos != end; pos++)
{
if (*pos < -limit || *pos > limit) return true;
}
return false;
}
}
| 17.880829 | 90 | 0.616923 | colugomusic |
3ffb9128a689f3b9ddcb15655694c5b5e7f34cab | 666 | cc | C++ | chapter3/ex3-39.cc | guojing0/cpp-primer | b0e36982d1323395aaca9bd9be09f383c130b645 | [
"MIT"
] | 1 | 2015-03-15T00:35:51.000Z | 2015-03-15T00:35:51.000Z | chapter3/ex3-39.cc | guojing0/cpp-primer | b0e36982d1323395aaca9bd9be09f383c130b645 | [
"MIT"
] | null | null | null | chapter3/ex3-39.cc | guojing0/cpp-primer | b0e36982d1323395aaca9bd9be09f383c130b645 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[])
{
string s1 = "Happy day", s2 = "Bad cat";
const char ch1[] = "Know yourself", ch2[] = "Know thyself";
if (s1 > s2) {
cout << "String s1 is larger.";
} else if (s2 < s1) {
cout << "String s2 is larger.";
} else {
cout << "They are equal.";
}
cout << endl;
if (strcmp(ch1, ch2) > 0) {
cout << "Char ch1 is larger.";
} else if (strcmp(ch1, ch2) < 0) {
cout << "Char ch2 is larger.";
} else {
cout << "They are equal.";
}
cout << endl;
return 0;
} | 21.483871 | 63 | 0.509009 | guojing0 |
b203c07bc6768841c65461f3783e765da3896ea0 | 385 | cpp | C++ | lessons/03-loops/src/problem1_sol.cpp | chemphys/LearnCPP | 025a6e043c6eadb61324c261168bbd0478d9690b | [
"BSD-3-Clause"
] | null | null | null | lessons/03-loops/src/problem1_sol.cpp | chemphys/LearnCPP | 025a6e043c6eadb61324c261168bbd0478d9690b | [
"BSD-3-Clause"
] | null | null | null | lessons/03-loops/src/problem1_sol.cpp | chemphys/LearnCPP | 025a6e043c6eadb61324c261168bbd0478d9690b | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <number>\n";
return 1;
}
int nmax = atoi(argv[1]);
int sum_num = 0;
for (int i = 3; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum_num += i;
}
}
std::cout << "Result: " << sum_num << std::endl;
return 0;
}
| 16.041667 | 55 | 0.467532 | chemphys |
b204c5bc971170676d5d06fdf68655dbdae8aae5 | 2,119 | cpp | C++ | src/clock.cpp | JoakimLindbom/JLmod | d4ef1f0fd376492a32b229e054a63dcc32ea317f | [
"BSD-3-Clause"
] | 10 | 2018-01-10T20:29:22.000Z | 2020-07-06T21:23:02.000Z | src/clock.cpp | JoakimLindbom/vcvrack | d4ef1f0fd376492a32b229e054a63dcc32ea317f | [
"BSD-3-Clause"
] | 5 | 2018-02-25T13:57:19.000Z | 2020-04-01T16:07:41.000Z | src/clock.cpp | JoakimLindbom/vcvrack | d4ef1f0fd376492a32b229e054a63dcc32ea317f | [
"BSD-3-Clause"
] | null | null | null | #include "clock.hpp"
#include <functional>
Clock::Clock() {
reset();
}
void Clock::reset() {
step = -1.0;
}
bool Clock::isReset() {
return step == -1.0;
}
double Clock::getStep() {
return step;
}
void Clock::setSampleRate(double inSampleRate) {
sampleRate = inSampleRate; // TODO: Cascade to sub clocks. Needed???
}
void Clock::construct(Clock* clkGiven, bool *resetClockOutputsHighPtr) {
syncSrc = clkGiven;
resetClockOutputsHigh = resetClockOutputsHighPtr;
}
void Clock::addSubClock(Clock* subClock) {
//subClocks.push_back(subClock);
if (numSubClocks < 32 ){
numSubClocks++;
//subClocks[numSubClocks] = subClock;
std::cout << "size: " << numSubClocks << "\n";
}
}
void Clock::start() {
step = 0.0;
}
void Clock::setup(double lengthGiven, int iterationsGiven, double sampleTimeGiven) {
length = lengthGiven;
iterations = iterationsGiven;
sampleTime = sampleTimeGiven;
}
void Clock::process() { // Refactored code from calling
}
void Clock::stepClock() {// here the clock was output on step "step", this function is called near end of module::process()
_tick = false;
if (step >= 0.0) {// if active clock
step += sampleTime;
if ( (syncSrc != nullptr) && (iterations == 1) && (step > (length - guard)) ) {// if in sync region
if (syncSrc->isReset()) {
reset();
}// else nothing needs to be done, just wait and step stays the same
}
else {
if (step >= length) {// reached end iteration
iterations--;
step -= length;
_tick = true;
if (iterations <= 0)
reset();// frame done
}
}
}
}
void Clock::applyNewLength(double lengthStretchFactor) {
if (step != -1.0)
step *= lengthStretchFactor;
length *= lengthStretchFactor;
}
int Clock::isHigh() {
if (step >= 0.0) {
return (step < (length * 0.5)) ? 1 : 0;
}
return (*resetClockOutputsHigh) ? 1 : 0;
}
bool Clock::Tick() {
return (_tick);
}
| 23.285714 | 123 | 0.577631 | JoakimLindbom |
b20538b53f06da71e3a0e4464c2f782d82060ba8 | 418 | cpp | C++ | app.cpp | retorillo/appveyor-playground | d30895cf7267bdd2083bde81b4e4cfc2ceede940 | [
"CC0-1.0"
] | null | null | null | app.cpp | retorillo/appveyor-playground | d30895cf7267bdd2083bde81b4e4cfc2ceede940 | [
"CC0-1.0"
] | null | null | null | app.cpp | retorillo/appveyor-playground | d30895cf7267bdd2083bde81b4e4cfc2ceede940 | [
"CC0-1.0"
] | null | null | null | #include "app.h"
int CALLBACK WinMain(HINSTANCE i, HINSTANCE p, LPSTR c, int n) {
auto foobar = combine(L"C:\\foo\\bar", L"..\\bar");
MessageBoxW(NULL, foobar.c_str(), L"test", MB_OK);
return foobar != L"C:\\foo\\bar";
}
std::wstring combine(std::wstring l, std::wstring r) {
WCHAR* b;
PathAllocCombine(l.c_str(), r.c_str(), PATHCCH_ALLOW_LONG_PATHS, &b);
std::wstring w(b);
LocalFree(b);
return w;
}
| 27.866667 | 71 | 0.648325 | retorillo |
b2278b98545dec581081afdf28a8433cbab546af | 302 | hpp | C++ | src/cpp3ds/Graphics/CitroHelpers.hpp | cpp3ds/cpp3ds | 7813714776e2134bd75b9f3869ed142c1d4eeaaf | [
"MIT"
] | 98 | 2015-08-26T16:49:29.000Z | 2022-03-03T10:15:43.000Z | src/cpp3ds/Graphics/CitroHelpers.hpp | Naxann/cpp3ds | 1932e798306ec6d910c6a5b9e85e9d8f02fb815f | [
"MIT"
] | 10 | 2016-02-26T21:30:51.000Z | 2020-07-12T20:48:09.000Z | src/cpp3ds/Graphics/CitroHelpers.hpp | Naxann/cpp3ds | 1932e798306ec6d910c6a5b9e85e9d8f02fb815f | [
"MIT"
] | 15 | 2015-10-16T06:22:37.000Z | 2020-10-01T08:52:48.000Z | #pragma once
#include <citro3d.h>
void CitroInit(size_t commandBufferSize);
void CitroDestroy();
void CitroBindUniforms(shaderProgram_s* program);
void CitroUpdateMatrixStacks();
C3D_MtxStack* CitroGetProjectionMatrix();
C3D_MtxStack* CitroGetModelviewMatrix();
C3D_MtxStack* CitroGetTextureMatrix();
| 27.454545 | 49 | 0.831126 | cpp3ds |
b22d96ce16a46e20c9a9b9c05ea235799addebaa | 3,041 | cpp | C++ | common/test_libs/arduino_sim/ArduinoSim.cpp | sienna0127/VentilatorSoftware | 73e65d8b00c29617b64430cff921afa597096bf8 | [
"Apache-2.0"
] | null | null | null | common/test_libs/arduino_sim/ArduinoSim.cpp | sienna0127/VentilatorSoftware | 73e65d8b00c29617b64430cff921afa597096bf8 | [
"Apache-2.0"
] | null | null | null | common/test_libs/arduino_sim/ArduinoSim.cpp | sienna0127/VentilatorSoftware | 73e65d8b00c29617b64430cff921afa597096bf8 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020, RespiraWorks
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.
*/
/*
* module contributors: verityRF
*
* The purpose of this module is to recreate fake versions of Arduino routines
* so that unit tests of the controller modules can be done on a x86 host. This
* module should never end up on an actual Arduino target.
*/
//@TODO: Merge this module with `hal`.
//@TODO: Write unit tests for this module
#include "ArduinoSim.h"
#include <math.h>
#include <stdlib.h>
// how (maximally) long are the simulated analog signals
static const int ANALOG_SIGNAL_DEPTH = 256;
// how many channels (analog pins) are supported
static const int NUM_ANALOG_CHANNELS = 4;
// Arduino ADC VREF_P setting/value [V]
static const float ADC_VREFP = 5.0f;
// 10 bit ADC with given ADC VREF_P [Count/V]
static const float ADC_COUNTS_PER_VOLT = 1024.0f / ADC_VREFP;
static float analogSignalMemory[NUM_ANALOG_CHANNELS][ANALOG_SIGNAL_DEPTH];
static int analogSignalMemoryIndexes[NUM_ANALOG_CHANNELS];
int getSignalChannelDepth() { return ANALOG_SIGNAL_DEPTH; }
void resetAnalogMemoryIndexes() {
for (int i = 0; i < NUM_ANALOG_CHANNELS; i++) {
analogSignalMemoryIndexes[i] = 0;
}
}
void createDynamicAnalogSignal(int pin, float *buffer, int count) {
if (buffer == NULL) {
throw "Input buffer pointer is null";
}
if (count > ANALOG_SIGNAL_DEPTH) {
throw "Input count greater than analog memory depth";
}
// copy input buffer to corresponding analog pin memory, constraining the
// allowable voltage on the pin
for (int i = 0; i < count; i++) {
float currentValue = buffer[i];
if (currentValue < 0.0f) {
currentValue = 0.0f;
}
if (currentValue > ADC_VREFP) {
currentValue = ADC_VREFP;
}
analogSignalMemory[pin][i] = currentValue;
}
}
void createStaticAnalogSignal(int pin, float val) {
if (val < 0.0f) {
val = 0.0f;
}
if (val > ADC_VREFP) {
val = ADC_VREFP;
}
for (int i = 0; i < ANALOG_SIGNAL_DEPTH; i++) {
analogSignalMemory[pin][i] = val;
}
}
int analogRead(int pin) {
if (pin < 0 || pin > (NUM_ANALOG_CHANNELS - 1)) {
throw "Analog pin is out of bounds";
}
int output =
(int)roundf((analogSignalMemory[pin][analogSignalMemoryIndexes[pin]] *
ADC_COUNTS_PER_VOLT));
// rollover the index if necessary
if (analogSignalMemoryIndexes[pin] == (ANALOG_SIGNAL_DEPTH - 1)) {
analogSignalMemoryIndexes[pin] = 0;
} else {
analogSignalMemoryIndexes[pin] += 1;
}
// output constrained to 10 bits
return output & 0x3FF;
}
| 30.108911 | 79 | 0.70832 | sienna0127 |
b23885ece11a149f98a639c53ec6a016954c6167 | 1,139 | cpp | C++ | codechef/BINIM2/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codechef/BINIM2/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codechef/BINIM2/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 21-10-2018 22:40:38
* solution_verdict: Accepted language: C++14
* run_time: 0.00 sec memory_used: 14.9M
* problem: https://www.codechef.com/COOK99A/problems/BINIM2
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;string s;cin>>s;
int dee=0,dum=0;
while(n--)
{
string x;cin>>x;
if(x[0]=='0'&&x.back()=='0')dee++;
if(x[0]=='1'&&x.back()=='1')dum++;
}
if(s=="Dee")
{
if(dee<=dum)cout<<"Dee"<<endl;
else cout<<"Dum"<<endl;
}
else
{
if(dum<=dee)cout<<"Dum"<<endl;
else cout<<"Dee"<<endl;
}
}
return 0;
} | 30.783784 | 111 | 0.369622 | kzvd4729 |
b23c37009fd8fb21a79a37d2a980d31f16e19b66 | 3,835 | cpp | C++ | src/036_valid_sudoku.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 1 | 2019-09-01T22:54:39.000Z | 2019-09-01T22:54:39.000Z | src/036_valid_sudoku.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 6 | 2019-07-19T07:16:42.000Z | 2019-07-26T08:21:31.000Z | src/036_valid_sudoku.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | null | null | null |
/*
Valid Sudoku
URL: https://leetcode.com/problems/valid-sudoku
Tags: ['hash-table']
___
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be
validated according to the following rules :
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the 9 `3x3` sub-boxes of the grid must contain the digits `1-9`
without repetition.

A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with
the character `'.'`.
Example 1:
Input:
[
[ "5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: true
Example 2:
Input:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner
being modified to 8. Since there are two 8 's in the top left 3x3 sub-box, it is
invalid.
Note:
* A Sudoku board (partially filled) could be valid but is not necessarily
solvable.
* Only the filled cells need to be validated according to the mentioned rules.
* The given board contain only digits `1-9` and the character `'.'`.
* The given board size is always `9x9`.
*/
#include "test.h"
using std::vector;
namespace valid_sudoku {
inline namespace v1 {
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool bitmaps[3][9];
auto checkDup = [&](int k, int i, int j) {
int n = board[i][j] - '1';
if (n < 0 || n >= 9) {
return false;
}
if (bitmaps[k][n]) {
return true;
}
bitmaps[k][n] = true;
return false;
};
for (int i = 0; i < 9; i++) {
for (int k = 0; k < 3; k++) {
memset(&bitmaps[k][0], 0, sizeof(bitmaps[k]));
}
for (int j = 0; j < 9; j++) {
if (checkDup(0, i, j) || checkDup(1, j, i) ||
checkDup(2, (i / 3) * 3 + (j / 3), (i % 3) * 3 + (j % 3))) {
return false;
}
}
}
return true;
}
};
} // namespace v1
TEST_CASE("Valid Sudoku") {
TEST_SOLUTION(isValidSudoku, v1) {
vector<vector<char>> v = {
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
CHECK(isValidSudoku(v));
v[0][0] = '3';
CHECK_FALSE(isValidSudoku(v));
};
}
} // namespace valid_sudoku
| 30.19685 | 80 | 0.393481 | llife09 |
b23d918b6b8841b218baedbc00d97ead1298d0f9 | 191 | hpp | C++ | src/Input.hpp | RichardMarks/proto | 68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01 | [
"MIT"
] | null | null | null | src/Input.hpp | RichardMarks/proto | 68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01 | [
"MIT"
] | null | null | null | src/Input.hpp | RichardMarks/proto | 68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01 | [
"MIT"
] | null | null | null | #ifndef INPUT_H
#define INPUT_H
namespace proto {
class Config;
class Input {
public:
Input(Config& config);
~Input();
};
} // !namespace proto
#endif // !INPUT_H
| 10.611111 | 28 | 0.602094 | RichardMarks |
b23e0884e156046a6e20dc29f642df205a4f990e | 888 | cpp | C++ | src/prod/src/api/wrappers/ComClientSettingsResult.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/api/wrappers/ComClientSettingsResult.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/api/wrappers/ComClientSettingsResult.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Api;
using namespace Common;
using namespace ServiceModel;
using namespace std;
ComClientSettingsResult::ComClientSettingsResult(
FabricClientSettings const & settings)
: IFabricClientSettingsResult()
, ComUnknownBase()
, heap_()
, settings_()
{
settings_ = heap_.AddItem<FABRIC_CLIENT_SETTINGS>();
settings.ToPublicApi(heap_, *settings_);
}
ComClientSettingsResult::~ComClientSettingsResult()
{
}
const FABRIC_CLIENT_SETTINGS * STDMETHODCALLTYPE ComClientSettingsResult::get_Settings()
{
return settings_.GetRawPointer();
}
| 26.909091 | 98 | 0.653153 | vishnuk007 |
b2402af98fb294e4e193cec4112358712acd635c | 54,548 | hpp | C++ | ch_frb_io.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | null | null | null | ch_frb_io.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | 17 | 2016-06-15T22:55:57.000Z | 2020-09-25T18:15:40.000Z | ch_frb_io.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | 3 | 2017-01-12T11:42:19.000Z | 2019-01-14T23:54:44.000Z | #ifndef _CH_FRB_IO_HPP
#define _CH_FRB_IO_HPP
#if (__cplusplus < 201103) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
#error "This source file needs to be compiled with C++11 support (g++ -std=c++11)"
#endif
#include <queue>
#include <string>
#include <vector>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <memory>
#include <cstdint>
#include <atomic>
#include <random>
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <hdf5.h>
#include <arpa/inet.h>
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode
#endif
template<typename T> struct hdf5_extendable_dataset;
struct noncopyable
{
noncopyable() { }
noncopyable(const noncopyable &) = delete;
noncopyable& operator=(const noncopyable &) = delete;
};
// Defined later in this file
class assembled_chunk;
class memory_slab_pool;
class output_device;
// Defined in ch_frb_io_internals.hpp
struct intensity_packet;
struct udp_packet_list;
struct udp_packet_ringbuf;
class assembled_chunk_ringbuf;
// "uptr" is a unique_ptr for memory that is allocated by
// malloc()-like calls and should therefore be freed by free().
// It uses this little custom deleter class (that is
// default-constructable, so doesn't need to specified when creating a
// uptr). This was copy-pasted from rf_pipelines.
struct uptr_deleter {
inline void operator()(const void *p) { std::free(const_cast<void *> (p)); }
};
template<typename T>
using uptr = std::unique_ptr<T[], uptr_deleter>;
// And we use it for blocks of memory used for assembled_chunks.
typedef uptr<uint8_t> memory_slab_t;
// -------------------------------------------------------------------------------------------------
//
// Compile-time constants
//
// FIXME many of these don't really need to be fixed at compile time, and could be runtime parameters instead.
namespace constants {
static constexpr int cache_line_size = 64;
// Number of seconds per FPGA count. This "magic number" appears in multiple libraries
// (ch_frb_io, rf_pipelines, ch_vdif_assembler). FIXME: it would be better to keep it
// in one place, to avoid any possibility of having it get out-of-sync.
static constexpr double dt_fpga = 2.56e-6;
// Number of "coarse" (i.e. pre-upchannelized) frequency channels.
static constexpr int nfreq_coarse_tot = 1024;
// For an explanation of this parameter, see class intensity_network_ostream below
static constexpr double default_wt_cutoff = 0.3;
static constexpr int default_udp_port = 6677;
#ifdef __APPLE__
// osx seems to have very small limits on socket buffer size
static constexpr int default_socket_bufsize = 4 * 1024 * 1024;
#else
static constexpr int default_socket_bufsize = 128 * 1024 * 1024;
#endif
// This applies to the ring buffer between the network _output_ thread, and callers of
// intensity_network_ostream::send_chunk().
static constexpr int output_ringbuf_capacity = 8;
static constexpr int nt_per_assembled_chunk = 1024;
// These parameters don't really affect anything but appear in asserts.
static constexpr int max_input_udp_packet_size = 9000; // largest value the input stream will accept
static constexpr int max_output_udp_packet_size = 8910; // largest value the output stream will produce
static constexpr int max_allowed_beam_id = 65535;
static constexpr int max_allowed_nupfreq = 64;
static constexpr int max_allowed_nt_per_packet = 1024;
static constexpr int max_allowed_fpga_counts_per_sample = 3200;
static constexpr double max_allowed_output_gbps = 10.0;
};
// -------------------------------------------------------------------------------------------------
//
// HDF5 file I/O
//
// Note that there are two classes here: one for reading (intensity_hdf5_file),
// and one for writing (intensity_hdf5_ofile).
struct intensity_hdf5_file : noncopyable {
std::string filename;
int nfreq;
int npol;
int nt_file; // number of time samples in file (which can have gaps)
int nt_logical; // total number of samples in time range spanned by file, including gaps
//
// We currently throw an exception unless the frequencies are equally spaced and consecutive.
// Therefore, we don't keep a full list of frequencies, just the endpoints of the range and number of samples.
//
// This still leaves two possibilities: the frequencies can either be ordered from lowest to highest,
// or vice versa. The 'frequencies_are_increasing' flag is set in the former case. (Note that the
// standard CHIME convention is frequencies_are_increasing=false.)
//
// The 'freq_lo_MHz' and 'freq_hi_MHz' fields are the lowest and highest frequencies in the entire
// band. Just to spell this out in detail, if frequencies_are_increasing=true, then the i-th channel
// spans the frequency range
//
// [ freq_lo + i*(freq_hi-freq_lo)/nfreq, freq_lo + (i+1)*(freq_hi-freq_lo)/nfreq ]
//
// and if frequences_are_increasing=false, then the i-th channel spans frequency range
//
// [ freq_hi - (i+1)*(freq_hi-freq_lo)/nfreq, freq_hi - i*(freq_hi-freq_lo)/nfreq ]
//
// where 0 <= i <= nfreq-1.
//
bool frequencies_are_increasing;
double freq_lo_MHz;
double freq_hi_MHz;
//
// We distinguish between "file" time indices, which span the range 0 <= it < nt_file,
// and "logical" time indices, which span the range 0 <= it < nt_logical.
//
// The i-th logical time sample spans the time range
//
// [ time_lo + i*dt_sample, time_lo + (i+1)*dt_sample ]
//
double dt_sample;
double time_lo;
double time_hi; // always equal to time_lo + nt_logical * dt_sample
std::vector<double> times; // 1D array of length nt_file
std::vector<int> time_index_mapping; // 1D array of length nt_file, which maps a "file" index to a "logical" index.
// Polarization info (currently read from file but not really used)
std::vector<std::string> polarizations; // 1D array of length npol, each element is either "XX" or "YY"
// 3d arrays of shape (nfreq, npol, nt_file), verbatim from the hdf5 file.
// Rather than using them directly, you may want to use the member function get_unpolarized_intensity() below.
std::vector<float> intensity;
std::vector<float> weights;
// Summary statistics
double frac_ungapped; // fraction of "logical" time samples which aren't in time gaps
double frac_unmasked; // fraction of _ungapped_ data with large weight
// Construct from file. If 'noisy' is true, then a one-line message will be printed when the file is read.
explicit intensity_hdf5_file(const std::string &filename, bool noisy=true);
//
// Extracts a 2D array containing total intensity in time range [out_t0, out_t0+out_nt),
// summing over polarizations. The 'out_t0' and 'out_nt' are "logical" time indices, not
// "file" time indices. If this range of logical time indices contains gaps, the corresponding
// entries of the 'out_int' and 'out_wt' arrays will be filled with zeros.
//
// The 'out_int' and 'out_wt' arrays have shape (nfreq, out_nt).
//
// The 'out_istride' and 'out_wstride' args can be negative, if reversing the channel ordering is desired.
// If out_istride is zero, it defaults to out_nt. If out_wstride is zero, it defaults to out_istride.
//
void get_unpolarized_intensity(float *out_int, float *out_wt, int out_t0, int out_nt, int out_istride=0, int out_wstride=0) const;
void run_unit_tests() const;
};
struct intensity_hdf5_ofile {
std::string filename;
double dt_sample;
int nfreq;
int npol;
ssize_t curr_nt; // current size of file (in time samples, not including gaps)
double curr_time; // time in seconds relative to arbitrary origin
ssize_t curr_ipos; // keeps track of gaps
ssize_t initial_ipos;
// used internally to print summary info when file is written
double wsum;
double wmax;
std::unique_ptr<hdf5_extendable_dataset<double> > time_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > intensity_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > weights_dataset;
//
// The 'pol' argument is typically { "XX", "YY" }. Note that pol.size() determines intensity_hdf5_file::npol,
// which in turn determines the expected shape of the 'intensity' and 'weights' arguments passed to append_chunk().
//
// The 'freq0_MHz' and 'freq1_MHz' args should be the edges of the band, ordered the same way as the channel
// indices. For example in CHIME data, frequencies are ordered from highest to lowest, so we take freq0_MHz=800
// and freq1_MHz=400.
//
// The optional 'ipos0' and 'time0' args are:
// ipos0 = index of first sample in file (in downsampled units, i.e. one sample is ~1 msec, not ~2.56 usec)
// time0 = arrival time of first sample in file (in seconds).
//
// The meaning of the 'bitshuffle' arg is:
// 0 = no compression
// 1 = try to compress, but if plugin fails then just write uncompressed data instead
// 2 = try to compress, but if plugin fails then print a warning and write uncompressed data instead
// 3 = compression mandatory
//
// The default nt_chunk=128 comes from ch_vdif_assembler chunk size, assuming downsampling by factor 512.
//
intensity_hdf5_ofile(const std::string &filename, int nfreq, const std::vector<std::string> &pol,
double freq0_MHz, double freq1_MHz, double dt_sample, ssize_t ipos0=0,
double time0=0.0, int bitshuffle=2, int nt_chunk=128);
// Note that there is no close() member function. The file is flushed to disk and closed when the
// intensity_hdf5_ofile destructor is called.
~intensity_hdf5_ofile();
//
// Append a chunk of data, of length 'nt_chunk.
// The 'intensity' and 'weight' arrays have shape (nfreq, npol, nt_chunk).
// The mandatory 'chunk_ipos' arg is the index of the first sample in the chunk (in downsampled units).
// The optional 'chunk_t0' arg is the arrival time of the first sample in the chunk (if omitted, will be inferred from 'chunk_ipos').
//
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos, double chunk_t0);
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos);
};
// -------------------------------------------------------------------------------------------------
//
// intensity_network_stream: stream object which receives a packet stream from the network.
//
// (Writing a packet stream is handled by a separate class intensity_network_ostream, see below.)
//
// When the intensity_network_stream object is constructed, threads are automatically spawned to read and process
// packets. The stream presents the incoming data to the "outside world" as a per-beam sequence
// of regular arrays which are obtained by calling get_assembled_chunk().
//
// Reminder: normal shutdown sequence works as follows.
//
// - in network thread, end-of-stream packet is received (in intensity_network_stream::_network_thread_body())
// - network thread calls intensity_network_stream::_network_thread_exit().
// - stream state is advanced to 'stream_end_requested', this means that stream has exited but not all threads have joined.
// - unassembled_ringbuf.end_stream() is called, which will tell the assembler thread that there are no more packets.
//
// - in assembler thread, unassembled_ringbuf.get_packet_list() returns false.
// - the assembler thread loops over all beams ('assemblers') and calls assembled_chunk_ringbuf::end_stream()
// - this sets assembled_chunk_ringbuf::doneflag
//
// - in dedispersion thread, assembled_chunk_ringbuf::end_stream() returns an empty pointer.
struct packet_counts {
struct timeval tv;
double period; // in seconds
std::unordered_map<uint64_t, uint64_t> counts;
// Default constructor
packet_counts();
// Copy constructor
packet_counts(const packet_counts& other);
// Convert keys to IP:port format
std::unordered_map<std::string, uint64_t> to_string() const;
double start_time() const;
void increment(const struct sockaddr_in& sender_addr, int nbytes);
void update(const packet_counts& other);
};
class intensity_network_stream : noncopyable {
public:
// The 'struct initializer' is used to construct the stream object. A few notes:
//
// - Beams are identified in the packet profile by an opaque uint16_t. The 'beam_ids' argument
// should be the list of beam_ids which we expect to receive.
//
// - The throw_exception_on_buffer_drop, throw_exception_on_assembler_miss flags are useful
// for a unit test, but probably don't make sense otherwise.
//
// - Our network protocol doesn't define any way of indicating end-of-stream. This makes sense for the
// realtime search, but for testing we'd like to have a way of shutting down gracefully. If the
// accept_end_of_stream_packets flag is set, then a special packet with nbeams=nupfreq=nt=0 is
// interpreted as an "end of stream" flag, and triggers shutdown of the network_stream.
//
// - If 'nrfifreq' is initialized to a nonzero value, then memory will be allocated in each
// assembled_chunk for the RFI bitmask. The "downstream" pipeline must fill the mask in each
// chunk. If this does not happen quickly enough (more precisely, by the time the chunk
// leaves the top level of the telescoping ring buffer) then an exception will be thrown.
struct initializer {
std::vector<int> beam_ids;
std::shared_ptr<memory_slab_pool> memory_pool;
std::vector<std::shared_ptr<output_device>> output_devices;
int nupfreq = 0;
int nrfifreq = 0;
int nt_per_packet = 0;
int fpga_counts_per_sample = 384;
int stream_id = 0; // only used in assembled_chunk::format_filename().
// If 'nt_align' is set to a nonzero value, then the time sample index of the first
// assembled_chunk in the stream must be a multiple of nt_align. This is used in the
// real-time server, to align all beams to the RFI and dedispersion block sizes. Note
// that if nt_align is enabled, then some packets may be dropped, and these will be
// treated as assembler misses.
int nt_align = 0;
// If 'frame0_url' is a nonempty string, then assembler thread will retrieve frame0 info by "curling" the URL.
std::string frame0_url = "";
int frame0_timeout = 3000;
// If ipaddr="0.0.0.0", then network thread will listen on all interfaces.
std::string ipaddr = "0.0.0.0";
int udp_port = constants::default_udp_port;
bool force_reference_kernels = false;
bool force_fast_kernels = false;
bool emit_warning_on_buffer_drop = true;
bool throw_exception_on_beam_id_mismatch = true;
bool throw_exception_on_packet_mismatch = true;
bool throw_exception_on_buffer_drop = false;
bool throw_exception_on_assembler_miss = false;
bool accept_end_of_stream_packets = true;
bool deliberately_crash = false; // deliberately crash dedispersion thread (for debugging purposes, obviously)
// If nonempty, threads will be pinned to given list of cores.
std::vector<int> network_thread_cores;
std::vector<int> assembler_thread_cores;
// The recv_socket_timeout determines how frequently the network thread wakes up, while blocked waiting
// for packets. The purpose of the periodic wakeup is to check whether intensity_network_stream::end_stream()
// has been called, and check the timeout for flushing data to assembler threads.
//
// The stream_cancellation_latency_usec arg determines how frequently the network thread checks whether
// intensity_network_stream::end_stream() has been called. (We don't do this check in every iteration of
// the packet read loop, since it requires acquiring a lock.)
int max_packet_size = 9000;
int socket_bufsize = constants::default_socket_bufsize;
int socket_timeout_usec = 10000; // 0.01 sec
int stream_cancellation_latency_usec = 10000; // 0.01 sec
int packet_count_period_usec = 1000000; // 1 sec
int max_packet_history_size = 3600; // keep an hour of history
// The 'unassembled_ringbuf' is between the network thread and assembler thread.
int unassembled_ringbuf_capacity = 16;
int max_unassembled_packets_per_list = 16384;
int max_unassembled_nbytes_per_list = 8 * 1024 * 1024;
int unassembled_ringbuf_timeout_usec = 250000; // 0.25 sec
// The 'assembled_ringbuf' is between the assembler thread and processing threads.
int assembled_ringbuf_capacity = 8;
// The 'telescoping_ringbuf' stores assembled_chunks for retrieval by RPC.
// Its capacity is a vector, whose length is the number of downsampling levels,
// and whose elements are the number of assembled_chunks at each level.
std::vector<int> telescoping_ringbuf_capacity;
// A temporary hack that will go away soon.
// Sleep for specified number of seconds, after intensity_stream starts up.
double sleep_hack = 0.0;
};
// Event counts are kept in an array of the form int64_t[event_type::num_types].
// Currently we don't do anything with the event counts besides print them at the end,
// but they're intended to be a hook for real-time monitoring via RPC's.
enum event_type {
byte_received = 0,
packet_received = 1,
packet_good = 2,
packet_bad = 3,
packet_dropped = 4, // network thread will drop packets if assembler thread runs slow and ring buffer overfills
packet_end_of_stream = 5,
beam_id_mismatch = 6, // beam id in packet doesn't match any element of initializer::beam_ids
stream_mismatch = 7, // stream params (nupfreq, nt_per_packet, fpga_counts_per_sample) don't match values sepcified in constructor
assembler_hit = 8,
assembler_miss = 9,
assembled_chunk_dropped = 10, // assembler thread will drop assembled_chunks if processing thread runs slow
assembled_chunk_queued = 11,
num_types = 12 // must be last
};
const initializer ini_params;
// The largest FPGA count in a received packet.
std::atomic<uint64_t> packet_max_fpga_seen;
// It's convenient to initialize intensity_network_streams using a static factory function make(),
// rather than having a public constructor. Note that make() spawns network and assembler threads,
// but won't listen for packets until start_stream() is called. Between calling make() and start_stream(),
// you'll want to spawn "consumer" threads which call get_assembled_chunk().
static std::shared_ptr<intensity_network_stream> make(const initializer &ini_params);
// High level control.
void start_stream(); // tells network thread to start listening for packets (if stream has already started, this is not an error)
void end_stream(); // requests stream exit (but stream will stop after a few timeouts, not immediately)
void join_threads(); // should only be called once, does not request stream exit, blocks until network and assembler threads exit
// This is the main routine called by the processing threads, to read data from one beam
// corresponding to ini_params.beam_ids[assembler_ix]. (Note that the assembler_index
// satisifes 0 <= assembler_ix < ini_params.beam_ids.size(), and is not a beam_id.)
std::shared_ptr<assembled_chunk> get_assembled_chunk(int assembler_index, bool wait=true);
// Can be called at any time, from any thread. Note that the event counts returned by get_event_counts()
// may slightly lag the real-time event counts (this behavior derives from wanting to avoid acquiring a
// lock in every iteration of the packet read loop).
std::vector<int64_t> get_event_counts();
std::unordered_map<std::string, uint64_t> get_perhost_packets();
std::vector<std::unordered_map<std::string, uint64_t> > get_statistics();
// Retrieves chunks from one or more ring buffers. The uint64_t
// return value is a bitmask of l1_ringbuf_level values saying
// where in the ringbuffer the chunk was found; this is an
// implementation detail revealed for debugging purposes.
//
// If a vector of beam numbers is given, only the ring buffers for
// those beams will be returned; otherwise the ring buffers for
// all beams will be returned.
std::vector< std::vector< std::pair<std::shared_ptr<assembled_chunk>, uint64_t> > >
get_ringbuf_snapshots(const std::vector<int> &beams = std::vector<int>(),
uint64_t min_fpga_counts=0, uint64_t max_fpga_counts=0);
// Searches the telescoping ring buffer for the given beam and fpgacounts start.
// If 'toplevel' is true, then only the top level of the ring buffer is searched.
// Returns an empty pointer iff stream has ended, and chunk is requested past end-of-stream.
// If anything else goes wrong, an exception will be thrown.
std::shared_ptr<assembled_chunk> find_assembled_chunk(int beam, uint64_t fpga_counts, bool toplevel=true);
// Returns the first fpgacount of the first chunk sent downstream by
// the given beam id.
uint64_t get_first_fpga_count(int beam);
// Returns the last FPGA count processed by each of the assembler,
// (in the same order as the "beam_ids" array), flushed downstream,
// and retrieved by downstream callers.
void get_max_fpga_count_seen(std::vector<uint64_t> &flushed,
std::vector<uint64_t> &retrieved);
// If period = 0, returns the packet rate with timestamp closest
// to *start*. If *start* is zero or negative, it is interpreted
// as seconds relative to now; otherwise as gettimeofday()
// seconds. Zero grabs the most recent rate. If *period* is
// given, the rate samples overlapping [start, start+period] are
// summed.
std::shared_ptr<packet_counts> get_packet_rates(double start, double period);
// Returns the set of packet rates with timestamps overlapping *start* to *end*.
// If *start* is zero, treat as NOW. If *start* or *end* are negative, NOW - that many seconds.
std::vector<std::shared_ptr<packet_counts> > get_packet_rate_history(double start, double end, double period);
// For debugging/testing purposes: pretend that the given
// assembled_chunk has just arrived. Returns true if there was
// room in the ring buffer for the new chunk.
bool inject_assembled_chunk(assembled_chunk* chunk);
// For debugging/testing: pretend a packet has just arrived.
void fake_packet_from(const struct sockaddr_in& sender, int nbytes);
// stream_to_files(): for streaming incoming data to disk.
//
// 'filename_pattern': see assembled_chunk::format_filename below (empty string means "streaming disabled")
//
// On the DRAO backend, this will probably be one of the following two possibilities:
// /local/acq_data/(ACQNAME)/beam_(BEAM)/chunk_(CHUNK).msg (save to local SSD in node)
// /frb-archiver-(STREAM)/acq_data/(ACQNAME)/beam_(BEAM)/chunk_(CHUNK).msg (save to NFS, with load-balancing)
//
// 'beam_ids': list of beam_ids to stream (if an empty list, this will also disable streaming)
//
// This should be a subset of the beam_ids processed by the intensity_network_stream,
// which in turn in a subset of all beam_ids processed by the node.
//
// 'priority': see write_chunk_request::priority below
//
// Throws an exception if anything goes wrong! When called from an RPC thread, caller will want to
// wrap in try..except, and use exception::what() to get the error message.
void stream_to_files(const std::string &filename_pattern, const std::vector<int> &beam_ids, int priority, bool need_rfi);
void get_streaming_status(std::string &filename_pattern,
std::vector<int> &beam_ids,
int &priority,
int &chunks_written,
size_t &bytes_written);
// For debugging: print state.
void print_state();
~intensity_network_stream();
protected:
// Constant after construction, so not protected by lock
std::vector<std::shared_ptr<assembled_chunk_ringbuf> > assemblers;
// Used to exchange data between the network and assembler threads
std::unique_ptr<udp_packet_ringbuf> unassembled_ringbuf;
// Written by network thread, read by outside thread
// How much wall time do we spend waiting in recvfrom() vs processing?
std::atomic<uint64_t> network_thread_waiting_usec;
std::atomic<uint64_t> network_thread_working_usec;
std::atomic<uint64_t> socket_queued_bytes;
// I'm not sure how much it actually helps bottom-line performace, but it seemed like a good idea
// to insert padding so that data accessed by different threads is in different cache lines.
char _pad1[constants::cache_line_size];
// Written by assembler thread, read by outside thread
std::atomic<uint64_t> assembler_thread_waiting_usec;
std::atomic<uint64_t> assembler_thread_working_usec;
// Initialized by assembler thread when first packet is received, constant thereafter.
uint64_t frame0_nano = 0; // nanosecond time() value for fgpacount zero.
char _pad1b[constants::cache_line_size];
// Used only by the network thread (not protected by lock)
//
// Note on event counting implementation: on short timescales, the network and assembler
// threads accumulate event counts into "local" arrays 'network_thread_event_subcounts',
// 'assembler_thread_event_subcounts'. On longer timescales, these local subcounts are
// accumulated into the global 'cumulative_event_counts'. This two-level accumulation
// scheme is designed to avoid excessive contention for the event_count_lock.
int sockfd = -1;
std::unique_ptr<udp_packet_list> incoming_packet_list;
std::vector<int64_t> network_thread_event_subcounts;
std::shared_ptr<packet_counts> network_thread_perhost_packets;
char _pad2[constants::cache_line_size];
// Used only by the assembler thread
std::vector<int64_t> assembler_thread_event_subcounts;
std::thread network_thread;
std::thread assembler_thread;
char _pad3[constants::cache_line_size];
// State model. These flags are protected by the state_lock and are set in sequence.
// Note that the 'stream_ended_requested' flag means that the stream shutdown is imminent,
// but doesn't mean that it has actually shut down yet, it may still be reading packets.
// So far it hasn't been necessary to include a 'stream_ended' flag in the state model.
pthread_mutex_t state_lock;
pthread_cond_t cond_state_changed; // threads wait here for state to change
bool stream_started = false; // set asynchonously by calling start_stream()
bool stream_end_requested = false; // can be set asynchronously by calling end_stream(), or by network/assembler threads on exit
bool join_called = false; // set by calling join_threads()
bool threads_joined = false; // set when both threads (network + assembler) are joined
char _pad4[constants::cache_line_size];
pthread_mutex_t event_lock;
std::vector<int64_t> cumulative_event_counts;
std::shared_ptr<packet_counts> perhost_packets;
pthread_mutex_t packet_history_lock;
std::map<double, std::shared_ptr<packet_counts> > packet_history;
// Streaming-related data (arguments to stream_to_files()).
std::mutex stream_lock; // FIXME need to convert pthread_mutex to std::mutex everywhere
std::string stream_filename_pattern;
std::vector<int> stream_beam_ids;
int stream_priority;
bool stream_rfi_mask;
int stream_chunks_written;
size_t stream_bytes_written;
// The actual constructor is protected, so it can be a helper function
// for intensity_network_stream::make(), but can't be called otherwise.
intensity_network_stream(const initializer &x);
void _open_socket();
void _network_flush_packets();
void _add_event_counts(std::vector<int64_t> &event_subcounts);
void _update_packet_rates(std::shared_ptr<packet_counts> last_packet_counts);
void network_thread_main();
void assembler_thread_main();
// Private methods called by the network thread.
void _network_thread_body();
void _network_thread_exit();
void _put_unassembled_packets();
// Private methods called by the assembler thread.
void _assembler_thread_body();
void _assembler_thread_exit();
// initializes 'frame0_nano' by curling 'frame0_url', called when first packet is received.
// NOTE that one must call curl_global_init() before, and curl_global_cleanup() after; in chime-frb-l1 we do this in the top-level main() method.
void _fetch_frame0();
};
// -------------------------------------------------------------------------------------------------
//
// assembled_chunk
//
// This is the data structure which is returned by intensity_network_stream::get_assembled_chunk().
// It repesents a regular subarray of the intensity data in a single beam.
//
// The data in the assembled_chunk is represented as 8-bit integers, with a coarser array of additive
// and mutiplicative offsets, but can be "decoded" to a simple floating-point array by calling
// assembled_chunk::decode().
//
// The 'offsets' and 'scales' arrays below are coarse-grained in both frequency and time, relative
// to the 'data' array. The level of frequency coarse-graining is the constructor argument 'nupfreq',
// and the level of time coarse-graining is the constructor-argument 'nt_per_packet'. For no particular
// reason, the number of coarse-grained frequency channels is a compile-time constant (constants::nfreq_coarse)
// whereas the number of fine-grained time samples is also a compile-time constant (constants::nt_per_assembled_chunk).
//
// Summarizing:
//
// fine-grained shape = (constants::nfreq_coarse * nupfreq, constants::nt_per_assembled_chunk)
// coarse-grained shape = (constants::nfreq_coarse, constants::nt_per_assembled_chunk / nt_per_packet)
//
// A note on timestamps: there are several units of time used in different parts of the CHIME pipeline.
//
// 1 fpga count = 2.56e-6 seconds (approx)
// 1 intensity sample = fpga_counts_per_sample * (1 fpga count)
// 1 assembled_chunk = constants::nt_per_assembled_chunk * (1 intensity sample)
//
// The 'isample' and 'ichunk' fields of the 'struct assembled_chunk' are simply defined by
// isample = (initial fpga count) / fpga_counts_per_sample
// ichunk = (initial fpga count) / (fpga_counts_per_sample * constants::nt_per_assembled_chunk)
//
// The 'binning' field of the 'struct assembled_chunk' is 1, 2, 4, 8, ... depending on what level
// of downsampling has been applied (i.e. the location of the assembled_chunk in the telescoping
// ring buffer). Note that consecutive chunks src1, src2 with the same binning will satisfy
// (src2->ichunk == src1->ichunk + binning).
class assembled_chunk : noncopyable {
public:
struct initializer {
int beam_id = 0;
int nupfreq = 0;
int nrfifreq = 0; // number of frequencies in downsampled RFI chain processing
int nt_per_packet = 0;
int fpga_counts_per_sample = 0;
int binning = 1;
int stream_id = 0; // only used in assembled_chunk::format_filename().
uint64_t ichunk = 0;
bool force_reference = false;
bool force_fast = false;
// "ctime" in nanoseconds of FGPAcount zero
uint64_t frame0_nano = 0;
// If a memory slab has been preallocated from a pool, these pointers should be set.
// Otherwise, both pointers should be empty, and the assembled_chunk constructor will allocate.
std::shared_ptr<memory_slab_pool> pool;
mutable memory_slab_t slab;
};
// Parameters specified at construction.
const int beam_id = 0;
const int nupfreq = 0;
const int nrfifreq = 0;
const int nt_per_packet = 0;
const int fpga_counts_per_sample = 0; // no binning factor applied here
const int binning = 0; // either 1, 2, 4, 8... depending on level in telescoping ring buffer
const int stream_id = 0;
const uint64_t ichunk = 0;
// "ctime" in nanoseconds of FGPAcount zero
const uint64_t frame0_nano = 0;
// Derived parameters.
const int nt_coarse = 0; // equal to (constants::nt_per_assembled_chunk / nt_per_packet)
const int nscales = 0; // equal to (constants::nfreq_coarse * nt_coarse)
const int ndata = 0; // equal to (constants::nfreq_coarse * nupfreq * constants::nt_per_assembled_chunk)
const int nrfimaskbytes = 0; // equal to (nrfifreq * constants::nt_per_assembled_chunk / 8)
const uint64_t isample = 0; // equal to ichunk * constants::nt_per_assembled_chunk
const uint64_t fpga_begin = 0; // equal to ichunk * constants::nt_per_assembled_chunk * fpga_counts_per_sample
const uint64_t fpga_end = 0; // equal to (ichunk+binning) * constants::nt_per_assembled_chunk * fpga_counts_per_sample
// Note: you probably don't want to call the assembled_chunk constructor directly!
// Instead use the static factory function assembed_chunk::make().
assembled_chunk(const initializer &ini_params);
virtual ~assembled_chunk();
// Returns C time() (seconds since the epoch, 1970.0) of the first/last sample in this chunk.
double time_begin() const;
double time_end() const;
// The following virtual member functions have default implementations,
// which are overridden by the subclass 'fast_assembled_chunk' to be faster
// on a CPU with the AVX2 instruction set, if certain conditions are met
// (currently nt_per_packet==16 and nupfreq even).
//
// If 'prescale' is specified, then the intensity array written by decode()
// will be multiplied by its value. This is a temporary workaround for some
// 16-bit overflow issues in bonsai. (We currently don't need prescaling
// in decode_subset(), but this could be added easily.)
//
// Warning (FIXME?): decode() and decode_subset() do not apply the RFI mask
// in assembled_chunk::rfi_mask (if this exists).
virtual void add_packet(const intensity_packet &p);
virtual void decode(float *intensity, float *weights, int istride, int wstride, float prescale=1.0) const;
virtual void decode_subset(float *intensity, float *weights, int t0, int nt, int istride, int wstride) const;
virtual void downsample(const assembled_chunk *src1, const assembled_chunk *src2); // downsamples data and RFI mask
// Static factory functions which can return either an assembled_chunk or a fast_assembled_chunk.
static std::unique_ptr<assembled_chunk> make(const initializer &ini_params);
static std::shared_ptr<assembled_chunk> read_msgpack_file(const std::string& filename);
// Note: the hdf5 file format has been phased out now..
void write_hdf5_file(const std::string &filename);
void write_msgpack_file(const std::string &filename, bool compress,
uint8_t* buffer=NULL);
// How big can the bitshuffle-compressed data for a chunk of this size become?
size_t max_compressed_size();
// Performs a printf-like pattern replacement on *pattern* given the parameters of this assembled_chunk.
// Replacements:
// (STREAM) -> %01i stream_id
// (BEAM) -> %04i beam_id
// (CHUNK) -> %08i ichunk
// (NCHUNK) -> %02i size in chunks
// (BINNING) -> %02i size in chunks
// (FPGA0) -> %012i start FPGA-counts
// (FPGAN) -> %08i FPGA-counts size
std::string format_filename(const std::string &pattern) const;
// Utility functions currently used only for testing.
void fill_with_copy(const std::shared_ptr<assembled_chunk> &x);
void randomize(std::mt19937 &rng); // also randomizes rfi_mask (if it exists)
static ssize_t get_memory_slab_size(int nupfreq, int nt_per_packet, int nrfifreq);
// I wanted to make the following fields protected, but msgpack doesn't like it...
// Primary buffers.
float *scales = nullptr; // 2d array of shape (constants::nfreq_coarse, nt_coarse)
float *offsets = nullptr; // 2d array of shape (constants::nfreq_coarse, nt_coarse)
uint8_t *data = nullptr; // 2d array of shape (constants::nfreq_coarse * nupfreq, constants::nt_per_assembled_chunk)
uint8_t *rfi_mask = nullptr; // 2d array of downsampled masks, packed bitwise; (nrfifreq x constants::nt_per_assembled_chunk / 8 bits)
// False on initialization.
// If the RFI mask is being saved (nrfifreq > 0), it will be subsequently set to True by the processing thread.
std::atomic<bool> has_rfi_mask;
std::atomic<int> packets_received;
// Temporary buffers used during downsampling.
float *ds_w2 = nullptr; // 1d array of length (nt_coarse/2)
float *ds_data = nullptr; // 2d array of shape (nupfreq, constants::nt_per_assembled_chunk/2)
int *ds_mask = nullptr; // 2d array of shape (nupfreq, constants::nt_per_assembled_chunk/2)
// Used in the write path, to keep track of writes to disk.
std::mutex filename_mutex;
std::unordered_set<std::string> filename_set;
std::unordered_map<std::string, std::string> filename_map; // hash output_device_name -> filename
protected:
// The array members above (scales, ..., ds_mask) are packed into a single contiguous memory slab.
std::shared_ptr<memory_slab_pool> memory_pool;
memory_slab_t memory_slab;
void _check_downsample(const assembled_chunk *src1, const assembled_chunk *src2);
// Note: destructors must call _deallocate()!
// Otherwise the memory_slab can't be returned to the pool.
void _deallocate();
};
// If the CPU has the AVX2 instruction set, and for some choices of packet parameters (the precise
// criterion is nt_per_packet == 16 and nupfreq % 2 == 0), we can speed up the assembled_chunk
// member functions using assembly language kernels.
class fast_assembled_chunk : public assembled_chunk
{
public:
// Note: you probably don't want to call the assembled_chunk constructor directly!
// Instead use the static factory function assembed_chunk::make().
fast_assembled_chunk(const assembled_chunk::initializer &ini_params);
virtual ~fast_assembled_chunk();
// Override viruals with fast assembly language versions.
virtual void add_packet(const intensity_packet &p) override;
virtual void decode(float *intensity, float *weights, int istride, int wstride, float prescale=1.0) const override;
virtual void downsample(const assembled_chunk *src1, const assembled_chunk *src2) override;
};
// -------------------------------------------------------------------------------------------------
//
// memory_slab_pool
class memory_slab_pool {
public:
// The 'verbosity' parameter has the following meaning:
// 0 = ninja-quiet
// 1 = a little output during initialization
// 2 = debug trace of all allocations/deallocations
memory_slab_pool(ssize_t nbytes_per_slab, ssize_t nslabs, const std::vector<int> &allocation_cores, int verbosity=1);
~memory_slab_pool();
// Returns a new slab from the pool.
//
// If the pool is empty, then either a null pointer is returned (wait=false),
// or get_slab() blocks until a slab is available (wait=true).
//
// If zero=true, then the new slab is zeroed.
memory_slab_t get_slab(bool zero=true, bool wait=false);
// Puts a slab back in the pool.
// Note: 'p' will be set to a null pointer after put_slab() returns.
void put_slab(memory_slab_t &p);
int count_slabs_available();
const ssize_t nbytes_per_slab;
const ssize_t nslabs;
const int verbosity;
protected:
std::mutex lock;
std::condition_variable cv;
std::vector<memory_slab_t> slabs;
ssize_t curr_size = 0;
ssize_t low_water_mark = 0;
// Called by constructor, in separate thread.
void allocate(const std::vector<int> &allocation_cores);
};
// -------------------------------------------------------------------------------------------------
//
// output_device and helper classes.
//
// FIXME(?): it would be natural to add member functions of 'class output_device' or
// 'class output_device_pool' which return summary information, such as number of
// chunks queued for writing, total number of chunks written, etc. (Same goes for
// the memory_slab_pool!)
// write_chunk_request: mini-struct consisting of a (chunk, filename, priority) triple.
//
// If the write_callback() virtual function is overridden, it will be called when the write
// request completes, either successfully or unsuccessfully. Note that the callback is made
// from the i/o thread!
struct write_chunk_request {
std::shared_ptr<assembled_chunk> chunk;
std::string filename;
int priority = 0;
bool need_rfi_mask = false;
// Called when the status of this chunk has changed --
// due to an error, successful completion, or, eg, RFI mask added.
virtual void status_changed(bool finished, bool success,
const std::string &state,
const std::string &error_message) { }
virtual ~write_chunk_request() { }
// This comparator class is used below, to make an STL priority queue.
struct _less_than {
bool operator()(const std::shared_ptr<write_chunk_request> &x, const std::shared_ptr<write_chunk_request> &y)
{
// Compare priority first, then time.
if (x->priority < y->priority) return true;
if (x->priority > y->priority) return false;
// Reversed inequality is intentional here (earlier time = higher priority)
return x->chunk->fpga_begin > y->chunk->fpga_begin;
}
};
};
// output_device: corresponds to one "device" where assembled_chunks may be written.
//
// An output_device is identified by a device_name string, which is a directory such
// as '/ssd0' or /nfs1'. When the output_device is created (with output_device::make(),
// an i/o thread is automatically spawned, which runs in the background.
class output_device : noncopyable {
public:
struct initializer {
std::string device_name; // if empty string, this output_device will write all chunks
std::string io_thread_name; // if empty string, a default io_thread_name will be used
std::vector<int> io_thread_allowed_cores; // if empty vector, the io thread will be unpinned
// Possible 'verbosity' values:
// 0 = log nothing
// 1 = log unsuccessful writes
// 2 = log i/o thread startup/shutdown
// 3 = verbose trace of all write_requests
int verbosity = 1;
};
const initializer ini_params;
// This factory function should be used to create a new output_device.
// Returns a shared_ptr to a new output_device, and spawns a thread which
// runs in the background, and also holds a shared_ptr.
static std::shared_ptr<output_device> make(const initializer &ini_params);
// Can be called by either the assembler thread, or an RPC thread.
// Returns 'false' if request could not be queued (because end_stream() was called)
bool enqueue_write_request(const std::shared_ptr<write_chunk_request> &req);
// Counts the number of queued write request chunks
int count_queued_write_requests();
// If 'wait' is true, then end_stream() blocks until pending writes are complete.
// If 'wait' is false, then end_stream() cancels all pending writes.
void end_stream(bool wait);
// Blocks until i/o thread exits. Call end_stream() first!
void join_thread();
// Called (by RFI thread) to notify that the given chunk has had its
// RFI mask filled in.
void filled_rfi_mask(const std::shared_ptr<assembled_chunk> &chunk);
protected:
std::thread output_thread;
// State model.
bool end_stream_called = false;
bool join_thread_called = false;
bool thread_joined = false;
// The priority queue of write requests to be run by the output thread.
std::priority_queue<std::shared_ptr<write_chunk_request>,
std::vector<std::shared_ptr<write_chunk_request>>,
write_chunk_request::_less_than> _write_reqs;
// Write requests where need_rfi_mask is set and the rfi mask isn't
// yet available.
std::vector<std::shared_ptr<write_chunk_request> > _awaiting_rfi;
// The state model and request queue are protected by this lock and condition variable.
std::mutex _lock;
std::condition_variable _cond;
// Temporary buffer used for assembled_chunk serialization, accessed only by I/O thread
std::unique_ptr<uint8_t[]> _buffer;
// Constructor is protected -- use output_device::make() instead!
output_device(const initializer &ini_params);
// This is "main()" for the i/o thread.
void io_thread_main();
// Helper function called by output thread.
// Blocks until a write request is available; returns highest-priority request.
std::shared_ptr<write_chunk_request> pop_write_request();
};
// output_device_pool: this little helper class is a wrapper around a list of
// output_devices with different device_names.
class output_device_pool {
public:
// Note: length-zero vector is OK!
output_device_pool(const std::vector<std::shared_ptr<output_device>> &streams);
// Sends the write request to the appropriate output_device (based on filename).
// Returns 'false' if request could not be queued.
bool enqueue_write_request(const std::shared_ptr<write_chunk_request> &req);
// Loops over output_devices, and calls either end_stream() or join_thread().
void end_streams(bool wait);
void join_threads();
protected:
std::vector<std::shared_ptr<output_device>> streams;
std::vector<std::string> device_names;
};
// -------------------------------------------------------------------------------------------------
//
// intensity_network_ostream: this class is used to packetize intensity data and send
// it over the network.
//
// The stream object presents the "oustide world" with an object which is fed regular
// chunks of data via a member function send_chunk(). Under the hood, send_chunk() is
// encoding each chunk as multiple UDP packets, which are handed off to a network
// thread running in the background.
class intensity_network_ostream : noncopyable {
public:
// The 'struct initializer' is used to construct the ostream object. A few notes:
//
// - It's convenient for the input to intensity_network_ostream to be a pair of
// floating-point arrays (intensity, weights). Since the packet protocol allows
// a boolean mask but not floating-point weights, we simply mask all samples
// whose weight is below some cutoff. This is the 'wt_cutoff' parameter.
//
// - Each UDP packet is a 4D logical array of shape
// (nbeams, nfreq_coarse_per_packet, nupfreq, nt_per_packet).
// Each chunk passed to send_chunk() is a 4D logical array of shape
// (nbeams, coarse_freq_ids.size(), nupfreq, nt_per_chunk)
// and will generally correspond to multiple packets.
//
// - If throttle=false, then UDP packets will be written as quickly as possible.
// If throttle=true, then the packet-throttling logic works as follows:
//
// - If target_gbps > 0.0, then packets will be transmitted at the
// specified rate in Gbps.
//
// - If target_gbps = 0, then the packet transmit rate will be inferred
// from the value of 'fpga_counts_per_sample', assuming 2.56 usec per
// fpga count. (This is the default.)
struct initializer {
std::string dstname;
std::vector<int> beam_ids;
std::vector<int> coarse_freq_ids; // will usually be [ 0, 1, ..., 1023 ], but reordering is allowed
int nupfreq = 0;
int nt_per_chunk = 0;
int nfreq_coarse_per_packet = 0;
int nt_per_packet = 0;
int fpga_counts_per_sample = 0;
float wt_cutoff = constants::default_wt_cutoff;
int bind_port = 0; // 0: don't bind; send from randomly assigned port
std::string bind_ip = "0.0.0.0";
bool throttle = true;
double target_gbps = 0.0;
bool is_blocking = true;
bool emit_warning_on_buffer_drop = true;
bool throw_exception_on_buffer_drop = false;
bool send_end_of_stream_packets = true;
bool print_status_at_end = true;
};
const initializer ini_params;
// Some of these fields are redundant with fields in the ini_params, but the redundancy is convenient.
const int nbeams;
const int nfreq_coarse_per_packet;
const int nfreq_coarse_per_chunk;
const int nupfreq;
const int nt_per_packet;
const int nt_per_chunk;
const int nbytes_per_packet;
const int npackets_per_chunk;
const int nbytes_per_chunk;
const int elts_per_chunk;
const uint64_t fpga_counts_per_sample;
const uint64_t fpga_counts_per_packet;
const uint64_t fpga_counts_per_chunk;
// Note: this->target_gpbs is not identical to ini_params.target_gpbs, since there is a case
// (ini_params.throttle=true and ini_params.target_gbps=0) where ini_params.target_gbps is zero,
// but this->target_gbps has a nonzero value inferred from 'fpga_counts_per_sample'.
double target_gbps = 0.0;
// It's convenient to initialize intensity_network_ostreams using a static factory function make(),
// rather than having a public constructor. Note that make() spawns a network thread which runs
// in the background.
static std::shared_ptr<intensity_network_ostream> make(const initializer &ini_params);
// Data is added to the network stream by calling send_chunk(). This routine packetizes
// the data and puts the packets in a thread-safe ring buffer, for the network thread to send.
//
// The 'intensity' and 'weights' arrays have logical shape
// (nbeams, nfreq_coarse_per_chunk, nupfreq, nt_per_chunk).
//
// The 'istride/wstride' args are tmemory offsets between time series in the intensity/weights arrays.
// To write this out explicitly, the intensity sample with logical indices (b,fcoarse,u,t) has memory location
// intensity + ((b + fcoarse*nupfreq) * nupfreq + u) * stride + t
void send_chunk(const float *intensity, int istride, const float *weights, int wstride, uint64_t fpga_count);
void get_statistics(int64_t& curr_timestamp,
int64_t& npackets_sent,
int64_t& nbytes_sent);
// Called when there is no more data; sends end-of-stream packets.
void end_stream(bool join_network_thread);
~intensity_network_ostream();
// This is a helper function called by send_chunk(), but we make it public so that the unit tests can call it.
void _encode_chunk(const float *intensity, int istride, const float *weights, int wstride, uint64_t fpga_count, const std::unique_ptr<udp_packet_list> &out);
void print_status(std::ostream &os = std::cout);
bool is_sending();
protected:
std::vector<uint16_t> beam_ids_16bit;
std::vector<uint16_t> coarse_freq_ids_16bit;
int sockfd = -1;
std::string hostname;
uint16_t udp_port = constants::default_udp_port;
pthread_mutex_t statistics_lock;
int64_t curr_timestamp = 0; // microseconds between first packet and most recent packet
int64_t npackets_sent = 0;
int64_t nbytes_sent = 0;
// State model.
pthread_t network_thread;
pthread_mutex_t state_lock;
pthread_cond_t cond_state_changed;
bool network_thread_started = false;
bool network_thread_joined = false;
// Ring buffer used to exchange packets with network thread
std::unique_ptr<udp_packet_ringbuf> ringbuf;
// Temp buffer for packet encoding
std::unique_ptr<udp_packet_list> tmp_packet_list;
// The actual constructor is protected, so it can be a helper function
// for intensity_network_ostream::make(), but can't be called otherwise.
intensity_network_ostream(const initializer &ini_params);
static void *network_pthread_main(void *opaque_args);
void _network_thread_body();
// For testing purposes (eg, can create a subclass that randomly drops packets), a wrapper on the underlying packet send() function.
virtual ssize_t _send(int socket, const uint8_t* packet, int nbytes, int flags);
void _open_socket();
void _send_end_of_stream_packets();
};
// -------------------------------------------------------------------------------------------------
//
// Miscellaneous
// Used in RPC's which return chunks, to indicate where the chunk was found.
// Note: implementation of assembled_chunk_ringbuf::get_ringbuf_snapshot() assumes
// that L1RB_LEVELn == 2^n, so be careful when modifying this!
enum l1_ringbuf_level {
L1RB_DOWNSTREAM = 1,
L1RB_LEVEL1 = 2,
L1RB_LEVEL2 = 4,
L1RB_LEVEL3 = 8,
L1RB_LEVEL4 = 0x10,
// queued for writing in the L1 RPC system
L1RB_WRITEQUEUE = 0x100,
};
extern void pin_thread_to_cores(const std::vector<int> &core_list);
// Utility routine: converts a string to type T (only a few T's are defined; see lexical_cast.cpp)
// Returns true on success, false on failure
template<typename T> extern bool lexical_cast(const std::string &x, T &ret);
// Also defined in lexical_cast.cpp (for the same values of T)
template<typename T> extern const char *typestr();
// Version of lexical_cast() which throws exception on failure.
template<typename T> inline T lexical_cast(const std::string &x, const char *name="string")
{
T ret;
if (lexical_cast(x, ret))
return ret;
throw std::runtime_error("couldn't convert " + std::string(name) + "='" + x + "' to " + typestr<T>());
}
// Unit tests
extern void test_lexical_cast();
extern void test_packet_offsets(std::mt19937 &rng);
extern void test_avx2_kernels(std::mt19937 &rng);
extern void peek_at_unpack_kernel();
} // namespace ch_frb_io
#endif // _CH_FRB_IO_HPP
| 44.240065 | 161 | 0.705507 | CHIMEFRB |
b240b483f53d28c2668fc46cb5c62b6ffad27663 | 1,886 | cpp | C++ | src/src/expr/evaluter_term.cpp | Yukikamome316/MineCode | 65ffbd06a05f09c11cbd43c4de934f97eaffca6d | [
"MIT"
] | 17 | 2020-12-07T10:58:03.000Z | 2021-09-10T05:49:38.000Z | src/src/expr/evaluter_term.cpp | Yukikamome316/MineCode | 65ffbd06a05f09c11cbd43c4de934f97eaffca6d | [
"MIT"
] | 2 | 2021-05-16T18:45:36.000Z | 2021-10-20T13:02:35.000Z | src/src/expr/evaluter_term.cpp | Yukikamome316/MineCode | 65ffbd06a05f09c11cbd43c4de934f97eaffca6d | [
"MIT"
] | 8 | 2021-01-11T09:11:21.000Z | 2021-09-02T17:52:46.000Z | #include <eval.h>
#include <parserCore.h>
#include <parserTypes.h>
#include <stmtProcessor.h>
#include <syntaxError.h>
#include <util.h>
using namespace parserTypes;
void eval::Term(parserCore *that, term obj, int dest) {
int offs = that->Asm->stack_offset;
struct offset {
enum Type { MUL, DIV, MOD };
Type type;
int offset;
};
std::vector<struct offset> stackOffsets;
if (obj.isSingle()) {
Expo(that, obj.parts[0].value, dest);
} else {
// write all
for (auto elem : obj.parts) {
Expo(that, elem.value, dest);
int offset = that->Asm->push(dest);
offset::Type type;
switch (elem.type) {
case expo_wrap::MUL:
type = offset::Type::MUL;
break;
case expo_wrap::DIV:
type = offset::Type::DIV;
break;
case expo_wrap::MOD:
type = offset::Type::MOD;
break;
default:
synErr::processError(that, L"Unknown expr_wrap type ", __FILE__,
__func__, __LINE__);
std::terminate(); // dead code
}
struct offset element;
element.type = type;
element.offset = offset;
stackOffsets.emplace_back(element);
}
that->Asm->writeRegister(1, dest); // init dest
for (auto a : stackOffsets) {
that->Asm->pop(a.offset, 14);
switch (a.type) {
case offset::MUL:
that->stream << "mullw r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
case offset::DIV:
that->stream << "divw r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
case offset::MOD:
that->stream << "#mod r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
}
}
}
that->Asm->stack_offset = offs;
} | 25.835616 | 74 | 0.513256 | Yukikamome316 |
b24543063e7a8606e02d514248c669a3d9159efa | 3,344 | cpp | C++ | PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | #include "Precompiled.hpp"
#include "RigidBody2d.hpp"
#include "Engine/Cog.hpp"
#include "Engine/Space.hpp"
#include "PhysicsSpace2d.hpp"
#include "Utilities/ZeroUtilities.hpp"
namespace Physics2d
{
//-------------------------------------------------------------------RigidBody2d
ZilchDefineType(RigidBody2d, builder, type)
{
ZeroBindSetup(Zero::SetupMode::DefaultSerialization);
ZeroBindComponent();
ZeroBindDocumented();
ZeroBindDependency(Zero::Cog);
ZeroBindDependency(Zero::Transform);
ZilchBindGetterSetterProperty(IsStatic);
ZilchBindGetterSetterProperty(LinearVelocity)->ZeroSerialize(Vector2::cZero);
ZilchBindGetterSetterProperty(AngularVelocity)->ZeroSerialize(0.0f);
ZilchBindFieldProperty(mInvMass)->ZeroSerialize(1.0f);
ZilchBindFieldProperty(mInvInertia)->ZeroSerialize(1.0f);
}
void RigidBody2d::Serialize(Zero::Serializer& stream)
{
MetaSerializeProperties(this, stream);
}
void RigidBody2d::Initialize(Zero::CogInitializer& initializer)
{
mSpace = GetSpace()->has(PhysicsSpace2d);
if(mSpace == nullptr)
return;
mSpace->Add(this);
ReadTransform();
}
void RigidBody2d::TransformUpdate(Zero::TransformUpdateInfo& info)
{
bool isPhysicsUpdate = (info.TransformFlags & Zero::TransformUpdateFlags::Physics) != 0;
if(!isPhysicsUpdate)
ReadTransform();
}
void RigidBody2d::OnDestroy(uint flags)
{
if(mSpace == nullptr)
return;
mSpace->Remove(this);
}
bool RigidBody2d::GetIsStatic() const
{
return mIsStatic;
}
void RigidBody2d::SetIsStatic(bool isStatic)
{
mIsStatic = isStatic;
if(mSpace != nullptr)
mSpace->UpdateRigidBodyDynamicState(this);
}
float RigidBody2d::GetInvMass() const
{
if(mIsStatic)
return 0.0f;
return mInvMass;
}
void RigidBody2d::SetInvMass(float invMass)
{
mInvMass = invMass;
}
float RigidBody2d::GetInvInertia() const
{
if(mIsStatic)
return 0.0f;
return mInvInertia;
}
void RigidBody2d::SetInvInertia(float invInertia)
{
mInvInertia = invInertia;
}
Vector2 RigidBody2d::GetWorldCenterOfMass() const
{
return mWorldCenterOfMass;
}
void RigidBody2d::SetWorldCenterOfMass(const Vector2& worldCenterOfMass)
{
mWorldCenterOfMass = worldCenterOfMass;
}
float RigidBody2d::GetWorldRotation() const
{
return mWorldRotation;
}
Vector2 RigidBody2d::GetLinearVelocity() const
{
return mLinearVelocity;
}
void RigidBody2d::SetLinearVelocity(const Vector2& linearVelocity)
{
mLinearVelocity = linearVelocity;
}
float RigidBody2d::GetAngularVelocity() const
{
return mAngularVelocity;
}
void RigidBody2d::SetAngularVelocity(float angularVelocity)
{
mAngularVelocity = angularVelocity;
}
void RigidBody2d::GetVelocities(Vector2& linearVelocity, float& angularVelocity) const
{
linearVelocity = mLinearVelocity;
angularVelocity = mAngularVelocity;
}
void RigidBody2d::SetVelocities(const Vector2& linearVelocity, float angularVelocity)
{
mLinearVelocity = linearVelocity;
mAngularVelocity = angularVelocity;
}
void RigidBody2d::SetNode(Physics2dNode* node)
{
mNode = node;
}
Physics2dNode* RigidBody2d::GetNode()
{
return mNode;
}
void RigidBody2d::ReadTransform()
{
Zero::Transform* transform = GetOwner()->has(Zero::Transform);
mWorldCenterOfMass = ZeroUtilities::GetWorldTranslation(transform);
mWorldRotation = ZeroUtilities::GetWorldRotation(transform);
}
}//namespace Physics2d
| 20.9 | 90 | 0.75299 | jodavis42 |
b24fdc9bd6f32d5eddd556105561518396f867f4 | 2,453 | cpp | C++ | src/world/csvr/Parser.cpp | desktopgame/ofxPlanet | fe364e83f4c0ec0f169df63ce989a88ae6328c07 | [
"BSD-2-Clause",
"MIT"
] | 3 | 2020-02-24T14:19:20.000Z | 2021-05-17T11:25:07.000Z | src/world/csvr/Parser.cpp | desktopgame/ofxPlanet | fe364e83f4c0ec0f169df63ce989a88ae6328c07 | [
"BSD-2-Clause",
"MIT"
] | 1 | 2020-02-25T09:20:34.000Z | 2020-02-25T09:38:49.000Z | src/world/csvr/Parser.cpp | desktopgame/ofxPlanet | fe364e83f4c0ec0f169df63ce989a88ae6328c07 | [
"BSD-2-Clause",
"MIT"
] | 1 | 2021-08-14T07:12:42.000Z | 2021-08-14T07:12:42.000Z | #include "parser.hpp"
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
namespace ofxPlanet {
namespace csvr {
Parser::Parser() : tables() {}
void Parser::parse(const std::string& source) {
int start = 0;
while (true) {
Table table;
int read = parse(start, source, table);
if (start >= static_cast<int>(source.size())) {
break;
}
start += read;
this->tables.emplace_back(table);
}
}
Table& Parser::getTableAt(int index) { return tables.at(index); }
const Table& Parser::getTableAt(int index) const { return tables.at(index); }
int Parser::getTableCount() const { return static_cast<int>(tables.size()); }
int Parser::parse(int start, const std::string& source, Table& table) {
int len = static_cast<int>(source.size());
int read = 0;
int columns = 0;
Line line;
std::stringstream sbuf;
for (int i = start; i < len; i++) {
char c = source.at(i);
read++;
if (c == separator) {
line.emplace_back(sbuf.str());
sbuf.str("");
sbuf.clear(std::stringstream::goodbit);
columns++;
} else if (c == newline) {
if (i == 0) {
continue;
}
auto str = sbuf.str();
if (isNullOrEmpty(str) && columns == 0) {
return read;
} else {
line.emplace_back(str);
sbuf.str("");
sbuf.clear(std::stringstream::goodbit);
table.emplace_back(line);
line.clear();
}
columns = 0;
} else {
sbuf << c;
}
}
return read;
}
bool Parser::isNullOrEmpty(const std::string& str) {
if (str.empty()) {
return true;
}
for (auto c : str) {
if (!std::isspace(c)) {
return false;
}
}
return true;
}
} // namespace csvr
} // namespace ofxPlanet | 33.148649 | 77 | 0.416633 | desktopgame |
b2506097ff0fe500e6be1b5f819e94c3a7b1d673 | 467 | cpp | C++ | C++/isPalindrome.cpp | xtt129/LeetCode | 1afa893d38e2fce68e4677b34169c0f0262b6fac | [
"MIT"
] | 2 | 2020-04-08T17:57:43.000Z | 2021-11-07T09:11:51.000Z | C++/isPalindrome.cpp | xtt129/LeetCode | 1afa893d38e2fce68e4677b34169c0f0262b6fac | [
"MIT"
] | null | null | null | C++/isPalindrome.cpp | xtt129/LeetCode | 1afa893d38e2fce68e4677b34169c0f0262b6fac | [
"MIT"
] | 8 | 2018-03-13T18:20:26.000Z | 2022-03-09T19:48:11.000Z | // Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
int d = 1;
for(; x / d >= 10 ; d *= 10);
for(; x > 0; x = (x % d) / 10, d /= 100) {
int q = x / d;
int r = x % 10;
if(q != r)
return false;
}
return true;
}
};
| 20.304348 | 54 | 0.329764 | xtt129 |
b250704696796f07757187ddd0f347e9fd3a5209 | 2,052 | hh | C++ | src/ui/win32/bindings/NumericUpDownBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 71 | 2018-04-15T13:02:43.000Z | 2022-03-26T11:19:18.000Z | src/ui/win32/bindings/NumericUpDownBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 309 | 2018-04-15T12:10:59.000Z | 2022-01-22T20:13:04.000Z | src/ui/win32/bindings/NumericUpDownBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 17 | 2018-04-17T16:09:31.000Z | 2022-03-04T08:49:03.000Z | #ifndef RA_UI_WIN32_NUMERICUPDOWNBINDING_H
#define RA_UI_WIN32_NUMERICUPDOWNBINDING_H
#pragma once
#include "NumericTextBoxBinding.hh"
namespace ra {
namespace ui {
namespace win32 {
namespace bindings {
class NumericUpDownBinding : public NumericTextBoxBinding
{
public:
explicit NumericUpDownBinding(ViewModelBase& vmViewModel) noexcept
: NumericTextBoxBinding(vmViewModel)
{
GSL_SUPPRESS_F6 BindKey(VK_UP, [this]()
{
Adjust(1); return true;
});
GSL_SUPPRESS_F6 BindKey(VK_DOWN, [this]()
{
Adjust(-1); return true;
});
}
void SetWrapAround(bool bValue) noexcept { m_bWrapAround = bValue; }
void SetSpinnerControl(const DialogBase& pDialog, int nControlResourceId) noexcept
{
SetSpinnerHWND(GetDlgItem(pDialog.GetHWND(), nControlResourceId));
}
void SetSpinnerHWND(HWND hControl) noexcept
{
m_hWndSpinner = hControl;
ControlBinding::AddSecondaryControlBinding(hControl);
}
void OnUdnDeltaPos(const NMUPDOWN& lpUpDown)
{
Adjust(-lpUpDown.iDelta); // up returns negative data
}
protected:
void Adjust(int nAmount)
{
std::wstring sBuffer;
GetText(sBuffer);
wchar_t* pEnd;
int nVal = std::wcstol(sBuffer.c_str(), &pEnd, 10);
nVal += nAmount;
if (nVal < m_nMinimum)
nVal = m_bWrapAround ? m_nMaximum : m_nMinimum;
else if (nVal > m_nMaximum)
nVal = m_bWrapAround ? m_nMinimum : m_nMaximum;
if (m_pValueBoundProperty)
{
SetValue(*m_pValueBoundProperty, nVal);
}
else
{
std::wstring sValue = std::to_wstring(nVal);
SetWindowTextW(m_hWnd, sValue.c_str());
UpdateSourceFromText(sValue);
}
}
HWND m_hWndSpinner = nullptr;
bool m_bWrapAround = false;
};
} // namespace bindings
} // namespace win32
} // namespace ui
} // namespace ra
#endif // !RA_UI_WIN32_NUMERICUPDOWNBINDING_H
| 24.428571 | 86 | 0.63499 | Jamiras |
b25451f79ccd6a2b2420e0d7196676082dedbb56 | 362 | hpp | C++ | core/LinearActivation.hpp | CltKitakami/NeuralNetwork | 78f2ba1cc38b16d94c10341fe3c5afd8f684db7e | [
"MIT"
] | null | null | null | core/LinearActivation.hpp | CltKitakami/NeuralNetwork | 78f2ba1cc38b16d94c10341fe3c5afd8f684db7e | [
"MIT"
] | null | null | null | core/LinearActivation.hpp | CltKitakami/NeuralNetwork | 78f2ba1cc38b16d94c10341fe3c5afd8f684db7e | [
"MIT"
] | null | null | null | #ifndef _LINEARACTIVATION_HPP_
#define _LINEARACTIVATION_HPP_
#include "Activation.hpp"
namespace nn {
class LinearActivation : public Activation
{
public:
virtual ~LinearActivation() = default;
virtual void forward(MatrixType &) override {}
virtual void backward(MatrixType &x) override
{
x = MatrixType::Ones(x.rows(), x.cols());
};
};
}
#endif
| 14.48 | 47 | 0.729282 | CltKitakami |
b258a92d14a33205982860ce6fcfc512805b1cfa | 26,537 | cpp | C++ | Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp | iscalab/PCIe_FPGA_Accel | bd601ac5b212583fd6329721ff21a857ae45a0d6 | [
"MIT"
] | 5 | 2018-12-11T03:17:17.000Z | 2021-11-17T06:30:50.000Z | Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp | dbakoyiannis/PCIe_FPGA_Accel | 1980073afba12c0d3d6accb95066c591e428180a | [
"MIT"
] | null | null | null | Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp | dbakoyiannis/PCIe_FPGA_Accel | 1980073afba12c0d3d6accb95066c591e428180a | [
"MIT"
] | 2 | 2021-04-04T08:47:03.000Z | 2021-04-27T12:32:48.000Z | /*******************************************************************************
* Filename: acceleration_scheduler_sg_xdma.cpp
* Author: Dimitrios Bakoyiannis <[email protected]>
* License:
*
* MIT License
*
* Copyright (c) [2018] [Dimitrios Bakoyiannis]
*
* 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ap_int.h"
#include "ap_utils.h"
#include "ap_cint.h"
#include "ap_utils.h"
#include "ap_int.h"
#include "acceleration_scheduler_sg_xdma.h"
/*
* -----------------------------
* Registers of the Sobel Filter
* -----------------------------
*/
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL 0x00
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_ROWS_DATA 0x18
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_COLS_DATA 0x20
/*
* -------------------------------------------------------------
* Registers and Masks of the AXI Performance Monitor Unit (APM)
* -------------------------------------------------------------
*/
#define XAPM_CR_GCC_RESET_MASK 0x00020000 // Global Clock Counter (GCC) Reset Mask.
#define XAPM_CR_GCC_ENABLE_MASK 0x00010000 // Global Clock Counter (GCC) Enable Mask.
#define XAPM_CR_MCNTR_RESET_MASK 0x00000002 // Metrics Counter Reset Mask.
#define XAPM_CR_MCNTR_ENABLE_MASK 0x00000001 // Metrics Counter Enable Mask.
#define XAPM_CTL_OFFSET 0x0300 // Control Register Offset.
#define XAPM_GCC_HIGH_OFFSET 0x0000 // Global Clock Counter 32 to 63 bits (Upper) Register Offset.
#define XAPM_GCC_LOW_OFFSET 0x0004 // Global Clock Counter 0 to 31 bits (Lower) Register Offset.
#define XAPM_MC0_OFFSET 0x0100 // Metrics Counter 0 Register Offset.
#define XAPM_MC1_OFFSET 0x0110 // Metrics Counter 1 Register Offset.
#define XAPM_MC2_OFFSET 0x0120 // Metrics Counter 2 Register Offset.
#define XAPM_MC3_OFFSET 0x0130 // Metrics Counter 3 Register Offset.
#define XAPM_MC4_OFFSET 0x0140 // Metrics Counter 4 Register Offset.
#define XAPM_MC5_OFFSET 0x0150 // Metrics Counter 5 Register Offset.
/*
* --------------------------------------
* Registers of the DMA SG PCIe Scheduler
* --------------------------------------
*/
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL 0x00 // Control Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE 0x04 // Global Interrupt Enable Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER 0x08 // Interrupt Enable Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_ISR 0x0C // Interrupt Interrupt Status Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_REQUESTED_DATA_SIZE_DATA 0x20 // Data Size Register for the Scatter/Gather Transfer.
/*
* acceleration_scheduler_sg_xdma()
*
* The Hardware Funtionality of the Acceleration Scheduler Scatter/Gather Core.
*
* The Acceleration Scheduler Scatter/Gather Core is Part of the Acceleration Group Scatter/Gather and is Used to Manage the whole Acceleration Procedure.
* It Interacts with the DMA SG PCIe Scheduler, Sobel Filter and APM of the Acceleration Group Direct as well as the Shared Timer (Shared APM) to Get Time Metrics.
* It, also, Interacts with the Interrupt Manager to Signalize the Completion of the Acceleration Procedure.
*
* The Sequential Steps of the Acceleration Procedure are as Follows:
*
* a --> Enable the Counters of the AXI Performance Monitor Unit (APM).
* b --> Read the Current Value of the Shared Timer to Get the Time that the Acceleration Started.
* c --> Setup and Start the Sobel Filter.
* d --> Enable the Interrupts of the DMA SG PCIe Scheduler.
* e --> Setup and Start the DMA SG PCIe Scheduler.
* f --> Wait for an Interrupt by the DMA SG PCIe Scheduler on Completion of the Acceleration.
* g --> Read the Current Value of the Shared Timer to Get the Time that the Acceleration Ended.
* h --> Disable the Counters of the AXI Performance Monitor Unit (APM).
* i --> Clear and Re-Enable the Interrupts of the DMA SG PCIe Scheduler.
* j --> Collect the Metrics from the Counters of the AXI Performance Monitor Unit (APM).
* k --> Reset the Counters of the AXI Performance Monitor Unit (APM).
* l --> Inform the Interrupt Manager About the Completion of the Acceleration Procedure.
*
* The Function Parameters are the Input/Output Ports/Interfaces of the Core:
*
* 01 --------> The AXI Master Interface of the Core Used to Access External Devices and Memories.
* 02 --------> Single Bit Input Used to Receive External Interrupts from the DMA SG PCIe Scheduler.
* 03 to 11 --> Registers of the Core that are Accessed through the AXI Slave Lite Interface of the Core.
*/
int acceleration_scheduler_sg_xdma(/*01*/volatile ap_uint<32> *ext_cfg,
/*02*/volatile ap_uint<1> *scheduler_intr_in,
/*03*/unsigned int dma_sg_pcie_scheduler_base_address,
/*04*/unsigned int sobel_device_address,
/*05*/unsigned int interrupt_manager_register_offset,
/*06*/unsigned int apm_device_address,
/*07*/unsigned int shared_apm_device_address,
/*08*/unsigned int shared_metrics_address,
/*09*/unsigned int image_cols,
/*10*/unsigned int image_rows,
/*11*/unsigned int accel_group
)
{
/*
* The ext_cfg is the AXI Master Interface of the Core.
*/
#pragma HLS INTERFACE m_axi port=ext_cfg
/*
* The scheduler_intr_in is a Single Bit Input which is Used to Receive External Interrupts from the DMA SG PCIe Scheduler.
*/
#pragma HLS INTERFACE ap_none port=scheduler_intr_in
/*
* The dma_sg_pcie_scheduler_base_address is a Register to Store the Base Address of the DMA SG PCIe Scheduler that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=dma_sg_pcie_scheduler_base_address bundle=mm2s_cfg
/*
* The sobel_device_address is a Register to Store the Base Address of the Sobel Filter that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=sobel_device_address bundle=mm2s_cfg
/*
* The interrupt_manager_register_offset is a Register to Store the Offset of a Specific Register of the Interrupt Manager that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=interrupt_manager_register_offset bundle=mm2s_cfg
/*
* The apm_device_address is a Register to Store the Base Address of the AXI Performance Monitor Unit (APM) that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=apm_device_address bundle=mm2s_cfg
/*
* The shared_apm_device_address is a Register to Store the Base Address of the Shared Timer (APM) that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=shared_apm_device_address bundle=mm2s_cfg
/*
* The shared_metrics_address is a Register to Store the Base Address of the Memory that this Core
* will Need to Access through the ext_cfg AXI Master Interface in Order to Write the Metrics Information.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=shared_metrics_address bundle=mm2s_cfg
/*
* The image_cols is a Register to Store the Number of Columns of the Image that will be Accelerated.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=image_cols bundle=mm2s_cfg
/*
* The image_rows is a Register to Store the Number of Rows of the Image that will be Accelerated.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=image_rows bundle=mm2s_cfg
/*
* The accel_group is a Register to Store the Acceleration Group Number (0-6) that this Core Belongs to.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=accel_group bundle=mm2s_cfg
#pragma HLS INTERFACE s_axilite port=return bundle=mm2s_cfg
ap_uint<32> data_register; // Used to Temporalily Store Values when Reading or Writing from/to Registers of External Devices.
ap_uint<32> initial_data_register; // Used to Temporalily Store Values when Reading or Writing from/to Registers of External Devices.
ap_uint<32> read_transactions; // Store the Read Transactions from the APM.
ap_uint<32> read_bytes; // Store the Read Bytes from the APM.
ap_uint<32> write_transactions; // Store the Write Transactions from the APM
ap_uint<32> write_bytes; // Store the Write Bytes from the APM.
ap_uint<32> stream_packets; // Store the Stream Packets from the APM.
ap_uint<32> stream_bytes; // Store the Stream Bytes from the APM.
ap_uint<32> gcc_lower; // Store the Global Clock Counter Lower Register from the APM.
ap_uint<32> gcc_upper; // Store the Global Clock Counter Upper Register from the APM.
ap_uint<32> dma_accel_time_start_gcc_l; // Store the Acceleration Start Time Lower Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_start_gcc_u; // Store the Acceleration Start Time Upper Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_end_gcc_l; // Store the Acceleration End Time Lower Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_end_gcc_u; // Store the Acceleration End Time Upper Register from the Shared Timer (Shared APM).
ap_uint<1> scheduler_intr_in_value; // Used to Read the Last Value of the scheduler_intr_in_value Input Port.
/*
* -----------------------
* Enable the APM Counters
* -----------------------
*/
//Read the Control Register of the APM.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Required to Enable the GCC and Metrics Counters.
data_register = data_register | XAPM_CR_GCC_ENABLE_MASK | XAPM_CR_MCNTR_ENABLE_MASK;
//Write the new Value Back to the Control Register of the APM to Enable the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ---------------------------------------------------------------------------------------------------------------------
* Read the Upper and Lower Registers of the Global Clock Counter of the Shared Timer to Get DMA Acceleration Start Time
* ---------------------------------------------------------------------------------------------------------------------
*/
//Read the Lower Register of the GCC of the Shared Timer to Get the 32 LSBs of the Acceleration Start Time.
memcpy(&dma_accel_time_start_gcc_l, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 LSBs of the Acceleration Start Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_START_L_OFFSET) / 4), &dma_accel_time_start_gcc_l, sizeof(ap_uint<32>));
//Read the Upper Register of the GCC of the Shared Timer to Get the 32 MSBs of the Acceleration Start Time.
memcpy(&dma_accel_time_start_gcc_u, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 MSBs of the Acceleration Start Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_START_U_OFFSET) / 4), &dma_accel_time_start_gcc_u, sizeof(ap_uint<32>));
/*
* --------------------------------
* Setup and Start the Sobel Filter
* --------------------------------
*/
//Get the Sobel Filter Columns from the Internal Register (image_cols) of the Core.
data_register = image_cols;
//Write the Sobel Filter Columns to a Specific Offset of the Sobel Filter Device.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_COLS_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Get the Sobel Filter Rows from the Internal Register (image_rows) of the Core.
data_register = image_rows;
//Write the Sobel Filter Rows to a Specific Offset of the Sobel Filter Device.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_ROWS_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Control Register of the Sobel Filter.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL) / 4), sizeof(ap_uint<32>));
//Set the Appropriate Masks According to the Recently Read Value that Will be Needed to Start the Sobel Filter.
data_register = data_register & 0x80;
data_register = data_register | 0x01;
//Write the new Value Back to the Control Register of the Sobel Filter so that the Sobel Filter Gets Started.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ---------------------------------------------------
* Enable the Interrupts for the DMA SG PCIe Scheduler
* --------------------------------------------------
*/
//Read the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with a Mask to Configure the IER that all the Available IRQs Should be Enabled.
data_register = data_register | 0xFFFFFFFF;
//Write the new Value Back to the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), &data_register, sizeof(ap_uint<32>));
data_register = 0x1;
//Write the data_register Value to the Global Interrupt Enable Register (GIE) of the DMA SG PCIe Scheduler to Enable the Interrupts.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE) / 4), &data_register, sizeof(ap_uint<32>));
/*
* -----------------------------------------
* Setup and Start the DMA SG PCIe Scheduler
* -----------------------------------------
*/
//Calculate the Image/Transfer Size According to the Internal Registers (image_cols, image_rows) of the Core.
data_register = image_rows * image_cols * 4;
//Write the Transfer Size to the Requested Data Size Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_REQUESTED_DATA_SIZE_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Control Register of the DMA SG PCIe Scheduler.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL) / 4), sizeof(ap_uint<32>));
//Set the Appropriate Masks According to the Recently Read Value that Will be Needed to Start the Sobel Filter.
data_register = data_register & 0x80;
data_register = data_register | 0x01;
//Write the new Value Back to the Control Register of the DMA SG PCIe Scheduler so that the DMA SG PCIe Scheduler Gets Started.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ------------------------------------------
* Wait for a DMA SG PCIe Scheduler Interrupt
* ------------------------------------------
*/
//Make an Initial Read of the Current State of the scheduler_intr_in_value Input.
scheduler_intr_in_value = *scheduler_intr_in;
//Keep Looping for as long as the scheduler_intr_in_value Input Does not Reach a Logic 1 Value.
while(scheduler_intr_in_value != 1)
{
//Keep Reading the Last Value of the scheduler_intr_in Input.
scheduler_intr_in_value = *scheduler_intr_in;
}
//Reset the Reader Variable.
scheduler_intr_in_value = 0;
/*
* ---------------------------------------------------------------------------------------------------------------------
* Read the Upper and Lower Registers of the Global Clock Counter of the Shared Timer to Get DMA Acceleration End Time
* ---------------------------------------------------------------------------------------------------------------------
*/
//Read the Lower Register of the GCC of the Shared Timer to Get the 32 LSBs of the Acceleration End Time.
memcpy(&dma_accel_time_end_gcc_l, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 LSBs of the Acceleration End Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_END_L_OFFSET) / 4), &dma_accel_time_end_gcc_l, sizeof(ap_uint<32>));
//Read the Upper Register of the GCC of the Shared Timer to Get the 32 MSBs of the Acceleration End Time.
memcpy(&dma_accel_time_end_gcc_u, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 MSBs of the Acceleration End Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_END_U_OFFSET) / 4), &dma_accel_time_end_gcc_u, sizeof(ap_uint<32>));
/*
* ------------------------
* Disable the APM Counters
* ------------------------
*/
//Read the Control Register of the APM.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Accordingly to Disable the GCC and Metrics Counters.
data_register = data_register & ~(XAPM_CR_GCC_ENABLE_MASK) & ~(XAPM_CR_MCNTR_ENABLE_MASK);
//Write the new Value Back to the Control Register of the APM to Disable the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* -------------------------------------------------------------
* Clear and then Re-Enable the DMA SG PCIe Scheduler Interrupts
* -------------------------------------------------------------
*/
//Set a Mask to Clear the Interrupt Status Register of the DMA SG PCIe Scheduler.
data_register = data_register | 0xFFFFFFFF;
//Clear the Interrupt Status Register of the DMA SG PCIe Scheduler According to the Previous Mask.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_ISR) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Interrupt Enable Register of the DMA SG PCIe Scheduler
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with a Mask to Configure the IER that all the Available IRQs Should be Enabled.
data_register = data_register | 0xFFFFFFFF;
//Write the new Value Back to the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), &data_register, sizeof(ap_uint<32>));
data_register = 0x1;
//Write the data_register Value to the Global Interrupt Enable Register (GIE) of the DMA SG PCIe Scheduler to Enable the Interrupts.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE) / 4), &data_register, sizeof(ap_uint<32>));
/*
* --------------------------------------------------------------------------
* Read the APM Metrics Counters and Store their Values to the Metrics Memory
* --------------------------------------------------------------------------
*/
//Get the Read Transactions from the APM and Write it to the Shared Metrics Memory
memcpy(&read_transactions, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC0_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_READ_TRANSACTIONS_OFFSET) / 4), &read_transactions, sizeof(ap_uint<32>));
//Get the Read Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&read_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC1_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_READ_BYTES_OFFSET) / 4), &read_bytes, sizeof(ap_uint<32>));
//Get the Write Transactions from the APM and Write it to the Shared Metrics Memory
memcpy(&write_transactions, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC2_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_WRITE_TRANSACTIONS_OFFSET) / 4), &write_transactions, sizeof(ap_uint<32>));
//Get the Write Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&write_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC3_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_WRITE_BYTES_OFFSET) / 4), &write_bytes, sizeof(ap_uint<32>));
//Get the Stream Packets from the APM and Write it to the Shared Metrics Memory
memcpy(&stream_packets, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC4_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_PACKETS_OFFSET) / 4), &stream_packets, sizeof(ap_uint<32>));
//Get the Stream Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&stream_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC5_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_BYTES_OFFSET) / 4), &stream_bytes, sizeof(ap_uint<32>));
//Get the GCC Lower Register from the APM and Write it to the Shared Metrics Memory
memcpy(&gcc_lower, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_GCC_L_OFFSET) / 4), &gcc_lower, sizeof(ap_uint<32>));
//Get the GCC Upper Register from the APM and Write it to the Shared Metrics Memory
memcpy(&gcc_upper, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_GCC_U_OFFSET) / 4), &gcc_upper, sizeof(ap_uint<32>));
/*
* ----------------------
* Reset the APM Counters
* ----------------------
*/
//Read the Control Register of the APM.
memcpy(&initial_data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Accordingly to Reset the GCC and Metrics Counters.
data_register = initial_data_register | XAPM_CR_GCC_RESET_MASK | XAPM_CR_MCNTR_RESET_MASK;
//Write the new Value Back to the Control Register of the APM to Reset the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
//Now Reverse the Value of the Previous Masks in order to Release the Reset.
data_register = initial_data_register & ~(XAPM_CR_GCC_RESET_MASK) & ~(XAPM_CR_MCNTR_RESET_MASK);
//Write the new Value Back to the Control Register of the APM to Release the Reset.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ------------------------------------------------------------------------------------
* Inform the Interrupt Manager that this Core Has Completed the Acceleration Procedure
* ------------------------------------------------------------------------------------
*/
//Get from the Internal Register (accel_group) of the Core the Current Acceleration Group Number that this Core Belongs to.
data_register = accel_group;
//Write the Current Acceleration Group Number to a Specific Register of the Interrupt Manager to Let It Know which Acceleration Group Has Completed.
memcpy((ap_uint<32> *)(ext_cfg + (interrupt_manager_register_offset) / 4), &data_register, sizeof(ap_uint<32>));
return 1;
}
| 52.548515 | 187 | 0.703885 | iscalab |
b25f39b9c350db8114d85c4c171a568e8d87cdd3 | 5,936 | cpp | C++ | src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp | SemenMartynov/SPbPU_SystemProgramming | 151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e | [
"MIT"
] | null | null | null | src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp | SemenMartynov/SPbPU_SystemProgramming | 151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e | [
"MIT"
] | null | null | null | src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp | SemenMartynov/SPbPU_SystemProgramming | 151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e | [
"MIT"
] | null | null | null | #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <strsafe.h>
#include "logger.h"
#define BUFSIZE 512
DWORD WINAPI InstanceThread(LPVOID);
int _tmain(int argc, _TCHAR* argv[]) {
//Init log
initlog(argv[0]);
_tprintf(_T("Server is started.\n\n"));
BOOL fConnected = FALSE; // Флаг наличия подключенных клиентов
DWORD dwThreadId = 0; // Номер обслуживающего потока
HANDLE hPipe = INVALID_HANDLE_VALUE; // Идентификатор канала
HANDLE hThread = NULL; // Идентификатор обслуживающего потока
LPTSTR lpszPipename = _T("\\\\.\\pipe\\$$MyPipe$$"); // Имя создаваемого канала
//**************************************************************************
// Создание SECURITY_ATTRIBUTES и SECURITY_DESCRIPTOR объектов
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
// Инициализация SECURITY_DESCRIPTOR значениями по-умолчанию
if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) == 0) {
double errorcode = GetLastError();
writelog(_T("InitializeSecurityDescriptor failed, GLE=%d."), errorcode);
_tprintf(_T("InitializeSecurityDescriptor failed, GLE=%d.\n"), errorcode);
closelog();
exit(5000);
}
// Установка поля DACL в SECURITY_DESCRIPTOR в NULL
if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE) == 0) {
double errorcode = GetLastError();
writelog(_T("SetSecurityDescriptorDacl failed, GLE=%d."), errorcode);
_tprintf(_T("SetSecurityDescriptorDacl failed, GLE=%d.\n"), errorcode);
closelog();
exit(5001);
}
// Установка SECURITY_DESCRIPTOR в структуре SECURITY_ATTRIBUTES
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE; //запрещение наследования
//**************************************************************************
// Цикл ожидает клиентов и создаёт для них потоки обработки
for (;;) {
writelog(_T("Try to create named pipe on %s"), lpszPipename);
_tprintf(_T("Try to create named pipe on %s\n"), lpszPipename);
// Создаем канал:
if ((hPipe = CreateNamedPipe(
lpszPipename, // имя канала,
PIPE_ACCESS_DUPLEX, // режим отрытия канала - двунаправленный,
PIPE_TYPE_MESSAGE | // данные записываются в канал в виде потока сообщений,
PIPE_READMODE_MESSAGE | // данные считываются в виде потока сообщений,
PIPE_WAIT, // функции передачи и приема блокируются до их окончания,
5, // максимальное число экземпляров каналов равно 5 (число клиентов),
BUFSIZE, //размеры выходного и входного буферов канала,
BUFSIZE,
5000, // 5 секунд - длительность для функции WaitNamedPipe,
&sa))// дескриптор безопасности
== INVALID_HANDLE_VALUE) {
double errorcode = GetLastError();
writelog(_T("CreateNamedPipe failed, GLE=%d."), errorcode);
_tprintf(_T("CreateNamedPipe failed, GLE=%d.\n"), errorcode);
closelog();
exit(1);
}
writelog(_T("Named pipe created successfully!"));
_tprintf(_T("Named pipe created successfully!\n"));
// Ожидаем соединения со стороны клиента
writelog(_T("Waiting for connect..."));
_tprintf(_T("Waiting for connect...\n"));
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE :
(GetLastError() == ERROR_PIPE_CONNECTED);
// Если произошло соединение
if (fConnected) {
writelog(_T("Client connected!"));
writelog(_T("Creating a processing thread..."));
_tprintf(_T("Client connected!\nCreating a processing thread...\n"));
// Создаём поток для обслуживания клиента
hThread = CreateThread(
NULL, // дескриптор защиты
0, // начальный размер стека
InstanceThread, // функция потока
(LPVOID)hPipe, // параметр потока
0, // опции создания
&dwThreadId); // номер потока
// Если поток создать не удалось - сообщаем об ошибке
if (hThread == NULL) {
double errorcode = GetLastError();
writelog(_T("CreateThread failed, GLE=%d."), errorcode);
_tprintf(_T("CreateThread failed, GLE=%d.\n"), errorcode);
closelog();
exit(1);
}
else CloseHandle(hThread);
}
else {
// Если клиенту не удалось подключиться, закрываем канал
CloseHandle(hPipe);
writelog(_T("There are not connecrtion reqests."));
_tprintf(_T("There are not connecrtion reqests.\n"));
}
}
closelog();
exit(0);
}
DWORD WINAPI InstanceThread(LPVOID lpvParam) {
writelog(_T("Thread %d started!"), GetCurrentThreadId());
_tprintf(_T("Thread %d started!\n"), GetCurrentThreadId());
HANDLE hPipe = (HANDLE)lpvParam; // Идентификатор канала
// Буфер для хранения полученного и передаваемого сообщения
_TCHAR* chBuf = (_TCHAR*)HeapAlloc(GetProcessHeap(), 0, BUFSIZE * sizeof(_TCHAR));
DWORD readbytes, writebytes; // Число байт прочитанных и переданных
while (1) {
// Получаем очередную команду через канал Pipe
if (ReadFile(hPipe, chBuf, BUFSIZE*sizeof(_TCHAR), &readbytes, NULL)) {
// Посылаем эту команду обратно клиентскому приложению
if (!WriteFile(hPipe, chBuf, (lstrlen(chBuf) + 1)*sizeof(_TCHAR), &writebytes, NULL))
break;
// Выводим принятую команду на консоль
writelog(_T("Thread %d: Get client msg: %s"), GetCurrentThreadId(), chBuf);
_tprintf(TEXT("Get client msg: %s\n"), chBuf);
// Если пришла команда "exit", завершаем работу приложения
if (!_tcsncmp(chBuf, L"exit", 4))
break;
} else {
double errorcode = GetLastError();
writelog(_T("Thread %d: GReadFile: Error %ld"), GetCurrentThreadId(), errorcode);
_tprintf(TEXT("ReadFile: Error %ld\n"), errorcode);
_getch();
break;
}
}
// Освобождение ресурсов
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(GetProcessHeap(), 0, chBuf);
writelog(_T("Thread %d: InstanceThread exitting."), GetCurrentThreadId());
_tprintf(TEXT("InstanceThread exitting.\n"));
return 0;
}
| 37.1 | 89 | 0.6656 | SemenMartynov |
b261584d02f89b87c0729209149505d5b65840ad | 13,157 | cpp | C++ | NextEngine/src/graphics/renderer/terrain.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 1 | 2021-09-10T18:19:16.000Z | 2021-09-10T18:19:16.000Z | NextEngine/src/graphics/renderer/terrain.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | null | null | null | NextEngine/src/graphics/renderer/terrain.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 2 | 2020-04-02T06:46:56.000Z | 2021-06-17T16:47:57.000Z | #include "core/profiler.h"
#include "ecs/ecs.h"
#include "graphics/renderer/terrain.h"
#include "graphics/assets/assets.h"
#include "graphics/assets/model.h"
#include "components/transform.h"
#include "components/terrain.h"
#include "components/camera.h"
#include "graphics/assets/material.h"
#include "graphics/renderer/renderer.h"
#include "graphics/culling/culling.h"
#include "graphics/rhi/rhi.h"
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include "graphics/rhi/vulkan/texture.h"
#include "graphics/rhi/vulkan/draw.h"
model_handle load_subdivided(uint num) {
return load_Model(tformat("engine/subdivided_plane", num, ".fbx"));
}
//todo instanced rendering is always utilised even when a simple push constant or even uniform buffer
//would be more efficient!
void init_terrain_render_resources(TerrainRenderResources& resources) {
resources.terrain_shader = load_Shader("shaders/terrain.vert", "shaders/terrain.frag");
resources.subdivided_plane[0] = load_subdivided(32);
resources.subdivided_plane[1] = load_subdivided(16);
resources.subdivided_plane[2] = load_subdivided(8);
resources.displacement_sampler = query_Sampler({Filter::Linear, Filter::Linear, Filter::Linear});
resources.blend_values_sampler = query_Sampler({Filter::Linear, Filter::Linear, Filter::Linear});
resources.blend_idx_sampler = query_Sampler({Filter::Nearest, Filter::Nearest, Filter::Nearest});
//todo add shader variants for shadow mapping!
GraphicsPipelineDesc pipeline_desc = {};
pipeline_desc.shader = resources.terrain_shader;
pipeline_desc.render_pass = RenderPass::Shadow0;
pipeline_desc.shader_flags = SHADER_INSTANCED | SHADER_DEPTH_ONLY;
pipeline_desc.instance_layout = INSTANCE_LAYOUT_TERRAIN_CHUNK;
resources.depth_terrain_pipeline = query_Pipeline(pipeline_desc);
pipeline_desc.render_pass = RenderPass::Scene;
resources.depth_terrain_prepass_pipeline = query_Pipeline(pipeline_desc);
pipeline_desc.shader_flags = SHADER_INSTANCED;
pipeline_desc.subpass = 1;
resources.color_terrain_pipeline = query_Pipeline(pipeline_desc);
resources.ubo = alloc_ubo_buffer(sizeof(TerrainUBO), UBO_PERMANENT_MAP);
}
const uint MAX_TERRAIN_TEXTURES = 2;
const uint TERRAIN_SUBDIVISION = 32;
void clear_terrain(Terrain& terrain) {
terrain.displacement_map[0].clear();
terrain.displacement_map[1].clear();
terrain.displacement_map[2].clear();
terrain.blend_idx_map.clear();
terrain.blend_values_map.clear();
//terrain.materials.clear(); todo create new function
uint width = terrain.width * 32;
uint height = terrain.height * 32;
terrain.displacement_map[0].resize(width * height);
terrain.displacement_map[1].resize(width * height / 4);
terrain.displacement_map[2].resize(width * height / 8);
terrain.blend_idx_map.resize(width * height);
terrain.blend_values_map.resize(width * height);
}
//todo should this function clear the material
//or only set material if it's empty?
void default_terrain_material(Terrain& terrain) {
if (terrain.materials.length > 0) return;
TerrainMaterial terrain_material;
terrain_material.diffuse = default_textures.checker;
terrain_material.metallic = default_textures.black;
terrain_material.roughness = default_textures.white;
terrain_material.normal = default_textures.normal;
terrain_material.height = default_textures.white;
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
/*
{
TerrainMaterial terrain_material;
terrain_material.diffuse = load_Texture("grassy_ground/GrassyGround_basecolor.jpg");
terrain_material.metallic = load_Texture("grassy_ground/GrassyGround_metallic.jpg");
terrain_material.roughness = load_Texture("grassy_ground/GrassyGround_roughness.jpg");
terrain_material.normal = load_Texture("grassy_ground/GrassyGround_normal.jpg");
terrain_material.height = load_Texture("grassy_ground/GrassyGround_height.jpg");
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
}
{
TerrainMaterial terrain_material;
terrain_material.diffuse = load_Texture("rock_ground/RockGround_basecolor.jpg");
terrain_material.metallic = load_Texture("rock_ground/RockGround_metallic.jpg");
terrain_material.roughness = load_Texture("rock_ground/RockGround_roughness.jpg");
terrain_material.normal = load_Texture("rock_ground/RockGround_normal.jpg");
terrain_material.height = default_textures.white;
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
}
*/
}
void default_terrain(Terrain& terrain) {
clear_terrain(terrain);
uint width = terrain.width * 32;
uint height = terrain.height * 32;
for (uint y = 0; y < height; y++) {
for (uint x = 0; x < width; x++) {
float displacement = sin(10.0 * (float)x / width) * sin(10.0 * (float)y / height);
displacement = displacement * 0.5 + 0.5f;
uint index = y * width + x;
terrain.displacement_map[0][index] = displacement;
terrain.blend_idx_map[index] = pack_char_rgb(0, 1, 2, 3);
terrain.blend_values_map[index] = pack_float_rgb(1.0f - displacement, displacement, 0, 0);
}
}
default_terrain_material(terrain);
}
void update_terrain_material(TerrainRenderResources& resources, Terrain& terrain) {
uint width = terrain.width * 32;
uint height = terrain.height * 32;
Image displacement_desc{ TextureFormat::HDR, width, height, 1 };
Image blend_idx_desc{ TextureFormat::U8, width, height, 4 };
Image blend_map_desc{ TextureFormat::UNORM, width, height, 4 };
displacement_desc.data = terrain.displacement_map[0].data;
blend_idx_desc.data = terrain.blend_idx_map.data;
blend_map_desc.data = terrain.blend_values_map.data;
CombinedSampler diffuse_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler metallic_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler roughness_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler normal_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler height_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler ao_textures[MAX_TERRAIN_TEXTURES] = {};
static sampler_handle default_sampler = query_Sampler({});
for (uint i = 0; i < MAX_TERRAIN_TEXTURES; i++) {
diffuse_textures[i] = { default_sampler, default_textures.white };
metallic_textures[i] = { default_sampler, default_textures.white };
roughness_textures[i] = { default_sampler, default_textures.white };
normal_textures[i] = { default_sampler, default_textures.normal };
height_textures[i] = { default_sampler, default_textures.black };
ao_textures[i] = { default_sampler, default_textures.white };
}
for (uint i = 0; i < terrain.materials.length; i++) {
diffuse_textures[i].texture = terrain.materials[i].diffuse;
metallic_textures[i].texture = terrain.materials[i].metallic;
roughness_textures[i].texture = terrain.materials[i].roughness;
normal_textures[i].texture = terrain.materials[i].normal;
height_textures[i].texture = terrain.materials[i].height;
ao_textures[i].texture = terrain.materials[i].ao;
}
DescriptorDesc terrain_descriptor = {};
add_ubo(terrain_descriptor, VERTEX_STAGE, resources.ubo, 0);
add_combined_sampler(terrain_descriptor, VERTEX_STAGE, resources.displacement_sampler, resources.displacement_map, 1);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, resources.blend_idx_sampler, resources.blend_idx_map, 2);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, resources.blend_values_sampler, resources.blend_values_map, 3);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { diffuse_textures, MAX_TERRAIN_TEXTURES }, 4);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { metallic_textures, MAX_TERRAIN_TEXTURES }, 5);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { roughness_textures, MAX_TERRAIN_TEXTURES }, 6);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { normal_textures, MAX_TERRAIN_TEXTURES }, 7);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { height_textures, MAX_TERRAIN_TEXTURES }, 8);
//add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { ao_textures, MAX_TERRAIN_TEXTURES}, 9);
TerrainUBO terrain_ubo;
terrain_ubo.max_height = terrain.max_height;
terrain_ubo.displacement_scale = glm::vec2(1.0 / terrain.width, 1.0 / terrain.height);
terrain_ubo.transformUVs = glm::vec2(1, 1);
terrain_ubo.grid_size = terrain.size_of_block * terrain.width;
memcpy_ubo_buffer(resources.ubo, sizeof(TerrainUBO), &terrain_ubo);
update_descriptor_set(resources.descriptor, terrain_descriptor);
}
uint lod_from_dist(float dist) {
if (dist < 50) return 0;
else if (dist < 100) return 1;
else return 2;
}
glm::vec3 position_of_chunk(glm::vec3 position, float size_of_block, uint w, uint h) {
return position + glm::vec3(w * size_of_block, 0, (h + 1) * size_of_block);
}
void extract_render_data_terrain(TerrainRenderData& render_data, World& world, const Viewport viewports[RenderPass::ScenePassCount], EntityQuery layermask) {
uint render_pass_count = 1;
//TODO THIS ASSUMES EITHER 0 or 1 TERRAINS
for (auto[e, self, self_trans] : world.filter<Terrain, Transform>(layermask)) { //todo heavily optimize terrain
for (uint w = 0; w < self.width; w++) {
for (uint h = 0; h < self.height; h++) {
//Calculate position of chunk
Transform t;
t.position = position_of_chunk(self_trans.position, self.size_of_block, w, h);
t.scale = glm::vec3((float)self.size_of_block);
t.scale.y = 1.0f;
glm::mat4 model_m = compute_model_matrix(t);
glm::vec2 displacement_offset = glm::vec2(1.0 / self.width * w, 1.0 / self.height * h);
//Cull and compute lod of chunk
AABB aabb;
aabb.min = glm::vec3(0, 0, -(int)self.size_of_block) + t.position;
aabb.max = glm::vec3(self.size_of_block, self.max_height, 0) + t.position;
for (uint pass = 0; pass < render_pass_count; pass++) {
if (frustum_test(viewports[pass].frustum_planes, aabb) == OUTSIDE) continue;
glm::vec3 cam_pos = viewports[pass].cam_pos;
float dist = glm::length(t.position - cam_pos);
uint lod = lod_from_dist(dist);
uint edge_lod = lod;
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w - 1, h))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w + 1, h))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w, h - 1))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w, h + 1))));
ChunkInfo chunk_info = {};
chunk_info.model_m = model_m;
chunk_info.displacement_offset = displacement_offset;
chunk_info.lod = lod;
chunk_info.edge_lod = edge_lod;
render_data.lod_chunks[pass][lod].append(chunk_info);
}
}
}
}
}
//todo move into RHI
void clear_image(CommandBuffer& cmd_buffer, texture_handle handle, glm::vec4 color) {
Texture& texture = *get_Texture(handle);
VkClearColorValue vk_clear_color = {};
vk_clear_color = { color.x, color.y, color.z, color.a };
VkImageSubresourceRange range = {};
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseArrayLayer = 0;
range.layerCount = 1;
range.baseMipLevel = 0;
range.levelCount = texture.desc.num_mips;
vkCmdClearColorImage(cmd_buffer, get_Texture(handle)->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &vk_clear_color, 1, &range);
}
void clear_undefined_image(CommandBuffer& cmd_buffer, texture_handle handle, glm::vec4 color, TextureLayout final_layout = TextureLayout::ShaderReadOptimal) {
transition_layout(cmd_buffer, handle, TextureLayout::Undefined, TextureLayout::TransferDstOptimal);
clear_image(cmd_buffer, handle, color);
transition_layout(cmd_buffer, handle, TextureLayout::TransferDstOptimal, final_layout);
}
void render_terrain(TerrainRenderResources& resources, const TerrainRenderData& data, RenderPass render_passes[RenderPass::ScenePassCount]) {
if (!resources.descriptor.current.id) return;
recycle_descriptor_set(resources.descriptor);
for (uint pass = 0; pass < 1; pass++) {
CommandBuffer& cmd_buffer = render_passes[pass].cmd_buffer;
bool is_depth = render_passes[pass].type == RenderPass::Depth; //todo extract info function
bool is_depth_prepass = is_depth && render_passes[pass].id == RenderPass::Scene;
bind_vertex_buffer(cmd_buffer, VERTEX_LAYOUT_DEFAULT, INSTANCE_LAYOUT_TERRAIN_CHUNK);
bind_pipeline(cmd_buffer, is_depth_prepass ? resources.depth_terrain_prepass_pipeline : is_depth ? resources.depth_terrain_pipeline : resources.color_terrain_pipeline);
bind_descriptor(cmd_buffer, 2, resources.descriptor.current);
for (uint i = 0; i < MAX_TERRAIN_CHUNK_LOD; i++) { //todo heavily optimize terrain
const tvector<ChunkInfo>& chunk_info = data.lod_chunks[pass][i];
VertexBuffer vertex_buffer = get_vertex_buffer(resources.subdivided_plane[i], 0);
InstanceBuffer instance_buffer = frame_alloc_instance_buffer<ChunkInfo>(INSTANCE_LAYOUT_TERRAIN_CHUNK, chunk_info);
draw_mesh(cmd_buffer, vertex_buffer, instance_buffer);
}
}
} | 43.566225 | 170 | 0.769628 | CompilerLuke |
b26527d03ec717ccb01c9a61e85e359f363b29ba | 6,146 | cpp | C++ | elem.cpp | soulofmachines/QtCue | 035148f32fa1ca08ded9eca2fa6810c235d4831c | [
"MIT"
] | null | null | null | elem.cpp | soulofmachines/QtCue | 035148f32fa1ca08ded9eca2fa6810c235d4831c | [
"MIT"
] | null | null | null | elem.cpp | soulofmachines/QtCue | 035148f32fa1ca08ded9eca2fa6810c235d4831c | [
"MIT"
] | null | null | null | #include "elem.hpp"
QComboBox *file_list() {
QStringList string = QStringList() << "BINARY" << "MOTOROLA"
<< "AIFF" << "WAVE" << "MP3";
QComboBox* combo = new QComboBox();
combo->addItems(string);
return combo;
}
QComboBox *track_list() {
QStringList string = QStringList() << "AUDIO" << "CDG"
<< "MODE1/2048" << "MODE1/2352"
<< "MODE2/2336" << "MODE2/2352"
<< "CDI/2336" << "CDI/2352";
QComboBox* combo = new QComboBox();
combo->addItems(string);
return combo;
}
QComboBox *genre_list() {
QStringList string = QStringList() << ""
<< "Blues"
<< "Classical"
<< "Country"
<< "Electronic"
<< "Folk"
<< "Funk"
<< "Hip-Hop"
<< "Jazz"
<< "Latin"
<< "New-Age"
<< "Pop"
<< "R&B"
<< "Reggae"
<< "Rock"
<< "Soundtrack";
QComboBox* combo = new QComboBox();
combo->addItems(string);
combo->setEditable(true);
return combo;
}
QString GetFileName() {
QString file_name = QFileDialog::getOpenFileName(0,"Name","cdda.wav","Audio File (*.wav *.flac *.ape)");
int begin = file_name.lastIndexOf(QDir::separator());
if (begin == -1)
begin = 0;
return file_name.mid(begin+1);
}
bool ParseMiddle(QString expstr, QString &var, QString line, int begin) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.at(begin);
for (int x = begin+1; x < list.size()-1; ++x)
line += " " + list.at(x);
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool ParseLast(QString expstr, QString &var, QString line) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.back();
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool ParseLast(QString expstr, QString &var, QString line, int begin) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.at(begin);
for (int x = begin+1; x < list.size(); ++x)
line += " " + list.at(x);
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool MMSSFF_valid(QString line) {
if (line.count() != 8)
return false;
QStringList list = line.split(":",QString::SkipEmptyParts);
if (list.size() != 3)
return false;
bool ok = true;
int time = 0;
time = list.at(0).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=99)) {
time = list.at(1).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=59)) {
time = list.at(2).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=74)) {
return true;
}
}
}
return false;
}
QString MMSSFF_sum(QString line1, QString line2, bool &ok) {
ok = true;
QString retstr = "00:00:00";
QStringList list1;
QStringList list2;
int mm = 0, ss = 0, ff = 0;
if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {
list1 = line1.split(":",QString::SkipEmptyParts);
list2 = line2.split(":",QString::SkipEmptyParts);
mm = list1.at(0).toInt() + list2.at(0).toInt();
ss = list1.at(1).toInt() + list2.at(1).toInt();
ff = list1.at(2).toInt() + list2.at(2).toInt();
if (ff > 74) {
ff = ff - 75;
ss = ss + 1;
}
if (ss > 59) {
ss = ss - 60;
mm = mm + 1;
}
if (mm > 99)
ok = false;
else {
retstr.clear();
if (mm < 10)
retstr += "0";
retstr += QString::number(mm) + ":";
if (ss < 10)
retstr += "0";
retstr += QString::number(ss) + ":";
if (ff < 10)
retstr += "0";
retstr += QString::number(ff);
}
} else
ok = false;
return retstr;
}
QString MMSSFF_diff(QString line1, QString line2, bool &ok) {
ok = true;
QString retstr = "00:00:00";
QStringList list1;
QStringList list2;
int mm = 0, ss = 0, ff = 0;
if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {
list1 = line1.split(":",QString::SkipEmptyParts);
list2 = line2.split(":",QString::SkipEmptyParts);
mm = list1.at(0).toInt() - list2.at(0).toInt();
ss = list1.at(1).toInt() - list2.at(1).toInt();
ff = list1.at(2).toInt() - list2.at(2).toInt();
if (ff < 0) {
ff = 75 + ff;
ss = ss - 1;
}
if (ss < 0) {
ss = 60 + ss;
mm = mm - 1;
}
if (mm < 0)
ok = false;
else {
retstr.clear();
if (mm < 10)
retstr = "0";
retstr += QString::number(mm) + ":";
if (ss < 10)
retstr += "0";
retstr += QString::number(ss) + ":";
if (ff < 10)
retstr += "0";
retstr += QString::number(ff);
}
} else
ok = false;
return retstr;
}
| 30.884422 | 108 | 0.441263 | soulofmachines |
05d1ac22327335fe17703d3be4a530ea8bc67348 | 1,944 | hpp | C++ | test/examples/code/3rdparty/assimp/detail/ph.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/examples/code/3rdparty/assimp/detail/ph.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/examples/code/3rdparty/assimp/detail/ph.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright SOFT-ERG (Przemek Kuczmierczyk) 2016
All Rights Reserved.
THIS WORK CONTAINS TRADE SECRET
AND PROPRIETARY INFORMATION WHICH IS THE
PROPERTY OF SOFT-ERG (Przemek Kuczmierczyk)
AND IS SUBJECT TO LICENSE TERMS.
*/
// ---------------------------------------------------------------------------
#pragma warning (disable: 4267)
#include <cstdlib>
#include <csignal>
#include <csetjmp>
#include <cstdarg>
#include <typeinfo>
#include <typeindex>
#include <type_traits>
#include <bitset>
#include <functional>
#include <utility>
#include <ctime>
#include <chrono>
#include <cstddef>
#include <initializer_list>
#include <tuple>
#include <new>
#include <memory>
#include <scoped_allocator>
#include <climits>
#include <cfloat>
#include <cstdint>
#include <cinttypes>
#include <limits>
#include <exception>
#include <stdexcept>
#include <cassert>
#include <system_error>
#include <cerrno>
#include <cctype>
#include <cwctype>
#include <cstring>
#include <cwchar>
#include <cuchar>
#include <string>
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <complex>
#include <valarray>
#include <random>
#include <numeric>
#include <ratio>
#include <cfenv>
#include <iosfwd>
#include <ios>
#include <istream>
#include <ostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <strstream>
#include <iomanip>
#include <streambuf>
#include <cstdio>
#include <codecvt>
#include <regex>
#include <atomic>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <future>
#include <condition_variable>
// -----------------------------------------------------------------------------
| 21.6 | 81 | 0.64249 | maikebing |
05d31ac2b37312671d2275ca84dd41fca9cdea6a | 445 | cc | C++ | src/main.cc | rsanchezm98/sudoku-solver | 4b7580105acb4dda50ca24c69be09f89826f39a4 | [
"MIT"
] | null | null | null | src/main.cc | rsanchezm98/sudoku-solver | 4b7580105acb4dda50ca24c69be09f89826f39a4 | [
"MIT"
] | null | null | null | src/main.cc | rsanchezm98/sudoku-solver | 4b7580105acb4dda50ca24c69be09f89826f39a4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "sudoku.hpp"
int main(int argc, char** argv)
{
if(argc < 2)
{
std::cout << "Please, rerun the program with a filename...\n";
return 0;
}
std::string filename = argv[1];
filename = "../sudoku_files/" + filename;
size_t table_size = 9;
std::cout << "Sudoku filename: " << filename << "\n";
game::Sudoku sudoku(table_size, filename);
return 0;
} | 22.25 | 70 | 0.58427 | rsanchezm98 |
05d487dc83be83fe591a9cb01fd315bc83ee3151 | 4,405 | hh | C++ | libsrc/pylith/friction/obsolete/StaticFriction.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | libsrc/pylith/friction/obsolete/StaticFriction.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | libsrc/pylith/friction/obsolete/StaticFriction.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
/** @file libsrc/friction/StaticFriction.hh
*
* @brief C++ static friction fault constitutive model.
*/
#if !defined(pylith_friction_staticfriction_hh)
#define pylith_friction_staticfriction_hh
// Include directives ---------------------------------------------------
#include "FrictionModel.hh" // ISA FrictionModel
// StaticFriction -------------------------------------------------------
/** @brief C++ static friction fault constitutive model.
*
* Friction is equal to the product of a coefficient of friction and
* the normal traction.
*/
class pylith::friction::StaticFriction : public FrictionModel
{ // class StaticFriction
friend class TestStaticFriction; // unit testing
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Default constructor.
StaticFriction(void);
/// Destructor.
~StaticFriction(void);
// PROTECTED METHODS //////////////////////////////////////////////////
protected :
/// These methods should be implemented by every constitutive model.
/** Compute properties from values in spatial database.
*
* @param propValues Array of property values.
* @param dbValues Array of database values.
*/
void _dbToProperties(PylithScalar* const propValues,
const scalar_array& dbValues) const;
/** Nondimensionalize properties.
*
* @param values Array of property values.
* @param nvalues Number of values.
*/
void _nondimProperties(PylithScalar* const values,
const int nvalues) const;
/** Dimensionalize properties.
*
* @param values Array of property values.
* @param nvalues Number of values.
*/
void _dimProperties(PylithScalar* const values,
const int nvalues) const;
/** Compute friction from properties and state variables.
*
* @param t Time in simulation.
* @param slip Current slip at location.
* @param slipRate Current slip rate at location.
* @param normalTraction Normal traction at location.
* @param properties Properties at location.
* @param numProperties Number of properties.
* @param stateVars State variables at location.
* @param numStateVars Number of state variables.
*/
PylithScalar _calcFriction(const PylithScalar t,
const PylithScalar slip,
const PylithScalar slipRate,
const PylithScalar normalTraction,
const PylithScalar* properties,
const int numProperties,
const PylithScalar* stateVars,
const int numStateVars);
/** Compute derivative of friction with slip from properties and
* state variables.
*
* @param t Time in simulation.
* @param slip Current slip at location.
* @param slipRate Current slip rate at location.
* @param normalTraction Normal traction at location.
* @param properties Properties at location.
* @param numProperties Number of properties.
* @param stateVars State variables at location.
* @param numStateVars Number of state variables.
*
* @returns Derivative of friction (magnitude of shear traction) at vertex.
*/
PylithScalar _calcFrictionDeriv(const PylithScalar t,
const PylithScalar slip,
const PylithScalar slipRate,
const PylithScalar normalTraction,
const PylithScalar* properties,
const int numProperties,
const PylithScalar* stateVars,
const int numStateVars);
// PRIVATE MEMBERS ////////////////////////////////////////////////////
private :
static const int p_coef;
static const int p_cohesion;
static const int db_coef;
static const int db_cohesion;
// NOT IMPLEMENTED ////////////////////////////////////////////////////
private :
StaticFriction(const StaticFriction&); ///< Not implemented.
const StaticFriction& operator=(const StaticFriction&); ///< Not implemented
}; // class StaticFriction
#endif // pylith_friction_staticfriction_hh
// End of file
| 30.804196 | 78 | 0.640863 | Grant-Block |
05e3e38e2b358720cf85efb9805fa60b9adc7b79 | 1,301 | cpp | C++ | CipherTools/PluginSupport/PIDocManager.cpp | kuustudio/CipherTools | d99e707eab0515424ebe3555bb15dfbdc1782575 | [
"MIT"
] | 2 | 2019-09-02T16:28:10.000Z | 2020-08-19T09:29:51.000Z | PluginSupport/PIDocManager.cpp | SurrealSky/CipherManager | b0b4f3e58d148ee285a279cea46171ef9ef6cb00 | [
"MIT"
] | null | null | null | PluginSupport/PIDocManager.cpp | SurrealSky/CipherManager | b0b4f3e58d148ee285a279cea46171ef9ef6cb00 | [
"MIT"
] | 1 | 2021-07-03T02:49:46.000Z | 2021-07-03T02:49:46.000Z | #include "stdafx.h"
#include "PIDocManager.h"
IMPLEMENT_DYNAMIC(CPIDocManager, CDocManager)
CPIDocManager::CPIDocManager(void)
{
}
CPIDocManager::~CPIDocManager(void)
{
}
#ifdef _DEBUG
void CPIDocManager::AssertValid() const
{
CDocManager::AssertValid();
}
void CPIDocManager::Dump(CDumpContext& dc) const
{
CDocManager::Dump(dc);
}
#endif
void CPIDocManager::OnFileNew()
{
if (m_templateList.IsEmpty())
{
TRACE(traceAppMsg, 0, "Error: no document templates registered with CWinApp.\n");
AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
return;
}
CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetHead();
if (m_templateList.GetCount() > 1)
{
// use default template instead
/* // more than one document template to choose from
// bring up dialog prompting user
CNewTypeDlg dlg(&m_templateList);
INT_PTR nID = dlg.DoModal();
if (nID == IDOK)
pTemplate = dlg.m_pSelectedTemplate;
else
return; // none - cancel operation
*/
}
ASSERT(pTemplate != NULL);
ASSERT_KINDOF(CDocTemplate, pTemplate);
pTemplate->OpenDocumentFile(NULL);
// if returns NULL, the user has already been alerted
}
// remove plugin document template
void CPIDocManager::RemovePluginDocTemplate()
{
while (m_templateList.GetSize() > 1)
{
m_templateList.RemoveTail();
}
}
| 19.41791 | 83 | 0.730208 | kuustudio |
05edb2d789e67f3c9d902a64ab32b4664fc0b4f3 | 12,624 | cpp | C++ | AircraftDynamicsTestFramework/TrajectoryFromFile.cpp | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | AircraftDynamicsTestFramework/TrajectoryFromFile.cpp | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | AircraftDynamicsTestFramework/TrajectoryFromFile.cpp | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | // ****************************************************************************
// NOTICE
//
// This is the copyright work of The MITRE Corporation, and was produced
// for the U. S. Government under Contract Number DTFAWA-10-C-00080, and
// is subject to Federal Aviation Administration Acquisition Management
// System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV
// (Oct. 1996). No other use other than that granted to the U. S.
// Government, or to those acting on behalf of the U. S. Government,
// under that Clause is authorized without the express written
// permission of The MITRE Corporation. For further information, please
// contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive,
// McLean, VA 22102-7539, (703) 983-6000.
//
// Copyright 2018 The MITRE Corporation. All Rights Reserved.
// ****************************************************************************
#include "framework/TrajectoryFromFile.h"
#include "public/AircraftCalculations.h"
#include "public/CoreUtils.h"
#include "utility/CsvParser.h"
TrajectoryFromFile::TrajectoryFromFile(void) {
v_traj.mTimeToGo.clear();
v_traj.mDistToGo.clear();
v_traj.mAlt.clear();
v_traj.mIas.clear();
v_traj.mDotAlt.clear();
h_traj.clear();
mVerticalTrajectoryFile = "";
mHorizontalTrajectoryFile = "";
mMassPercentile = 0.5; // Dave Elliott says we can hard-code this for the tests
mAltAtFAF = Units::FeetLength(-50.0);
mLoaded = false;
}
TrajectoryFromFile::~TrajectoryFromFile(void) {}
bool TrajectoryFromFile::load(DecodedStream *input) {
set_stream(input);
register_var("vfp_csv_file", &mVerticalTrajectoryFile);
register_var("hfp_csv_file", &mHorizontalTrajectoryFile);
mLoaded = complete();
if (mLoaded) {
readVerticalTrajectoryFile();
readHorizontalTrajectoryFile();
}
return mLoaded;
}
void TrajectoryFromFile::readVerticalTrajectoryFile(void) {
std::ifstream file(mVerticalTrajectoryFile.c_str());
if (!file.is_open()) {
std::cout << "Vertical trajectory file " << mVerticalTrajectoryFile.c_str() << " not found" << std::endl;
exit(-20);
}
int numhdrs = 0;
for (CsvParser::CsvIterator csviter(file);csviter != CsvParser::CsvIterator();++csviter) {
if (numhdrs < 1) {
numhdrs++;
continue;
}
if ((int) (*csviter).size() != NUM_VERTICAL_TRAJ_FIELDS) {
std::cout << "Bad number of fields found in " << mVerticalTrajectoryFile.c_str()
<< std::endl << "vertical trajectory file. Found " << (int) (*csviter).size()
<< " fields expected " << (int) NUM_VERTICAL_TRAJ_FIELDS << " fields." << std::endl;
exit(-21);
}
for (int vfield = TIME_TO_GO_SEC; vfield != NUM_VERTICAL_TRAJ_FIELDS; vfield++) {
std::string fieldstr = (*csviter)[vfield];
double val = atof(fieldstr.c_str());
switch (static_cast<VerticalFields>(vfield)) {
case TIME_TO_GO_SEC:
v_traj.mTimeToGo.push_back(val);
break;
case DISTANCE_TO_GO_VERT_M:
v_traj.mDistToGo.push_back(val);
break;
case ALTITUDE_M:
v_traj.mAlt.push_back(val);
break;
case IAS_MPS:
v_traj.mIas.push_back(val);
break;
case DOT_ALTITUDE_MPS:
v_traj.mDotAlt.push_back(val);
break;
}
}
}
file.close();
}
void TrajectoryFromFile::readHorizontalTrajectoryFile(void) {
std::ifstream file(mHorizontalTrajectoryFile.c_str());
if (!file.is_open()) {
std::cout << "Horizontal trajectory file " << mHorizontalTrajectoryFile.c_str() << " not found" << std::endl;
exit(-22);
}
int numhdrs = 0;
for (CsvParser::CsvIterator csviter(file);csviter != CsvParser::CsvIterator();++csviter) {
if (numhdrs < 2) {
numhdrs++;
continue;
}
if ((int) (*csviter).size() != (int) NUM_HORIZONTAL_TRAJ_FIELDS) {
std::cout << "Bad number of fields found in " << mHorizontalTrajectoryFile.c_str()
<< std::endl << "vertical trajectory file. Found " << (int) (*csviter).size()
<< " fields expected " << (int) NUM_HORIZONTAL_TRAJ_FIELDS << " fields." << std::endl;
exit(-38);
}
HorizontalPath htrajseg;
for (int hfield = IX; hfield != (int) NUM_HORIZONTAL_TRAJ_FIELDS; hfield++) {
std::string fieldstr = (*csviter)[hfield];
double val = atof(fieldstr.c_str());
switch (static_cast<HorizontalFields>(hfield)) {
case IX:
// unused
break;
case X_M:
htrajseg.x = val;
break;
case Y_M:
htrajseg.y = val;
break;
case DISTANCE_TO_GO_HORZ_M:
htrajseg.L = val;
break;
case SEGMENT_TYPE:
htrajseg.segment = fieldstr;
break;
case COURSE_R:
htrajseg.course = val;
break;
case TURN_CENTER_X_M:
htrajseg.turns.x_turn = val;
break;
case TURN_CENTER_Y_M:
htrajseg.turns.y_turn = val;
break;
case ANGLE_AT_TURN_START_R:
htrajseg.turns.q_start = Units::UnsignedRadiansAngle(val);
break;
case ANGLE_AT_TURN_END_R:
htrajseg.turns.q_end = Units::UnsignedRadiansAngle(val);
break;
case TURN_RADIUS_M:
htrajseg.turns.radius = Units::MetersLength(val);
break;
case LAT_D:
// unused
break;
case LON_D:
// unused
break;
case TURN_CENTER_LAT_D:
// unused
break;
case TURN_CENTER_LON_D:
// unused
break;
}
}
h_traj.push_back(htrajseg);
}
file.close();
}
Guidance TrajectoryFromFile::update(AircraftState state, Guidance guidance_in) {
// Sets guidance information based on input guidance and aircraft state.
// Guidance information set include psi, cross track information, reference altitude,
// altitude rate, and indicated airspeed.
//
// state:Input aircraft state.
// guidance_in:Input guidance.
//
// returns updated guidance.
Guidance result = guidance_in;
Units::MetersLength hdtg;
Units::UnsignedAngle temp_course;
double h_next;
double v_next;
double h_dot_next;
int curr_index = 0;
AircraftCalculations::getPathLengthFromPos(
Units::FeetLength(state.x),
Units::FeetLength(state.y),
h_traj,
hdtg,
temp_course); // calls the distance to end helper method to calculate the distance to the end of the track
// if the check if the distance left is <= the start of the precalculated descent distance
if( hdtg.value() <= fabs(v_traj.mDistToGo.back()))
{
// Get index.
curr_index = CoreUtils::nearestIndex(curr_index,hdtg.value(),v_traj.mDistToGo);
// Set _next values.
if (curr_index == 0)
{
// Below lowest distance-take values at end of route.
h_next = v_traj.mAlt[curr_index];
v_next = v_traj.mIas[curr_index];
h_dot_next = v_traj.mDotAlt[curr_index];
}
else if (curr_index == v_traj.mDistToGo.size())
{
// Higher than furthest distance-take values at beginning of route.
// NOTE:this should never occur because of if with hdtg above.
h_next = v_traj.mAlt[(v_traj.mAlt.size()-1)];
v_next = v_traj.mIas[(v_traj.mIas.size()-1)];
h_dot_next = v_traj.mDotAlt[(v_traj.mDotAlt.size()-1)];
}
else
{
// Interpolate values using distance.
h_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mAlt);
v_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mIas);
h_dot_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mDotAlt);
}
// Set result
result.reference_altitude = h_next / FT_M;
result.altitude_rate = h_dot_next / FT_M;
result.indicated_airspeed = v_next / FT_M;
}
// Calculate Psi command and cross-track error if the aircraft is turning
// get the distance based on aircraft position
Units::MetersLength dist_out(0);
Units::RadiansAngle course_out(0);
AircraftCalculations::getPathLengthFromPos(
Units::FeetLength(state.x),
Units::FeetLength(state.y),
h_traj, dist_out, course_out);
// get aircraft position based on that calculated distance
Units::MetersLength x_pos(0);
Units::MetersLength y_pos(0);
int traj_index = 0;
AircraftCalculations::getPosFromPathLength(dist_out, h_traj, x_pos, y_pos, temp_course, traj_index);
result.psi = course_out.value(); // set the course command result
// calculate cross track as difference between actual and precalculated position
double cross_track = sqrt( pow(state.x*FT_M - x_pos.value(), 2) + pow(state.y*FT_M - y_pos.value(), 2) );
// generate cross-track sign based on distance from turn center and change in course
double center_dist = sqrt( pow(state.x*FT_M - h_traj[traj_index].turns.x_turn, 2) + pow(state.y*FT_M - h_traj[traj_index].turns.y_turn, 2) );
// calculate the cross track error based on distance from center point and course change if turning
if (h_traj[traj_index].segment == "turn") {
if (center_dist > Units::MetersLength(h_traj[traj_index].turns.radius).value()) {
if (course_out > state.get_heading_in_radians_mathematical()) {
result.cross_track = cross_track;
} else {
result.cross_track = -cross_track;
}
} else {
if (course_out > state.get_heading_in_radians_mathematical()) {
result.cross_track = -cross_track;
} else {
result.cross_track = cross_track;
}
}
result.use_cross_track = true;
} else {
// else do straight track trajectory cross-track calculation
result.cross_track = -(state.y*FT_M - h_traj[traj_index+1].y)*cos(course_out) + (state.x*FT_M - h_traj[traj_index+1].x)*sin(course_out);
}
result.use_cross_track = true;
return result;
}
std::vector<HorizontalPath> TrajectoryFromFile::getHorizontalData(void) {
// Gets horizontal trajectory data.
//
// Returns horizontal trajectory data.
return this->h_traj;
}
TrajectoryFromFile::VerticalData TrajectoryFromFile::getVerticalData(void) {
// Gets vertical trajectory data.
//
// Returns vertical trajectory data.
return this->v_traj;
}
bool TrajectoryFromFile::is_loaded(void) {
return mLoaded;
}
void TrajectoryFromFile::calculateWaypoints(AircraftIntent &intent) {
// Sets waypoints and altitude at FAF (final) waypoint based on intent.
//
// intent:aircraft intent.
// set altitude at FAF.
mAltAtFAF = Units::MetersLength(intent.getFms().AltWp[(intent.getNumberOfWaypoints()-1)]);
// Set waypoints.
waypoint_vector.clear(); // empties the waypoint vector for Aircraft Intent Waypoints
double prev_dist = 0;
//loop to translate all of the intent waypoints into Precalc Waypoints, works from back to front since precalc starts from the endpoint
for( int loop = intent.getNumberOfWaypoints()-1; loop > 0; loop--)
{
double delta_x = intent.getFms().xWp[loop-1].value() - intent.getFms().xWp[loop].value();
double delta_y = intent.getFms().yWp[loop-1].value() - intent.getFms().yWp[loop].value();
// calculate leg distance in meters
double leg_length = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
// calculate Psi course
double course = atan2( delta_y, delta_x );
PrecalcWaypoint new_waypoint;
new_waypoint.leg_length = leg_length;
new_waypoint.course_angle = Units::RadiansAngle(course);
new_waypoint.x_pos = intent.getFms().xWp[loop].value();
new_waypoint.y_pos = intent.getFms().yWp[loop].value();
// add new constraints
new_waypoint.constraints.constraint_dist = leg_length + prev_dist;
new_waypoint.constraints.constraint_altHi = intent.getFms().altHi[loop-1].value();
new_waypoint.constraints.constraint_altLow = intent.getFms().altLow[loop-1].value();
new_waypoint.constraints.constraint_speedHi = intent.getFms().speedHi[loop-1].value();
new_waypoint.constraints.constraint_speedLow = intent.getFms().speedLow[loop-1].value();
prev_dist += leg_length;
waypoint_vector.push_back(new_waypoint);
}
// add the final waypoint
PrecalcWaypoint new_waypoint;
new_waypoint.leg_length = 0;
new_waypoint.course_angle = waypoint_vector.back().course_angle;//0;
new_waypoint.x_pos = intent.getFms().xWp[0].value();
new_waypoint.y_pos = intent.getFms().yWp[0].value();
new_waypoint.constraints.constraint_dist = prev_dist;
new_waypoint.constraints.constraint_altHi = intent.getFms().altHi[0].value();
new_waypoint.constraints.constraint_altLow = intent.getFms().altLow[0].value();
new_waypoint.constraints.constraint_speedHi = intent.getFms().speedHi[0].value();
new_waypoint.constraints.constraint_speedLow = intent.getFms().speedLow[0].value();
waypoint_vector.push_back(new_waypoint);
}
| 27.503268 | 143 | 0.680925 | sbowman-mitre |
05ee5a8bee6a009cee9280c7b62d81e9d27a6228 | 1,436 | cpp | C++ | VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp | danjoconnell/VideoScriptEditor | 1d836e0cbe6e5afc56bdeb17ff834da308d752b0 | [
"MIT"
] | null | null | null | VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp | danjoconnell/VideoScriptEditor | 1d836e0cbe6e5afc56bdeb17ff834da308d752b0 | [
"MIT"
] | null | null | null | VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp | danjoconnell/VideoScriptEditor | 1d836e0cbe6e5afc56bdeb17ff834da308d752b0 | [
"MIT"
] | 1 | 2021-02-04T16:43:57.000Z | 2021-02-04T16:43:57.000Z | #include "pch.h"
#include <string>
#include "AviSynthEnvironment.h"
#include <system_error>
namespace VideoScriptEditor::PreviewRenderer::Unmanaged
{
using namespace VideoScriptEditor::Unmanaged;
AviSynthEnvironment::AviSynthEnvironment() : AviSynthEnvironmentBase()
{
if (!CreateScriptEnvironment())
{
throw std::runtime_error("Failed to initialize AviSynth Script Environment");
}
}
AviSynthEnvironment::~AviSynthEnvironment()
{
// Falls through to base class destructor
}
void AviSynthEnvironment::ResetEnvironment()
{
// Unload the current environment
DeleteScriptEnvironment();
// Initialize a new environment
if (!CreateScriptEnvironment())
{
throw std::runtime_error("Failed to initialize AviSynth Script Environment");
}
}
bool AviSynthEnvironment::LoadScriptFromFile(const std::string& fileName)
{
if (_clip)
{
ResetEnvironment();
}
// Invoke the AviSynth Import source filter to load the file - see http://avisynth.nl/index.php/Import#Import
AVSValue avsImportResult;
if (!_scriptEnvironment->InvokeTry(&avsImportResult, "Import", AVSValue(fileName.c_str())) || !avsImportResult.IsClip())
{
return false;
}
_clip = avsImportResult.AsClip();
return true;
}
} | 27.09434 | 128 | 0.638579 | danjoconnell |
05f2da41f5bd8713c9a218fa5c8d7d7a351847c1 | 3,876 | cpp | C++ | orbwebai/common/src/common.cpp | HungMingWu/ncnn_example | 6604eab8d76a5e49280e3f840847c84244c0fb2b | [
"MIT"
] | 1 | 2022-03-28T12:45:43.000Z | 2022-03-28T12:45:43.000Z | orbwebai/common/src/common.cpp | HungMingWu/ncnn_example | 6604eab8d76a5e49280e3f840847c84244c0fb2b | [
"MIT"
] | null | null | null | orbwebai/common/src/common.cpp | HungMingWu/ncnn_example | 6604eab8d76a5e49280e3f840847c84244c0fb2b | [
"MIT"
] | null | null | null | #include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <orbwebai/structure.h>
#include <orbwebai/structure_operator.h>
#include <common/common.h>
namespace orbwebai
{
namespace face
{
float CalculateSimilarity(
const std::vector<float>& feature1,
const std::vector<float>& feature2) {
assert(feature1.size() == feature2.size());
float inner_product = 0.0f;
float feature_norm1 = 0.0f;
float feature_norm2 = 0.0f;
#if defined(_OPENMP)
#pragma omp parallel for num_threads(threads_num)
#endif
for (int i = 0; i < orbwebai::kFaceFeatureDim; ++i) {
inner_product += feature1[i] * feature2[i];
feature_norm1 += feature1[i] * feature1[i];
feature_norm2 += feature2[i] * feature2[i];
}
return inner_product / sqrt(feature_norm1) / sqrt(feature_norm2);
}
}
static std::vector<orbwebai::Rect>
RatioAnchors(const orbwebai::Rect& anchor, const std::vector<float>& ratios) {
std::vector<orbwebai::Rect> anchors;
orbwebai::Point center(anchor.x + (anchor.width - 1) * 0.5f,
anchor.y + (anchor.height - 1) * 0.5f);
float anchor_size = anchor.width * anchor.height;
#if defined(_OPENMP)
#pragma omp parallel for num_threads(threads_num)
#endif
for (int i = 0; i < static_cast<int>(ratios.size()); ++i) {
float ratio = ratios.at(i);
float anchor_size_ratio = anchor_size / ratio;
float curr_anchor_width = std::sqrt(anchor_size_ratio);
float curr_anchor_height = curr_anchor_width * ratio;
float curr_x = center.x - (curr_anchor_width - 1) * 0.5f;
float curr_y = center.y - (curr_anchor_height - 1) * 0.5f;
anchors.emplace_back(curr_x, curr_y,
curr_anchor_width - 1, curr_anchor_height - 1);
}
return anchors;
}
static std::vector<orbwebai::Rect>
ScaleAnchors(const std::vector<orbwebai::Rect>& ratio_anchors,
const std::vector<float>& scales) {
std::vector<orbwebai::Rect> anchors;
for (const auto& anchor : ratio_anchors) {
orbwebai::Point2f center(anchor.x + anchor.width * 0.5f,
anchor.y + anchor.height * 0.5f);
for (const auto scale : scales) {
const float curr_width = scale * (anchor.width + 1);
const float curr_height = scale * (anchor.height + 1);
const float curr_x = center.x - curr_width * 0.5f;
const float curr_y = center.y - curr_height * 0.5f;
anchors.emplace_back(curr_x, curr_y,
curr_width, curr_height);
}
}
return anchors;
}
std::vector<orbwebai::Rect> GenerateAnchors(const int& base_size,
const std::vector<float>& ratios,
const std::vector<float> scales) {
orbwebai::Rect anchor(0, 0, base_size, base_size);
std::vector<orbwebai::Rect> ratio_anchors = RatioAnchors(anchor, ratios);
return ScaleAnchors(ratio_anchors, scales);
}
static float InterRectArea(const orbwebai::Rect& a, const orbwebai::Rect& b) {
orbwebai::Point left_top(std::max(a.x, b.x), std::max(a.y, b.y));
orbwebai::Point right_bottom(std::min(a.br().x, b.br().x), std::min(a.br().y, b.br().y));
orbwebai::Point diff = right_bottom - left_top;
return (std::max(diff.x + 1, 0) * std::max(diff.y + 1, 0));
}
float ComputeIOU(const orbwebai::Rect& rect1,
const orbwebai::Rect& rect2, const std::string& type) {
float inter_area = InterRectArea(rect1, rect2);
if (type == "UNION") {
return inter_area / (rect1.area() + rect2.area() - inter_area);
}
else {
return inter_area / std::min(rect1.area(), rect2.area());
}
}
std::vector<uint8_t> CopyImageFromRange(const orbwebai::ImageMetaInfo& img_src, const orbwebai::Rect& face)
{
std::vector<uint8_t> result;
int channels = img_src.channels;
for (int y = face.y; y < face.y + face.height; y++)
for (int x = face.x; x < face.x + face.width; x++)
for (int c = 0; c < img_src.channels; c++)
result.push_back(img_src.data[img_src.width * y * channels + x * channels + c]);
return result;
}
} | 34 | 108 | 0.680599 | HungMingWu |
05f3ab142aa6e830e78f51725f90b93050b2ef4a | 1,615 | cpp | C++ | src/Alias.cpp | irov/GOAP | f8d5f061537019fccdd143b232aa8a869fdb0b2d | [
"MIT"
] | 14 | 2016-10-07T21:53:02.000Z | 2021-12-13T02:57:19.000Z | src/Alias.cpp | irov/GOAP | f8d5f061537019fccdd143b232aa8a869fdb0b2d | [
"MIT"
] | null | null | null | src/Alias.cpp | irov/GOAP | f8d5f061537019fccdd143b232aa8a869fdb0b2d | [
"MIT"
] | 4 | 2016-09-01T10:06:29.000Z | 2021-12-13T02:57:20.000Z | /*
* Copyright (C) 2017-2019, Yuriy Levchenko <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "GOAP/Alias.h"
#include "GOAP/SourceInterface.h"
#include "GOAP/Cook.h"
#include "GOAP/Exception.h"
namespace GOAP
{
//////////////////////////////////////////////////////////////////////////
Alias::Alias( Allocator * _allocator )
: TaskInterface( _allocator )
{
}
//////////////////////////////////////////////////////////////////////////
Alias::~Alias()
{
}
//////////////////////////////////////////////////////////////////////////
bool Alias::_onRun( NodeInterface * _node )
{
SourceInterfacePtr source = _node->makeSource();
SourceInterfacePtr guard_source = Cook::addGuard( source, [this]()
{
this->incref();
}
, [this]()
{
this->_onAliasFinally();
this->decref();
} );
this->_onAliasGenerate( guard_source );
const SourceProviderInterfacePtr & provider = source->getSourceProvider();
if( _node->injectSource( provider ) == false )
{
Helper::throw_exception( "Alias invalid inject source" );
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void Alias::_onFinally()
{
//Empty
}
//////////////////////////////////////////////////////////////////////////
void Alias::_onAliasFinally()
{
//Empty
}
} | 26.47541 | 82 | 0.430341 | irov |
05f426ef899df9cabd8a310697ee86808e2508cc | 17,589 | cpp | C++ | src/Engine/imgui/imgui_impl_gl3.cpp | ennis/autograph-pipelines | afc66ef60bf99fca26d200bd7739528e1bf3ed8c | [
"MIT"
] | 1 | 2021-04-24T12:29:42.000Z | 2021-04-24T12:29:42.000Z | src/Engine/imgui/imgui_impl_gl3.cpp | ennis/autograph-pipelines | afc66ef60bf99fca26d200bd7739528e1bf3ed8c | [
"MIT"
] | null | null | null | src/Engine/imgui/imgui_impl_gl3.cpp | ennis/autograph-pipelines | afc66ef60bf99fca26d200bd7739528e1bf3ed8c | [
"MIT"
] | null | null | null | // ImGui GLFW binding with OpenGL3 + shaders
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture
// identifier. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See
// main.cpp for an example of using this. If you use this binding you'll need to
// call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(),
// ImGui::Render() and ImGui_ImplXXXX_Shutdown(). If you are new to ImGui, see
// examples/README.txt and documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
#include "imgui_impl_gl3.h"
#include <autograph/Engine/Event.h>
#include <autograph/Engine/Window.h>
#include <autograph/Engine/imgui.h>
#include <autograph/Gfx/gl_core_4_5.h>
namespace ag {
using namespace gl;
// Data
static Window *g_LastWindow = nullptr;
static double g_Time = 0.0f;
static bool g_MousePressed[3] = {false, false, false};
static bool g_MousePressedThisFrame[3] = {false, false, false};
static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0,
g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
// This is the main rendering function that you have to implement and provide to
// ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) If text
// or lines are blurry when integrating ImGui in your engine: - in your Render
// function, try translating your projection matrix by (0.5f,0.5f) or
// (0.375f,0.375f)
void ImGui_Impl_RenderDrawLists(ImDrawData *draw_data) {
// Avoid rendering when minimized, scale coordinates for retina displays
// (screen coordinates != framebuffer coordinates)
ImGuiIO &io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLint last_program;
gl::GetIntegerv(gl::CURRENT_PROGRAM, &last_program);
GLint last_texture;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
GLint last_active_texture;
gl::GetIntegerv(gl::ACTIVE_TEXTURE, &last_active_texture);
GLint last_array_buffer;
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer;
gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array;
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src;
gl::GetIntegerv(gl::BLEND_SRC, &last_blend_src);
GLint last_blend_dst;
gl::GetIntegerv(gl::BLEND_DST, &last_blend_dst);
GLint last_blend_equation_rgb;
gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha;
gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4];
gl::GetIntegerv(gl::VIEWPORT, last_viewport);
GLboolean last_enable_blend = gl::IsEnabled(gl::BLEND);
GLboolean last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
GLboolean last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
GLboolean last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
GLboolean last_enable_framebuffer_srgb = gl::IsEnabled(gl::FRAMEBUFFER_SRGB);
// Setup render state: alpha-blending enabled, no face culling, no depth
// testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
gl::Disable(gl::FRAMEBUFFER_SRGB);
gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] = {
{2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f},
{0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f},
{0.0f, 0.0f, -1.0f, 0.0f},
{-1.0f, 1.0f, 0.0f, 1.0f},
};
gl::UseProgram(g_ShaderHandle);
gl::Uniform1i(g_AttribLocationTex, 0);
gl::UniformMatrix4fv(g_AttribLocationProjMtx, 1, gl::FALSE_,
&ortho_projection[0][0]);
gl::BindVertexArray(g_VaoHandle);
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList *cmd_list = draw_data->CmdLists[n];
const ImDrawIdx *idx_buffer_offset = 0;
gl::BindBuffer(gl::ARRAY_BUFFER, g_VboHandle);
gl::BufferData(gl::ARRAY_BUFFER,
(gl::GLsizeiptr)cmd_list->VtxBuffer.size() *
sizeof(ImDrawVert),
(GLvoid *)&cmd_list->VtxBuffer.front(), gl::STREAM_DRAW);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
gl::BufferData(gl::ELEMENT_ARRAY_BUFFER,
(gl::GLsizeiptr)cmd_list->IdxBuffer.size() *
sizeof(ImDrawIdx),
(GLvoid *)&cmd_list->IdxBuffer.front(), gl::STREAM_DRAW);
for (const ImDrawCmd *pcmd = cmd_list->CmdBuffer.begin();
pcmd != cmd_list->CmdBuffer.end(); pcmd++) {
if (pcmd->UserCallback) {
pcmd->UserCallback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
gl::Scissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w),
(int)(pcmd->ClipRect.z - pcmd->ClipRect.x),
(int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
gl::DrawElements(gl::TRIANGLES, (GLsizei)pcmd->ElemCount,
sizeof(ImDrawIdx) == 2 ? gl::UNSIGNED_SHORT
: gl::UNSIGNED_INT,
idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
// Restore modified GL state
gl::UseProgram(last_program);
gl::ActiveTexture(last_active_texture);
gl::BindTexture(gl::TEXTURE_2D, last_texture);
gl::BindVertexArray(last_vertex_array);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
gl::BlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
gl::BlendFunc(last_blend_src, last_blend_dst);
if (last_enable_blend)
gl::Enable(gl::BLEND);
else
gl::Disable(gl::BLEND);
if (last_enable_cull_face)
gl::Enable(gl::CULL_FACE);
else
gl::Disable(gl::CULL_FACE);
if (last_enable_depth_test)
gl::Enable(gl::DEPTH_TEST);
else
gl::Disable(gl::DEPTH_TEST);
if (last_enable_scissor_test)
gl::Enable(gl::SCISSOR_TEST);
else
gl::Disable(gl::SCISSOR_TEST);
if (last_enable_framebuffer_srgb)
gl::Enable(gl::FRAMEBUFFER_SRGB);
else
gl::Disable(gl::FRAMEBUFFER_SRGB);
gl::Viewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2],
(GLsizei)last_viewport[3]);
}
static void mouseScrollCallback(const Event &e) {
g_MouseWheel +=
(float)e.scroll.dy; // Use fractional mouse wheel, 1.0 unit 5 lines.
}
static void mouseButtonCallback(const Event &ev) {
const KeyAction action = ev.mouseButton.action;
const int button = ev.mouseButton.button;
if (action == KeyAction::Press && button >= 0 && button < 3) {
g_MousePressedThisFrame[button] = true;
g_MousePressed[button] = true;
} else if (action == KeyAction::Release && button >= 0 && button < 3) {
g_MousePressed[button] = false;
}
}
static void keyCallback(const Event &ev) {
const KeyAction action = ev.key.action;
const int key = ev.key.key;
ImGuiIO &io = ImGui::GetIO();
if (action == KeyAction::Press)
io.KeysDown[key] = true;
if (action == KeyAction::Release)
io.KeysDown[key] = false;
io.KeyCtrl = io.KeysDown[KEY_LEFT_CONTROL] || io.KeysDown[KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[KEY_LEFT_SHIFT] || io.KeysDown[KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[KEY_LEFT_ALT] || io.KeysDown[KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[KEY_LEFT_SUPER] || io.KeysDown[KEY_RIGHT_SUPER];
}
static void charCallback(const Event &ev) {
const int c = ev.text.codepoint;
ImGuiIO &io = ImGui::GetIO();
if (c > 0 && c < 0x10000)
io.AddInputCharacter((unsigned short)c);
}
void ImGui_Impl_ProcessEvent(const Event &e) {
switch (e.type) {
case EventType::MouseScroll:
mouseScrollCallback(e);
break;
case EventType::MouseButton:
mouseButtonCallback(e);
break;
case EventType::Key:
keyCallback(e);
break;
case EventType::Text:
charCallback(e);
break;
}
}
/*
static const char *ImGui_ImplGlfwGL3_GetClipboardText(void *userdata) {
return glfwGetClipboardString(g_Window);
}
static void ImGui_ImplGlfwGL3_SetClipboardText(void *userdata,
const char *text) {
glfwSetClipboardString(g_Window, text);
}
*/
static bool ImGui_Impl_CreateFontsTexture() {
// Build texture atlas
ImGuiIO &io = ImGui::GetIO();
unsigned char *pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(
&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo
// because it is more likely to be compatible
// with user's existing shader.
// Upload texture to graphics system
GLint last_texture;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
gl::GenTextures(1, &g_FontTexture);
gl::BindTexture(gl::TEXTURE_2D, g_FontTexture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA, width, height, 0, gl::RGBA,
gl::UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Restore state
gl::BindTexture(gl::TEXTURE_2D, last_texture);
return true;
}
bool ImGui_Impl_CreateDeviceObjects() {
// Backup GL state
GLint last_texture, last_array_buffer, last_vertex_array;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array);
const gl::GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const gl::GLchar *fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
g_ShaderHandle = gl::CreateProgram();
g_VertHandle = gl::CreateShader(gl::VERTEX_SHADER);
g_FragHandle = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(g_VertHandle, 1, &vertex_shader, 0);
gl::ShaderSource(g_FragHandle, 1, &fragment_shader, 0);
gl::CompileShader(g_VertHandle);
gl::CompileShader(g_FragHandle);
gl::AttachShader(g_ShaderHandle, g_VertHandle);
gl::AttachShader(g_ShaderHandle, g_FragHandle);
gl::LinkProgram(g_ShaderHandle);
g_AttribLocationTex = gl::GetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = gl::GetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = gl::GetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = gl::GetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = gl::GetAttribLocation(g_ShaderHandle, "Color");
gl::GenBuffers(1, &g_VboHandle);
gl::GenBuffers(1, &g_ElementsHandle);
gl::GenVertexArrays(1, &g_VaoHandle);
gl::BindVertexArray(g_VaoHandle);
gl::BindBuffer(gl::ARRAY_BUFFER, g_VboHandle);
gl::EnableVertexAttribArray(g_AttribLocationPosition);
gl::EnableVertexAttribArray(g_AttribLocationUV);
gl::EnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t) & (((TYPE *)0)->ELEMENT))
gl::VertexAttribPointer(g_AttribLocationPosition, 2, gl::FLOAT, gl::FALSE_,
sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, pos));
gl::VertexAttribPointer(g_AttribLocationUV, 2, gl::FLOAT, gl::FALSE_,
sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, uv));
gl::VertexAttribPointer(g_AttribLocationColor, 4, gl::UNSIGNED_BYTE,
gl::TRUE_, sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
ImGui_Impl_CreateFontsTexture();
// Restore modified GL state
gl::BindTexture(gl::TEXTURE_2D, last_texture);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer);
gl::BindVertexArray(last_vertex_array);
return true;
}
void ImGui_Impl_InvalidateDeviceObjects() {
if (g_VaoHandle)
gl::DeleteVertexArrays(1, &g_VaoHandle);
if (g_VboHandle)
gl::DeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle)
gl::DeleteBuffers(1, &g_ElementsHandle);
g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
gl::DetachShader(g_ShaderHandle, g_VertHandle);
gl::DeleteShader(g_VertHandle);
g_VertHandle = 0;
gl::DetachShader(g_ShaderHandle, g_FragHandle);
gl::DeleteShader(g_FragHandle);
g_FragHandle = 0;
gl::DeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
if (g_FontTexture) {
gl::DeleteTextures(1, &g_FontTexture);
ImGui::GetIO().Fonts->TexID = 0;
g_FontTexture = 0;
}
}
bool ImGui_Impl_Init() {
ImGuiIO &io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = KEY_TAB; // Keyboard mapping. ImGui will use
// those indices to peek into the
// io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = KEY_HOME;
io.KeyMap[ImGuiKey_End] = KEY_END;
io.KeyMap[ImGuiKey_Delete] = KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = KEY_A;
io.KeyMap[ImGuiKey_C] = KEY_C;
io.KeyMap[ImGuiKey_V] = KEY_V;
io.KeyMap[ImGuiKey_X] = KEY_X;
io.KeyMap[ImGuiKey_Y] = KEY_Y;
io.KeyMap[ImGuiKey_Z] = KEY_Z;
io.RenderDrawListsFn =
ImGui_Impl_RenderDrawLists; // Alternatively you can set this to
// NULL and call ImGui::GetDrawData()
// after ImGui::Render() to get the
// same ImDrawData pointer.
// io.SetClipboardTextFn = ImGui_Impl_SetClipboardText;
// io.GetClipboardTextFn = ImGui_Impl_GetClipboardText;
//#ifdef _WIN32
// io.ImeWindowHandle = glfwGetWin32Window(g_Window);
//#endif
return true;
}
void ImGui_Impl_Shutdown() {
ImGui_Impl_InvalidateDeviceObjects();
ImGui::Shutdown();
}
void ImGui_Impl_NewFrame(Window &w, double current_time) {
if (!g_FontTexture)
ImGui_Impl_CreateDeviceObjects();
ImGuiIO &io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
auto size = w.getWindowSize();
auto display_size = w.getFramebufferSize();
io.DisplaySize = ImVec2((float)size.x, (float)size.y);
io.DisplayFramebufferScale =
ImVec2(size.x > 0 ? ((float)display_size.x / size.x) : 0,
size.y > 0 ? ((float)display_size.y / size.y) : 0);
// Setup time step
// double current_time = glfwGetTime();
io.DeltaTime =
g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks
// polled in glfwPollEvents())
if (w.isFocused()) {
auto mousePos = w.getCursorPos();
io.MousePos =
ImVec2((float)mousePos.x, (float)mousePos.y); // Mouse position in
// screen coordinates
// (set to -1,-1 if no
// mouse / on another
// screen, etc.)
} else {
io.MousePos = ImVec2(-1, -1);
}
for (int i = 0; i < 3; i++) {
io.MouseDown[i] =
g_MousePressed[i] ||
g_MousePressedThisFrame[i]; // If a mouse press event came, always pass
// it as "mouse held this frame", so we
// don't miss click-release events that are
// shorter than 1 frame.
g_MousePressedThisFrame[i] = false;
}
io.MouseWheel = g_MouseWheel;
g_MouseWheel = 0.0f;
// Hide OS mouse cursor if ImGui is drawing it
/*glfwSetInputMode(g_Window, GLFW_CURSOR,
io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN
: GLFW_CURSOR_NORMAL);*/
// Start the frame
ImGui::NewFrame();
}
} // namespace ag | 37.107595 | 80 | 0.669907 | ennis |
05f5d52656a4bcfcc7f70162b7b08a51e588f8e3 | 5,924 | cpp | C++ | test/unit/models/TransactionFilterTest.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | 12 | 2021-09-28T14:37:22.000Z | 2022-03-04T17:54:11.000Z | test/unit/models/TransactionFilterTest.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | null | null | null | test/unit/models/TransactionFilterTest.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | 8 | 2021-11-05T18:56:55.000Z | 2022-01-10T11:14:24.000Z | /* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "JsonTestSuite.hpp"
#include "enjinsdk/models/TransactionFilter.hpp"
#include <string>
#include <vector>
using namespace enjin::sdk::models;
using namespace enjin::test::suites;
class TransactionFilterTest : public JsonTestSuite,
public testing::Test {
public:
TransactionFilter class_under_test;
constexpr static char POPULATED_JSON_OBJECT[] =
R"({"and":[],"or":[],"id":"1","id_in":[],"transactionId":"1","transactionId_in":[],"assetId":"1","assetId_in":[],"type":"APPROVE","type_in":[],"value":1,"value_gt":1,"value_gte":1,"value_lt":1,"value_lte":1,"state":"PENDING","state_in":[],"wallet":"1","wallet_in":[]})";
static TransactionFilter create_default_filter() {
return TransactionFilter().set_and(std::vector<TransactionFilter>())
.set_or(std::vector<TransactionFilter>())
.set_id("1")
.set_id_in(std::vector<std::string>())
.set_transaction_id("1")
.set_transaction_id_in(std::vector<std::string>())
.set_asset_id("1")
.set_asset_id_in(std::vector<std::string>())
.set_type(RequestType::APPROVE)
.set_type_in(std::vector<RequestType>())
.set_value(1)
.set_value_gt(1)
.set_value_gte(1)
.set_value_lt(1)
.set_value_lte(1)
.set_state(RequestState::PENDING)
.set_state_in(std::vector<RequestState>())
.set_wallet("1")
.set_wallet_in(std::vector<std::string>());
}
};
TEST_F(TransactionFilterTest, SerializeNoSetFieldsReturnsEmptyJsonObject) {
// Arrange
const std::string expected(EMPTY_JSON_OBJECT);
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeSetFieldsReturnsExpectedJsonObject) {
// Arrange
const std::string expected(POPULATED_JSON_OBJECT);
class_under_test.set_and(std::vector<TransactionFilter>())
.set_or(std::vector<TransactionFilter>())
.set_id("1")
.set_id_in(std::vector<std::string>())
.set_transaction_id("1")
.set_transaction_id_in(std::vector<std::string>())
.set_asset_id("1")
.set_asset_id_in(std::vector<std::string>())
.set_type(RequestType::APPROVE)
.set_type_in(std::vector<RequestType>())
.set_value(1)
.set_value_gt(1)
.set_value_gte(1)
.set_value_lt(1)
.set_value_lte(1)
.set_state(RequestState::PENDING)
.set_state_in(std::vector<RequestState>())
.set_wallet("1")
.set_wallet_in(std::vector<std::string>());
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeRequestInFieldSetReturnsExpectedJsonObject) {
// Arrange
const std::string expected(R"({"type_in":["APPROVE","APPROVE","APPROVE"]})");
class_under_test.set_type_in({RequestType::APPROVE, RequestType::APPROVE, RequestType::APPROVE});
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeStateInReturnsFieldSetExpectedJsonObject) {
// Arrange
const std::string expected(R"({"state_in":["PENDING","PENDING","PENDING"]})");
std::vector<RequestState> states;
class_under_test.set_state_in({RequestState::PENDING, RequestState::PENDING, RequestState::PENDING});
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, EqualityNeitherSideIsPopulatedReturnsTrue) {
// Arrange
TransactionFilter lhs;
TransactionFilter rhs;
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_TRUE(actual);
}
TEST_F(TransactionFilterTest, EqualityBothSidesArePopulatedReturnsTrue) {
// Arrange
TransactionFilter lhs = create_default_filter();
TransactionFilter rhs = create_default_filter();
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_TRUE(actual);
}
TEST_F(TransactionFilterTest, EqualityLeftSideIsPopulatedReturnsFalse) {
// Arrange
TransactionFilter lhs = create_default_filter();
TransactionFilter rhs;
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_FALSE(actual);
}
TEST_F(TransactionFilterTest, EqualityRightSideIsPopulatedReturnsFalse) {
// Arrange
TransactionFilter lhs;
TransactionFilter rhs = create_default_filter();
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_FALSE(actual);
}
| 34.847059 | 282 | 0.597569 | BlockChain-Station |
af0087a7e85abdf54d4f22d5fb776247e8f8c5db | 3,491 | cpp | C++ | cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp | aungpaing98/cmpf | 6dc561895946c8faa5b15c72d2590990ac7d3e9f | [
"Apache-2.0"
] | 3 | 2021-12-23T15:36:37.000Z | 2022-02-28T15:05:35.000Z | cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp | aungpaing98/cmpf | 6dc561895946c8faa5b15c72d2590990ac7d3e9f | [
"Apache-2.0"
] | 1 | 2022-01-12T15:33:42.000Z | 2022-01-12T15:33:42.000Z | cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp | aungpaing98/cmpf | 6dc561895946c8faa5b15c72d2590990ac7d3e9f | [
"Apache-2.0"
] | 1 | 2022-01-10T04:47:13.000Z | 2022-01-10T04:47:13.000Z | /************************************************************************
Copyright 2021 Phone Thiha Kyaw
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 "cmpf_decoupled_controller/decoupled_controller.hpp"
namespace cmpf
{
namespace path_tracking_controller
{
namespace decoupled_controller
{
DecoupledController::DecoupledController()
: latc_loader_("cmpf_decoupled_controller",
"cmpf::path_tracking_controller::decoupled_controller::"
"LateralController")
{
}
DecoupledController::~DecoupledController()
{
}
void DecoupledController::initialize(const std::string& name, ros::NodeHandle nh, tf2_ros::Buffer* tf)
{
nh.param("/" + name + "/longitudinal_controller/plugin", lg_controller_id_,
std::string("path_tracking_controller/decoupled_controller/"
"longitudinal_controller/PID"));
nh.param("/" + name + "/lateral_controller_plugin", lat_controller_id_,
std::string("cmpf_decoupled_controller/PurePursuit"));
/*
// load longitudinal controller
try {
lg_controller_ = lgc_loader_.createUniqueInstance(lg_controller_id_);
ROS_INFO("Created path_tracking_controller %s", lg_controller_id_.c_str());
lg_controller_->initialize(lgc_loader_.getName(lg_controller_id_), tf);
} catch (const pluginlib::PluginlibException& ex) {
ROS_FATAL(
"Failed to create the %s controller, are you sure it is properly "
"registered and that the containing library is built? Exception: %s",
lg_controller_id_.c_str(), ex.what());
exit(1);
}
*/
// load lateral controller
try
{
lat_controller_ = latc_loader_.createUniqueInstance(lat_controller_id_);
ROS_INFO("Created lateral_controller %s", lat_controller_id_.c_str());
lat_controller_->initialize(latc_loader_.getName(lat_controller_id_), nh, tf);
}
catch (const pluginlib::PluginlibException& ex)
{
ROS_FATAL(
"Failed to create the %s lateral_controller, are you sure it is "
"properly registered and that the containing library is built? "
"Exception: %s",
lat_controller_id_.c_str(), ex.what());
exit(1);
}
}
void DecoupledController::setTrajectory(const cmpf_msgs::Trajectory& trajectory)
{
}
void DecoupledController::computeVehicleControlCommands(const geometry_msgs::PoseStamped& pose,
carla_msgs::CarlaEgoVehicleControl& vehicle_control_cmd)
{
// ROS_INFO("Current Vehicle pose - x: %.4f , y: %.4f", pose.pose.position.x, pose.pose.position.y);
}
} // namespace decoupled_controller
} // namespace path_tracking_controller
} // namespace cmpf
#include <pluginlib/class_list_macros.h>
// register this controller as a BaseController plugin
PLUGINLIB_EXPORT_CLASS(cmpf::path_tracking_controller::decoupled_controller::DecoupledController,
cmpf::cmpf_core::BaseController) | 37.138298 | 112 | 0.691492 | aungpaing98 |
af04effcd92a2963645f7475b5a05bf9cd15440e | 6,021 | cpp | C++ | LiteCppDB/LiteCppDB/ObjectId.cpp | pnadan/LiteCppDB | cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2 | [
"MIT"
] | 2 | 2019-07-18T06:30:33.000Z | 2020-01-23T17:40:36.000Z | LiteCppDB/LiteCppDB/ObjectId.cpp | pnadan/LiteCppDB | cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2 | [
"MIT"
] | null | null | null | LiteCppDB/LiteCppDB/ObjectId.cpp | pnadan/LiteCppDB | cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "BsonValue.h"
#include <functional>
#include <random>
#include <sstream>
#include "ObjectId.h"
#include <gsl\gsl>
namespace LiteCppDB
{
#pragma region Properties
// Get timestamp
int32_t ObjectId::getTimestamp() noexcept
{
return this->mTimestamp;
}
void ObjectId::setTimestamp(int32_t timestamp) noexcept
{
this->mTimestamp = timestamp;
}
// Get machine number
int32_t ObjectId::getMachine() noexcept
{
return this->mMachine;
}
void ObjectId::setMachine(int32_t machine) noexcept
{
this->mMachine = machine;
}
// Get pid number
int16_t ObjectId::getPid() noexcept
{
return this->mPid;
}
void ObjectId::setPid(int16_t pid) noexcept
{
this->mPid = pid;
}
// Get increment
int32_t ObjectId::getIncrement() noexcept
{
return this->mIncrement;
}
void ObjectId::setIncrement(int32_t increment) noexcept
{
this->mIncrement = increment;
}
// Get creation time
std::any ObjectId::getCreationTime() noexcept
{
return std::any();
}
#pragma endregion Properties
#pragma region Ctor
// Initializes a new empty instance of the ObjectId class.
ObjectId::ObjectId() noexcept
{
this->mTimestamp = 0;
this->mMachine = 0;
this->mPid = 0;
this->mIncrement = 0;
}
// Initializes a new instance of the ObjectId class from ObjectId vars.
ObjectId::ObjectId(int32_t timestamp, int32_t machine, int16_t pid, int32_t increment) noexcept
{
this->mTimestamp = timestamp;
this->mMachine = machine;
this->mPid = pid;
this->mIncrement = increment;
}
// Initializes a new instance of ObjectId class from another ObjectId.
ObjectId::ObjectId(LiteCppDB::ObjectId* from) noexcept
{
this->mTimestamp = 0;
this->mIncrement = from->mTimestamp;
this->mMachine = from->mMachine;
this->mPid = from->mPid;
this->mIncrement = from->mIncrement;
}
// Initializes a new instance of the ObjectId class from hex string.
ObjectId::ObjectId(std::string value) noexcept//TODO : FromHex(value)
{
this->mIncrement = 0;
this->mMachine = 0;
this->mPid = 0;
this->mTimestamp = 0;
}
// Initializes a new instance of the ObjectId class from byte array.
ObjectId::ObjectId(std::vector<uint8_t> bytes)
{
this->mTimestamp = (bytes.at(0) << 24) + (bytes.at(1) << 16) + (bytes.at(2) << 8) + bytes.at(3);
this->mMachine = (bytes[4] << 16) + (bytes[5] << 8) + bytes[6];
this->mPid = gsl::narrow_cast<int16_t>((bytes[7] << 8) + bytes[8]);
this->mIncrement = (bytes[9] << 16) + (bytes[10] << 8) + bytes[11];
}
/// Convert hex value string in byte array
std::array<uint8_t, 12> ObjectId::FromHex(std::string value)
{
if (value.empty()) throw std::exception("ArgumentNullException(\"val\")");
std::array<uint8_t, 12> bytes{0,0,0,0,0,0,0,0,0,0,0,0};
std::vector<uint8_t> myVector(value.begin(), value.end());
if (12 == myVector.size())
{
int32_t i = 0;
for (auto& byte : bytes)
{
byte = myVector.at(i);
i++;
}
}
return bytes;
}
#pragma endregion Ctor
#pragma region Equals / CompareTo / ToString
// Checks if this ObjectId is equal to the given object. Returns true
// if the given object is equal to the value of this instance.
// Returns false otherwise.
bool ObjectId::Equals(ObjectId other) noexcept
{
return
this->mTimestamp == other.mTimestamp &&
this->mMachine == other.mMachine &&
this->mPid == other.mPid &&
this->mIncrement == other.mIncrement;
}
// Determines whether the specified object is equal to this instance.
bool ObjectId::Equals(std::any other)
{
if (std::any_cast<ObjectId>(other) == ObjectId::ObjectId())
{
return this->Equals(std::any_cast<ObjectId>(other));
}
return false;
}
// Returns a hash code for this instance.
int32_t ObjectId::GetHashCode()
{
int32_t hash = 17;
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mTimestamp));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mMachine));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mPid));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mIncrement));
return hash;
}
/// Compares two instances of ObjectId
int32_t ObjectId::CompareTo(ObjectId other) noexcept
{
//return this->mIncrement.CompareTo(other.mIncrement);
return 0;
}
/// Represent ObjectId as 12 bytes array
std::array<uint8_t, 12> ObjectId::ToByteArray() noexcept
{
std::array<uint8_t, 12> bytes =
{
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 24),
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 16),
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 8),
gsl::narrow_cast<uint8_t>(this->mTimestamp),
gsl::narrow_cast<uint8_t>(this->mMachine >> 16),
gsl::narrow_cast<uint8_t>(this->mMachine >> 8),
gsl::narrow_cast<uint8_t>(this->mMachine),
gsl::narrow_cast<uint8_t>(this->mPid >> 8),
gsl::narrow_cast<uint8_t>(this->mPid),
gsl::narrow_cast<uint8_t>(this->mIncrement >> 16),
gsl::narrow_cast<uint8_t>(this->mIncrement >> 8),
gsl::narrow_cast<uint8_t>(this->mIncrement)
};
return bytes;
}
std::string ObjectId::ToString() noexcept
{
return std::string();
}
#pragma endregion Equals / CompareTo / ToString
#pragma region Operators
bool operator ==(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.Equals(rhs);
}
bool operator !=(ObjectId lhs, ObjectId rhs) noexcept
{
return !(lhs == rhs);
}
bool operator >=(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) >= 0;
}
bool operator >(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) > 0;
}
bool operator <(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) < 0;
}
bool operator <=(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) <= 0;
}
#pragma endregion Operators
#pragma region Static methods
int32_t GetMachineHash()
{
auto hostname = "unknown"; //boost::asio::ip::host_name();
return 0x00ffffff & (int32_t)std::hash<std::string>{}(hostname);
}
#pragma endregion Static methods
} | 23.892857 | 98 | 0.680618 | pnadan |
af0a3817e818a47eb04b4bd4d953565af9c173f0 | 348 | hpp | C++ | include/cereal/size_type.hpp | VaderY/cereal | b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a | [
"BSD-3-Clause"
] | null | null | null | include/cereal/size_type.hpp | VaderY/cereal | b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a | [
"BSD-3-Clause"
] | null | null | null | include/cereal/size_type.hpp | VaderY/cereal | b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <cstdint>
#include <cereal/macros.hpp>
namespace cereal {
// -------------------------------------------------------------------------------------------------
using size_type = CEREAL_SIZE_TYPE;
// -------------------------------------------------------------------------------------------------
} // namespace cereal
| 20.470588 | 100 | 0.304598 | VaderY |
af0fce98bb2f00f6f1c531b9a680a347f47dd3c7 | 4,343 | hpp | C++ | math/utility/fn.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | math/utility/fn.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | math/utility/fn.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_MATH_UTILITY_FUNCTION_HPP_
#define _SNAKEOIL_MATH_UTILITY_FUNCTION_HPP_
#include "../typedefs.h"
namespace so_math
{
template< typename type_t >
class fn
{
typedef fn< type_t > this_t;
typedef type_t const typec_t;
public:
static type_t abs(type_t x) {
return x < type_t(0) ? -x : x;
}
static type_t mod(typec_t x, typec_t m) {
const int_t n = int_t(x / m);
return x < type_t(0) ? x - m * type_t(n + 1) : x - m * type_t(n);
}
public:
static int_t ceil(typec_t x) {
//return (int)x + (int)( (x > T(0)) && ( (int)x != x ) ) ;
return x < type_t(0) ? int_t(x) : int_t(x + type_t(1));
}
static type_t floor(typec_t x) {
//return (int)x - (int)( (x < T(0)) && ( (int)x != x ) ) ;
//return type_t( x > type_t(0) ? int_t(x) : int_t(x - type_t(1)) );
return std::floor( x ) ;
}
static type_t fract( type_t v )
{
return v - this_t::floor( v ) ;
}
/// performs x^y
static type_t pow( typec_t x, typec_t y ) {
return std::pow( x, y ) ;
}
static type_t sqrt( typec_t x ){
return std::sqrt( x ) ;
}
static type_t sin( typec_t x ){
return std::sin(x) ;
}
static type_t cos( typec_t x ){
return std::cos(x) ;
}
static type_t acos( typec_t x ){
return std::acos(x) ;
}
public:
static type_t step(typec_t x, typec_t a) {
return x < a ? type_t(0) : type_t(1);
}
static type_t pulse(typec_t x, typec_t a, typec_t b) {
return this_t::step(x, a) - this_t::step(x, b);
}
static type_t clamp(typec_t x, typec_t a, typec_t b) {
return x < a ? a : x > b ? b : x;
}
static type_t saturate(typec_t x) {
return this_t::clamp(x, type_t(0), type_t(1));
}
/// @precondition x in [a,b] && a < b
static type_t box_step(typec_t x, typec_t a, typec_t b) {
return this_t::clamp((x - a) / (b - a), type_t(0), type_t(1));
}
/// @precondition x in [0,1]
/// return 3x^2-2*x^3
static type_t smooth_step(typec_t x) {
return ( x * x * (type_t(3)-(x + x)));
}
/// @precondition x in [a,b] && a < b
/// if x is not in [a,b], use
/// smooth_step( clamp(x, a, b), a, b )
static type_t smooth_step(typec_t x, typec_t a, typec_t b) {
return this_t::smooth_step((x - a) / (b - a));
}
/// @precondition x in [0,1]
/// return 6x^5 - 15x^4 + 10t^3
static type_t smooth_step_e5(typec_t x) {
return x * x * x * (x * (x * type_t(6) - type_t(15)) + type_t(10));
}
/// @precondition x in [a,b] && a < b
/// if x is not in [a,b], use
/// smooth_step2( clamp(x, a, b), a, b )
static type_t smooth_step_e5(typec_t x, typec_t a, typec_t b) {
return this_t::smooth_step_e5((x - a) / (b - a));
}
public:
/// @precondition x in [0,1]
static type_t mix(typec_t x, typec_t a, typec_t b) {
return a + x * (b - a);
}
/// @precondition x in [0,1]
static type_t lerp(typec_t x, typec_t a, typec_t b) {
return this_t::mix(x, a, b);
}
public:
static type_t sign(typec_t in_) {
return type_t(int_t(type_t(0) < in_) - int_t(type_t(0) > in_));
}
public:
/// negative normalized value to positive normalized value
/// takes a value in [-1,1] to [0,1]
static type_t nnv_to_pnv( typec_t v )
{
return v * type_t(0.5) + type_t(0.5) ;
}
/// positive normalized value to negative normalized value
/// takes a value in [0,1] to [-1,1]
static type_t pnv_to_nnv( typec_t v )
{
return v * type_t(2) - type_t(1) ;
}
};
}
#endif
| 28.019355 | 79 | 0.474557 | aconstlink |
af1130ae08cae69f83aa8589451a7aa94b454f9f | 1,347 | cpp | C++ | src/calc/Checksum.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 2 | 2016-05-21T03:09:19.000Z | 2016-08-27T03:40:51.000Z | src/calc/Checksum.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 75 | 2017-10-08T22:21:19.000Z | 2020-03-30T21:13:20.000Z | src/calc/Checksum.cpp | StratifyLabs/StratifyLib | 975a5c25a84296fd0dec64fe4dc579cf7027abe6 | [
"MIT"
] | 5 | 2018-03-27T16:44:09.000Z | 2020-07-08T16:45:55.000Z | /*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include <cstdio>
#include "calc/Checksum.hpp"
using namespace calc;
u8 Checksum::calc_zero_sum(const u8 * data, int size){
int i;
u8 sum = 0;
int count = size/sizeof(u8) - 1;
for(i=0; i < count; i++){
sum += data[i];
}
return (0 - sum);
}
bool Checksum::verify_zero_sum(const u8 * data, int size){
int i;
u8 sum = 0;
int count = size/sizeof(u8);
for(i=0; i < count; i++){
sum += data[i];
}
return (sum == 0);
}
u32 Checksum::calc_zero_sum8(const var::Data & data){
return calc_zero_sum(data.to_u8(), data.size());
}
bool Checksum::verify_zero_sum8(const var::Data & data){
return verify_zero_sum(data.to_u8(), data.size());
}
u32 Checksum::calc_zero_sum32(const var::Data & data){
return calc_zero_sum(data.to_u32(), data.size());
}
bool Checksum::verify_zero_sum32(const var::Data & data){
return verify_zero_sum(data.to_u32(), data.size());
}
u32 Checksum::calc_zero_sum(const u32 * data, int size){
int i;
u32 sum = 0;
int count = size/sizeof(u32) - 1;
for(i=0; i < count; i++){
sum += data[i];
}
return (0 - sum);
}
bool Checksum::verify_zero_sum(const u32 * data, int size){
int i;
u32 sum = 0;
int count = size/sizeof(u32);
for(i=0; i < count; i++){
sum += data[i];
}
return (sum == 0);
}
| 20.104478 | 100 | 0.644395 | bander9289 |
af11adfc5ebd185ea6fb7dfa00beeff452fdfca1 | 1,597 | cpp | C++ | SharedUtility/DataReader/BaseLibsvmReader.cpp | ELFairyhyuk/ova-gpu-svm | 78610da3d0ae4c1fb60b629d1ed3fd824f878234 | [
"Apache-1.1"
] | null | null | null | SharedUtility/DataReader/BaseLibsvmReader.cpp | ELFairyhyuk/ova-gpu-svm | 78610da3d0ae4c1fb60b629d1ed3fd824f878234 | [
"Apache-1.1"
] | null | null | null | SharedUtility/DataReader/BaseLibsvmReader.cpp | ELFairyhyuk/ova-gpu-svm | 78610da3d0ae4c1fb60b629d1ed3fd824f878234 | [
"Apache-1.1"
] | null | null | null | /*
* BaseLibsvmReader.cpp
*
* Created on: 6 May 2016
* Author: Zeyi Wen
* @brief: definition of some basic functions for reading data in libsvm format
*/
#include <iostream>
#include <assert.h>
#include <sstream>
#include <stdio.h>
#include "BaseLibsvmReader.h"
using std::istringstream;
/**
* @brief: get the number of features and the number of instances of a dataset
*/
void BaseLibSVMReader::GetDataInfo(string strFileName, int &nNumofFeatures, int &nNumofInstance, uint &nNumofValue)
{
nNumofInstance = 0;
nNumofFeatures = 0;
nNumofValue = 0;
ifstream readIn;
readIn.open(strFileName.c_str());
if(readIn.is_open() == false){
printf("opening %s failed\n", strFileName.c_str());
}
assert(readIn.is_open());
//for storing character from file
string str;
//get a sample
char cColon;
while (readIn.eof() != true){
getline(readIn, str);
if (str == "") break;
istringstream in(str);
real fValue = 0;//label
in >> fValue;
//get features of a sample
int nFeature;
real x = 0xffffffff;
while (in >> nFeature >> cColon >> x)
{
assert(cColon == ':');
if(nFeature > nNumofFeatures)
nNumofFeatures = nFeature;
nNumofValue++;
}
//skip an empty line (usually this case happens in the last line)
if(x == 0xffffffff)
continue;
nNumofInstance++;
};
//clean eof bit, when pointer reaches end of file
if(readIn.eof())
{
//cout << "end of file" << endl;
readIn.clear();
}
readIn.close();
printf("GetDataInfo. # of instances: %d; # of features: %d; # of fvalue: %d\n", nNumofInstance, nNumofFeatures, nNumofValue);
}
| 21.581081 | 127 | 0.66938 | ELFairyhyuk |
af19a928b1a8c576a437ad0ca9799287405ae88d | 445 | cpp | C++ | src/collection/CollectionInterface.cpp | christian-esken/mediawarp | 0c0d2423175774421c4b78b36693e29f6146af6b | [
"Apache-2.0"
] | null | null | null | src/collection/CollectionInterface.cpp | christian-esken/mediawarp | 0c0d2423175774421c4b78b36693e29f6146af6b | [
"Apache-2.0"
] | null | null | null | src/collection/CollectionInterface.cpp | christian-esken/mediawarp | 0c0d2423175774421c4b78b36693e29f6146af6b | [
"Apache-2.0"
] | null | null | null | /*
* CollectionInterface.cpp
*
* Created on: 13.01.2015
* Author: chris
*/
#include "CollectionInterface.h"
#include <exception>
CollectionInterface::CollectionInterface(int collectionId) : collectionId(collectionId)
{
}
CollectionInterface::~CollectionInterface()
{
}
std::vector<shared_ptr<MediaItem> > CollectionInterface::load()
{
throw std::runtime_error(std::string("CollectionInterface should not be instanciated" ));
}
| 17.8 | 90 | 0.74382 | christian-esken |
af2196db2443b3566ae1eb91d8c17b7d3c5769ae | 4,719 | cpp | C++ | src/socketinputstream.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | 1 | 2016-10-06T20:09:32.000Z | 2016-10-06T20:09:32.000Z | src/socketinputstream.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | null | null | null | src/socketinputstream.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/helpers/socketinputstream.h>
#include <log4cxx/helpers/socket.h>
#include <log4cxx/helpers/loglog.h>
using namespace log4cxx;
using namespace log4cxx::helpers ;
IMPLEMENT_LOG4CXX_OBJECT(SocketInputStream)
size_t SocketInputStream::DEFAULT_BUFFER_SIZE = 32;
SocketInputStream::SocketInputStream(SocketPtr socket)
: socket(socket), bufferSize(DEFAULT_BUFFER_SIZE),
currentPos(0), maxPos(0)
{
// memBuffer = new unsigned char[bufferSize];
}
SocketInputStream::SocketInputStream(SocketPtr socket, size_t bufferSize)
: socket(socket), bufferSize(bufferSize),
currentPos(0), maxPos(0)
{
// memBuffer = new unsigned char[bufferSize];
}
SocketInputStream::~SocketInputStream()
{
// delete [] memBuffer;
}
void SocketInputStream::read(void * buf, size_t len) const
{
size_t read = socket->read(buf, len);
if (read == 0)
{
throw EOFException();
}
/*
// LOGLOG_DEBUG(_T("SocketInputStream reading ") << len << _T(" bytes"));
unsigned char * dstBuffer = (unsigned char *)buf;
if (len <= maxPos - currentPos)
{
// LOGLOG_DEBUG(_T("SocketInputStream using cache buffer, currentPos=")
// << currentPos << _T(", maxPos=") << maxPos);
memcpy(dstBuffer, memBuffer + currentPos, len);
currentPos += len;
}
else
{
// LOGLOG_DEBUG(_T("SocketInputStream cache buffer too small"));
// LOGLOG_DEBUG(_T("tmpBuffer=alloca(")
// << len - maxPos + currentPos + bufferSize << _T(")"));
unsigned char * tmpBuffer
= (unsigned char *) alloca(len - maxPos + currentPos + bufferSize);
size_t read = socket->read(tmpBuffer, len - maxPos + currentPos + bufferSize);
if (read == 0)
{
throw EOFException();
}
// LOGLOG_DEBUG(_T("SocketInputStream currentPos:") << currentPos
// << _T(", maxPos:") << maxPos << _T(", read:") << read);
if (maxPos - currentPos > 0)
{
// LOGLOG_DEBUG(_T("memcpy(dstBuffer, membuffer+") << currentPos
// << _T(",") << maxPos << _T("-") << currentPos << _T(")"));
memcpy(dstBuffer, memBuffer + currentPos, maxPos - currentPos);
}
if (read <= len - maxPos + currentPos)
{
// LOGLOG_DEBUG(_T("SocketInputStream read <= len - maxPos + currentPos"));
// LOGLOG_DEBUG(_T("memcpy(dstBuffer+") << maxPos - currentPos
// << _T(",tmpBuffer,") << read << _T(")"));
memcpy(dstBuffer + maxPos - currentPos, tmpBuffer, read);
currentPos = 0;
maxPos = 0;
}
else
{
// LOGLOG_DEBUG(_T("memcpy(dstBuffer+") << maxPos - currentPos
// << _T(",tmpBuffer,") << len - maxPos + currentPos << _T(")"));
memcpy(dstBuffer + maxPos - currentPos, tmpBuffer, len - maxPos + currentPos);
// LOGLOG_DEBUG(_T("memcpy(memBuffer,tmpBuffer+")
// << len - maxPos + currentPos
// << _T(",") << read - len + maxPos - currentPos << _T(")"));
memcpy(memBuffer,
tmpBuffer + len - maxPos + currentPos,
read - len + maxPos - currentPos);
// LOGLOG_DEBUG(_T("maxPos=") << read - len + maxPos - currentPos);
maxPos = read - len + maxPos - currentPos;
currentPos = 0;
}
}
*/
}
void SocketInputStream::read(unsigned int& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("unsigned int read:") << value);
}
void SocketInputStream::read(int& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("int read:") << value);
}
void SocketInputStream::read(unsigned long& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("unsigned long read:") << value);
}
void SocketInputStream::read(long& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("long read:") << value);
}
void SocketInputStream::read(String& value) const
{
String::size_type size = 0;
read(&size, sizeof(String::size_type));
// LOGLOG_DEBUG(_T("string size read:") << size);
if (size > 0)
{
if (size > 1024)
{
throw SocketException();
}
TCHAR * buffer;
buffer = (TCHAR *)alloca((size + 1)* sizeof(TCHAR));
buffer[size] = _T('\0');
read(buffer, size * sizeof(TCHAR));
value = buffer;
}
// LOGLOG_DEBUG(_T("string read:") << value);
}
void SocketInputStream::close()
{
// seek to begin
currentPos = 0;
// dereference socket
socket = 0;
}
| 26.071823 | 81 | 0.665395 | MacroGu |
af2ae618822789d926e55512bd0cbb68f9dc399a | 25,648 | cpp | C++ | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | // include definition
#define _CRT_SECURE_NO_DEPRECATE
#include "cnetwork.h"
// Defines for this code
#define SAFE_RELEASE( p ) { if ( p ) { ( p )->Release ( ); ( p ) = NULL; } }
#define SAFE_DELETE_ARRAY( p ) { if ( p ) { delete [ ] ( p ); ( p ) = NULL; } }
// GUID Value
GUID DPCREATE_GUID = { 0x7d2f0893, 0xb73, 0x48ff, { 0xae, 0x7f, 0x66, 0x83, 0xec, 0x72, 0x6b, 0x21 } };
// External Data
extern DWORD gInternalErrorCode;
// Internal Data
int netTypeNum;
char *netType[MAX_CONNECTIONS];
GUID netTypeGUID[MAX_CONNECTIONS];
VOID *gConnection[MAX_CONNECTIONS];
int netConnectionTypeSelected;
int netSessionPos;
DPSessionInfo netSession[MAX_SESSIONS];
char *netSessionName[MAX_SESSIONS];
int netPlayersPos;
DPID netPlayersID[MAX_PLAYERS];
char *netPlayersName[MAX_PLAYERS];
int gNetQueueCount=0;
CNetQueue* gpNetQueue=NULL;
int gGameSessionActive=0;
bool gbSystemSessionLost=false;
int gSystemPlayerCreated=0;
int gSystemPlayerDestroyed=0;
int gSystemSessionIsNowHosting=0;
std::vector < QueuePacketStruct > g_NewNetQueue;
////////////////////////////////////////////////////////////////////////////////
// Function Name: CNetwork
// Description: Default constructor for class, is called upon creation of
// instance
// Parameters: none
// Example: none
////////////////////////////////////////////////////////////////////////////////
CNetwork::CNetwork()
{
HRESULT hr;
int temp = 0;
m_pDP=NULL; // main DirectPlay object
m_LocalPlayerDPID=0; // player id
m_hDPMessageEvent=NULL; // player event info
m_pvDPMsgBuffer=NULL; // message buffer
m_dwDPMsgBufferSize=0; // message buffer size
selectedNetSession=0;
memset(netType, NULL, sizeof(netType));
memset(netTypeGUID, NULL, sizeof(netTypeGUID));
netTypeNum = 0;
memset(gConnection, NULL, sizeof(gConnection));
netConnectionTypeSelected=0;
netPlayersPos = 0;
// create the main DirectPlay interface
if (FAILED(hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&m_pDP)))
gInternalErrorCode=18501;
// find out all of the available network connections
// by setting up this callback function, remember that
// because it is a callback function that it cannot
// be included in the class, it has to be global
if ( m_pDP )
{
if (FAILED(hr = m_pDP->EnumConnections(NULL, (LPDPENUMCONNECTIONSCALLBACK)StaticGetConnection, NULL, DPCONNECTION_DIRECTPLAY)))
gInternalErrorCode=18502;
}
netSessionPos = 0;
/*
// mike - 300305
// Global Creation of New Queue
if(gpNetQueue)
{
gpNetQueue->Clear();
gNetQueueCount=0;
}
else
{
gpNetQueue = new CNetQueue;
gNetQueueCount=0;
}
*/
// clear connection ptr
Connection=NULL;
// Clear flags
gGameSessionActive=0;
gbSystemSessionLost=false;
gSystemPlayerCreated=0;
gSystemPlayerDestroyed=0;
gSystemSessionIsNowHosting=0;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: ~CNetwork
// Description: Default destructor for class, is called upon deletion of
// instance
// Parameters: none
// Example: none
////////////////////////////////////////////////////////////////////////////////
CNetwork::~CNetwork()
{
int temp;
// delete all of the arrays
for (temp = 0; temp < MAX_PLAYERS; temp++)
SAFE_DELETE_ARRAY(netPlayersName[temp]);
for (temp = 0; temp < MAX_CONNECTIONS; temp++)
SAFE_DELETE_ARRAY(netType[temp]);
for (temp = 0; temp < MAX_SESSIONS; temp++)
SAFE_DELETE_ARRAY(netSessionName[temp]);
for (temp = 0; temp < MAX_CONNECTIONS; temp++)
SAFE_DELETE_ARRAY(gConnection[temp]);
// set them all to null
memset(netPlayersName, NULL, sizeof(netPlayersName));
memset(netType, NULL, sizeof(netType));
memset(netTypeGUID, NULL, sizeof(netTypeGUID));
memset(netSessionName, NULL, sizeof(netSessionName));
memset(gConnection, NULL, sizeof(gConnection));
if(m_pDP)
{
if(m_LocalPlayerDPID!=0)
{
m_pDP->DestroyPlayer(m_LocalPlayerDPID);
m_LocalPlayerDPID=0;
}
m_pDP->Close();
}
SAFE_RELEASE(m_pDP);
/*
// mike - 300305
if(gpNetQueue)
{
delete gpNetQueue;
gpNetQueue=NULL;
}
*/
// free allocated connection memory
if(Connection)
{
GlobalFreePtr(Connection);
Connection=NULL;
}
// Clear flags
gGameSessionActive=0;
gbSystemSessionLost=false;
gSystemPlayerCreated=0;
gSystemPlayerDestroyed=0;
gSystemSessionIsNowHosting=0;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::SetNetConnections(int index)
{
if ( !m_pDP )
return 0;
// Find an IPX, or TCP/IP if -1 (better for auto-connection than serial or modem)
if(index==-1)
{
index=0;
int iBetterIndex=-1;
for(int t=0; t<netTypeNum; t++)
{
if(netTypeGUID[t]==DPSPGUID_IPX) iBetterIndex=t;
if(netTypeGUID[t]==DPSPGUID_TCPIP && iBetterIndex==-1) iBetterIndex=t;
}
if(iBetterIndex!=-1) index=iBetterIndex;
}
HRESULT hr;
if (FAILED (hr = m_pDP->InitializeConnection(gConnection[index], 0)))
return 0;
// Later used in find session...
netConnectionTypeSelected=index;
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// gamename = session name
// name = player name
// players = max. players
// flags = session protocols
////////////////////////////////////////////////////////////////////////////////
int CNetwork::CreateNetGame(char *gamename, char *name, int players, DWORD flags)
{
HRESULT hr;
DPSESSIONDESC2 dpsd;
DPNAME dpname;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.lpszSessionNameA = gamename;
dpsd.dwMaxPlayers = players;
dpsd.dwFlags = flags | DPSESSION_DIRECTPLAYPROTOCOL;
if (FAILED(hr = m_pDP->Open(&dpsd, DPOPEN_CREATE)))
{
if(hr==DPERR_ALREADYINITIALIZED) gInternalErrorCode=18531;
if(hr==DPERR_CANTCREATEPLAYER) gInternalErrorCode=18532;
if(hr==DPERR_TIMEOUT) gInternalErrorCode=18533;
if(hr==DPERR_USERCANCEL) gInternalErrorCode=18534;
if(hr==DPERR_NOSESSIONS) gInternalErrorCode=18535;
return 0;
}
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if ( !m_pDP )
{
gInternalErrorCode=18504;
return 0;
}
if (FAILED(hr = m_pDP->CreatePlayer(&m_LocalPlayerDPID, &dpname, m_hDPMessageEvent, NULL, 0, DPPLAYER_SERVERPLAYER)))
{
gInternalErrorCode=18504;
return 0;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// ipaddress = ip address of session
// name = player name
////////////////////////////////////////////////////////////////////////////////
int CNetwork::JoinNetGame(char *name)
{
DPSESSIONDESC2 dpsd;
DPNAME dpname;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
// get all available sessions
HRESULT hr;
if ( !m_pDP )
{
gInternalErrorCode=18512;
return 0;
}
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18512;
return 0;
}
// enum sessions changes the dpsd struct, for the demo
// just select the first session that was found
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.guidInstance = netSession[selectedNetSession].guidSession;
dpsd.dwFlags = 0;
// attempt to join the session
while(1)
{
hr = m_pDP->Open(&dpsd, DPOPEN_JOIN);
if(hr==DP_OK)
break;
if(hr!=DPERR_CONNECTING)
{
gInternalErrorCode=18549;
if(hr==DPERR_ACCESSDENIED) gInternalErrorCode=18525;
if(hr==DPERR_ALREADYINITIALIZED ) gInternalErrorCode=18526;
if(hr==DPERR_AUTHENTICATIONFAILED ) gInternalErrorCode=18527;
if(hr==DPERR_CANNOTCREATESERVER ) gInternalErrorCode=18528;
if(hr==DPERR_CANTCREATEPLAYER ) gInternalErrorCode=18529;
if(hr==DPERR_CANTLOADCAPI ) gInternalErrorCode=18530;
if(hr==DPERR_CANTLOADSECURITYPACKAGE ) gInternalErrorCode=18531;
if(hr==DPERR_CANTLOADSSPI ) gInternalErrorCode=18532;
if(hr==DPERR_CONNECTING ) gInternalErrorCode=18533;
if(hr==DPERR_CONNECTIONLOST ) gInternalErrorCode=18534;
if(hr==DPERR_ENCRYPTIONFAILED ) gInternalErrorCode=18535;
if(hr==DPERR_ENCRYPTIONNOTSUPPORTED ) gInternalErrorCode=18536;
if(hr==DPERR_INVALIDFLAGS ) gInternalErrorCode=18537;
if(hr==DPERR_INVALIDPARAMS ) gInternalErrorCode=18538;
if(hr==DPERR_INVALIDPASSWORD ) gInternalErrorCode=18539;
if(hr==DPERR_LOGONDENIED ) gInternalErrorCode=18540;
if(hr==DPERR_NOCONNECTION ) gInternalErrorCode=18541;
if(hr==DPERR_NONEWPLAYERS ) gInternalErrorCode=18542;
if(hr==DPERR_NOSESSIONS ) gInternalErrorCode=18543;
if(hr==DPERR_SIGNFAILED ) gInternalErrorCode=18544;
if(hr==DPERR_TIMEOUT ) gInternalErrorCode=18545;
if(hr==DPERR_UNINITIALIZED ) gInternalErrorCode=18546;
if(hr==DPERR_USERCANCEL ) gInternalErrorCode=18547;
if(hr==DPERR_CANTCREATEPLAYER) { gInternalErrorCode=18548; return 3; }
return 0;
}
}
// create the player
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if (FAILED(hr = m_pDP->CreatePlayer(&m_LocalPlayerDPID, &dpname, m_hDPMessageEvent, NULL, 0, 0)))
{
gInternalErrorCode=18514;
return 2;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
void CNetwork::CloseNetGame(void)
{
int temp;
// delete all of the arrays
for (temp = 0; temp < MAX_PLAYERS; temp++)
SAFE_DELETE_ARRAY(netPlayersName[temp]);
for (temp = 0; temp < MAX_SESSIONS; temp++)
SAFE_DELETE_ARRAY(netSessionName[temp]);
// set them all to null
memset(netPlayersName, NULL, sizeof(netPlayersName));
memset(netSessionName, NULL, sizeof(netSessionName));
if(m_pDP)
{
if(m_LocalPlayerDPID!=0)
{
m_pDP->DestroyPlayer(m_LocalPlayerDPID);
m_LocalPlayerDPID=0;
}
m_pDP->Close();
}
}
////////////////////////////////////////////////////////////////////////////////
DPID CNetwork::CreatePlayer(char* name)
{
// create the player
DPNAME dpname;
DPID dpid;
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if ( !m_pDP )
{
gInternalErrorCode=18523;
return 0;
}
if(FAILED(m_pDP->CreatePlayer(&dpid, &dpname, m_hDPMessageEvent, NULL, 0, 0)))
{
gInternalErrorCode=18523;
return 0;
}
return dpid;
}
bool CNetwork::DestroyPlayer(DPID dpid)
{
if ( !m_pDP )
{
gInternalErrorCode=18524;
return false;
}
if(dpid!=DPID_SERVERPLAYER)
{
if(FAILED(m_pDP->DestroyPlayer(dpid)))
{
gInternalErrorCode=18524;
return false;
}
return true;
}
else
return false;
}
int CNetwork::SetNetSessions(int num)
{
selectedNetSession = num;
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// Function Name: INT_PTR CALLBACK CNetwork::GetConnection(LPCGUID pguidSP, VOID* pConnection, DWORD dwConnectionSize, LPCDPNAME pName, DWORD dwFlags, VOID* pvContext)
// Description: Finds all available network connections
// Parameters:
// Example: none as this is only called internally
////////////////////////////////////////////////////////////////////////////////
INT_PTR CALLBACK CNetwork::StaticGetConnection(LPCGUID pguidSP, VOID* pConnection, DWORD dwConnectionSize, LPCDPNAME pName, DWORD dwFlags, VOID* pvContext)
{
HRESULT hr;
LPDIRECTPLAY4A pDP;
VOID* pConnectionBuffer = NULL;
if (FAILED (hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&pDP)))
return FALSE;
// attempt to init the connection
if (FAILED (hr = pDP->InitializeConnection(pConnection, 0)))
{
SAFE_RELEASE(pDP);
return 1;
}
pConnectionBuffer = new BYTE [dwConnectionSize];
if (pConnectionBuffer == NULL)
return FALSE;
memcpy (pConnectionBuffer, pConnection, dwConnectionSize);
gConnection[netTypeNum] = pConnectionBuffer;
netType[netTypeNum] = new char[256];
strcpy(netType[netTypeNum], (CHAR *)pName->lpszShortNameA);
netTypeGUID[netTypeNum] = *pguidSP;
netTypeNum++;
SAFE_RELEASE(pDP);
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: INT_PTR CALLBACK CNetwork::GetSessions(LPCDPSESSIONDESC2 pdpsd, DWORD* pdwTimeout, DWORD dwFlags, VOID* pvContext)
// Description: finds all available sessions
// Parameters: none
// Example: none as this is only called internally
////////////////////////////////////////////////////////////////////////////////
INT_PTR CALLBACK CNetwork::StaticGetSessions(LPCDPSESSIONDESC2 pdpsd, DWORD* pdwTimeout, DWORD dwFlags, VOID* pvContext)
{
if (dwFlags & DPESC_TIMEDOUT)
return FALSE;
netSession[netSessionPos].guidSession = pdpsd->guidInstance;
sprintf(netSession[netSessionPos].szSession, "%s (%d/%d)", pdpsd->lpszSessionNameA, pdpsd->dwCurrentPlayers, pdpsd->dwMaxPlayers);
netSessionName[netSessionPos] = new char[256];
strcpy(netSessionName[netSessionPos], netSession[netSessionPos].szSession);
// mike - 250604 - stores extra data
netSession[netSessionPos].iPlayers = pdpsd->dwCurrentPlayers;
netSession[netSessionPos].iMaxPlayers = pdpsd->dwMaxPlayers;
netSessionPos++;
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: EXPORT int CNetwork::SendMsg(char *msg)
// Description: sends a text msg to all players
// Parameters: char *msg, text to send
// Example: SendMsg("hello");
////////////////////////////////////////////////////////////////////////////////
int CNetwork::SendNetMsg(int player, tagNetData* pMsg)
{
if ( !m_pDP )
return 1;
DWORD size = sizeof(int) + sizeof(DWORD) + pMsg->size;
m_pDP->Send(m_LocalPlayerDPID, player, 0, pMsg, size);
return 1;
}
int CNetwork::SendNetMsgGUA(int player, tagNetData* pMsg)
{
if ( !m_pDP )
return 1;
DWORD size = sizeof(int) + sizeof(DWORD) + pMsg->size;
m_pDP->Send(m_LocalPlayerDPID, player, DPSEND_GUARANTEED, pMsg, size);
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: EXPORT int CNetwork::GetMsg(void)
// Description: Searches for any msg that have been sent
// Parameters: none
// Example: GetMsg()
////////////////////////////////////////////////////////////////////////////////
bool gbProcessMessageElsewhere=false;
int CNetwork::AddAnyNewNetMsgToQueue(void)
{
if ( !m_pDP )
return S_FALSE;
DPID idFrom;
DPID idTo;
void *pvMsgBuffer;
DWORD dwMsgBufferSize;
HRESULT hr;
// Read all messages in queue
dwMsgBufferSize = m_dwDPMsgBufferSize;
pvMsgBuffer = m_pvDPMsgBuffer;
gbProcessMessageElsewhere=false;
while(TRUE)
{
// See what's out there
idFrom = 0;
idTo = 0;
// get msg
hr = m_pDP->Receive(&idFrom, &idTo, DPRECEIVE_ALL, pvMsgBuffer, &dwMsgBufferSize);
// resize buffer if it's too small
if (hr == DPERR_BUFFERTOOSMALL)
{
SAFE_DELETE_ARRAY(pvMsgBuffer);
pvMsgBuffer = new BYTE[dwMsgBufferSize];
if (pvMsgBuffer == NULL)
return E_OUTOFMEMORY;
m_pvDPMsgBuffer = pvMsgBuffer;
m_dwDPMsgBufferSize = dwMsgBufferSize;
continue;
}
if (DPERR_NOMESSAGES == hr)
return S_OK;
if (FAILED(hr))
return hr;
// check if system or app msg
if( idFrom == DPID_SYSMSG )
{
hr = ProcessSystemMsg((DPMSG_GENERIC*)pvMsgBuffer, dwMsgBufferSize, idFrom, idTo);
if (FAILED(hr))
return hr;
}
else
{
hr = ProcessAppMsg((DPMSG_GENERIC*)pvMsgBuffer, dwMsgBufferSize, idFrom, idTo );
if (FAILED(hr))
return hr;
}
// mike - 250604 - remove memory
delete [ ] pvMsgBuffer;
pvMsgBuffer = NULL;
m_pvDPMsgBuffer = NULL;
m_dwDPMsgBufferSize = 0;
// Quick Exit Where System Flag Was Set - To Process Elsewhere
if(gbProcessMessageElsewhere==true)
return 1;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetOneNetMsgOffQueue(QueuePacketStruct* pQPacket)
{
/*
// mike - 300305
// Scan for new messages when queue empty
if(gpNetQueue)
{
AddAnyNewNetMsgToQueue();
}
// Obtain oldest message and give to MSG
if(gpNetQueue)
{
if(gNetQueueCount>0)
{
gpNetQueue->TakeNextFromQueue(pQPacket);
gNetQueueCount--;
return 1;
}
}
*/
// mike - 300305
AddAnyNewNetMsgToQueue();
if(g_NewNetQueue.size ( ) > 0 )
{
QueuePacketStruct msg = g_NewNetQueue [ 0 ];
int id=msg.pMsg->id;
DWORD size = msg.pMsg->size;
char* pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &id, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), &msg.pMsg->msg, size);
pQPacket->pMsg = (tagNetData*)pData;
pQPacket->idFrom = msg.idFrom;
pQPacket->idTo = msg.idTo;
// mike - 020206 - addition for vs8, is this right?
//g_NewNetQueue.erase ( &g_NewNetQueue [ 0 ] );
g_NewNetQueue.erase ( g_NewNetQueue.begin ( ) + 0 );
return 1;
}
return 0;
}
int CNetwork::GetSysNetMsgIfAny(void)
{
// Scan for new messages when queue empty
// mike - 300305
//if(gpNetQueue)
AddAnyNewNetMsgToQueue();
return 1;
}
HRESULT CNetwork::ProcessSystemMsg(DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo )
{
// check msg type
switch (pMsg->dwType)
{
// chat msg
case DPSYS_CHAT:
{
DPMSG_CHAT* pChatMsg = (DPMSG_CHAT*) pMsg;
DPCHAT* pChatStruct = pChatMsg->lpChat;
break;
}
// session lost
case DPSYS_SESSIONLOST:
gbProcessMessageElsewhere=true;
gbSystemSessionLost=true;
gGameSessionActive=0;
break;
// session being hosted by new player
case DPSYS_HOST:
gbProcessMessageElsewhere=true;
gSystemSessionIsNowHosting=1;
break;
// player or group created
case DPSYS_CREATEPLAYERORGROUP:
DPMSG_CREATEPLAYERORGROUP* pCreateMsg;
pCreateMsg = (DPMSG_CREATEPLAYERORGROUP*) pMsg;
gSystemPlayerCreated=pCreateMsg->dpId;
gbProcessMessageElsewhere=true;
break;
// player or group destroyed
case DPSYS_DESTROYPLAYERORGROUP:
DPMSG_DESTROYPLAYERORGROUP* pDeleteMsg;
pDeleteMsg = (DPMSG_DESTROYPLAYERORGROUP*) pMsg;
gSystemPlayerDestroyed=pDeleteMsg->dpId;
gbProcessMessageElsewhere=true;
break;
default:
break;
}
return 1;
}
HRESULT CNetwork::ProcessAppMsg(DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo )
{
tagNetData* msg = (tagNetData*)pMsg;
/*
// mike - 300305
if(gpNetQueue)
{
QueuePacketStruct packet;
packet.pMsg=msg;
packet.idFrom=idFrom;
packet.idTo=idTo;
gpNetQueue->AddToQueue(&packet);
gNetQueueCount++;
}
*/
QueuePacketStruct packet;
QueuePacketStruct packetNew;
packet.pMsg=msg;
packet.idFrom=idFrom;
packet.idTo=idTo;
int id=packet.pMsg->id;
DWORD size = packet.pMsg->size;
char* pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &id, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), &packet.pMsg->msg, size);
// Fill item with MSG data
packetNew.pMsg = (tagNetData*)pData;
packetNew.idFrom = packet.idFrom;
packetNew.idTo = packet.idTo;
g_NewNetQueue.push_back ( packetNew );
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetNetConnections(char *data[MAX_CONNECTIONS])
{
for (int temp = 0; temp < netTypeNum; temp++)
data[temp] = netType[temp];
return 1;
}
int CNetwork::FindNetSessions(char *ExtraData)
{
LPDIRECTPLAYLOBBY2A m_DPLobby;
LPDIRECTPLAYLOBBYA DPLobbyA = NULL;
HRESULT hr;
// create instance
if(m_pDP) SAFE_RELEASE(m_pDP);
// if(m_pDP==NULL)
// {
if (FAILED(hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay4A, (LPVOID*)&m_pDP)))
{
gInternalErrorCode=18515;
return 0;
}
// }
// create lobby
if (FAILED(hr = DirectPlayLobbyCreate(NULL, &DPLobbyA, NULL, NULL, 0)))
{
gInternalErrorCode=18516;
return 0;
}
// query interface
if (FAILED(hr = DPLobbyA->QueryInterface(IID_IDirectPlayLobby2A, (LPVOID *)&m_DPLobby)))
{
gInternalErrorCode=18517;
return 0;
}
// Release unused lobby
SAFE_RELEASE(DPLobbyA);
// fill in information for create compound address
// this way we can get around the windows dialog boxes
DPCOMPOUNDADDRESSELEMENT Address[2];
DWORD AddressSize = 0;
BOOL SkipEnum=FALSE;
// IPX
int AddressMax=1;
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_IPX)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_IPX;
AddressMax=1;
}
// TCP IP
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_TCPIP)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_TCPIP;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_INet;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
}
// MODEM
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_MODEM)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_MODEM;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_Phone;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
else
{
// No Enumeration if Modem Answering..
SkipEnum=TRUE;
}
}
// SERIAL
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_SERIAL)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_SERIAL;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_ComPort;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
}
// create compound address
hr = m_DPLobby->CreateCompoundAddress(Address, AddressMax, NULL, &AddressSize);
if (hr != DPERR_BUFFERTOOSMALL)
{
gInternalErrorCode=18518;
}
// allocate memory
Connection = GlobalAllocPtr(GHND, AddressSize);
if(Connection == NULL)
{
gInternalErrorCode=18519;
return 0;
}
// create new compound address
if (FAILED(hr = m_DPLobby->CreateCompoundAddress(Address, AddressMax, Connection, &AddressSize)))
{
gInternalErrorCode=18520;
return 0;
}
// now init connection
if (FAILED(hr = m_pDP->InitializeConnection(Connection, 0)))
{
gInternalErrorCode=18521;
return 0;
}
// Free Connection and clear
GlobalFreePtr(Connection);
Connection=NULL;//fixed 4/1/3
// Delete connection allocation
SAFE_RELEASE(m_DPLobby);
// Can be skipped
if(SkipEnum==FALSE)
{
// get all available sessions
netSessionPos = 0;
DPSESSIONDESC2 dpsd;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18522;
return 0;
}
}
return 1;
}
int CNetwork::GetNetSessions(char *data[MAX_SESSIONS])
{
if ( !m_pDP )
{
gInternalErrorCode=18522;
return 0;
}
// Update Session Liost (as it is dynamic)
HRESULT hr;
netSessionPos = 0;
DPSESSIONDESC2 dpsd;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18522;
return 0;
}
for (int temp = 0; temp < netSessionPos; temp++)
data[temp] = netSessionName[temp];
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetNetPlayers(char *data[], DPID dpids[])
{
if ( !m_pDP )
{
gInternalErrorCode=18523;
return 0;
}
HRESULT hr; // for error codes
int temp; // used for loops etc.
netPlayersPos = 0; // reset to 0
// find all of the players in a session
if (FAILED(hr = m_pDP->EnumPlayers(NULL, (LPDPENUMPLAYERSCALLBACK2)StaticGetPlayers, NULL, DPENUMPLAYERS_ALL)))
{
gInternalErrorCode=18523;
return 0;
}
// store the players names
for (temp = 0; temp < netPlayersPos; temp++)
{
dpids[temp] = netPlayersID[temp];
data[temp] = netPlayersName[temp];
}
return netPlayersPos;
}
INT_PTR CALLBACK CNetwork::StaticGetPlayers(DPID dpId, DWORD dwPlayerType, LPCDPNAME lpName, DWORD dwFlags, LPVOID lpContext)
{
netPlayersID[netPlayersPos] = dpId;
netPlayersName[netPlayersPos] = new char[256];
strcpy(netPlayersName[netPlayersPos], (CHAR *)lpName->lpszShortName);
netPlayersPos++;
return 1;
}
| 25.828802 | 167 | 0.641181 | domydev |
af30f8bb5bc055f1be18c4b6dd569f56c27a7f0c | 184 | cpp | C++ | old_src/example_server/main.cpp | InsightCenterNoodles/NoodlesPlusPlus | 3396e530a5948416fd364cc9ffa3f5bcbb8abc3b | [
"MIT"
] | null | null | null | old_src/example_server/main.cpp | InsightCenterNoodles/NoodlesPlusPlus | 3396e530a5948416fd364cc9ffa3f5bcbb8abc3b | [
"MIT"
] | null | null | null | old_src/example_server/main.cpp | InsightCenterNoodles/NoodlesPlusPlus | 3396e530a5948416fd364cc9ffa3f5bcbb8abc3b | [
"MIT"
] | null | null | null | #include "plotty.h"
#include <QCoreApplication>
int main(int argc, char* argv[]) {
auto app = QCoreApplication(argc, argv);
Plotty plotty(50000);
return app.exec();
}
| 14.153846 | 44 | 0.652174 | InsightCenterNoodles |
af314665d27de3c965b1cdad16acd9bdcf07c943 | 959 | cpp | C++ | tests/cpp/nontype_template_args.201411.cpp | eggs-cpp/sd-6 | d7ba0c08acf7c1c817baa1ea53f488d02394858a | [
"BSL-1.0"
] | 7 | 2015-03-03T18:33:02.000Z | 2018-08-31T08:26:01.000Z | tests/cpp/nontype_template_args.201411.cpp | eggs-cpp/sd-6 | d7ba0c08acf7c1c817baa1ea53f488d02394858a | [
"BSL-1.0"
] | null | null | null | tests/cpp/nontype_template_args.201411.cpp | eggs-cpp/sd-6 | d7ba0c08acf7c1c817baa1ea53f488d02394858a | [
"BSL-1.0"
] | null | null | null | // Eggs.SD-6
//
// Copyright Agustin K-ballo Berge, Fusion Fenix 2015
//
// 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)
int x;
int arr[10];
void fun() {}
struct s { static int sm; } so;
template <typename T, T*> struct ptr {};
void test_ptr_nontype_template_args() {
ptr<int const, &x> q;
ptr<int, arr> a;
ptr<void(), fun> f;
ptr<int, &so.sm> sm;
ptr<int, nullptr> np;
}
template <typename T, T&> struct ref {};
void test_ref_nontype_template_args() {
ref<int const, x> q;
ref<int, so.sm> sm;
}
template <typename T, typename C, T C::*> struct mem_ptr {};
void test_mem_ptr_nontype_template_args() {
mem_ptr<int, s, nullptr> np;
}
void test_nontype_template_args() {
test_ptr_nontype_template_args();
test_ref_nontype_template_args();
test_mem_ptr_nontype_template_args();
}
int main() {
test_nontype_template_args();
}
| 21.311111 | 79 | 0.698644 | eggs-cpp |
af3243cdf44db04240e5caaeeb6c906616f39c47 | 14,615 | cpp | C++ | src/intcomp/AbbreviationCodegen.cpp | WebAssembly/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 11 | 2016-07-08T20:43:29.000Z | 2021-05-09T21:43:34.000Z | src/intcomp/AbbreviationCodegen.cpp | DalavanCloud/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 62 | 2016-06-07T15:21:24.000Z | 2017-05-18T15:51:04.000Z | src/intcomp/AbbreviationCodegen.cpp | DalavanCloud/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 5 | 2016-06-07T15:05:32.000Z | 2020-01-06T17:21:43.000Z | // -*- C++ -*- */
//
// Copyright 2016 WebAssembly Community Group participants
//
// 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.
// Implements an s-exprssion code generator for abbreviations.
#include "intcomp/AbbreviationCodegen.h"
#include "algorithms/cism0x0.h"
#if 1
#include "sexp/TextWriter.h"
#endif
#include <algorithm>
namespace wasm {
using namespace decode;
using namespace filt;
using namespace interp;
using namespace utils;
namespace intcomp {
namespace {
//#define X(NAME, VALUE)
#define SPECIAL_ABBREV_TABLE \
X(CismDefaultSingleValue, 16767) \
X(CismDefaultMultipleValue, 16766) \
X(CismBlockEnterValue, 16768) \
X(CismBlockExitValue, 16769) \
X(CismAlignValue, 16770)
enum class SpecialAbbrev : IntType {
#define X(NAME, VALUE) NAME = VALUE,
SPECIAL_ABBREV_TABLE
#undef X
Unknown = ~(IntType(0))
};
static IntType SpecialAbbrevs[] = {
#define X(NAME, VALUE) IntType(SpecialAbbrev::NAME),
SPECIAL_ABBREV_TABLE
#undef X
};
} // end of anonymous namespace
AbbreviationCodegen::AbbreviationCodegen(const CompressionFlags& Flags,
CountNode::RootPtr Root,
HuffmanEncoder::NodePtr EncodingRoot,
CountNode::PtrSet& Assignments,
bool ToRead)
: Flags(Flags),
Root(Root),
EncodingRoot(EncodingRoot),
Assignments(Assignments),
ToRead(ToRead),
CategorizeName("categorize"),
OpcodeName("opcode"),
ProcessName("process"),
ValuesName("values"),
OldName(".old") {}
AbbreviationCodegen::~AbbreviationCodegen() {}
Node* AbbreviationCodegen::generateHeader(NodeType Type,
uint32_t MagicNumber,
uint32_t VersionNumber) {
Header* Header = nullptr;
switch (Type) {
default:
return Symtab->create<Void>();
case NodeType::SourceHeader:
Header = Symtab->create<SourceHeader>();
break;
case NodeType::ReadHeader:
Header = Symtab->create<ReadHeader>();
break;
case NodeType::WriteHeader:
Header = Symtab->create<WriteHeader>();
break;
}
Header->append(
Symtab->create<U32Const>(MagicNumber, ValueFormat::Hexidecimal));
Header->append(
Symtab->create<U32Const>(VersionNumber, ValueFormat::Hexidecimal));
return Header;
}
void AbbreviationCodegen::generateFunctions(Algorithm* Alg) {
if (!Flags.UseCismModel)
return Alg->append(generateStartFunction());
Alg->append(generateEnclosingAlg("cism"));
if (!ToRead) {
Alg->append(generateRename(ProcessName));
Alg->append(generateProcessFunction());
Alg->append(generateValuesFunction());
}
Alg->append(generateOpcodeFunction());
Alg->append(generateCategorizeFunction());
}
Node* AbbreviationCodegen::generateValuesFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(ValuesName));
Fcn->append(Symtab->create<NoParams>());
Fcn->append(Symtab->create<NoLocals>());
Fcn->append(Symtab->create<Loop>(Symtab->create<Varuint64>(),
Symtab->create<Varint64>()));
return Fcn;
}
Node* AbbreviationCodegen::generateProcessFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(ProcessName));
Fcn->append(Symtab->create<ParamValues>(1, ValueFormat::Decimal));
Fcn->append(Symtab->create<NoLocals>());
auto* Swch = Symtab->create<Switch>();
Fcn->append(Swch);
Swch->append(Symtab->create<Param>(0, ValueFormat::Decimal));
auto* Eval = Symtab->create<EvalVirtual>();
Swch->append(Eval);
Eval->append(generateOld(ProcessName));
Eval->append(Symtab->create<Param>(0, ValueFormat::Decimal));
Swch->append(Symtab->create<Case>(
Symtab->create<U64Const>(IntType(SpecialAbbrev::CismBlockEnterValue),
ValueFormat::Decimal),
generateCallback(PredefinedSymbol::Block_enter_writeonly)));
Swch->append(Symtab->create<Case>(
Symtab->create<U64Const>(IntType(SpecialAbbrev::CismBlockExitValue),
ValueFormat::Decimal),
generateCallback(PredefinedSymbol::Block_exit_writeonly)));
return Fcn;
}
Node* AbbreviationCodegen::generateOpcodeFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(OpcodeName));
Fcn->append(Symtab->create<NoParams>());
if (Flags.AlignOpcodes)
Fcn->append(Symtab->create<Locals>(1, ValueFormat::Decimal));
else
Fcn->append(Symtab->create<NoLocals>());
Node* Rd = generateAbbreviationRead();
if (!Flags.AlignOpcodes) {
Fcn->append(Rd);
return Fcn;
}
Sequence* Seq = Symtab->create<Sequence>();
Fcn->append(Seq);
Seq->append(
Symtab->create<Set>(Symtab->create<Local>(0, ValueFormat::Decimal), Rd));
Seq->append(generateCallback(PredefinedSymbol::Align));
Seq->append(Symtab->create<Local>(0, ValueFormat::Decimal));
return Fcn;
}
Node* AbbreviationCodegen::generateCategorizeFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(CategorizeName));
Fcn->append(Symtab->create<ParamValues>(1, ValueFormat::Decimal));
Fcn->append(Symtab->create<NoLocals>());
auto* MapNd = Symtab->create<Map>();
Fcn->append(MapNd);
MapNd->append(Symtab->create<Param>(0, ValueFormat::Decimal));
// Define remappings for each special action.
std::map<IntType, IntType> FixMap;
{
// Start by collecting set of used abbreviations.
std::unordered_set<IntType> Used;
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
Used.insert(Nd->getAbbrevIndex());
}
// Now find available renames for conflicting values.
IntType NextAvail = 0;
for (size_t i = 0; i < size(SpecialAbbrevs); ++i) {
IntType Val = SpecialAbbrevs[i];
if (Used.count(Val)) {
while (Used.count(NextAvail))
++NextAvail;
}
FixMap[Val] = NextAvail++;
}
}
std::map<IntType, IntType> CatMap;
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
IntType Val = Nd->getAbbrevIndex();
if (FixMap.count(Val)) {
CatMap[Val] = FixMap[Val];
continue;
}
switch (Nd->getKind()) {
default:
break;
case CountNode::Kind::Default:
CatMap[Nd->getAbbrevIndex()] =
(IntType(cast<DefaultCountNode>(Nd.get())->isSingle()
? SpecialAbbrev::CismDefaultSingleValue
: SpecialAbbrev::CismDefaultMultipleValue));
break;
case CountNode::Kind::Block:
CatMap[Nd->getAbbrevIndex()] =
IntType(cast<BlockCountNode>(Nd.get())->isEnter()
? SpecialAbbrev::CismBlockEnterValue
: SpecialAbbrev::CismBlockExitValue);
break;
case CountNode::Kind::Align:
CatMap[Nd->getAbbrevIndex()] = IntType(SpecialAbbrev::CismAlignValue);
break;
}
}
for (const auto& Pair : CatMap)
MapNd->append(generateMapCase(Pair.first, Pair.second));
return Fcn;
}
Node* AbbreviationCodegen::generateMapCase(IntType Index, IntType Value) {
return Symtab->create<Case>(
Symtab->create<U64Const>(Index, ValueFormat::Decimal),
Symtab->create<U64Const>(Value, ValueFormat::Decimal));
}
Node* AbbreviationCodegen::generateEnclosingAlg(charstring Name) {
auto* Enc = Symtab->create<EnclosingAlgorithms>();
Enc->append(Symtab->getOrCreateSymbol(Name));
return Enc;
}
Node* AbbreviationCodegen::generateOld(std::string Name) {
return Symtab->getOrCreateSymbol(Name + OldName);
}
Node* AbbreviationCodegen::generateRename(std::string Name) {
Node* From = Symtab->getOrCreateSymbol(Name);
Node* To = generateOld(Name);
return Symtab->create<Rename>(From, To);
}
Node* AbbreviationCodegen::generateStartFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getPredefined(PredefinedSymbol::File));
Fcn->append(Symtab->create<NoParams>());
Fcn->append(Symtab->create<NoLocals>());
Fcn->append(Symtab->create<LoopUnbounded>(generateSwitchStatement()));
return Fcn;
}
Node* AbbreviationCodegen::generateAbbreviationRead() {
auto* Format =
EncodingRoot
? Symtab->create<BinaryEval>(generateHuffmanEncoding(EncodingRoot))
: generateAbbrevFormat(Flags.AbbrevFormat);
if (ToRead) {
Format = Symtab->create<Read>(Format);
}
return Format;
}
Node* AbbreviationCodegen::generateHuffmanEncoding(
HuffmanEncoder::NodePtr Root) {
Node* Result = nullptr;
switch (Root->getType()) {
case HuffmanEncoder::NodeType::Selector: {
HuffmanEncoder::Selector* Sel =
cast<HuffmanEncoder::Selector>(Root.get());
Result =
Symtab->create<BinarySelect>(generateHuffmanEncoding(Sel->getKid1()),
generateHuffmanEncoding(Sel->getKid2()));
break;
}
case HuffmanEncoder::NodeType::Symbol:
Result = Symtab->create<BinaryAccept>();
break;
}
return Result;
}
Node* AbbreviationCodegen::generateSwitchStatement() {
auto* SwitchStmt = Symtab->create<Switch>();
SwitchStmt->append(generateAbbreviationRead());
SwitchStmt->append(Symtab->create<Error>());
// TODO(karlschimpf): Sort so that output consistent or more readable?
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
SwitchStmt->append(generateCase(Nd->getAbbrevIndex(), Nd));
}
return SwitchStmt;
}
Node* AbbreviationCodegen::generateCase(size_t AbbrevIndex, CountNode::Ptr Nd) {
return Symtab->create<Case>(
Symtab->create<U64Const>(AbbrevIndex, decode::ValueFormat::Decimal),
generateAction(Nd));
}
Node* AbbreviationCodegen::generateAction(CountNode::Ptr Nd) {
CountNode* NdPtr = Nd.get();
if (auto* CntNd = dyn_cast<IntCountNode>(NdPtr))
return generateIntLitAction(CntNd);
else if (auto* BlkPtr = dyn_cast<BlockCountNode>(NdPtr))
return generateBlockAction(BlkPtr);
else if (auto* DefaultPtr = dyn_cast<DefaultCountNode>(NdPtr))
return generateDefaultAction(DefaultPtr);
else if (isa<AlignCountNode>(NdPtr))
return generateCallback(PredefinedSymbol::Align);
return Symtab->create<Error>();
}
Node* AbbreviationCodegen::generateCallback(PredefinedSymbol Sym) {
return Symtab->create<Callback>(
Symtab->create<LiteralActionUse>(Symtab->getPredefined(Sym)));
}
Node* AbbreviationCodegen::generateBlockAction(BlockCountNode* Blk) {
PredefinedSymbol Sym;
if (Blk->isEnter()) {
Sym = ToRead ? PredefinedSymbol::Block_enter
: PredefinedSymbol::Block_enter_writeonly;
} else {
Sym = ToRead ? PredefinedSymbol::Block_exit
: PredefinedSymbol::Block_exit_writeonly;
}
return generateCallback(Sym);
}
Node* AbbreviationCodegen::generateDefaultAction(DefaultCountNode* Default) {
return Default->isSingle() ? generateDefaultSingleAction()
: generateDefaultMultipleAction();
}
Node* AbbreviationCodegen::generateDefaultMultipleAction() {
Node* LoopSize = Symtab->create<Varuint64>();
if (ToRead)
LoopSize = Symtab->create<Read>(LoopSize);
return Symtab->create<Loop>(LoopSize, generateDefaultSingleAction());
}
Node* AbbreviationCodegen::generateDefaultSingleAction() {
return Symtab->create<Varint64>();
}
Node* AbbreviationCodegen::generateIntType(IntType Value) {
return Symtab->create<U64Const>(Value, decode::ValueFormat::Decimal);
}
Node* AbbreviationCodegen::generateIntLitAction(IntCountNode* Nd) {
return ToRead ? generateIntLitActionRead(Nd) : generateIntLitActionWrite(Nd);
}
Node* AbbreviationCodegen::generateIntLitActionRead(IntCountNode* Nd) {
std::vector<IntCountNode*> Values;
while (Nd) {
Values.push_back(Nd);
Nd = Nd->getParent().get();
}
std::reverse(Values.begin(), Values.end());
auto* W = Symtab->create<Write>();
W->append(Symtab->create<Varuint64>());
for (IntCountNode* Nd : Values)
W->append(generateIntType(Nd->getValue()));
return W;
}
Node* AbbreviationCodegen::generateIntLitActionWrite(IntCountNode* Nd) {
return Symtab->create<Void>();
}
std::shared_ptr<SymbolTable> AbbreviationCodegen::getCodeSymtab() {
Symtab = std::make_shared<SymbolTable>();
auto* Alg = Symtab->create<Algorithm>();
Alg->append(generateHeader(NodeType::SourceHeader, CasmBinaryMagic,
CasmBinaryVersion));
if (Flags.UseCismModel) {
Symtab->setEnclosingScope(getAlgcism0x0Symtab());
if (ToRead) {
Alg->append(generateHeader(NodeType::ReadHeader, CismBinaryMagic,
CismBinaryVersion));
Alg->append(generateHeader(NodeType::WriteHeader, WasmBinaryMagic,
WasmBinaryVersionD));
} else {
Alg->append(generateHeader(NodeType::ReadHeader, WasmBinaryMagic,
WasmBinaryVersionD));
Alg->append(generateHeader(NodeType::WriteHeader, CismBinaryMagic,
CismBinaryVersion));
}
} else {
Alg->append(generateHeader(NodeType::ReadHeader, WasmBinaryMagic,
WasmBinaryVersionD));
}
generateFunctions(Alg);
Symtab->setAlgorithm(Alg);
Symtab->install();
return Symtab;
}
Node* AbbreviationCodegen::generateAbbrevFormat(IntTypeFormat AbbrevFormat) {
switch (AbbrevFormat) {
case IntTypeFormat::Uint8:
return Symtab->create<Uint8>();
case IntTypeFormat::Varint32:
return Symtab->create<Varint32>();
case IntTypeFormat::Varuint32:
return Symtab->create<Varuint32>();
case IntTypeFormat::Uint32:
return Symtab->create<Uint32>();
case IntTypeFormat::Varint64:
return Symtab->create<Varint64>();
case IntTypeFormat::Varuint64:
return Symtab->create<Varuint64>();
case IntTypeFormat::Uint64:
return Symtab->create<Uint64>();
}
WASM_RETURN_UNREACHABLE(nullptr);
}
} // end of namespace intcomp
} // end of namespace wasm
| 33.36758 | 80 | 0.67376 | WebAssembly |
af32802b9e92115193ac6365f68c26580d39cc78 | 1,473 | cpp | C++ | string/simplify_path.cpp | zhangxin23/leetcode | 4c8fc60e59448045a3e880caaedd0486164e68e7 | [
"MIT"
] | 1 | 2015-07-15T07:31:42.000Z | 2015-07-15T07:31:42.000Z | string/simplify_path.cpp | zhangxin23/leetcode | 4c8fc60e59448045a3e880caaedd0486164e68e7 | [
"MIT"
] | null | null | null | string/simplify_path.cpp | zhangxin23/leetcode | 4c8fc60e59448045a3e880caaedd0486164e68e7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <bits/stl_stack.h>
using namespace std;
/**
* Given an absolute path for a file (Unix-style), simplify it.
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
* Corner Cases:
* • Did you consider the case where path = "/../"? In this case, you should return "/".
* • Another corner case is the path might contain multiple slashes '/' together,
* such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo".
* */
class Solution {
public:
string simplifyPath(string path) {
string curDir;
vector<string> vec;
path += "/";
for(int i = 0; i < path.length(); i++) {
if(path[i] == '/') {
if(curDir.empty())
continue;
else if(curDir == ".")
curDir.clear();
else if(curDir == "..") {
if(vec.empty())
vec.pop_back();
curDir.clear();
} else {
vec.push_back(curDir);
curDir.clear();
}
} else {
curDir += path[i];
}
}
string result;
if(vec.empty())
return "/";
else {
for(int i = 0; i < vec.size(); i++)
result += vec[i];
return result;
}
}
};
| 27.277778 | 102 | 0.441955 | zhangxin23 |
af3684c70243779d4f462636a73078db6e072682 | 2,950 | cpp | C++ | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | //
// zoneview.cpp
// MelobaseStation
//
// Created by Daniel Cliche on 2016-02-08.
// Copyright (c) 2016-2021 Daniel Cliche. All rights reserved.
//
#include "zoneview.h"
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::ZoneView(std::string name, void* owner, int zone) : View(name, owner) {
_channel = zone;
std::vector<Any> items;
for (int i = 0; i < STUDIO_MAX_CHANNELS; ++i) items.push_back(std::to_string(i + 1));
_channelSegmentedControl = std::make_shared<MDStudio::SegmentedControl>("channelSegmentedControl", this, items);
_channelSegmentedControl->setFont(SystemFonts::sharedInstance()->semiboldFontSmall());
addSubview(_channelSegmentedControl);
_channelSegmentedControl->setSelectedSegment(_channel);
_transposeLabelImage = std::make_shared<Image>("[email protected]");
_transposeLabelImageView = std::make_shared<ImageView>("transposeLabelImageView", this, _transposeLabelImage);
_transposeBoxView = std::make_shared<BoxView>("transposeBoxView", this);
_transposeLabelView = std::make_shared<LabelView>("transposeLabelView", this, "0");
_transposeStepper = std::make_shared<Stepper>("transposeStepper", this, 12, -48, 48, 0);
_studioChannelView = std::make_shared<StudioChannelView>("studioChannelView", this, _channel);
addSubview(_studioChannelView);
addSubview(_transposeBoxView);
addSubview(_transposeLabelView);
addSubview(_transposeStepper);
addSubview(_transposeLabelImageView);
}
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::~ZoneView() {}
// ---------------------------------------------------------------------------------------------------------------------
void ZoneView::setFrame(Rect aRect) {
View::setFrame(aRect);
MDStudio::Rect r = bounds();
r.origin.x = 60.0f;
r.origin.y = r.size.height - 18.0f;
r.size.height = 16.0f;
r.size.width -= 60.0f;
r = MDStudio::makeCenteredRectInRect(r, STUDIO_MAX_CHANNELS * 20.0f, 16.0f);
_channelSegmentedControl->setFrame(r);
MDStudio::Rect r2 = MDStudio::makeCenteredRectInRect(
makeRect(0.0f, 0.0f, bounds().size.width, bounds().size.height - r.size.height), 440.0f, 140.0f);
auto r3 = r2;
if (r3.origin.x < 0.0f) r3.origin.x = 0.0f;
_transposeStepper->setFrame(makeRect(r3.origin.x + 0.0f, r3.origin.y + 40.0f, 20.0f, 30.0f));
_transposeBoxView->setFrame(makeRect(r3.origin.x + 20.0f, r3.origin.y + 40.0f, 40.0f, 30.0f));
_transposeLabelView->setFrame(makeInsetRect(_transposeBoxView->frame(), 5, 5));
_transposeLabelImageView->setFrame(makeRect(r3.origin.x, r3.origin.y + 30.0f + 40.0f, 60.0f, 20.0f));
_studioChannelView->setFrame(makeRect(r2.origin.x + 60.0f, r2.origin.y, r2.size.width - 60.0f, r2.size.height));
}
| 42.142857 | 120 | 0.622034 | dcliche |
af3c5d944ca4f879ea6d4365e1365e221f69cde7 | 45,136 | cpp | C++ | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 418 | 2019-12-16T10:36:42.000Z | 2022-03-27T02:46:08.000Z | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 15 | 2019-12-16T15:39:29.000Z | 2021-12-02T15:45:21.000Z | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 54 | 2019-12-16T12:33:18.000Z | 2022-02-27T16:33:28.000Z | /*
MIT License
Copyright (c) 2019 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//---------------------------------------------------------------------------------------
// BVH traversal operations to find contacts between FEM surface-triangle meshes, and
// operations to test for nearest or intersected tets of rest-state meshes
//---------------------------------------------------------------------------------------
#include "AMD_FEMFX.h"
#include "FEMFXBvhBuild.h"
#include "FEMFXTetMesh.h"
#include "FEMFXTriCcd.h"
#include "FEMFXTriIntersection.h"
#include "FEMFXCollisionPairData.h"
#include "FEMFXFindContacts.h"
namespace AMD
{
struct FmClosestTetResult;
struct FmConstraintsBuffer;
void FmFitLeafAabbs(FmTetMesh* tetMesh, float timestep, float padding)
{
FmBvh& bvh = tetMesh->bvh;
uint numExteriorFaces = tetMesh->numExteriorFaces;
bvh.numPrims = numExteriorFaces;
if (numExteriorFaces == 0)
{
return;
}
FmVector3 minPosition = tetMesh->vertsPos[0];
FmVector3 maxPosition = tetMesh->vertsPos[0];
for (uint exteriorFaceId = 0; exteriorFaceId < numExteriorFaces; exteriorFaceId++)
{
FmExteriorFace& exteriorFace = tetMesh->exteriorFaces[exteriorFaceId];
FmTetVertIds tetVerts = tetMesh->tetsVertIds[exteriorFace.tetId];
FmFaceVertIds faceVerts;
FmGetFaceVertIds(&faceVerts, exteriorFace.faceId, tetVerts);
FmVector3 pos0 = tetMesh->vertsPos[faceVerts.ids[0]];
FmVector3 pos1 = tetMesh->vertsPos[faceVerts.ids[1]];
FmVector3 pos2 = tetMesh->vertsPos[faceVerts.ids[2]];
FmVector3 vel0 = tetMesh->vertsVel[faceVerts.ids[0]];
FmVector3 vel1 = tetMesh->vertsVel[faceVerts.ids[1]];
FmVector3 vel2 = tetMesh->vertsVel[faceVerts.ids[2]];
minPosition = min(minPosition, pos0);
maxPosition = max(maxPosition, pos0);
minPosition = min(minPosition, pos1);
maxPosition = max(maxPosition, pos1);
minPosition = min(minPosition, pos2);
maxPosition = max(maxPosition, pos2);
FmTri tri;
tri.pos0 = pos0;
tri.pos1 = pos1;
tri.pos2 = pos2;
tri.vel0 = vel0;
tri.vel1 = vel1;
tri.vel2 = vel2;
FmAabb aabb = FmComputeTriAabb(tri, timestep, padding);
bvh.primBoxes[exteriorFaceId] = aabb;
}
tetMesh->minPosition = minPosition;
tetMesh->maxPosition = maxPosition;
}
// For CCD, must build after integration computes new velocities.
void FmBuildHierarchy(FmTetMesh* tetMesh, float timestep, float gap)
{
FM_TRACE_SCOPED_EVENT(REBUILD_BVH);
FmFitLeafAabbs(tetMesh, timestep, gap);
FmBuildBvhOnLeaves(&tetMesh->bvh, tetMesh->minPosition, tetMesh->maxPosition);
}
// Fit leaves on rest position tets of a constructed TetMesh
void FmFitLeafAabbsOnRestTets(FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos, const FmTetMesh& tetMesh)
{
FmBvh& bvh = *outBvh;
uint numTets = tetMesh.numTets;
bvh.numPrims = numTets;
if (numTets == 0)
{
*tetMeshMinPos = FmInitVector3(0.0);
*tetMeshMaxPos = FmInitVector3(0.0);
return;
}
FmVector3 meshMinPos = tetMesh.vertsRestPos[0];
FmVector3 meshMaxPos = tetMesh.vertsRestPos[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetMesh.tetsVertIds[tetId];
FmVector3 pos0 = tetMesh.vertsRestPos[tetVerts.ids[0]];
FmVector3 pos1 = tetMesh.vertsRestPos[tetVerts.ids[1]];
FmVector3 pos2 = tetMesh.vertsRestPos[tetVerts.ids[2]];
FmVector3 pos3 = tetMesh.vertsRestPos[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Fit leaves on rest position tets provided as array of positions and tet vertex ids.
void FmFitLeafAabbsOnRestTets(
FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmBvh& bvh = *outBvh;
bvh.numPrims = numTets;
FmVector3 meshMinPos = vertRestPositions[0];
FmVector3 meshMaxPos = vertRestPositions[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetVertIds[tetId];
FmVector3 pos0 = vertRestPositions[tetVerts.ids[0]];
FmVector3 pos1 = vertRestPositions[tetVerts.ids[1]];
FmVector3 pos2 = vertRestPositions[tetVerts.ids[2]];
FmVector3 pos3 = vertRestPositions[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmTetMesh& tetMesh)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, tetMesh);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, vertRestPositions, tetVertIds, numTets);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
struct FmClosestTetQueryState
{
const FmTetMesh* tetMesh; // if NULL uses vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 queryPoint;
FmVector3 closestPoint;
uint closestTetId;
uint closestFaceId;
float closestDistance;
bool insideTet;
};
static FM_FORCE_INLINE float FmPointBoxDistance(const FmVector3& queryPoint, const FmAabb& box)
{
float maxGapX = FmMaxFloat(FmMaxFloat(queryPoint.x - box.pmax.x, box.pmin.x - queryPoint.x), 0.0f);
float maxGapY = FmMaxFloat(FmMaxFloat(queryPoint.y - box.pmax.y, box.pmin.y - queryPoint.y), 0.0f);
float maxGapZ = FmMaxFloat(FmMaxFloat(queryPoint.z - box.pmax.z, box.pmin.z - queryPoint.z), 0.0f);
float distance = sqrtf(maxGapX*maxGapX + maxGapY*maxGapY + maxGapZ*maxGapZ);
return distance;
}
void FmFindClosestTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, find nearest position of tet
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
else
{
// Check tet faces for points nearer than current result
for (uint faceId = 0; faceId < 4; faceId++)
{
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, faceId);
FmVector3 triPos0 = tetPos[tetCorners.ids[0]];
FmVector3 triPos1 = tetPos[tetCorners.ids[1]];
FmVector3 triPos2 = tetPos[tetCorners.ids[2]];
FmDistanceResult distResult;
FmPointTriangleDistance(&distResult, queryPoint, triPos0, triPos1, triPos2, 0, 0, 1, 2);
if (distResult.distance < queryState.closestDistance)
{
queryState.closestPoint = distResult.posj;
queryState.closestTetId = tetId;
queryState.closestFaceId = faceId;
queryState.closestDistance = distResult.distance;
}
}
}
}
else
{
FmAabb& lbox = hierarchy->nodes[lc].box;
FmAabb& rbox = hierarchy->nodes[rc].box;
float ldistance = FmPointBoxDistance(queryPoint, lbox);
float rdistance = FmPointBoxDistance(queryPoint, rbox);
if (ldistance < rdistance)
{
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
}
else
{
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
}
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
void FmFindIntersectedTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
FmAabb& box = hierarchy->nodes[idx].box;
if (queryPoint.x < box.pmin.x || queryPoint.x > box.pmax.x
|| queryPoint.y < box.pmin.y || queryPoint.y > box.pmax.y
|| queryPoint.z < box.pmin.z || queryPoint.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, test intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
}
else
{
FmFindIntersectedTetRecursive(queryState, (uint)lc);
FmFindIntersectedTetRecursive(queryState, (uint)rc);
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
struct FmTetsIntersectingBoxQueryState
{
uint* tets;
uint numTets;
const FmTetMesh* tetMesh; // If NULL, use vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 boxHalfDimensions;
FmVector3 boxCenterPos;
FmMatrix3 boxRotation;
FmMatrix3 boxRotationInv;
FmVector3 boxPoints[8];
FmVector3 aabbMinPos;
FmVector3 aabbMaxPos;
};
void FmFindTetsIntersectingBoxRecursive(FmTetsIntersectingBoxQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmBvhNode* nodes = hierarchy->nodes;
// Return if box's AABB does not intersect BVH node
FmAabb& box = hierarchy->nodes[idx].box;
if (queryState.aabbMaxPos.x < box.pmin.x || queryState.aabbMinPos.x > box.pmax.x
|| queryState.aabbMaxPos.y < box.pmin.y || queryState.aabbMinPos.y > box.pmax.y
|| queryState.aabbMaxPos.z < box.pmin.z || queryState.aabbMinPos.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
FmVector3 tetPosBoxSpace[4];
tetPosBoxSpace[0] = mul(queryState.boxRotationInv, tetPos[0] - queryState.boxCenterPos);
tetPosBoxSpace[1] = mul(queryState.boxRotationInv, tetPos[1] - queryState.boxCenterPos);
tetPosBoxSpace[2] = mul(queryState.boxRotationInv, tetPos[2] - queryState.boxCenterPos);
tetPosBoxSpace[3] = mul(queryState.boxRotationInv, tetPos[3] - queryState.boxCenterPos);
bool intersecting = false;
// Check for box points inside tet
for (uint boxPntIdx = 0; boxPntIdx < 8; boxPntIdx++)
{
if (FmIntersectionX30(tetPosBoxSpace[0], tetPosBoxSpace[1], tetPosBoxSpace[2], tetPosBoxSpace[3], queryState.boxPoints[boxPntIdx]))
{
intersecting = true;
break;
}
}
// Check for tet points inside box
if (!intersecting)
{
FmVector3 halfDims = queryState.boxHalfDimensions;
for (uint tetPntIdx = 0; tetPntIdx < 4; tetPntIdx++)
{
if (tetPosBoxSpace[tetPntIdx].x >= -halfDims.x && tetPosBoxSpace[tetPntIdx].x <= halfDims.x
&& tetPosBoxSpace[tetPntIdx].y >= -halfDims.y && tetPosBoxSpace[tetPntIdx].y <= halfDims.y
&& tetPosBoxSpace[tetPntIdx].z >= -halfDims.z && tetPosBoxSpace[tetPntIdx].z <= halfDims.z)
{
intersecting = true;
}
}
}
// Test for edges intersecting faces
if (!intersecting)
{
for (uint tvi = 0; tvi < 4; tvi++)
{
FmVector3 intersectionPnt;
FmVector3 tetEdgePosi = tetPosBoxSpace[tvi];
for (uint tvj = tvi + 1; tvj < 4; tvj++)
{
FmVector3 tetEdgePosj = tetPosBoxSpace[tvj];
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[2], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[1], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[3], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[5], queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[4], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[5], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[6], queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[6], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[3], queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
}
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, tvi);
FmVector3 triPos0 = tetPosBoxSpace[tetCorners.ids[0]];
FmVector3 triPos1 = tetPosBoxSpace[tetCorners.ids[1]];
FmVector3 triPos2 = tetPosBoxSpace[tetCorners.ids[2]];
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
}
}
if (intersecting)
{
queryState.tets[queryState.numTets] = tetId;
queryState.numTets++;
}
}
else
{
FmFindTetsIntersectingBoxRecursive(queryState, (uint)lc);
FmFindTetsIntersectingBoxRecursive(queryState, (uint)rc);
}
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmTetMesh* tetMesh, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
struct FmSceneCollisionPlanesContactsQueryState
{
FmCollidedObjectPair* objectPair;
FmSceneCollisionPlanes collisionPlanes;
};
void FmFindSceneCollisionPlanesContactsRecursive(FmSceneCollisionPlanesContactsQueryState& queryState, uint idx)
{
FmCollidedObjectPair* objectPair = queryState.objectPair;
const FmBvh* hierarchy = objectPair->objectAHierarchy;
FmSceneCollisionPlanes& collisionPlanes = queryState.collisionPlanes;
FmBvhNode* nodes = hierarchy->nodes;
float timestep = objectPair->timestep;
float distContactThreshold = objectPair->distContactThreshold;
// Return if AABB shows no potential contact
FmAabb& box = hierarchy->nodes[idx].box;
bool results[6];
float threshold = distContactThreshold * 0.5f; // distContactThreshold - AABB padding
if (!FmAabbSceneCollisionPlanesPotentialContact(results, box, collisionPlanes, timestep, threshold))
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for contact
uint exteriorFaceId = (uint)lc;
FmGenerateFaceCollisionPlaneContacts(objectPair, results, exteriorFaceId, collisionPlanes);
}
else
{
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)lc);
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)rc);
}
}
uint FmFindSceneCollisionPlanesContactsQuery(
FmCollidedObjectPair* objectPair,
const FmSceneCollisionPlanes& collisionPlanes)
{
uint numContactsStart = objectPair->numDistanceContacts;
FmSceneCollisionPlanesContactsQueryState queryState;
queryState.objectPair = objectPair;
queryState.collisionPlanes = collisionPlanes;
FmFindSceneCollisionPlanesContactsRecursive(queryState, 0);
return objectPair->numDistanceContacts - numContactsStart;
}
void FmCollideRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
float timestep = objectPair->timestep;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
float impactTime;
if (FmAabbCcd(impactTime, *boxA, *boxB, timestep))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
#if FM_SOA_TRI_INTERSECTION
FmMeshCollisionTriPair& pair = objectPair->temps.meshCollisionTriPairs[objectPair->temps.numMeshCollisionTriPairs];
pair.exteriorFaceIdA = (uint)nodeA->left;
pair.exteriorFaceIdB = (uint)nodeB->left;
objectPair->temps.numMeshCollisionTriPairs++;
if (objectPair->temps.numMeshCollisionTriPairs >= FM_MAX_MESH_COLLISION_TRI_PAIR)
{
FmGenerateContactsFromMeshCollisionTriPairs(objectPair);
objectPair->temps.numMeshCollisionTriPairs = 0;
}
#else
FmGenerateContacts(objectPair, nodeA->left, nodeB->left);
#endif
}
else if (nodeAIsLeaf)
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
else if (nodeBIsLeaf)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
}
}
}
static FM_FORCE_INLINE bool FmAabbOverlapXY(const FmAabb& aabb0, const FmAabb& aabb1)
{
return
aabb0.pmin.x <= aabb1.pmax.x &&
aabb0.pmin.y <= aabb1.pmax.y &&
aabb1.pmin.x <= aabb0.pmax.x &&
aabb1.pmin.y <= aabb0.pmax.y;
}
void FmFindInsideVertsRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB, bool includeA, bool includeB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
// If node found to be outside of other mesh bounding box, do not need to test any of its vertices as inside.
// Pass flag down to all children tests to prevent computing intersection values.
includeA = includeA && FmAabbOverlap(boxA->pmin, boxA->pmax, objectPair->objectBMinPosition, objectPair->objectBMaxPosition);
includeB = includeB && FmAabbOverlap(boxB->pmin, boxB->pmax, objectPair->objectAMinPosition, objectPair->objectAMaxPosition);
if ((includeA || includeB) && FmAabbOverlapXY(*boxA, *boxB))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
FmUpdateVertIntersectionVals(objectPair, (uint)nodeA->left, (uint)nodeB->left, includeA, includeB);
}
else if (nodeAIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
else if (nodeBIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
}
}
}
void FmFindInsideVerts(FmCollidedObjectPair* meshPair)
{
FmFindInsideVertsRecursive(meshPair, 0, 0, true, true);
}
void FmCollideHierarchies(FmCollidedObjectPair* meshPair)
{
FmCollideRecursive(meshPair, 0, 0);
#if FM_SOA_TRI_INTERSECTION
FmGenerateContactsFromMeshCollisionTriPairs(meshPair);
meshPair->temps.numMeshCollisionTriPairs = 0;
#endif
}
} | 44.294406 | 197 | 0.624225 | UnifiQ |
af3c85ba4560bd4fbd781a99e2b5af71ae654cf9 | 772 | hpp | C++ | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 5 | 2015-09-08T01:59:26.000Z | 2018-11-26T10:19:29.000Z | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 6 | 2015-11-29T03:00:11.000Z | 2015-11-29T03:11:52.000Z | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | null | null | null | #ifndef CLPP_COMMAND_QUEUE_FLAGS_HPP
#define CLPP_COMMAND_QUEUE_FLAGS_HPP
#include "clpp/detail/common.hpp"
#include "clpp/detail/mask_wrapper.hpp"
namespace cl {
class CommandQueueFlags final :
public detail::MaskWrapper<cl_command_queue_properties>
{
public:
using detail::MaskWrapper<CommandQueueFlags::cl_mask_type>::MaskWrapper;
auto inline isOutOfOrderExecModeEnabled() const -> bool;
auto inline isProfilingEnabled() const -> bool;
auto inline enableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline enableProfiling() -> CommandQueueFlags &;
auto inline disableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline disableProfiling() -> CommandQueueFlags &;
};
}
#endif // CLPP_COMMAND_QUEUE_FLAGS_HPP
| 29.692308 | 74 | 0.759067 | Robbepop |
af4b5024feecf15d017f713595e8a8251eeb9623 | 3,158 | cpp | C++ | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | 1 | 2021-12-11T10:23:05.000Z | 2021-12-11T10:23:05.000Z | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | null | null | null | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | 3 | 2021-12-23T17:19:42.000Z | 2022-01-27T13:53:47.000Z | #include <bits/stdc++.h>
using namespace std;
vector<double> sjfnp(vector<int> &cpu_burst, vector<int> &arrival_times, int mode)
{
int n = cpu_burst.size();
vector<int> wait_time(n, 0), turnaround_time(n, 0), response_time(n), completion_time(n, 0);
vector<vector<int> > table(n, vector<int>(6));
table[0][0] = arrival_times[0];
table[0][1] = cpu_burst[0];
table[0][5] = 0;
for (int i = 1; i < n; i++)
{
table[i][0] = arrival_times[i];
table[i][1] = cpu_burst[i];
table[i][2] = completion_time[i];
table[i][3] = wait_time[i];
table[i][4] = turnaround_time[i];
table[i][5] = i;
}
sort(table.begin(), table.end());
table[0][2] = table[0][1] + table[0][0];
table[0][4] = table[0][2] - table[0][0];
table[0][3] = table[0][4] - table[0][1];
for (int i = 1; i < n; i++)
{
int ct = table[i - 1][2];
int burst = table[i][1];
int row = i;
bool inside = false;
for (int j = i; j < n; j++)
{
if (ct >= table[j][0] && burst >= table[j][1])
{
burst = table[j][1];
row = j;
}
}
if (ct < table[i][0])
ct = table[i][0];
table[row][2] = ct + table[row][1];
table[row][4] = table[row][2] - table[row][0];
table[row][3] = table[row][4] - table[row][1];
for (int k = 0; k < 5; k++)
{
swap(table[row][k], table[i][k]);
}
// completion_time[i]=wait_time[i]+cpu_burst[i]-;
}
if (mode == 0)
{
cout << "----------------------------------------------------------------------" << endl;
cout << "Shortest job first Non premptive" << endl;
vector<pair<int, pair<int, int> > > rq;
for (int j = 0; j < n; j++)
{
rq.push_back(make_pair(table[j][0], make_pair(0, table[j][5])));
rq.push_back(make_pair(table[j][3], make_pair(1, table[j][5])));
}
sort(rq.begin(), rq.end());
for (int j = 0; j < rq.size(); j++)
{
if (rq[j].second.first == 0)
{
cout << "Process " << rq[j].second.second+1 << " entering the ready queue" << endl;
}
else
{
cout << "Process " << rq[j].second.second+1 << " leaving the ready queue" << endl;
}
}
cout << "----------------------------------------------------------------------" << endl;
}
double average_waiting_time = 0, average_turnaround_time = 0, average_response_time = 0;
for (int i = 0; i < n; i++)
{
average_waiting_time += table[i][3];
average_turnaround_time += table[i][4];
// average_response_time+=response_time[i];
}
// cout<<average_turnaround_time<<" "<<average_waiting_time<<endl;
// average_response_time/=n;
average_turnaround_time /= n;
average_waiting_time /= n;
vector<double> final(3);
final[0] = average_waiting_time;
final[1] = average_turnaround_time;
final[2] = average_waiting_time;
return final;
} | 31.58 | 99 | 0.468334 | binodkumar23 |
af507d136ec0c8e4bb719e673a2005234f73e475 | 756 | hpp | C++ | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | 1 | 2021-01-03T17:49:59.000Z | 2021-01-03T17:49:59.000Z | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | 39 | 2020-12-19T18:19:06.000Z | 2021-12-29T01:25:39.000Z | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | null | null | null | #ifndef REPEATERBOOKRESULTSWIDGET_HPP
#define REPEATERBOOKRESULTSWIDGET_HPP
#pragma GCC diagnostic ignored "-Weffc++"
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QtWidgets>
#include <memory>
#pragma GCC diagnostic pop
#include "BSONDocWidget.hpp"
class RepeaterBookResultsWidget : public BSONDocWidget
{
Q_OBJECT
public:
RepeaterBookResultsWidget(const std::vector<Mongo::BSONDoc>& bsonDocs, QWidget* parent = 0);
RepeaterBookResultsWidget(const RepeaterBookResultsWidget&) = delete;
RepeaterBookResultsWidget& operator=(const RepeaterBookResultsWidget&) = delete;
virtual ~RepeaterBookResultsWidget();
void filterPreset(const std::string& columnName, const std::string& regexStr);
};
#endif
| 28 | 94 | 0.80291 | neotericpiguy |
af5783770d5c282eca5c5eb8feffe07c4126afe6 | 8,308 | cpp | C++ | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/s/catalog/catalog_manager.h"
#include <memory>
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/write_ops/batched_command_request.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/s/write_ops/batched_delete_document.h"
#include "mongo/s/write_ops/batched_delete_request.h"
#include "mongo/s/write_ops/batched_insert_request.h"
#include "mongo/s/write_ops/batched_update_document.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
Status getStatus(const BatchedCommandResponse& response) {
if (response.getOk() == 0) {
return Status(static_cast<ErrorCodes::Error>(response.getErrCode()),
response.getErrMessage());
}
if (response.isErrDetailsSet()) {
const WriteErrorDetail* errDetail = response.getErrDetails().front();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
if (response.isWriteConcernErrorSet()) {
const WCErrorDetail* errDetail = response.getWriteConcernError();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
return Status::OK();
}
} // namespace
Status CatalogManager::insert(const string& ns,
const BSONObj& doc,
BatchedCommandResponse* response) {
unique_ptr<BatchedInsertRequest> insert(new BatchedInsertRequest());
insert->addToDocuments(doc);
BatchedCommandRequest request(insert.release());
request.setNS(ns);
request.setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
// Make sure to add ids to the request, since this is an insert operation
unique_ptr<BatchedCommandRequest> requestWithIds(BatchedCommandRequest::cloneWithIds(request));
const BatchedCommandRequest& requestToSend = requestWithIds.get() ? *requestWithIds : request;
writeConfigServerDirect(requestToSend, response);
return getStatus(*response);
}
Status CatalogManager::update(const string& ns,
const BSONObj& query,
const BSONObj& update,
bool upsert,
bool multi,
BatchedCommandResponse* response) {
unique_ptr<BatchedUpdateDocument> updateDoc(new BatchedUpdateDocument());
updateDoc->setQuery(query);
updateDoc->setUpdateExpr(update);
updateDoc->setUpsert(upsert);
updateDoc->setMulti(multi);
unique_ptr<BatchedUpdateRequest> updateRequest(new BatchedUpdateRequest());
updateRequest->addToUpdates(updateDoc.release());
updateRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(updateRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::remove(const string& ns,
const BSONObj& query,
int limit,
BatchedCommandResponse* response) {
unique_ptr<BatchedDeleteDocument> deleteDoc(new BatchedDeleteDocument);
deleteDoc->setQuery(query);
deleteDoc->setLimit(limit);
unique_ptr<BatchedDeleteRequest> deleteRequest(new BatchedDeleteRequest());
deleteRequest->addToDeletes(deleteDoc.release());
deleteRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(deleteRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::updateCollection(const std::string& collNs, const CollectionType& coll) {
fassert(28634, coll.validate());
BatchedCommandResponse response;
Status status = update(CollectionType::ConfigNS,
BSON(CollectionType::fullNs(collNs)),
coll.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "collection metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
Status CatalogManager::updateDatabase(const std::string& dbName, const DatabaseType& db) {
fassert(28616, db.validate());
BatchedCommandResponse response;
Status status = update(DatabaseType::ConfigNS,
BSON(DatabaseType::name(dbName)),
db.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "database metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
// static
StatusWith<ShardId> CatalogManager::selectShardForNewDatabase(ShardRegistry* shardRegistry) {
vector<ShardId> allShardIds;
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
shardRegistry->reload();
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
return Status(ErrorCodes::ShardNotFound, "No shards found");
}
}
auto bestShard = shardRegistry->getShard(allShardIds[0]);
if (!bestShard) {
return {ErrorCodes::ShardNotFound, "Candidate shard disappeared"};
}
ShardStatus bestStatus = bestShard->getStatus();
for (size_t i = 1; i < allShardIds.size(); i++) {
const auto shard = shardRegistry->getShard(allShardIds[i]);
if (!shard) {
continue;
}
const ShardStatus status = shard->getStatus();
if (status < bestStatus) {
bestShard = shard;
bestStatus = status;
}
}
return bestShard->getId();
}
} // namespace mongo
| 35.504274 | 99 | 0.649735 | rzh |
af58dd217a39669eeccb09954b94c546564e8b0a | 955 | cpp | C++ | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 5 | 2020-09-02T06:58:15.000Z | 2021-12-26T02:29:35.000Z | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 10 | 2021-11-23T16:10:38.000Z | 2021-12-30T16:05:52.000Z | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 1 | 2021-07-13T16:55:53.000Z | 2021-07-13T16:55:53.000Z | #include "../include/Privileges.hpp"
#include <algorithm>
void PrivilegeHandler::GivePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter == m_privs.end()) {
// TODO: error check
m_privs.insert(std::make_pair(name, std::vector { priv }));
}
else {
// TODO: Check if already has priv
iter->second.push_back(priv);
}
}
void PrivilegeHandler::TakePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
std::remove_if(iter->second.begin(), iter->second.end(), [&](std::string checkPriv) { return priv == checkPriv; });
}
}
priv_result PrivilegeHandler::HasPrivilege(std::string name, std::string priv) const
{
priv_result result{ "Missing priv: " + priv, -1 };
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
for (auto& obj : iter->second) {
if (obj == priv) {
result.error = 0;
break;
}
}
}
return result;
}
| 22.738095 | 117 | 0.653403 | vexyl |
af5c39f793d2afa67502e2cd8d8dfca3c8bb0987 | 4,149 | cpp | C++ | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | template<class T>
T rsBandwidthConverter::bandedgesToCenterFrequency(T fl, T fu)
{
return sqrt(fl*fu);
}
template<class T>
T rsBandwidthConverter::bandedgesToAbsoluteBandwidth(T fl, T fu)
{
return fu - fl;
}
template<class T>
T rsBandwidthConverter::relativeBandwidthToBandedgeFactor(T br)
{
return 0.5*br + sqrt(0.25*br*br + 1);
}
template<class T>
void rsBandwidthConverter::absoluteBandwidthToBandedges(T bw, T fc, T *fl,
T *fu)
{
T br = bandwidthAbsoluteToRelative(bw, fc);
T k = relativeBandwidthToBandedgeFactor(br);
*fl = fc/k;
*fu = fc*k;
}
template<class T>
T rsBandwidthConverter::bandwidthAbsoluteToRelative(T bw, T fc)
{
return bw / fc;
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToQ(T bw, T fc)
{
return 1.0 / bandwidthAbsoluteToRelative(bw, fc);
}
template<class T>
T rsBandwidthConverter::bandedgesToBandwidthInOctaves(T fl, T fu)
{
return rsLog2(fu/fl);
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToOctaves(T bw, T fc)
{
T fl, fu;
absoluteBandwidthToBandedges(bw, fc, &fl, &fu);
return bandedgesToBandwidthInOctaves(fl, fu);
}
template<class T>
T rsBandwidthConverter::multipassScalerButterworth(int M, int N, T g)
{
return pow(pow(g, -2.0/M)-1, -0.5/N);
// The formula was derived by considering the analog magnitude-squared response of a N-th order
// Butterworth lowpass applied M times, given by: g^2(w) = (1 / (1 + (w^2/w0^2)^N))^M. To find
// the frequency w, where the magnitude-squared response has some particular value p, we solve
// for w. Chosing some particluar value for g (such as g = sqrt(0.5) for the -3.01 dB
// "half-power" point), we can compute the scaler s, at which we see this value of p. Scaling our
// cutoff frequency w0 by 1/s, we shift the half-power point to w0 in the multipass case.
// \todo to apply this to bilinear-transform based digital filters, we should replace w by
// wd = tan(...) and solve....
}
// for energy normalization, use the total energy formula (that i have obtained via sage)
// E = pi*gamma(M - 1/2/N)/(N*gamma(M)*gamma(-1/2/N + 1)*sin(1/2*pi/N)) // 1/2 -> 0.5
// E = pi*gamma(M - 0.5/N)/(N*gamma(M)*gamma(-0.5/N + 1)*sin(0.5*pi/N)) // k = 0.5/N
// k = 0.5/N
// E = pi*gamma(M-k) / (N*gamma(M)*gamma(1-k)*sin(k*pi))
// maybe compare the energy normalization to the formula above
// this formula has been implemented in
// rsPrototypeDesigner<T>::butterworthEnergy
template<class T>
T rsBandwidthConverter::lowpassResoGainToQ(T a)
{
a *= a;
T b = sqrt(a*a - a);
T P = T(0.5) * (a + b); // P := Q^2
return sqrt(P);
// The formula was derived by considering the magnitude response of a 2nd order analog lowpass
// with transfer function H(s) = 1 / (1 + s/Q + s^2). The magnitude-squared response of such a
// filter is given by: M(w) = Q^2 / (Q^2 (w^2 - 1)^2 + w^2). This function has maxima of height
// (4 Q^4)/(4 Q^2 - 1) at w = -1/2 sqrt(4 - 2/Q^2). The expression for the height was solved
// for Q. We get a quadratic equation for P := Q^2. The correct solution of the two was picked
// empirically. It was also observed empirically that the formula also works for highpass
// filters.
}
// ToDo: implement a formula, that computes the exact frequency of the resonance peak, i.e. the
// w at which the derivative of the mag-response is zero. This could be useful, if the filter
// designer wants to set the peak-gain frequency rather than the resonance frequency. These two
// frequencies are different because each pole sits on the skirt of the other. For high Q,
// they are approximately the same but for low Q, the peak-freq will be appreciably below the
// nominal reso-freq in the lowpass case - in fact, for Q <= 1/sqrt(2), the peak will be at DC.
// A filter design algo could first fix the resonance gain, then compute the Q via the function
// above, then compute the peak-freq, then scale the cutoff accordingly, namely by the reciprocal
// of the computed (normalized) peak-freq.
/*
More formulas that need some numeric checks:
fu = fl * 2^bo
fc = fl * sqrt(2^bo) = fl * 2^(bo/2)
k = 2^(bo/2)
Q = 2^(bo/2) / (2^bo - 1)
*/ | 35.767241 | 100 | 0.692697 | RobinSchmidt |
af5defc1c825bc5680eab5e811e314bbc2dc0de5 | 404 | cpp | C++ | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | #include "MyTestBenchMonitor.h"
void MyTestBenchMonitor::Display_Patterns()
{
cout << "At time : " << sc_time_stamp();
//next_trigger(TBMonitor_a. | TBMonitor_b | TBMonitor_c);
cout << "\ta = " << TBMonitor_a << "\tb = " << TBMonitor_b << "\tc_in = " << TBMonitor_c;
//next_trigger(TBMonitor_sum | TBMonitor_sum);
cout << "\tCarry = " << TBMonitor_carry << "\tSum = " << TBMonitor_sum << endl;
}
| 33.666667 | 90 | 0.648515 | VSPhaneendraPaluri |
af5dfb203e9dceb2ef6970ffe47f34b30138073b | 17,261 | cpp | C++ | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | 3 | 2020-02-13T02:08:06.000Z | 2020-10-06T16:26:30.000Z | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.
#include <array>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <crab/crab.hpp>
static size_t count_zeroes(uint64_t val) {
for (size_t i = 0; i != sizeof(val) * 8; ++i)
if ((val & (uint64_t(1) << i)) != 0)
return i;
return sizeof(val) * 8;
}
struct Random {
explicit Random(uint64_t random_seed = 0) : random_seed(random_seed) {}
uint64_t rnd() { // MMIX by Donald Knuth
random_seed = 6364136223846793005 * random_seed + 1442695040888963407;
return random_seed;
}
private:
uint64_t random_seed;
};
static constexpr size_t LEVELS = 10;
template<class T>
class SkipList {
public:
struct Item { // We allocate only part of it
T value;
Item *prev;
size_t height;
Item *s_nexts[LEVELS];
Item *&nexts(size_t i) {
if (i >= height)
throw std::logic_error("out of nexts");
return s_nexts[i];
}
};
struct InsertPtr {
std::array<Item *, LEVELS> previous_levels{};
Item *next() const { return previous_levels.at(0)->nexts(0); }
};
SkipList() {
tail_head.value = T{};
tail_head.prev = &tail_head;
tail_head.height = LEVELS;
for (size_t i = 0; i != LEVELS; ++i)
tail_head.nexts(i) = &tail_head;
}
~SkipList() {
while (tail_head.prev != &tail_head) {
erase_begin();
// print();
}
}
int lower_bound(const T &value, InsertPtr *insert_ptr) {
Item *curr = &tail_head;
size_t current_height = LEVELS - 1;
int hops = 0;
Item **p_levels = insert_ptr->previous_levels.data();
while (true) {
hops += 1;
Item *next_curr = curr->s_nexts[current_height];
if (next_curr == &tail_head || next_curr->value >= value) {
p_levels[current_height] = curr;
if (current_height == 0)
break;
current_height -= 1;
continue;
}
curr = next_curr;
}
return hops;
}
int count(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return 0;
return 1;
}
std::pair<Item *, bool> insert(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *next_curr = insert_ptr.next();
if (next_curr != &tail_head && next_curr->value == value)
return std::make_pair(next_curr, false);
// static uint64_t keybuf[4] = {};
// auto ctx = blake2b_ctx{};
// blake2b_init(&ctx, 32, nullptr, 0);
// blake2b_update(&ctx, &keybuf, sizeof(keybuf));
// blake2b_final(&ctx, &keybuf);
const size_t height = std::min<size_t>(LEVELS, 1 + count_zeroes(random.rnd()) / 3); // keybuf[0]
Item *new_item =
reinterpret_cast<Item *>(malloc(sizeof(Item) - (LEVELS - height) * sizeof(Item *))); // new Item{};
new_item->prev = insert_ptr.previous_levels.at(0);
next_curr->prev = new_item;
new_item->height = height;
size_t i = 0;
for (; i != height; ++i) {
new_item->nexts(i) = insert_ptr.previous_levels.at(i)->nexts(i);
insert_ptr.previous_levels.at(i)->nexts(i) = new_item;
}
// for(; i != LEVELS; ++i)
// new_item->nexts(i) = nullptr;
new_item->value = value;
return std::make_pair(new_item, true);
}
bool erase(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return false;
del_item->nexts(0)->prev = del_item->prev;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i)
if (del_item->nexts(i)) {
insert_ptr.previous_levels.at(i)->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
return true;
}
void erase_begin() {
Item *del_item = tail_head.nexts(0);
if (del_item == &tail_head)
throw std::logic_error("deleting head_tail");
Item *prev_item = del_item->prev;
del_item->nexts(0)->prev = prev_item;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i) {
prev_item->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
}
bool empty() const { return tail_head.prev == &tail_head; }
Item *end(const T &v);
void print() {
Item *curr = &tail_head;
std::array<size_t, LEVELS> level_counts{};
std::cerr << "---- list ----" << std::endl;
while (true) {
if (curr == &tail_head)
std::cerr << std::setw(4) << "end"
<< " | ";
else
std::cerr << std::setw(4) << curr->value << " | ";
for (size_t i = 0; i != curr->height; ++i) {
level_counts[i] += 1;
if (curr == &tail_head || curr->nexts(i) == &tail_head)
std::cerr << std::setw(4) << "end"
<< " ";
else
std::cerr << std::setw(4) << curr->nexts(i)->value << " ";
}
for (size_t i = curr->height; i != LEVELS; ++i)
std::cerr << std::setw(4) << "_"
<< " ";
if (curr->prev == &tail_head)
std::cerr << "| " << std::setw(4) << "end" << std::endl;
else
std::cerr << "| " << std::setw(4) << curr->prev->value << std::endl;
if (curr == tail_head.prev)
break;
curr = curr->nexts(0);
}
std::cerr << " #"
<< " | ";
for (size_t i = 0; i != LEVELS; ++i) {
std::cerr << std::setw(4) << level_counts[i] << " ";
}
std::cerr << "| " << std::endl;
}
private:
Item tail_head;
Random random;
};
struct HeapElement {
crab::IntrusiveHeapIndex heap_index;
uint64_t value = 0;
bool operator<(const HeapElement &other) const { return value < other.value; }
};
// typical benchmark
// skiplist insert of 1000000 hashes, inserted 632459, seconds=1.486
// skiplist get of 1000000 hashes, hops 37.8428, seconds=1.428
// skiplist delete of 1000000 hashes, found 400314, seconds=1.565
// std::set insert of 1000000 hashes, inserted 632459, seconds=0.782
// std::set get of 1000000 hashes, found_counter 1000000, seconds=0.703
// std::set delete of 1000000 hashes, found 400314, seconds=0.906
std::vector<uint64_t> fill_random(uint64_t seed, size_t count) {
Random random(seed);
std::vector<uint64_t> result;
for (size_t i = 0; i != count; ++i)
result.push_back(random.rnd() % count);
return result;
}
void benchmark_timers() {
constexpr size_t COUNT = 1000000;
constexpr size_t COUNT_MOVE = 100;
crab::RunLoop runloop;
Random random(12345);
std::vector<std::chrono::steady_clock::duration> durs;
std::list<crab::Timer> timers;
for (size_t i = 0; i != COUNT; ++i) {
timers.emplace_back(crab::empty_handler);
std::chrono::duration<double> delay(random.rnd() % COUNT);
durs.push_back(std::chrono::duration_cast<std::chrono::steady_clock::duration>(delay));
}
auto idea_start = std::chrono::high_resolution_clock::now();
std::list<crab::Timer>::iterator it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i]);
}
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Set Timers (random delay)"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
idea_start = std::chrono::high_resolution_clock::now();
for (size_t j = 0; j != COUNT_MOVE; ++j) {
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i] + std::chrono::steady_clock::duration{1 + j});
}
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Moving Timers to the future"
<< " count=" << COUNT_MOVE << "*" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000
<< std::endl;
idea_start = std::chrono::high_resolution_clock::now();
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->cancel();
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Cancel Timers"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
template<class T, class Op>
void benchmark_op(const char *str, const std::vector<T> &samples, Op op) {
size_t found_counter = 0;
auto idea_start = std::chrono::high_resolution_clock::now();
for (const auto &sample : samples)
found_counter += op(sample);
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << str << " count=" << samples.size() << " hits=" << found_counter
<< ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
void benchmark_sets() {
size_t count = 1000000;
std::vector<uint64_t> to_insert = fill_random(1, count);
std::vector<uint64_t> to_count = fill_random(2, count);
std::vector<uint64_t> to_erase = fill_random(3, count);
std::vector<HeapElement *> el_to_insert;
std::vector<HeapElement *> el_to_count;
std::vector<HeapElement *> el_to_erase;
std::map<uint64_t, HeapElement> heap_storage;
for (auto s : to_insert)
el_to_insert.push_back(&heap_storage[s]);
for (auto s : to_count)
el_to_count.push_back(&heap_storage[s]);
for (auto s : to_erase)
el_to_erase.push_back(&heap_storage[s]);
crab::IntrusiveHeap<HeapElement, &HeapElement::heap_index, std::less<HeapElement>> int_heap;
int_heap.reserve(1000000);
benchmark_op(
"OurHeap insert ", el_to_insert, [&](HeapElement *sample) -> size_t { return int_heap.insert(*sample); });
benchmark_op(
"OurHeap erase ", el_to_erase, [&](HeapElement *sample) -> size_t { return int_heap.erase(*sample); });
benchmark_op("OurHeap pop_front ", el_to_insert, [&](HeapElement *sample) -> size_t {
if (int_heap.empty())
return 0;
int_heap.pop_front();
return 1;
});
std::set<uint64_t> test_set;
benchmark_op(
"std::set insert ", to_insert, [&](uint64_t sample) -> size_t { return test_set.insert(sample).second; });
benchmark_op("std::set count ", to_count, [&](uint64_t sample) -> size_t { return test_set.count(sample); });
benchmark_op("std::set erase ", to_erase, [&](uint64_t sample) -> size_t { return test_set.erase(sample); });
benchmark_op("std::set pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_set.empty()) {
test_set.erase(test_set.begin());
return 1;
}
return 0;
});
std::unordered_set<uint64_t> test_uset;
benchmark_op(
"std::uset insert ", to_insert, [&](uint64_t sample) -> size_t { return test_uset.insert(sample).second; });
benchmark_op("std::uset count ", to_count, [&](uint64_t sample) -> size_t { return test_uset.count(sample); });
benchmark_op("std::uset erase ", to_erase, [&](uint64_t sample) -> size_t { return test_uset.erase(sample); });
benchmark_op("std::uset pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_uset.empty()) {
test_uset.erase(test_uset.begin());
return 1;
}
return 0;
});
SkipList<uint64_t> skip_list;
benchmark_op(
"skip_list insert ", to_insert, [&](uint64_t sample) -> size_t { return skip_list.insert(sample).second; });
benchmark_op("skip_list count ", to_count, [&](uint64_t sample) -> size_t { return skip_list.count(sample); });
benchmark_op("skip_list erase ", to_erase, [&](uint64_t sample) -> size_t { return skip_list.erase(sample); });
// immer::set<uint64_t> immer_set;
// benchmark_op("immer insert ", to_insert, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.insert(sample);
// return immer_set.size() - was_size;
// });
// benchmark_op("immer count ", to_count, [&](uint64_t sample)->size_t{ return immer_set.count(sample); });
// benchmark_op("immer erase ", to_count, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.erase(sample);
// return was_size - immer_set.size();
// });
// const auto v0 = immer::vector<int>{};
// const auto v1 = v0.push_back(13);
// assert(v0.size() == 0 && v1.size() == 1 && v1[0] == 13);
//
// const auto v2 = v1.set(0, 42);
// assert(v1[0] == 13 && v2[0] == 42);
}
template<typename T>
struct BucketsGetter {
static size_t bucket_count(const T &) { return 0; }
};
template<>
struct BucketsGetter<std::unordered_map<std::string, size_t>> {
static size_t bucket_count(const std::unordered_map<std::string, size_t> &v) { return v.bucket_count(); }
};
constexpr size_t COUNT = 1000000;
template<typename K, typename T, size_t max_key>
class ArrayAdapter { // Array large enough to index by K
public:
void emplace(K k, T t) {
std::pair<T, bool> &pa = storage.at(k);
if (pa.second)
return;
storage_size += 1;
pa = std::make_pair(t, true);
}
size_t size() const { return 1000; }
size_t count(K k) const { return storage.at(k).second ? 1 : 0; }
private:
size_t storage_size = 0;
std::array<std::pair<T, bool>, max_key + 1> storage;
};
template<typename T, typename S>
void benchmark(std::function<T(size_t)> items_gen) {
S storage;
std::mt19937 rnd;
std::vector<T> to_insert;
std::vector<T> to_search;
for (size_t i = 0; i != COUNT; ++i) {
to_insert.push_back(items_gen(rnd() % COUNT));
to_search.push_back(items_gen(rnd() % COUNT));
}
auto tp = std::chrono::high_resolution_clock::now();
auto start = tp;
size_t counter = 0;
struct Sample {
int mksec;
size_t counter;
size_t buckets;
};
std::vector<Sample> long_samples;
long_samples.reserve(to_insert.size());
for (const auto &key : to_insert) {
storage.emplace(key, ++counter);
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - tp).count();
if (mksec > 100) {
auto bc = BucketsGetter<S>::bucket_count(storage);
long_samples.emplace_back(Sample{int(mksec), counter, bc});
}
tp = now;
}
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "inserted " << storage.size() << ", mksec=" << mksec << std::endl;
for (const auto &p : long_samples)
std::cout << "mksec=" << p.mksec << " counter=" << p.counter << " buckets=" << p.buckets << std::endl;
start = now;
counter = 0;
for (const auto &key : to_search)
counter += storage.count(key);
now = std::chrono::high_resolution_clock::now();
mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "searched " << to_search.size() << ", found=" << counter << ", mksec=" << mksec << std::endl;
}
std::string string_gen(size_t c) {
return std::to_string(c % COUNT) + std::string("SampleSampleSampleSampleSampleSample");
}
int int_gen(size_t c) { return int(c); }
int small_int_gen(size_t c) { return int(c % 256); }
struct OrderId {
uint64_t arr[4] = {};
bool operator==(const OrderId &b) const {
return arr[0] == b.arr[0] && arr[1] == b.arr[1] && arr[2] == b.arr[2] && arr[3] == b.arr[3];
}
bool operator!=(const OrderId &b) const { return !operator==(b); }
};
OrderId order_id_gen(size_t c) {
OrderId id;
id.arr[0] = 12345678;
id.arr[1] = 87654321;
id.arr[2] = c % COUNT;
id.arr[3] = 88888888;
return id;
}
template<typename T>
inline void hash_combine(std::size_t &seed, T const &v) {
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
// seed ^= std::hash<T>()(v) + 0x9e3779b9 * seed;
}
namespace std {
template<>
struct hash<OrderId> {
std::size_t operator()(const OrderId &w) const {
size_t hash = 0;
hash_combine(hash, w.arr[0]);
hash_combine(hash, w.arr[1]);
hash_combine(hash, w.arr[2]);
hash_combine(hash, w.arr[3]);
return hash;
}
};
} // namespace std
int main() {
benchmark_timers();
benchmark_sets();
std::cout << "Testing small std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(small_int_gen);
std::cout << "Testing small std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(small_int_gen);
std::cout << "Testing small ArrayAdapter count=" << COUNT << std::endl;
benchmark<int, ArrayAdapter<int, size_t, 2000>>(small_int_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::unordered_map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<OrderId> count=" << COUNT << std::endl;
benchmark<OrderId, std::unordered_map<OrderId, size_t>>(order_id_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(int_gen);
std::cout << "Testing std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(int_gen);
std::cout << "----" << std::endl;
return 0;
}
| 33.911591 | 115 | 0.639071 | hrissan |
af60f971a6f1c6055b70c3a18f62b8330d3fd656 | 439 | cpp | C++ | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 16 | 2019-03-14T19:45:02.000Z | 2022-02-06T19:18:08.000Z | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 1 | 2020-05-08T08:40:02.000Z | 2020-05-08T13:27:59.000Z | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 2 | 2021-01-16T20:42:05.000Z | 2021-12-01T23:37:18.000Z | // memccpy.cpp
// Copyright (c) 2014 - 2016, zhiayang
// Licensed under the Apache License Version 2.0.
#include <stddef.h>
extern "C" void* memccpy(void* dest_ptr, const void* src_ptr, int c, size_t n)
{
unsigned char* dest = (unsigned char*) dest_ptr;
const unsigned char* src = (const unsigned char*) src_ptr;
for(size_t i = 0; i < n; i++)
{
if((dest[i] = src[i]) == (unsigned char) c)
return dest + i + 1;
}
return NULL;
}
| 25.823529 | 78 | 0.649203 | zhiayang |
af661942888ffecea18cb24d30e3d05615c1592e | 3,693 | cpp | C++ | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPathBuilder.h"
#include "include/core/SkPoint.h"
#include "include/core/SkTypes.h"
// This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.).
// See also the bottom of dashing4 and skia:6886.
static const int K = 49;
DEF_SIMPLE_GM(daa, canvas, K + 350, 5 * K) {
SkPaint paint;
paint.setAntiAlias(true);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Should be a green square with no red showing through.", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPoint tri1[] = {{0, 0}, {K, K}, {0, K}, {0, 0}};
SkPoint tri2[] = {{0, 0}, {K, K}, {K, 0}, {0, 0}};
SkPath path = SkPathBuilder()
.addPolygon(tri1, SK_ARRAY_COUNT(tri1), false)
.addPolygon(tri2, SK_ARRAY_COUNT(tri2), false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, two draws. Blue then green, no red?", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPath::Polygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false);
paint.setColor(SK_ColorBLUE);
canvas->drawPath(path, paint);
}
{
SkPath path = SkPath::Polygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound together. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K, 0}, {K, K}, {K * 0.5f, K}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"One poly, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPath path = SkPath::Polygon(
{{K * 0.5f, 0},
{0, 0},
{0, K},
{K * 0.5f, K},
{K * 0.5f, 0},
{K, 0},
{K, K},
{K * 0.5f, K}},
false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
| 27.766917 | 94 | 0.541565 | NearTox |
af6c3a5fa03dab6a87d9a3abe48f4804956e52cf | 1,287 | hpp | C++ | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | /*********************************************************************
* Filename: sha256.h
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Defines the API for the corresponding SHA1 implementation.
*********************************************************************/
#ifndef SSYBC_LIBRARY_SHA256_SHA256_HPP_
#define SSYBC_LIBRARY_SHA256_SHA256_HPP_
/*************************** HEADER FILES ***************************/
#include <stddef.h>
/****************************** MACROS ******************************/
#define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest
/**************************** DATA TYPES ****************************/
typedef unsigned char BYTE; // 8-bit byte
typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
typedef struct {
BYTE data[64];
WORD datalen;
unsigned long long bitlen;
WORD state[8];
} SHA256_CTX;
/*********************** FUNCTION DECLARATIONS **********************/
void sha256_init(SHA256_CTX *ctx);
void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);
void sha256_final(SHA256_CTX *ctx, BYTE hash[]);
#endif // SSYBC_LIBRARY_SHA256_SHA256_HPP_
| 36.771429 | 92 | 0.523699 | shuyangsun |
af6de3fd4345760aea98549bb776b82adb22984a | 603 | cpp | C++ | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | /*
RemoteVehicle - library for controlling a remote vehicle using a ESP32CAM board.
Created by Luan Negroni Sibinel, August 24, 2021.
Released under the MIT license.
*/
#include "VehicleIR.h"
VehicleIR::VehicleIR(int8_t panalog, int8_t pdigital) {
_panalog = panalog;
_pdigital = pdigital;
if (_pdigital != -1)
pinMode(_pdigital, INPUT);
if (_panalog != -1)
pinMode(_panalog, INPUT);
}
int VehicleIR::digital() {
return _pdigital == -1 ? -1 : digitalRead(_pdigital);
}
int VehicleIR::analog() {
return _panalog == -1 ? -1 : analogRead(_panalog);
}
| 25.125 | 84 | 0.660033 | tcklpl |
af6e73cb9cc01c2facf801835c69d271e7115792 | 7,182 | cpp | C++ | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "Wme.h"
#include "UiObjectOld.h"
#include "UiObjectFactory.h"
#include "ContentManager.h"
#include "ElementCollection.h"
#include "Sprite.h"
#include "XmlUtil.h"
namespace Wme
{
//////////////////////////////////////////////////////////////////////////
UiObjectOld::UiObjectOld(GuiStage* parentStage)
{
m_ParentStage = parentStage;
m_Parent = NULL;
m_ZOrder = 0;
m_PixelPerfect = false;
m_Disabled = false;
m_Visible = true;
m_PosX = m_PosY = 0;
m_Width = m_Height = 0;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld::~UiObjectOld()
{
foreach (UiObjectOld* child, m_Children)
{
SAFE_DELETE(child);
}
m_Children.clear();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Create()
{
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Display(ElementCollection* elementCol, const SpriteDrawingParams& params)
{
foreach (UiObjectOld* child, m_Children)
{
child->Display(elementCol, params);
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Update()
{
foreach (UiObjectOld* child, m_Children)
{
child->Update();
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::AddChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) return;
m_Children.push_back(child);
child->SetParent(this);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::RemoveChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end())
{
(*it)->SetParent(NULL);
m_Children.erase(it);
}
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildAfter(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end())
{
it++;
m_Children.insert(it, child);
}
else m_Children.push_back(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildBefore(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end()) m_Children.insert(it, child);
else m_Children.push_front(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(size_t index)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetZOrder() == index) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(const WideString& name)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetName() == name) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::UpdateChildrenZOrder()
{
size_t order = 0;
foreach (UiObjectOld* child, m_Children)
{
child->SetZOrder(order);
order++;
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::GetOffset(int& offsetX, int& offsetY) const
{
if (m_Parent) m_Parent->GetOffset(offsetX, offsetY);
offsetX += m_PosX;
offsetY += m_PosY;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteX() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posX;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteY() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posY;
}
//////////////////////////////////////////////////////////////////////////
// DocumentAwareObject
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::LoadFromXml(TiXmlElement* rootNode)
{
ScriptableObject::LoadFromXml(rootNode);
for (TiXmlElement* elem = rootNode->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())
{
if (elem->ValueStr() == "Position")
{
m_PosX = XmlUtil::AttrToInt(elem, "X", 0);
m_PosY = XmlUtil::AttrToInt(elem, "Y", 0);
}
else if (elem->ValueStr() == "Size")
{
m_Width = XmlUtil::AttrToInt(elem, "Width", 0);
m_Height = XmlUtil::AttrToInt(elem, "Height", 0);
}
else if (elem->ValueStr() == "PixelPerfect")
{
m_PixelPerfect = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Disabled")
{
m_Disabled = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Visible")
{
m_Visible = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Text")
{
m_Text = XmlUtil::TextToString(elem);
}
// load children
else if (elem->ValueStr() == "Children")
{
for (TiXmlElement* childNode = elem->FirstChildElement(); childNode != NULL; childNode = childNode->NextSiblingElement())
{
UiObjectOld* child = UiObjectFactory::GetInstance()->CreateInstance(m_ParentStage, childNode->ValueStr());
if (!child) continue;
child->Create();
child->LoadFromXml(childNode);
AddChild(child);
}
}
}
UpdateChildrenZOrder();
return true;
}
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::SaveToXml(TiXmlElement* rootNode)
{
ScriptableObject::SaveToXml(rootNode);
TiXmlElement* elem;
elem = XmlUtil::AddElem("Position", rootNode);
XmlUtil::SetAttr(elem, "X", m_PosX);
XmlUtil::SetAttr(elem, "Y", m_PosY);
elem = XmlUtil::AddElem("Size", rootNode);
XmlUtil::SetAttr(elem, "Width", m_Width);
XmlUtil::SetAttr(elem, "Height", m_Height);
elem = XmlUtil::AddElem("PixelPerfect", rootNode);
XmlUtil::SetText(elem, m_PixelPerfect);
elem = XmlUtil::AddElem("Disabled", rootNode);
XmlUtil::SetText(elem, m_Disabled);
elem = XmlUtil::AddElem("Visible", rootNode);
XmlUtil::SetText(elem, m_Visible);
elem = XmlUtil::AddElem("Text", rootNode);
XmlUtil::SetText(elem, m_Text, true);
// save children
elem = XmlUtil::AddElem("Children", rootNode);
foreach (UiObjectOld* child, m_Children)
{
TiXmlElement* childNode = XmlUtil::AddElem(child->GetDocRootName(), elem);
child->SaveToXml(childNode);
}
return true;
}
} // namespace Wme
| 25.468085 | 125 | 0.536062 | retrowork |
af774e896c3c26f1dd8eac933d891f0007b6d59f | 3,048 | cpp | C++ | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | /**
* This file is part of gltoolbox
*
* MIT License
*
* Copyright (c) 2021 Georges Nader
*
* 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 <gltoolbox/buffer.h>
using namespace gltoolbox;
Buffer::Buffer(GLenum target, GLsizei elementsize, GLenum usage)
: mId(0), mOwned(false), mUsage(usage), mTarget(target), mElementSize(elementsize)
{
create();
}
Buffer::Buffer(Buffer &&temp)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = temp.mId;
mOwned = temp.mOwned;
mUsage = temp.mUsage;
mTarget = temp.mTarget;
mElementSize = temp.mElementSize;
temp.mId = 0;
temp.mOwned = false;
}
Buffer::~Buffer()
{
destroy();
}
Buffer &Buffer::operator=(Buffer &other)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = other.mId;
mOwned = other.mOwned;
mUsage = other.mUsage;
mTarget = other.mTarget;
mElementSize = other.mElementSize;
other.mId = 0;
other.mOwned = false;
return *this;
}
void Buffer::upload(void *ptr, GLsizei count) const
{
bind();
glBufferData(target(), count * element_size(), ptr, usage());
}
void Buffer::upload(void *ptr, GLsizei offset, GLsizei count) const
{
bind();
glBufferSubData(target(), offset * element_size(), count * element_size(), ptr);
}
void Buffer::download(void *ptr, GLsizei size) const
{
bind();
glGetBufferSubData(target(), 0, size, ptr);
}
void Buffer::download(void *ptr, GLsizei offset, GLsizei size) const
{
bind();
glGetBufferSubData(target(), offset, size, ptr);
}
void Buffer::create()
{
if (!mOwned || !is_valid())
{
glCreateBuffers(1, &mId);
bind(); // this will actually trigger the buffer creation
mOwned = true;
}
}
void Buffer::destroy()
{
if (mOwned && is_valid())
{
glDeleteBuffers(1, &mId);
mId = 0;
mOwned = false;
}
}
GLint Buffer::get_parameter(const GLenum param) const
{
GLint result;
bind();
glGetBufferParameteriv(target(), param, &result);
return result;
} | 23.8125 | 86 | 0.69521 | gnader |
af7b6ea6d128439d18c9fff9b840644ddb98f9d1 | 2,779 | cpp | C++ | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | // program to quick short the linked list
// first of all create the linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node **head,int data1)
{
struct node* newnode=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data1;
newnode->next=*head;
*head=newnode;
}
void printlinkedlist(struct node* head)
{
while(head!=NULL)
{
printf("%d",head->data);
head=head->next;
}
}
struct node* gettail(struct node* head)
{
struct node* current =head;
while(current!=NULL&¤t->next!=NULL)
{
current=current->next;
}
return current;
}
struct node* partitionof(struct node*head1,struct node*end1,struct node**newhead,struct node**newend)
{
struct node*previous=NULL;
struct node*pivot=end1;
struct node*current = head1;
struct node*tail=pivot;
while(current!=pivot)
{
printf("ss");
if(current->data < pivot->data)
{
if((*newhead)==NULL)
{
(*newhead)=current;
}
previous=current;
current=current->next;
}
else
{
if(previous!=NULL)
{
previous->next=current->next;
}
struct node* temp=current->next;
current->next=NULL;
tail->next=current;
// tail=tail->next;
tail=current;
current=temp;
}
if((*newhead)==NULL)
{
(*newhead)=pivot;
}
(*newend)=tail;
printlinkedlist(pivot);
printf("\n");
return pivot;
}
}
struct node*quicksortrecursive(struct node*head,struct node*end1)
{
if(head==NULL||head==end1)
{
return head;
}
struct node*newend=NULL;
struct node*newhead=NULL;
struct node*pivot=partitionof(head,end1,&newhead,&newend);
if(newhead!=pivot)
{
struct node*temp=newhead;
while(temp->next!=pivot)
{
temp=temp->next;
}
temp->next=NULL;
newhead=quicksortrecursive(newhead,temp);
temp=gettail(newhead);
temp->next=pivot;
}
pivot->next=quicksortrecursive(pivot->next,newend);
return newhead;
}
void quicksort(struct node**head)
{
(*head)=quicksortrecursive((*head),gettail(*head));
return;
}
int main()
{
struct node*head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
printlinkedlist(head);
printf("\n");
// struct node* nodee=head->next->next->next;
// struct node* one=NULL;
// struct node* two=NULL;
quicksort(&head);
// printf("SS");
printlinkedlist(head);
printf("\n");
}
| 21.21374 | 101 | 0.558834 | luckylove |
5038382f91b12e996e0a51390909ea21e6dce422 | 4,239 | cpp | C++ | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | #include "raytracing/primitive/Box.h"
#include "raytracing/maths/Ray.h"
#include "raytracing/maths/Normal.h"
#include "raytracing/utilities/ShadeRec.h"
#include "raytracing/utilities/Constants.h"
namespace rt
{
Box::Box(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
bool Box::Hit(const Ray& ray, double& tmin, ShadeRec& sr) const
{
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON) {
tmin = t0; // ray hits outside surface
sr.normal = GetNormal(face_in);
}
else {
tmin = t1; // ray hits inside surface
sr.normal = GetNormal(face_out);
}
sr.local_hit_point = ray.ori + tmin * ray.dir;
return true;
} else {
return false;
}
}
bool Box::ShadowHit(const Ray& ray, float& tmin) const
{
if (!m_shadows) {
return false;
}
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON)
tmin = static_cast<float>(t0); // ray hits outside surface
else
tmin = static_cast<float>(t1); // ray hits inside surface
return true;
} else {
return false;
}
}
AABB Box::GetBoundingBox() const
{
AABB aabb;
aabb.x0 = x0;
aabb.y0 = y0;
aabb.z0 = z0;
aabb.x1 = x1;
aabb.y1 = y1;
aabb.z1 = z1;
return aabb;
}
void Box::SetSize(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
Normal Box::GetNormal(const int face_hit) const
{
switch (face_hit)
{
case 0: return (Normal(-1, 0, 0)); // -x face
case 1: return (Normal(0, -1, 0)); // -y face
case 2: return (Normal(0, 0, -1)); // -z face
case 3: return (Normal(1, 0, 0)); // +x face
case 4: return (Normal(0, 1, 0)); // +y face
case 5: return (Normal(0, 0, 1)); // +z face
default: return Normal(-999, -999, -999);
}
}
} | 18.592105 | 69 | 0.538099 | xzrunner |
5039bf2a4c5eb2fd363d549f3197c97c53c2b558 | 1,142 | cpp | C++ | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | #include "viewastrattapubblicazionestampata.h"
viewAstrattaPubblicazioneStampata::viewAstrattaPubblicazioneStampata(astrattaPubblicazione *p , QWidget* parent): viewAstrattaPubblicazione(p,parent){}
void viewAstrattaPubblicazioneStampata::caricaCampiDati() {
viewAstrattaPubblicazione::caricaCampiDati();
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
casaEditrice = new QLineEdit(QString::fromStdString(tmp->getCasaEditrice()),this);
viewLayout->addRow("Casa editrice: ", casaEditrice);
casaEditrice->setCursorPosition(0);
connect(casaEditrice,SIGNAL(textEdited(QString)),this,SLOT(valueChanged()));
}
void viewAstrattaPubblicazioneStampata::setEditablility(bool editable) {
viewAstrattaPubblicazione::setEditablility(editable);
casaEditrice->setReadOnly(!editable);
}
bool viewAstrattaPubblicazioneStampata::checkAndSet() {
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
if(viewAstrattaPubblicazione::checkAndSet()) {
tmp->setCasaEditrice(casaEditrice->text().toStdString());
return true;
}
else
return false;
}
| 40.785714 | 151 | 0.801226 | mtodescato |
503c2a584d5c9e29ceb89ad561296769117282b3 | 900 | cpp | C++ | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | 1 | 2020-12-03T15:26:20.000Z | 2020-12-03T15:26:20.000Z | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | // Chapter 4: Program 3
/***
Write a C++ program to read diameter of a circle. Find perimeter and area
of the circle.
**/
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main(void)
{
const double PI = 3.141592;
double Diameter, Radius, Perimeter, Area;
cout << "\n\t This program finds the perimeter and area of a circle";
cout << "\n\t To get started, please enter the diameter of the circle \n";
cin >> Diameter;
// Calculate perimeter and area using diameter and radius
Perimeter = Diameter * PI;
Radius = Diameter / 2;
Area = pow(Diameter, 2) * PI;
// Display correct values
cout << "Using a diameter of " << Diameter << endl;
cout << "The Perimeter is = " << Perimeter << endl;
cout << "The Area is = " << Area << endl;
system("pause");
return 0;
}
// Code written by: Othneil Drew
| 25 | 78 | 0.625556 | othneildrew |
50408d093de66e680842e2a1f4f0f26a9a96ebbf | 1,569 | cpp | C++ | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | 2 | 2021-09-10T00:19:49.000Z | 2021-11-16T11:27:20.000Z | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | null | null | null | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow 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 <pybind11/pybind11.h>
#include "oneflow/core/common/container_util.h"
#include "oneflow/api/python/of_api_registry.h"
#include "oneflow/core/framework/py_distribute.h"
namespace py = pybind11;
namespace oneflow {
namespace compatible_py {
ONEFLOW_API_PYBIND11_MODULE("distribute", m) {
py::class_<Distribute, std::shared_ptr<Distribute>>(m, "Distribute");
py::class_<AutoDistribute, Distribute, std::shared_ptr<AutoDistribute>>(m, "AutoDistribute");
py::class_<BroadcastDistribute, Distribute, std::shared_ptr<BroadcastDistribute>>(
m, "BroadcastDistribute");
py::class_<SplitDistribute, Distribute, std::shared_ptr<SplitDistribute>>(m, "SplitDistribute")
.def_property_readonly("axis", &SplitDistribute::axis);
m.def("auto", &GlobalAutoDistribute);
m.def("broadcast", &GlobalBroadcastDistribute);
m.def("split", [](int axis) { return GlobalSplitDistribute(axis).GetPtrOrThrow(); });
}
} // namespace compatible_py
} // namespace oneflow
| 37.357143 | 97 | 0.765456 | jackalcooper |
50534627e9e01b4312b826745b1493b5659a67cb | 471 | hpp | C++ | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | 1 | 2022-02-10T04:41:57.000Z | 2022-02-10T04:41:57.000Z | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | null | null | null | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | null | null | null | #ifndef DRK_UTIL_IMGUI_HPP
#define DRK_UTIL_IMGUI_HPP
#include "Core/Base.hpp"
#include <imgui/imgui.h>
#include <string_view>
namespace DrkCraft::DrkImGui
{
void BeginFullscreen(std::string_view name, ImGuiWindowFlags flags=0);
void BeginCentered(std::string_view name, const ImVec2& size, ImGuiWindowFlags flags=0);
void TextCentered(std::string_view text);
bool ButtonCentered(const char* text, const ImVec2& size);
}
#endif // DRK_UTIL_IMGUI_HPP
| 24.789474 | 92 | 0.766454 | D3r3k23 |
5053ea1a70f91478eda466acf7088a52a44b6e56 | 1,030 | hpp | C++ | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <typeinfo>
namespace def::detail
{
struct memory_chunk_header;
/// Base for helper for deferred-enabled type.
class type_helper
{
public:
explicit type_helper(const std::type_info& info,
std::size_t bytes_object,
std::size_t bytes_allocator)
: type_info{info}
, bytes_per_object{bytes_object}
, bytes_per_allocator{bytes_allocator}
{ }
/// Traverse through deferred pointers known to
/// deferred-enabled type and recursively mark them as visited.
virtual void mark_recursive(memory_chunk_header&) const = 0;
/// Run destructor(s).
void destroy(memory_chunk_header&) const;
/// Free memory.
virtual void deallocate(memory_chunk_header*) const = 0;
private:
virtual void destroy_impl(memory_chunk_header&) const = 0;
public:
const std::type_info& type_info;
const std::size_t bytes_per_object;
const std::size_t bytes_per_allocator;
}; // class type_helper
} // namespace def::detail
| 23.953488 | 67 | 0.691262 | JohnJocoo |
5055bedb072381a75762b2d8ba9b253cba5b000f | 4,331 | cpp | C++ | src/test/value_parser_path_test.cpp | RichardCory/svgpp | 801e0142c61c88cf2898da157fb96dc04af1b8b0 | [
"BSL-1.0"
] | 428 | 2015-01-05T17:13:54.000Z | 2022-03-31T08:25:47.000Z | src/test/value_parser_path_test.cpp | andrew2015/svgpp | 1d2f15ab5e1ae89e74604da08f65723f06c28b3b | [
"BSL-1.0"
] | 61 | 2015-01-08T14:32:27.000Z | 2021-12-06T16:55:11.000Z | src/test/value_parser_path_test.cpp | andrew2015/svgpp | 1d2f15ab5e1ae89e74604da08f65723f06c28b3b | [
"BSL-1.0"
] | 90 | 2015-05-19T04:56:46.000Z | 2022-03-26T16:42:50.000Z | #include <svgpp/parser/path_data.hpp>
// Only compilation is checked
using namespace svgpp;
namespace
{
struct PathContext1
{
public:
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
struct PathContext2
{
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_move_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::relative)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::relative)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::relative)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
}
void check_path()
{
std::string testStr;
{
PathContext1 ctx;
value_parser<tag::type::path_data>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
{
PathContext2 ctx;
value_parser<
tag::type::path_data,
path_policy<policy::path::raw>
>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
} | 28.682119 | 87 | 0.471946 | RichardCory |
506c250b70618bfcc89ad1ff716504527bdbcba2 | 315 | cpp | C++ | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | #include "json_null.h"
JsonNull::JsonNull() : JsonValue(JsonType::kNull) {
}
bool JsonNull::IsNull() const noexcept {
return true;
}
bool JsonNull::operator==(const JsonValue &value) const noexcept {
return type_ == value.Type();
}
std::nullptr_t JsonNull::Value() const noexcept {
return nullptr;
}
| 19.6875 | 66 | 0.695238 | syohex |
507098b06484c39551ae4b05fd71ecee34241a0a | 1,078 | cpp | C++ | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 55 | 2015-03-22T16:19:03.000Z | 2022-03-18T18:11:39.000Z | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 2 | 2015-04-09T07:42:08.000Z | 2015-07-26T02:56:06.000Z | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 11 | 2015-04-29T04:52:19.000Z | 2019-12-31T09:36:53.000Z | /*
* error.cpp:
*
* Copyright (C) 2015-2017 Light Lin <blog.poxiao.me> All Rights Reserved.
*
*/
#include "error.hpp"
namespace dawn_player {
open_error::open_error(const std::string& what_arg, open_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* open_error::what() const
{
return this->what_msg.c_str();
}
open_error_code open_error::code() const
{
return this->error_code;
}
get_sample_error::get_sample_error(const std::string& what_arg, get_sample_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* get_sample_error::what() const {
return this->what_msg.c_str();
}
get_sample_error_code get_sample_error::code() const {
return this->error_code;
}
seek_error::seek_error(const std::string& what_arg, seek_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* seek_error::what() const
{
return this->what_msg.c_str();
}
seek_error_code seek_error::code() const
{
return this->error_code;
}
} // namespace dawn_player
| 20.339623 | 90 | 0.67718 | lxrite |
5072d895de952d882d7d0940f0497c0c83e79859 | 17,031 | cc | C++ | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | 8 | 2018-10-29T14:56:05.000Z | 2022-02-10T09:42:21.000Z | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | null | null | null | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | 4 | 2018-10-16T20:12:56.000Z | 2020-10-19T07:37:05.000Z | #include "matrices.h"
#ifdef Z_36
unsigned int wimax_864_0_66B_D = 35;
unsigned int wimax_864_0_66B_X = 6;
int16_t wimax_864_0_66B[288][11] = {
{0, 79, 161, 234, 301, 390, 449, 509, 611, 612, -1},
{1, 80, 162, 235, 302, 391, 450, 510, 576, 613, -1},
{2, 81, 163, 236, 303, 392, 451, 511, 577, 614, -1},
{3, 82, 164, 237, 304, 393, 452, 512, 578, 615, -1},
{4, 83, 165, 238, 305, 394, 453, 513, 579, 616, -1},
{5, 84, 166, 239, 306, 395, 454, 514, 580, 617, -1},
{6, 85, 167, 240, 307, 360, 455, 515, 581, 618, -1},
{7, 86, 168, 241, 308, 361, 456, 516, 582, 619, -1},
{8, 87, 169, 242, 309, 362, 457, 517, 583, 620, -1},
{9, 88, 170, 243, 310, 363, 458, 518, 584, 621, -1},
{10, 89, 171, 244, 311, 364, 459, 519, 585, 622, -1},
{11, 90, 172, 245, 312, 365, 460, 520, 586, 623, -1},
{12, 91, 173, 246, 313, 366, 461, 521, 587, 624, -1},
{13, 92, 174, 247, 314, 367, 462, 522, 588, 625, -1},
{14, 93, 175, 248, 315, 368, 463, 523, 589, 626, -1},
{15, 94, 176, 249, 316, 369, 464, 524, 590, 627, -1},
{16, 95, 177, 250, 317, 370, 465, 525, 591, 628, -1},
{17, 96, 178, 251, 318, 371, 466, 526, 592, 629, -1},
{18, 97, 179, 216, 319, 372, 467, 527, 593, 630, -1},
{19, 98, 144, 217, 320, 373, 432, 528, 594, 631, -1},
{20, 99, 145, 218, 321, 374, 433, 529, 595, 632, -1},
{21, 100, 146, 219, 322, 375, 434, 530, 596, 633, -1},
{22, 101, 147, 220, 323, 376, 435, 531, 597, 634, -1},
{23, 102, 148, 221, 288, 377, 436, 532, 598, 635, -1},
{24, 103, 149, 222, 289, 378, 437, 533, 599, 636, -1},
{25, 104, 150, 223, 290, 379, 438, 534, 600, 637, -1},
{26, 105, 151, 224, 291, 380, 439, 535, 601, 638, -1},
{27, 106, 152, 225, 292, 381, 440, 536, 602, 639, -1},
{28, 107, 153, 226, 293, 382, 441, 537, 603, 640, -1},
{29, 72, 154, 227, 294, 383, 442, 538, 604, 641, -1},
{30, 73, 155, 228, 295, 384, 443, 539, 605, 642, -1},
{31, 74, 156, 229, 296, 385, 444, 504, 606, 643, -1},
{32, 75, 157, 230, 297, 386, 445, 505, 607, 644, -1},
{33, 76, 158, 231, 298, 387, 446, 506, 608, 645, -1},
{34, 77, 159, 232, 299, 388, 447, 507, 609, 646, -1},
{35, 78, 160, 233, 300, 389, 448, 508, 610, 647, -1},
{61, 141, 192, 253, 330, 409, 483, 558, 612, 648, -1},
{62, 142, 193, 254, 331, 410, 484, 559, 613, 649, -1},
{63, 143, 194, 255, 332, 411, 485, 560, 614, 650, -1},
{64, 108, 195, 256, 333, 412, 486, 561, 615, 651, -1},
{65, 109, 196, 257, 334, 413, 487, 562, 616, 652, -1},
{66, 110, 197, 258, 335, 414, 488, 563, 617, 653, -1},
{67, 111, 198, 259, 336, 415, 489, 564, 618, 654, -1},
{68, 112, 199, 260, 337, 416, 490, 565, 619, 655, -1},
{69, 113, 200, 261, 338, 417, 491, 566, 620, 656, -1},
{70, 114, 201, 262, 339, 418, 492, 567, 621, 657, -1},
{71, 115, 202, 263, 340, 419, 493, 568, 622, 658, -1},
{36, 116, 203, 264, 341, 420, 494, 569, 623, 659, -1},
{37, 117, 204, 265, 342, 421, 495, 570, 624, 660, -1},
{38, 118, 205, 266, 343, 422, 496, 571, 625, 661, -1},
{39, 119, 206, 267, 344, 423, 497, 572, 626, 662, -1},
{40, 120, 207, 268, 345, 424, 498, 573, 627, 663, -1},
{41, 121, 208, 269, 346, 425, 499, 574, 628, 664, -1},
{42, 122, 209, 270, 347, 426, 500, 575, 629, 665, -1},
{43, 123, 210, 271, 348, 427, 501, 540, 630, 666, -1},
{44, 124, 211, 272, 349, 428, 502, 541, 631, 667, -1},
{45, 125, 212, 273, 350, 429, 503, 542, 632, 668, -1},
{46, 126, 213, 274, 351, 430, 468, 543, 633, 669, -1},
{47, 127, 214, 275, 352, 431, 469, 544, 634, 670, -1},
{48, 128, 215, 276, 353, 396, 470, 545, 635, 671, -1},
{49, 129, 180, 277, 354, 397, 471, 546, 636, 672, -1},
{50, 130, 181, 278, 355, 398, 472, 547, 637, 673, -1},
{51, 131, 182, 279, 356, 399, 473, 548, 638, 674, -1},
{52, 132, 183, 280, 357, 400, 474, 549, 639, 675, -1},
{53, 133, 184, 281, 358, 401, 475, 550, 640, 676, -1},
{54, 134, 185, 282, 359, 402, 476, 551, 641, 677, -1},
{55, 135, 186, 283, 324, 403, 477, 552, 642, 678, -1},
{56, 136, 187, 284, 325, 404, 478, 553, 643, 679, -1},
{57, 137, 188, 285, 326, 405, 479, 554, 644, 680, -1},
{58, 138, 189, 286, 327, 406, 480, 555, 645, 681, -1},
{59, 139, 190, 287, 328, 407, 481, 556, 646, 682, -1},
{60, 140, 191, 252, 329, 408, 482, 557, 647, 683, -1},
{3, 104, 167, 226, 319, 366, 444, 531, 648, 684, -1},
{4, 105, 168, 227, 320, 367, 445, 532, 649, 685, -1},
{5, 106, 169, 228, 321, 368, 446, 533, 650, 686, -1},
{6, 107, 170, 229, 322, 369, 447, 534, 651, 687, -1},
{7, 72, 171, 230, 323, 370, 448, 535, 652, 688, -1},
{8, 73, 172, 231, 288, 371, 449, 536, 653, 689, -1},
{9, 74, 173, 232, 289, 372, 450, 537, 654, 690, -1},
{10, 75, 174, 233, 290, 373, 451, 538, 655, 691, -1},
{11, 76, 175, 234, 291, 374, 452, 539, 656, 692, -1},
{12, 77, 176, 235, 292, 375, 453, 504, 657, 693, -1},
{13, 78, 177, 236, 293, 376, 454, 505, 658, 694, -1},
{14, 79, 178, 237, 294, 377, 455, 506, 659, 695, -1},
{15, 80, 179, 238, 295, 378, 456, 507, 660, 696, -1},
{16, 81, 144, 239, 296, 379, 457, 508, 661, 697, -1},
{17, 82, 145, 240, 297, 380, 458, 509, 662, 698, -1},
{18, 83, 146, 241, 298, 381, 459, 510, 663, 699, -1},
{19, 84, 147, 242, 299, 382, 460, 511, 664, 700, -1},
{20, 85, 148, 243, 300, 383, 461, 512, 665, 701, -1},
{21, 86, 149, 244, 301, 384, 462, 513, 666, 702, -1},
{22, 87, 150, 245, 302, 385, 463, 514, 667, 703, -1},
{23, 88, 151, 246, 303, 386, 464, 515, 668, 704, -1},
{24, 89, 152, 247, 304, 387, 465, 516, 669, 705, -1},
{25, 90, 153, 248, 305, 388, 466, 517, 670, 706, -1},
{26, 91, 154, 249, 306, 389, 467, 518, 671, 707, -1},
{27, 92, 155, 250, 307, 390, 432, 519, 672, 708, -1},
{28, 93, 156, 251, 308, 391, 433, 520, 673, 709, -1},
{29, 94, 157, 216, 309, 392, 434, 521, 674, 710, -1},
{30, 95, 158, 217, 310, 393, 435, 522, 675, 711, -1},
{31, 96, 159, 218, 311, 394, 436, 523, 676, 712, -1},
{32, 97, 160, 219, 312, 395, 437, 524, 677, 713, -1},
{33, 98, 161, 220, 313, 360, 438, 525, 678, 714, -1},
{34, 99, 162, 221, 314, 361, 439, 526, 679, 715, -1},
{35, 100, 163, 222, 315, 362, 440, 527, 680, 716, -1},
{0, 101, 164, 223, 316, 363, 441, 528, 681, 717, -1},
{1, 102, 165, 224, 317, 364, 442, 529, 682, 718, -1},
{2, 103, 166, 225, 318, 365, 443, 530, 683, 719, -1},
{46, 120, 210, 262, 357, 397, 489, 553, 684, 720, -1},
{47, 121, 211, 263, 358, 398, 490, 554, 685, 721, -1},
{48, 122, 212, 264, 359, 399, 491, 555, 686, 722, -1},
{49, 123, 213, 265, 324, 400, 492, 556, 687, 723, -1},
{50, 124, 214, 266, 325, 401, 493, 557, 688, 724, -1},
{51, 125, 215, 267, 326, 402, 494, 558, 689, 725, -1},
{52, 126, 180, 268, 327, 403, 495, 559, 690, 726, -1},
{53, 127, 181, 269, 328, 404, 496, 560, 691, 727, -1},
{54, 128, 182, 270, 329, 405, 497, 561, 692, 728, -1},
{55, 129, 183, 271, 330, 406, 498, 562, 693, 729, -1},
{56, 130, 184, 272, 331, 407, 499, 563, 694, 730, -1},
{57, 131, 185, 273, 332, 408, 500, 564, 695, 731, -1},
{58, 132, 186, 274, 333, 409, 501, 565, 696, 732, -1},
{59, 133, 187, 275, 334, 410, 502, 566, 697, 733, -1},
{60, 134, 188, 276, 335, 411, 503, 567, 698, 734, -1},
{61, 135, 189, 277, 336, 412, 468, 568, 699, 735, -1},
{62, 136, 190, 278, 337, 413, 469, 569, 700, 736, -1},
{63, 137, 191, 279, 338, 414, 470, 570, 701, 737, -1},
{64, 138, 192, 280, 339, 415, 471, 571, 702, 738, -1},
{65, 139, 193, 281, 340, 416, 472, 572, 703, 739, -1},
{66, 140, 194, 282, 341, 417, 473, 573, 704, 740, -1},
{67, 141, 195, 283, 342, 418, 474, 574, 705, 741, -1},
{68, 142, 196, 284, 343, 419, 475, 575, 706, 742, -1},
{69, 143, 197, 285, 344, 420, 476, 540, 707, 743, -1},
{70, 108, 198, 286, 345, 421, 477, 541, 708, 744, -1},
{71, 109, 199, 287, 346, 422, 478, 542, 709, 745, -1},
{36, 110, 200, 252, 347, 423, 479, 543, 710, 746, -1},
{37, 111, 201, 253, 348, 424, 480, 544, 711, 747, -1},
{38, 112, 202, 254, 349, 425, 481, 545, 712, 748, -1},
{39, 113, 203, 255, 350, 426, 482, 546, 713, 749, -1},
{40, 114, 204, 256, 351, 427, 483, 547, 714, 750, -1},
{41, 115, 205, 257, 352, 428, 484, 548, 715, 751, -1},
{42, 116, 206, 258, 353, 429, 485, 549, 716, 752, -1},
{43, 117, 207, 259, 354, 430, 486, 550, 717, 753, -1},
{44, 118, 208, 260, 355, 431, 487, 551, 718, 754, -1},
{45, 119, 209, 261, 356, 396, 488, 552, 719, 755, -1},
{8, 82, 149, 227, 312, 369, 450, 527, 720, 756, -1},
{9, 83, 150, 228, 313, 370, 451, 528, 721, 757, -1},
{10, 84, 151, 229, 314, 371, 452, 529, 722, 758, -1},
{11, 85, 152, 230, 315, 372, 453, 530, 723, 759, -1},
{12, 86, 153, 231, 316, 373, 454, 531, 724, 760, -1},
{13, 87, 154, 232, 317, 374, 455, 532, 725, 761, -1},
{14, 88, 155, 233, 318, 375, 456, 533, 726, 762, -1},
{15, 89, 156, 234, 319, 376, 457, 534, 727, 763, -1},
{16, 90, 157, 235, 320, 377, 458, 535, 728, 764, -1},
{17, 91, 158, 236, 321, 378, 459, 536, 729, 765, -1},
{18, 92, 159, 237, 322, 379, 460, 537, 730, 766, -1},
{19, 93, 160, 238, 323, 380, 461, 538, 731, 767, -1},
{20, 94, 161, 239, 288, 381, 462, 539, 732, 768, -1},
{21, 95, 162, 240, 289, 382, 463, 504, 733, 769, -1},
{22, 96, 163, 241, 290, 383, 464, 505, 734, 770, -1},
{23, 97, 164, 242, 291, 384, 465, 506, 735, 771, -1},
{24, 98, 165, 243, 292, 385, 466, 507, 736, 772, -1},
{25, 99, 166, 244, 293, 386, 467, 508, 737, 773, -1},
{26, 100, 167, 245, 294, 387, 432, 509, 738, 774, -1},
{27, 101, 168, 246, 295, 388, 433, 510, 739, 775, -1},
{28, 102, 169, 247, 296, 389, 434, 511, 740, 776, -1},
{29, 103, 170, 248, 297, 390, 435, 512, 741, 777, -1},
{30, 104, 171, 249, 298, 391, 436, 513, 742, 778, -1},
{31, 105, 172, 250, 299, 392, 437, 514, 743, 779, -1},
{32, 106, 173, 251, 300, 393, 438, 515, 744, 780, -1},
{33, 107, 174, 216, 301, 394, 439, 516, 745, 781, -1},
{34, 72, 175, 217, 302, 395, 440, 517, 746, 782, -1},
{35, 73, 176, 218, 303, 360, 441, 518, 747, 783, -1},
{0, 74, 177, 219, 304, 361, 442, 519, 748, 784, -1},
{1, 75, 178, 220, 305, 362, 443, 520, 749, 785, -1},
{2, 76, 179, 221, 306, 363, 444, 521, 750, 786, -1},
{3, 77, 144, 222, 307, 364, 445, 522, 751, 787, -1},
{4, 78, 145, 223, 308, 365, 446, 523, 752, 788, -1},
{5, 79, 146, 224, 309, 366, 447, 524, 753, 789, -1},
{6, 80, 147, 225, 310, 367, 448, 525, 754, 790, -1},
{7, 81, 148, 226, 311, 368, 449, 526, 755, 791, -1},
{47, 132, 200, 257, 324, 407, 495, 540, 756, 792, -1},
{48, 133, 201, 258, 325, 408, 496, 541, 757, 793, -1},
{49, 134, 202, 259, 326, 409, 497, 542, 758, 794, -1},
{50, 135, 203, 260, 327, 410, 498, 543, 759, 795, -1},
{51, 136, 204, 261, 328, 411, 499, 544, 760, 796, -1},
{52, 137, 205, 262, 329, 412, 500, 545, 761, 797, -1},
{53, 138, 206, 263, 330, 413, 501, 546, 762, 798, -1},
{54, 139, 207, 264, 331, 414, 502, 547, 763, 799, -1},
{55, 140, 208, 265, 332, 415, 503, 548, 764, 800, -1},
{56, 141, 209, 266, 333, 416, 468, 549, 765, 801, -1},
{57, 142, 210, 267, 334, 417, 469, 550, 766, 802, -1},
{58, 143, 211, 268, 335, 418, 470, 551, 767, 803, -1},
{59, 108, 212, 269, 336, 419, 471, 552, 768, 804, -1},
{60, 109, 213, 270, 337, 420, 472, 553, 769, 805, -1},
{61, 110, 214, 271, 338, 421, 473, 554, 770, 806, -1},
{62, 111, 215, 272, 339, 422, 474, 555, 771, 807, -1},
{63, 112, 180, 273, 340, 423, 475, 556, 772, 808, -1},
{64, 113, 181, 274, 341, 424, 476, 557, 773, 809, -1},
{65, 114, 182, 275, 342, 425, 477, 558, 774, 810, -1},
{66, 115, 183, 276, 343, 426, 478, 559, 775, 811, -1},
{67, 116, 184, 277, 344, 427, 479, 560, 776, 812, -1},
{68, 117, 185, 278, 345, 428, 480, 561, 777, 813, -1},
{69, 118, 186, 279, 346, 429, 481, 562, 778, 814, -1},
{70, 119, 187, 280, 347, 430, 482, 563, 779, 815, -1},
{71, 120, 188, 281, 348, 431, 483, 564, 780, 816, -1},
{36, 121, 189, 282, 349, 396, 484, 565, 781, 817, -1},
{37, 122, 190, 283, 350, 397, 485, 566, 782, 818, -1},
{38, 123, 191, 284, 351, 398, 486, 567, 783, 819, -1},
{39, 124, 192, 285, 352, 399, 487, 568, 784, 820, -1},
{40, 125, 193, 286, 353, 400, 488, 569, 785, 821, -1},
{41, 126, 194, 287, 354, 401, 489, 570, 786, 822, -1},
{42, 127, 195, 252, 355, 402, 490, 571, 787, 823, -1},
{43, 128, 196, 253, 356, 403, 491, 572, 788, 824, -1},
{44, 129, 197, 254, 357, 404, 492, 573, 789, 825, -1},
{45, 130, 198, 255, 358, 405, 493, 574, 790, 826, -1},
{46, 131, 199, 256, 359, 406, 494, 575, 791, 827, -1},
{12, 72, 149, 237, 319, 361, 434, 523, 576, 792, 828},
{13, 73, 150, 238, 320, 362, 435, 524, 577, 793, 829},
{14, 74, 151, 239, 321, 363, 436, 525, 578, 794, 830},
{15, 75, 152, 240, 322, 364, 437, 526, 579, 795, 831},
{16, 76, 153, 241, 323, 365, 438, 527, 580, 796, 832},
{17, 77, 154, 242, 288, 366, 439, 528, 581, 797, 833},
{18, 78, 155, 243, 289, 367, 440, 529, 582, 798, 834},
{19, 79, 156, 244, 290, 368, 441, 530, 583, 799, 835},
{20, 80, 157, 245, 291, 369, 442, 531, 584, 800, 836},
{21, 81, 158, 246, 292, 370, 443, 532, 585, 801, 837},
{22, 82, 159, 247, 293, 371, 444, 533, 586, 802, 838},
{23, 83, 160, 248, 294, 372, 445, 534, 587, 803, 839},
{24, 84, 161, 249, 295, 373, 446, 535, 588, 804, 840},
{25, 85, 162, 250, 296, 374, 447, 536, 589, 805, 841},
{26, 86, 163, 251, 297, 375, 448, 537, 590, 806, 842},
{27, 87, 164, 216, 298, 376, 449, 538, 591, 807, 843},
{28, 88, 165, 217, 299, 377, 450, 539, 592, 808, 844},
{29, 89, 166, 218, 300, 378, 451, 504, 593, 809, 845},
{30, 90, 167, 219, 301, 379, 452, 505, 594, 810, 846},
{31, 91, 168, 220, 302, 380, 453, 506, 595, 811, 847},
{32, 92, 169, 221, 303, 381, 454, 507, 596, 812, 848},
{33, 93, 170, 222, 304, 382, 455, 508, 597, 813, 849},
{34, 94, 171, 223, 305, 383, 456, 509, 598, 814, 850},
{35, 95, 172, 224, 306, 384, 457, 510, 599, 815, 851},
{0, 96, 173, 225, 307, 385, 458, 511, 600, 816, 852},
{1, 97, 174, 226, 308, 386, 459, 512, 601, 817, 853},
{2, 98, 175, 227, 309, 387, 460, 513, 602, 818, 854},
{3, 99, 176, 228, 310, 388, 461, 514, 603, 819, 855},
{4, 100, 177, 229, 311, 389, 462, 515, 604, 820, 856},
{5, 101, 178, 230, 312, 390, 463, 516, 605, 821, 857},
{6, 102, 179, 231, 313, 391, 464, 517, 606, 822, 858},
{7, 103, 144, 232, 314, 392, 465, 518, 607, 823, 859},
{8, 104, 145, 233, 315, 393, 466, 519, 608, 824, 860},
{9, 105, 146, 234, 316, 394, 467, 520, 609, 825, 861},
{10, 106, 147, 235, 317, 395, 432, 521, 610, 826, 862},
{11, 107, 148, 236, 318, 360, 433, 522, 611, 827, 863},
{36, 125, 184, 274, 355, 416, 497, 555, 611, 828, -1},
{37, 126, 185, 275, 356, 417, 498, 556, 576, 829, -1},
{38, 127, 186, 276, 357, 418, 499, 557, 577, 830, -1},
{39, 128, 187, 277, 358, 419, 500, 558, 578, 831, -1},
{40, 129, 188, 278, 359, 420, 501, 559, 579, 832, -1},
{41, 130, 189, 279, 324, 421, 502, 560, 580, 833, -1},
{42, 131, 190, 280, 325, 422, 503, 561, 581, 834, -1},
{43, 132, 191, 281, 326, 423, 468, 562, 582, 835, -1},
{44, 133, 192, 282, 327, 424, 469, 563, 583, 836, -1},
{45, 134, 193, 283, 328, 425, 470, 564, 584, 837, -1},
{46, 135, 194, 284, 329, 426, 471, 565, 585, 838, -1},
{47, 136, 195, 285, 330, 427, 472, 566, 586, 839, -1},
{48, 137, 196, 286, 331, 428, 473, 567, 587, 840, -1},
{49, 138, 197, 287, 332, 429, 474, 568, 588, 841, -1},
{50, 139, 198, 252, 333, 430, 475, 569, 589, 842, -1},
{51, 140, 199, 253, 334, 431, 476, 570, 590, 843, -1},
{52, 141, 200, 254, 335, 396, 477, 571, 591, 844, -1},
{53, 142, 201, 255, 336, 397, 478, 572, 592, 845, -1},
{54, 143, 202, 256, 337, 398, 479, 573, 593, 846, -1},
{55, 108, 203, 257, 338, 399, 480, 574, 594, 847, -1},
{56, 109, 204, 258, 339, 400, 481, 575, 595, 848, -1},
{57, 110, 205, 259, 340, 401, 482, 540, 596, 849, -1},
{58, 111, 206, 260, 341, 402, 483, 541, 597, 850, -1},
{59, 112, 207, 261, 342, 403, 484, 542, 598, 851, -1},
{60, 113, 208, 262, 343, 404, 485, 543, 599, 852, -1},
{61, 114, 209, 263, 344, 405, 486, 544, 600, 853, -1},
{62, 115, 210, 264, 345, 406, 487, 545, 601, 854, -1},
{63, 116, 211, 265, 346, 407, 488, 546, 602, 855, -1},
{64, 117, 212, 266, 347, 408, 489, 547, 603, 856, -1},
{65, 118, 213, 267, 348, 409, 490, 548, 604, 857, -1},
{66, 119, 214, 268, 349, 410, 491, 549, 605, 858, -1},
{67, 120, 215, 269, 350, 411, 492, 550, 606, 859, -1},
{68, 121, 180, 270, 351, 412, 493, 551, 607, 860, -1},
{69, 122, 181, 271, 352, 413, 494, 552, 608, 861, -1},
{70, 123, 182, 272, 353, 414, 495, 553, 609, 862, -1},
{71, 124, 183, 273, 354, 415, 496, 554, 610, 863, -1}
};
#endif | 57.151007 | 59 | 0.509424 | iamviji |
5074b492e1d6cad9623d045c0e74c142a9cf7662 | 299 | cpp | C++ | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char a[100], b[100];
gets(a);
gets(b);
int lena = -1, i = 0;
while(a[++lena] != '\0');
while(b[i] != '\0'){
a[lena++] = b[i++];
}
a[lena] = '\0';
cout << a << endl;
return 0;
}
| 15.736842 | 29 | 0.441472 | wmjtxt |
507cdeacfef76c4f63da9a526dbb2de19e2ae25d | 5,139 | cpp | C++ | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | 2 | 2021-08-28T23:02:30.000Z | 2021-08-28T23:26:21.000Z | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | null | null | null | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. 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.
*/
#include "vulkan-backend.h"
#include <nvrhi/common/misc.h>
namespace nvrhi::vulkan
{
std::shared_ptr<BufferChunk> UploadManager::CreateChunk(uint64_t size)
{
std::shared_ptr<BufferChunk> chunk = std::make_shared<BufferChunk>();
if (m_IsScratchBuffer)
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::None;
desc.debugName = "ScratchBufferChunk";
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = nullptr;
chunk->bufferSize = size;
}
else
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::Write;
desc.debugName = "UploadChunk";
// The upload manager buffers are used in buildTopLevelAccelStruct to store instance data
desc.isAccelStructBuildInput = m_Device->queryFeatureSupport(Feature::RayTracingAccelStruct);
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = m_Device->mapBuffer(chunk->buffer, CpuAccessMode::Write);
chunk->bufferSize = size;
}
return chunk;
}
bool UploadManager::suballocateBuffer(uint64_t size, Buffer** pBuffer, uint64_t* pOffset, void** pCpuVA,
uint64_t currentVersion, uint32_t alignment)
{
std::shared_ptr<BufferChunk> chunkToRetire;
if (m_CurrentChunk)
{
uint64_t alignedOffset = align(m_CurrentChunk->writePointer, (uint64_t)alignment);
uint64_t endOfDataInChunk = alignedOffset + size;
if (endOfDataInChunk <= m_CurrentChunk->bufferSize)
{
m_CurrentChunk->writePointer = endOfDataInChunk;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = alignedOffset;
if (pCpuVA && m_CurrentChunk->mappedMemory)
*pCpuVA = (char*)m_CurrentChunk->mappedMemory + alignedOffset;
return true;
}
chunkToRetire = m_CurrentChunk;
m_CurrentChunk.reset();
}
CommandQueue queue = VersionGetQueue(currentVersion);
uint64_t completedInstance = m_Device->queueGetCompletedInstance(queue);
for (auto it = m_ChunkPool.begin(); it != m_ChunkPool.end(); ++it)
{
std::shared_ptr<BufferChunk> chunk = *it;
if (VersionGetSubmitted(chunk->version)
&& VersionGetInstance(chunk->version) <= completedInstance)
{
chunk->version = 0;
}
if (chunk->version == 0 && chunk->bufferSize >= size)
{
m_ChunkPool.erase(it);
m_CurrentChunk = chunk;
break;
}
}
if (chunkToRetire)
{
m_ChunkPool.push_back(chunkToRetire);
}
if (!m_CurrentChunk)
{
uint64_t sizeToAllocate = align(std::max(size, m_DefaultChunkSize), BufferChunk::c_sizeAlignment);
if ((m_MemoryLimit > 0) && (m_AllocatedMemory + sizeToAllocate > m_MemoryLimit))
return false;
m_CurrentChunk = CreateChunk(sizeToAllocate);
}
m_CurrentChunk->version = currentVersion;
m_CurrentChunk->writePointer = size;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = 0;
if (pCpuVA)
*pCpuVA = m_CurrentChunk->mappedMemory;
return true;
}
void UploadManager::submitChunks(uint64_t currentVersion, uint64_t submittedVersion)
{
if (m_CurrentChunk)
{
m_ChunkPool.push_back(m_CurrentChunk);
m_CurrentChunk.reset();
}
for (const auto& chunk : m_ChunkPool)
{
if (chunk->version == currentVersion)
chunk->version = submittedVersion;
}
}
} | 34.26 | 110 | 0.622884 | Impulse21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.