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 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e0447588f79276f223c96a4be21122dcde195285 | 3,313 | cpp | C++ | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 21 | 2018-07-06T06:09:42.000Z | 2021-06-28T21:21:01.000Z | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 21 | 2018-06-29T23:57:33.000Z | 2022-03-01T02:37:49.000Z | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 9 | 2019-10-16T10:14:12.000Z | 2021-06-29T17:11:27.000Z | /// 786
#include <string>
using namespace std;
#include "src/common.h"
#include "src/search.h"
#include "src/chain.h"
#include "src/align.h"
class PyHit {
public:
int qs, qe;
int rs, re;
Alignment c;
// PyHit() = default;
int query_start() { return qs; }
int query_end() { return qe; }
int ref_start() { return rs; }
int ref_end() { return re; }
string cigar() { return c.cigar_string(); }
int alignment_size() { return c.span(); }
int gaps() { return c.gap_bases(); }
int mismatches() { return c.mismatches(); }
bool operator==(const PyHit &q) const {
return tie(qs, qe, rs, re) == tie(q.qs, q.qe, q.rs, q.re);
}
};
class PyAligner {
public:
vector<PyHit> jaccard_align(const string &q, const string &r);
vector<PyHit> chain_align(const string &q, const string &r);
vector<PyHit> full_align(const string &q, const string &r);
};
vector<PyHit> PyAligner::jaccard_align(const string &q, const string &r)
{
shared_ptr<Index> query_hash = make_shared<Index>(make_shared<Sequence>("qry", q), 12, 16);
shared_ptr<Index> ref_hash = make_shared<Index>(make_shared<Sequence>("ref", r), 12, 16);
Tree tree;
vector<PyHit> hits;
bool iterative = true;
if (iterative) {
for (int qi = 0; qi < query_hash->minimizers.size(); qi++) {
auto &qm = query_hash->minimizers[qi];
// eprn("search {}", qm.loc);
if (qm.hash.status != Hash::Status::HAS_UPPERCASE)
continue;
auto hi = search(qi, query_hash, ref_hash, tree, false,
max(q.size(), r.size()), true, false);
for (auto &pp: hi) {
hits.push_back(PyHit {
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
{}
});
}
}
} else {
// Disabled for now
auto hi = search(0, query_hash, ref_hash, tree,
false, max(q.size(), r.size()), false, false);
for (auto &pp: hi) {
hits.push_back({
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
{}
});
}
}
return hits;
}
vector<PyHit> PyAligner::chain_align(const string &q, const string &r)
{
vector<PyHit> hits;
Hit orig {
make_shared<Sequence>("A", q), 0, (int)q.size(),
make_shared<Sequence>("B", r), 0, (int)r.size()
};
auto hi = fast_align(q, r, orig, 11);
for (auto &pp: hi) {
hits.push_back({
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
pp.aln
});
}
return hits;
}
vector<PyHit> PyAligner::full_align(const string &q, const string &r)
{
auto aln = Alignment(q, r);
return vector<PyHit> {{
0, (int)q.size(),
0, (int)r.size(),
aln
}};
}
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
BOOST_PYTHON_MODULE(sedef)
{
using namespace boost::python;
class_<PyHit>("PyHit")
.def("cigar", &PyHit::cigar)
.def("alignment_size", &PyHit::alignment_size)
.def("gaps", &PyHit::gaps)
.def("mismatches", &PyHit::mismatches)
.def("query_start", &PyHit::query_start)
.def("query_end", &PyHit::query_end)
.def("ref_start", &PyHit::ref_start)
.def("ref_end", &PyHit::ref_end);
class_<std::vector<PyHit>>("vector")
.def(vector_indexing_suite<std::vector<PyHit>, true>());
class_<PyAligner>("PyAligner")
.def("jaccard_align", &PyAligner::jaccard_align)
.def("chain_align", &PyAligner::chain_align)
.def("full_align", &PyAligner::full_align)
;
} | 25.290076 | 92 | 0.638696 | mateog4712 |
e0462028989128bc82fc25982091e8b8a48f3869 | 355 | cpp | C++ | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | #include "Model.h"
Model::Model() {}
Model::~Model()
{
for(int i=0; i<meshes.size(); i++)
delete meshes[i];
}
void Model::draw(Program* program)
{
for (std::vector<Mesh*>::iterator mesh = this->meshes.begin(); mesh != this->meshes.end(); ++mesh)
{
(*mesh)->draw(program);
}
}
void Model::addMesh(Mesh* mesh)
{
this->meshes.push_back(mesh);
}
| 15.434783 | 99 | 0.616901 | RPKQ |
e046997443b3e543fb43151ef82eb3009d970a81 | 447 | cpp | C++ | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | 1 | 2021-07-13T03:58:36.000Z | 2021-07-13T03:58:36.000Z | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | //
// This file contains the C++ code from Program 2.3 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm02_03.cpp
//
unsigned int Factorial (unsigned int n)
{
if (n == 0)
return 1;
else
return n * Factorial (n - 1);
}
| 24.833333 | 80 | 0.651007 | neharkarvishal |
e047b1720d51db02c5a4f7efba596675bf572a7a | 2,538 | cpp | C++ | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 62 | 2016-10-14T23:11:14.000Z | 2022-03-20T08:32:15.000Z | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 2 | 2017-11-16T08:17:44.000Z | 2021-10-14T06:49:41.000Z | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 31 | 2017-01-04T12:32:40.000Z | 2022-03-28T12:19:20.000Z | template<typename T>
struct sorter
{
struct chunk_to_sort
{
std::list<T> data;
std::promise<std::list<T> > promise;
};
thread_safe_stack<chunk_to_sort> chunks;
std::vector<std::thread> threads;
unsigned const max_thread_count;
std::atomic<bool> end_of_data;
sorter():
max_thread_count(std::thread::hardware_concurrency()-1),
end_of_data(false)
{}
~sorter()
{
end_of_data=true;
for(unsigned i=0;i<threads.size();++i)
{
threads[i].join();
}
}
void try_sort_chunk()
{
boost::shared_ptr<chunk_to_sort > chunk=chunks.pop();
if(chunk)
{
sort_chunk(chunk);
}
}
std::list<T> do_sort(std::list<T>& chunk_data)
{
if(chunk_data.empty())
{
return chunk_data;
}
std::list<T> result;
result.splice(result.begin(),chunk_data,chunk_data.begin());
T const& partition_val=*result.begin();
typename std::list<T>::iterator divide_point=
std::partition(chunk_data.begin(),chunk_data.end(),
[&](T const& val){return val<partition_val;});
chunk_to_sort new_lower_chunk;
new_lower_chunk.data.splice(new_lower_chunk.data.end(),
chunk_data,chunk_data.begin(),
divide_point);
std::future<std::list<T> > new_lower=
new_lower_chunk.promise.get_future();
chunks.push(std::move(new_lower_chunk));
if(threads.size()<max_thread_count)
{
threads.push_back(std::thread(&sorter<T>::sort_thread,this));
}
std::list<T> new_higher(do_sort(chunk_data));
result.splice(result.end(),new_higher);
while(new_lower.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready)
{
try_sort_chunk();
}
result.splice(result.begin(),new_lower.get());
return result;
}
void sort_chunk(boost::shared_ptr<chunk_to_sort > const& chunk)
{
chunk->promise.set_value(do_sort(chunk->data));
}
void sort_thread()
{
while(!end_of_data)
{
try_sort_chunk();
std::this_thread::yield();
}
}
};
template<typename T>
std::list<T> parallel_quick_sort(std::list<T> input)
{
if(input.empty())
{
return input;
}
sorter<T> s;
return s.do_sort(input);
}
| 24.640777 | 73 | 0.550827 | renc |
e04c85a0329210b5e84e7c4166cd0b2d80957b2f | 2,590 | hpp | C++ | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | 1 | 2017-03-12T20:32:36.000Z | 2017-03-12T20:32:36.000Z | #ifndef PYTHONIC_UTILS_NUMPY_TRAITS_HPP
#define PYTHONIC_UTILS_NUMPY_TRAITS_HPP
namespace pythonic {
namespace types {
template<class T, size_t N>
class ndarray;
template<class A>
class numpy_iexpr;
template<class A, class F>
class numpy_fexpr;
template<class A, class ...S>
class numpy_gexpr;
template<class A>
class numpy_texpr;
template<class A>
class numpy_texpr_2;
template<class O, class... Args>
class numpy_expr;
template<class T>
class list;
template<class T, size_t N>
struct array;
template<class T>
struct is_ndarray {
static constexpr bool value = false;
};
template<class T, size_t N>
struct is_ndarray<ndarray<T,N>> {
static constexpr bool value = true;
};
/* Type trait that checks if a type is a potential numpy expression parameter
*
* Only used to write concise expression templates
*/
template<class T>
struct is_array {
static constexpr bool value = false;
};
template<class T, size_t N>
struct is_array<ndarray<T,N>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_iexpr<A>> {
static constexpr bool value = true;
};
template<class A, class F>
struct is_array<numpy_fexpr<A,F>> {
static constexpr bool value = true;
};
template<class A, class... S>
struct is_array<numpy_gexpr<A,S...>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_texpr<A>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_texpr_2<A>> {
static constexpr bool value = true;
};
template<class O, class... Args>
struct is_array<numpy_expr<O,Args...>> {
static constexpr bool value = true;
};
template<class T>
struct is_numexpr_arg : is_array<T> {
};
template<class T>
struct is_numexpr_arg<list<T>> {
static constexpr bool value = true;
};
template<class T, size_t N>
struct is_numexpr_arg<array<T,N>> {
static constexpr bool value = true;
};
}
}
#endif
| 27.849462 | 85 | 0.535521 | Pikalchemist |
e04e3aa2bc206c8ad55cb71fb24826415cfdf6f2 | 8,439 | cpp | C++ | vbox/src/VBox/Additions/darwin/vboxfs/VBoxVFS.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/Additions/darwin/vboxfs/VBoxVFS.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/Additions/darwin/vboxfs/VBoxVFS.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | /* $Id: VBoxVFS.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */
/** @file
* VBoxVFS - Guest Additions Shared Folders driver. KEXT entry point.
*/
/*
* Copyright (C) 2013-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <IOKit/IOLib.h> /* Assert as function */
#include <IOKit/IOService.h>
#include <mach/mach_port.h>
#include <mach/kmod.h>
#include <libkern/libkern.h>
#include <mach/mach_types.h>
#include <sys/mount.h>
#include <iprt/cdefs.h>
#include <iprt/types.h>
#include <sys/param.h>
#include <VBox/version.h>
#include <iprt/asm.h>
#include <VBox/log.h>
#include "vboxvfs.h"
/*********************************************************************************************************************************
* Structures and Typedefs *
*********************************************************************************************************************************/
/**
* The service class for dealing with Share Folder filesystem.
*/
class org_virtualbox_VBoxVFS : public IOService
{
OSDeclareDefaultStructors(org_virtualbox_VBoxVFS);
private:
IOService * waitForCoreService(void);
IOService * coreService;
public:
virtual bool start(IOService *pProvider);
virtual void stop(IOService *pProvider);
};
OSDefineMetaClassAndStructors(org_virtualbox_VBoxVFS, IOService);
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
/**
* Declare the module stuff.
*/
RT_C_DECLS_BEGIN
static kern_return_t VBoxVFSModuleLoad(struct kmod_info *pKModInfo, void *pvData);
static kern_return_t VBoxVFSModuleUnLoad(struct kmod_info *pKModInfo, void *pvData);
extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
KMOD_EXPLICIT_DECL(VBoxVFS, VBOX_VERSION_STRING, _start, _stop)
DECLHIDDEN(kmod_start_func_t *) _realmain = VBoxVFSModuleLoad;
DECLHIDDEN(kmod_stop_func_t *) _antimain = VBoxVFSModuleUnLoad;
DECLHIDDEN(int) _kext_apple_cc = __APPLE_CC__;
RT_C_DECLS_END
/** The number of IOService class instances. */
static bool volatile g_fInstantiated = 0;
/* Global connection to the host service */
VBGLSFCLIENT g_vboxSFClient;
/* VBoxVFS filesystem handle. Needed for FS unregistering. */
static vfstable_t g_oVBoxVFSHandle;
/**
* KEXT Module BSD entry point
*/
static kern_return_t VBoxVFSModuleLoad(struct kmod_info *pKModInfo, void *pvData)
{
int rc;
/* Initialize the R0 guest library. */
#if 0
rc = VbglR0SfInit();
if (RT_FAILURE(rc))
return KERN_FAILURE;
#endif
PINFO("VirtualBox " VBOX_VERSION_STRING " shared folders "
"driver is loaded");
return KERN_SUCCESS;
}
/**
* KEXT Module BSD exit point
*/
static kern_return_t VBoxVFSModuleUnLoad(struct kmod_info *pKModInfo, void *pvData)
{
int rc;
#if 0
VbglR0SfTerm();
#endif
PINFO("VirtualBox " VBOX_VERSION_STRING " shared folders driver is unloaded");
return KERN_SUCCESS;
}
/**
* Register VBoxFS filesystem.
*
* @returns IPRT status code.
*/
int VBoxVFSRegisterFilesystem(void)
{
struct vfs_fsentry oVFsEntry;
int rc;
memset(&oVFsEntry, 0, sizeof(oVFsEntry));
/* Attach filesystem operations set */
oVFsEntry.vfe_vfsops = &g_oVBoxVFSOpts;
/* Attach vnode operations */
oVFsEntry.vfe_vopcnt = g_cVBoxVFSVnodeOpvDescListSize;
oVFsEntry.vfe_opvdescs = g_VBoxVFSVnodeOpvDescList;
/* Set flags */
oVFsEntry.vfe_flags =
#if ARCH_BITS == 64
VFS_TBL64BITREADY |
#endif
VFS_TBLTHREADSAFE |
VFS_TBLFSNODELOCK |
VFS_TBLNOTYPENUM;
memcpy(oVFsEntry.vfe_fsname, VBOXVBFS_NAME, MFSNAMELEN);
rc = vfs_fsadd(&oVFsEntry, &g_oVBoxVFSHandle);
if (rc)
{
PINFO("Unable to register VBoxVFS filesystem (%d)", rc);
return VERR_GENERAL_FAILURE;
}
PINFO("VBoxVFS filesystem successfully registered");
return VINF_SUCCESS;
}
/**
* Unregister VBoxFS filesystem.
*
* @returns IPRT status code.
*/
int VBoxVFSUnRegisterFilesystem(void)
{
int rc;
if (g_oVBoxVFSHandle == 0)
return VERR_INVALID_PARAMETER;
rc = vfs_fsremove(g_oVBoxVFSHandle);
if (rc)
{
PINFO("Unable to unregister VBoxVFS filesystem (%d)", rc);
return VERR_GENERAL_FAILURE;
}
g_oVBoxVFSHandle = 0;
PINFO("VBoxVFS filesystem successfully unregistered");
return VINF_SUCCESS;
}
/**
* Start this service.
*/
bool org_virtualbox_VBoxVFS::start(IOService *pProvider)
{
int rc;
if (!IOService::start(pProvider))
return false;
/* Low level initialization should be performed only once */
if (!ASMAtomicCmpXchgBool(&g_fInstantiated, true, false))
{
IOService::stop(pProvider);
return false;
}
/* Wait for VBoxGuest to be started */
coreService = waitForCoreService();
if (coreService)
{
rc = VbglR0SfInit();
if (RT_SUCCESS(rc))
{
/* Connect to the host service. */
rc = VbglR0SfConnect(&g_vboxSFClient);
if (RT_SUCCESS(rc))
{
PINFO("VBox client connected");
rc = VbglR0SfSetUtf8(&g_vboxSFClient);
if (RT_SUCCESS(rc))
{
rc = VBoxVFSRegisterFilesystem();
if (RT_SUCCESS(rc))
{
registerService();
PINFO("Successfully started I/O kit class instance");
return true;
}
PERROR("Unable to register VBoxVFS filesystem");
}
else
{
PERROR("VbglR0SfSetUtf8 failed: rc=%d", rc);
}
VbglR0SfDisconnect(&g_vboxSFClient);
}
else
{
PERROR("Failed to get connection to host: rc=%d", rc);
}
VbglR0SfTerm();
}
else
{
PERROR("Failed to initialize low level library");
}
coreService->release();
}
else
{
PERROR("VBoxGuest KEXT not started");
}
ASMAtomicXchgBool(&g_fInstantiated, false);
IOService::stop(pProvider);
return false;
}
/**
* Stop this service.
*/
void org_virtualbox_VBoxVFS::stop(IOService *pProvider)
{
int rc;
AssertReturnVoid(ASMAtomicReadBool(&g_fInstantiated));
rc = VBoxVFSUnRegisterFilesystem();
if (RT_FAILURE(rc))
{
PERROR("VBoxVFS filesystem is busy. Make sure all "
"shares are unmounted (%d)", rc);
}
VbglR0SfDisconnect(&g_vboxSFClient);
PINFO("VBox client disconnected");
VbglR0SfTerm();
PINFO("Low level uninit done");
coreService->release();
PINFO("VBoxGuest service released");
IOService::stop(pProvider);
ASMAtomicWriteBool(&g_fInstantiated, false);
PINFO("Successfully stopped I/O kit class instance");
}
/**
* Wait for VBoxGuest.kext to be started
*/
IOService * org_virtualbox_VBoxVFS::waitForCoreService(void)
{
IOService *service;
OSDictionary *serviceToMatch = serviceMatching("org_virtualbox_VBoxGuest");
if (!serviceToMatch)
{
PINFO("unable to create matching dictionary");
return false;
}
/* Wait 10 seconds for VBoxGuest to be started */
service = waitForMatchingService(serviceToMatch, 10ULL * 1000000000ULL);
serviceToMatch->release();
return service;
}
| 26.790476 | 130 | 0.591302 | Nurzamal |
e05062ff88b45be93f2a4832f6fda5fcfea6ea79 | 1,211 | cpp | C++ | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | 1 | 2019-01-12T07:00:46.000Z | 2019-01-12T07:00:46.000Z | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | null | null | null | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_nodelist.h"
#include <memory>
#include "core/fxcrt/fx_extension.h"
#include "fxjs/cfxjse_engine.h"
#include "fxjs/cjx_nodelist.h"
#include "xfa/fxfa/parser/cxfa_document.h"
#include "xfa/fxfa/parser/cxfa_node.h"
CXFA_NodeList::CXFA_NodeList(CXFA_Document* pDocument)
: CXFA_Object(pDocument,
XFA_ObjectType::NodeList,
XFA_Element::NodeList,
WideStringView(L"nodeList"),
pdfium::MakeUnique<CJX_NodeList>(this)) {
m_pDocument->GetScriptContext()->AddToCacheList(
std::unique_ptr<CXFA_NodeList>(this));
}
CXFA_NodeList::~CXFA_NodeList() {}
CXFA_Node* CXFA_NodeList::NamedItem(const WideStringView& wsName) {
uint32_t dwHashCode = FX_HashCode_GetW(wsName, false);
int32_t iCount = GetLength();
for (int32_t i = 0; i < iCount; i++) {
CXFA_Node* ret = Item(i);
if (dwHashCode == ret->GetNameHash())
return ret;
}
return nullptr;
}
| 31.051282 | 80 | 0.695293 | jamespayor |
e0598af3d478abd775a354a1b4a6e602c1a8efe3 | 11,422 | cpp | C++ | examples/descriptorsets/descriptorsets.cpp | harskish/Vulkan | 25be6e4fda8b0d16875a55a1a476209305d4a983 | [
"MIT"
] | 318 | 2016-05-30T18:53:13.000Z | 2022-03-23T19:09:57.000Z | examples/descriptorsets/descriptorsets.cpp | harskish/Vulkan | 25be6e4fda8b0d16875a55a1a476209305d4a983 | [
"MIT"
] | 47 | 2016-06-04T20:53:27.000Z | 2020-12-21T17:14:21.000Z | examples/descriptorsets/descriptorsets.cpp | harskish/Vulkan | 25be6e4fda8b0d16875a55a1a476209305d4a983 | [
"MIT"
] | 35 | 2016-06-08T11:05:02.000Z | 2021-07-26T17:26:36.000Z | /*
* Vulkan Example - Using descriptor sets for passing data to shader stages
*
* Relevant code parts are marked with [POI]
*
* Copyright (C) 2018 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <vulkanExampleBase.h>
class VulkanExample : public vkx::ExampleBase {
public:
bool animate{ true };
vks::model::VertexLayout vertexLayout{ {
vks::model::VERTEX_COMPONENT_POSITION,
vks::model::VERTEX_COMPONENT_NORMAL,
vks::model::VERTEX_COMPONENT_UV,
vks::model::VERTEX_COMPONENT_COLOR,
} };
struct Cube {
struct Matrices {
glm::mat4 projection;
glm::mat4 view;
glm::mat4 model;
} matrices;
vk::DescriptorSet descriptorSet;
vks::texture::Texture2D texture;
vks::Buffer uniformBuffer;
glm::vec3 rotation;
void destroy() {
texture.destroy();
uniformBuffer.destroy();
}
};
std::array<Cube, 2> cubes;
struct Models {
vks::model::Model cube;
} models;
vk::Pipeline pipeline;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;
VulkanExample() {
title = "Using descriptor Sets";
settings.overlay = true;
camera.type = Camera::CameraType::lookat;
camera.setPerspective(60.0f, size, 0.1f, 512.0f);
camera.setRotation({ 0.0f, 0.0f, 0.0f });
camera.setTranslation({ 0.0f, 0.0f, -5.0f });
}
~VulkanExample() {
device.destroy(pipeline);
device.destroy(pipelineLayout);
device.destroy(descriptorSetLayout);
models.cube.destroy();
for (auto cube : cubes) {
cube.uniformBuffer.destroy();
cube.texture.destroy();
}
}
void getEnabledFeatures() override {
if (context.deviceFeatures.samplerAnisotropy) {
context.enabledFeatures.samplerAnisotropy = VK_TRUE;
};
}
void updateDrawCommandBuffer(const vk::CommandBuffer& drawCmdBuffer) override {
drawCmdBuffer.setViewport(0, viewport());
drawCmdBuffer.setScissor(0, scissor());
drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
drawCmdBuffer.bindVertexBuffers(0, models.cube.vertices.buffer, { 0 });
drawCmdBuffer.bindIndexBuffer(models.cube.indices.buffer, 0, vk::IndexType::eUint32);
/*
[POI] Render cubes with separate descriptor sets
*/
for (const auto& cube : cubes) {
// Bind the cube's descriptor set. This tells the command buffer to use the uniform buffer and image set for this cube
drawCmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, cube.descriptorSet, nullptr);
drawCmdBuffer.drawIndexed(models.cube.indexCount, 1, 0, 0, 0);
}
}
void loadAssets() override {
models.cube.loadFromFile(context, getAssetPath() + "models/cube.dae", vertexLayout, 1.0f);
cubes[0].texture.loadFromFile(context, getAssetPath() + "textures/crate01_color_height_rgba.ktx");
cubes[1].texture.loadFromFile(context, getAssetPath() + "textures/crate02_color_height_rgba.ktx");
}
/*
[POI] Set up descriptor sets and set layout
*/
void setupDescriptors() {
/*
Descriptor set layout
The layout describes the shader bindings and types used for a certain descriptor layout and as such must match the shader bindings
Shader bindings used in this example:
VS:
layout (set = 0, binding = 0) uniform UBOMatrices ...
FS :
layout (set = 0, binding = 1) uniform sampler2D ...;
*/
std::array<vk::DescriptorSetLayoutBinding, 2> setLayoutBindings{};
/*
Binding 0: Uniform buffers (used to pass matrices matrices)
*/
setLayoutBindings[0] =
vk::DescriptorSetLayoutBinding{ // Shader binding point
0,
// This is a uniform buffer
vk::DescriptorType::eUniformBuffer,
// Binding contains one element (can be used for array bindings)
1,
// Accessible from the vertex shader only (flags can be combined to make it accessible to multiple shader stages)
vk::ShaderStageFlagBits::eVertex
};
/*
Binding 1: Combined image sampler (used to pass per object texture information)
*/
setLayoutBindings[1] = vk::DescriptorSetLayoutBinding{ // Shader binding point
1,
// This is a image buffer
vk::DescriptorType::eCombinedImageSampler,
// Binding contains one element (can be used for array bindings)
1,
// Accessible from the fragment shader only
vk::ShaderStageFlagBits::eFragment
};
// Create the descriptor set layout
descriptorSetLayout = device.createDescriptorSetLayout({ {}, static_cast<uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() });
/*
Descriptor pool
Actual descriptors are allocated from a descriptor pool telling the driver what types and how many
descriptors this application will use
An application can have multiple pools (e.g. for multiple threads) with any number of descriptor types
as long as device limits are not surpassed
It's good practice to allocate pools with actually required descriptor types and counts
*/
std::array<vk::DescriptorPoolSize, 2> descriptorPoolSizes;
// Uniform buffers : 1 for scene and 1 per object (scene and local matrices)
descriptorPoolSizes[0] = vk::DescriptorPoolSize{ vk::DescriptorType::eUniformBuffer, 1 + static_cast<uint32_t>(cubes.size()) };
// Combined image samples : 1 per mesh texture
descriptorPoolSizes[1] = vk::DescriptorPoolSize{ vk::DescriptorType::eCombinedImageSampler, static_cast<uint32_t>(cubes.size()) };
// Create the global descriptor pool
// Max. number of descriptor sets that can be allocted from this pool (one per object)
descriptorPool = device.createDescriptorPool(
{ {}, static_cast<uint32_t>(descriptorPoolSizes.size()), static_cast<uint32_t>(descriptorPoolSizes.size()), descriptorPoolSizes.data() });
/*
Descriptor sets
Using the shared descriptor set layout and the descriptor pool we will now allocate the descriptor sets.
Descriptor sets contain the actual descriptor fo the objects (buffers, images) used at render time.
*/
std::vector<vk::WriteDescriptorSet> writeDescriptorSets;
for (auto& cube : cubes) {
// Allocates an empty descriptor set without actual descriptors from the pool using the set layout
cube.descriptorSet = device.allocateDescriptorSets({ descriptorPool, 1, &descriptorSetLayout })[0];
// Update the descriptor set with the actual descriptors matching shader bindings set in the layout
/*
Binding 0: Object matrices Uniform buffer
*/
writeDescriptorSets.push_back({ cube.descriptorSet, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &cube.uniformBuffer.descriptor });
/*
Binding 1: Object texture
*/
// Images use a different descriptor strucutre, so we use pImageInfo instead of pBufferInfo
writeDescriptorSets.push_back({ cube.descriptorSet, 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &cube.texture.descriptor });
}
// Execute the writes to update descriptors for ALL sets
device.updateDescriptorSets(writeDescriptorSets, nullptr);
}
void preparePipelines() {
/*
[POI] Create a pipeline layout used for our graphics pipeline
*/
// The pipeline layout is based on the descriptor set layout we created above
pipelineLayout = device.createPipelineLayout({ {}, 1, &descriptorSetLayout });
auto builder = vks::pipelines::GraphicsPipelineBuilder(device, pipelineLayout, renderPass);
builder.rasterizationState.frontFace = vk::FrontFace::eClockwise;
// Vertex bindings and attributes
builder.vertexInputState.appendVertexLayout(vertexLayout);
builder.loadShader(getAssetPath() + "shaders/descriptorsets/cube.vert.spv", vk::ShaderStageFlagBits::eVertex);
builder.loadShader(getAssetPath() + "shaders/descriptorsets/cube.frag.spv", vk::ShaderStageFlagBits::eFragment);
pipeline = builder.create(context.pipelineCache);
}
void prepareUniformBuffers() {
// Vertex shader matrix uniform buffer block
for (auto& cube : cubes) {
cube.uniformBuffer = context.createUniformBuffer<glm::mat4>({});
}
updateUniformBuffers();
}
void updateUniformBuffers() {
cubes[0].matrices.model = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f, 0.0f, 0.0f));
cubes[1].matrices.model = glm::translate(glm::mat4(1.0f), glm::vec3(1.5f, 0.5f, 0.0f));
for (auto& cube : cubes) {
cube.matrices.projection = camera.matrices.perspective;
cube.matrices.view = camera.matrices.view;
cube.matrices.model = glm::rotate(cube.matrices.model, glm::radians(cube.rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
cube.matrices.model = glm::rotate(cube.matrices.model, glm::radians(cube.rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
cube.matrices.model = glm::rotate(cube.matrices.model, glm::radians(cube.rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
memcpy(cube.uniformBuffer.mapped, &cube.matrices, sizeof(cube.matrices));
}
}
void prepare() override {
ExampleBase::prepare();
prepareUniformBuffers();
setupDescriptors();
preparePipelines();
buildCommandBuffers();
prepared = true;
}
void update(float deltaTime) override {
if (animate) {
cubes[0].rotation.x += 2.5f * frameTimer;
if (cubes[0].rotation.x > 360.0f)
cubes[0].rotation.x -= 360.0f;
cubes[1].rotation.y += 2.0f * frameTimer;
if (cubes[1].rotation.x > 360.0f)
cubes[1].rotation.x -= 360.0f;
viewUpdated = true;
}
ExampleBase::update(deltaTime);
}
void viewChanged() override { updateUniformBuffers(); }
void OnUpdateUIOverlay() override {
if (ui.header("Settings")) {
ui.checkBox("Animate", &animate);
}
}
};
VULKAN_EXAMPLE_MAIN()
| 40.647687 | 157 | 0.601471 | harskish |
e05f0e003cec62d237f36c821b18874dde622368 | 1,398 | cxx | C++ | src/Message.cxx | krafczyk/ArgParse | 0ff6f17d028a56da3478dfe8eec1b40f4d584fce | [
"MIT"
] | 1 | 2019-03-10T18:38:51.000Z | 2019-03-10T18:38:51.000Z | src/Message.cxx | krafczyk/ArgParse | 0ff6f17d028a56da3478dfe8eec1b40f4d584fce | [
"MIT"
] | null | null | null | src/Message.cxx | krafczyk/ArgParse | 0ff6f17d028a56da3478dfe8eec1b40f4d584fce | [
"MIT"
] | null | null | null | #include <cstdarg>
#include "ArgParse/Message.h"
namespace ArgParse {
std::string currentMessage = "";
FILE* STDOUT_Channel = stdout;
FILE* STDERR_Channel = stderr;
int DebugLevel = -1;
bool Color = true;
const std::string& GetMessage() {
return currentMessage;
}
void SetMessage(const std::string& message) {
currentMessage = message;
}
int _vscprintf (const char* format, va_list pargs) {
int retval;
va_list argcopy;
va_copy(argcopy, pargs);
retval = vsnprintf(nullptr, 0, format, argcopy);
va_end(argcopy);
return retval;
}
void SetMessage(const char* format, ...) {
va_list argptr;
va_start(argptr, format);
int the_length = _vscprintf(format, argptr)+1;
char buffer[the_length];
vsprintf(buffer, format, argptr);
va_end(argptr);
currentMessage = buffer;
}
void SetSTDOUTChannel(FILE* stdout_channel) {
STDOUT_Channel = stdout_channel;
}
void SetSTDERRChannel(FILE* stderr_channel) {
STDERR_Channel = stderr_channel;
}
void MessageStandardPrint(const char* format, ...) {
if(STDOUT_Channel != nullptr) {
va_list argptr;
va_start(argptr, format);
vfprintf(STDOUT_Channel, format, argptr);
va_end(argptr);
}
}
void MessageErrorPrint(const char* format, ...) {
if(STDERR_Channel != nullptr) {
va_list argptr;
va_start(argptr, format);
vfprintf(STDERR_Channel, format, argptr);
va_end(argptr);
}
}
}
| 21.507692 | 53 | 0.702432 | krafczyk |
e0611582d2ae2383e1455983130a81b56f6bf90f | 3,899 | cpp | C++ | tests/testOpenAddressingHash.cpp | tellproject/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 49 | 2015-09-30T13:02:31.000Z | 2022-03-23T01:12:42.000Z | tests/testOpenAddressingHash.cpp | ngaut/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 1 | 2016-07-18T03:21:56.000Z | 2016-07-27T05:07:29.000Z | tests/testOpenAddressingHash.cpp | ngaut/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 10 | 2016-02-25T15:46:13.000Z | 2020-07-02T10:21:24.000Z | /*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <mpilman@inf.ethz.ch>
* Simon Loesing <sloesing@inf.ethz.ch>
* Thomas Etter <etterth@gmail.com>
* Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
* Lucas Braun <braunl@inf.ethz.ch>
*/
#include <util/OpenAddressingHash.hpp>
#include <gtest/gtest.h>
using namespace tell::store;
namespace {
class OpenAddressingTableTest : public ::testing::Test {
protected:
OpenAddressingTableTest()
: mTable(1024),
mElement1(0x1u), mElement2(0x2u), mElement3(0x3u) {
}
OpenAddressingTable mTable;
uint64_t mElement1;
uint64_t mElement2;
uint64_t mElement3;
};
/**
* @class OpenAddressingTable
* @test Check if a simple get after insert returns the element
*/
TEST_F(OpenAddressingTableTest, insertAndGet) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if multiple get and inserts return the correct elements
*/
TEST_F(OpenAddressingTableTest, insertAndGetMultiple) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_TRUE(mTable.insert(10u, 12u, &mElement2));
EXPECT_TRUE(mTable.insert(11u, 11u, &mElement3));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
EXPECT_EQ(&mElement2, mTable.get(10u, 12u));
EXPECT_EQ(&mElement3, mTable.get(11u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if inserting a duplicate fails
*/
TEST_F(OpenAddressingTableTest, insertDuplicate) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.insert(10u, 11u, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing an element works correctly
*/
TEST_F(OpenAddressingTableTest, erase) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
EXPECT_TRUE(mTable.erase(10u, 11u, &mElement1));
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing a non existing element works
*/
TEST_F(OpenAddressingTableTest, eraseNonExisting) {
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
EXPECT_TRUE(mTable.erase(10u, 11u, &mElement1));
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing a changed element is prevented
*/
TEST_F(OpenAddressingTableTest, eraseChanged) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.erase(10u, 11u, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if updating an element works
*/
TEST_F(OpenAddressingTableTest, update) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_TRUE(mTable.update(10u, 11u, &mElement1, &mElement2));
EXPECT_EQ(&mElement2, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if updating a changed element is prevented
*/
TEST_F(OpenAddressingTableTest, updateChanged) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.update(10u, 11u, &mElement3, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
}
| 28.459854 | 88 | 0.710439 | tellproject |
e0662402ab66259e863a37cf175454d66072fc87 | 3,947 | cpp | C++ | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_messages/message_handlers/message_synchronized_source.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 5 | 2020-03-11T14:36:13.000Z | 2021-09-09T09:01:15.000Z | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_messages/message_handlers/message_synchronized_source.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 1 | 2020-06-07T17:25:04.000Z | 2020-07-15T07:36:10.000Z | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_messages/message_handlers/message_synchronized_source.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 2 | 2020-11-30T08:17:53.000Z | 2021-06-19T05:07:07.000Z | #include "message_synchronized_source.h"
#include "message_pack.h"
#include "srrg_system_utils/shell_colors.h"
namespace srrg2_core {
void MessageSynchronizedSource::clearBuffer() {
// we delete all messages in the buffers
for (auto it = _message_map.begin(); it != _message_map.end(); ++it) {
if (it->second) {
it->second.reset();
}
}
}
void MessageSynchronizedSource::handleTopicsChanged() {
resetCounters();
clearBuffer();
_message_map.clear();
for (size_t i = 0; i < param_topics.size(); ++i) {
const std::string& t = param_topics.value(i);
_message_map.insert(std::make_pair(t, nullptr));
}
_topics_changed = false;
_seq = 0;
}
void MessageSynchronizedSource::handleIntervalChanged() {
resetCounters();
_interval_changed = false;
}
MessageSynchronizedSource::MessageSynchronizedSource() {
std::cerr << RED << className() << "| is deprecated. Please revise your pipeline using sinks"
<< RESET << std::endl;
}
BaseSensorMessagePtr MessageSynchronizedSource::getMessage() {
// std::cerr << __PRETTY_FUNCTION__ << std::endl;
assert(param_source.value() && "you need to set a valid source");
MessageSourceBasePtr src = param_source.value();
if (_topics_changed) {
// std::cerr << "topics changed" << std::endl;
handleTopicsChanged();
}
if (_interval_changed) {
// std::cerr << "interval changed" << std::endl;
handleIntervalChanged();
}
while (!isPacketReady()) {
BaseSensorMessagePtr msg = src->getMessage();
if (!msg) {
// std::cerr << __PRETTY_FUNCTION__ << ": source ova" << std::endl;
return nullptr;
}
// std::cerr << "got msg " << msg->topic.value() << std::endl;
// find a bucket;
auto it = _message_map.find(msg->topic.value());
if (it == _message_map.end()) {
// std::cerr << "msg not map, deleting " << std::endl;
// delete msg;
msg.reset();
continue;
}
// we assume the message is more recent than the previous
// one and we replace it
if (it->second) {
// std::cerr << "replacing old msg " << it->second->timestamp.value() << std::endl;
++_num_dropped_messages;
// delete it->second;
it->second.reset();
}
it->second = msg;
// std::cerr << "new ts: " << it->second->timestamp.value() << std::endl;
}
// we come here if all messages are synchronized
// we need to assemble them in a packet
// in the order of the topics
MessagePack* pack =
new MessagePack(param_output_topic.value(), param_output_frame_id.value(), _seq, _t_min);
for (size_t i = 0; i < param_topics.size(); ++i) {
const std::string& t = param_topics.value(i);
auto it = _message_map.find(t);
assert(it != _message_map.end() && "no messge in map");
assert(it->second && "invalid pointer");
pack->messages.push_back(BaseSensorMessagePtr(it->second));
it->second = 0;
}
++_seq;
return BaseSensorMessagePtr(pack);
}
bool MessageSynchronizedSource::isPacketReady() {
_t_min = std::numeric_limits<double>::max();
_t_max = 0;
// a pack is ready if the lag between t_max and t_min is below time_interval
for (auto it = _message_map.begin(); it != _message_map.end(); ++it) {
if (!it->second) {
return false;
}
_t_min = std::min(_t_min, it->second->timestamp.value());
_t_max = std::max(_t_max, it->second->timestamp.value());
}
return (_t_max - _t_min) < param_time_interval.value();
}
void MessageSynchronizedSource::resetCounters() {
_num_dropped_messages = 0;
}
void MessageSynchronizedSource::reset() {
handleTopicsChanged();
_seq = 0;
MessageFilterBase::reset();
}
} // namespace srrg2_core
| 32.891667 | 98 | 0.60375 | laaners |
e068180c7c3841ca885196dbf2f2d2d7fd0b2bac | 4,729 | cpp | C++ | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | // -*- C++ -*-
/*!
* @file VolumeAdjust.cpp
* @brief ModuleDescription
* @date $Date$
*
* $Id$
*/
#include "VolumeAdjust.h"
// Module specification
// <rtc-template block="module_spec">
static const char* volumeadjust_spec[] =
{
"implementation_id", "VolumeAdjust",
"type_name", "VolumeAdjust",
"description", "ModuleDescription",
"version", "1.0.0",
"vendor", "VenderName",
"category", "Category",
"activity_type", "PERIODIC",
"kind", "DataFlowComponent",
"max_instance", "1",
"language", "C++",
"lang_type", "compile",
// Configuration variables
"conf.default.base", "4.5",
// Widget
"conf.__widget__.base", "text",
// Constraints
"conf.__type__.base", "double",
""
};
// </rtc-template>
/*!
* @brief constructor
* @param manager Maneger Object
*/
VolumeAdjust::VolumeAdjust(RTC::Manager* manager)
// <rtc-template block="initializer">
: RTC::DataFlowComponentBase(manager),
m_accIn("acc", m_acc),
m_baseaccIn("baseacc", m_baseacc),
m_volumesetOut("volumeset", m_volumeset)
// </rtc-template>
{
}
/*!
* @brief destructor
*/
VolumeAdjust::~VolumeAdjust()
{
}
RTC::ReturnCode_t VolumeAdjust::onInitialize()
{
// Registration: InPort/OutPort/Service
// <rtc-template block="registration">
// Set InPort buffers
addInPort("acc", m_accIn);
addInPort("baseacc", m_baseaccIn);
// Set OutPort buffer
addOutPort("volumeset", m_volumesetOut);
// Set service provider to Ports
// Set service consumers to Ports
// Set CORBA Service Ports
// </rtc-template>
// <rtc-template block="bind_config">
// Bind variables and configuration variable
bindParameter("base", m_base, "4.5");
// </rtc-template>
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t VolumeAdjust::onFinalize()
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onStartup(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onShutdown(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
RTC::ReturnCode_t VolumeAdjust::onActivated(RTC::UniqueId ec_id)
{
count = 1;
memset(data, 0, sizeof(data));
basedata = m_base;
return RTC::RTC_OK;
}
RTC::ReturnCode_t VolumeAdjust::onDeactivated(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
RTC::ReturnCode_t VolumeAdjust::onExecute(RTC::UniqueId ec_id)
{
if(m_accIn.isNew())
{
m_accIn.read();
accdata = m_acc.data;
if(count<(sizeof(data)/sizeof(data[0]))){
count += 1;
}else{
count = 1;
}
data[count] = accdata;
std::cout<<"accdata"<<accdata<<std::endl;
sum = 0;
ave= 0;
for(i=0;i<(sizeof(data)/sizeof(data[0]));i++){
sum += data[i];
}
ave = sum/(sizeof(data)/sizeof(data[0]));
changedata = ave*100/(basedata*2);
if(0<=changedata && changedata<=5){m_volumeset.data = 0;}
else if(5<changedata && changedata<=15){m_volumeset.data = 10;}
else if(15<changedata && changedata<=25){m_volumeset.data = 20;}
else if(25<changedata && changedata<=35){m_volumeset.data = 30;}
else if(35<changedata && changedata<=45){m_volumeset.data = 40;}
else if(45<changedata && changedata<=55){m_volumeset.data = 50;}
else if(55<changedata && changedata<=65){m_volumeset.data = 60;}
else if(65<changedata && changedata<=75){m_volumeset.data = 70;}
else if(75<changedata && changedata<=85){m_volumeset.data = 80;}
else if(85<changedata && changedata<=95){m_volumeset.data = 90;}
else if(95<changedata){m_volumeset.data = 100;}
std::cout<<"set volume :"<< m_volumeset.data <<std::endl;
m_volumesetOut.write();
}
if(m_baseaccIn.isNew())
{
m_baseaccIn.read();
basedata = m_baseacc.data;
}
if(basedata == 0){
return RTC::RTC_ERROR;
}
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t VolumeAdjust::onAborting(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onError(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onReset(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onStateUpdate(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onRateChanged(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
extern "C"
{
void VolumeAdjustInit(RTC::Manager* manager)
{
coil::Properties profile(volumeadjust_spec);
manager->registerFactory(profile,
RTC::Create<VolumeAdjust>,
RTC::Delete<VolumeAdjust>);
}
};
| 20.383621 | 70 | 0.618524 | rsdlab |
e06d0ef15d477fc966c299c097764754af0b4205 | 615 | cpp | C++ | base/fs/sis/groveler/debug.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/fs/sis/groveler/debug.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/fs/sis/groveler/debug.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998 Microsoft Corporation
Module Name:
debug.cpp
Abstract:
SIS Groveler debug print file
Authors:
John Douceur, 1998
Cedric Krumbein, 1998
Environment:
User Mode
Revision History:
--*/
#include "all.hxx"
#if DBG
VOID __cdecl PrintDebugMsg(
TCHAR *format,
...)
{
TCHAR debugStr[1024];
va_list ap;
HRESULT r;
va_start(ap, format);
r = StringCbVPrintf(debugStr, sizeof(debugStr), format, ap);
ASSERT(r == S_OK);
OutputDebugString(debugStr);
va_end(ap);
}
#endif // DBG
| 12.8125 | 65 | 0.585366 | npocmaka |
e0704e8caad5741d51be04513041d9bf2654efc7 | 725 | cc | C++ | base/profiler/stack_sampler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | base/profiler/stack_sampler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 802 | 2017-04-21T14:18:36.000Z | 2022-03-31T21:20:48.000Z | base/profiler/stack_sampler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/profiler/stack_sampler.h"
#include "base/memory/ptr_util.h"
#include "base/profiler/stack_buffer.h"
namespace base {
StackSampler::StackSampler() = default;
StackSampler::~StackSampler() = default;
std::unique_ptr<StackBuffer> StackSampler::CreateStackBuffer() {
size_t size = GetStackBufferSize();
if (size == 0)
return nullptr;
return std::make_unique<StackBuffer>(size);
}
StackSamplerTestDelegate::~StackSamplerTestDelegate() = default;
StackSamplerTestDelegate::StackSamplerTestDelegate() = default;
} // namespace base
| 25.892857 | 73 | 0.758621 | zealoussnow |
2fda1fbec701c99d237ea4c2bb3ff1f8226e6107 | 19,329 | cpp | C++ | sp/src/game/server/hl2/prop_gravity_ball.cpp | ntrf/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 12 | 2016-09-24T02:47:18.000Z | 2020-12-29T16:16:52.000Z | sp/src/game/server/hl2/prop_gravity_ball.cpp | Margen67/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 31 | 2016-11-27T14:38:02.000Z | 2020-06-03T11:11:29.000Z | sp/src/game/server/hl2/prop_gravity_ball.cpp | Margen67/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 3 | 2016-09-24T16:08:44.000Z | 2020-12-30T00:59:58.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: TE120 combine ball - launched by physconcussion
//
//
//=============================================================================//
#include "cbase.h"
#include "prop_combine_ball.h"
#include "prop_gravity_ball.h"
#include "props.h"
#include "explode.h"
#include "saverestore_utlvector.h"
#include "hl2_shareddefs.h"
#include "materialsystem/imaterial.h"
#include "beam_flags.h"
#include "physics_prop_ragdoll.h"
#include "soundent.h"
#include "soundenvelope.h"
#include "te_effect_dispatch.h"
#include "ai_basenpc.h"
#include "npc_bullseye.h"
#include "filters.h"
#include "SpriteTrail.h"
#include "decals.h"
#include "hl2_player.h"
#include "eventqueue.h"
#include "physics_collisionevent.h"
#include "gamestats.h"
#include "weapon_physcannon.h"
#include "util.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define PROP_GRAVITY_BALL_MODEL "models/effects/combineball.mdl"
#define PROP_GRAVITY_BALL_SPRITE_TRAIL "sprites/combineball_trail_black_1.vmt"
ConVar gravityball_tracelength( "gravityball_tracelength", "128" );
ConVar gravityball_magnitude( "gravityball_magnitude", "1.07f" );
ConVar gravityball_knockback("gravityball_knockback", "26000.0f");
ConVar gravityball_ignorewalls("gravityball_ignorewalls", "0", FCVAR_NOTIFY);
ConVar gravityball_response("gravityball_response", "2", FCVAR_NOTIFY);
// For our ring explosion
int s_nExplosionGBTexture = -1;
//-----------------------------------------------------------------------------
// Context think
//-----------------------------------------------------------------------------
static const char *s_pRemoveContext = "RemoveContext";
//-----------------------------------------------------------------------------
// Purpose:
// Input : radius -
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CreateGravityBall(const Vector &origin, const Vector &velocity, float radius, float mass, float lifetime, CBaseEntity *pOwner, class CWeaponPhysCannon *pWeapon)
{
CPropGravityBall *pBall = static_cast<CPropGravityBall*>( CreateEntityByName( "prop_gravity_ball" ) );
pBall->m_pWeaponPC = pWeapon;
pBall->SetRadius( radius );
pBall->SetAbsOrigin( origin );
pBall->SetOwnerEntity( pOwner );
pBall->SetOriginalOwner( pOwner );
pBall->SetAbsVelocity( velocity );
pBall->Spawn();
pBall->SetState( CPropCombineBall::STATE_THROWN );
pBall->SetSpeed( velocity.Length() );
pBall->EmitSound( "NPC_GravityBall.Launch" );
PhysSetGameFlags( pBall->VPhysicsGetObject(), FVPHYSICS_WAS_THROWN );
pBall->StartWhizSoundThink();
pBall->SetMass( mass );
pBall->StartLifetime( lifetime );
pBall->SetWeaponLaunched( true );
pBall->SetModel( PROP_GRAVITY_BALL_MODEL );
return pBall;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is a combine ball or not
// Input : *pObj - Object to test
// Output : Returns true on success, false on failure.
// Notes : This function cannot identify a combine ball that is held by
// the physcannon because any object held by the physcannon is
// COLLISIONGROUP_DEBRIS.
//-----------------------------------------------------------------------------
bool UTIL_IsGravityBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is an AR2 combine ball or not
// Input : *pEntity -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsAR2GravityBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
CPropGravityBall *pBall = dynamic_cast<CPropGravityBall *>(pEntity);
if ( pBall && pBall->WasWeaponLaunched() )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Uses a deeper casting check to determine if pEntity is a combine
// ball. This function exists because the normal (much faster) check
// in UTIL_IsCombineBall() can never identify a combine ball held by
// the physcannon because the physcannon changes the held entity's
// collision group.
// Input : *pEntity - Entity to check
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsGravityBallDefinite( CBaseEntity *pEntity )
{
CPropGravityBall *pBall = dynamic_cast<CPropGravityBall *>(pEntity);
return pBall != NULL;
}
//-----------------------------------------------------------------------------
// Implementation of CPropCombineBall
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( prop_gravity_ball, CPropGravityBall );
//-----------------------------------------------------------------------------
// Save/load:
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CPropGravityBall )
DEFINE_FIELD( m_flLastBounceTime, FIELD_TIME ),
DEFINE_FIELD( m_flRadius, FIELD_FLOAT ),
DEFINE_FIELD( m_nState, FIELD_CHARACTER ),
DEFINE_FIELD( m_pGlowTrail, FIELD_CLASSPTR ),
DEFINE_SOUNDPATCH( m_pHoldingSound ),
DEFINE_FIELD( m_bFiredGrabbedOutput, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bEmit, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bHeld, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bStruckEntity, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bWeaponLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForward, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flNextDamageTime, FIELD_TIME ),
DEFINE_FIELD( m_flLastCaptureTime, FIELD_TIME ),
DEFINE_FIELD( m_bCaptureInProgress, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nBounceCount, FIELD_INTEGER ),
DEFINE_FIELD( m_nMaxBounces, FIELD_INTEGER ),
DEFINE_FIELD( m_bBounceDie, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hSpawner, FIELD_EHANDLE ),
DEFINE_THINKFUNC( ExplodeThink ),
DEFINE_THINKFUNC( WhizSoundThink ),
DEFINE_THINKFUNC( DieThink ),
DEFINE_THINKFUNC( DissolveThink ),
DEFINE_THINKFUNC( DissolveRampSoundThink ),
DEFINE_THINKFUNC( AnimThink ),
DEFINE_THINKFUNC( CaptureBySpawner ),
DEFINE_INPUTFUNC( FIELD_VOID, "Explode", InputExplode ),
DEFINE_INPUTFUNC( FIELD_VOID, "FadeAndRespawn", InputFadeAndRespawn ),
DEFINE_INPUTFUNC( FIELD_VOID, "Kill", InputKill ),
DEFINE_INPUTFUNC( FIELD_VOID, "Socketed", InputSocketed ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CPropGravityBall, DT_PropGravityBall )
SendPropBool( SENDINFO( m_bEmit ) ),
SendPropFloat( SENDINFO( m_flRadius ), 0, SPROP_NOSCALE ),
SendPropBool( SENDINFO( m_bHeld ) ),
SendPropBool( SENDINFO( m_bLaunched ) ),
END_SEND_TABLE()
//-----------------------------------------------------------------------------
// Precache
//-----------------------------------------------------------------------------
void CPropGravityBall::Precache( void )
{
// NOTENOTE: We don't call into the base class because it chains multiple
// precaches we don't need to incur
PrecacheModel( PROP_GRAVITY_BALL_MODEL );
PrecacheModel( PROP_GRAVITY_BALL_SPRITE_TRAIL);
s_nExplosionGBTexture = PrecacheModel( "sprites/lgtning.vmt" );
PrecacheScriptSound( "NPC_GravityBall.Launch" );
PrecacheScriptSound( "NPC_GravityBall.Explosion" );
PrecacheScriptSound( "NPC_GravityBall.WhizFlyby" );
if ( hl2_episodic.GetBool() )
{
PrecacheScriptSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
PrecacheScriptSound( "NPC_CombineBall.Impact" );
}
}
//-----------------------------------------------------------------------------
// Spawn:
//-----------------------------------------------------------------------------
void CPropGravityBall::Spawn( void )
{
CBaseAnimating::Spawn();
SetModel( PROP_GRAVITY_BALL_MODEL );
if( ShouldHitPlayer() )
{
// This allows the combine ball to hit the player.
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL_NPC );
}
else
{
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL );
}
CreateVPhysics();
Vector vecAbsVelocity = GetAbsVelocity();
VPhysicsGetObject()->SetVelocity( &vecAbsVelocity, NULL );
m_nState = STATE_NOT_THROWN;
m_flLastBounceTime = -1.0f;
m_bFiredGrabbedOutput = false;
m_bForward = true;
m_bCaptureInProgress = false;
// No shadow!
AddEffects( EF_NOSHADOW );
// Start up the eye trail
CSpriteTrail *pGlowTrail = CSpriteTrail::SpriteTrailCreate( PROP_GRAVITY_BALL_SPRITE_TRAIL, GetAbsOrigin(), false );
m_pGlowTrail = pGlowTrail;
if ( pGlowTrail != NULL )
{
pGlowTrail->FollowEntity( this );
pGlowTrail->SetTransparency( kRenderTransAdd, 0, 0, 0, 255, kRenderFxNone );
pGlowTrail->SetStartWidth( m_flRadius );
pGlowTrail->SetEndWidth( 0 );
pGlowTrail->SetLifeTime( 0.1f );
pGlowTrail->TurnOff();
}
m_bEmit = true;
m_bHeld = false;
m_bLaunched = false;
m_bStruckEntity = false;
m_bWeaponLaunched = false;
m_flNextDamageTime = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Create vphysics
//-----------------------------------------------------------------------------
bool CPropGravityBall::CreateVPhysics()
{
SetSolid( SOLID_BBOX );
float flSize = m_flRadius;
SetCollisionBounds( Vector(-flSize, -flSize, -flSize), Vector(flSize, flSize, flSize) );
objectparams_t params = g_PhysDefaultObjectParams;
params.pGameData = static_cast<void *>(this);
int nMaterialIndex = physprops->GetSurfaceIndex("metal_bouncy");
IPhysicsObject *pPhysicsObject = physenv->CreateSphereObject( flSize, nMaterialIndex, GetAbsOrigin(), GetAbsAngles(), ¶ms, false );
if ( !pPhysicsObject )
return false;
VPhysicsSetObject( pPhysicsObject );
SetMoveType( MOVETYPE_VPHYSICS );
pPhysicsObject->Wake();
pPhysicsObject->SetMass( 750.0f );
pPhysicsObject->EnableGravity( false );
pPhysicsObject->EnableDrag( false );
float flDamping = 0.0f;
float flAngDamping = 0.5f;
pPhysicsObject->SetDamping( &flDamping, &flAngDamping );
pPhysicsObject->SetInertia( Vector( 1e30, 1e30, 1e30 ) );
PhysSetGameFlags( pPhysicsObject, FVPHYSICS_NO_NPC_IMPACT_DMG );
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::DoImpactEffect( const Vector &preVelocity, int index, gamevcollisionevent_t *pEvent )
{
// Do that crazy impact effect!
trace_t tr;
CollisionEventToTrace( !index, pEvent, tr );
CBaseEntity *pTraceEntity = pEvent->pEntities[index];
UTIL_TraceLine( tr.startpos - preVelocity * 2.0f, tr.startpos + preVelocity * 2.0f, MASK_SOLID, pTraceEntity, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0f )
{
// See if we hit the sky
if ( tr.surface.flags & SURF_SKY )
{
DoExplosion();
return;
}
// Send the effect over
CEffectData data;
data.m_flRadius = 16;
data.m_vNormal = tr.plane.normal;
data.m_vOrigin = tr.endpos + tr.plane.normal * 1.0f;
DispatchEffect( "gball_bounce", data );
// We need to affect ragdolls on the client
CEffectData dataRag;
dataRag.m_vOrigin = GetAbsOrigin();
dataRag.m_flRadius = gravityball_tracelength.GetFloat();
dataRag.m_flMagnitude = 1.0f;
DispatchEffect( "RagdollConcussion", dataRag );
}
if ( hl2_episodic.GetBool() )
{
EmitSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
EmitSound( "NPC_CombineBall.Impact" );
}
}
//-----------------------------------------------------------------------------
// Lighten the mass so it's zippy toget to the gun
//-----------------------------------------------------------------------------
void CPropGravityBall::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
{
/* Do nothing, don't want to allow phys gun pickup. */
CDefaultPlayerPickupVPhysics::OnPhysGunPickup( pPhysGunUser, reason );
}
//------------------------------------------------------------------------------
// Pow!
//------------------------------------------------------------------------------
void CPropGravityBall::DoExplosion( )
{
// don't do this twice
if ( GetMoveType() == MOVETYPE_NONE )
return;
if ( PhysIsInCallback() )
{
g_PostSimulationQueue.QueueCall( this, &CPropGravityBall::DoExplosion );
return;
}
//Shockring
CBroadcastRecipientFilter filter2;
EmitSound( "NPC_GravityBall.Explosion" );
UTIL_ScreenShake( GetAbsOrigin(), 20.0f, 150.0, 1.0, 1250.0f, SHAKE_START );
CEffectData data;
data.m_vOrigin = GetAbsOrigin();
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
gravityball_tracelength.GetFloat() + 128.0, //end radius
s_nExplosionGBTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.2f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
32, //a
0, //speed
FBEAM_FADEOUT
);
//Shockring
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
gravityball_tracelength.GetFloat() + 128.0, //end radius
s_nExplosionGBTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.5f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
64, //a
0, //speed
FBEAM_FADEOUT
);
if( hl2_episodic.GetBool() )
{
CSoundEnt::InsertSound( SOUND_COMBAT | SOUND_CONTEXT_EXPLOSION, WorldSpaceCenter(), 180.0f, 0.25, this );
}
// Turn us off and wait because we need our trails to finish up properly
SetAbsVelocity( vec3_origin );
SetMoveType( MOVETYPE_NONE );
AddSolidFlags( FSOLID_NOT_SOLID );
SetEmitState( false );
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player *>( GetOwnerEntity() );
if( !m_bStruckEntity && hl2_episodic.GetBool() && GetOwnerEntity() != NULL )
{
// Notify the player proxy that this combine ball missed so that it can fire an output.
if ( pPlayer )
{
pPlayer->MissedAR2AltFire();
}
}
SetContextThink( &CPropCombineBall::SUB_Remove, gpGlobals->curtime + 0.5f, s_pRemoveContext );
StopLoopingSounds();
// Gravity Push these mofos
CBaseEntity *list[512]; // An array to store all the nearby gravity affected entities
Vector start, end, forward; // Vectors for traces if valid entity
CBaseEntity *pEntity;
int count = UTIL_EntitiesInSphere(list, 512, GetAbsOrigin(), gravityball_tracelength.GetFloat(), 0);
start = GetAbsOrigin();
// Make sure we're not in the ground
if (UTIL_PointContents(start) & CONTENTS_SOLID)
start.z += 1;
// Loop through each entity and apply a force
for ( int i = 0; i < count; i++ )
{
// Make sure the entity is valid or not itself or not the firing weapon
pEntity = list[i];
// Make sure the entity is valid or not itself or not the firing weapon
if ( !pEntity || pEntity == this || pEntity == (CBaseEntity*)this->m_pWeaponPC )
continue;
// Make sure its a gravity touchable entity
if ( (pEntity->IsEFlagSet( EFL_NO_PHYSCANNON_INTERACTION ) || pEntity->GetMoveType() != MOVETYPE_VPHYSICS) && ( pEntity->m_takedamage == DAMAGE_NO ) )
{
continue;
}
// Check that the explosion can 'see' this entity.
end = pEntity->BodyTarget(start, false);
// direction of flight
forward = end - start;
// Skew the z direction upward
//forward.z += 44.0f;
trace_t tr;
UTIL_TraceLine(start, end, (MASK_SHOT | CONTENTS_GRATE), pEntity, COLLISION_GROUP_NONE, &tr);
// debugoverlay->AddLineOverlay( start, end, 0,255,0, true, 18.0 );
if (!gravityball_ignorewalls.GetBool() && !pEntity->IsPlayer() && tr.fraction != 1.0 && tr.m_pEnt != pEntity && !tr.allsolid)
continue;
if (pEntity->IsPlayer()) {
Vector fbellow = pEntity->GetAbsOrigin();
Vector fabove = fbellow;
fabove.z += 2.0f;
trace_t ptr;
UTIL_TraceLine(fbellow, fabove, MASK_PLAYERSOLID, pEntity, COLLISION_GROUP_NONE, &ptr);
if (ptr.startsolid)
forward.z += 44.0f;
}
// normalizing the vector
float len = forward.Length();
if (gravityball_response.GetInt() == 1) {
float pow_x = clamp(len / gravityball_tracelength.GetFloat(), 0.0f, 1.0f);
float pow_y = 1.0f - pow_x * pow_x;
forward *= pow_y * gravityball_magnitude.GetFloat() / len;
} else if (gravityball_response.GetInt() == 2) {
float pow_x = clamp(len / gravityball_tracelength.GetFloat(), 0.5f, 1.0f);
forward *= pow_x / len;
} else {
forward /= gravityball_tracelength.GetFloat();
}
forward *= gravityball_magnitude.GetFloat();
// DevMsg("Found valid gravity entity %s / forward %f %f %f\n", pEntity->GetClassname(),
// forward.x, forward.y, forward.z);
// Punt Non VPhysics Objects
if ( pEntity->GetMoveType() != MOVETYPE_VPHYSICS )
{
// Amplify the height of the push
forward.z *= 1.4f;
if ( pEntity->IsNPC() && !pEntity->IsEFlagSet( EFL_NO_MEGAPHYSCANNON_RAGDOLL ) && pEntity->MyNPCPointer()->CanBecomeRagdoll() )
{
// Necessary to cause it to do the appropriate death cleanup
Vector force = forward * gravityball_knockback.GetFloat();
CTakeDamageInfo ragdollInfo(pPlayer, pPlayer, force, end, 10000.0, DMG_PHYSGUN | DMG_BLAST);
pEntity->TakeDamage( ragdollInfo );
}
else if ( m_pWeaponPC )
{
PhysCannon_PuntConcussionNonVPhysics(m_pWeaponPC, pEntity, forward, tr);
}
}
else
{
if (PhysCannonEntityAllowsPunts(m_pWeaponPC, pEntity) == false )
{
continue;
}
if ( dynamic_cast<CRagdollProp*>(pEntity) )
{
// Amplify the height of the push
forward.z *= 1.4f;
if ( m_pWeaponPC )
PhysCannon_PuntConcussionRagdoll(m_pWeaponPC, pEntity, forward, tr);
}
else if ( m_pWeaponPC )
{
PhysCannon_PuntConcussionVPhysics(m_pWeaponPC, pEntity, forward, tr);
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPropGravityBall::IsHittableEntity( CBaseEntity *pHitEntity )
{
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::OnHitEntity( CBaseEntity *pHitEntity, float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
DoExplosion();
}
//-----------------------------------------------------------------------------
// Deflects the ball toward enemies in case of a collision
//-----------------------------------------------------------------------------
void CPropGravityBall::DeflectTowardEnemy( float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
/* Do nothing, we just want this to explode. */
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
{
CPropCombineBall::VPhysicsCollision( index, pEvent );
DoExplosion();
}
| 31.429268 | 173 | 0.62326 | ntrf |
2fdac9740de9a531064d3bb538a3891c02f81bb8 | 3,167 | cc | C++ | chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.h"
#include "components/autofill/core/browser/metrics/autofill_metrics.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill {
AutofillProgressDialogControllerImpl::AutofillProgressDialogControllerImpl(
content::WebContents* web_contents)
: web_contents_(web_contents) {}
AutofillProgressDialogControllerImpl::~AutofillProgressDialogControllerImpl() {
if (autofill_progress_dialog_view_) {
autofill_progress_dialog_view_->Dismiss(
/*show_confirmation_before_closing=*/false,
/*is_canceled_by_user=*/true);
autofill_progress_dialog_view_ = nullptr;
}
}
void AutofillProgressDialogControllerImpl::ShowDialog(
base::OnceClosure cancel_callback) {
DCHECK(!autofill_progress_dialog_view_);
cancel_callback_ = std::move(cancel_callback);
autofill_progress_dialog_view_ =
AutofillProgressDialogView::CreateAndShow(this);
if (autofill_progress_dialog_view_)
// TODO(crbug.com/1261529): Pass in the flow type once we have another use
// case so that the progress dialog can be shared across multiple use cases.
AutofillMetrics::LogProgressDialogShown();
}
void AutofillProgressDialogControllerImpl::DismissDialog(
bool show_confirmation_before_closing) {
if (!autofill_progress_dialog_view_)
return;
autofill_progress_dialog_view_->Dismiss(show_confirmation_before_closing,
/*is_canceled_by_user=*/false);
autofill_progress_dialog_view_ = nullptr;
}
void AutofillProgressDialogControllerImpl::OnDismissed(
bool is_canceled_by_user) {
// Dialog is being dismissed so set the pointer to nullptr.
autofill_progress_dialog_view_ = nullptr;
if (is_canceled_by_user)
std::move(cancel_callback_).Run();
// TODO(crbug.com/1261529): Pass in the flow type once we have another use
// case so that the progress dialog can be shared across multiple use cases.
AutofillMetrics::LogProgressDialogResultMetric(is_canceled_by_user);
cancel_callback_.Reset();
}
const std::u16string AutofillProgressDialogControllerImpl::GetTitle() {
return l10n_util::GetStringUTF16(IDS_AUTOFILL_CARD_UNMASK_PROMPT_TITLE_V2);
}
const std::u16string
AutofillProgressDialogControllerImpl::GetCancelButtonLabel() {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_CANCEL_BUTTON_LABEL);
}
const std::u16string AutofillProgressDialogControllerImpl::GetLoadingMessage() {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROGRESS_BAR_MESSAGE);
}
const std::u16string
AutofillProgressDialogControllerImpl::GetConfirmationMessage() {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_CONFIRMATION_MESSAGE);
}
content::WebContents* AutofillProgressDialogControllerImpl::GetWebContents() {
return web_contents_;
}
} // namespace autofill
| 35.188889 | 89 | 0.791285 | zealoussnow |
2fded95ceaec827151e12e1f6f025b3732cd03d4 | 1,323 | cpp | C++ | tree/left_view_simple_recusion.cpp | kashyap99saksham/Code | 96658d0920eb79c007701d2a3cc9dbf453d78f96 | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | tree/left_view_simple_recusion.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | tree/left_view_simple_recusion.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | /*
Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side.
left-view
Examples:
Input :
1
/ \
2 3
/ \ \
4 5 6
Output : 1 2 4
Input :
1
/ \
2 3
\
4
\
5
\
6
Output :1 2 4 5 6
*/
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
void leftViewUtil(node* root,int level, int* maxLevel){
if(!root) return;
if(*maxLevel<level){
cout<<root->data<<" ";
*maxLevel=level;
}
leftViewUtil(root->left, level+1, maxLevel);
leftViewUtil(root->right, level+1, maxLevel);
}
struct node* newNode(int value){
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->left=temp->right=NULL;
return temp;
}
void leftView(struct node* root){
int maxLevel=0;
leftViewUtil(root, 1, &maxLevel);
}
int main(){
struct node* root=newNode(1);
root->left=newNode(2);
root->right=newNode(3);
root->right->left=newNode(4);
root->right->left->right=newNode(5);
leftView(root);
return 0;
}
| 16.5375 | 131 | 0.535903 | kashyap99saksham |
2fe31bcb242a2c7da6f07b3090679706be6475a0 | 408 | cpp | C++ | Engine/Audio/_dummy/Audio_ps.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 47 | 2018-04-27T02:16:26.000Z | 2022-02-28T05:21:24.000Z | Engine/Audio/_dummy/Audio_ps.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 2 | 2018-11-13T18:46:41.000Z | 2022-03-12T00:04:44.000Z | Engine/Audio/_dummy/Audio_ps.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 6 | 2019-08-10T21:56:23.000Z | 2020-10-21T11:18:29.000Z | /****************************************************************************
// Usagi Engine, Copyright © Vitei, Inc. 2013
****************************************************************************/
#include "Engine/Common/Common.h"
#include "Audio_ps.h"
namespace usg{
Audio_ps::Audio_ps()
{
}
Audio_ps::~Audio_ps()
{
}
void Audio_ps::Init()
{
}
void Audio_ps::Update(float fElapsed)
{
}
}
| 12.75 | 77 | 0.404412 | vitei |
2fe43e6569d47f6f433679d35f420ed5e6eac3cd | 23,369 | cpp | C++ | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | 53 | 2017-11-08T06:23:47.000Z | 2022-03-25T20:14:38.000Z | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | null | null | null | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | 7 | 2018-09-07T02:27:48.000Z | 2022-03-25T20:14:40.000Z | //--------------------------------------------------------------------------//
/// Copyright (c) 2010-2016 Milos Tosic. All Rights Reserved. ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause ///
//--------------------------------------------------------------------------//
#include <rapp_pch.h>
#include <rapp/inc/rapp.h>
#include <rapp/inc/widgets/numpad_debug.h>
#include <inttypes.h>
#if RAPP_WITH_BGFX
namespace rapp {
static inline uint32_t propertyGetSize(Property::Type _type)
{
switch (_type)
{
case Property::Uint8:
case Property::Int8: return 1;
case Property::Uint16:
case Property::Int16: return 2;
case Property::Uint32:
case Property::Int32: return 4;
case Property::Uint64:
case Property::Int64: return 8;
case Property::Float: return sizeof(float);
case Property::Double: return sizeof(double);
case Property::Bool: return sizeof(bool);
case Property::Color: return 16; // 4 floats
default: return 0;
};
}
inline void propertyCopyValue(Property::Type _type, void* _dest, void* _src)
{
uint32_t copySize = propertyGetSize(_type);
if (copySize)
memcpy(_dest, _src, copySize);
}
inline bool propertyIsGreater(Property::Type _type, void* _v1, void* _v2)
{
switch (_type)
{
case Property::Int8: return *(int8_t*)_v1 > *(int8_t*)_v2;
case Property::Int16: return *(int16_t*)_v1 > *(int16_t*)_v2;
case Property::Int32: return *(int32_t*)_v1 > *(int32_t*)_v2;
case Property::Int64: return *(int64_t*)_v1 > *(int64_t*)_v2;
case Property::Uint8: return *(uint8_t*)_v1 > *(uint8_t*)_v2;
case Property::Uint16: return *(uint16_t*)_v1 > *(uint16_t*)_v2;
case Property::Uint32: return *(uint32_t*)_v1 > *(uint32_t*)_v2;
case Property::Uint64: return *(uint64_t*)_v1 > *(uint64_t*)_v2;
case Property::Float: return *(float*)_v1 > *(float*)_v2;
case Property::Double: return *(double*)_v1 > *(double*)_v2;
};
return false;
}
void propertyClamp(DebugMenu* _menu)
{
if (propertyIsGreater(_menu->m_type, _menu->m_minMax.m_min, _menu->m_value))
memcpy(_menu->m_value, _menu->m_minMax.m_min, propertyGetSize(_menu->m_type));
if (propertyIsGreater(_menu->m_type, _menu->m_value, _menu->m_minMax.m_max))
memcpy(_menu->m_value, _menu->m_minMax.m_max, propertyGetSize(_menu->m_type));
}
void propertyPrintToBuffer(ImGuiDataType _type, void* _value, char _buffer[128])
{
switch (_type)
{
case ImGuiDataType_S8: sprintf(_buffer, "%" PRId8, *(int8_t*)_value); break;
case ImGuiDataType_S16: sprintf(_buffer, "%" PRId16, *(int16_t*)_value); break;
case ImGuiDataType_S32: sprintf(_buffer, "%" PRId32, *(int32_t*)_value); break;
case ImGuiDataType_S64: sprintf(_buffer, "%" PRId64, *(int64_t*)_value); break;
case ImGuiDataType_U8: sprintf(_buffer, "%" PRIu8, *(uint8_t*)_value); break;
case ImGuiDataType_U16: sprintf(_buffer, "%" PRIu16,*(uint16_t*)_value); break;
case ImGuiDataType_U32: sprintf(_buffer, "%" PRIu32,*(uint32_t*)_value); break;
case ImGuiDataType_U64: sprintf(_buffer, "%" PRIu64,*(uint64_t*)_value); break;
case ImGuiDataType_Float: sprintf(_buffer, "%f", *(float*)_value); break;
case ImGuiDataType_Double: sprintf(_buffer, "%lf", *(double*)_value); break;
};
}
DebugMenu g_rootMenu(0, "Home");
rapp::DebugMenu* g_currentDebugMenu = 0;
void initializeMenus()
{
g_rootMenu.m_type = Property::None;
g_currentDebugMenu = &g_rootMenu;
}
DebugMenu::DebugMenu(DebugMenu* _parent, const char* _label, uint32_t _width, Property::Type _type)
: m_parent(_parent)
, m_index(0)
, m_numChildren(0)
, m_label(_label)
, m_type(_type)
, m_width(_width)
, m_customEditor(0)
, m_customPreview(0)
, m_minmaxSet(false)
{
static int initialized = 0;
if (initialized++ == 1)
{
initializeMenus();
}
if (!_parent)
m_parent = g_currentDebugMenu;
for (int i=0; i<8; ++i)
m_children[i] = 0;
if (m_width > 1)
if (!((_type >= Property::Int8) && (_type <= Property::Double)))
{
RTM_BREAK;
}
if (m_parent)
{
if (m_parent->m_numChildren == 8) // ignore more than 8 child menus
return;
m_index = m_parent->m_numChildren;
if (m_parent)
m_parent->m_children[m_parent->m_numChildren++] = this;
}
else
m_index = 0;
}
DebugMenu::DebugMenu(DebugMenu* _parent, const char* _label, Property::Type _type, void* _pointer
, void* _defaultValue
, void* _minValue
, void* _maxValue
, CustomDfltFn _customDefault
, CustomEditFn _customEditor
, CustomPrevFn _customPreview)
: m_parent(_parent)
, m_index(0)
, m_numChildren(0)
, m_label(_label)
, m_type(_type)
, m_width(1)
, m_value(_pointer)
, m_customEditor(_customEditor)
, m_customPreview(_customPreview)
, m_minmaxSet(false)
{
if (m_parent->m_numChildren == 8) // ignore more than 8 child menus
return;
for (int i=0; i<8; ++i)
m_children[i] = 0;
m_index = m_parent->m_numChildren;
m_parent->m_children[m_parent->m_numChildren++] = this;
if (Property::Color == _type)
{
_defaultValue = (float*)*(float**)_defaultValue;
if (_minValue && _maxValue)
{
_minValue = (float*)*(float**)_minValue;
_maxValue = (float*)*(float**)_maxValue;
}
}
if (_defaultValue)
propertyCopyValue(_type, m_value, _defaultValue);
if (_customDefault)
_customDefault(m_value);
if (_minValue && _minValue)
{
propertyCopyValue(_type, m_minMax.m_min, _minValue);
propertyCopyValue(_type, m_minMax.m_max, _maxValue);
m_minmaxSet = true;
}
}
ImGuiDataType rappToImGuiScalarType(Property::Type _type)
{
switch (_type)
{
case Property::Int8: return ImGuiDataType_S8;
case Property::Int16: return ImGuiDataType_S16;
case Property::Int32: return ImGuiDataType_S32;
case Property::Int64: return ImGuiDataType_S64;
case Property::Uint8: return ImGuiDataType_U8;
case Property::Uint16: return ImGuiDataType_U16;
case Property::Uint32: return ImGuiDataType_U32;
case Property::Uint64: return ImGuiDataType_U64;
case Property::Float: return ImGuiDataType_Float;
case Property::Double: return ImGuiDataType_Double;
};
RTM_BREAK;
return ImGuiDataType_COUNT;
}
void rappPrintValueType(ImGuiDataType _type, void* _value)
{
char text[128];
propertyPrintToBuffer(_type, _value, text);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT), text);
}
void rappAddCentered_text(const char* _text, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
float fontSizeNumber = ImGui::GetFontSize() * 1.35f;
ImVec2 text_size(1000.0f, 1000.0f);
while (text_size.y > _size.y)
{
fontSizeNumber *= 0.9f;
text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeNumber, FLT_MAX, 0.0f, _text);
}
_drawList->PushClipRect(_minXY, ImVec2(_minXY.x + _size.x, _minXY.y + _size.y));
ImVec2 textPos(_minXY.x + (_size.x - text_size.x)/2, _minXY.y + (_size.y - text_size.y)/2);
_drawList->AddText(0, fontSizeNumber, textPos, RAPP_COLOR_TEXT, _text);
_drawList->PopClipRect();
}
static int cmdKey(rapp::App* /*_app*/, void* /*_userData*/, int /*_argc*/, char const* const* /*_argv*/)
{
return 0;
}
void rappDebugAddBindings()
{
static bool inputBindingsRegistered = false;
if (inputBindingsRegistered)
return;
inputBindingsRegistered = true;
static const rapp::InputBinding bindings[] =
{
{ 0, "num0", 1, { rapp::KeyboardState::Key::NumPad0, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num1", 1, { rapp::KeyboardState::Key::NumPad1, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num2", 1, { rapp::KeyboardState::Key::NumPad2, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num3", 1, { rapp::KeyboardState::Key::NumPad3, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num4", 1, { rapp::KeyboardState::Key::NumPad4, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num5", 1, { rapp::KeyboardState::Key::NumPad5, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num6", 1, { rapp::KeyboardState::Key::NumPad6, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num7", 1, { rapp::KeyboardState::Key::NumPad7, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num8", 1, { rapp::KeyboardState::Key::NumPad8, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num9", 1, { rapp::KeyboardState::Key::NumPad9, rapp::KeyboardState::Modifier::NoMods }},
RAPP_INPUT_BINDING_END
};
rapp::inputAddBindings("debug_bindings", bindings);
rapp::cmdAdd("num0", cmdKey, (void*)KeyboardState::Key::NumPad0, "");
rapp::cmdAdd("num1", cmdKey, (void*)KeyboardState::Key::NumPad1, "");
rapp::cmdAdd("num2", cmdKey, (void*)KeyboardState::Key::NumPad2, "");
rapp::cmdAdd("num3", cmdKey, (void*)KeyboardState::Key::NumPad3, "");
rapp::cmdAdd("num4", cmdKey, (void*)KeyboardState::Key::NumPad4, "");
rapp::cmdAdd("num5", cmdKey, (void*)KeyboardState::Key::NumPad5, "");
rapp::cmdAdd("num6", cmdKey, (void*)KeyboardState::Key::NumPad6, "");
rapp::cmdAdd("num7", cmdKey, (void*)KeyboardState::Key::NumPad7, "");
rapp::cmdAdd("num8", cmdKey, (void*)KeyboardState::Key::NumPad8, "");
rapp::cmdAdd("num9", cmdKey, (void*)KeyboardState::Key::NumPad9, "");
}
static void rappPropertyTypeEditor_scalar(DebugMenu* _menu, ImGuiDataType _type, int _cnt = -1)
{
if (!_menu->m_value)
{
for (uint32_t i=0; i<_menu->m_width; ++i)
rappPropertyTypeEditor_scalar(_menu->m_children[i], rappToImGuiScalarType(_menu->m_type), i);
}
else
{
if (_menu->m_minmaxSet)
{
char name1[6]; strcpy(name1, "##00"); name1[3] = (char)('0' + _cnt);
char name2[6]; strcpy(name2, "##10"); name2[3] = (char)('0' + _cnt);
ImGui::InputScalar(name1, _type, _menu->m_value);
propertyClamp(_menu);
ImGui::SliderScalar(name2, _type, _menu->m_value, _menu->m_minMax.m_min, _menu->m_minMax.m_max);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_HIGHLIGHT), "Min:");
ImGui::SameLine();
rappPrintValueType(_type, _menu->m_minMax.m_min);
ImGui::SameLine();
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_HIGHLIGHT), "Max:");
ImGui::SameLine();
rappPrintValueType(_type, _menu->m_minMax.m_max);
}
else
ImGui::InputScalar("", _type, _menu->m_value);
}
}
static void rappPropertyPreview_scalar(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size, ImGuiDataType _type)
{
char text[128];
char textFull[128*4] = "";
if (!_menu->m_value)
{
for (uint32_t i=0; i<_menu->m_width; ++i)
{
propertyPrintToBuffer(_type, _menu->m_children[i]->m_value, text);
strcat(textFull, text);
if (i != _menu->m_width)
strcat(textFull, "\n");
}
}
else
propertyPrintToBuffer(_type, _menu->m_value, textFull);
rappAddCentered_text(textFull, _drawList, _minXY, _size);
}
static void rappPropertyTypeEditor_Bool(DebugMenu* _menu)
{
bool* valuePtr = (bool*)_menu->m_value;
int b = *valuePtr ? 1 : 0;
ImGui::RadioButton("False", &b, 0);
ImGui::SameLine();
ImGui::RadioButton("True", &b, 1);
*valuePtr = b == 1 ? true : false;
}
static void rappPropertyPreview_Bool(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
bool value = *(bool*)_menu->m_value;
rappAddCentered_text(value ? "True" : "False", _drawList, _minXY, _size);
}
static void rappPropertyTypeEditor_Color(DebugMenu* _menu)
{
float* valuesPtr = (float*)_menu->m_value;
float col[4] = {0};
for (int i=0; i<4; ++i) col[i] = valuesPtr[i];
ImGui::ColorPicker4("", col, ImGuiColorEditFlags_PickerHueWheel);
for (int i=0; i<4; ++i) valuesPtr[i] = col[i];
}
static void rappPropertyPreview_Color(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
float* rgb = (float*)_menu->m_value;
ImU32 color = ImColor(ImVec4(rgb[0], rgb[1], rgb[2], rgb[3]));
float extent = _size.x < _size.y ? _size.x : _size.y;
ImVec2 rectPos(_minXY.x + (_size.x- extent)/2, _minXY.y + (_size.y- extent)/2);
ImVec2 rectSize(rectPos.x + extent, rectPos.y + extent);
_drawList->AddRectFilled(rectPos, rectSize, RAPP_COLOR_WIDGET_OUTLINE);
rectPos.x += RAPP_WIDGET_OUTLINE; rectPos.y += RAPP_WIDGET_OUTLINE;
rectSize.x -= RAPP_WIDGET_OUTLINE; rectSize.y -= RAPP_WIDGET_OUTLINE;
_drawList->AddRectFilled(rectPos, rectSize, color);
}
static Property::Edit rappPropertyTypeEditorDispath(DebugMenu* _menu, ImVec2 _minXY, ImVec2 _size)
{
ImGui::OpenPopup("##propEditor");
ImGui::SetNextWindowPos(_minXY);
ImGui::SetNextWindowSize(_size, ImGuiCond_Always);
if (ImGui::BeginPopup("##propEditor", ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoBackground))
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImVec2 maxXY(_minXY.x+_size.x, _minXY.y+_size.y);
draw_list->AddRectFilled(_minXY, maxXY, RAPP_COLOR_WIDGET_OUTLINE);
_minXY = ImVec2(_minXY.x + RAPP_WIDGET_OUTLINE*3, _minXY.y + RAPP_WIDGET_OUTLINE*2);
maxXY = ImVec2(maxXY.x - (RAPP_WIDGET_OUTLINE*3), maxXY.y - (RAPP_WIDGET_OUTLINE*2));
draw_list->AddRectFilled(_minXY, maxXY, RAPP_COLOR_WIDGET);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_TITLE), " %s", _menu->m_label);
ImGui::Separator();
ImGui::BeginChild("##propEditorInner",ImVec2(),false,ImGuiWindowFlags_NoScrollbar);
switch (_menu->m_type)
{
case Property::Int8:
case Property::Int16:
case Property::Int32:
case Property::Int64:
case Property::Uint8:
case Property::Uint16:
case Property::Uint32:
case Property::Uint64:
case Property::Float:
case Property::Double: rappPropertyTypeEditor_scalar(_menu, rappToImGuiScalarType(_menu->m_type)); break;
case Property::Bool: rappPropertyTypeEditor_Bool(_menu); break;
case Property::Color: rappPropertyTypeEditor_Color(_menu); break;
#if RAPP_DEBUG_WITH_STD_STRING
case Property::StdString:
#endif // RAPP_DEBUG_WITH_STD_STRING
case Property::Custom: _menu->m_customEditor(_menu); break;
default:
RTM_BREAK;
break;
};
ImGui::EndChild();
ImGui::EndPopup();
}
if (rapp::inputGetKeyState(rapp::KeyboardState::Key::Esc))
return Property::Cancel;
if (rapp::inputGetKeyState(rapp::KeyboardState::Key::Return) ||
rapp::inputGetKeyState(rapp::KeyboardState::Key::NumPad5))
return Property::Accept;
return Property::Editing;
}
static bool rappPropertyTypePreviewDispath(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
if (!_menu)
return false;
if (_menu->m_parent && (_menu->m_parent->m_width > 1))
return false;
switch (_menu->m_type)
{
case Property::Int8:
case Property::Int16:
case Property::Int32:
case Property::Int64:
case Property::Uint8:
case Property::Uint16:
case Property::Uint32:
case Property::Uint64:
case Property::Float:
case Property::Double: rappPropertyPreview_scalar(_menu, _drawList, _minXY, _size, rappToImGuiScalarType(_menu->m_type)); return true;
case Property::Bool: rappPropertyPreview_Bool(_menu, _drawList, _minXY, _size); return true;
case Property::Color: rappPropertyPreview_Color(_menu, _drawList, _minXY, _size); return true;
#if RAPP_DEBUG_WITH_STD_STRING
case Property::StdString:
#endif // RAPP_DEBUG_WITH_STD_STRING
case Property::Custom: if (_menu->m_customPreview)
{
_menu->m_customPreview(_menu, _drawList, _minXY, _size);
return true;
}
else
return false;
default:
return false;
};
}
#if RAPP_DEBUG_WITH_STD_STRING
void stringSetDefaultFn(void* _var)
{
*(std::string*)_var = "";
}
void stringEditorFn(void* _var)
{
std::string* var = (std::string*)_var;
char tempString[4096];
strcpy(tempString, var->c_str());
ImGui::InputText("", tempString, 4096);
*var = tempString;
}
void stringPreviewFn(void* _var, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
std::string* value = (std::string*)_var;
rapp::rappAddCentered_text(value->c_str(), _drawList, _minXY, _size);
}
#endif // RAPP_DEBUG_WITH_STD_STRING
static bool rappRoundedButton(DebugMenu* _menu, ImDrawList* _drawList, ImVec2& _position, ImVec2& _size, int _button, const char* _label, bool _editingValue)
{
static uint64_t s_lastHoverTime[9] = {0};
static uint64_t s_lastClickTime[9] = {0};
static bool s_hovered[9] = {false};
ImVec2 maxC(_position.x + _size.x, _position.y + _size.y);
_drawList->AddRectFilled(_position, maxC, RAPP_COLOR_WIDGET_OUTLINE, RAPP_WIDGET_OUTLINE * 3, ImDrawCornerFlags_All);
_position.x += RAPP_WIDGET_OUTLINE;
_position.y += RAPP_WIDGET_OUTLINE;
maxC.x -= RAPP_WIDGET_OUTLINE;
maxC.y -= RAPP_WIDGET_OUTLINE;
ImU32 drawColor = RAPP_COLOR_WIDGET;
ImVec2 mousePos(ImGui::GetIO().MousePos);
uint64_t currTime = rtm::CPU::clock();
bool hover = false;
if (ImGui::IsMouseHoveringRect(_position, ImVec2(maxC.x, maxC.y)))
{
if (!s_hovered[_button])
s_lastHoverTime[_button] = currTime;
if (!_editingValue)
flashColor(drawColor, RAPP_COLOR_WIDGET_BLINK, currTime - s_lastHoverTime[_button]);
hover = true;
}
if (hover && ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered())
s_lastClickTime[_button] = currTime;
if (s_hovered[_button] && (hover == false))
s_lastHoverTime[_button] = 0;
s_hovered[_button] = hover;
uint64_t deltaTime = currTime - s_lastClickTime[_button];
if (!_editingValue)
flashColor(drawColor, RAPP_COLOR_WIDGET_HIGHLIGHT, deltaTime);
_drawList->AddRectFilled(_position, maxC, drawColor, RAPP_WIDGET_OUTLINE * 3);
ImU32 numberColor = _button == 5 ? RAPP_COLOR_WIDGET : RAPP_COLOR_TEXT_STATUS;
if (!_editingValue)
flashColor(numberColor, _button == 5 ? RAPP_COLOR_TEXT_SHADOW : RAPP_COLOR_TEXT, deltaTime*2);
char FK[] = "0";
FK[0] = (char)('0' + _button);
static float fontSizeNumber = ImGui::GetFontSize() * 1.66f;
static float fontSizeLabel = ImGui::GetFontSize() * 1.11f;
ImVec2 text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeNumber, FLT_MAX, 0.0f, FK);
ImVec2 center = ImVec2(_position.x + _size.x/2, _position.y + _size.y/ 2);
ImVec2 text_pos = ImVec2(center.x - text_size.x/2, center.y - text_size.y);
ImVec2 previewPosition(center.x - _size.x/2 + 6, center.y - _size.y/2 + 6);
ImVec2 previewSize(_size.x - 12, _size.y/2 - 12);
bool previewDrawn = rappPropertyTypePreviewDispath(_menu, _drawList, previewPosition, previewSize);
if (!previewDrawn)
_drawList->AddText(0, fontSizeNumber, text_pos, numberColor, FK);
text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeLabel, FLT_MAX, 0.0f, _label);
text_pos = ImVec2(center.x - text_size.x/2, center.y+4);
drawColor = RAPP_COLOR_TEXT_HIGHLIGHT;
flashColor(drawColor, IM_COL32_WHITE, deltaTime);
if (!_editingValue)
_drawList->AddText(0, fontSizeLabel, text_pos, drawColor, _label);
return s_lastClickTime[_button] == currTime;
}
void rappDebugMenu()
{
rappDebugAddBindings();
DebugMenu* ret = g_currentDebugMenu;
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0,0,0,0));
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0,0,0,0));
ImVec2 screenRes = ImGui::GetIO().DisplaySize;
ImVec2 buttonSize = ImVec2(128.0f,128.0f);
screenRes.x -= (buttonSize.x + RAPP_WIDGET_SPACING) * 3;
screenRes.y -= (buttonSize.y + RAPP_WIDGET_SPACING) * 3;
ImGui::SetNextWindowPos(screenRes);
static uint32_t remapIndex[] = {5, 6, 5, 4, 7, 5, 3, 0, 1, 2 };
static uint32_t remapIndexChild[] = {7,8,9,6,3,2,1,4};
bool editingValue = ((g_currentDebugMenu->m_numChildren == 0) && (g_currentDebugMenu->m_type != Property::None) ||
(g_currentDebugMenu->m_width > 1));
static bool oldEditingValue = editingValue;
ImGui::SetNextWindowSize(ImVec2(buttonSize.x * 3 + RAPP_WIDGET_SPACING * 3,buttonSize.y * 3 + RAPP_WIDGET_SPACING * 3));
if (ImGui::Begin("##rappDebugMenu", 0, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize))
{
const ImVec2 drag_delta = ImVec2(ImGui::GetIO().MousePos.x - screenRes.x, ImGui::GetIO().MousePos.y - screenRes.y);
const float drag_dist2 = drag_delta.x*drag_delta.x + drag_delta.y*drag_delta.y;
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRectFullScreen();
uint32_t editIndex = 0xffffffff;
static bool oldPressed[9] = {false};
for (uint32_t x=0; x<3; ++x)
for (uint32_t y=0; y<3; ++y)
{
ImVec2 minC(screenRes.x + buttonSize.x * x + RAPP_WIDGET_SPACING * x, screenRes.y + buttonSize.y * y + RAPP_WIDGET_SPACING * y);
uint32_t displayIndex = 9 - (y*3 + (2-x));
uint32_t childIndex = remapIndex[displayIndex];
DebugMenu* child = g_currentDebugMenu->m_numChildren > childIndex ? g_currentDebugMenu->m_children[childIndex] : 0;
bool validButton = false;
const char* label = "";
if (childIndex < (int)g_currentDebugMenu->m_numChildren)
{
validButton = true;
label = child->m_label;
}
if ((displayIndex == 5) && (g_currentDebugMenu->m_parent))
label = g_currentDebugMenu->m_parent->m_label;
if (editingValue && (displayIndex != 5) && (g_currentDebugMenu->m_index == childIndex))
{
editIndex = childIndex;
label = g_currentDebugMenu->m_label;
}
bool keyPressed = rapp::inputGetKeyState(rapp::KeyboardState::Key(rapp::KeyboardState::Key::NumPad0 + displayIndex));
if (rappRoundedButton(child, draw_list, minC, buttonSize, displayIndex, label, editingValue) && !editingValue)
{
if ((5 == displayIndex) && g_currentDebugMenu->m_parent) // 5, go up a level
ret = g_currentDebugMenu->m_parent;
else
if (childIndex < (int)g_currentDebugMenu->m_numChildren)
ret = child;
}
keyPressed = oldPressed[displayIndex];
}
draw_list->PopClipRect();
ImGui::End();
static uint8_t origValue[DebugMenu::MAX_STORAGE_SIZE][DebugMenu::MAX_VARIABLES]; // for undo
static DebugMenu* editedMenu = 0;
static bool undoNeeded = false;
if (editingValue && (oldEditingValue != editingValue)) // started to edit
{
editedMenu = g_currentDebugMenu;
if (g_currentDebugMenu->m_width > 1)
{
for (uint32_t i=0; i<g_currentDebugMenu->m_width; ++i)
propertyCopyValue(g_currentDebugMenu->m_type, origValue[i], g_currentDebugMenu->m_children[i]->m_value);
}
else
propertyCopyValue(g_currentDebugMenu->m_type, origValue, g_currentDebugMenu->m_value);
}
if (!editingValue && (oldEditingValue != editingValue)) // finished edit
{
if (undoNeeded)
{
if (editedMenu->m_width > 1)
{
for (uint32_t i=0; i<editedMenu->m_width; ++i)
propertyCopyValue(editedMenu->m_type, editedMenu->m_children[i]->m_value, origValue[i]);
}
else
propertyCopyValue(editedMenu->m_type, editedMenu->m_value, origValue);
}
editedMenu = 0;
undoNeeded = false;
}
Property::Edit editRet = Property::Editing;
if (editingValue && g_currentDebugMenu->m_index == editIndex)
editRet = rappPropertyTypeEditorDispath(g_currentDebugMenu, ImVec2(screenRes.x + RAPP_WIDGET_SPACING * 2, screenRes.y + RAPP_WIDGET_SPACING * 2),
ImVec2(buttonSize.x * 3 - RAPP_WIDGET_SPACING * 2, buttonSize.y * 3 - RAPP_WIDGET_SPACING * 2));
if (editRet == Property::Cancel)
undoNeeded = true;
if (editRet != Property::Editing)
ret = g_currentDebugMenu->m_parent;
oldEditingValue = editingValue;
}
ImGui::PopStyleColor(2);
g_currentDebugMenu = ret;
}
} // namespace rapp
#endif // RAPP_WITH_BGFX
| 34.879104 | 158 | 0.690102 | milostosic |
2fe45aa4c3689136a07eae048668c4d5befce9c7 | 320 | cpp | C++ | source/template/function.cpp | chronoxor/CppTemplate | 57357f3a21f1f8721331a9f4a3758344741858b1 | [
"MIT"
] | 24 | 2016-10-09T04:08:55.000Z | 2022-02-18T01:03:54.000Z | source/template/function.cpp | chronoxor/CppTemplate | 57357f3a21f1f8721331a9f4a3758344741858b1 | [
"MIT"
] | null | null | null | source/template/function.cpp | chronoxor/CppTemplate | 57357f3a21f1f8721331a9f4a3758344741858b1 | [
"MIT"
] | 15 | 2019-01-19T16:04:01.000Z | 2021-09-14T15:07:56.000Z | /*!
\file function.cpp
\brief Template function implementation
\author Ivan Shynkarenka
\date 26.05.2016
\copyright MIT License
*/
#include "template/function.h"
#include <cstdlib>
namespace CppTemplate {
int function(int parameter)
{
return rand() % parameter;
}
} // namespace CppTemplate
| 15.238095 | 43 | 0.69375 | chronoxor |
2fe4a45196ef837f7e4d1c6f4969fd58ed6d0163 | 1,475 | hpp | C++ | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | 3 | 2019-10-09T19:03:05.000Z | 2019-12-15T14:22:38.000Z | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | null | null | null | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | null | null | null | #ifndef _ML_EDITOR_MAIN_MENU_HPP_
#define _ML_EDITOR_MAIN_MENU_HPP_
#include <ML/Editor/Editor_Widget.hpp>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * */
class ML_EDITOR_API Editor_MainMenuBar final : public Editor_Widget
{
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
friend class Editor;
Editor_MainMenuBar();
~Editor_MainMenuBar() {}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void onEvent(Event const & value) override;
bool beginDraw(int32_t flags) override;
bool draw() override;
bool endDraw() override;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
std::vector<std::pair<
String,
std::vector<std::function<void()>>
>> m_menus;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
inline Editor_MainMenuBar & addMenu(String const & name, const std::function<void()> & fun)
{
auto it{ std::find_if(m_menus.begin(), m_menus.end(), [&](auto elem)
{
return (elem.first == name);
}) };
if (it == m_menus.end())
{
m_menus.push_back({ name, {} });
it = (m_menus.end() - 1);
}
if (fun)
{
it->second.push_back(fun);
}
return (*this);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
};
/* * * * * * * * * * * * * * * * * * * * */
}
#endif // !_ML_EDITOR_MAIN_MENU_HPP_ | 23.046875 | 93 | 0.423051 | Gurman8r |
2fe54390124f1481683ad394b8cdc34d24997cba | 7,619 | cpp | C++ | hmdv/hmdfix.cpp | risa2000/hmdq | 5eba01dad407b32d06cd3847ae5057f9b4fb7691 | [
"BSD-3-Clause"
] | 16 | 2019-08-08T15:33:04.000Z | 2022-03-03T20:29:18.000Z | hmdv/hmdfix.cpp | risa2000/hmdq | 5eba01dad407b32d06cd3847ae5057f9b4fb7691 | [
"BSD-3-Clause"
] | 1 | 2021-10-20T06:27:33.000Z | 2021-10-20T19:59:16.000Z | hmdv/hmdfix.cpp | risa2000/hmdq | 5eba01dad407b32d06cd3847ae5057f9b4fb7691 | [
"BSD-3-Clause"
] | 2 | 2020-08-20T07:12:54.000Z | 2022-03-03T20:30:01.000Z | /******************************************************************************
* HMDQ Tools - tools for VR headsets and other hardware introspection *
* https://github.com/risa2000/hmdq *
* *
* Copyright (c) 2019, Richard Musil. All rights reserved. *
* *
* This source code is licensed under the BSD 3-Clause "New" or "Revised" *
* License found in the LICENSE file in the root directory of this project. *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
#include <iomanip>
#include <string>
#include <fmt/chrono.h>
#include <fmt/format.h>
#include "calcview.h"
#include "jkeys.h"
#include "misc.h"
#include "verhlp.h"
#include "json_proxy.h"
// locals
//------------------------------------------------------------------------------
// miscellanous section keys
static constexpr auto MM_IN_METER = 1000;
// fix identifications
//------------------------------------------------------------------------------
static constexpr const char* PROG_VER_DATETIME_FORMAT_FIX = "0.3.1";
static constexpr const char* PROG_VER_OPENVR_SECTION_FIX = "1.0.0";
static constexpr const char* PROG_VER_IPD_FIX = "1.2.3";
static constexpr const char* PROG_VER_FOV_FIX = "1.2.4";
static constexpr const char* PROG_VER_OPENVR_LOCALIZED = "1.3.4";
static constexpr const char* PROG_VER_TRIS_OPT_TO_FACES_RAW = "1.3.91";
static constexpr const char* PROG_VER_NEW_FOV_ALGO = "2.1.0";
// functions
//------------------------------------------------------------------------------
// Return 'hmdv_ver' if it is defined in JSON data, otherwise return 'hmdq_ver'.
std::string get_hmdx_ver(const json& jd)
{
const auto misc = jd[j_misc];
std::string hmdx_ver;
if (misc.contains(j_hmdv_ver)) {
hmdx_ver = misc[j_hmdv_ver].get<std::string>();
}
else {
hmdx_ver = misc[j_hmdq_ver].get<std::string>();
}
return hmdx_ver;
}
// Fix datetime format in misc.time field (ver < v0.3.1)
void fix_datetime_format(json& jd)
{
std::istringstream stime;
std::tm tm = {};
// get the old format with 'T' in the middle
stime.str(jd[j_misc][j_time].get<std::string>());
stime >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S");
// put the new format without 'T'
jd[j_misc][j_time] = fmt::format("{:%F %T}", tm);
}
// Fix for moved OpenVR things from 'misc' to 'openvr'
void fix_misc_to_openvr(json& jd)
{
json jopenvr;
if (jd[j_misc].contains("openvr_ver")) {
jopenvr[j_rt_ver] = jd[j_misc]["openvr_ver"];
jd[j_misc].erase("openvr_ver");
}
else {
jopenvr[j_rt_ver] = "n/a";
}
jopenvr[j_rt_path] = "n/a";
jd[j_openvr] = jopenvr;
}
void fix_ipd_unit(json& jd)
{
// the old IPD is in milimeters, transform it to meters
const auto ipd = jd[j_geometry][j_view_geom][j_ipd].get<double>() / MM_IN_METER;
jd[j_geometry][j_view_geom][j_ipd] = ipd;
}
// Fix for vertical FOV calculation in (ver < v1.2.4)
void fix_fov_calc(json& jd)
{
const auto fov_tot = calc_total_fov(jd[j_geometry][j_fov_head]);
jd[j_geometry][j_fov_tot] = fov_tot;
}
// move openvr data into openvr section (ver < v1.3.4)
void fix_openvr_section(json& jd)
{
jd[j_openvr][j_devices] = jd[j_devices];
jd[j_openvr][j_properties] = jd[j_properties];
jd[j_openvr][j_geometry] = jd[j_geometry];
jd.erase(j_devices);
jd.erase(j_properties);
jd.erase(j_geometry);
}
// change (temporarily introduced) 'tris_opt' key to 'faces_raw' and make 'verts_opt'
// without 'verts_raw' 'verts_raw' again
void fix_tris_opt(json& jd)
{
std::vector<json*> geoms;
if (jd.contains(j_openvr)) {
json& jd_openvr = jd[j_openvr];
if (jd_openvr.contains(j_geometry)) {
geoms.push_back(&jd_openvr[j_geometry]);
}
}
if (jd.contains(j_oculus)) {
json& jd_oculus = jd[j_oculus];
if (jd_oculus.contains(j_geometry)) {
for (const auto& fov_id : {j_default_fov, j_max_fov}) {
if (jd_oculus[j_geometry].contains(fov_id)) {
geoms.push_back(&jd_oculus[j_geometry][fov_id]);
}
}
}
}
for (json* g : geoms) {
if ((*g).contains(j_ham_mesh)) {
for (const auto& neye : {j_leye, j_reye}) {
if ((*g)[j_ham_mesh].contains(neye)
&& !(*g)[j_ham_mesh][neye].is_null()) {
json& hm_eye = (*g)[j_ham_mesh][neye];
if (hm_eye.contains(j_tris_opt)) {
hm_eye[j_faces_raw] = std::move(hm_eye[j_tris_opt]);
hm_eye.erase(j_tris_opt);
}
if (hm_eye.contains(j_verts_opt) && !hm_eye.contains(j_verts_raw)) {
hm_eye[j_verts_raw] = std::move(hm_eye[j_verts_opt]);
hm_eye.erase(j_verts_opt);
}
}
}
}
}
}
// recalculate FOV points with the new algorithm which works fine with total FOV > 180
// deg.
void fix_fov_algo(json& jd)
{
if (jd.contains(j_openvr)) {
json& jd_openvr = jd[j_openvr];
if (jd_openvr.contains(j_geometry)) {
jd_openvr[j_geometry] = calc_geometry(jd_openvr[j_geometry]);
}
}
if (jd.contains(j_oculus)) {
json& jd_oculus = jd[j_oculus];
if (jd_oculus.contains(j_geometry)) {
for (const auto& fov_id : {j_default_fov, j_max_fov}) {
if (jd_oculus[j_geometry].contains(fov_id)) {
jd_oculus[j_geometry][fov_id]
= calc_geometry(jd_oculus[j_geometry][fov_id]);
}
}
}
}
}
// Check and run all fixes (return true if there was any)
bool apply_all_relevant_fixes(json& jd)
{
const auto hmdx_ver = get_hmdx_ver(jd);
bool fixed = false;
// datetime format fix - remove 'T' in the middle
if (comp_ver(hmdx_ver, PROG_VER_DATETIME_FORMAT_FIX) < 0) {
fix_datetime_format(jd);
fixed = true;
}
// moved OpenVR things from 'misc' to 'openvr'
if (comp_ver(hmdx_ver, PROG_VER_OPENVR_SECTION_FIX) < 0) {
fix_misc_to_openvr(jd);
fixed = true;
}
// change IPD unit in the JSON file - mm -> meters
if (comp_ver(hmdx_ver, PROG_VER_IPD_FIX) < 0) {
fix_ipd_unit(jd);
fixed = true;
}
// change the vertical FOV calculation formula
if (comp_ver(hmdx_ver, PROG_VER_FOV_FIX) < 0) {
fix_fov_calc(jd);
fixed = true;
}
// move all OpenVR data into 'openvr' section
if (comp_ver(hmdx_ver, PROG_VER_OPENVR_LOCALIZED) < 0) {
fix_openvr_section(jd);
fixed = true;
}
// change (temporarily introduced) 'tris_opt' key to 'faces_raw' and make 'verts_opt'
// without 'verts_raw' 'verts_raw' again
if (comp_ver(hmdx_ver, PROG_VER_TRIS_OPT_TO_FACES_RAW) < 0) {
fix_tris_opt(jd);
fixed = true;
}
// recalculate FOV points with the new algorithm which works fine with total FOV >
// 180 deg.
if (comp_ver(hmdx_ver, PROG_VER_NEW_FOV_ALGO) < 0) {
fix_fov_algo(jd);
fixed = true;
}
// add 'hmdv_ver' into misc, if some change was made
if (fixed) {
jd[j_misc][j_hmdv_ver] = PROG_VERSION;
}
return fixed;
}
| 34.789954 | 89 | 0.55926 | risa2000 |
2fe62929799606f23c74c320cffe4e481624588c | 696 | cpp | C++ | torch_mlu/csrc/aten/operators/bang/dump.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | 20 | 2022-03-01T11:40:51.000Z | 2022-03-30T08:17:47.000Z | torch_mlu/csrc/aten/operators/bang/dump.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | torch_mlu/csrc/aten/operators/bang/dump.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | #include "aten/operators/bang/bang_kernel.h"
#include "aten/operators/bang/internal/bang_internal.h"
namespace torch_mlu {
namespace bang {
namespace ops {
bool bang_dump(const at::Tensor& input) {
auto input_impl = getMluTensorImpl(input);
auto input_ptr = input_impl->cnnlMalloc();
int32_t size = input.numel();
cnrtDataType_t cnrt_type = fromCnnlType2CnrtType(input_impl->getCnnlType());
cnrtDim3_t dim = {1, 1, 1};
cnrtFunctionType_t ktype = CNRT_FUNC_TYPE_BLOCK;
auto queue = getCurQueue();
dump(input_ptr, size, dim, ktype, queue, cnrt_type);
cnrtQueueSync(queue);
return true;
}
} // namespace ops
} // namespace bang
} // namespace torch_mlu
| 29 | 80 | 0.716954 | Cambricon |
2fe90f86043e426ce667ee98163fbb2abcb3e45b | 22,787 | cpp | C++ | Sources/Elastos/Packages/InputMethods/PinyinIME/src/elastos/droid/inputmethod/pinyin/InputModeSwitcher.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Packages/InputMethods/PinyinIME/src/elastos/droid/inputmethod/pinyin/InputModeSwitcher.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Packages/InputMethods/PinyinIME/src/elastos/droid/inputmethod/pinyin/InputModeSwitcher.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Text.h"
#include "elastos/droid/inputmethod/pinyin/InputModeSwitcher.h"
#include "elastos/droid/inputmethod/pinyin/CPinyinIME.h"
#include "elastos/droid/inputmethod/pinyin/SoftKeyboard.h"
#include "R.h"
#include <elastos/core/StringUtils.h>
using Elastos::Droid::Content::IContext;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Text::IInputType;
using Elastos::Core::StringUtils;
namespace Elastos {
namespace Droid {
namespace InputMethod {
namespace Pinyin {
//===========================================================
// InputModeSwitcher::ToggleStates
//===========================================================
InputModeSwitcher::ToggleStates::ToggleStates()
: mQwerty(FALSE)
, mQwertyUpperCase(FALSE)
, mRowIdToEnable(0)
, mKeyStatesNum(0)
{
mKeyStates = ArrayOf<Int32>::Alloc(InputModeSwitcher::MAX_TOGGLE_STATES);
}
//===========================================================
// InputModeSwitcher
//===========================================================
const Int32 InputModeSwitcher::USERDEF_KEYCODE_SHIFT_1 = -1;
const Int32 InputModeSwitcher::USERDEF_KEYCODE_LANG_2 = -2;
const Int32 InputModeSwitcher::USERDEF_KEYCODE_SYM_3 = -3;
const Int32 InputModeSwitcher::USERDEF_KEYCODE_MORE_SYM_5 = -5;
const Int32 InputModeSwitcher::USERDEF_KEYCODE_SMILEY_6 = -6;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT = 0xf0000000;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT_QWERTY = 0x10000000;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT_SYMBOL1 = 0x20000000;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT_SYMBOL2 = 0x30000000;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT_SMILEY = 0x40000000;
const Int32 InputModeSwitcher::MASK_SKB_LAYOUT_PHONE = 0x50000000;
const Int32 InputModeSwitcher::MASK_LANGUAGE = 0x0f000000;
const Int32 InputModeSwitcher::MASK_LANGUAGE_CN = 0x01000000;
const Int32 InputModeSwitcher::MASK_LANGUAGE_EN = 0x02000000;
const Int32 InputModeSwitcher::MASK_CASE = 0x00f00000;
const Int32 InputModeSwitcher::MASK_CASE_LOWER = 0x00100000;
const Int32 InputModeSwitcher::MASK_CASE_UPPER = 0x00200000;
const Int32 InputModeSwitcher::USERDEF_KEYCODE_PHONE_SYM_4 = -4;
const Int32 InputModeSwitcher::MODE_SKB_CHINESE = (MASK_SKB_LAYOUT_QWERTY | MASK_LANGUAGE_CN);
const Int32 InputModeSwitcher::MODE_SKB_SYMBOL1_CN = (MASK_SKB_LAYOUT_SYMBOL1 | MASK_LANGUAGE_CN);
const Int32 InputModeSwitcher::MODE_SKB_SYMBOL2_CN = (MASK_SKB_LAYOUT_SYMBOL2 | MASK_LANGUAGE_CN);
const Int32 InputModeSwitcher::MODE_SKB_ENGLISH_LOWER = (MASK_SKB_LAYOUT_QWERTY
| MASK_LANGUAGE_EN | MASK_CASE_LOWER);
const Int32 InputModeSwitcher::MODE_SKB_ENGLISH_UPPER = (MASK_SKB_LAYOUT_QWERTY
| MASK_LANGUAGE_EN | MASK_CASE_UPPER);
const Int32 InputModeSwitcher::MODE_SKB_SYMBOL1_EN = (MASK_SKB_LAYOUT_SYMBOL1 | MASK_LANGUAGE_EN);
const Int32 InputModeSwitcher::MODE_SKB_SYMBOL2_EN = (MASK_SKB_LAYOUT_SYMBOL2 | MASK_LANGUAGE_EN);
const Int32 InputModeSwitcher::MODE_SKB_SMILEY = (MASK_SKB_LAYOUT_SMILEY | MASK_LANGUAGE_CN);
const Int32 InputModeSwitcher::MODE_SKB_PHONE_NUM = (MASK_SKB_LAYOUT_PHONE);
const Int32 InputModeSwitcher::MODE_SKB_PHONE_SYM = (MASK_SKB_LAYOUT_PHONE | MASK_CASE_UPPER);
const Int32 InputModeSwitcher::MODE_HKB_CHINESE = (MASK_LANGUAGE_CN);
const Int32 InputModeSwitcher::MODE_HKB_ENGLISH = (MASK_LANGUAGE_EN);
const Int32 InputModeSwitcher::MODE_UNSET = 0;
const Int32 InputModeSwitcher::MAX_TOGGLE_STATES = 4;
InputModeSwitcher::InputModeSwitcher(
/* [in] */ CPinyinIME* imeService)
: mInputMode(MODE_UNSET)
, mPreviousInputMode(MODE_SKB_CHINESE)
, mRecentLauageInputMode(MODE_SKB_CHINESE)
, mToggleStates(new ToggleStates())
, mShortMessageField(FALSE)
, mEnterKeyNormal(TRUE)
, mInputIcon(R::drawable::ime_pinyin)
, mToggleStateCn(0)
, mToggleStateCnCand(0)
, mToggleStateEnLower(0)
, mToggleStateEnUpper(0)
, mToggleStateEnSym1(0)
, mToggleStateEnSym2(0)
, mToggleStateSmiley(0)
, mToggleStatePhoneSym(0)
, mToggleStateGo(0)
, mToggleStateSearch(0)
, mToggleStateSend(0)
, mToggleStateNext(0)
, mToggleStateDone(0)
, mToggleRowCn(0)
, mToggleRowEn(0)
, mToggleRowUri(0)
, mToggleRowEmailAddress(0)
{
mImeService = imeService;
AutoPtr<IResources> r;
IContext::Probe(mImeService)->GetResources((IResources**)&r);
String strValue;
mToggleStateCn = StringUtils::ParseInt32((r->GetString(R::string::toggle_cn, &strValue), strValue));
mToggleStateCnCand = StringUtils::ParseInt32((r->GetString(R::string::toggle_cn_cand, &strValue), strValue));
mToggleStateEnLower = StringUtils::ParseInt32((r->GetString(R::string::toggle_en_lower, &strValue), strValue));
mToggleStateEnUpper = StringUtils::ParseInt32((r->GetString(R::string::toggle_en_upper, &strValue), strValue));
mToggleStateEnSym1 = StringUtils::ParseInt32((r->GetString(R::string::toggle_en_sym1, &strValue), strValue));
mToggleStateEnSym2 = StringUtils::ParseInt32((r->GetString(R::string::toggle_en_sym2, &strValue), strValue));
mToggleStateSmiley = StringUtils::ParseInt32((r->GetString(R::string::toggle_smiley, &strValue), strValue));
mToggleStatePhoneSym = StringUtils::ParseInt32((r->GetString(R::string::toggle_phone_sym, &strValue), strValue));
mToggleStateGo = StringUtils::ParseInt32((r->GetString(R::string::toggle_enter_go, &strValue), strValue));
mToggleStateSearch = StringUtils::ParseInt32((r->GetString(R::string::toggle_enter_search, &strValue), strValue));
mToggleStateSend = StringUtils::ParseInt32((r->GetString(R::string::toggle_enter_send, &strValue), strValue));
mToggleStateNext = StringUtils::ParseInt32((r->GetString(R::string::toggle_enter_next, &strValue), strValue));
mToggleStateDone = StringUtils::ParseInt32((r->GetString(R::string::toggle_enter_done, &strValue), strValue));
mToggleRowCn = StringUtils::ParseInt32((r->GetString(R::string::toggle_row_cn, &strValue), strValue));
mToggleRowEn = StringUtils::ParseInt32((r->GetString(R::string::toggle_row_en, &strValue), strValue));
mToggleRowUri = StringUtils::ParseInt32((r->GetString(R::string::toggle_row_uri, &strValue), strValue));
mToggleRowEmailAddress = StringUtils::ParseInt32((r->GetString(R::string::toggle_row_emailaddress, &strValue), strValue));
}
Int32 InputModeSwitcher::GetInputMode()
{
return mInputMode;
}
AutoPtr<InputModeSwitcher::ToggleStates> InputModeSwitcher::GetToggleStates()
{
return mToggleStates;
}
Int32 InputModeSwitcher::GetSkbLayout()
{
Int32 layout = (mInputMode & MASK_SKB_LAYOUT);
switch (layout) {
case MASK_SKB_LAYOUT_QWERTY: {
return R::xml::skb_qwerty;
}
case MASK_SKB_LAYOUT_SYMBOL1: {
return R::xml::skb_sym1;
}
case MASK_SKB_LAYOUT_SYMBOL2: {
return R::xml::skb_sym2;
}
case MASK_SKB_LAYOUT_SMILEY: {
return R::xml::skb_smiley;
}
case MASK_SKB_LAYOUT_PHONE: {
return R::xml::skb_phone;
}
}
return 0;
}
Int32 InputModeSwitcher::SwitchLanguageWithHkb()
{
Int32 newInputMode = MODE_HKB_CHINESE;
mInputIcon = R::drawable::ime_pinyin;
if (MODE_HKB_CHINESE == mInputMode) {
newInputMode = MODE_HKB_ENGLISH;
mInputIcon = R::drawable::ime_en;
}
SaveInputMode(newInputMode);
return mInputIcon;
}
Int32 InputModeSwitcher::SwitchModeForUserKey(
/* [in] */ Int32 userKey)
{
Int32 newInputMode = MODE_UNSET;
if (USERDEF_KEYCODE_LANG_2 == userKey) {
if (MODE_SKB_CHINESE == mInputMode) {
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
else if (MODE_SKB_ENGLISH_LOWER == mInputMode
|| MODE_SKB_ENGLISH_UPPER == mInputMode) {
newInputMode = MODE_SKB_CHINESE;
}
else if (MODE_SKB_SYMBOL1_CN == mInputMode) {
newInputMode = MODE_SKB_SYMBOL1_EN;
}
else if (MODE_SKB_SYMBOL1_EN == mInputMode) {
newInputMode = MODE_SKB_SYMBOL1_CN;
}
else if (MODE_SKB_SYMBOL2_CN == mInputMode) {
newInputMode = MODE_SKB_SYMBOL2_EN;
}
else if (MODE_SKB_SYMBOL2_EN == mInputMode) {
newInputMode = MODE_SKB_SYMBOL2_CN;
}
else if (MODE_SKB_SMILEY == mInputMode) {
newInputMode = MODE_SKB_CHINESE;
}
}
else if (USERDEF_KEYCODE_SYM_3 == userKey) {
if (MODE_SKB_CHINESE == mInputMode) {
newInputMode = MODE_SKB_SYMBOL1_CN;
}
else if (MODE_SKB_ENGLISH_UPPER == mInputMode
|| MODE_SKB_ENGLISH_LOWER == mInputMode) {
newInputMode = MODE_SKB_SYMBOL1_EN;
}
else if (MODE_SKB_SYMBOL1_EN == mInputMode
|| MODE_SKB_SYMBOL2_EN == mInputMode) {
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
else if (MODE_SKB_SYMBOL1_CN == mInputMode
|| MODE_SKB_SYMBOL2_CN == mInputMode) {
newInputMode = MODE_SKB_CHINESE;
}
else if (MODE_SKB_SMILEY == mInputMode) {
newInputMode = MODE_SKB_SYMBOL1_CN;
}
}
else if (USERDEF_KEYCODE_SHIFT_1 == userKey) {
if (MODE_SKB_ENGLISH_LOWER == mInputMode) {
newInputMode = MODE_SKB_ENGLISH_UPPER;
}
else if (MODE_SKB_ENGLISH_UPPER == mInputMode) {
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
}
else if (USERDEF_KEYCODE_MORE_SYM_5 == userKey) {
Int32 sym = (MASK_SKB_LAYOUT & mInputMode);
if (MASK_SKB_LAYOUT_SYMBOL1 == sym) {
sym = MASK_SKB_LAYOUT_SYMBOL2;
}
else {
sym = MASK_SKB_LAYOUT_SYMBOL1;
}
newInputMode = ((mInputMode & (~MASK_SKB_LAYOUT)) | sym);
}
else if (USERDEF_KEYCODE_SMILEY_6 == userKey) {
if (MODE_SKB_CHINESE == mInputMode) {
newInputMode = MODE_SKB_SMILEY;
}
else {
newInputMode = MODE_SKB_CHINESE;
}
}
else if (USERDEF_KEYCODE_PHONE_SYM_4 == userKey) {
if (MODE_SKB_PHONE_NUM == mInputMode) {
newInputMode = MODE_SKB_PHONE_SYM;
}
else {
newInputMode = MODE_SKB_PHONE_NUM;
}
}
if (newInputMode == mInputMode || MODE_UNSET == newInputMode) {
return mInputIcon;
}
SaveInputMode(newInputMode);
PrepareToggleStates(TRUE);
return mInputIcon;
}
// Return the icon to update.
Int32 InputModeSwitcher::RequestInputWithHkb(
/* [in] */ IEditorInfo* editorInfo)
{
mShortMessageField = FALSE;
Boolean english = FALSE;
Int32 newInputMode = MODE_HKB_CHINESE;
Int32 inputType = 0;
editorInfo->GetInputType(&inputType);
switch (inputType & IInputType::TYPE_MASK_CLASS) {
case IInputType::TYPE_CLASS_NUMBER:
case IInputType::TYPE_CLASS_PHONE:
case IInputType::TYPE_CLASS_DATETIME:
english = TRUE;
break;
case IInputType::TYPE_CLASS_TEXT: {
Int32 v = inputType & IInputType::TYPE_MASK_VARIATION;
if (v == IInputType::TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| v == IInputType::TYPE_TEXT_VARIATION_PASSWORD
|| v == IInputType::TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|| v == IInputType::TYPE_TEXT_VARIATION_URI) {
english = TRUE;
}
else if (v == IInputType::TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mShortMessageField = TRUE;
}
break;
}
default:
break;
}
if (english) {
// If the application request English mode, we switch to it.
newInputMode = MODE_HKB_ENGLISH;
}
else {
// If the application do not request English mode, we will
// try to keep the previous mode to input language text.
// Because there is not soft keyboard, we need discard all
// soft keyboard related information from the previous language
// mode.
if ((mRecentLauageInputMode & MASK_LANGUAGE) == MASK_LANGUAGE_CN) {
newInputMode = MODE_HKB_CHINESE;
}
else {
newInputMode = MODE_HKB_ENGLISH;
}
}
mEditorInfo = editorInfo;
SaveInputMode(newInputMode);
PrepareToggleStates(FALSE);
return mInputIcon;
}
Int32 InputModeSwitcher::RequestInputWithSkb(
/* [in] */ IEditorInfo* editorInfo)
{
mShortMessageField = FALSE;
Int32 newInputMode = MODE_SKB_CHINESE;
Int32 inputType = 0;
editorInfo->GetInputType(&inputType);
switch (inputType & IInputType::TYPE_MASK_CLASS) {
case IInputType::TYPE_CLASS_NUMBER:
case IInputType::TYPE_CLASS_DATETIME:
newInputMode = MODE_SKB_SYMBOL1_EN;
break;
case IInputType::TYPE_CLASS_PHONE:
newInputMode = MODE_SKB_PHONE_NUM;
break;
case IInputType::TYPE_CLASS_TEXT: {
Int32 v = inputType & IInputType::TYPE_MASK_VARIATION;
if (v == IInputType::TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| v == IInputType::TYPE_TEXT_VARIATION_PASSWORD
|| v == IInputType::TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|| v == IInputType::TYPE_TEXT_VARIATION_URI) {
// If the application request English mode, we switch to it.
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
else {
if (v == IInputType::TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mShortMessageField = TRUE;
}
// If the application do not request English mode, we will
// try to keep the previous mode.
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
newInputMode = mInputMode;
if (0 == skbLayout) {
if ((mInputMode & MASK_LANGUAGE) == MASK_LANGUAGE_CN) {
newInputMode = MODE_SKB_CHINESE;
}
else {
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
}
}
break;
}
default: {
// Try to keep the previous mode.
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
newInputMode = mInputMode;
if (0 == skbLayout) {
if ((mInputMode & MASK_LANGUAGE) == MASK_LANGUAGE_CN) {
newInputMode = MODE_SKB_CHINESE;
}
else {
newInputMode = MODE_SKB_ENGLISH_LOWER;
}
}
break;
}
}
mEditorInfo = editorInfo;
SaveInputMode(newInputMode);
PrepareToggleStates(TRUE);
return mInputIcon;
}
Int32 InputModeSwitcher::RequestBackToPreviousSkb()
{
Int32 layout = (mInputMode & MASK_SKB_LAYOUT);
Int32 lastLayout = (mPreviousInputMode & MASK_SKB_LAYOUT);
if (0 != layout && 0 != lastLayout) {
mInputMode = mPreviousInputMode;
SaveInputMode(mInputMode);
PrepareToggleStates(TRUE);
return mInputIcon;
}
return 0;
}
Int32 InputModeSwitcher::GetTooggleStateForCnCand()
{
return mToggleStateCnCand;
}
Boolean InputModeSwitcher::IsEnglishWithHkb()
{
return MODE_HKB_ENGLISH == mInputMode;
}
Boolean InputModeSwitcher::IsEnglishWithSkb()
{
return MODE_SKB_ENGLISH_LOWER == mInputMode
|| MODE_SKB_ENGLISH_UPPER == mInputMode;
}
Boolean InputModeSwitcher::IsEnglishUpperCaseWithSkb()
{
return MODE_SKB_ENGLISH_UPPER == mInputMode;
}
Boolean InputModeSwitcher::IsChineseText()
{
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
if (MASK_SKB_LAYOUT_QWERTY == skbLayout || 0 == skbLayout) {
Int32 language = (mInputMode & MASK_LANGUAGE);
if (MASK_LANGUAGE_CN == language) {
return TRUE;
}
}
return FALSE;
}
Boolean InputModeSwitcher::IsChineseTextWithHkb()
{
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
if (0 == skbLayout) {
Int32 language = (mInputMode & MASK_LANGUAGE);
if (MASK_LANGUAGE_CN == language) {
return TRUE;
}
}
return FALSE;
}
Boolean InputModeSwitcher::IsChineseTextWithSkb()
{
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
if (MASK_SKB_LAYOUT_QWERTY == skbLayout) {
Int32 language = (mInputMode & MASK_LANGUAGE);
if (MASK_LANGUAGE_CN == language) {
return TRUE;
}
}
return FALSE;
}
Boolean InputModeSwitcher::IsSymbolWithSkb()
{
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
if (MASK_SKB_LAYOUT_SYMBOL1 == skbLayout
|| MASK_SKB_LAYOUT_SYMBOL2 == skbLayout) {
return TRUE;
}
return FALSE;
}
Boolean InputModeSwitcher::IsEnterNoramlState()
{
return mEnterKeyNormal;
}
Boolean InputModeSwitcher::TryHandleLongPressSwitch(
/* [in] */ Int32 keyCode)
{
if (USERDEF_KEYCODE_LANG_2 == keyCode
|| USERDEF_KEYCODE_PHONE_SYM_4 == keyCode) {
mImeService->ShowOptionsMenu();
return TRUE;
}
return FALSE;
}
void InputModeSwitcher::SaveInputMode(
/* [in] */ Int32 newInputMode)
{
mPreviousInputMode = mInputMode;
mInputMode = newInputMode;
Int32 skbLayout = (mInputMode & MASK_SKB_LAYOUT);
if (MASK_SKB_LAYOUT_QWERTY == skbLayout || 0 == skbLayout) {
mRecentLauageInputMode = mInputMode;
}
mInputIcon = R::drawable::ime_pinyin;
if (IsEnglishWithHkb()) {
mInputIcon = R::drawable::ime_en;
}
else if (IsChineseTextWithHkb()) {
mInputIcon = R::drawable::ime_pinyin;
}
if (!Environment::GetInstance()->HasHardKeyboard()) {
mInputIcon = 0;
}
}
void InputModeSwitcher::PrepareToggleStates(
/* [in] */ Boolean needSkb)
{
mEnterKeyNormal = TRUE;
if (!needSkb) return;
mToggleStates->mQwerty = FALSE;
mToggleStates->mKeyStatesNum = 0;
AutoPtr<ArrayOf<Int32> > states = mToggleStates->mKeyStates;
Int32 statesNum = 0;
// Toggle state for language.
Int32 language = (mInputMode & MASK_LANGUAGE);
Int32 layout = (mInputMode & MASK_SKB_LAYOUT);
Int32 charcase = (mInputMode & MASK_CASE);
Int32 inputType = 0;
Int32 variation = (mEditorInfo->GetInputType(&inputType), inputType) & IInputType::TYPE_MASK_VARIATION;
if (MASK_SKB_LAYOUT_PHONE != layout) {
if (MASK_LANGUAGE_CN == language) {
// Chinese and Chinese symbol are always the default states,
// do not add a toggling operation.
if (MASK_SKB_LAYOUT_QWERTY == layout) {
mToggleStates->mQwerty = TRUE;
mToggleStates->mQwertyUpperCase = TRUE;
if (mShortMessageField) {
(*states)[statesNum] = mToggleStateSmiley;
statesNum++;
}
}
}
else if (MASK_LANGUAGE_EN == language) {
if (MASK_SKB_LAYOUT_QWERTY == layout) {
mToggleStates->mQwerty = TRUE;
mToggleStates->mQwertyUpperCase = FALSE;
(*states)[statesNum] = mToggleStateEnLower;
if (MASK_CASE_UPPER == charcase) {
mToggleStates->mQwertyUpperCase = TRUE;
(*states)[statesNum] = mToggleStateEnUpper;
}
statesNum++;
}
else if (MASK_SKB_LAYOUT_SYMBOL1 == layout) {
(*states)[statesNum] = mToggleStateEnSym1;
statesNum++;
}
else if (MASK_SKB_LAYOUT_SYMBOL2 == layout) {
(*states)[statesNum] = mToggleStateEnSym2;
statesNum++;
}
}
// Toggle rows for QWERTY.
mToggleStates->mRowIdToEnable = SoftKeyboard::KeyRow::DEFAULT_ROW_ID;
if (variation == IInputType::TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mToggleStates->mRowIdToEnable = mToggleRowEmailAddress;
}
else if (variation == IInputType::TYPE_TEXT_VARIATION_URI) {
mToggleStates->mRowIdToEnable = mToggleRowUri;
}
else if (MASK_LANGUAGE_CN == language) {
mToggleStates->mRowIdToEnable = mToggleRowCn;
}
else if (MASK_LANGUAGE_EN == language) {
mToggleStates->mRowIdToEnable = mToggleRowEn;
}
}
else {
if (MASK_CASE_UPPER == charcase) {
(*states)[statesNum] = mToggleStatePhoneSym;
statesNum++;
}
}
// Toggle state for enter key.
Int32 imeOptions = 0;
Int32 action = (mEditorInfo->GetImeOptions(&imeOptions), imeOptions)
& (IEditorInfo::IME_MASK_ACTION | IEditorInfo::IME_FLAG_NO_ENTER_ACTION);
if (action == IEditorInfo::IME_ACTION_GO) {
(*states)[statesNum] = mToggleStateGo;
statesNum++;
mEnterKeyNormal = FALSE;
}
else if (action == IEditorInfo::IME_ACTION_SEARCH) {
(*states)[statesNum] = mToggleStateSearch;
statesNum++;
mEnterKeyNormal = FALSE;
}
else if (action == IEditorInfo::IME_ACTION_SEND) {
(*states)[statesNum] = mToggleStateSend;
statesNum++;
mEnterKeyNormal = FALSE;
}
else if (action == IEditorInfo::IME_ACTION_NEXT) {
Int32 inputType = 0;
mEditorInfo->GetInputType(&inputType);
Int32 f = inputType & IInputType::TYPE_MASK_FLAGS;
if (f != IInputType::TYPE_TEXT_FLAG_MULTI_LINE) {
(*states)[statesNum] = mToggleStateNext;
statesNum++;
mEnterKeyNormal = FALSE;
}
}
else if (action == IEditorInfo::IME_ACTION_DONE) {
(*states)[statesNum] = mToggleStateDone;
statesNum++;
mEnterKeyNormal = FALSE;
}
mToggleStates->mKeyStatesNum = statesNum;
}
} // namespace Pinyin
} // namespace InputMethod
} // namespace Droid
} // namespace Elastos
| 35.549142 | 126 | 0.641155 | jingcao80 |
2fea1e25f312515fa2c33c3731c88c9339d6d3ee | 5,442 | hh | C++ | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | #pragma once
#include "board_cfg.h"
#ifdef DEV_WS2812
#include "device.h"
#if BOARD_CFG_FREQ == 16000000
template<uint8_t kIoi>
void WS2812_send(uint8_t n, uint8_t *grb)
{
// 0: 400ns( 6.4) high, 850ns(13.6) low
// 1: 800ns(12.8) high, 450ns( 7.2) low
// Note that writing a bit to the PIN register toggles the bit in the PORT register
// which only takes 1 cycle versus, e.g., SBI which is 2 cycles
constexpr uint8_t out_reg = (kIoi >> 4); // PIN reg for IOI
constexpr uint8_t out_pin = IOI_MASK(kIoi); // bits to toggle
uint8_t v, bit;
IOI_PORT_SET(kIoi, 0);
__asm__ volatile (
" cli \n" /* Disable interrupts! */ \
" ld %2, %a0+ \n" /* v = *grb++ */ \
" ldi %3, 0x08 \n" /* bit = 8 */ \
/* High side, bit: 0=400ns(6.4=7), 1=800ns(12.8=13) */ \
"1: nop \n" /* 1 */ \
" out %7, %6 \n" /* 1 PINC, toggle high */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" lsl %2 \n" /* 1 Shift MSB into carry */ \
" brcc 3f \n" /* 1/2 Skip the delay if bit was 0 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
"2: nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
/* Low side: 0=850ns(13.6=14), 1=450ns(7.2=7) */ \
"3: out %7, %6 \n" /* 1 OUT LOW */ \
" brcs 4f \n" /* 1/2 Skip the delay if bit was 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
"4: dec %3 \n" /* 1 bit-- */ \
" brne 1b \n" /* 1/2 while(bit) */ \
" dec %1 \n" /* 1 n-- */ \
" breq 9f \n" /* 1 if (!n) break */ \
/* High side, byte: 0=400ns(6.4=7), 1=800ns(12.8=13) */ \
" out %7, %6 \n" /* 1 OUT HIGH */ \
" ld %2, %a0+ \n" /* 2 v = *grb++ (2 clocks? The docs would say 1, but maybe the post-inc?) */ \
" ldi %3, 0x08 \n" /* 1 bit = 8 */ \
" lsl %2 \n" /* 1 Shift MSB into carry */ \
" brcc 3b \n" /* 1/2 Jump to long-low if bit was 0 as byte setup took all the short-high clocks */ \
" rjmp 2b \n" /* 2 Jump into long-high delay to burn the remaining long-high clocks */ \
"9: sei \n" /* End, restore interrupts */
: "=e"(grb), "=r"(n), "=&r"(v), "=&d"(bit)
: "0"(grb), "1"(n), "r"(out_pin), "M"(out_reg)
);
}
#else
#error Unsupported CPU clock
#endif
#endif // DEV_WS2812
| 71.605263 | 113 | 0.212238 | artraze |
2feb47bc9d43868e354b96864e908a2e2ee735b9 | 7,004 | cpp | C++ | cpp/benckmark01_inproc_communication/zmq_inproc/bench_zmq_inproc.cpp | ForrestSu/StudyNotes | 7e823de2edbbdb1dc192dfa57c83b1776ef29836 | [
"MIT"
] | null | null | null | cpp/benckmark01_inproc_communication/zmq_inproc/bench_zmq_inproc.cpp | ForrestSu/StudyNotes | 7e823de2edbbdb1dc192dfa57c83b1776ef29836 | [
"MIT"
] | 1 | 2020-10-24T11:30:30.000Z | 2020-10-24T11:30:32.000Z | cpp/benckmark01_inproc_communication/zmq_inproc/bench_zmq_inproc.cpp | ForrestSu/StudyNotes | 7e823de2edbbdb1dc192dfa57c83b1776ef29836 | [
"MIT"
] | null | null | null | /*
* bench_zmq_inproc.cpp
* 测试zmq inproc 发送接收效率, (取代传统的进程间通信带锁的方式)
*
* Created on: 2019年03月14日
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <atomic>
#include <vector>
#include <string>
#include <zmq.h>
#include <chrono>
#include <pthread.h>
#include <unistd.h>
#include <cassert>
int64_t CurrentTimeMillis()
{
//#ifdef _WIN32
int64_t timems = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
return timems;
}
using namespace std;
/**
* g++ -std=c++11 -Wall -O2 test_zmq_inproc_perf.cpp -lpthread -lzmq -o inproc_test
*/
int test_count = 1000000;
int64_t global_start_time_ms = 0;
// 创建 并设置socket 的属性 (发送和接收水位)
void * CreateSocket(void* context, int type);
/**
* 生产者线程
* 发送大量 8 个字节的数据
*/
static void *
producer_routine(void *m_socket)
{
printf("start send thread!\n");
int k = 0;
int success_cnt = 0;
const int64_t msg_data = 0x12345678;
const int msg_len = sizeof(msg_data);
if(global_start_time_ms <1){
global_start_time_ms = CurrentTimeMillis();
}
while (k < test_count) {
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, msg_len);
assert(rc == 0);
memcpy(zmq_msg_data(&msg), &msg_data, msg_len);
int nbytes = zmq_msg_send(&msg, m_socket, ZMQ_DONTWAIT);
if (nbytes == 8) {
++success_cnt;
} else {
fprintf(stderr, "send error %d, errno = %d!\n", nbytes, errno);
}
++k;
zmq_msg_close(&msg);
}
auto end_time_ms = CurrentTimeMillis();
printf("zmq_inproc_send : cost time %lld ms.\n", (end_time_ms - global_start_time_ms));
printf("zmq_inproc_send : k = %d, success_cnt = %d.\n", k, success_cnt);
return NULL;
}
void start_consumer(void *m_socket, int recv_count_total)
{
int success_cnt = 0;
int64_t fail_count = 0;
int64_t fail_count_eagain = 0;
// 开始接收数据
while (true) {
zmq_msg_t msg;
zmq_msg_init(&msg);
int nbytes = zmq_msg_recv(&msg, m_socket, ZMQ_DONTWAIT);
if (nbytes < 0) {
++fail_count;
//printf("error : 1 recv rc = %d \n", nbytes);
continue;
}
int more = zmq_msg_more(&msg);
if(more){
zmq_msg_close(&msg);
zmq_msg_init(&msg);
nbytes = zmq_msg_recv(&msg, m_socket, ZMQ_DONTWAIT);
// printf("%d is more\n", more);
}
if (nbytes == 8) {
++success_cnt;
// 接收完毕
if (success_cnt >= recv_count_total) {
int64_t* pdata = (int64_t*)(zmq_msg_data(&msg));
printf("last recv 0x%x, nbytes %d!\n ", *pdata, nbytes);
break;
}
zmq_msg_close(&msg);
} else {
printf("error : 2 recv rc = %d \n", nbytes);
if (errno == EAGAIN) {
++fail_count_eagain;
}
if(nbytes > 0){
int32_t* pdata = (int32_t*)(zmq_msg_data(&msg));
printf("recv nbytes = %d, msg_size %d, msg_data = %x\n", nbytes, zmq_msg_size(&msg), *pdata);
}
}
}
auto end_time_ms = CurrentTimeMillis();
printf("zmq_inproc_recv : cost time %lld ms.\n", (end_time_ms - global_start_time_ms));
printf("zmq_inproc_recv : test_count = %d, success_cnt = %d.\n", recv_count_total, success_cnt);
printf("zmq_inproc_recv : fail_count %lld , fail_count_eagain = %lld.\n", fail_count, fail_count_eagain);
}
/**
* TODO 测试发现,先bind 或者先 connect 的先后顺序 不影响程序运行
* @param argc
* @param argv
* @return
*/
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("sizeof(int64_t) %d\n", sizeof(int64_t));
puts("error: input test_count!");
return 0;
}
test_count = atoi(argv[1]);
//ZMQ_PAIR 只适合 1:1 的socket 通信
//如果是 1:n 这里可以使用 ZMQ_PULL + ZMQ_PUSH
//如果是 n:m 这里可以使用 ZMQ_ROUTER + ZMQ_DEALER
void *context = zmq_ctx_new();
void *m_recv_sock = CreateSocket(context, ZMQ_PAIR);
zmq_bind(m_recv_sock, "inproc://workers");
void *m_send_sock = CreateSocket(context, ZMQ_PAIR);
int rc = zmq_connect(m_send_sock, "inproc://workers");
printf("use ZMQ_PAIR! connect rc = %d\n", rc);
pthread_t tid;
pthread_create(&tid, NULL, producer_routine, m_send_sock);
//启动生产者
start_consumer(m_recv_sock, test_count);
/*void *m_send_sock2 = CreateSocket(context, ZMQ_PUSH);
rc = zmq_connect(m_send_sock2, "inproc://workers");
pthread_t tid2;
pthread_create(&tid2, NULL, producer_routine, m_send_sock2);
//启动生产者
start_consumer(m_recv_sock, test_count*2);*/
pthread_join(tid, NULL);
//pthread_join(tid2, NULL);
// We never get here, but clean up anyhow
zmq_close(m_send_sock);
zmq_close(m_recv_sock);
zmq_ctx_destroy(context);
return 0;
}
/********/
void * CreateSocket(void* context, int type)
{
void *m_socket = zmq_socket(context, type);
int iTimeOut = 0;
size_t sizeTimeOut = sizeof(iTimeOut);
zmq_setsockopt(m_socket, ZMQ_SNDTIMEO, &iTimeOut, sizeTimeOut);
zmq_setsockopt(m_socket, ZMQ_RCVTIMEO, &iTimeOut, sizeTimeOut);
// water line
int iHWM = 100000000;
size_t sizeHWM = sizeof(iHWM);
zmq_setsockopt(m_socket, ZMQ_SNDHWM, &iHWM, sizeHWM);
zmq_setsockopt(m_socket, ZMQ_RCVHWM, &iHWM, sizeHWM);
// reconnect interval
int iReconnectInterval = 10;
size_t sizeReconnect = sizeof(iReconnectInterval);
zmq_setsockopt(m_socket, ZMQ_RECONNECT_IVL, &iReconnectInterval, sizeReconnect);
// max reconnect interval
int iMaxReconnectInterval = 2000;
size_t sizeReconnectMax = sizeof(iMaxReconnectInterval);
zmq_setsockopt(m_socket, ZMQ_RECONNECT_IVL_MAX, &iMaxReconnectInterval, sizeReconnectMax);
// tcp heartbeat
int iTcpHeartBeat = 1;
size_t sizeTcpHeartBeat = sizeof(iTcpHeartBeat);
zmq_setsockopt(m_socket, ZMQ_TCP_KEEPALIVE, &iTcpHeartBeat, sizeTcpHeartBeat);
int iTcpIdle = 1;
size_t sizeTcpIdle = sizeof(iTcpIdle);
zmq_setsockopt(m_socket, ZMQ_TCP_KEEPALIVE_IDLE, &iTcpIdle, sizeTcpIdle);
int iTcpCnt = 3;
size_t sizeTcpCnt = sizeof(iTcpCnt);
zmq_setsockopt(m_socket, ZMQ_TCP_KEEPALIVE_CNT, &iTcpCnt, sizeTcpCnt);
int iTcpIntvl = 3;
size_t sizeTcpIntvl = sizeof(iTcpIntvl);
zmq_setsockopt(m_socket, ZMQ_TCP_KEEPALIVE_INTVL, &iTcpIntvl, sizeTcpIntvl);
int iZmqLiner = 0;
size_t sizeLiner = sizeof(iZmqLiner);
zmq_setsockopt(m_socket, ZMQ_LINGER, &iZmqLiner, sizeLiner);
return m_socket;
}
/**
* SOCKET 类型使用 push/pull 效率 和 ROUTER/DEALER 差不多,只是 ROUTER/DEALER 每次会发送2 帧
connect rc = 0
start send thread!
last recv 0x12345678, nbytes 8!
zmq_inproc_recv : cost time 2200 ms.
zmq_inproc_recv : test_count = 10000000, success_cnt = 10000000.
zmq_inproc_recv : fail_count 339851 , fail_count_eagain = 0.
zmq_inproc_send : cost time 2200 ms.
zmq_inproc_send : k = 10000000, success_cnt = 10000000.
*/
| 30.854626 | 136 | 0.643632 | ForrestSu |
2feef87cd92c4cf7ed70cd5289ee1ae1d3b0a2f5 | 6,492 | cpp | C++ | src/drawBitmap.cpp | solhuebner/ardynia | 23e1f2449c7f4919eb88f23faa40cbd141d05249 | [
"MIT"
] | 41 | 2018-10-08T16:40:53.000Z | 2022-02-22T03:10:02.000Z | src/drawBitmap.cpp | paulderson/ardynia | 431663a63471cc8d11d7245c9992bf1cc1746a5a | [
"MIT"
] | 6 | 2019-02-25T03:55:51.000Z | 2021-08-08T20:08:45.000Z | src/drawBitmap.cpp | paulderson/ardynia | 431663a63471cc8d11d7245c9992bf1cc1746a5a | [
"MIT"
] | 14 | 2018-10-08T16:49:59.000Z | 2021-10-05T06:24:55.000Z | #include "drawBitmap.h"
#include <Arduboy2.h>
/**
* draw a bitmap with an optional mask and optional mirroring
*
* This code is a combination of Arduboy2's Sprite::drawExternalMask() and Ardbitmap's drawBitmap()
*
* This method can accomplish the same effect as most of Sprite's methods:
* drawOverwrite: pass in a mask of NULL
* drawExternalMask: pass in a separate mask
* drawSelfMasked: pass in the same pointer for bitmap and mask
*
* To mirror the sprite, pass in MIRROR_HORIZONTAL or MIRROR_VERTICAL as the mirror parameter.
* To mirrow both ways at once, pass in MIRROR_HORIZONTAL | MIRROR_VERTICAL as the parameter
*/
void drawBitmap(int16_t x, int8_t y, const uint8_t* bitmap, const uint8_t* mask, bool plusMask, uint8_t frame, uint8_t mirror, DrawMode drawMode, uint8_t maskFrame) {
if (bitmap == NULL)
return;
if (maskFrame == 255) {
maskFrame = frame;
} else {
maskFrame = 0;
}
uint8_t w = pgm_read_byte(bitmap++);
uint8_t h = pgm_read_byte(bitmap++);
// no need to draw at all if we're offscreen
if (x + w <= 0 || x > WIDTH - 1 || y + h <= 0 || y > HEIGHT - 1)
return;
if (plusMask) {
mask = bitmap;
}
const boolean hasMask = mask != NULL;
uint16_t frame_offset = (w * ( h / 8 + ( h % 8 == 0 ? 0 : 1)));
if (frame > 0) {
mask += maskFrame * frame_offset;
bitmap += frame * frame_offset;
// plusMask means the sprite is frame,mask,frame,mask
// jump ahead one more time to get to the correct frame
if (plusMask) {
mask += maskFrame * frame_offset;
bitmap += frame * frame_offset;
}
}
if (plusMask) {
mask += frame_offset;
}
// xOffset technically doesn't need to be 16 bit but the math operations
// are measurably faster if it is
uint16_t xOffset, ofs;
int8_t yOffset = abs(y) % 8;
int8_t sRow = y / 8;
uint8_t loop_h, start_h, rendered_width;
if (y < 0 && yOffset > 0) {
sRow--;
yOffset = 8 - yOffset;
}
// if the left side of the render is offscreen skip those loops
if (x < 0) {
xOffset = abs(x);
} else {
xOffset = 0;
}
// if the right side of the render is offscreen skip those loops
if (x + w > WIDTH - 1) {
rendered_width = ((WIDTH - x) - xOffset);
} else {
rendered_width = (w - xOffset);
}
// if the top side of the render is offscreen skip those loops
if (sRow < -1) {
start_h = abs(sRow) - 1;
} else {
start_h = 0;
}
loop_h = h / 8 + (h % 8 > 0 ? 1 : 0); // divide, then round up
// if (sRow + loop_h - 1 > (HEIGHT/8)-1)
if (sRow + loop_h > (HEIGHT / 8)) {
loop_h = (HEIGHT / 8) - sRow;
}
// prepare variables for loops later so we can compare with 0
// instead of comparing two variables
loop_h -= start_h;
sRow += start_h;
ofs = (sRow * WIDTH) + x + xOffset;
const uint8_t *bofs = bitmap + (start_h * w) + xOffset;
const uint8_t *mask_ofs = mask + (start_h * w) + xOffset;
if (mirror & MIRROR_HORIZONTAL) {
bofs += rendered_width - 1;
mask_ofs += rendered_width - 1;
if (x < 0){
bofs -= w - rendered_width;
mask_ofs -= w - rendered_width;
} else{
bofs += w - rendered_width;
mask_ofs += w - rendered_width;
}
}
if (mirror & MIRROR_VERTICAL) {
bofs += (loop_h - 1) * w;
mask_ofs += (loop_h - 1) * w;
if (y < 0) {
bofs -= (start_h * w);
mask_ofs -= (start_h * w);
}
}
uint8_t data;
uint8_t mul_amt = 1 << yOffset;
uint16_t bitmap_data;
uint16_t mask_data;
// really if yOffset = 0 you have a faster case here that could be
// optimized
for (uint8_t a = 0; a < loop_h; a++) {
for (uint8_t iCol = 0; iCol < rendered_width; iCol++) {
data = pgm_read_byte(bofs);
mask_data = hasMask ? pgm_read_byte(mask_ofs) : 0xFF;
if (drawMode != Normal) {
data = ~data & mask_data;
}
if (mirror & MIRROR_VERTICAL) {
//reverse bits
data = (data & 0xF0) >> 4 | (data & 0x0F) << 4;
data = (data & 0xCC) >> 2 | (data & 0x33) << 2;
data = (data & 0xAA) >> 1 | (data & 0x55) << 1;
mask_data = (mask_data & 0xF0) >> 4 | (mask_data & 0x0F) << 4;
mask_data = (mask_data & 0xCC) >> 2 | (mask_data & 0x33) << 2;
mask_data = (mask_data & 0xAA) >> 1 | (mask_data & 0x55) << 1;
}
bitmap_data = data * mul_amt;
mask_data = ~(mask_data * mul_amt);
if (drawMode == Xor) {
if (sRow >= 0) {
data = Arduboy2Base::sBuffer[ofs];
Arduboy2Base::sBuffer[ofs] = data ^ bitmap_data;
}
if (yOffset != 0 && sRow < 7) {
data = Arduboy2Base::sBuffer[ofs + WIDTH];
Arduboy2Base::sBuffer[ofs + WIDTH] = data ^ (*((unsigned char *) (&bitmap_data) + 1));
}
} else {
if (sRow >= 0) {
data = Arduboy2Base::sBuffer[ofs];
data &= (uint8_t)(mask_data);
data |= (uint8_t)(bitmap_data);
Arduboy2Base::sBuffer[ofs] = data;
}
if (yOffset != 0 && sRow < 7) {
data = Arduboy2Base::sBuffer[ofs + WIDTH];
data &= (*((unsigned char *) (&mask_data) + 1));
data |= (*((unsigned char *) (&bitmap_data) + 1));
Arduboy2Base::sBuffer[ofs + WIDTH] = data;
}
}
ofs++;
if (mirror & MIRROR_HORIZONTAL) {
bofs--;
mask_ofs--;
} else{
bofs++;
mask_ofs++;
}
}
sRow++;
if (mirror & MIRROR_HORIZONTAL) {
bofs += w + rendered_width;
mask_ofs += w + rendered_width;
} else{
bofs += w - rendered_width;
mask_ofs += w - rendered_width;
}
if (mirror & MIRROR_VERTICAL) {
bofs -= 2 * w;
mask_ofs -= 2 * w;
}
ofs += WIDTH - rendered_width;
}
}
| 30.767773 | 166 | 0.504467 | solhuebner |
2fef4489639e885cd1ccf3ab83099f1155306d7e | 534 | cpp | C++ | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#define maxn 60
#define maxm 410
using namespace std;
int Vmax,Mmax;
int n;
int v[maxn],m[maxn],cal[maxn];
int dp[maxm][maxm];
int main()
{
scanf("%d %d",&Vmax,&Mmax);
scanf("%d",&n);
for(int i = 1; i <= n; ++i)
{
scanf("%d %d %d",&v[i],&m[i],&cal[i]);
}
for(int i = 1; i <= n; ++i)
{
for(int j = Mmax; j >= m[i]; --j)
{
for(int k = Vmax; k >= v[i]; --k)
{
dp[j][k] = max(dp[j][k],dp[j-m[i]][k-v[i]]+cal[i]);
}
}
}
printf("%d",dp[Mmax][Vmax]);
return 0;
}
| 14.432432 | 55 | 0.490637 | ajidow |
2ff11fc42c7206551433943312a819d138d29b8e | 1,351 | cpp | C++ | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 5 | 2020-04-24T17:34:54.000Z | 2021-04-07T15:56:00.000Z | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 5 | 2021-05-13T14:16:35.000Z | 2021-08-15T15:11:55.000Z | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 1 | 2021-05-09T12:17:30.000Z | 2021-05-09T12:17:30.000Z | #include <bats.hpp>
#include <iostream>
#define FT ModP<int, 3>
int main() {
bats::future::Matrix A(5,5, FT(1));
A(1,0) = 0;
A(2,1) = 2;
A(3,2) = 2;
A.print();
// auto H1 = HessenbergTransform(A);
// H1.print();
// H1.prod().print();
//
// std::cout << "hessenberg_to_companion" << std::endl;
//
// hessenberg_to_companion(H1);
// H1.print();
// H1.prod().print();
auto F = bats::future::LU(A);
F.print();
std::cout << "product:" << std::endl;
auto P = F.prod();
P.print();
size_t test[2] = {1,2};
std::cout << test[0] << test[1] << std::endl;
P = bats::future::Matrix<FT>(P, bats::future::ColumnMajor());
P.append_column();
P.print();
auto r = bats::future::range(0, 4);
std::vector<size_t> c = {0,2,3} ;
// auto view = MatrixView(P, r, c);
auto view = P.view(r,c);
// auto view = MatrixView(P, range(0, 4), range(0, 3));
view.print();
auto S = bats::future::Span(2, FT());
S.Pt.print();
S.L.print();
std::vector<FT> v = {1,1};
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
v = {1,0};
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
// std::cout << S.L.column(0)[1] << std::endl;
std::cout << S.contains(v) << std::endl;
v = {0,1};
std::cout << S.contains(v) << std::endl;
return 0;
}
| 17.776316 | 62 | 0.541821 | YuanL12 |
2ff28ed346fd99064cd2abecccf0ab33431d93af | 399 | cpp | C++ | C++/OOP/inheritance/multilevel-inheritance.cpp | mohitkhedkar/Programming-Language-Basics | 82252d6d056079a1b581e8299b69638d44444e6a | [
"MIT"
] | null | null | null | C++/OOP/inheritance/multilevel-inheritance.cpp | mohitkhedkar/Programming-Language-Basics | 82252d6d056079a1b581e8299b69638d44444e6a | [
"MIT"
] | null | null | null | C++/OOP/inheritance/multilevel-inheritance.cpp | mohitkhedkar/Programming-Language-Basics | 82252d6d056079a1b581e8299b69638d44444e6a | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"eating"<<endl;
}
};
class Dog: public Animal{
public:
void bark(){
cout<<"Barking"<<endl;
}
};
class BabyDog: public Dog{
public:
void weep(){
cout<<"Weeping"<<endl;
}
};
int main(){
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
} | 13.3 | 30 | 0.52381 | mohitkhedkar |
2ff925f50291ade82dd732d6a582bdeeea36fe7e | 1,620 | cpp | C++ | src/round/common/StringTokenizer.cpp | cybergarage/round-cc | 13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1 | [
"BSD-3-Clause"
] | null | null | null | src/round/common/StringTokenizer.cpp | cybergarage/round-cc | 13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1 | [
"BSD-3-Clause"
] | null | null | null | src/round/common/StringTokenizer.cpp | cybergarage/round-cc | 13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <round/common/StringTokenizer.h>
Round::StringTokenizer::StringTokenizer(const std::string &str, const std::string &delim) {
hasNextTokens = true;
strBuf = str;
strDelim = delim;
lastDelimPos = std::string::npos;
nextToken(delim);
}
Round::StringTokenizer::~StringTokenizer() {}
bool Round::StringTokenizer::hasMoreTokens() {
return hasNextTokens;
}
const char *Round::StringTokenizer::nextToken() {
return nextToken(strDelim.c_str());
}
const char *Round::StringTokenizer::nextToken(const std::string &delim) {
strCurrToken = strNextToken;
std::string::size_type findStartDelimPos = (lastDelimPos == std::string::npos) ? 0 : (lastDelimPos+1);
std::string::size_type startDelimPos = strBuf.find_first_not_of(delim, findStartDelimPos);
if (startDelimPos == std::string::npos) {
hasNextTokens = false;
strNextToken = "";
return strCurrToken.c_str();
}
std::string::size_type endDelimPos = strBuf.find_first_of(delim, startDelimPos);
if (endDelimPos == std::string::npos)
endDelimPos = strBuf.length();
strNextToken = strBuf.substr(startDelimPos, endDelimPos-startDelimPos);
lastDelimPos = endDelimPos;
return strCurrToken.c_str();
}
std::size_t Round::StringTokenizer::getTokens(StringTokenList *tokenList) {
while (hasMoreTokens())
tokenList->push_back(nextToken());
return tokenList->size();
}
| 27.931034 | 104 | 0.668519 | cybergarage |
2ff9d7d478df79adce264170d405ea95bbfcf349 | 569 | cpp | C++ | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | #include "messagebuilder.hpp"
#include <iostream>
using std::cerr;
void
MessageBuilder::addChunk(
const char *chunk,
size_t chunk_size,
const MessageHandler& message_handler
)
{
size_t i=0;
while (i!=chunk_size) {
size_t begin = i;
while (i!=chunk_size && chunk[i]!='\0') {
++i;
}
message_so_far.append(chunk+begin,i-begin);
if (i==chunk_size) {
// Got a partial message_so_far
return;
}
assert(chunk[i]=='\0');
message_handler(message_so_far);
message_so_far.clear();
++i;
}
}
| 14.589744 | 47 | 0.602812 | vcato |
2ffdcc5bf5f728e1d17b54d45a3587b197febfac | 1,986 | cpp | C++ | gm/picture.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 3 | 2020-08-06T00:31:13.000Z | 2021-07-29T07:28:17.000Z | gm/picture.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 3 | 2020-04-26T17:03:31.000Z | 2020-04-28T14:55:33.000Z | gm/picture.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 57 | 2016-12-29T02:00:25.000Z | 2021-11-16T01:22:50.000Z | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPictureRecorder.h"
static sk_sp<SkPicture> make_picture() {
SkPictureRecorder rec;
SkCanvas* canvas = rec.beginRecording(100, 100);
SkPaint paint;
paint.setAntiAlias(true);
SkPath path;
paint.setColor(0x800000FF);
canvas->drawRect(SkRect::MakeWH(100, 100), paint);
paint.setColor(0x80FF0000);
path.moveTo(0, 0); path.lineTo(100, 0); path.lineTo(100, 100);
canvas->drawPath(path, paint);
paint.setColor(0x8000FF00);
path.reset(); path.moveTo(0, 0); path.lineTo(100, 0); path.lineTo(0, 100);
canvas->drawPath(path, paint);
paint.setColor(0x80FFFFFF);
paint.setBlendMode(SkBlendMode::kPlus);
canvas->drawRect(SkRect::MakeXYWH(25, 25, 50, 50), paint);
return rec.finishRecordingAsPicture();
}
// Exercise the optional arguments to drawPicture
//
class PictureGM : public skiagm::GM {
public:
PictureGM()
: fPicture(nullptr)
{}
protected:
void onOnceBeforeDraw() override {
fPicture = make_picture();
}
SkString onShortName() override {
return SkString("pictures");
}
SkISize onISize() override {
return SkISize::Make(450, 120);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(10, 10);
SkMatrix matrix;
SkPaint paint;
canvas->drawPicture(fPicture);
matrix.setTranslate(110, 0);
canvas->drawPicture(fPicture, &matrix, nullptr);
matrix.postTranslate(110, 0);
canvas->drawPicture(fPicture, &matrix, &paint);
paint.setAlphaf(0.5f);
matrix.postTranslate(110, 0);
canvas->drawPicture(fPicture, &matrix, &paint);
}
private:
sk_sp<SkPicture> fPicture;
typedef skiagm::GM INHERITED;
};
DEF_GM(return new PictureGM;)
| 23.093023 | 78 | 0.650554 | pospx |
2ffea2ad79528e7c0808b12426690b2552f1413d | 2,413 | cpp | C++ | src/Arabic/names/ar_IdFTokens.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Arabic/names/ar_IdFTokens.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Arabic/names/ar_IdFTokens.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
#include "Arabic/names/ar_IdFTokens.h"
#include <string>
#include <cstdio>
IdFTokens::IdFTokens(){
//arrays are statically allocated
_numTokens = 0;
}
IdFTokens::~IdFTokens(){
resetTokens();
}
int IdFTokens::getNumTokens(){
return _numTokens;
}
const LexicalToken* IdFTokens::getToken(int tokNum){
return _idfTokens[tokNum];
}
int IdFTokens::getSerifTokenNum(int tokNum){
return _tokMap[tokNum];
}
void IdFTokens::tokenize(const TokenSequence* serifTokens){
const LexicalTokenSequence *serifLexicalTokens = dynamic_cast<const LexicalTokenSequence*>(serifTokens);
if (!serifLexicalTokens) throw InternalInconsistencyException("IdFTokens::tokenize",
"This IdFTokens name recognizer requires a LexicalTokenSequence.");
int numSerifTok = serifLexicalTokens->getNTokens();
for(int i = 0; i< numSerifTok; i++){
Symbol serifWord = serifLexicalTokens->getToken(i)->getSymbol();
int serifOrigTok = i;
const std::wstring word =serifWord.to_string();
if((word.length() < 2) || !isIdFClitic(word.at(0))){
_idfTokens[_numTokens] = _new LexicalToken(*serifLexicalTokens->getToken(i), serifOrigTok, 0, NULL);
_tokMap[_numTokens] = i;
_numTokens++;
}
else{
// Note: the offset span for both the clitic and the subword are set to the span of the entire
// source word. We don't set clitic's span to cover the first character and the subword's
// span to cover the remainder of the word's characters.
_clitic[0] = word.at(0);
_clitic[1] =L'\0';
_idfTokens[_numTokens] = _new LexicalToken(*serifLexicalTokens->getToken(i), Symbol(_clitic), serifOrigTok);
_tokMap[_numTokens] = i;
_numTokens++;
int len = word.length() <75 ? static_cast<int>(word.length()) : 75;
int j = 0;
for(j = 1; j<len; j++){
_subword[j-1] = word.at(j);
}
_subword[j-1] = L'\0';
_idfTokens[_numTokens] = _new LexicalToken(*serifLexicalTokens->getToken(i), Symbol(_subword), serifOrigTok);
_tokMap[_numTokens] = i;
_numTokens++;
}
}
}
void IdFTokens::resetTokens(){
for(int i =0; i<_numTokens; i++){
delete _idfTokens[i];
}
_numTokens = 0;
}
//true if c is b, l, w
bool IdFTokens::isIdFClitic(wchar_t c){
return ( (c==L'\x648') || (c==L'\x628') || (c==L'\x644') );
}
| 31.75 | 113 | 0.678823 | BBN-E |
64001866965efbaa045fa902d576df34e221d8fd | 990 | cpp | C++ | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | #include <vector>
#include <Graphics/Renderer.h>
#include <Entity/Components/Camera.h>
#include <Game/SceneLoader.h>
#include "GameObject.h"
#include "Scene.h"
#include "SceneManager.h"
//Properties
namespace SceneManager
{
//Private
Scene *scene;
}
void SceneManager::SetScene(Scene *s)
{
if (scene != nullptr)
scene->Close();
scene = s;
Start();
Renderer::SetScene(scene);
}
Scene* SceneManager::GetCurrent()
{
return scene;
}
void SceneManager::SetCurrentCamera(Camera *cam)
{
scene->SetCurrentCamera(cam);
}
void SceneManager::Start()
{
if (scene != nullptr)
scene->Start();
}
void SceneManager::Update()
{
if (scene != nullptr)
scene->Update();
}
bool SceneManager::CheckScene()
{
return scene != nullptr;
}
void SceneManager::UnloadScene(Scene **s)
{
(*s)->Unload();
*s = nullptr;
}
void SceneManager::LoadScene(const char *path, Scene **inScene, bool setCurrent)
{
SceneLoader::LoadScene(path, inScene, setCurrent);
}
void SceneManager::Close()
{
}
| 14.347826 | 80 | 0.694949 | Nordaj |
6400e34a737eb3fba8a54b442d7a577821976df7 | 399 | hpp | C++ | RaiderEngine/ObjectRegistryBase.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | 4 | 2019-07-20T08:41:04.000Z | 2022-03-04T01:53:38.000Z | RaiderEngine/ObjectRegistryBase.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | RaiderEngine/ObjectRegistryBase.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
#include "GameObject.hpp"
#include "Light.hpp"
class ObjectRegistryBase {
public:
virtual GameObject* instantiateGameObject(std::string name, glm::vec3 pos, glm::vec3 rot, glm::vec3 scale, std::vector<std::string> extraArgs);
virtual Light* instantiateLight(std::string name, glm::vec3 pos, glm::vec3 rot, glm::vec3 scale, std::vector<std::string> extraArgs);
}; | 36.272727 | 144 | 0.746867 | rystills |
6401d0ca36a268f8acae3ca3adf73ddf79d557d2 | 4,336 | cpp | C++ | src/utils/Log.cpp | pkicki/bench-mr | db22f75062aff47cf0800c8a2189db1f674a93cc | [
"Apache-2.0",
"MIT"
] | 41 | 2021-02-10T08:40:34.000Z | 2022-03-20T18:33:20.000Z | src/utils/Log.cpp | pkicki/bench-mr | db22f75062aff47cf0800c8a2189db1f674a93cc | [
"Apache-2.0",
"MIT"
] | 5 | 2021-06-15T14:27:53.000Z | 2022-02-20T08:16:55.000Z | src/utils/Log.cpp | pkicki/bench-mr | db22f75062aff47cf0800c8a2189db1f674a93cc | [
"Apache-2.0",
"MIT"
] | 23 | 2021-04-07T08:09:49.000Z | 2022-03-20T18:33:53.000Z | #include "Log.h"
#include <stdio.h>
#include <stdlib.h>
#include "smoothers/grips/GRIPS.h"
nlohmann::json Log::_json = {{"runs", nlohmann::json::array()}};
nlohmann::json Log::_currentRun;
void Log::instantiateRun() {
auto time =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%F %T", std::localtime(&time));
std::string tstr(mbstr);
tstr = tstr.substr(0, tstr.length() - 1);
_currentRun = {{"globals",
{
{"time", tstr},
}},
{"runs", nlohmann::json::array()}};
_currentRun["settings"] = nlohmann::json(global::settings)["settings"];
_currentRun["settings"]["steering"] =
Steering::to_string(global::settings.steer.steering_type);
}
void Log::log(const PathStatistics &stats) {
nlohmann::json runStats = stats;
runStats["ps_roundStats"] = GRIPS::statsPerRound;
_currentRun["runs"].push_back(runStats);
}
void Log::log(const nlohmann::json &stats) {
_currentRun["runs"].push_back(stats);
}
void Log::save(std::string filename, const std::string &path) {
if (filename.empty()) filename = Log::filename() + (std::string) ".json";
std::ofstream o(filename);
o << std::setw(4) << _currentRun << std::endl;
o.close();
OMPL_INFORM("Saved log at %s", filename.c_str());
}
void Log::storeRun() { _json["runs"].push_back(_currentRun); }
bool replace(std::string &str, const std::string &from, const std::string &to) {
// thanks to https://stackoverflow.com/a/3418285
size_t start_pos = str.find(from);
if (start_pos == std::string::npos) return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string Log::filename() {
auto env_name = global::settings.environment->name();
replace(env_name, "/", "_");
replace(env_name, ".", "_");
replace(env_name, ":", "_");
replace(env_name, "*", "_");
return _currentRun["settings"]["steering"].get<std::string>() + " " +
std::to_string(global::settings.environment->width()) + "x" +
std::to_string(global::settings.environment->height()) + " " +
env_name + " " + _currentRun["globals"]["time"].get<std::string>();
}
std::vector<std::array<double, 2>> Log::serializePath(
const std::vector<Point> &path) {
std::vector<std::array<double, 2>> r;
for (auto &p : path) r.push_back({p.x, p.y});
return r;
}
std::vector<std::array<double, 3>> Log::serializeTrajectory(
const ompl::geometric::PathGeometric &t, bool interpolate) {
ompl::geometric::PathGeometric traj = t;
if (interpolate) traj = PlannerUtils::interpolated(t);
std::vector<std::array<double, 3>> r;
double x, y, yaw;
for (auto i = 0u; i < traj.getStateCount(); ++i) {
if (global::settings.forwardpropagation.forward_propagation_type ==
ForwardPropagation::FORWARD_PROPAGATION_TYPE_KINEMATIC_SINGLE_TRACK) {
const auto *compState =
traj.getState(i)->as<ob::CompoundStateSpace::StateType>();
const auto *se2state = compState->as<ob::SE2StateSpace::StateType>(0);
x = se2state->getX();
y = se2state->getY();
yaw = se2state->getYaw();
} else {
const auto *s = traj.getState(i)->as<State>();
x = s->getX();
y = s->getY();
yaw = s->getYaw();
}
r.push_back({x, y, yaw});
}
return r;
}
std::vector<std::array<double, 3>> Log::serializeTrajectory(
const ompl::control::PathControl &t, bool interpolate) {
ompl::control::PathControl traj = t;
if (interpolate) traj = PlannerUtils::interpolated(t);
std::vector<std::array<double, 3>> r;
for (auto i = 0u; i < traj.getStateCount(); ++i) {
if (global::settings.forwardpropagation.forward_propagation_type ==
ForwardPropagation::FORWARD_PROPAGATION_TYPE_KINEMATIC_CAR) {
const auto *s = traj.getState(i)->as<State>();
r.push_back({s->getX(), s->getY(), s->getYaw()});
}
if (global::settings.forwardpropagation.forward_propagation_type ==
ForwardPropagation::FORWARD_PROPAGATION_TYPE_KINEMATIC_SINGLE_TRACK) {
const auto *s = traj.getState(i)->as<ob::CompoundStateSpace::StateType>();
const auto *se2state = s->as<ob::SE2StateSpace::StateType>(0);
r.push_back({se2state->getX(), se2state->getY(), se2state->getYaw()});
}
}
return r;
} | 34.688 | 80 | 0.63953 | pkicki |
64028553177bfa199627de11285bd3d494d40879 | 1,218 | cpp | C++ | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | #include <polyvec/curve-tracer/curve_constraints.hpp>
using namespace polyvec;
GlobFitConstraint_LineDirection::GlobFitConstraint_LineDirection(GlobFitLineParametrization* line, GlobFitCurveParametrization::ParameterAddress& target)
: line(line)
{
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 0));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 1));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 2));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 3));
this->target_param = target;
}
std::pair<double, Eigen::VectorXd> GlobFitConstraint_LineDirection::f()
{
Eigen::Vector2d diff = line->get_curve()->pos(1.0) - line->get_curve()->pos(0.0);
auto dDiffdParams = line->dposdparams(1.0) - line->dposdparams(0.0);
double angle = std::atan2(diff.y(), diff.x());
double xSq = diff.x() * diff.x();
double ySq = diff.y() * diff.y();
double denom = xSq + ySq;
Eigen::Vector2d dAngledDiff(-diff.y() / denom, diff.x() / denom);
Eigen::VectorXd dAngledParams = (dAngledDiff.transpose() * dDiffdParams).transpose();
return std::make_pair(angle, dAngledParams);
} | 39.290323 | 153 | 0.759442 | dedoardo |
64041b31db8531435f261be78200fa5609186602 | 263 | hpp | C++ | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 39 | 2020-07-15T13:36:44.000Z | 2022-03-21T00:46:00.000Z | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 255 | 2020-07-16T17:54:59.000Z | 2022-03-27T20:16:51.000Z | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 11 | 2020-07-15T21:46:48.000Z | 2022-03-24T22:19:17.000Z | #pragma once
#include <catch2/catch.hpp>
#include <fmt/format.h>
template <typename T>
requires fmt::has_formatter<T, fmt::format_context>::value struct Catch::StringMaker<T> {
static std::string convert(const T &value) { return fmt::to_string(value); }
};
| 26.3 | 89 | 0.726236 | frederic-tingaud-sonarsource |
6405f83ca701f14127c5b3f8483e53625a63617b | 27,962 | cpp | C++ | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | #include <windows.h>
#include <iostream>
#include <algorithm>
#include "RegistryKey.hpp"
#include "AutoPlay.hpp"
#include "../GeneralUtil.hpp"
#include <TraceLoggingProvider.h>
#include "../MsixTraceLoggingProvider.hpp"
#include "Constants.hpp"
#include "CryptoProvider.hpp"
#include "Base32Encoding.hpp"
#include <StrSafe.h>
using namespace MsixCoreLib;
const PCWSTR AutoPlay::HandlerName = L"AutoPlay";
HRESULT AutoPlay::ExecuteForAddRequest()
{
for (auto autoPlay = m_autoPlay.begin(); autoPlay != m_autoPlay.end(); ++autoPlay)
{
RETURN_IF_FAILED(ProcessAutoPlayForAdd(*autoPlay));
}
return S_OK;
}
HRESULT AutoPlay::ExecuteForRemoveRequest()
{
for (auto autoPlay = m_autoPlay.begin(); autoPlay != m_autoPlay.end(); ++autoPlay)
{
RETURN_IF_FAILED(ProcessAutoPlayForRemove(*autoPlay));
}
return S_OK;
}
HRESULT AutoPlay::ProcessAutoPlayForRemove(AutoPlayObject& autoPlayObject)
{
RegistryKey explorerKey;
RETURN_IF_FAILED(explorerKey.Open(HKEY_LOCAL_MACHINE, explorerRegKeyName.c_str(), KEY_READ | KEY_WRITE));
RegistryKey handlerRootKey;
HRESULT hrCreateSubKey = explorerKey.CreateSubKey(handlerKeyName.c_str(), KEY_READ | KEY_WRITE, &handlerRootKey);
if (SUCCEEDED(hrCreateSubKey))
{
const HRESULT hrDeleteSubKeyTree = handlerRootKey.DeleteTree(autoPlayObject.generatedhandlerName.c_str());
if (FAILED(hrDeleteSubKeyTree) && hrDeleteSubKeyTree != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay generatedHandlerName",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteSubKeyTree, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
}
else
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
if (autoPlayObject.autoPlayType == DesktopAppxContent)
{
RegistryKey classesRootKey;
HRESULT hrCreateSubKey = classesRootKey.Open(HKEY_LOCAL_MACHINE, classesKeyPath.c_str(), KEY_READ | KEY_WRITE | WRITE_DAC);
if (SUCCEEDED(hrCreateSubKey))
{
const HRESULT hrDeleteSubKeyTree = classesRootKey.DeleteTree(autoPlayObject.generatedProgId.c_str());
if (FAILED(hrDeleteSubKeyTree) && hrDeleteSubKeyTree != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay progId reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteSubKeyTree, "HR"),
TraceLoggingValue(autoPlayObject.generatedProgId.c_str(), "GeneratedProgId"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
}
}
RegistryKey handleEventRootKey;
hrCreateSubKey = explorerKey.CreateSubKey(eventHandlerRootRegKeyName.c_str(), KEY_READ | KEY_WRITE, &handleEventRootKey);
if (SUCCEEDED(hrCreateSubKey))
{
RegistryKey handleEventKey;
HRESULT hrCreateHandleSubKey = handleEventRootKey.CreateSubKey(autoPlayObject.handleEvent.c_str(), KEY_READ | KEY_WRITE, &handleEventKey);
if (SUCCEEDED(hrCreateHandleSubKey))
{
const HRESULT hrDeleteValue = handleEventKey.DeleteValue(autoPlayObject.generatedhandlerName.c_str());
if (FAILED(hrDeleteValue) && hrDeleteValue != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay handleEventKey generatedHandlerName reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteValue, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrDeleteValue;
}
}
else
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateHandleSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrCreateHandleSubKey;
}
}
else
{
// Log failure of creating the handleEventRootKey
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrCreateSubKey;
}
return S_OK;
}
HRESULT AutoPlay::ParseManifest()
{
ComPtr<IMsixDocumentElement> domElement;
RETURN_IF_FAILED(m_msixRequest->GetPackageInfo()->GetManifestReader()->QueryInterface(UuidOfImpl<IMsixDocumentElement>::iid, reinterpret_cast<void**>(&domElement)));
ComPtr<IMsixElement> element;
RETURN_IF_FAILED(domElement->GetDocumentElement(&element));
ComPtr<IMsixElementEnumerator> extensionEnum;
RETURN_IF_FAILED(element->GetElements(extensionQuery.c_str(), &extensionEnum));
BOOL hasCurrent = FALSE;
RETURN_IF_FAILED(extensionEnum->GetHasCurrent(&hasCurrent));
while (hasCurrent)
{
ComPtr<IMsixElement> extensionElement;
RETURN_IF_FAILED(extensionEnum->GetCurrent(&extensionElement));
Text<wchar_t> extensionCategory;
RETURN_IF_FAILED(extensionElement->GetAttributeValue(categoryAttribute.c_str(), &extensionCategory));
if (wcscmp(extensionCategory.Get(), desktopAppXExtensionCategory.c_str()) == 0)
{
BOOL hc_invokeAction = FALSE;
ComPtr<IMsixElementEnumerator> invokeActionEnum;
RETURN_IF_FAILED(extensionElement->GetElements(invokeActionQuery.c_str(), &invokeActionEnum));
RETURN_IF_FAILED(invokeActionEnum->GetHasCurrent(&hc_invokeAction));
while (hc_invokeAction)
{
ComPtr<IMsixElement> invokeActionElement;
RETURN_IF_FAILED(invokeActionEnum->GetCurrent(&invokeActionElement));
//desktop appx content element
BOOL has_DesktopAppxContent = FALSE;
ComPtr<IMsixElementEnumerator> desktopAppxContentEnum;
RETURN_IF_FAILED(invokeActionElement->GetElements(invokeActionContentQuery.c_str(), &desktopAppxContentEnum));
RETURN_IF_FAILED(desktopAppxContentEnum->GetHasCurrent(&has_DesktopAppxContent));
while (has_DesktopAppxContent)
{
ComPtr<IMsixElement> desktopAppxContentElement;
RETURN_IF_FAILED(desktopAppxContentEnum->GetCurrent(&desktopAppxContentElement));
AutoPlayObject autoPlay;
//autoplay type
autoPlay.autoPlayType = DesktopAppxContent;
//action
Text<wchar_t> action;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(actionAttributeName.c_str(), &action));
autoPlay.action = action.Get();
//provider
Text<wchar_t> provider;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(providerAttributeName.c_str(), &provider));
autoPlay.provider = provider.Get();
// Get the App's app user model id
autoPlay.appUserModelId = m_msixRequest->GetPackageInfo()->GetId();
//get the logo
std::wstring logoPath = m_msixRequest->GetPackageInfo()->GetPackageDirectoryPath() + m_msixRequest->GetPackageInfo()->GetRelativeLogoPath();
std::wstring iconPath;
RETURN_IF_FAILED(ConvertLogoToIcon(logoPath, iconPath));
autoPlay.defaultIcon = iconPath.c_str();
//verb
Text<wchar_t> id;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(idAttributeName.c_str(), &id));
autoPlay.id = id.Get();
//content event
Text<wchar_t> handleEvent;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(contentEventAttributeName.c_str(), &handleEvent));
autoPlay.handleEvent = handleEvent.Get();
//drop target handler
Text<wchar_t> dropTargetHandler;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(dropTargetHandlerAttributeName.c_str(), &dropTargetHandler));
if (dropTargetHandler.Get() != nullptr)
{
autoPlay.dropTargetHandler = dropTargetHandler.Get();
}
//parameters
Text<wchar_t> parameters;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(parametersAttributeName.c_str(), ¶meters));
if (parameters.Get() != nullptr)
{
autoPlay.parameters = parameters.Get();
}
//GenerateProgId
std::wstring uniqueProgId;
uniqueProgId.append(id.Get());
uniqueProgId.append(handleEvent.Get());
std::wstring generatedProgId;
RETURN_IF_FAILED(GenerateProgId(desktopAppXExtensionCategory.c_str(), uniqueProgId.c_str(), generatedProgId));
autoPlay.generatedProgId = generatedProgId.c_str();
//GenerateHandlerName
std::wstring uniqueHandlerName;
uniqueHandlerName.append(id.Get());
uniqueHandlerName.append(handleEvent.Get());
std::wstring generatedHandlerName;
RETURN_IF_FAILED(GenerateHandlerName(L"DesktopAppXContent", uniqueHandlerName.c_str(), generatedHandlerName));
autoPlay.generatedhandlerName = generatedHandlerName.c_str();
m_autoPlay.push_back(autoPlay);
RETURN_IF_FAILED(desktopAppxContentEnum->MoveNext(&has_DesktopAppxContent));
}
//desktop appx device element
BOOL has_DesktopAppxDevice = FALSE;
ComPtr<IMsixElementEnumerator> desktopAppxDeviceEnum;
RETURN_IF_FAILED(invokeActionElement->GetElements(invokeActionDeviceQuery.c_str(), &desktopAppxDeviceEnum));
RETURN_IF_FAILED(desktopAppxDeviceEnum->GetHasCurrent(&has_DesktopAppxDevice));
while (has_DesktopAppxDevice)
{
ComPtr<IMsixElement> desktopAppxDeviceElement;
RETURN_IF_FAILED(desktopAppxDeviceEnum->GetCurrent(&desktopAppxDeviceElement));
AutoPlayObject autoPlay;
//autoplay type
autoPlay.autoPlayType = DesktopAppxDevice;
//action
Text<wchar_t> action;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(actionAttributeName.c_str(), &action));
autoPlay.action = action.Get();
//provider
Text<wchar_t> provider;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(providerAttributeName.c_str(), &provider));
autoPlay.provider = provider.Get();
// Get the App's app user model id
autoPlay.appUserModelId = m_msixRequest->GetPackageInfo()->GetId();
//get the logo
std::wstring logoPath = m_msixRequest->GetPackageInfo()->GetPackageDirectoryPath() + m_msixRequest->GetPackageInfo()->GetRelativeLogoPath();
std::wstring iconPath;
RETURN_IF_FAILED(ConvertLogoToIcon(logoPath, iconPath));
autoPlay.defaultIcon = iconPath.c_str();
//handle event
Text<wchar_t> handleEvent;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(deviceEventAttributeName.c_str(), &handleEvent));
autoPlay.handleEvent = handleEvent.Get();
//hwEventHandler
Text<wchar_t> hwEventHandler;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(hwEventHandlerAttributeName.c_str(), &hwEventHandler));
autoPlay.hwEventHandler = hwEventHandler.Get();
//init cmd line
Text<wchar_t> initCmdLine;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(InitCmdLineAttributeName.c_str(), &initCmdLine));
if (initCmdLine.Get() != nullptr)
{
autoPlay.initCmdLine = initCmdLine.Get();
}
//GenerateHandlerName
std::wstring uniqueHandlerName;
uniqueHandlerName.append(handleEvent.Get());
std::wstring generatedHandlerName;
RETURN_IF_FAILED(GenerateHandlerName(L"DesktopAppXDevice", uniqueHandlerName.c_str(), generatedHandlerName));
autoPlay.generatedhandlerName = generatedHandlerName.c_str();
m_autoPlay.push_back(autoPlay);
RETURN_IF_FAILED(desktopAppxDeviceEnum->MoveNext(&has_DesktopAppxDevice));
}
RETURN_IF_FAILED(invokeActionEnum->MoveNext(&hc_invokeAction));
}
}
RETURN_IF_FAILED(extensionEnum->MoveNext(&hasCurrent));
}
return S_OK;
}
HRESULT AutoPlay::GenerateProgId(std::wstring categoryName, std::wstring subCategory, std::wstring & generatedProgId)
{
std::wstring packageFamilyName = m_msixRequest->GetPackageInfo()->GetPackageFamilyName();
std::wstring applicationId = m_msixRequest->GetPackageInfo()->GetApplicationId();
if (packageFamilyName.empty() || applicationId.empty() || categoryName.empty())
{
return E_INVALIDARG;
}
// Constants
std::wstring AppXPrefix = L"AppX";
static const size_t MaxProgIDLength = 39;
// The maximum number of characters we can have as base32 encoded is 32.
// We arrive at this due to the interface presented by the GetChars function;
// it is byte only. Ideally, the MaxBase32EncodedStringLength would be
// 35 [39 total for the progID, minus 4 for the prefix]. 35 characters means
// a maximum of 22 bytes in the digest [ceil(35*5/8)]. However, 22 bytes of digest
// actually encodes 36 characters [ceil(22/8*5)]. So we have to reduce the
// character count of the encoded string. At 33 characters, this translates into
// a 21 byte buffer. A 21 byte buffer translates into 34 characters. Although
// this meets the requirements, it is confusing since a 33 character limit
// results in a 34 character long encoding. In comparison, a 32 character long
// encoding divides evenly and always results in a 20 byte digest.
static const size_t MaxBase32EncodedStringLength = 32;
// The maximum number of bytes the digest can be is 20. We arrive at this by:
// - The maximum count of characters [without prefix] in the encoding (32):
// - multiplied by 5 (since each character in base 32 encoding is based off of 5 bits)
// - divided by 8 (to find how many bytes are required)
// - The initial plus 7 is to enable integer math (equivalent of writing ceil)
static const ULONG MaxByteCountOfDigest = (MaxBase32EncodedStringLength * 5 + 7) / 8;
// Build the progIdSeed by appending the incoming strings
// The package family name and the application ID are case sensitive
std::wstring tempProgIDBuilder;
tempProgIDBuilder.append(packageFamilyName);
std::transform(tempProgIDBuilder.begin(), tempProgIDBuilder.end(), tempProgIDBuilder.begin(), ::tolower);
tempProgIDBuilder.append(applicationId);
// The category name and the subcategory are not case sensitive
// so we should lower case them
std::wstring tempLowerBuffer;
tempLowerBuffer.assign(categoryName);
std::transform(tempLowerBuffer.begin(), tempLowerBuffer.end(), tempLowerBuffer.begin(), ::tolower);
tempProgIDBuilder.append(tempLowerBuffer);
if (!subCategory.empty())
{
tempLowerBuffer.assign(subCategory);
std::transform(tempLowerBuffer.begin(), tempLowerBuffer.end(), tempLowerBuffer.begin(), ::tolower);
tempProgIDBuilder.append(tempLowerBuffer);
}
// Create the crypto provider and start the digest / hash
AutoPtr<CryptoProvider> cryptoProvider;
RETURN_IF_FAILED(CryptoProvider::Create(&cryptoProvider));
RETURN_IF_FAILED(cryptoProvider->StartDigest());
COMMON_BYTES data = { 0 };
data.length = (ULONG)tempProgIDBuilder.size() * sizeof(WCHAR);
data.bytes = (LPBYTE)tempProgIDBuilder.c_str();
RETURN_IF_FAILED(cryptoProvider->DigestData(&data));
// Grab the crypto digest
COMMON_BYTES digest = { 0 };
RETURN_IF_FAILED(cryptoProvider->GetDigest(&digest));
// Ensure the string buffer has enough capacity
std::wstring base32EncodedDigest;
base32EncodedDigest.resize(MaxBase32EncodedStringLength);
// Base 32 encode the bytes of the digest and put them into the string buffer
ULONG base32EncodedDigestCharCount = 0;
RETURN_IF_FAILED(Base32Encoding::GetChars(
digest.bytes,
std::min(digest.length, MaxByteCountOfDigest),
MaxBase32EncodedStringLength,
base32EncodedDigest.data(),
&base32EncodedDigestCharCount));
// Set the length of the string buffer to the appropriate value
base32EncodedDigest.resize(base32EncodedDigestCharCount);
// ProgID name is formed by appending the encoded digest to the "AppX" prefix string
tempProgIDBuilder.clear();
tempProgIDBuilder.append(AppXPrefix);
tempProgIDBuilder.append(base32EncodedDigest.c_str());
// Set the return value
generatedProgId.assign(tempProgIDBuilder.c_str());
return S_OK;
}
HRESULT AutoPlay::GenerateHandlerName(LPWSTR type, const std::wstring handlerNameSeed, std::wstring & generatedHandlerName)
{
// Constants
static const ULONG HashedByteCount = 32; // SHA256 generates 256 hashed bits, which is 32 bytes
static const ULONG Base32EncodedLength = 52; // SHA256 generates 256 hashed bits, which is 52 characters after base 32 encoding (5 bits per character)
std::wstring packageFamilyName = m_msixRequest->GetPackageInfo()->GetPackageFamilyName();
std::wstring applicationId = m_msixRequest->GetPackageInfo()->GetApplicationId();
std::wstring handlerNameBuilder;
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
DWORD hashLength;
BYTE bytes[HashedByteCount];
ULONG base32EncodedDigestCharCount;
std::wstring base32EncodedDigest;
size_t typeLength;
// First, append Package family name and App Id to a std::wstring variable for convenience - lowercase the values so that the comparison
// in future versions or other code will be case insensitive
handlerNameBuilder.append(packageFamilyName);
handlerNameBuilder.append(applicationId);
std::transform(handlerNameBuilder.begin(), handlerNameBuilder.end(), handlerNameBuilder.begin(), ::tolower);
// Next, SHA256 hash the Package family name and Application Id
if (!CryptAcquireContext(&hProv, nullptr, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (!CryptHashData(hHash, (BYTE *)handlerNameBuilder.c_str(), (DWORD)handlerNameBuilder.size() * sizeof(wchar_t), 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
hashLength = HashedByteCount;
if (!CryptGetHashParam(hHash, HP_HASHVAL, bytes, &hashLength, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Ensure the string has enough capacity for the string and a null terminator
base32EncodedDigest.resize(Base32EncodedLength + 1);
// Base 32 encode the bytes of the digest and put them into the string buffer
RETURN_IF_FAILED(Base32Encoding::GetChars(
bytes,
HashedByteCount,
Base32EncodedLength,
base32EncodedDigest.data(),
&base32EncodedDigestCharCount));
// Set the length of the string to the appropriate value
base32EncodedDigest.resize(base32EncodedDigestCharCount);
// Find the length of the type string
RETURN_IF_FAILED(StringCchLength(type, STRSAFE_MAX_CCH, &typeLength));
// Finally, construct the string
handlerNameBuilder.clear();
handlerNameBuilder.append(base32EncodedDigest.c_str());
handlerNameBuilder.append(L"!", 1);
handlerNameBuilder.append(type, (ULONG)typeLength);
handlerNameBuilder.append(L"!", 1);
handlerNameBuilder.append(handlerNameSeed);
// Set the return value
generatedHandlerName.assign(handlerNameBuilder.c_str());
std::transform(generatedHandlerName.begin(), generatedHandlerName.end(), generatedHandlerName.begin(), ::tolower);
return S_OK;
}
HRESULT AutoPlay::ProcessAutoPlayForAdd(AutoPlayObject& autoPlayObject)
{
RegistryKey explorerKey;
RETURN_IF_FAILED(explorerKey.Open(HKEY_LOCAL_MACHINE, explorerRegKeyName.c_str(), KEY_READ | KEY_WRITE));
RegistryKey handlerRootKey;
RETURN_IF_FAILED(explorerKey.CreateSubKey(handlerKeyName.c_str(), KEY_WRITE, &handlerRootKey));
//generatedhandlername
RegistryKey handlerKey;
RETURN_IF_FAILED(handlerRootKey.CreateSubKey(autoPlayObject.generatedhandlerName.c_str(), KEY_WRITE, &handlerKey));
// Keys associated with all types
RETURN_IF_FAILED(handlerKey.SetStringValue(L"Action", autoPlayObject.action));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"Provider", autoPlayObject.provider));
//Get the default icon
RETURN_IF_FAILED(handlerKey.SetStringValue(L"DefaultIcon", autoPlayObject.defaultIcon));
RegistryKey handleEventRootKey;
RETURN_IF_FAILED(explorerKey.CreateSubKey(eventHandlerRootRegKeyName.c_str(), KEY_WRITE, &handleEventRootKey));
RegistryKey handleEventKey;
RETURN_IF_FAILED(handleEventRootKey.CreateSubKey(autoPlayObject.handleEvent.c_str(), KEY_WRITE, &handleEventKey));
RETURN_IF_FAILED(handleEventKey.SetStringValue(autoPlayObject.generatedhandlerName.c_str(), L""));
RETURN_IF_FAILED(handlerKey.SetUInt32Value(L"DesktopAppX", 1));
if (autoPlayObject.autoPlayType == DesktopAppxContent)
{
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InvokeProgID", autoPlayObject.generatedProgId));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InvokeVerb", autoPlayObject.id));
RegistryKey verbRootKey;
RETURN_IF_FAILED(BuildVerbKey(autoPlayObject.generatedProgId, autoPlayObject.id, verbRootKey));
if (autoPlayObject.dropTargetHandler.size() > 0)
{
RegistryKey dropTargetKey;
RETURN_IF_FAILED(verbRootKey.CreateSubKey(dropTargetRegKeyName.c_str(), KEY_WRITE, &dropTargetKey));
std::wstring regDropTargetHandlerBuilder;
regDropTargetHandlerBuilder.append(L"{");
regDropTargetHandlerBuilder.append(autoPlayObject.dropTargetHandler);
regDropTargetHandlerBuilder.append(L"}");
RETURN_IF_FAILED(dropTargetKey.SetStringValue(L"CLSID", regDropTargetHandlerBuilder));
}
else
{
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"AppUserModelID", autoPlayObject.appUserModelId));
std::wstring resolvedExecutableFullPath = m_msixRequest->GetPackageDirectoryPath() + L"\\" + m_msixRequest->GetPackageInfo()->GetRelativeExecutableFilePath();
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"PackageRelativeExecutable", resolvedExecutableFullPath));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"Parameters", autoPlayObject.parameters));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"ContractId", L"Windows.File"));
RETURN_IF_FAILED(verbRootKey.SetUInt32Value(L"DesiredInitialViewState", 0));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"PackageId", m_msixRequest->GetPackageFullName()));
RegistryKey commandKey;
RETURN_IF_FAILED(verbRootKey.CreateSubKey(commandKeyRegName.c_str(), KEY_WRITE, &commandKey));
RETURN_IF_FAILED(commandKey.SetStringValue(L"DelegateExecute", desktopAppXProtocolDelegateExecuteValue));
}
}
else if (autoPlayObject.autoPlayType == DesktopAppxDevice)
{
std::wstring regHWEventHandlerBuilder;
regHWEventHandlerBuilder.append(L"{");
regHWEventHandlerBuilder.append(autoPlayObject.hwEventHandler);
regHWEventHandlerBuilder.append(L"}");
RETURN_IF_FAILED(handlerKey.SetStringValue(L"CLSID", regHWEventHandlerBuilder));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InitCmdLine", autoPlayObject.initCmdLine));
}
return S_OK;
}
HRESULT AutoPlay::BuildVerbKey(std::wstring generatedProgId, std::wstring id, RegistryKey & verbRootKey)
{
RegistryKey classesRootKey;
RETURN_IF_FAILED(classesRootKey.Open(HKEY_LOCAL_MACHINE, classesKeyPath.c_str(), KEY_READ | KEY_WRITE | WRITE_DAC));
RegistryKey progIdRootKey;
RETURN_IF_FAILED(classesRootKey.CreateSubKey(generatedProgId.c_str(), KEY_READ | KEY_WRITE, &progIdRootKey));
RegistryKey shellRootKey;
RETURN_IF_FAILED(progIdRootKey.CreateSubKey(shellKeyName.c_str(), KEY_READ | KEY_WRITE, &shellRootKey));
RETURN_IF_FAILED(shellRootKey.CreateSubKey(id.c_str(), KEY_READ | KEY_WRITE, &verbRootKey));
return S_OK;
}
HRESULT AutoPlay::CreateHandler(MsixRequest * msixRequest, IPackageHandler ** instance)
{
std::unique_ptr<AutoPlay > localInstance(new AutoPlay(msixRequest));
if (localInstance == nullptr)
{
return E_OUTOFMEMORY;
}
RETURN_IF_FAILED(localInstance->ParseManifest());
*instance = localInstance.release();
return S_OK;
} | 44.954984 | 171 | 0.664008 | rooju |
6408a78f1f877309787a70b763eee146d1036e86 | 2,573 | cc | C++ | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | //--------------------------------------------------------//
//----------STEPPING ACTION-------------------------------//
//--------------------------------------------------------//
#include "Ht1RAction.hh"
#include "Ht1SAction.hh"
#include "Ht1EAction.hh"
#include "Ht1DetectorConstruction.hh"
#include "Ht1Run.hh"
#include "HistoManager.hh"
#include <fstream>
#include "G4Step.hh"
#include "G4Event.hh"
#include "G4RunManager.hh"
#include "G4LogicalVolume.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
//#include "G4PhysicalConstants.hh"
//#include "G4Material.hh"
//#include "G4Element.hh"
using namespace std;
Ht1SAction::Ht1SAction(Ht1RAction* runaction, Ht1EAction* EAction )
: G4UserSteppingAction(),
hRAction(runaction),
fEventAction(EAction),
fScoringVolume(0)
{
}
Ht1SAction::~Ht1SAction()
{}
void Ht1SAction::UserSteppingAction(const G4Step* step)
{
if (!fScoringVolume)
{
const Ht1DetectorConstruction* DConstruction
= static_cast<const Ht1DetectorConstruction*>
(G4RunManager::GetRunManager()->GetUserDetectorConstruction());
fScoringVolume = DConstruction->GetScoringVolume();
}
G4LogicalVolume* volume
= step->GetPreStepPoint()->GetTouchableHandle()
->GetVolume()->GetLogicalVolume();
//Getting track
G4Track *track =step->GetTrack();
//G4double stepl = step->GetStepLength();
//G4double stepid = track->GetCurrentStepNumber();
//Getting particle definition
G4ParticleDefinition *fpParticleDefinition = track->GetDefinition();
int PDGEncoding = fpParticleDefinition->GetPDGEncoding();
//if(PDGEncoding == 11 ){
// G4double Kenergy = track->GetKineticEnergy();
// fEventAction->output<<stepl/meter<<G4endl;
// G4cout<<Kenergy/keV<<"\t"<<stepid<<"\t"<<stepl/meter<<G4endl;
//}
//Kinetic Energy of X-rays:
if(PDGEncoding == 22 )
{
if(step->GetPreStepPoint()->GetTouchableHandle()->GetVolume()->GetName()=="Env" && step->GetPostStepPoint()->GetTouchableHandle()->GetVolume()->GetName() == "detector")
{
G4double Kenergy = track->GetKineticEnergy();
G4AnalysisManager::Instance()->FillH1(5,Kenergy);
// fEventAction->output<<"Track \t" <<trackid<< "\t" << track->GetCreatorProcess()->GetProcessName()<<G4endl;
// fEventAction->output<<"Step \t" <<stepid<<"\t"<< step->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName()<<G4endl;
//fEventAction-> output << Kenergy << /*"\t" << mat1 << "\t" << mat2 << "\t" <<*/ G4endl;
}
}
// IF ITS NOT SCORING VOLUME THEN EXIT
if (volume != fScoringVolume) return;
} //======================================================//
| 31 | 169 | 0.652546 | hiteshvvr |
640a5a98c08ee9e54c620c8b4a67b07b596360d5 | 592 | hpp | C++ | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | #ifndef IR_2_LLVM_HPP_INCLUDED__
#define IR_2_LLVM_HPP_INCLUDED__
#include <memory>
#include "ir/unit.hpp"
class IR2LLVM {
public:
explicit IR2LLVM(IntermediateUnit const &iunit);
IR2LLVM(IR2LLVM const&) = delete;
IR2LLVM& operator=(IR2LLVM const&) = delete;
[[nodiscard]] std::string getRes() const;
~IR2LLVM(); // Needed for unique_ptr to incomplete type
class IR2LLVM_Impl;
private:
friend class IR2LLVM_Impl;
std::unique_ptr<IR2LLVM_Impl> impl;
IntermediateUnit const &iunit;
std::string llvmIR;
};
#endif /* IR_2_LLVM_HPP_INCLUDED__ */
| 19.096774 | 59 | 0.714527 | Sokolmish |
640bd5b0256ba44923bd2097a770d6cf1bac4799 | 806 | cpp | C++ | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include "VFXCommonScene.h"
#include "LevSceneData.h"
#include "LevSceneNode.h"
#include "LevSceneObject.h"
#include "LevSceneObjectDescription.h"
#include "LevNormalScene.h"
#include "LevNumericalUniform.h"
#include "LevRAttrUniformManager.h"
namespace Leviathan
{
namespace Viewer
{
VFXCommonScene::VFXCommonScene()
: LevNormalScene()
{
Init(ELST_3D_SCENE);
}
bool VFXCommonScene::AddLightToLightRootNode(LSPtr<Scene::LevLight> light)
{
const LSPtr<Scene::LevSceneNode> m_light_node = new Scene::LevSceneNode(TryCast<Scene::LevLight, Scene::LevSceneObject>(light));
return GetSceneData().AddSceneNodeToParent(m_light_node, GetLightRootNode());
}
bool VFXCommonScene::SetMainCamera(LSPtr<Scene::LevCamera> camera)
{
return GetSceneData().SetMainCamera(camera);
}
}
} | 26 | 131 | 0.761787 | wakare |
640e25a5443bb2adfc95b094ae08051b0c92beac | 2,160 | cpp | C++ | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 2 | 2019-01-30T12:45:18.000Z | 2021-05-06T19:02:51.000Z | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | null | null | null | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 3 | 2020-10-02T15:42:04.000Z | 2022-03-27T15:14:16.000Z | #include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(false);cin.tie(0)
#define pb push_back
#define digit(x) floor(log10(x))+1
#define mod 1000000007
#define endl "\n"
#define int long long
#define matrix vector<vector<int> >
#define vi vector<int>
#define pii pair<int,int>
#define vs vector<string>
#define vp vector<pii>
#define test() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define debug(x) cerr << #x << " is " << x << endl;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int N = 100005;
void showArr(int *arr, int n){for(int i=0;i<n;i++) cout<<arr[i]<<" ";}
//=================================================================//
vector<int> gr[N];
int tin[N], tout[N];
int timer;
void euler_tour_1(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_1(x, curr);
//when coming back again curr vertex from other vertex
cout<<curr<<" ";
}
}
return;
}
void euler_tour_2(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
tin[curr] = timer++;
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_2(x, curr);
}
}
//after leaving curr vertex
tout[curr] = timer++;
cout<<curr<<" ";
return;
}
void euler_tour_3(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
tin[curr] = ++timer;
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_3(x, curr);
}
}
tout[curr] = timer;
return;
}
// whether x is ancestor of y or not
bool is_ancestor(int x, int y) {
return tin[x]<=tin[y] && tout[x]>=tout[y];
}
void solve() {
int n,m;
cin>>n;
for(int i=0;i<n-1;i++) {
int x, y;
cin>>x>>y;
gr[x].push_back(y);
gr[y].push_back(x);
}
timer = 0;
// euler_tour_1(1,0);
// euler_tour_2(1,0);
euler_tour_3(1,0);
for(int i=1;i<=n;i++) {
cout<<i<<" "<<tin[i]<<" "<<tout[i]<<endl;
}
}
int32_t main(){
fast;
return 0;
} | 22.736842 | 70 | 0.522222 | vkashkumar |
640ef212363af275b62548b75b00467c81615297 | 10,028 | cc | C++ | tensorflow/core/kernels/matrix_triangular_solve_op.cc | c0g/tomserflow | f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/matrix_triangular_solve_op.cc | c0g/tomserflow | f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/matrix_triangular_solve_op.cc | c0g/tomserflow | f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include <cmath>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/binary_linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#if GOOGLE_CUDA
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
#if GOOGLE_CUDA
namespace {
template <typename T>
perftools::gputools::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory)
{
perftools::gputools::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory));
perftools::gputools::DeviceMemory<T> typed(wrapped);
return typed;
}
}//namespace
#endif // GOOGLE_CUDA
template <class Scalar, bool SupportsBatchOperationT>
class MatrixTriangularSolveOp
: public BinaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> {
public:
explicit MatrixTriangularSolveOp(OpKernelConstruction* context)
: BinaryLinearAlgebraOp<Scalar, SupportsBatchOperationT>(context),
lower_(true),
adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
~MatrixTriangularSolveOp() override {}
TensorShape GetOutputMatrixShape(
const TensorShape& input_matrix_shape,
const TensorShape& rhs_matrix_shape) override {
CHECK_EQ(input_matrix_shape.dims(), rhs_matrix_shape.dims());
TensorShape output_matrix_shape = input_matrix_shape;
output_matrix_shape.set_dim(
output_matrix_shape.dims() - 1,
rhs_matrix_shape.dim_size(output_matrix_shape.dims() - 1));
return output_matrix_shape;
}
int64 GetCostPerUnit(const TensorShape& input_matrix_shape,
const TensorShape& rhs_matrix_shape) override {
const int64 rows = input_matrix_shape.dim_size(0);
const int64 rhss = rhs_matrix_shape.dim_size(1);
if (rows > (1LL << 20)) {
// A big number to cap the cost in case overflow.
return kint32max;
} else {
return rows * rows * rhss;
}
}
using typename BinaryLinearAlgebraOp<Scalar,
SupportsBatchOperationT>::MatrixMap;
using typename BinaryLinearAlgebraOp<Scalar,
SupportsBatchOperationT>::ConstMatrixMap;
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMap& matrix,
const ConstMatrixMap& rhs, MatrixMap* output) override {
OP_REQUIRES(context, matrix.rows() == matrix.cols(),
errors::InvalidArgument("Input matrix must be square."));
OP_REQUIRES(
context, matrix.cols() == rhs.rows(),
errors::InvalidArgument("Input matrix and rhs are incompatible."));
if (matrix.rows() == 0 || rhs.cols() == 0) {
// To be consistent with the MatrixInverse op, we define the solution for
// an empty set of equation as the empty matrix.
return;
}
const Scalar min_abs_pivot = matrix.diagonal().cwiseAbs().minCoeff();
OP_REQUIRES(context, min_abs_pivot > Scalar(0),
errors::InvalidArgument("Input matrix is not invertible."));
if (lower_) {
auto triangle = matrix.template triangularView<Eigen::Lower>();
if (adjoint_) {
output->noalias() = triangle.adjoint().solve(rhs);
} else {
output->noalias() = triangle.solve(rhs);
}
} else {
auto triangle = matrix.template triangularView<Eigen::Upper>();
if (adjoint_) {
output->noalias() = triangle.adjoint().solve(rhs);
} else {
output->noalias() = triangle.solve(rhs);
}
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOp);
};
#ifdef GOOGLE_CUDA
template <class T, bool SupportsBatchOperationT>
class MatrixTriangularSolveOpGPU
: public BinaryLinearAlgebraOpBase {
public:
explicit MatrixTriangularSolveOpGPU(OpKernelConstruction* context)
: BinaryLinearAlgebraOpBase(context),
lower_(true),
adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
~MatrixTriangularSolveOpGPU() override {}
bool SupportsBatchOperation() {
return SupportsBatchOperationT;
}
TensorShape GetOutputMatrixShape(
const TensorShape& input_matrix_shape,
const TensorShape& rhs_matrix_shape) override {
CHECK_EQ(input_matrix_shape.dims(), rhs_matrix_shape.dims());
TensorShape output_matrix_shape = input_matrix_shape;
output_matrix_shape.set_dim(
output_matrix_shape.dims() - 1,
rhs_matrix_shape.dim_size(output_matrix_shape.dims() - 1));
return output_matrix_shape;
}
int64 GetCostPerUnit(const TensorShape& input_matrix_shape,
const TensorShape& rhs_matrix_shape) override {
const int64 rows = input_matrix_shape.dim_size(0);
const int64 rhss = rhs_matrix_shape.dim_size(1);
if (rows > (1LL << 20)) {
// A big number to cap the cost in case overflow.
return kint32max;
} else {
return rows * rows * rhss;
}
}
using UpLo = perftools::gputools::blas::UpperLower;
using Trans = perftools::gputools::blas::Transpose;
void ComputeMatrix(OpKernelContext* context, int64 matrix_index,
const Tensor& a_in,
const TensorShape& a_in_matrix_shape,
const Tensor& b_in,
const TensorShape& b_in_matrix_shape,
Tensor* output,
const TensorShape& output_matrix_shape) override {
OP_REQUIRES(context, a_in_matrix_shape.dim_size(0)
== a_in_matrix_shape.dim_size(1),
errors::InvalidArgument("Input matrix must be square."));
OP_REQUIRES(
context, a_in_matrix_shape.dim_size(1)
== b_in_matrix_shape.dim_size(0),
errors::InvalidArgument("Input matrix and rhs are incompatible."));
auto aptr = AsDeviceMemory(a_in.flat<T>().data() +
matrix_index * a_in_matrix_shape.num_elements());
auto bptr = AsDeviceMemory(b_in.flat<T>().data() +
matrix_index * b_in_matrix_shape.num_elements());
auto cptr = AsDeviceMemory(output->flat<T>().data());
auto* stream = context->op_device_context()->stream();
// Copy b into output (cublas works inplace)
uint64 belems = b_in_matrix_shape.num_elements();
bool copy_status = stream->ThenMemcpyD2D(&cptr, bptr, sizeof(T) * belems).ok();
if (!copy_status) {
context->SetStatus(errors::Internal("Failed to copy B into output before TRSM"));
}
UpLo uplo;
Trans trans;
if (lower_) {
uplo = UpLo::kUpper;
} else {
uplo = UpLo::kLower;
}
if (adjoint_) {
trans = Trans::kTranspose;
} else {
trans = Trans::kNoTranspose;
}
uint64 lda = a_in_matrix_shape.dim_size(1);
uint64 ldb = b_in_matrix_shape.dim_size(1);
uint64 cublas_m = b_in_matrix_shape.dim_size(1);
uint64 cublas_n = b_in_matrix_shape.dim_size(0);
bool blas_launch_status = stream->ThenBlasTrsm(
perftools::gputools::blas::Side::kRight,
uplo, trans,
perftools::gputools::blas::Diagonal::kNonUnit,
cublas_m, cublas_n, 1.0,
aptr, lda,
&cptr,ldb
).ok();
// LOG(INFO) << blas_launch_status;
if (!blas_launch_status) {
context->SetStatus(errors::Internal(
"Blas TRSM launch failed : a.shape=(", a_in_matrix_shape.dim_size(0), ", ",
a_in_matrix_shape.dim_size(1), "), b.shape=(", b_in_matrix_shape.dim_size(0), ", ",
b_in_matrix_shape.dim_size(1),"), m=", cublas_m, ", n=", cublas_n, ")"));
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOpGPU);
};
#endif
REGISTER_BINARY_LINALG_OP("MatrixTriangularSolve",
(MatrixTriangularSolveOp<float, false>), float);
REGISTER_BINARY_LINALG_OP("MatrixTriangularSolve",
(MatrixTriangularSolveOp<double, false>), double);
REGISTER_BINARY_LINALG_OP("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<float, true>), float);
REGISTER_BINARY_LINALG_OP("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<double, true>), double);
REGISTER_KERNEL_BUILDER(
Name("MatrixTriangularSolve")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T"),
MatrixTriangularSolveOpGPU<float, false>);
REGISTER_KERNEL_BUILDER(
Name("MatrixTriangularSolve")
.Device(DEVICE_GPU)
.TypeConstraint<double>("T"),
MatrixTriangularSolveOpGPU<double, false>);
REGISTER_KERNEL_BUILDER(
Name("BatchMatrixTriangularSolve")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T"),
MatrixTriangularSolveOpGPU<float, true>);
REGISTER_KERNEL_BUILDER(
Name("BatchMatrixTriangularSolve")
.Device(DEVICE_GPU)
.TypeConstraint<double>("T"),
MatrixTriangularSolveOpGPU<double, true>);
} // namespace tensorflow
| 36.867647 | 94 | 0.674611 | c0g |
640f9dbc3b4c998391f88f9691a65f12ade5ca26 | 3,066 | hpp | C++ | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | #include <future>
#include <utility>
#include "../GeneratorBlock.h"
namespace dataflow::blocks {
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::GeneratorBlock(
OPERATOR& op,
ChannelBundle<T_OUT...> outputChannels,
OUTPUT_PREDICATE outputPredicate)
: op_(op)
, outputChannels_(std::move(outputChannels))
, outputPredicate_(outputPredicate)
, execute_(false)
{
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::execute()
{
std::tuple<T_OUT...> output = op_();
const auto outputPredicate = evalOutputPredicate(output, std::index_sequence_for<T_OUT...> {});
outputChannels_.push(std::move(output), outputPredicate);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
bool GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::readyForExecution() const
{
return execute_ && (maxExecutions_ == inf or executions_ < maxExecutions_);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <class REP, class PERIOD>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::executionLoop(
std::chrono::duration<REP, PERIOD> period,
std::chrono::duration<REP, PERIOD> offset,
size_t maxExecutions)
{
maxExecutions_ = maxExecutions;
std::this_thread::sleep_for(offset);
while (readyForExecution()) {
execute();
++executions_;
std::this_thread::sleep_for(period);
};
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <class REP, class PERIOD>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::start(
std::chrono::duration<REP, PERIOD> period,
std::chrono::duration<REP, PERIOD> offset,
size_t count)
{
execute_ = true;
auto execLoopAsyncWrapper = [&](auto period, auto offset, auto count) {
executionLoop(period, offset, count);
};
executionHandle_ = std::async(std::launch::async, execLoopAsyncWrapper, period, offset, count);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::stop()
{
execute_ = false;
executionHandle_.wait();
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::wait()
{
executionHandle_.wait();
execute_ = false;
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <size_t... Is>
[[nodiscard]] std::array<bool, sizeof...(T_OUT)> GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::evalOutputPredicate(const std::tuple<T_OUT...>& output,
std::index_sequence<Is...> /*unused*/) const
{
return outputPredicate_(std::get<Is>(output)...);
}
} // namespace dataflow::blocks
// ns
| 32.273684 | 113 | 0.722766 | Klirxel |
64110b5df90cb18944554afc169a8d4d9f33a89a | 1,714 | cpp | C++ | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | 4 | 2021-03-01T13:24:24.000Z | 2022-03-06T10:58:34.000Z | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | null | null | null | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | 1 | 2021-03-01T13:24:32.000Z | 2021-03-01T13:24:32.000Z | // File: 6-1-13.cpp
// Author: csh
// Date: 2020/12/26
// ===================
// 无向图
void Graph::Apart(){
int i, j;
for(i = 0; i < numVertex; i++)
Mark[i] = UNVISITED;
for(i = 0; i < numVertex; i++){
// 检查所有顶点是否被标记,从未标记顶点开始周游
if(Mark[i] == UNVISITED){
do_traverse(i, j);
j++;
}
}
}
void Graph::do_traverse(int v, int mark){
Mark[i] = VISITED;
value[v] = mark;
// 访问v邻接到的未被访问的结点,并递归地按照深度优先的方式进行周游
for(Edge e = FirstEdge(v); IsEdge(e); e = NextEdge(e)){
if(Mark[ToVertices(e)] == UNVISITED)
do_traverse(ToVertices(e), mark));
}
}
// 有向图
// 判断u,v是否连通
bool Graph::connected(int u, int v){
for(int i = 0; i < numVertex; i++)
Mark[i] = UNVISITED;
using std::queue;
queue<int> Q;
Q.push(u);
while(!Q.empty()){
int temp = Q.front();
Q.pop();
Mark[temp] = VISITED;
if(temp == v)
return true;
for(Edge e = FirstEdge; IsEdge(e); e = NextEdge(e)){
// 相邻的未访问的结点入队
if(Mark[ToVertex(e)] == UNVISITED)
Q.push(ToVertex(e));
}
}
return false;
}
void Graph::Apart(){
memset(value 0, numVertex * sizeof(int));
int mark = 0;
for(int i = 0; i < numVertex-1; i++){
if(value[i] > 0) // 结点i已经属于某个连通分量
continue;
mark++;
value[i] = mark;
for(int j = i+1; j < numVertex; j++){
if(value[j] > 0) // 结点j已经属于某个连通分量
continue;
if(connected(i, j)){
if(connected(j, i))
value[j] = mark;
}
}
}
}
| 22.25974 | 60 | 0.452742 | caoshenghui |
64139d8a85b21b523f3c202a4ac876b16c35fd4e | 581 | cpp | C++ | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | #include "StdAfx.h"
#include "Connections.h"
CConnections::CConnections(void)
: NumberConnections(0)
, From(NULL)
, Target(NULL)
{
}
CConnections::~CConnections(void)
{
Destroy();
}
int CConnections::Create(int N)
{
Destroy();
if(N>0)
{
NumberConnections = N;
From = new int [N];
Target = new int [N];
}
for(int n=0; n<N; n++)
{
From[n] = -3;
Target[n] = -3;
}
return 0;
}
int CConnections::Destroy(void)
{
if(From) delete [] From;
From = NULL;
if(Target) delete [] Target;
Target = NULL;
return 0;
}
| 12.630435 | 34 | 0.566265 | sirsz |
641f0847696f11c80a80a947cad10885eabd3359 | 7,191 | cpp | C++ | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 68 | 2018-12-16T11:03:08.000Z | 2021-09-30T19:14:02.000Z | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 72 | 2018-12-18T01:13:18.000Z | 2019-11-08T02:13:07.000Z | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 43 | 2018-12-14T21:38:49.000Z | 2021-10-01T02:17:22.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// Module Name:
//
// file.cpp
//
// Abstract:
//
// This module contains methods implementation for the file object create/close
// callbacks.
//
// Environment:
//
// Kernel mode only
//
#include "precomp.h"
#pragma hdrstop
#include "imxpwmhw.hpp"
#include "imxpwm.hpp"
#include "trace.h"
#include "file.tmh"
IMXPWM_PAGED_SEGMENT_BEGIN; //==================================================
_Use_decl_annotations_
VOID
ImxPwmEvtDeviceFileCreate (
WDFDEVICE WdfDevice,
WDFREQUEST WdfRequest,
WDFFILEOBJECT WdfFileObject
)
{
PAGED_CODE();
IMXPWM_ASSERT_MAX_IRQL(PASSIVE_LEVEL);
UNICODE_STRING* filenamePtr = WdfFileObjectGetFileName(WdfFileObject);
IMXPWM_DEVICE_CONTEXT* deviceContextPtr = ImxPwmGetDeviceContext(WdfDevice);
NTSTATUS status;
ULONG pinNumber = ULONG_MAX;
//
// Parse and validate the filename associated with the file object.
//
bool isPinInterface;
if (filenamePtr == nullptr) {
WdfRequestComplete(WdfRequest, STATUS_INVALID_DEVICE_REQUEST);
return;
} else if (filenamePtr->Length > 0) {
//
// A non-empty filename means to open a pin under the controller namespace.
//
status = PwmParsePinPath(filenamePtr, &pinNumber);
if (!NT_SUCCESS(status)) {
WdfRequestComplete(WdfRequest, status);
return;
}
NT_ASSERT(deviceContextPtr->ControllerInfo.PinCount == 1);
if (pinNumber >= deviceContextPtr->ControllerInfo.PinCount) {
IMXPWM_LOG_INFORMATION(
"Requested pin number out of bounds. (pinNumber = %lu)",
pinNumber);
WdfRequestComplete(WdfRequest, STATUS_NO_SUCH_FILE);
return;
}
isPinInterface = true;
} else {
//
// An empty filename means that the create is against the root controller.
//
isPinInterface = false;
}
ACCESS_MASK desiredAccess;
ULONG shareAccess;
ImxPwmCreateRequestGetAccess(WdfRequest, &desiredAccess, &shareAccess);
//
// ShareAccess will not be honored as it has no meaning currently in the
// PWM DDI.
//
if (shareAccess != 0) {
IMXPWM_LOG_INFORMATION(
"Requested share access is not supported and request ShareAccess "
"parameter should be zero. Access denied. (shareAccess = %lu)",
shareAccess);
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
//
// Verify request desired access.
//
const bool hasWriteAccess = ((desiredAccess & FILE_WRITE_DATA) != 0);
if (isPinInterface) {
IMXPWM_PIN_STATE* pinPtr = &deviceContextPtr->Pin;
WdfWaitLockAcquire(pinPtr->Lock, NULL);
if (hasWriteAccess) {
if (pinPtr->IsOpenForWrite) {
WdfWaitLockRelease(pinPtr->Lock);
IMXPWM_LOG_ERROR("Pin access denied.");
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
pinPtr->IsOpenForWrite = true;
}
IMXPWM_LOG_INFORMATION(
"Pin Opened. (IsOpenForWrite = %!bool!)",
pinPtr->IsOpenForWrite);
WdfWaitLockRelease(pinPtr->Lock);
} else {
WdfWaitLockAcquire(deviceContextPtr->ControllerLock, NULL);
if (hasWriteAccess) {
if (deviceContextPtr->IsControllerOpenForWrite) {
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
IMXPWM_LOG_ERROR("Controller access denied.");
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
deviceContextPtr->IsControllerOpenForWrite = true;
}
IMXPWM_LOG_INFORMATION(
"Controller Opened. (IsControllerOpenForWrite = %!bool!)",
deviceContextPtr->IsControllerOpenForWrite);
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
}
//
// Allocate and fill a file object context.
//
IMXPWM_FILE_OBJECT_CONTEXT* fileObjectContextPtr;
{
WDF_OBJECT_ATTRIBUTES wdfObjectAttributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(
&wdfObjectAttributes,
IMXPWM_FILE_OBJECT_CONTEXT);
void* contextPtr;
status = WdfObjectAllocateContext(
WdfFileObject,
&wdfObjectAttributes,
&contextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"WdfObjectAllocateContext(...) failed. (status = %!STATUS!)",
status);
WdfRequestComplete(WdfRequest, status);
return;
}
fileObjectContextPtr =
static_cast<IMXPWM_FILE_OBJECT_CONTEXT*>(contextPtr);
NT_ASSERT(fileObjectContextPtr != nullptr);
fileObjectContextPtr->IsPinInterface = isPinInterface;
fileObjectContextPtr->IsOpenForWrite = hasWriteAccess;
}
WdfRequestComplete(WdfRequest, STATUS_SUCCESS);
}
_Use_decl_annotations_
VOID
ImxPwmEvtFileClose (
WDFFILEOBJECT WdfFileObject
)
{
PAGED_CODE();
IMXPWM_ASSERT_MAX_IRQL(PASSIVE_LEVEL);
WDFDEVICE wdfDevice = WdfFileObjectGetDevice(WdfFileObject);
IMXPWM_DEVICE_CONTEXT* deviceContextPtr = ImxPwmGetDeviceContext(wdfDevice);
IMXPWM_FILE_OBJECT_CONTEXT* fileObjectContextPtr = ImxPwmGetFileObjectContext(WdfFileObject);
if (fileObjectContextPtr->IsPinInterface) {
WdfWaitLockAcquire(deviceContextPtr->Pin.Lock, NULL);
if (fileObjectContextPtr->IsOpenForWrite) {
NTSTATUS status = ImxPwmResetPinDefaults(deviceContextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"ImxPwmResetPinDefaults(...) failed. (status = %!STATUS!)",
status);
}
NT_ASSERT(deviceContextPtr->Pin.IsOpenForWrite);
deviceContextPtr->Pin.IsOpenForWrite = false;
}
IMXPWM_LOG_TRACE(
"Pin Closed. (IsOpenForWrite = %lu)",
(deviceContextPtr->Pin.IsOpenForWrite ? 1 : 0));
WdfWaitLockRelease(deviceContextPtr->Pin.Lock);
} else {
WdfWaitLockAcquire(deviceContextPtr->ControllerLock, NULL);
if (fileObjectContextPtr->IsOpenForWrite) {
NTSTATUS status = ImxPwmResetControllerDefaults(deviceContextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"ImxPwmResetControllerDefaults(...) failed. (status = %!STATUS!)",
status);
}
NT_ASSERT(deviceContextPtr->IsControllerOpenForWrite);
deviceContextPtr->IsControllerOpenForWrite = false;
}
IMXPWM_LOG_TRACE(
"Controller Closed. (IsControllerOpenForWrite = %lu)",
(deviceContextPtr->IsControllerOpenForWrite ? 1 : 0));
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
}
}
IMXPWM_PAGED_SEGMENT_END; //=================================================== | 30.470339 | 97 | 0.624531 | pjgorka88 |
6420821e1c120f18bc426ff2449745f8b9088127 | 10,826 | hpp | C++ | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 27 | 2019-04-22T01:51:51.000Z | 2022-02-11T06:12:17.000Z | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 1 | 2021-11-12T05:19:52.000Z | 2021-11-12T05:19:52.000Z | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 2 | 2020-09-07T03:04:39.000Z | 2021-11-09T06:08:37.000Z |
#ifndef SL_BOUNDING_BOX_HPP
#define SL_BOUNDING_BOX_HPP
#include "lightsky/math/vec3.h"
#include "lightsky/math/vec4.h"
#include "lightsky/math/vec_utils.h"
#include "lightsky/math/mat4.h"
/**
* @brief Bounding Box Class
*/
class SL_BoundingBox
{
private:
ls::math::vec4 mMaxPoint;
ls::math::vec4 mMinPoint;
public:
/**
* @brief Destructor
*
* Defaulted
*/
~SL_BoundingBox() noexcept = default;
/**
* @brief Constructor
*/
SL_BoundingBox() noexcept;
/**
* @brief Copy Constructor
*
* Copies data from another bounding box.
*
* @param bb
* A constant reference to a fully constructed bounding box
* object.
*/
SL_BoundingBox(const SL_BoundingBox& bb) noexcept;
/**
* @brief Move Constructor
*
* Copies data from another bounding box (no moves are performed).
*
* @param An r-value reference to a fully constructed bounding box
*/
SL_BoundingBox(SL_BoundingBox&&) noexcept;
/**
* @brief Copy Operator
*
* Copies data from another bounding box.
*
* @param A constant reference to a fully constructed bounding box
* object.
*
* @return A reference to *this.
*/
SL_BoundingBox& operator=(const SL_BoundingBox&) noexcept;
/**
* @brief Move Operator
*
* @param An R-Value reference to a bounding box that is about to go
* out of scope.
*
* @return A reference to *this.
*/
SL_BoundingBox& operator=(SL_BoundingBox&&) noexcept;
/**
* @brief Check if a point is within this box.
*
* @param A constant reference to a vec3 object.
*
* @return TRUE if the point is within *this, or FALSE if otherwise.
*/
bool is_in_box(const ls::math::vec3&) const noexcept;
/**
* @brief Check if a point is within this box.
*
* @param A constant reference to a vec4 object.
*
* @return TRUE if the point is within *this, or FALSE if otherwise.
*/
bool is_in_box(const ls::math::vec4&) const noexcept;
/**
* Check if a portion of another bounding box is within *this.
*
* @param A constant reference to another bounding box.
*
* @return TRUE if a portion of the bounding box is within *this, or
* FALSE if it isn't.
*/
bool is_in_box(const SL_BoundingBox&) const noexcept;
/**
* Set the maximum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the maximum
* ponit of this bounding box.
*/
void max_point(const ls::math::vec3& v) noexcept;
/**
* Set the tmaximum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the maximum
* point of this bounding box.
*/
void max_point(const ls::math::vec4& v) noexcept;
/**
* Get the maximum extent of this bounding box.
*
* @return A constant reference to the maximum point of this bounding box.
*/
const ls::math::vec4& max_point() const noexcept;
/**
* Get the maximum extent of this bounding box.
*
* @param m
* A model matrix which can be used to return a pre-translated maximum
* point.
*
* @return The max point of this bounding box with regards to a
* transformation.
*/
ls::math::vec4 max_point(const ls::math::mat4& m) const noexcept;
/**
* Set the minimum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the min
* point of this bounding box.
*/
void min_point(const ls::math::vec3& v) noexcept;
/**
* Set the minimum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the min
* point of this bounding box.
*/
void min_point(const ls::math::vec4& v) noexcept;
/**
* Get the minimum extent of this bounding box.
*
* @return A constant reference to the min point of this bounding box.
*/
const ls::math::vec4& min_point() const noexcept;
/**
* Get the minimum extent of this bounding box.
*
* @param m
* A model matrix which can be used to return a pre-translated minimum
* point.
*
* @return The min point of this bounding box with regards to a
* transformation.
*/
ls::math::vec4 min_point(const ls::math::mat4& m) const noexcept;
/**
* Reset the bounds of this bounding box to their default values.
*/
void reset_size() noexcept;
/**
* Compare a point to the current set of vertices.
* If any of the components within the parameter are larger than the
* components of this box, the current set of points will be enlarged.
*
* @param point
* A point who's individual components should be used to update the
* size of this bounding box.
*/
void compare_and_update(const ls::math::vec3& point) noexcept;
/**
* Compare a point to the current set of vertices.
* If any of the components within the parameter are larger than the
* components of this box, the current set of points will be enlarged.
*
* @param point
* A point who's individual components should be used to update the
* size of this bounding box.
*/
void compare_and_update(const ls::math::vec4& point) noexcept;
};
/*-------------------------------------
Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox() noexcept :
mMaxPoint{1.f, 1.f, 1.f, 1.f},
mMinPoint{-1.f, -1.f, -1.f, 1.f}
{}
/*-------------------------------------
Copy Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox(const SL_BoundingBox& bb) noexcept :
mMaxPoint{bb.mMaxPoint},
mMinPoint{bb.mMinPoint}
{}
/*-------------------------------------
Move Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox(SL_BoundingBox&& bb) noexcept :
mMaxPoint{std::move(bb.mMaxPoint)},
mMinPoint{std::move(bb.mMinPoint)}
{
bb.reset_size();
}
/*-------------------------------------
Copy Operator
-------------------------------------*/
inline SL_BoundingBox& SL_BoundingBox::operator=(const SL_BoundingBox& bb) noexcept
{
mMaxPoint = bb.mMaxPoint;
mMinPoint = bb.mMinPoint;
return *this;
}
/*-------------------------------------
Move Operator
-------------------------------------*/
inline SL_BoundingBox& SL_BoundingBox::operator=(SL_BoundingBox&& bb) noexcept
{
mMaxPoint = std::move(bb.mMaxPoint);
mMinPoint = std::move(bb.mMinPoint);
bb.reset_size();
return *this;
}
/*-------------------------------------
Check if a portion of another bounding box is within *this.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const ls::math::vec3& v) const noexcept
{
return
v[0] < mMaxPoint[0] && v[1] < mMaxPoint[1] && v[2] < mMaxPoint[2]
&&
v[0] >= mMinPoint[0] && v[1] >= mMinPoint[1] && v[2] >= mMinPoint[2];
}
/*-------------------------------------
Check if a portion of another bounding box is within *this.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const ls::math::vec4& v) const noexcept
{
return v < mMaxPoint && v >= mMinPoint;
}
/*-------------------------------------
Check if a point is within this box.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const SL_BoundingBox& bb) const noexcept
{
return is_in_box(bb.mMaxPoint) || is_in_box(bb.mMinPoint);
}
/*-------------------------------------
Set the max point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::max_point(const ls::math::vec3& v) noexcept
{
mMaxPoint = ls::math::vec4{v[0], v[1], v[2], 1.f};
}
/*-------------------------------------
Set the max point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::max_point(const ls::math::vec4& v) noexcept
{
mMaxPoint = v;
}
/*-------------------------------------
Get the max point of this bounding box.
-------------------------------------*/
inline ls::math::vec4 SL_BoundingBox::max_point(const ls::math::mat4& m) const noexcept
{
const ls::math::vec4& extMax = m * mMaxPoint;
const ls::math::vec4& extMin = m * mMinPoint;
return ls::math::max(extMax, extMin);
}
/*-------------------------------------
Get the max point of this bounding box.
-------------------------------------*/
inline const ls::math::vec4& SL_BoundingBox::max_point() const noexcept
{
return mMaxPoint;
}
/*-------------------------------------
Set the min point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::min_point(const ls::math::vec3& v) noexcept
{
mMinPoint = ls::math::vec4{v[0], v[1], v[2], 1.f};
}
/*-------------------------------------
Set the min point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::min_point(const ls::math::vec4& v) noexcept
{
mMinPoint = v;
}
/*-------------------------------------
Get the min point of this bounding box.
-------------------------------------*/
inline const ls::math::vec4& SL_BoundingBox::min_point() const noexcept
{
return mMinPoint;
}
/*-------------------------------------
Get the min point of this bounding box.
-------------------------------------*/
inline ls::math::vec4 SL_BoundingBox::min_point(const ls::math::mat4& m) const noexcept
{
const ls::math::vec4& extMax = m * mMaxPoint;
const ls::math::vec4& extMin = m * mMinPoint;
return ls::math::min(extMax, extMin);
}
/*-------------------------------------
Reset the bounds of this bounding box to their default values.
-------------------------------------*/
inline void SL_BoundingBox::reset_size() noexcept
{
max_point(ls::math::vec4{1.f, 1.f, 1.f, 1.f});
min_point(ls::math::vec4{-1.f, -1.f, -1.f, 1.f});
}
/*-------------------------------------
Compare a point to the current set of vertices.
-------------------------------------*/
inline void SL_BoundingBox::compare_and_update(const ls::math::vec3& point) noexcept
{
compare_and_update(ls::math::vec4{point[0], point[1], point[2], 1.f});
}
/*-------------------------------------
Compare a point to the current set of vertices.
-------------------------------------*/
inline void SL_BoundingBox::compare_and_update(const ls::math::vec4& point) noexcept
{
mMaxPoint = ls::math::max(mMaxPoint, point);
mMinPoint = ls::math::min(mMinPoint, point);
}
#endif /* SL_BOUNDING_BOX_HPP */
| 26.086747 | 87 | 0.554776 | Kim-Du-Yeon |
642093883101895e2ced777fc54429b453950c07 | 337 | hpp | C++ | 2018/ED/atividade/include/Node.hpp | LorhanSohaky/UFSCar | af0e84946cbb61b12dfa738610065bbb0f4887a2 | [
"MIT"
] | 1 | 2021-04-24T05:33:26.000Z | 2021-04-24T05:33:26.000Z | 2018/ED/atividade/include/Node.hpp | LorhanSohaky/UFSCar | af0e84946cbb61b12dfa738610065bbb0f4887a2 | [
"MIT"
] | 8 | 2020-11-21T05:22:13.000Z | 2021-09-22T13:42:22.000Z | 2018/ED/atividade/include/Node.hpp | LorhanSohaky/UFSCar | af0e84946cbb61b12dfa738610065bbb0f4887a2 | [
"MIT"
] | 1 | 2018-11-18T15:50:55.000Z | 2018-11-18T15:50:55.000Z | #ifndef NODE_HPP
#define NODE_HPP
template < class T >
class Node {
public:
explicit Node( const int key, const T value, Node* const left, Node* const right );
T getValue() const;
int getKey() const;
Node* left;
Node* right;
int height;
private:
int key;
T value;
};
#include "../Node.cpp"
#endif | 15.318182 | 87 | 0.623145 | LorhanSohaky |
64225a6536c7393dd05f0a83d328c12af8b3fda5 | 459 | cpp | C++ | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include<cstring>
#include<windows.h>
using namespace std;
int main()
{
string s="x";
while(true){
for(int i=1;i<=30;i++){
cout<<s;
Sleep(100);
system("cls");
string k=" ";
s=k.append(s);
}
for(int i=1;i<=30;i++){
s.erase(s.begin());
cout<<s;
Sleep(100);
system("cls");
}
}
return 0;
} | 19.125 | 31 | 0.411765 | Randle-Github |
642c4a580020b110e07d7ed3938e43c59fbb95af | 2,420 | cpp | C++ | source/Library.Shared/Utility.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | 12 | 2019-08-18T19:28:55.000Z | 2022-03-29T12:55:20.000Z | str/wstring_convert/varcholik/Utility.cpp | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | str/wstring_convert/varcholik/Utility.cpp | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Utility.h"
using namespace std;
namespace Library
{
void Utility::GetFileName(const string& inputPath, string& filename)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
if (lastSlashIndex == string::npos)
{
filename = fullPath;
}
else
{
filename = fullPath.substr(lastSlashIndex + 1, fullPath.size() - lastSlashIndex - 1);
}
}
void Utility::GetDirectory(const string& inputPath, string& directory)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
if (lastSlashIndex == string::npos)
{
directory = "";
}
else
{
directory = fullPath.substr(0, lastSlashIndex);
}
}
tuple<string, string> Utility::GetFileNameAndDirectory(const string& inputPath)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
string directory;
string filename;
if (lastSlashIndex == string::npos)
{
directory = "";
filename = fullPath;
}
else
{
directory = fullPath.substr(0, lastSlashIndex);
filename = fullPath.substr(lastSlashIndex + 1, fullPath.size() - lastSlashIndex - 1);
}
return make_tuple(filename, directory);
}
void Utility::LoadBinaryFile(const wstring& filename, vector<char>& data)
{
ifstream file(filename.c_str(), ios::binary);
if (!file.good())
{
throw exception("Could not open file.");
}
file.seekg(0, ios::end);
uint32_t size = (uint32_t)file.tellg();
if (size > 0)
{
data.resize(size);
file.seekg(0, ios::beg);
file.read(&data.front(), size);
}
file.close();
}
#pragma warning(push)
#pragma warning(disable: 4996)
void Utility::ToWideString(const string& source, wstring& dest)
{
dest = wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(source);
}
wstring Utility::ToWideString(const string& source)
{
return wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(source);
}
void Utility::Totring(const wstring& source, string& dest)
{
dest = wstring_convert<codecvt_utf8<wchar_t>>().to_bytes(source);
}
string Utility::ToString(const wstring& source)
{
return wstring_convert<codecvt_utf8<wchar_t>>().to_bytes(source);
}
#pragma warning(pop)
} | 22.201835 | 88 | 0.682645 | ssshammi |
643358c9777896d06012fac8be2f28df2c499053 | 2,625 | cpp | C++ | include/taichi/visualization/json_pakua.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | 2 | 2019-06-25T02:12:37.000Z | 2019-06-25T02:12:48.000Z | include/taichi/visualization/json_pakua.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | null | null | null | include/taichi/visualization/json_pakua.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | 1 | 2021-11-29T22:47:24.000Z | 2021-11-29T22:47:24.000Z | /*******************************************************************************
Copyright (c) The Taichi Authors (2016- ). All Rights Reserved.
The use of this software is governed by the LICENSE file.
*******************************************************************************/
#include <thread>
#include <set>
#include <mutex>
#include <vector>
#include <fstream>
#include <taichi/visualization/pakua.h>
#include <taichi/visualization/image_buffer.h>
#include <json.hpp>
using json = nlohmann::json;
TC_NAMESPACE_BEGIN
class JsonPakua : public Pakua {
int frame_count;
std::string frame_directory;
json geometry;
public:
~JsonPakua() {
}
void initialize(const Config &config) override {
Pakua::initialize(config);
frame_directory = config.get_string("frame_directory");
frame_count = 0;
}
void add_point(Vector pos, Vector color, real size = 1.0f) override {
for (int i = 0; i < 3; i++) {
geometry["points"]["position"].push_back(pos[i]);
}
for (int i = 0; i < 3; i++) {
geometry["points"]["color"].push_back(color[i]);
}
geometry["points"]["sizes"].push_back(size);
}
void add_line(const std::vector<Vector> &pos_v,
const std::vector<Vector> &color_v,
real width = 1.0f) override {
/*
int number = (int)pos_v.size();
for (int i = 0; i < number; i++) {
for (int j = 0; j < 3; j++)
line_buffer.push_back(pos_v[i][j]);
for (int j = 0; j < 3; j++)
line_buffer.push_back(color_v[i][j]);
line_buffer.push_back(width);
}
*/
}
void add_triangle(const std::vector<Vector> &pos_v,
const std::vector<Vector> &color_v) override {
assert(pos_v.size() == 3);
assert(color_v.size() == 3);
for (int i = 0; i < 3; i++) {
for (int k = 0; k < 3; k++) {
geometry["triangles"]["position"].push_back(pos_v[i][k]);
}
}
for (int i = 0; i < 3; i++) {
for (int k = 0; k < 3; k++) {
geometry["triangles"]["color"].push_back(color_v[i][k]);
}
}
}
void start() override {
geometry["points"]["position"].clear();
geometry["points"]["color"].clear();
geometry["points"]["sizes"].clear();
geometry["triangles"]["position"].clear();
geometry["triangles"]["color"].clear();
}
void finish() override {
std::ofstream f(fmt::format("{}/{:04}.json", frame_directory, frame_count));
f << geometry;
frame_count += 1;
}
Array2D<Vector3> screenshot() {
return Array2D<Vector3>();
}
};
TC_IMPLEMENTATION(Pakua, JsonPakua, "json");
TC_NAMESPACE_END
| 26.785714 | 80 | 0.555048 | gonnavis |
643470cae896de052f1a6d5c1a9c45654b24b8bb | 1,162 | hpp | C++ | bat/msvc/private/test/cmdbit/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | null | null | null | bat/msvc/private/test/cmdbit/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | 22 | 2020-12-28T04:36:24.000Z | 2021-01-05T04:49:29.000Z | bat/msvc/private/test/garbage/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | null | null | null |
#pragma once
#ifndef dFSYSTEM_FIND_IN_USED_
#define dFSYSTEM_FIND_IN_USED_ 1
#include <functional>
#include <string>
#include <list>
//==============================================================================
//==============================================================================
namespace fsystem
{
using str_t = ::std::string;
using list_t = ::std::list<str_t>;
// --- const bool is_directory
// --- const ::std::string& path
// --- const size_t depth
using call_t = ::std::function<
bool(const bool, const ::std::string&, const size_t)
>;
struct settings
{
list_t scan_include ;
list_t scan_exclude ;
list_t dirs_include ;
list_t dirs_exclude ;
list_t files_include ;
list_t files_exclude ;
};
void find_in(
const str_t& start,
const settings& params,
const call_t& call
);
} // namespace fsystem
//==============================================================================
//==============================================================================
#endif // !dFSYSTEM_FIND_IN_USED_
| 24.208333 | 80 | 0.437177 | Kartonagnick |
643474b9efb34aa7004f76d894996c431760610c | 1,042 | cpp | C++ | lucida/imagematching/opencv_imm/server/IMMServer.cpp | rlugojr/lucida | a2a59d131dbf0835572faf0a968359829f199aa3 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T15:26:32.000Z | 2017-07-31T15:26:32.000Z | lucida/imagematching/opencv_imm/server/IMMServer.cpp | rlugojr/lucida | a2a59d131dbf0835572faf0a968359829f199aa3 | [
"BSD-3-Clause"
] | 1 | 2021-02-08T20:25:37.000Z | 2021-02-08T20:25:37.000Z | lucida/imagematching/opencv_imm/server/IMMServer.cpp | iru-ken/lucida | cd060b0aa0d8721828a8f37b271e1aa83e76ea6f | [
"BSD-3-Clause"
] | 1 | 2017-03-19T11:02:14.000Z | 2017-03-19T11:02:14.000Z | #include <iostream>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
DEFINE_int32(port,
8082,
"Port for IMM service (default: 8082)");
DEFINE_int32(num_of_threads,
4,
"Number of threads (default: 4)");
#include "IMMHandler.h"
using namespace folly;
using namespace apache::thrift;
using namespace apache::thrift::async;
using namespace cpp2;
using std::cout;
using std::endl;
using std::shared_ptr;
using std::unique_ptr;
using std::to_string;
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
auto handler = std::make_shared<IMMHandler>();
auto server = folly::make_unique<ThriftServer>();
server->setPort(FLAGS_port);
server->setNWorkerThreads(FLAGS_num_of_threads);
server->setInterface(std::move(handler));
server->setIdleTimeout(std::chrono::milliseconds(0));
server->setTaskExpireTime(std::chrono::milliseconds(0));
cout << "IMM at 8082" << endl;
server->serve();
return 0;
}
| 22.170213 | 57 | 0.737044 | rlugojr |
6435dedcd2519942859f49e672df56718525674f | 103 | cpp | C++ | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | #include "pctg_complex.h"
pctg_complex_t::pctg_complex_t(const int position) : position(position) {} | 34.333333 | 74 | 0.776699 | julky117 |
64371860c2204810ff38d9c47e07233a2c755006 | 1,599 | cpp | C++ | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | #include "point_light.h"
#include "platform/resource.h"
#include "core/entity.h"
#include "core/world.h"
#include "core/application.h"
#include "platform/renderer.h"
namespace pronto
{
PointLight::PointLight(Entity* ent) :
Component(ent),
attenuation_(100.f),
color_(glm::vec3(1, 1, 1)),
intensity_(5000.f)
{
entity_->world()->application()->renderer()->RegisterPointLight(this);
}
PointLight::~PointLight()
{
entity_->world()->application()->renderer()->UnRegisterPointLight(this);
}
void PointLight::Update()
{
}
void PointLight::set_attenuation(const float attenuation)
{
attenuation_ = attenuation;
}
void PointLight::set_color(const glm::vec3& color)
{
color_ = color;
}
void PointLight::set_intensity(const float intensity)
{
intensity_ = intensity;
}
float PointLight::attenuation()
{
return attenuation_;
}
const glm::vec3& PointLight::color()
{
return color_;
}
float PointLight::intensity()
{
return intensity_;
}
PointLightBuffer PointLight::CreateStruct()
{
return PointLightBuffer(
glm::vec4(entity_->transform()->position(), 1),
glm::vec4(1, 1, 1, 1),
glm::vec4(color_, 1),
attenuation_,
intensity_);
}
PointLightBuffer::PointLightBuffer(
const glm::vec4& world_pos,
const glm::vec4& view_pos,
const glm::vec4& color,
const float attenuation,
const float intensity) :
world_pos_(world_pos),
view_pos_(view_pos),
color_(color),
attenuation_(attenuation),
intensity_(intensity)
{
}
}
| 19.5 | 76 | 0.654159 | MgBag |
64379ece0c2367f196cd4e054b7711692a305131 | 2,230 | cc | C++ | chrome/browser/invalidation/ticl_invalidation_service_unittest.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chrome/browser/invalidation/ticl_invalidation_service_unittest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | chrome/browser/invalidation/ticl_invalidation_service_unittest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/invalidation/ticl_invalidation_service.h"
#include "chrome/browser/invalidation/invalidation_service_factory.h"
#include "chrome/browser/invalidation/invalidation_service_test_template.h"
#include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
#include "chrome/test/base/testing_profile.h"
#include "sync/notifier/fake_invalidation_handler.h"
#include "sync/notifier/fake_invalidator.h"
#include "sync/notifier/invalidation_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace invalidation {
class TiclInvalidationServiceTestDelegate {
public:
TiclInvalidationServiceTestDelegate() { }
~TiclInvalidationServiceTestDelegate() {
DestroyInvalidationService();
}
void CreateInvalidationService() {
fake_invalidator_ = new syncer::FakeInvalidator();
profile_.reset(new TestingProfile());
token_service_.reset(new FakeProfileOAuth2TokenService);
invalidation_service_.reset(
new TiclInvalidationService(NULL,
token_service_.get(),
profile_.get()));
invalidation_service_->InitForTest(fake_invalidator_);
}
InvalidationService* GetInvalidationService() {
return invalidation_service_.get();
}
void DestroyInvalidationService() {
invalidation_service_->Shutdown();
}
void TriggerOnInvalidatorStateChange(syncer::InvalidatorState state) {
fake_invalidator_->EmitOnInvalidatorStateChange(state);
}
void TriggerOnIncomingInvalidation(
const syncer::ObjectIdInvalidationMap& invalidation_map) {
fake_invalidator_->EmitOnIncomingInvalidation(invalidation_map);
}
syncer::FakeInvalidator* fake_invalidator_; // owned by the service.
scoped_ptr<TiclInvalidationService> invalidation_service_;
scoped_ptr<TestingProfile> profile_;
scoped_ptr<FakeProfileOAuth2TokenService> token_service_;
};
INSTANTIATE_TYPED_TEST_CASE_P(
TiclInvalidationServiceTest, InvalidationServiceTest,
TiclInvalidationServiceTestDelegate);
} // namespace invalidation
| 34.307692 | 75 | 0.773094 | nagineni |
6438402a08ef58b7fccd04182984ed6d272e562e | 1,945 | hpp | C++ | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 54 | 2020-03-20T05:40:01.000Z | 2022-03-18T13:56:46.000Z | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 136 | 2020-03-19T18:23:18.000Z | 2022-03-31T09:08:10.000Z | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 47 | 2020-03-20T11:51:34.000Z | 2022-03-23T15:44:10.000Z | /**
* @file vae_utils.cpp
* @author Atharva Khandait
*
* Utility function necessary for training and working with VAE models.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MODELS_VAE_UTILS_HPP
#define MODELS_VAE_UTILS_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/ffn.hpp>
using namespace mlpack;
using namespace mlpack::ann;
// Calculates mean loss over batches.
template<typename NetworkType = FFN<MeanSquaredError<>, HeInitialization>,
typename DataType = arma::mat>
double MeanTestLoss(NetworkType& model, DataType& testSet, size_t batchSize)
{
double loss = 0;
size_t nofPoints = testSet.n_cols;
size_t i;
for (i = 0; i < ( size_t )nofPoints / batchSize; i++)
{
loss +=
model.Evaluate(testSet.cols(batchSize * i, batchSize * (i + 1) - 1),
testSet.cols(batchSize * i, batchSize * (i + 1) - 1));
}
if (nofPoints % batchSize != 0)
{
loss += model.Evaluate(testSet.cols(batchSize * i, nofPoints - 1),
testSet.cols(batchSize * i, nofPoints - 1));
loss /= ( int )nofPoints / batchSize + 1;
}
else
loss /= nofPoints / batchSize;
return loss;
}
// Sample from the output distribution and post-process the outputs(because
// we pre-processed it before passing it to the model).
template<typename DataType = arma::mat>
void GetSample(DataType &input, DataType& samples, bool isBinary)
{
if (isBinary)
{
samples = arma::conv_to<DataType>::from(
arma::randu<DataType>(input.n_rows, input.n_cols) <= input);
samples *= 255;
}
else
{
samples = input / 2 + 0.5;
samples *= 255;
samples = arma::clamp(samples, 0, 255);
}
}
#endif
| 28.188406 | 78 | 0.666324 | akhandait |
64384b178a8d27d119a2054dcd9134bb5307a8da | 2,985 | inl | C++ | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | 1 | 2021-02-28T10:58:11.000Z | 2021-02-28T10:58:11.000Z | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | 1 | 2021-07-06T17:34:48.000Z | 2021-09-16T20:41:57.000Z | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | null | null | null | /**
*
* @file: hsv_conversions.inl
* @author: lazergenixdev@gmail.com
*
*
* This file is provided under the MIT License:
*
* Copyright (c) 2021 Lazergenix Software
*
* 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.
*
*/
/*
*
* I am not the creator of these algorithms;
* They are mostly copied from stackoverflow,
* then further edited for my needs.
*
* All values are assumed to be in the range: [0,1]
*
* These macros are for code written in C,
* but they are compatable with C++
*
* These defines don't require any dependencies.
*
* defines: HSV_TO_RGB() and RGB_TO_HSV()
*
* undefine when done using.
*
*/
/* HSV_TO_RGB: Convert HSV to RGB */
#define HSV_TO_RGB( _R, _G, _B, _H, _S, _V ) {\
float hh, p, q, t, ff; \
long i; \
if( _S <= 0.0f ) { \
_R = _V; \
_G = _V; \
_B = _V; \
return; \
} \
hh = _H; \
if( hh >= 1.0f ) hh = 0.0f; \
hh *= 6.0f; \
i = (long)hh; \
ff = hh - i; \
p = _V * ( 1.0f - _S ); \
q = _V * ( 1.0f - _S * ff ); \
t = _V * ( 1.0f - _S * ( 1.0f - ff ) ); \
switch( i ) { \
case 0: _R = _V, _G = t, _B = p; break; \
case 1: _R = q, _G = _V, _B = p; break; \
case 2: _R = p, _G = _V, _B = t; break; \
case 3: _R = p, _G = q, _B = _V; break; \
case 4: _R = t, _G = p, _B = _V; break; \
default: _R = _V, _G = p, _B = q; break; \
} }
/* RGB_TO_HSV: Convert RGB to HSV */
#define RGB_TO_HSV( _R, _G, _B, _H, _S, _V ) {\
float min, max, delta; \
if( _R > _G ) \
min = _B < _G ? _B : _G, \
max = _B > _R ? _B : _R; \
else \
min = _B < _R ? _B : _R, \
max = _B > _G ? _B : _G; \
_V = max; \
delta = max - min; \
if( delta > 0.00001 ) \
_S = delta / max; \
else { _S = 0.0f, _H = 0.0f; return; } \
if( _R == max ) \
_H = (_G - _B)/delta; \
else if( _G == max ) \
_H = 2.0f + (_B - _R)/delta; \
else \
_H = 4.0f + (_R - _G)/delta; \
_H = _H / 6.0f; \
if( _H < 0.0f ) _H += 1.0f; }
| 29.264706 | 80 | 0.59263 | lazergenixdev |
64385ac90f0bb810e26972f831b4f2ba5c967011 | 174 | cpp | C++ | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
struct Student{
string name;
string id;
int year;
string dep;
float gpa;
}s2, s3;
int main(){
Student s1;
}
| 11.6 | 20 | 0.614943 | capacitybuilding |
643b0da1d1a79b461a9ab287360ad0f77b3f9b18 | 14,449 | cpp | C++ | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | 1 | 2018-01-06T04:44:36.000Z | 2018-01-06T04:44:36.000Z | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | #include "RenderSystem/Vulkan/Managers/CDeviceMemoryManager.h"
#if VKE_VULKAN_RENDERER
#include "RenderSystem/CDeviceContext.h"
#include "RenderSystem/CDDI.h"
namespace VKE
{
namespace RenderSystem
{
CDeviceMemoryManager::CDeviceMemoryManager(CDeviceContext* pCtx) :
m_pCtx{ pCtx }
{
}
CDeviceMemoryManager::~CDeviceMemoryManager()
{
}
Result CDeviceMemoryManager::Create(const SDeviceMemoryManagerDesc& Desc)
{
m_Desc = Desc;
Result ret = VKE_OK;
// Add empty pool
m_PoolBuffer.Add( {} );
m_vPoolViews.PushBack( {} );
m_vSyncObjects.PushBack( {} );
m_lastPoolSize = Desc.defaultPoolSize;
return ret;
}
void CDeviceMemoryManager::Destroy()
{
}
handle_t CDeviceMemoryManager::_CreatePool( const SCreateMemoryPoolDesc& Desc )
{
handle_t ret = INVALID_HANDLE;
SAllocateMemoryDesc AllocDesc;
AllocDesc.size = Desc.size;
AllocDesc.usage = Desc.usage;
SAllocateMemoryData MemData;
Result res = m_pCtx->DDI().Allocate( AllocDesc, &MemData );
if( VKE_SUCCEEDED( res ) )
{
SPool Pool;
Pool.Data = MemData;
ret = m_PoolBuffer.Add( Pool );
if( ret != UNDEFINED_U32 )
{
CMemoryPoolView::SInitInfo Info;
Info.memory = (uint64_t)(MemData.hDDIMemory);
Info.offset = 0;
Info.size = Desc.size;
Info.allocationAlignment = Desc.alignment;
CMemoryPoolView View;
handle_t viewIdx = ret;
// There is a new pool to be added
if( ret >= m_vPoolViews.GetCount() )
{
viewIdx = m_vPoolViews.PushBack( View );
m_vSyncObjects.PushBack( {} );
}
{
m_vPoolViews[ viewIdx ].Init( Info );
}
m_totalMemAllocated += AllocDesc.size;
VKE_LOG_WARN("Created new device memory pool with size: " << VKE_LOG_MEM_SIZE(AllocDesc.size) << ".");
VKE_LOG("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << ".");
}
}
return ret;
}
uint32_t CalculateNewPoolSize(const uint32_t& newPoolSize, const uint32_t& lastPoolSize,
const SDeviceMemoryManagerDesc& Desc)
{
uint32_t ret = newPoolSize;
if (newPoolSize == 0)
{
switch (Desc.resizePolicy)
{
case DeviceMemoryResizePolicies::DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize;
break;
}
case DeviceMemoryResizePolicies::TWO_TIMES_DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize * 2;
break;
}
case DeviceMemoryResizePolicies::FOUR_TIMES_DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize * 4;
break;
}
case DeviceMemoryResizePolicies::TWO_TIMES_LAST_SIZE:
{
ret = lastPoolSize * 2;
break;
}
case DeviceMemoryResizePolicies::FOUR_TIMES_LAST_SIZE:
{
ret = lastPoolSize * 4;
break;
}
}
}
return ret;
}
handle_t CDeviceMemoryManager::_CreatePool(const SAllocateDesc& Desc,
const SAllocationMemoryRequirementInfo& MemReq)
{
auto poolSize = std::max<uint32_t>(m_lastPoolSize, MemReq.size);
poolSize = std::max<uint32_t>(poolSize, Desc.poolSize);
SCreateMemoryPoolDesc PoolDesc;
PoolDesc.usage = Desc.Memory.memoryUsages;
PoolDesc.size = poolSize;
PoolDesc.alignment = MemReq.alignment;
handle_t hPool = _CreatePool(PoolDesc);
m_mPoolIndices[Desc.Memory.memoryUsages].PushBack(hPool);
m_lastPoolSize = poolSize;
return hPool;
}
handle_t CDeviceMemoryManager::_AllocateFromPool( const SAllocateDesc& Desc,
const SAllocationMemoryRequirementInfo& MemReq, SBindMemoryInfo* pBindInfoOut )
{
handle_t ret = INVALID_HANDLE;
//SPool* pPool = nullptr;
auto Itr = m_mPoolIndices.find( Desc.Memory.memoryUsages );
// If no pool is created for such memory usage create a new one
// and call this function again
if( Itr == m_mPoolIndices.end() )
{
const handle_t hPool = _CreatePool(Desc, MemReq);
VKE_ASSERT(hPool != INVALID_HANDLE, "");
ret = _AllocateFromPool( Desc, MemReq, pBindInfoOut );
}
else
{
const HandleVec& vHandles = Itr->second;
SAllocateMemoryInfo Info;
Info.alignment = MemReq.alignment;
Info.size = MemReq.size;
uint64_t memory = CMemoryPoolView::INVALID_ALLOCATION;
// Find firt pool with enough memory
for( uint32_t i = 0; i < vHandles.GetCount(); ++i )
{
const auto poolIdx = vHandles[ i ];
//auto& Pool = m_PoolBuffer[ poolIdx ];
auto& View = m_vPoolViews[ poolIdx ];
CMemoryPoolView::SAllocateData Data;
memory = View.Allocate( Info, &Data );
if( memory != CMemoryPoolView::INVALID_ALLOCATION )
{
pBindInfoOut->hDDIBuffer = Desc.Memory.hDDIBuffer;
pBindInfoOut->hDDITexture = Desc.Memory.hDDITexture;
pBindInfoOut->hDDIMemory = (DDIMemory)( Data.memory );
pBindInfoOut->offset = Data.offset;
pBindInfoOut->hMemory = poolIdx;
UAllocationHandle Handle;
SMemoryAllocationInfo AllocInfo;
AllocInfo.hMemory = Data.memory;
AllocInfo.offset = Data.offset;
AllocInfo.size = Info.size;
Handle.hAllocInfo = m_AllocBuffer.Add( AllocInfo );
Handle.hPool = static_cast< uint16_t >( poolIdx );
Handle.dedicated = false;
ret = Handle.handle;
break;
}
}
// If there is no free space in any of currently allocated pools
if (memory == CMemoryPoolView::INVALID_ALLOCATION)
{
// Create new memory pool
SAllocateDesc NewDesc = Desc;
NewDesc.poolSize = CalculateNewPoolSize(Desc.poolSize, m_lastPoolSize, m_Desc);
const float sizeMB = NewDesc.poolSize / 1024.0f / 1024.0f;
VKE_LOG_WARN("No device memory for allocation with requirements: " << VKE_LOG_MEM_SIZE(MemReq.size) << ", " << MemReq.alignment << " bytes alignment.");
//VKE_LOG_WARN("Create new device memory pool with size: " << VKE_LOG_MEM_SIZE(NewDesc.poolSize) << ".");
const handle_t hPool = _CreatePool(NewDesc, MemReq);
//VKE_LOG_WARN("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << "." );
VKE_ASSERT(hPool != INVALID_HANDLE, "");
ret = _AllocateFromPool(Desc, MemReq, pBindInfoOut);
}
}
m_totalMemUsed += MemReq.size;
return ret;
}
handle_t CDeviceMemoryManager::_AllocateMemory( const SAllocateDesc& Desc, SBindMemoryInfo* pOut )
{
handle_t ret = INVALID_HANDLE;
const auto dedicatedAllocation = Desc.Memory.memoryUsages & MemoryUsages::DEDICATED_ALLOCATION;
SAllocationMemoryRequirementInfo MemReq = {};
if( Desc.Memory.hDDIBuffer != DDI_NULL_HANDLE )
{
m_pCtx->DDI().GetBufferMemoryRequirements( Desc.Memory.hDDIBuffer, &MemReq );
}
else if( Desc.Memory.hDDITexture != DDI_NULL_HANDLE )
{
m_pCtx->DDI().GetTextureMemoryRequirements( Desc.Memory.hDDITexture, &MemReq );
}
if( !dedicatedAllocation )
{
ret =_AllocateFromPool( Desc, MemReq, pOut );
}
else
{
SAllocateMemoryData Data;
SAllocateMemoryDesc AllocDesc;
AllocDesc.size = MemReq.size;
AllocDesc.usage = Desc.Memory.memoryUsages;
Result res = m_pCtx->_GetDDI().Allocate( AllocDesc, &Data );
if( VKE_SUCCEEDED( res ) )
{
auto& BindInfo = *pOut;
BindInfo.hDDITexture = Desc.Memory.hDDITexture;
BindInfo.hDDIBuffer = Desc.Memory.hDDIBuffer;
BindInfo.hDDIMemory = Data.hDDIMemory;
BindInfo.hMemory = INVALID_HANDLE;
BindInfo.offset = 0;
SMemoryAllocationInfo AllocInfo;
AllocInfo.hMemory = ( handle_t )( Data.hDDIMemory );
AllocInfo.offset = 0;
AllocInfo.size = AllocDesc.size;
UAllocationHandle Handle;
Handle.dedicated = true;
Handle.hAllocInfo = m_AllocBuffer.Add( AllocInfo );
Handle.hPool = 0;
ret = Handle.handle;
VKE_LOG_WARN("Allocate new device memory with size: " << VKE_LOG_MEM_SIZE(AllocDesc.size) << ".");
m_totalMemAllocated += AllocDesc.size;
m_totalMemUsed += AllocDesc.size;
VKE_LOG_WARN("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << ".");
}
}
return ret;
}
handle_t CDeviceMemoryManager::AllocateBuffer( const SAllocateDesc& Desc )
{
SBindMemoryInfo BindInfo;
handle_t ret = _AllocateMemory( Desc, &BindInfo );
if( ret != INVALID_HANDLE )
{
{
m_pCtx->_GetDDI().Bind< ResourceTypes::BUFFER >( BindInfo );
}
}
return ret;
}
handle_t CDeviceMemoryManager::AllocateTexture(const SAllocateDesc& Desc )
{
SBindMemoryInfo BindInfo;
handle_t ret = _AllocateMemory( Desc, &BindInfo );
if( ret != INVALID_HANDLE )
{
{
m_pCtx->_GetDDI().Bind< ResourceTypes::TEXTURE >( BindInfo );
}
}
return ret;
}
Result CDeviceMemoryManager::UpdateMemory( const SUpdateMemoryInfo& DataInfo, const SBindMemoryInfo& BindInfo )
{
Result ret = VKE_ENOMEMORY;
SMapMemoryInfo MapInfo;
MapInfo.hMemory = BindInfo.hDDIMemory;
MapInfo.offset = BindInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
void* pDst = m_pCtx->DDI().MapMemory( MapInfo );
if( pDst != nullptr )
{
Memory::Copy( pDst, DataInfo.dataSize, DataInfo.pData, DataInfo.dataSize );
ret = VKE_OK;
}
m_pCtx->DDI().UnmapMemory( BindInfo.hDDIMemory );
return ret;
}
Result CDeviceMemoryManager::UpdateMemory( const SUpdateMemoryInfo& DataInfo, const handle_t& hMemory )
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[ Handle.hAllocInfo ];
Result ret = VKE_ENOMEMORY;
SMapMemoryInfo MapInfo;
MapInfo.hMemory = ( DDIMemory )( AllocInfo.hMemory );
MapInfo.offset = AllocInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
{
Threads::ScopedLock l( m_vSyncObjects[Handle.hPool] );
void* pDst = m_pCtx->DDI().MapMemory( MapInfo );
if( pDst != nullptr )
{
Memory::Copy( pDst, DataInfo.dataSize, DataInfo.pData, DataInfo.dataSize );
ret = VKE_OK;
}
m_pCtx->DDI().UnmapMemory( MapInfo.hMemory );
}
return ret;
}
void* CDeviceMemoryManager::MapMemory(const SUpdateMemoryInfo& DataInfo, const handle_t& hMemory)
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[Handle.hAllocInfo];
SMapMemoryInfo MapInfo;
MapInfo.hMemory = (DDIMemory)AllocInfo.hMemory;
MapInfo.offset = AllocInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
Threads::ScopedLock l(m_vSyncObjects[Handle.hPool]);
void* pRet = m_pCtx->DDI().MapMemory(MapInfo);
return pRet;
}
void CDeviceMemoryManager::UnmapMemory(const handle_t& hMemory)
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[Handle.hAllocInfo];
Threads::ScopedLock l(m_vSyncObjects[Handle.hPool]);
m_pCtx->DDI().UnmapMemory((DDIMemory)AllocInfo.hMemory);
}
const SMemoryAllocationInfo& CDeviceMemoryManager::GetAllocationInfo( const handle_t& hMemory )
{
UAllocationHandle Handle = hMemory;
return m_AllocBuffer[Handle.hAllocInfo];
}
} // RenderSystem
} // VKE
#endif // VKE_VULKAN_RENDERER | 40.247911 | 172 | 0.522181 | przemyslaw-szymanski |
643b2731e65bb36d7d7cac192ee3a77c4e702308 | 906 | hpp | C++ | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "../holocommon/CommonDefs.hpp"
#include <log4cxx/log4cxx.h>
#include <opencv2/opencv.hpp>
#include <OpenNI.h>
#include <mutex>
#include <condition_variable>
#define HOLO_CAPTURE_OPENNI2_MUTEX_TIMEOUT_MS 30
namespace holo
{
namespace capture
{
class HoloCaptureOpenNI2Listener : public openni::VideoStream::NewFrameListener
{
public:
HoloCaptureOpenNI2Listener();
~HoloCaptureOpenNI2Listener();
void onNewFrame(openni::VideoStream& stream);
void getDepthFrame(cv::Mat& depthOut);
void getColorFrame(cv::Mat& colorOut);
private:
openni::VideoFrameRef colorFrame_;
openni::VideoFrameRef depthFrame_;
bool haveNewColorFrame_;
bool haveNewDepthFrame_;
std::mutex colorFrameMutex_;
std::mutex depthFrameMutex_;
std::condition_variable colorFrameCV_;
std::condition_variable depthFrameCV_;
log4cxx::LoggerPtr logger_;
};
}
}
| 20.133333 | 81 | 0.756071 | itsermo |
643bd58227e5fc842f483310d28910448b8f85db | 3,207 | cpp | C++ | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | 2 | 2015-09-07T05:15:11.000Z | 2019-01-09T02:37:05.000Z | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | null | null | null | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | null | null | null | #include "GameScene.h"
#include "Colors.h"
USING_NS_CC;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = GameScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
if ( !Layer::init() )
{
return false;
}
auto colorLayer = LayerColor::create(GAME_SCENE_BACKGROUND_COLOR);
this->addChild(colorLayer, 0);
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
board = new GameBoard();
board->spawnNewPiece();
drawer = new GameBoardDrawer(board, this, origin, visibleSize);
drawer->drawGameBoard();
int SCREEN_BORDER = 20;
auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
[] (Ref *sender) {
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
});
closeItem->setScaleX(4.0f);
closeItem->setScaleY(4.0f);
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->boundingBox().size.width/2 - SCREEN_BORDER,
origin.y + closeItem->boundingBox().size.height/2 + SCREEN_BORDER));
auto resetItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
[this] (Ref *sender) {
this->board->resetBoard();
this->drawer->drawGameBoard();
});
resetItem->setScaleX(4.0f);
resetItem->setScaleY(4.0f);
int SEPARATOR = 5;
resetItem->setPosition(Vec2(closeItem->getPosition().x - closeItem->boundingBox().size.width/2 - resetItem->boundingBox().size.width/2 - SEPARATOR,
origin.y + resetItem->boundingBox().size.height/2 + SCREEN_BORDER));
Vector<MenuItem*> menuItems;
menuItems.pushBack(closeItem);
menuItems.pushBack(resetItem);
auto menu = Menu::createWithArray(menuItems);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto scheduler = Director::getInstance()->getScheduler();
scheduler->schedule(schedule_selector(GameScene::onBoardTimerTick), this, GAME_BOARD_TICK_IN_SECONDS, CC_REPEAT_FOREVER, 0.0f, false);
return true;
}
void GameScene::onBoardTimerTick(float delta)
{
board->processBoard();
drawer->drawGameBoard();
}
bool GameScene::onTouchBegan(Touch *touch, Event *event)
{
board->spawnNewPiece();
drawer->drawGameBoard();
return true;
}
void GameScene::onTouchMoved(Touch *touch, Event *event)
{
}
void GameScene::onTouchEnded(Touch *touch, Event *event)
{
}
| 29.971963 | 151 | 0.664484 | danielgimenes |
643cb5edcd9a93bd2ad13b582851a54cefb312f5 | 708 | cpp | C++ | Algorithms/2.add-two-numbers/add-two-numbers_2-dfs.cpp | OctopusLian/leetcode-solutions | 40920d11c584504e805d103cdc6ef3f3774172b3 | [
"MIT"
] | 1 | 2020-12-01T18:35:24.000Z | 2020-12-01T18:35:24.000Z | Algorithms/2.add-two-numbers/add-two-numbers_2-dfs.cpp | OctopusLian/leetcode-solutions | 40920d11c584504e805d103cdc6ef3f3774172b3 | [
"MIT"
] | 18 | 2020-11-10T05:48:29.000Z | 2020-11-26T08:39:20.000Z | Algorithms/2.add-two-numbers/add-two-numbers_2-dfs.cpp | OctopusLian/leetcode-solutions | 40920d11c584504e805d103cdc6ef3f3774172b3 | [
"MIT"
] | 5 | 2020-11-09T07:43:00.000Z | 2021-12-02T14:59:37.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return dfs(l1, l2, 0);
}
ListNode* dfs(ListNode* l, ListNode* r, int i) {
if (!l && !r && !i) return nullptr;
int sum = (l ? l->val : 0) + (r ? r->val : 0) + i;
ListNode* node = new ListNode(sum % 10);
node->next = dfs(l ? l->next : nullptr, r ? r->next : nullptr, sum / 10);
return node;
}
}; | 29.5 | 81 | 0.524011 | OctopusLian |
64423b92acd78d7636aad9ee0f9d39f4b190b3ed | 5,072 | cpp | C++ | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | #include <SFML/GRAPHICS.hpp>
#include <iostream>
using namespace sf;
void createCube(int arrOfCubes[62][62]) {
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 0) {
int numberOfCubes = 0;
if(arrOfCubes[i-1][j-1] == 1 || arrOfCubes[i-1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j] == 1 || arrOfCubes[i-1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j+1] == 1 || arrOfCubes[i-1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j+1] == 1 || arrOfCubes[i][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j+1] == 1 || arrOfCubes[i+1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j] == 1 || arrOfCubes[i+1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j-1] == 1 || arrOfCubes[i+1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j-1] == 1 || arrOfCubes[i][j-1] == 3) {numberOfCubes += 1;}
if(numberOfCubes == 3) {
arrOfCubes[i][j] = 2;
}
}
}
}
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 3){
arrOfCubes[i][j] = 0;
}
}
}
}
void isCellAlive(int arrOfCubes[62][62]) {
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 1 || arrOfCubes[i][j] == 2) {
int numberOfCubes = 0;
if(arrOfCubes[i-1][j-1] == 1 || arrOfCubes[i-1][j-1] == 2 || arrOfCubes[i-1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j] == 1 || arrOfCubes[i-1][j] == 2 || arrOfCubes[i-1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j+1] == 1 || arrOfCubes[i-1][j+1] == 2 || arrOfCubes[i-1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j+1] == 1 || arrOfCubes[i][j+1] == 2 || arrOfCubes[i][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j+1] == 1 || arrOfCubes[i+1][j+1] == 2 || arrOfCubes[i+1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j] == 1 || arrOfCubes[i+1][j] == 2 || arrOfCubes[i+1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j-1] == 1 || arrOfCubes[i+1][j-1] == 2 || arrOfCubes[i+1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j-1] == 1 || arrOfCubes[i][j-1] == 2 || arrOfCubes[i][j-1] == 3) {numberOfCubes += 1;}
if(numberOfCubes != 2 && numberOfCubes != 3) {
arrOfCubes[i][j] = 3;
}
}
}
}
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 2) {
arrOfCubes[i][j] = 1;
}
}
}
}
void drawLines(RenderWindow& window) {
for(int i = 10; i < 600; i += 10) {
RectangleShape rect1, rect2;
rect1.setPosition({i, 0});
rect1.setSize({2, 600});
rect1.setFillColor({Color::Black});
rect2.setPosition({0, i});
rect2.setSize({600, 2});
rect2.setFillColor({Color::Black});
window.draw(rect1);
window.draw(rect2);
}
}
int main() {
RenderWindow window({600, 600}, "GameOFLife");
int arrOfcubes[62][62] = {0}; // we will use arr 60x60, but our functions require more
// 0 - dead cell, 1 - old cell, 2 - new cell, 3 - dead cell
bool start = true;
Clock clock;
Time timer;
float delay = 0.1;
while(window.isOpen()) {
timer += clock.getElapsedTime();
clock.restart();
Event event;
while(window.pollEvent(event)) {
if(event.type == Event::Closed) {
window.close();
}
if(Mouse::isButtonPressed(Mouse::Left)) {
int y = Mouse::getPosition(window).y / 10;
int x = Mouse::getPosition(window).x / 10;
if(x > - 1 && x < 60 && y > -1 && y < 60){
arrOfcubes[y + 1][x + 1] = 2;
}
}
if(event.type == Event::KeyPressed) {
if(event.key.code == Keyboard::Space) {
start = false;
}
}
}
if(timer.asSeconds() >= delay && !start) {
timer = Time::Zero;
isCellAlive(arrOfcubes);
createCube(arrOfcubes);
}
window.clear({123, 159, 198});
drawLines(window);
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfcubes[i][j] == 1 || arrOfcubes[i][j] == 2) {
RectangleShape rect;
rect.setFillColor(Color::Black);
rect.setSize({10, 10});
rect.setPosition({j * 10 - 10, i * 10 - 10});
window.draw(rect);
}
}
}
window.display();
}
}
| 37.57037 | 125 | 0.440457 | anAwesomeWave |
6444adcd77313e5b74b96ba2b1c86d23c302bdd9 | 9,084 | hpp | C++ | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"
#pragma warning(push)
#pragma warning(disable: 4100) // unreferenced formal parameter
#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
#endif
#include "Scenario5_MatsTexs.xaml.h"
void ::Hot3dxRotoDraw::Scenario5_MatsTexs::InitializeComponent()
{
if (_contentLoaded)
{
return;
}
_contentLoaded = true;
::Windows::Foundation::Uri^ resourceLocator = ref new ::Windows::Foundation::Uri(L"ms-appx:///Scenario5_MatsTexs.xaml");
::Windows::UI::Xaml::Application::LoadComponent(this, resourceLocator, ::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Application);
}
void ::Hot3dxRotoDraw::Scenario5_MatsTexs::Connect(int __connectionId, ::Platform::Object^ __target)
{
switch (__connectionId)
{
case 2:
{
this->RootGrid = safe_cast<::Windows::UI::Xaml::Controls::Grid^>(__target);
}
break;
case 3:
{
this->IDC_PALETTE_FILE_NAME_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 4:
{
this->textBox = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 5:
{
this->filePath1TextBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 6:
{
this->textureFileTextBlock1 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 7:
{
this->filePath2TextBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 8:
{
this->textureFileTextBlock2 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 9:
{
this->IDC_CREATE_PALETTE_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 10:
{
this->IDC_OPEN_PALETTE_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 11:
{
this->IDC_ADD_MATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 12:
{
this->IDC_SAVE_PALETTE_BUTTON2 = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 13:
{
this->IDC_SET_MATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 14:
{
this->IDC_ADD_DELETEMATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 15:
{
this->textBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 16:
{
this->IDC_NUM_MATERIALS_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 17:
{
this->textBlock2 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 18:
{
this->IDC_CURRENT_MATERIAL_slider1 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 19:
{
this->IDC_CURRENT_MATERIAL_slider2 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 20:
{
this->IDC_CURRENT_MATERIAL_slider3 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 21:
{
this->IDC_CURRENT_MATERIAL_slider4 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 22:
{
this->IDC_CURRENT_MATERIAL_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 23:
{
this->MaterialListControl = safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(this->MaterialListControl))->SelectionChanged += ref new ::Windows::UI::Xaml::Controls::SelectionChangedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::Controls::SelectionChangedEventArgs^))&Scenario5_MatsTexs::MaterialListControl_SelectionChanged);
}
break;
case 24:
{
this->MaterialListControlData = safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(this->MaterialListControlData))->SelectionChanged += ref new ::Windows::UI::Xaml::Controls::SelectionChangedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::Controls::SelectionChangedEventArgs^))&Scenario5_MatsTexs::MaterialListControlData_SelectionChanged);
}
break;
case 25:
{
this->textBlock12 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 26:
{
this->IDC_NAME_SET_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 27:
{
this->IDC_NAME_SET_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 28:
{
this->IDC_TEXTURE_FILENAME_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 29:
{
this->IDC_CLEAR_TEXTURE_FILENAME_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 30:
{
this->textBlock13 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 31:
{
this->textBlock14 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 32:
{
this->IDC_POWER_SLIDER = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 33:
{
this->ID_COLOR_ADD_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 34:
{
this->scrollBar = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 35:
{
this->TextureImage1 = safe_cast<::Windows::UI::Xaml::Controls::Image^>(__target);
}
break;
case 36:
{
this->IDC_TEXTURE_IMAGE1_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::Button^>(this->IDC_TEXTURE_IMAGE1_BUTTON))->Click += ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::RoutedEventArgs^))&Scenario5_MatsTexs::IDC_TEXTURE_IMAGE1_BUTTON_Click);
}
break;
case 37:
{
this->IDC_TEXTURE_IMAGE2_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::Button^>(this->IDC_TEXTURE_IMAGE2_BUTTON))->Click += ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::RoutedEventArgs^))&Scenario5_MatsTexs::IDC_TEXTURE_IMAGE2_BUTTON_Click);
}
break;
case 38:
{
this->TextureImage2 = safe_cast<::Windows::UI::Xaml::Controls::Image^>(__target);
}
break;
case 39:
{
this->matName = safe_cast<::Windows::UI::Xaml::Controls::ListBoxItem^>(__target);
}
break;
case 40:
{
this->rgba_A = safe_cast<::Windows::UI::Xaml::Controls::ListBoxItem^>(__target);
}
break;
}
_contentLoaded = true;
}
::Windows::UI::Xaml::Markup::IComponentConnector^ ::Hot3dxRotoDraw::Scenario5_MatsTexs::GetBindingConnector(int __connectionId, ::Platform::Object^ __target)
{
__connectionId; // unreferenced
__target; // unreferenced
return nullptr;
}
#pragma warning(pop)
| 36.336 | 239 | 0.561867 | hot3dx |
64460cb1484577ce0dfd24ee892719fc986ca795 | 2,780 | cc | C++ | cdn/src/model/ModifyFileCacheExpiredConfigRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | cdn/src/model/ModifyFileCacheExpiredConfigRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | cdn/src/model/ModifyFileCacheExpiredConfigRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/cdn/model/ModifyFileCacheExpiredConfigRequest.h>
using AlibabaCloud::Cdn::Model::ModifyFileCacheExpiredConfigRequest;
ModifyFileCacheExpiredConfigRequest::ModifyFileCacheExpiredConfigRequest() :
RpcServiceRequest("cdn", "2014-11-11", "ModifyFileCacheExpiredConfig")
{}
ModifyFileCacheExpiredConfigRequest::~ModifyFileCacheExpiredConfigRequest()
{}
std::string ModifyFileCacheExpiredConfigRequest::getSecurityToken()const
{
return securityToken_;
}
void ModifyFileCacheExpiredConfigRequest::setSecurityToken(const std::string& securityToken)
{
securityToken_ = securityToken;
setParameter("SecurityToken", securityToken);
}
std::string ModifyFileCacheExpiredConfigRequest::getConfigID()const
{
return configID_;
}
void ModifyFileCacheExpiredConfigRequest::setConfigID(const std::string& configID)
{
configID_ = configID;
setParameter("ConfigID", configID);
}
std::string ModifyFileCacheExpiredConfigRequest::getDomainName()const
{
return domainName_;
}
void ModifyFileCacheExpiredConfigRequest::setDomainName(const std::string& domainName)
{
domainName_ = domainName;
setParameter("DomainName", domainName);
}
std::string ModifyFileCacheExpiredConfigRequest::getWeight()const
{
return weight_;
}
void ModifyFileCacheExpiredConfigRequest::setWeight(const std::string& weight)
{
weight_ = weight;
setParameter("Weight", weight);
}
std::string ModifyFileCacheExpiredConfigRequest::getCacheContent()const
{
return cacheContent_;
}
void ModifyFileCacheExpiredConfigRequest::setCacheContent(const std::string& cacheContent)
{
cacheContent_ = cacheContent;
setParameter("CacheContent", cacheContent);
}
long ModifyFileCacheExpiredConfigRequest::getOwnerId()const
{
return ownerId_;
}
void ModifyFileCacheExpiredConfigRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string ModifyFileCacheExpiredConfigRequest::getTTL()const
{
return tTL_;
}
void ModifyFileCacheExpiredConfigRequest::setTTL(const std::string& tTL)
{
tTL_ = tTL;
setParameter("TTL", tTL);
}
| 26.47619 | 93 | 0.771942 | sdk-team |
6446489f3bc7686b13790767d3634e2a0f2f0aa2 | 754 | cpp | C++ | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | 1 | 2021-12-22T18:24:08.000Z | 2021-12-22T18:24:08.000Z | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | null | null | null | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | null | null | null | //--------------------------------------------------
// Robot Simulator
// semaphore.cpp
// Date: 24/06/2020
// By Breno Cunha Queiroz
//--------------------------------------------------
#include "semaphore.h"
Semaphore::Semaphore(Device* device)
{
_device = device;
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if(vkCreateSemaphore(_device->handle(), &semaphoreInfo, nullptr, &_semaphore) != VK_SUCCESS)
{
std::cout << BOLDRED << "[Semaphore]" << RESET << RED << " Failed to create semaphore!" << RESET << std::endl;
exit(1);
}
}
Semaphore::~Semaphore()
{
if(_semaphore != nullptr)
{
vkDestroySemaphore(_device->handle(), _semaphore, nullptr);
_semaphore = nullptr;
}
}
| 23.5625 | 112 | 0.600796 | happydpc |
644798953569b9ef0bb7edf4ed78e2e4f7a17f15 | 8,707 | tcc | C++ | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | #include "libiop/algebra/utils.hpp"
namespace libiop {
template<typename FieldT>
combined_denominator<FieldT>::combined_denominator(const std::size_t num_rationals) :
num_rationals_(num_rationals)
{
}
/* Returns the product of all the denominators */
template<typename FieldT>
std::shared_ptr<std::vector<FieldT>> combined_denominator<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const
{
if (constituent_oracle_evaluations.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
std::shared_ptr<std::vector<FieldT>> result = std::make_shared<std::vector<FieldT>>(
*constituent_oracle_evaluations[0].get());
for (std::size_t i = 1; i < constituent_oracle_evaluations.size(); ++i)
{
if (constituent_oracle_evaluations[i]->size() != result->size())
{
throw std::invalid_argument("Vectors of mismatched size.");
}
for (std::size_t j = 0; j < result->size(); ++j)
{
result->operator[](j) *= constituent_oracle_evaluations[i]->operator[](j);
}
}
return result;
}
/* Takes a random linear combination of the constituent oracle evaluations. */
template<typename FieldT>
FieldT combined_denominator<FieldT>::evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const
{
libff::UNUSED(evaluation_position);
libff::UNUSED(evaluation_point);
if (constituent_oracle_evaluations.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
FieldT result = constituent_oracle_evaluations[0];
for (std::size_t i = 1; i < constituent_oracle_evaluations.size(); ++i)
{
result *= constituent_oracle_evaluations[i];
}
return result;
}
template<typename FieldT>
combined_numerator<FieldT>::combined_numerator(const std::size_t num_rationals) :
num_rationals_(num_rationals)
{
}
template<typename FieldT>
void combined_numerator<FieldT>::set_coefficients(const std::vector<FieldT>& coefficients)
{
if (coefficients.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of random coefficients as oracles.");
}
this->coefficients_ = coefficients;
}
template<typename FieldT>
std::shared_ptr<std::vector<FieldT>> combined_numerator<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const{
if (constituent_oracle_evaluations.size() != 2*this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
const size_t codeword_domain_size = constituent_oracle_evaluations[0]->size();
std::shared_ptr<std::vector<FieldT>> result = std::make_shared<std::vector<FieldT>>(
codeword_domain_size, FieldT::zero());
for (size_t j = 0; j < codeword_domain_size; j++)
{
for (size_t i = 0; i < this->num_rationals_; i++)
{
FieldT cur = this->coefficients_[i];
/** Multiply by numerator */
cur *= constituent_oracle_evaluations[i]->operator[](j);
/** Multiply by all other denominators */
for (size_t k = this->num_rationals_; k < 2 * this->num_rationals_; k++)
{
if (k - this->num_rationals_ == i)
{
continue;
}
cur *= constituent_oracle_evaluations[k]->operator[](j);
}
result->operator[](j) += cur;
}
}
return result;
}
template<typename FieldT>
FieldT combined_numerator<FieldT>::evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const
{
libff::UNUSED(evaluation_position);
libff::UNUSED(evaluation_point);
if (constituent_oracle_evaluations.size() != 2*this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
FieldT result = FieldT::zero();
for (size_t i = 0; i < this->num_rationals_; i++)
{
FieldT cur = this->coefficients_[i];
/** Multiply by numerator */
cur *= constituent_oracle_evaluations[i];
/** Multiply by all other denominators */
for (size_t j = this->num_rationals_; j < 2 * this->num_rationals_; j++)
{
if (j - this->num_rationals_ == i)
{
continue;
}
cur *= constituent_oracle_evaluations[j];
}
result += cur;
}
return result;
}
template<typename FieldT>
rational_linear_combination<FieldT>::rational_linear_combination(
iop_protocol<FieldT> &IOP,
const std::size_t num_rationals,
const std::vector<oracle_handle_ptr> numerator_handles,
const std::vector<oracle_handle_ptr> denominator_handles) :
IOP_(IOP),
num_rationals_(num_rationals)
{
if (numerator_handles.size() != this->num_rationals_ || denominator_handles.size() != this->num_rationals_)
{
throw std::invalid_argument("Rational Linear Combination: "
"#numerator handles passed in != #denominator handles passed in");
}
this->numerator_ = std::make_shared<combined_numerator<FieldT>>(this->num_rationals_);
this->denominator_ = std::make_shared<combined_denominator<FieldT>>(this->num_rationals_);
const domain_handle domain = this->IOP_.get_oracle_domain(numerator_handles[0]);
size_t denominator_degree = 1;
for (size_t i = 0; i < this->num_rationals_; i++)
{
denominator_degree += this->IOP_.get_oracle_degree(denominator_handles[i]) - 1;
}
this->combined_denominator_handle_ = this->IOP_.register_virtual_oracle(
domain, denominator_degree, denominator_handles, this->denominator_);
size_t numerator_degree = 0;
/** numerator degree = max(deg(N_i) + sum_{j \neq i} D_j)
* sum_{j \neq i} D_j = (sum D_i) - D_j
*/
for (size_t i = 0; i < this->num_rationals_; i++)
{
size_t candidate_numerator_degree =
this->IOP_.get_oracle_degree(numerator_handles[i])
+ denominator_degree - this->IOP_.get_oracle_degree(denominator_handles[i]);
if (candidate_numerator_degree > numerator_degree)
{
numerator_degree = candidate_numerator_degree;
}
}
std::vector<oracle_handle_ptr> all_handles(numerator_handles);
all_handles.insert(all_handles.end(), denominator_handles.begin(), denominator_handles.end());
this->combined_numerator_handle_ = this->IOP_.register_virtual_oracle(
domain, numerator_degree, all_handles, this->numerator_);
}
template<typename FieldT>
void rational_linear_combination<FieldT>::set_coefficients(
const std::vector<FieldT>& coefficients)
{
this->numerator_->set_coefficients(coefficients);
}
template<typename FieldT>
std::vector<FieldT> rational_linear_combination<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &numerator_evals,
const std::vector<std::shared_ptr<std::vector<FieldT>>> &denominator_evals) const
{
std::vector<FieldT> combined_denominator_evals =
*this->denominator_->evaluated_contents(denominator_evals).get();
const bool denominator_can_contain_zeroes = false;
combined_denominator_evals = batch_inverse<FieldT>(
combined_denominator_evals, denominator_can_contain_zeroes);
std::vector<std::shared_ptr<std::vector<FieldT>>> all_evals;
for (size_t i = 0; i < this->num_rationals_; i++)
{
all_evals.emplace_back(numerator_evals[i]);
}
for (size_t i = 0; i < this->num_rationals_; i++)
{
all_evals.emplace_back(denominator_evals[i]);
}
std::vector<FieldT> result = *this->numerator_->evaluated_contents(all_evals).get();
for (size_t i = 0; i < numerator_evals[0]->size(); i++)
{
result[i] *= combined_denominator_evals[i];
}
return result;
}
template<typename FieldT>
oracle_handle_ptr rational_linear_combination<FieldT>::get_denominator_handle() const
{
return std::make_shared<virtual_oracle_handle>(this->combined_denominator_handle_);
}
template<typename FieldT>
oracle_handle_ptr rational_linear_combination<FieldT>::get_numerator_handle() const
{
return std::make_shared<virtual_oracle_handle>(this->combined_numerator_handle_);
}
} // libiop
| 36.279167 | 111 | 0.683932 | alexander-zw |
64489282c7c1649226ff6f3dfb5152fa25dd174d | 9,447 | cpp | C++ | BRE/GeometryPass/GeometryPass.cpp | nicolasbertoa/D3D12Base | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | 9 | 2016-07-14T05:43:45.000Z | 2016-10-31T15:21:53.000Z | BRE/GeometryPass/GeometryPass.cpp | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | BRE/GeometryPass/GeometryPass.cpp | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | #include "GeometryPass.h"
#include <d3d12.h>
#include <DirectXColors.h>
#include <tbb/parallel_for.h>
#include <CommandListExecutor/CommandListExecutor.h>
#include <DescriptorManager\CbvSrvUavDescriptorManager.h>
#include <DescriptorManager\RenderTargetDescriptorManager.h>
#include <DirectXManager\DirectXManager.h>
#include <DXUtils/D3DFactory.h>
#include <GeometryPass\Recorders\HeightMappingCommandListRecorder.h>
#include <GeometryPass\Recorders\NormalMappingCommandListRecorder.h>
#include <GeometryPass\Recorders\TextureMappingCommandListRecorder.h>
#include <ResourceManager\ResourceManager.h>
#include <ResourceStateManager\ResourceStateManager.h>
#include <ShaderUtils\CBuffers.h>
#include <Utils\DebugUtils.h>
using namespace DirectX;
namespace BRE {
namespace {
// Geometry buffer formats
const DXGI_FORMAT sGeometryBufferFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]{
DXGI_FORMAT_R16G16B16A16_FLOAT,
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN
};
///
/// @brief Create geometry buffers and render target views
/// @param buffers Output list of geometry buffers
/// @param bufferRenderTargetViews Output geometry buffers render target views
///
void
CreateGeometryBuffersAndRenderTargetViews(ID3D12Resource* buffers[GeometryPass::BUFFERS_COUNT],
D3D12_CPU_DESCRIPTOR_HANDLE bufferRenderTargetViews[GeometryPass::BUFFERS_COUNT]) noexcept
{
// Set shared buffers properties
D3D12_RESOURCE_DESC resourceDescriptor = D3DFactory::GetResourceDescriptor(ApplicationSettings::sWindowWidth,
ApplicationSettings::sWindowHeight,
DXGI_FORMAT_UNKNOWN,
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
D3D12_RESOURCE_DIMENSION_TEXTURE2D,
D3D12_TEXTURE_LAYOUT_UNKNOWN,
0U);
D3D12_CLEAR_VALUE clearValue[]
{
{ DXGI_FORMAT_UNKNOWN, 0.0f, 0.0f, 0.0f, 1.0f },
{ DXGI_FORMAT_UNKNOWN, 0.0f, 0.0f, 0.0f, 0.0f },
};
BRE_ASSERT(_countof(clearValue) == GeometryPass::BUFFERS_COUNT);
const D3D12_HEAP_PROPERTIES heapProperties = D3DFactory::GetHeapProperties();
// Create and store render target views
const wchar_t* resourceNames[GeometryPass::BUFFERS_COUNT] =
{
L"Normal_RoughnessTexture Buffer",
L"BaseColor_MetalnessTexture Buffer"
};
for (std::uint32_t i = 0U; i < GeometryPass::BUFFERS_COUNT; ++i) {
resourceDescriptor.Format = sGeometryBufferFormats[i];
clearValue[i].Format = resourceDescriptor.Format;
D3D12_RENDER_TARGET_VIEW_DESC rtvDescriptor{};
rtvDescriptor.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
rtvDescriptor.Format = resourceDescriptor.Format;
resourceDescriptor.MipLevels = 1U;
buffers[i] = &ResourceManager::CreateCommittedResource(heapProperties,
D3D12_HEAP_FLAG_NONE,
resourceDescriptor,
D3D12_RESOURCE_STATE_RENDER_TARGET,
&clearValue[i],
resourceNames[i],
ResourceManager::ResourceStateTrackingType::FULL_TRACKING);
RenderTargetDescriptorManager::CreateRenderTargetView(*buffers[i],
rtvDescriptor,
&bufferRenderTargetViews[i]);
}
}
}
GeometryPass::GeometryPass(GeometryCommandListRecorders& geometryPassCommandListRecorders)
: mGeometryCommandListRecorders(geometryPassCommandListRecorders)
{}
void
GeometryPass::Init(const D3D12_CPU_DESCRIPTOR_HANDLE& depthBufferView) noexcept
{
BRE_ASSERT(IsDataValid() == false);
BRE_ASSERT(mGeometryCommandListRecorders.empty() == false);
CreateGeometryBuffersAndRenderTargetViews(mGeometryBuffers, mGeometryBufferRenderTargetViews);
HeightMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
NormalMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
TextureMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
InitShaderResourceViews();
// Init geometry command list recorders
for (GeometryCommandListRecorders::value_type& recorder : mGeometryCommandListRecorders) {
BRE_ASSERT(recorder.get() != nullptr);
recorder->Init(mGeometryBufferRenderTargetViews,
BUFFERS_COUNT,
depthBufferView);
}
BRE_ASSERT(IsDataValid());
}
std::uint32_t
GeometryPass::Execute(const FrameCBuffer& frameCBuffer) noexcept
{
BRE_ASSERT(IsDataValid());
const std::uint32_t geometryPassCommandListCount = static_cast<std::uint32_t>(mGeometryCommandListRecorders.size());
std::uint32_t commandListCount = geometryPassCommandListCount;
commandListCount += RecordAndPushPrePassCommandLists();
// Execute tasks
std::uint32_t grainSize{ max(1U, (geometryPassCommandListCount) / ApplicationSettings::sCpuProcessorCount) };
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, geometryPassCommandListCount, grainSize),
[&](const tbb::blocked_range<size_t>& r) {
for (size_t i = r.begin(); i != r.end(); ++i)
mGeometryCommandListRecorders[i]->RecordAndPushCommandLists(frameCBuffer);
}
);
return commandListCount;
}
bool
GeometryPass::IsDataValid() const noexcept
{
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (mGeometryBuffers[i] == nullptr) {
return false;
}
}
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (mGeometryBufferRenderTargetViews[i].ptr == 0UL) {
return false;
}
}
return mGeometryCommandListRecorders.empty() == false;
}
std::uint32_t
GeometryPass::RecordAndPushPrePassCommandLists() noexcept
{
BRE_ASSERT(IsDataValid());
ID3D12GraphicsCommandList& commandList = mPrePassCommandListPerFrame.ResetCommandListWithNextCommandAllocator(nullptr);
D3D12_RESOURCE_BARRIER barriers[BUFFERS_COUNT];
std::uint32_t barrierCount = 0UL;
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (ResourceStateManager::GetResourceState(*mGeometryBuffers[i]) != D3D12_RESOURCE_STATE_RENDER_TARGET) {
barriers[barrierCount] = ResourceStateManager::ChangeResourceStateAndGetBarrier(*mGeometryBuffers[i],
D3D12_RESOURCE_STATE_RENDER_TARGET);
++barrierCount;
}
}
if (barrierCount > 0UL) {
commandList.ResourceBarrier(barrierCount, barriers);
}
commandList.RSSetViewports(1U, &ApplicationSettings::sScreenViewport);
commandList.RSSetScissorRects(1U, &ApplicationSettings::sScissorRect);
float zero[4U] = { 0.0f, 0.0f, 0.0f, 0.0f };
commandList.ClearRenderTargetView(mGeometryBufferRenderTargetViews[NORMAL_ROUGHNESS], Colors::Black, 0U, nullptr);
commandList.ClearRenderTargetView(mGeometryBufferRenderTargetViews[BASECOLOR_METALNESS], zero, 0U, nullptr);
BRE_CHECK_HR(commandList.Close());
CommandListExecutor::Get().PushCommandList(commandList);
return 1U;
}
void
GeometryPass::InitShaderResourceViews() noexcept
{
D3D12_SHADER_RESOURCE_VIEW_DESC srvDescriptors[BUFFERS_COUNT]{};
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
srvDescriptors[i].Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDescriptors[i].ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDescriptors[i].Texture2D.MostDetailedMip = 0;
srvDescriptors[i].Texture2D.ResourceMinLODClamp = 0.0f;
srvDescriptors[i].Format = mGeometryBuffers[i]->GetDesc().Format;
srvDescriptors[i].Texture2D.MipLevels = mGeometryBuffers[i]->GetDesc().MipLevels;
}
const D3D12_GPU_DESCRIPTOR_HANDLE shaderResourceViewBegin =
CbvSrvUavDescriptorManager::CreateShaderResourceViews(mGeometryBuffers,
srvDescriptors,
BUFFERS_COUNT);
// After creating all the contiguous descriptors, we need to initialize each
// shader resource view member variables
const std::size_t descriptorHandleIncrementSize =
DirectXManager::GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
mGeometryBufferShaderResourceViews[i].ptr = shaderResourceViewBegin.ptr + i * descriptorHandleIncrementSize;
}
}
} | 41.986667 | 132 | 0.659998 | nicolasbertoa |
64495b0aa5d86ae44570c2d99cb6363e1d63ca9b | 526 | cpp | C++ | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | 2 | 2017-03-18T22:04:47.000Z | 2017-03-30T23:24:53.000Z | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | /*
Random seed.
*** Try and execute the program
more than once to see results.
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// Sets the seed of the random number generator.
srand(static_cast<unsigned int>(time(0)));
for (int i = 1; i <= 40; ++i) {
//int d1 = 1 + rand() % 6;
//int d2 = 1 + rand() % 6;
//cout << d1 << " " << d2 << endl;
int d1 = rand() % 10 + 11;
cout << d1 << endl;
}
cout << endl;
cin.ignore();
cin.get();
return 0;
}
| 15.470588 | 50 | 0.551331 | rushone2010 |
644a657565febdbdc70180d6cc39bb26357c09a8 | 4,763 | cpp | C++ | src/mame/video/gotya.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/video/gotya.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/video/gotya.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Zsolt Vasvari
#include "emu.h"
#include "video/resnet.h"
#include "includes/gotya.h"
/***************************************************************************
Convert the color PROMs into a more useable format.
***************************************************************************/
void gotya_state::gotya_palette(palette_device &palette) const
{
uint8_t const *color_prom = memregion("proms")->base();
static constexpr int resistances_rg[3] = { 1000, 470, 220 };
static constexpr int resistances_b [2] = { 470, 220 };
// compute the color output resistor weights
double rweights[3], gweights[3], bweights[2];
compute_resistor_weights(0, 255, -1.0,
3, &resistances_rg[0], rweights, 0, 0,
3, &resistances_rg[0], gweights, 0, 0,
2, &resistances_b[0], bweights, 0, 0);
// create a lookup table for the palette
for (int i = 0; i < 0x20; i++)
{
int bit0, bit1, bit2;
// red component
bit0 = BIT(color_prom[i], 0);
bit1 = BIT(color_prom[i], 1);
bit2 = BIT(color_prom[i], 2);
int const r = combine_weights(rweights, bit0, bit1, bit2);
// green component
bit0 = BIT(color_prom[i], 3);
bit1 = BIT(color_prom[i], 4);
bit2 = BIT(color_prom[i], 5);
int const g = combine_weights(gweights, bit0, bit1, bit2);
// blue component
bit0 = BIT(color_prom[i], 6);
bit1 = BIT(color_prom[i], 7);
int const b = combine_weights(bweights, bit0, bit1);
palette.set_indirect_color(i, rgb_t(r, g, b));
}
// color_prom now points to the beginning of the lookup table
color_prom += 32;
for (int i = 0; i < 0x40; i++)
{
uint8_t const ctabentry = color_prom[i] & 0x07;
palette.set_pen_indirect(i, ctabentry);
}
}
void gotya_state::gotya_videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
void gotya_state::gotya_colorram_w(offs_t offset, uint8_t data)
{
m_colorram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
void gotya_state::gotya_video_control_w(uint8_t data)
{
/* bit 0 - scroll bit 8
bit 1 - flip screen
bit 2 - sound disable ??? */
m_scroll_bit_8 = data & 0x01;
if (flip_screen() != (data & 0x02))
{
flip_screen_set(data & 0x02);
machine().tilemap().mark_all_dirty();
}
}
TILE_GET_INFO_MEMBER(gotya_state::get_bg_tile_info)
{
int code = m_videoram[tile_index];
int color = m_colorram[tile_index] & 0x0f;
tileinfo.set(0, code, color, 0);
}
TILEMAP_MAPPER_MEMBER(gotya_state::tilemap_scan_rows_thehand)
{
/* logical (col,row) -> memory offset */
row = 31 - row;
col = 63 - col;
return ((row) * (num_cols >> 1)) + (col & 31) + ((col >> 5) * 0x400);
}
void gotya_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(gotya_state::get_bg_tile_info)), tilemap_mapper_delegate(*this, FUNC(gotya_state::tilemap_scan_rows_thehand)), 8, 8, 64, 32);
}
void gotya_state::draw_status_row( bitmap_ind16 &bitmap, const rectangle &cliprect, int sx, int col )
{
int row;
if (flip_screen())
{
sx = 35 - sx;
}
for (row = 29; row >= 0; row--)
{
int sy;
if (flip_screen())
sy = row;
else
sy = 31 - row;
m_gfxdecode->gfx(0)->opaque(bitmap,cliprect,
m_videoram2[row * 32 + col],
m_videoram2[row * 32 + col + 0x10] & 0x0f,
flip_screen_x(), flip_screen_y(),
8 * sx, 8 * sy);
}
}
void gotya_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect )
{
uint8_t *spriteram = m_spriteram;
int offs;
for (offs = 2; offs < 0x0e; offs += 2)
{
int code = spriteram[offs + 0x01] >> 2;
int color = spriteram[offs + 0x11] & 0x0f;
int sx = 256 - spriteram[offs + 0x10] + (spriteram[offs + 0x01] & 0x01) * 256;
int sy = spriteram[offs + 0x00];
if (flip_screen())
sy = 240 - sy;
m_gfxdecode->gfx(1)->transpen(bitmap,cliprect,
code, color,
flip_screen_x(), flip_screen_y(),
sx, sy, 0);
}
}
void gotya_state::draw_status( bitmap_ind16 &bitmap, const rectangle &cliprect )
{
draw_status_row(bitmap, cliprect, 0, 1);
draw_status_row(bitmap, cliprect, 1, 0);
draw_status_row(bitmap, cliprect, 2, 2); /* these two are blank, but I dont' know if the data comes */
draw_status_row(bitmap, cliprect, 33, 13); /* from RAM or 'hardcoded' into the hardware. Likely the latter */
draw_status_row(bitmap, cliprect, 35, 14);
draw_status_row(bitmap, cliprect, 34, 15);
}
uint32_t gotya_state::screen_update_gotya(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->set_scrollx(0, -(*m_scroll + (m_scroll_bit_8 * 256)) - 2 * 8);
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
draw_sprites(bitmap, cliprect);
draw_status(bitmap, cliprect);
return 0;
}
| 26.758427 | 221 | 0.65274 | Robbbert |
644e8d460bfe9f3df6be2050b0aca3fc23bf59a5 | 10,094 | cc | C++ | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// nd3d9server_resource.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gfx2/nd3d9server.h"
#include "resource/nresourceserver.h"
#include "gfx2/nmesh2.h"
#include "gfx2/nd3d9mesharray.h"
#include "gfx2/nd3d9shader.h"
#include "gfx2/nd3d9occlusionquery.h"
//------------------------------------------------------------------------------
/**
Create a new shared mesh object. If the object already exists, its refcount
is increment.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Mesh2 object
*/
nMesh2*
nD3D9Server::NewMesh(const nString& RsrcName)
{
return (nMesh2*)nResourceServer::Instance()->NewResource("nd3d9mesh", RsrcName, nResource::Mesh);
}
//------------------------------------------------------------------------------
/**
Create a new mesh array object.
@return pointer to a nD3D9MeshArray object
*/
nMeshArray*
nD3D9Server::NewMeshArray(const nString& RsrcName)
{
return (nMeshArray*)nResourceServer::Instance()->NewResource("nd3d9mesharray", RsrcName, nResource::Mesh);
}
//------------------------------------------------------------------------------
/**
Create a new shared texture object. If the object already exists, its
refcount is incremented.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Texture2 object
*/
nTexture2*
nD3D9Server::NewTexture(const nString& RsrcName)
{
return (nTexture2*)nResourceServer::Instance()->NewResource("nd3d9texture", RsrcName, nResource::Texture);
}
//------------------------------------------------------------------------------
/**
Create a new shared shader object. If the object already exists, its
refcount is incremented.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Shader2 object
*/
nShader2*
nD3D9Server::NewShader(const nString& RsrcName)
{
return (nShader2*)nResourceServer::Instance()->NewResource("nd3d9shader", RsrcName, nResource::Shader);
}
//------------------------------------------------------------------------------
/**
Create a new render target object.
@param RsrcName a resource name for resource sharing
@param width width of render target
@param height height of render target
@param format pixel format of render target
@param usageFlags a combination of nTexture2::Usage flags
*/
nTexture2*
nD3D9Server::NewRenderTarget(const nString& RsrcName,
int width,
int height,
nTexture2::Format format,
int usageFlags)
{
nTexture2* renderTarget = (nTexture2*)nResourceServer::Instance()->NewResource("nd3d9texture", RsrcName, nResource::Texture);
n_assert(renderTarget);
if (!renderTarget->IsLoaded())
{
n_assert(0 != (usageFlags & (nTexture2::RenderTargetColor | nTexture2::RenderTargetDepth | nTexture2::RenderTargetStencil)));
renderTarget->SetUsage(usageFlags);
renderTarget->SetWidth(width);
renderTarget->SetHeight(height);
renderTarget->SetDepth(1);
renderTarget->SetFormat(format);
renderTarget->SetType(nTexture2::TEXTURE_2D);
bool success = renderTarget->Load();
if (!success)
{
renderTarget->Release();
return 0;
}
}
return renderTarget;
}
//------------------------------------------------------------------------------
/**
Create a new occlusion query object.
@return pointer to a new occlusion query object
*/
nOcclusionQuery*
nD3D9Server::NewOcclusionQuery()
{
return n_new(nD3D9OcclusionQuery);
}
//------------------------------------------------------------------------------
/**
Create a new occlusion query object.
-19-April-07 kims Fixed not to create a new vertex declaration if the declaration
is already created one. It was moved from nd3d9mesh to nd3d9server.
The patch from Trignarion.
@return pointer to a new d3d vertex declaration.
*/
IDirect3DVertexDeclaration9*
nD3D9Server::NewVertexDeclaration(const int vertexComponentMask)
{
IDirect3DVertexDeclaration9* d3d9vdecl(0);
if (this->vertexDeclarationCache.HasKey(vertexComponentMask))
{
d3d9vdecl = this->vertexDeclarationCache.GetElement(vertexComponentMask);
d3d9vdecl->AddRef();
return d3d9vdecl;
}
const int maxElements = nMesh2::NumVertexComponents;
D3DVERTEXELEMENT9 decl[maxElements];
int curElement = 0;
int curOffset = 0;
int index;
for (index = 0; index < maxElements; index++)
{
int mask = (1<<index);
if (vertexComponentMask & mask)
{
decl[curElement].Stream = 0;
n_assert( curOffset <= int( 0xffff ) );
decl[curElement].Offset = static_cast<WORD>( curOffset );
decl[curElement].Method = D3DDECLMETHOD_DEFAULT;
switch (mask)
{
case nMesh2::Coord:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_POSITION;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Coord4:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_POSITION;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::Normal:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_NORMAL;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Tangent:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_TANGENT;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Binormal:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_BINORMAL;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Color:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_COLOR;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::Uv0:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 0;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv1:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 1;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv2:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 2;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv3:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 3;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Weights:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_BLENDWEIGHT;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::JIndices:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_BLENDINDICES;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
default:
n_error("Unknown vertex component in vertex component mask");
break;
}
curElement++;
}
}
// write vertex declaration terminator element, see D3DDECL_END() macro in d3d9types.h for details
decl[curElement].Stream = 0xff;
decl[curElement].Offset = 0;
decl[curElement].Type = D3DDECLTYPE_UNUSED;
decl[curElement].Method = 0;
decl[curElement].Usage = 0;
decl[curElement].UsageIndex = 0;
//n_dxverify(//gfxServer->pD3D9Device->CreateVertexDeclaration(decl, &(this->vertexDeclaration)),
HRESULT hr = this->pD3D9Device->CreateVertexDeclaration(decl, &d3d9vdecl);
d3d9vdecl->AddRef();
this->vertexDeclarationCache.Add(vertexComponentMask, d3d9vdecl);
return d3d9vdecl;
}
| 38.67433 | 134 | 0.518526 | moltenguy1 |
6450ffd44849c9ecceaac140a9e4e85d496b960b | 4,721 | hpp | C++ | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | null | null | null | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | 11 | 2021-12-08T10:34:17.000Z | 2022-01-20T13:40:05.000Z | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | null | null | null | /* utils.hpp -- Utility function around type checking of py::array_t
* Copyright 2022 Ralph Urlus
*/
#ifndef INCLUDE_MMU_API_UTILS_HPP_
#define INCLUDE_MMU_API_UTILS_HPP_
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <string>
#include <mmu/api/numpy.hpp>
#include <mmu/core/common.hpp>
namespace py = pybind11;
namespace mmu {
namespace api {
namespace details {
/* Check if arr is 1D or two 1D with the second axis containing a single index.
* I.e. arr.shape ==
* * (n, )
* * (1, n)
* * (n, 1)
*
* Throws RuntimeError if condition is not met.
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
*/
template <typename T>
inline int check_1d_soft(const py::array_t<T>& arr, const std::string& name) {
ssize_t n_dim = arr.ndim();
if (n_dim == 1) {
return 0;
}
if (n_dim == 2) {
if (arr.shape(1) == 1) {
return 0;
}
if (arr.shape(0) == 1) {
return 1;
}
}
throw std::runtime_error(name + " should be one dimensional");
}
/* Check x and y have the same length where we account for row and column orientation.
* We only consider the obs_axis_ for each array, the obs_axis_ is the 0 for an array shaped (n, m)
*
* Throws RuntimeError if condition is not met.
*/
template <typename T, typename V>
inline void check_equal_length(
const py::array_t<T>& x,
const py::array_t<V>& y,
const std::string& x_name,
const std::string& y_name,
const int obs_axis_x = 0,
const int obs_axis_y = 0) {
if (x.shape(obs_axis_x) != y.shape(obs_axis_y)) {
throw std::runtime_error(x_name + " and " + y_name + " should have equal number of observations");
}
}
template <typename T>
inline void check_contiguous(const py::array_t<T>& arr, const std::string& name) {
if (!npy::is_contiguous<T>(arr)) {
throw std::runtime_error(name + " should be C or F contiguous");
}
}
template <typename T, typename V>
inline void check_equal_shape(
const py::array_t<T>& x,
const py::array_t<V>& y,
const std::string& x_name,
const std::string& y_name) {
int x_dim = x.ndim();
int y_dim = y.ndim();
int pass = 0;
if (x_dim == y_dim) {
for (int i = 0; i < x_dim; i++) {
pass += x.shape(i) == y.shape(i);
}
}
if (pass != x_dim) {
throw std::runtime_error(x_name + " and " + y_name + " should have equal shape");
}
}
/* Check if order matches shape of the array and copy otherwhise.
* We expect the observations (rows or columns) to be contiguous in memory.
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
*
* --- Returns ---
* - arr : the input array or the input array with the correct memory order
*/
template <typename T>
inline py::array_t<T> ensure_shape_order(py::array_t<T>& arr, const std::string& name, const int obs_axis = 0) {
const ssize_t n_dim = arr.ndim();
if (n_dim > 2) {
throw std::runtime_error(name + " must be at most two dimensional.");
}
if (obs_axis == 0) {
if (!is_f_contiguous(arr)) {
return py::array_t<T, py::array::f_style | py::array::forcecast>(arr);
}
return arr;
} else if (obs_axis == 1) {
if (!is_c_contiguous(arr)) {
return py::array_t<T, py::array::c_style | py::array::forcecast>(arr);
}
return arr;
} else {
throw std::runtime_error("``obs_axis`` must be zero or one.");
}
} // ensure_shape_order
/* Check if order matches shape of the array and the shape is as expected.
* We expect the observations (rows or columns) to be contiguous in memory.
*
* Array can be one or two dimensional.
* - If 1D it should have size == ``expected``
* - If 2D it should be:
* * C-Contiguous if shape (n, ``expected``)
* * F-Contiguous if shape (``expected``, n)
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
* - expected : the size we expect of one the two dimensions to have
*/
template <typename T>
inline bool is_correct_shape_order(const py::array_t<T>& arr, ssize_t expected) {
ssize_t n_dim = arr.ndim();
bool state = false;
if (n_dim == 1 && arr.size() == expected) {
state = npy::is_c_contiguous(arr);
} else if (n_dim == 2) {
if (arr.shape(1) == expected) {
state = is_c_contiguous(arr);
} else if (arr.shape(0) == expected) {
state = is_f_contiguous(arr);
}
}
return state;
} // check_shape_order
} // namespace details
} // namespace api
} // namespace mmu
#endif // INCLUDE_MMU_API_UTILS_HPP_
| 29.50625 | 112 | 0.614912 | RUrlus |
645551c936cef2b3fe3492e4d5b2e419c1fe9be1 | 2,898 | inl | C++ | inc/subevent/timer_manager.inl | SammyEnigma/subevent | e2d3deb9b55d73278c1c011368c6d1793834bd2d | [
"MIT"
] | 17 | 2017-03-19T16:08:21.000Z | 2022-02-22T16:21:33.000Z | inc/subevent/timer_manager.inl | SammyEnigma/subevent | e2d3deb9b55d73278c1c011368c6d1793834bd2d | [
"MIT"
] | null | null | null | inc/subevent/timer_manager.inl | SammyEnigma/subevent | e2d3deb9b55d73278c1c011368c6d1793834bd2d | [
"MIT"
] | 4 | 2017-12-16T14:36:09.000Z | 2020-02-12T13:14:15.000Z | #ifndef SUBEVENT_TIMER_MANAGER_INL
#define SUBEVENT_TIMER_MANAGER_INL
#include <algorithm>
#include <functional>
#include <subevent/timer_manager.hpp>
#include <subevent/common.hpp>
#include <subevent/timer.hpp>
#include <subevent/thread.hpp>
SEV_NS_BEGIN
//----------------------------------------------------------------------------//
// TimerManager
//----------------------------------------------------------------------------//
TimerManager::TimerManager()
{
}
TimerManager::~TimerManager()
{
cancelAll();
}
void TimerManager::start(Timer* timer)
{
timer->mRunning = true;
Item item;
item.end = std::chrono::system_clock::now() +
std::chrono::milliseconds(timer->getInterval());
item.timer = timer;
for (auto it = mItems.begin(); it != mItems.end(); ++it)
{
if (it->end > item.end)
{
mItems.insert(it, std::move(item));
return;
}
}
mItems.push_back(std::move(item));
}
void TimerManager::cancel(Timer* timer)
{
timer->mRunning = false;
auto it = std::find_if(
mItems.begin(), mItems.end(),
[&](const Item& item) {
return (item.timer == timer);
});
if (it != mItems.end())
{
mItems.erase(it);
return;
}
mExpired.erase(timer);
}
void TimerManager::cancelAll()
{
for (Item& item : mItems)
{
item.timer->mRunning = false;
}
mItems.clear();
for (Timer* timer : mExpired)
{
timer->mRunning = false;
}
mExpired.clear();
}
uint32_t TimerManager::nextTimeout()
{
if (mItems.empty())
{
return UINT32_MAX;
}
else
{
auto now = std::chrono::system_clock::now();
if (mItems.front().end <= now)
{
return 0;
}
auto remain = mItems.front().end - now;
return static_cast<uint32_t>(std::chrono::duration_cast<
std::chrono::milliseconds>(remain).count());
}
}
void TimerManager::expire()
{
auto now = std::chrono::system_clock::now();
while (!mItems.empty())
{
Item& item = mItems.front();
if (item.end > now)
{
break;
}
Timer* timer = item.timer;
mItems.pop_front();
if (!timer->isRunning())
{
continue;
}
mExpired.insert(timer);
Thread::getCurrent()->post([this, timer]() {
if (mExpired.erase(timer) == 0)
{
return;
}
if (!timer->isRunning())
{
return;
}
timer->mRunning = false;
if (timer->isRepeat())
{
start(timer);
}
TimerHandler handler = timer->mHandler;
handler(timer);
});
}
}
SEV_NS_END
#endif // SUBEVENT_TIMER_MANAGER_INL
| 19.32 | 80 | 0.494479 | SammyEnigma |
645d06e94c928595ffdfe90ae8908889e0a7b7e2 | 15,349 | cpp | C++ | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | null | null | null | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | null | null | null | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | 1 | 2019-12-25T02:32:13.000Z | 2019-12-25T02:32:13.000Z | //
// CUCapsuleObstacle.cpp
// Cornell Extensions to Cocos2D
//
// This class implements a capsule physics object. A capsule is a box with semicircular
// ends along the major axis. They are a popular physics objects, particularly for
// character avatars. The rounded ends means they are less likely to snag, and they
// naturally fall off platforms when they go too far.
//
// This file is based on the CS 3152 PhysicsDemo Lab by Don Holden, 2007
//
// Author: Walker White
// Version: 11/24/15
//
#include "CUCapsuleObstacle.h"
NS_CC_BEGIN
/** How many line segments to use to draw a circle */
#define BODY_DEBUG_SEGS 12
/** Epsilon factor to prevent issues with the fixture seams */
#define DEFAULT_EPSILON 0.01
#pragma mark -
#pragma mark Static Constructors
/**
* Creates a new capsule object at the origin with no size.
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create() {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init()) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object at the given point with no size.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object of the given dimensions.
*
* The orientation of the capsule will be a full capsule along the
* major axis. If width == height, it will default to a vertical
* orientation.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The capsule size (width and height)
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos, const Size& size) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos,size)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object of the given dimensions and orientation.
*
* The orientation must be consistent with the major axis (or else the
* two axes must be the same). If the orientation specifies a minor axis,
* then this constructor will return null.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The capsule size (width and height)
* @param orient The capsule orientation
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos, const Size& size, CapsuleObstacle::Orientation orient) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos,size,orient)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
#pragma mark -
#pragma mark Initialization Methods
/**
* Initializes a new capsule object of the given dimensions.
*
* The orientation of the capsule will be a full capsule along the
* major axis. If width == height, it will default to a vertical
* orientation.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The box size (width and height)
*
* @return true if the obstacle is initialized properly, false otherwise.
*/
bool CapsuleObstacle::init(const Vec2& pos, const Size& size) {
Orientation orient = (size.width > size.height ? Orientation::HORIZONTAL : Orientation::VERTICAL);
return init(pos,size,orient);
}
/**
* Initializes a new capsule object of the given dimensions.
*
* The orientation must be consistent with the major axis (or else the
* two axes must be the same). If the orientation specifies a minor axis,
* then this initializer will fail.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The box size (width and height)
*
* @return true if the obstacle is initialized properly, false otherwise.
*/
bool CapsuleObstacle::init(const Vec2& pos, const Size& size, CapsuleObstacle::Orientation orient) {
Obstacle::init(pos);
_core = nullptr;
_cap1 = nullptr;
_cap2 = nullptr;
_orient = orient;
_seamEpsilon = DEFAULT_EPSILON;
resize(size);
return true;
}
#pragma mark -
#pragma mark Scene Graph Methods
/**
* Resets the polygon vertices in the shape to match the dimension.
*
* @param size The new dimension (width and height)
*/
bool CapsuleObstacle::resize(const Size& size) {
_dimension = size;
if (size.width < size.height && isHorizontal(_orient)) {
_orient = Orientation::VERTICAL; // OVERRIDE
} else if (size.width > size.height && !isHorizontal(_orient)) {
_orient = Orientation::HORIZONTAL; // OVERRIDE
}
// Get an AABB for the core
_center.upperBound.x = size.width/2.0f;
_center.upperBound.y = size.height/2.0f;
_center.lowerBound.x = -size.width/2.0f;
_center.lowerBound.y = -size.height/2.0f;
// Now adjust the core
float r = 0;
switch (_orient) {
case Orientation::TOP:
r = size.width/2.0f;
_center.upperBound.y -= r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::VERTICAL:
r = size.width/2.0f;
_center.upperBound.y -= r;
_center.lowerBound.y += r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::BOTTOM:
r = size.width/2.0f;
_center.lowerBound.y += r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::LEFT:
r = size.height/2.0f;
_center.upperBound.x -= r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
case Orientation::HORIZONTAL:
r = size.height/2.0f;
_center.upperBound.x -= r;
_center.lowerBound.x += r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
case Orientation::RIGHT:
r = size.height/2.0f;
_center.lowerBound.x += r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
}
// Handle degenerate polys
if (_center.lowerBound.x == _center.upperBound.x) {
_center.lowerBound.x -= _seamEpsilon;
_center.upperBound.x += _seamEpsilon;
}
if (_center.lowerBound.y == _center.upperBound.y) {
_center.lowerBound.y -= _seamEpsilon;
_center.upperBound.y += _seamEpsilon;
}
// Make the box for the core
b2Vec2 corners[4];
corners[0].x = _center.lowerBound.x;
corners[0].y = _center.lowerBound.y;
corners[1].x = _center.lowerBound.x;
corners[1].y = _center.upperBound.y;
corners[2].x = _center.upperBound.x;
corners[2].y = _center.upperBound.y;
corners[3].x = _center.upperBound.x;
corners[3].y = _center.lowerBound.y;
_shape.Set(corners, 4);
_ends.m_radius = r;
if (_debug != nullptr) {
resetDebugNode();
}
return true;
}
/**
* Redraws the outline of the physics fixtures to the debug node
*
* The debug node is use to outline the fixtures attached to this object.
* This is very useful when the fixtures have a very different shape than
* the texture (e.g. a circular shape attached to a square texture).
*
* Unfortunately, the current implementation is very inefficient. Cocos2d
* does not batch drawnode commands like it does Sprites or PolygonSprites.
* Therefore, every distinct DrawNode is a distinct OpenGL call. This can
* really hurt framerate when debugging mode is on. Ideally, we would refactor
* this so that we only draw to a single, master draw node. However, this
* means that we would have to handle our own vertex transformations, instead
* of relying on the transforms in the scene graph.
*/
void CapsuleObstacle::resetDebugNode() {
Rect bounds;
// Create a capsule polygon
const float coef = (float)M_PI/BODY_DEBUG_SEGS;
float rx = _ends.m_radius*_drawScale.x;
float ry = _ends.m_radius*_drawScale.y;
std::vector<Vec2> vertices;
Vec2 vert;
// Start at top left corner
vert.x = _center.lowerBound.x*_drawScale.x;
vert.y = _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::TOP || _orient == Orientation::VERTICAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = M_PI-ii*coef;
vert.x = rx * cosf(rads);
vert.y = ry * sinf(rads) + _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.upperBound.x*_drawScale.x;
vert.y = _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::RIGHT || _orient == Orientation::HORIZONTAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = M_PI/2-ii*coef;
vert.x = rx * cosf(rads) + _center.upperBound.x*_drawScale.x;
vert.y = ry * sinf(rads);
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.upperBound.x*_drawScale.x;
vert.y = _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::BOTTOM || _orient == Orientation::VERTICAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = 2*M_PI-ii*coef;
vert.x = rx * cosf(rads);
vert.y = ry * sinf(rads) + _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.lowerBound.x*_drawScale.x;
vert.y = _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::LEFT || _orient == Orientation::HORIZONTAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = 3*M_PI/2-ii*coef;
vert.x = rx * cosf(rads) + _center.lowerBound.x*_drawScale.x;
vert.y = ry * sinf(rads);
vertices.push_back(vert);
}
}
// Create polygon
Poly2 poly(vertices);
poly.traverse(Poly2::Traversal::CLOSED);
_debug->setPolygon(poly);
}
#pragma mark -
#pragma mark Physics Methods
/**
* Sets the density of this body
*
* The density is typically measured in usually in kg/m^2. The density can be zero or
* positive. You should generally use similar densities for all your fixtures. This
* will improve stacking stability.
*
* @param value the density of this body
*/
void CapsuleObstacle::setDensity(float value) {
_fixture.density = value;
if (_body != nullptr) {
_core->SetDensity(value);
_cap1->SetDensity(value/2.0f);
_cap2->SetDensity(value/2.0f);
if (!_masseffect) {
_body->ResetMassData();
}
}
}
/**
* Create new fixtures for this body, defining the shape
*
* This is the primary method to override for custom physics objects
*/
void CapsuleObstacle::createFixtures() {
if (_body == nullptr) {
return;
}
releaseFixtures();
// Create the fixture
_fixture.shape = &_shape;
_core = _body->CreateFixture(&_fixture);
_fixture.density = _fixture.density/2.0f;
_ends.m_p.Set(0, 0);
switch (_orient) {
case Orientation::TOP:
_ends.m_p.y = _center.upperBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::VERTICAL:
_ends.m_p.y = _center.upperBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_ends.m_p.y = _center.lowerBound.y;
_fixture.shape = &_ends;
_cap2 = _body->CreateFixture(&_fixture);
break;
case Orientation::BOTTOM:
_ends.m_p.y = _center.lowerBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::LEFT:
_ends.m_p.x = _center.lowerBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::HORIZONTAL:
_ends.m_p.x = _center.lowerBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_ends.m_p.x = _center.upperBound.x;
_fixture.shape = &_ends;
_cap2 = _body->CreateFixture(&_fixture);
break;
case Orientation::RIGHT:
_ends.m_p.x = _center.upperBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
}
markDirty(false);
}
/**
* Release the fixtures for this body, reseting the shape
*
* This is the primary method to override for custom physics objects
*/
void CapsuleObstacle::releaseFixtures() {
if (_core != nullptr) {
_body->DestroyFixture(_core);
_core = nullptr;
}
if (_cap1 != nullptr) {
_body->DestroyFixture(_cap1);
_cap1 = nullptr;
}
if (_cap2 != nullptr) {
_body->DestroyFixture(_cap2);
_cap2 = nullptr;
}
}
NS_CC_END | 32.727079 | 114 | 0.640302 | Mshnik |
646165866984e4c015898cbcc1d64dd6cdada5b7 | 7,010 | cpp | C++ | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 50 | 2020-10-14T10:08:21.000Z | 2022-03-10T12:55:05.000Z | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 16 | 2020-10-26T13:05:47.000Z | 2022-02-22T20:24:41.000Z | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 16 | 2020-10-26T13:05:38.000Z | 2022-01-14T02:52:13.000Z | // SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research
#include <doctest/doctest.h>
#include "core/dataset.hpp"
#include "core/format.hpp"
#include "core/metrics.hpp"
#include "core/distance.hpp"
#include "core/pset.hpp"
#include "analyzers/diversity.hpp"
#include "operators/creator.hpp"
#include "nanobench.h"
namespace Operon {
namespace Test {
template<typename Callable>
struct ComputeDistanceMatrix {
explicit ComputeDistanceMatrix(Callable&& f)
: f_(f) { }
template<typename T>
inline double operator()(std::vector<Operon::Vector<T>> const& hashes) const noexcept
{
double d = 0;
for (size_t i = 0; i < hashes.size() - 1; ++i) {
for (size_t j = i+1; j < hashes.size(); ++j) {
d += static_cast<double>(Operon::Distance::CountIntersect(hashes[i], hashes[j]));
}
}
return d;
}
Callable f_;
};
TEST_CASE("Intersection performance")
{
size_t n = 1000;
size_t maxLength = 200;
size_t maxDepth = 1000;
Operon::RandomGenerator rd(1234);
auto ds = Dataset("../data/Poly-10.csv", true);
auto target = "Y";
auto variables = ds.Variables();
std::vector<Variable> inputs;
std::copy_if(variables.begin(), variables.end(), std::back_inserter(inputs), [&](const auto& v) { return v.Name != target; });
std::uniform_int_distribution<size_t> sizeDistribution(1, maxLength);
PrimitiveSet grammar;
grammar.SetConfig(PrimitiveSet::Arithmetic | NodeType::Exp | NodeType::Log);
std::vector<Tree> trees(n);
auto btc = BalancedTreeCreator { grammar, inputs };
std::generate(trees.begin(), trees.end(), [&]() { return btc(rd, sizeDistribution(rd), 0, maxDepth); });
std::vector<Operon::Vector<Operon::Hash>> hashesStrict(trees.size());
std::vector<Operon::Vector<Operon::Hash>> hashesStruct(trees.size());
std::vector<Operon::Vector<uint32_t>> hashesStrict32(trees.size());
std::vector<Operon::Vector<uint32_t>> hashesStruct32(trees.size());
const auto hashFunc = [](auto& tree, Operon::HashMode mode) { return MakeHashes<Operon::HashFunction::XXHash>(tree, mode); };
std::transform(trees.begin(), trees.end(), hashesStrict.begin(), [&](Tree tree) { return hashFunc(tree, Operon::HashMode::Strict); });
std::transform(trees.begin(), trees.end(), hashesStruct.begin(), [&](Tree tree) { return hashFunc(tree, Operon::HashMode::Relaxed); });
auto convertVec = [](Operon::Vector<Operon::Hash> const& vec) {
Operon::Vector<uint32_t> vec32(vec.size());
std::transform(vec.begin(), vec.end(), vec32.begin(), [](auto h) { return (uint32_t)h; });
pdqsort(vec32.begin(), vec32.end());
return vec32;
};
std::transform(hashesStrict.begin(), hashesStrict.end(), hashesStrict32.begin(), convertVec);
std::transform(hashesStruct.begin(), hashesStruct.end(), hashesStruct32.begin(), convertVec);
std::uniform_int_distribution<size_t> dist(0u, trees.size()-1);
auto avgLen = std::transform_reduce(trees.begin(), trees.end(), 0.0, std::plus<>{}, [](auto const& t) { return t.Length(); }) / (double)n;
auto totalOps = trees.size() * (trees.size() - 1) / 2;
SUBCASE("Performance 64-bit") {
ankerl::nanobench::Bench b;
b.performanceCounters(true).relative(true);
auto s = (double)totalOps * avgLen;
double d = 0;
b.batch(s).run("intersect str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("intersect str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
b.batch(s).run("jaccard str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("jaccard str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
b.batch(s).run("jaccard str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("jaccard str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
}
SUBCASE("Performance 32-bit") {
ankerl::nanobench::Bench b;
b.performanceCounters(true).relative(true);
auto s = (double)totalOps * avgLen;
double d = 0;
b.batch(s).run("intersect str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("intersect str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
b.batch(s).run("jaccard str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("jaccard str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
b.batch(s).run("jaccard str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("jaccard str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
}
}
} // namespace Test
} // namespace Operon
| 39.162011 | 142 | 0.592297 | lf-shaw |
64618a54f5177929ceddee34373c1f95fb79101b | 4,791 | cpp | C++ | Game/src/options.cpp | eliseuegewarth/seven-keys | 7afcd9d9af6d99117bf949e328099ad5f07acef8 | [
"MIT"
] | null | null | null | Game/src/options.cpp | eliseuegewarth/seven-keys | 7afcd9d9af6d99117bf949e328099ad5f07acef8 | [
"MIT"
] | null | null | null | Game/src/options.cpp | eliseuegewarth/seven-keys | 7afcd9d9af6d99117bf949e328099ad5f07acef8 | [
"MIT"
] | 1 | 2017-08-25T14:37:52.000Z | 2017-08-25T14:37:52.000Z | /**
* options.cpp
* Class that implements the options game menu.
* Licença: LGPL. Sem copyright.
*/
#include "options.hpp"
#include "7keys.hpp"
#include "internacionalization.hpp"
#include "util/button.hpp"
#include "core/font.hpp"
#include "core/environment.hpp"
#include "core/mousemotionevent.hpp"
#include <iostream>
using namespace std;
Options::Options() : Level(SevenKeys::ScreenType::OPTIONS)// Class that represents the option of the main menu of the game.
{
Environment *env = Environment::get_instance();// It is an object of the class environment. Is a pointer to the current instance of the game environment.
double width = env->canvas->width();// Receives the width of the game environment.
double height = env->canvas->height();// Receives the height of the game environment.
set_dimensions(width, height);
string path_fullscreen = Internacionalization::load_string("interface/optionsMenu/fullScreen.png");
string path_Sfullscreen = Internacionalization::load_string("interface/optionsMenu/SfullScreen.png");
Button *set_fullscreen = new Button(this, "fullscreen", path_fullscreen, path_Sfullscreen);
// Puts the screen in fullscreen.
set_fullscreen->align_to(this, Object::RIGHT, Object::MIDDLE);
set_fullscreen->set_vertical_position(230);
string path_windowed_mode = Internacionalization::load_string("interface/optionsMenu/windowedMode.png");
string path_Swindowed_mode = Internacionalization::load_string("interface/optionsMenu/SwindowedMode.png");
Button *windowmode = new Button(this, "windowmode", path_windowed_mode, path_Swindowed_mode);
// Puts the screen in windowed mode.
windowmode->align_to(this, Object::RIGHT, Object::NONE);
windowmode->set_vertical_position(set_fullscreen->vertical_position() + set_fullscreen->height() + 20);
string path_language_options = Internacionalization::load_string("interface/optionsMenu/language.png");
string path_Slanguage_options = Internacionalization::load_string("interface/optionsMenu/Slanguage.png");
Button *language_options = new Button(this, "language", path_language_options, path_Slanguage_options);
// Puts the screen in windowed mode.
language_options->align_to(this, Object::RIGHT, Object::NONE);
language_options->set_vertical_position(windowmode->vertical_position() + windowmode->height() + 20);
string path_back = Internacionalization::load_string("interface/optionsMenu/back.png");
string path_Sback = Internacionalization::load_string("interface/optionsMenu/Sback.png");
Button *back = new Button(this, "back", path_back, path_Sback);
// Directs to the main menu of the game.
back->align_to(this, Object::RIGHT, Object::NONE);
back->set_vertical_position(language_options->vertical_position() + language_options->height() + 20);
set_fullscreen->add_observer(this);
windowmode->add_observer(this);
back->add_observer(this);
language_options->add_observer(this);
add_child(set_fullscreen);
add_child(windowmode);
add_child(back);
add_child(language_options);
}
Options::~Options()
{
}
void Options::draw_self()// Drow options pinctures on the screen.
{
Environment *env = Environment::get_instance();// It is an object of the class environment. Is a pointer to the current instance of the game environment.
env->canvas->clear(Color::WHITE);
string path_option_menu = Internacionalization::load_string("interface/optionsMenu/optionsMenu.png");
shared_ptr<Texture> image = env->resources_manager->get_texture(path_option_menu);
env->canvas->draw(image.get(), 1, 0);
}
bool Options::on_message(Object *object, MessageID id, Parameters)// Let the dynamic buttons.
{
Environment *env = Environment::get_instance();// It is an object of the class environment. Is a pointer to the current instance of the game environment.
Button *button = dynamic_cast<Button *>(object);
env->sfx->play("res/sounds/navegacaomenu.wav", 1);
if (id != Button::clickedID)
{
return false;
}
if (not button)
{
return false;
}
if(button->id() == "fullscreen" || button->id() == "windowmode" || button->id() == "back")
env->sfx->play("res/sounds/navegacaomenu.wav",1);
if (button->id() == "fullscreen")
{
env->video->set_fullscreen();
set_next(SevenKeys::ScreenType::OPTIONS);
}
else if (button->id() == "windowmode")
{
env->video->set_fullscreen(false);
set_next(SevenKeys::ScreenType::OPTIONS);
}
else if (button->id() == "language")
{
set_next("language_options");
}
else if (button->id() == "back")
{
set_next(SevenKeys::ScreenType::MAIN_SCREEN);
}
finish();
return true;
}
| 38.95122 | 157 | 0.713212 | eliseuegewarth |
646196d8165d1709d1abeb6227ea4bde32c737ae | 193 | hpp | C++ | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | #define CRB_CIVILIANS
//#define CRB_DOGS
//#define CRB_EMERGENCY
//#define CRB_SHEPHERDS
//#define RMM_CTP
#define TUP_AIRTRAFFIC
#define TUP_SEATRAFFIC
//#define CRB_DESTROYCITY
//#define AEG
| 19.3 | 25 | 0.797927 | amlr |
6462b05d02741f58aa4986cbd534e071369dd649 | 273 | cpp | C++ | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | /*!
* \file
* \details This file is part of https://github.com/kurogit/arduino_pong which is licensed under the MIT License.
* \copyright 2016 Patrick Schwartz <kurogit@schwartzm.com>
*/
#include "GameState.hpp"
namespace arduino_pong
{
} // namespace arduino_pong
| 21 | 113 | 0.736264 | kurogit |
6464b097ed539aee40ed03c54e99a25489c2ad72 | 30 | cpp | C++ | paperfilter/linux/pcap.cpp | sbilly/dripcap | 895af8cc8f2a0b1881df73f0a1df19f78c1c47d7 | [
"MIT"
] | 3 | 2020-05-06T17:56:21.000Z | 2021-07-24T13:59:28.000Z | paperfilter/linux/pcap.cpp | sbilly/dripcap | 895af8cc8f2a0b1881df73f0a1df19f78c1c47d7 | [
"MIT"
] | null | null | null | paperfilter/linux/pcap.cpp | sbilly/dripcap | 895af8cc8f2a0b1881df73f0a1df19f78c1c47d7 | [
"MIT"
] | null | null | null | #include "../darwin/pcap.cpp"
| 15 | 29 | 0.666667 | sbilly |
6464e022c5a30b5196fc8c2be3e0dd0233c0bb3a | 3,394 | cpp | C++ | sketches/ledmatrix/ledmatrix.cpp | ubirch/ubirch-thgs | 29614c85f752ca7393169f1ce0e4ff71649675e6 | [
"Apache-2.0"
] | null | null | null | sketches/ledmatrix/ledmatrix.cpp | ubirch/ubirch-thgs | 29614c85f752ca7393169f1ce0e4ff71649675e6 | [
"Apache-2.0"
] | null | null | null | sketches/ledmatrix/ledmatrix.cpp | ubirch/ubirch-thgs | 29614c85f752ca7393169f1ce0e4ff71649675e6 | [
"Apache-2.0"
] | null | null | null | /***************************************************
This is a library for our I2C LED Backpacks
Designed specifically to work with the Adafruit LED Matrix backpacks
----> http://www.adafruit.com/products/872
----> http://www.adafruit.com/products/871
----> http://www.adafruit.com/products/870
These displays use I2C to communicate, 2 pins are required to
interface. There are multiple selectable I2C addresses. For backpacks
with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
with 3 Address Select pins: 0x70 thru 0x77
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Wire.h>
#include <Adafruit_LEDBackpack.h>
#ifndef BAUD
# define BAUD 9600
#endif
Adafruit_8x8matrix matrix = Adafruit_8x8matrix();
void setup() {
Serial.begin(BAUD);
Serial.println("8x8 LED Matrix Test");
matrix.begin(0x70); // pass in the address
}
static const uint8_t PROGMEM
cross_bmp[] =
{ B00000000,
B00000000,
B00111100,
B00000100,
B00000100,
B00000100,
B00000000,
B00000000 },
neutral_bmp[] =
{ B00111100,
B01000010,
B10100101,
B10000001,
B10111101,
B10000001,
B01000010,
B00111100 },
frown_bmp[] =
{ B00111100,
B01000010,
B10100101,
B10000001,
B10011001,
B10100101,
B01000010,
B00111100 };
void loop() {
matrix.clear();
matrix.drawBitmap(0, 0, cross_bmp, 8, 8, LED_ON);
matrix.writeDisplay();
delay(500);
matrix.clear();
matrix.drawBitmap(0, 0, neutral_bmp, 8, 8, LED_ON);
matrix.writeDisplay();
delay(500);
matrix.clear();
matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_ON);
matrix.writeDisplay();
delay(500);
matrix.clear(); // clear display
matrix.drawPixel(0, 0, LED_ON);
matrix.writeDisplay(); // write the changes we just made to the display
delay(500);
matrix.clear();
matrix.drawLine(0,0, 7,7, LED_ON);
matrix.writeDisplay(); // write the changes we just made to the display
delay(500);
matrix.clear();
matrix.drawRect(0,0, 8,8, LED_ON);
matrix.fillRect(2,2, 4,4, LED_ON);
matrix.writeDisplay(); // write the changes we just made to the display
delay(500);
matrix.clear();
matrix.drawCircle(3,3, 3, LED_ON);
matrix.writeDisplay(); // write the changes we just made to the display
delay(500);
matrix.setTextSize(1);
matrix.setTextWrap(false); // we dont want text to wrap so it scrolls nicely
matrix.setTextColor(LED_ON);
for (int8_t x=0; x>=-36; x--) {
matrix.clear();
matrix.setCursor(x,0);
matrix.print("ubirch");
matrix.writeDisplay();
delay(100);
}
matrix.setRotation(3);
for (int8_t x=7; x>=-36; x--) {
matrix.clear();
matrix.setCursor(x,0);
matrix.print("#1");
matrix.writeDisplay();
delay(100);
}
matrix.setRotation(0);
}
| 27.370968 | 81 | 0.598998 | ubirch |
64696e459790dd965d8067ab8d08da4aa89d3bfc | 5,802 | hpp | C++ | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/external.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/external.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/external.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*****************************************************************************
* external.hpp : Dialogs from other LibVLC core and other plugins
****************************************************************************
* Copyright (C) 2009 Rémi Denis-Courmont
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef QVLC_DIALOGS_EXTERNAL_H_
#define QVLC_DIALOGS_EXTERNAL_H_ 1
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <QObject>
#include <QDialog>
#include <QMap>
#include <vlc_common.h>
#include <vlc_dialog.h>
#include "adapters/variables.hpp"
struct intf_thread_t;
class QProgressDialog;
class DialogWrapper;
class DialogHandler : public QObject
{
Q_OBJECT
public:
DialogHandler (intf_thread_t *, QObject *parent);
virtual ~DialogHandler();
void removeDialogId(vlc_dialog_id *p_id);
signals:
void errorDisplayed(const QString &title, const QString &text);
void loginDisplayed(vlc_dialog_id *p_id, const QString &title,
const QString &text, const QString &defaultUsername,
bool b_ask_store);
void questionDisplayed(vlc_dialog_id *p_id, const QString &title,
const QString &text, int i_type,
const QString &cancel, const QString &action1,
const QString &action2);
void progressDisplayed(vlc_dialog_id *p_id, const QString &title,
const QString &text, bool b_indeterminate,
float f_position, const QString &cancel);
void cancelled(vlc_dialog_id *p_id);
void progressUpdated(vlc_dialog_id *p_id, float f_value, const QString &text);
private slots:
void displayError(const QString &title, const QString &text);
void displayLogin(vlc_dialog_id *p_id, const QString &title,
const QString &text, const QString &defaultUsername,
bool b_ask_store);
void displayQuestion(vlc_dialog_id *p_id, const QString &title,
const QString &text, int i_type,
const QString &cancel, const QString &action1,
const QString &action2);
void displayProgress(vlc_dialog_id *p_id, const QString &title,
const QString &text, bool b_indeterminate,
float f_position, const QString &cancel);
void cancel(vlc_dialog_id *p_id);
void updateProgress(vlc_dialog_id *p_id, float f_value, const QString &text);
private:
intf_thread_t *p_intf;
static void displayErrorCb(void *, const char *, const char *);
static void displayLoginCb(void *, vlc_dialog_id *, const char *,
const char *, const char *, bool);
static void displayQuestionCb(void *, vlc_dialog_id *, const char *,
const char *, vlc_dialog_question_type,
const char *, const char *, const char *);
static void displayProgressCb(void *, vlc_dialog_id *, const char *,
const char *, bool, float, const char *);
static void cancelCb(void *, vlc_dialog_id *);
static void updateProgressCb(void *, vlc_dialog_id *, float, const char *);
};
class DialogWrapper : public QObject
{
Q_OBJECT
friend class DialogHandler;
public:
DialogWrapper(DialogHandler *p_handler, intf_thread_t *p_intf,
vlc_dialog_id *p_id, QDialog *p_dialog);
virtual ~DialogWrapper();
protected slots:
virtual void finish(int result = QDialog::Rejected);
protected:
DialogHandler *p_handler;
intf_thread_t *p_intf;
vlc_dialog_id *p_id;
QDialog *p_dialog;
};
class QLineEdit;
class QCheckBox;
class LoginDialogWrapper : public DialogWrapper
{
Q_OBJECT
public:
LoginDialogWrapper(DialogHandler *p_handler, intf_thread_t *p_intf,
vlc_dialog_id *p_id, QDialog *p_dialog,
QLineEdit *userLine, QLineEdit *passLine,
QCheckBox *checkbox);
private slots:
virtual void accept();
private:
QLineEdit *userLine;
QLineEdit *passLine;
QCheckBox *checkbox;
};
class QAbstractButton;
class QMessageBox;
class QuestionDialogWrapper : public DialogWrapper
{
Q_OBJECT
public:
QuestionDialogWrapper(DialogHandler *p_handler, intf_thread_t *p_intf,
vlc_dialog_id *p_id, QMessageBox *p_box,
QAbstractButton *action1, QAbstractButton *action2);
private slots:
virtual void buttonClicked(QAbstractButton *);
private:
QAbstractButton *action1;
QAbstractButton *action2;
};
class ProgressDialogWrapper : public DialogWrapper
{
Q_OBJECT
public:
ProgressDialogWrapper(DialogHandler *p_handler, intf_thread_t *p_intf,
vlc_dialog_id *p_id, QProgressDialog *p_progress,
bool b_indeterminate);
void updateProgress(float f_position, const QString &text);
private:
bool b_indeterminate;
};
#endif
| 36.721519 | 82 | 0.639262 | Brook1711 |
646d6d10348f8a09d15ebef2da303b1a7b5d2277 | 40,174 | cpp | C++ | src/Cello/test_CelloArray.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 26 | 2019-02-12T19:39:13.000Z | 2022-03-31T01:52:29.000Z | src/Cello/test_CelloArray.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 128 | 2019-02-13T20:22:30.000Z | 2022-03-29T20:21:00.000Z | src/Cello/test_CelloArray.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 29 | 2019-02-12T19:37:51.000Z | 2022-03-14T14:02:45.000Z | // See LICENSE_CELLO file for license and copyright information
/// @file test_CelloArray.cpp
/// @author Matthew Abruzzo (matthewabruzzo@gmail.com)
/// @date 2020-06-09
/// @brief Test program for the CelloArray class template
///
/// The main testing strategy here is to test some of the core functionallity
/// of CelloArray with:
/// - SimpleInitializationTests
/// - SimpleAssignmentTests
/// - SizeShapeTests
/// And then use more sophisticated machinery that relies on this
/// functionallity to test the remaining features.
#include <cstdlib>
#include <initializer_list>
#include <vector>
#include "main.hpp"
#include "test.hpp"
#include "array.hpp"
//----------------------------------------------------------------------
template<typename T, std::size_t D>
class MemManagedArrayBuilder{
// This template class is used to build and a manage the lifetime of a
// CelloArray that manages its own memory
//
// In the future it might be a good idea to have this and
// PtrWrapArrayBuilder have a shared base class
public:
template<typename... Args>
MemManagedArrayBuilder(Args... args) : arr_(args...) {}
CelloArray<T,D>* get_arr() { return &arr_; }
T* get_wrapped_ptr() { return NULL; }
static std::string name() { return "MemManagedArrayBuilder"; }
private:
CelloArray<T,D> arr_;
};
//----------------------------------------------------------------------
template<typename T, std::size_t D>
class PtrWrapArrayBuilder{
// This template class is used to build and a manage the lifetime of a
// CelloArray wraps an existing pointer. This template class also manages the
// lifetime of the underlying pointer.
//
// In the future it might be a good idea to have this and
// MemManagedArrayBuilder have a shared base class
public:
template<typename... Args>
PtrWrapArrayBuilder(Args... args)
: arr_ptr_(nullptr),
ptr_(nullptr)
{
// we are sort of cheating here to compute the required size
CelloArray<T,D> temp(args...);
ptr_ = new T [temp.size()]{};
arr_ptr_ = new CelloArray<T,D>(ptr_,args...);
}
~PtrWrapArrayBuilder() {
delete arr_ptr_;
delete[] ptr_;
}
CelloArray<T,D>* get_arr() {return arr_ptr_;}
T* get_wrapped_ptr() { return ptr_; }
static std::string name() { return "PtrWrapArrayBuilder"; }
private:
CelloArray<T,D>* arr_ptr_;
T* ptr_;
};
//----------------------------------------------------------------------
void pointer_compare_(double vals[], std::vector<double> ref,
std::string func_name, const char* file, int line){
bool all_match = true;
for(std::size_t i = 0; i < ref.size(); i++){
bool match = (ref[i] == vals[i]);
if (!match){
if (all_match){
CkPrintf("\nUnequal Pointer Element Error in %s:\n",
func_name.c_str());
}
CkPrintf("Expected %e at index %lu. Got: %e\n", ref[i], i, vals[i]);
all_match = false;
}
}
Unit::instance()->assertion(all_match, file, line, true);
}
//----------------------------------------------------------------------
void compare_against_arr_(CelloArray<double, 2> &arr2d,
std::vector<double> ref,
std::string func_name,
const char* file, int line){
int my = arr2d.shape(0);
int mx = arr2d.shape(1);
bool all_match = true;
for(int iy=0; iy<my; iy++){
for(int ix=0; ix<mx; ix++){
int index = ix + mx*iy;
bool match = (arr2d(iy,ix) == ref[index]);
if (!match){
if (all_match){
CkPrintf("\nUnequal Array Element Error in %s:\n",
func_name.c_str());
}
all_match = false;
CkPrintf("Expected %e at (%d, %d). Got: %e\n",
ref[index], iy, ix, arr2d(iy,ix));
}
}
}
Unit::instance()->assertion(all_match, file, line, true);
}
//----------------------------------------------------------------------
template<typename Builder>
void compare_builder_arr_(Builder &builder, std::vector<double> ref,
std::string func_name,
const char* file, int line){
compare_against_arr_(*builder.get_arr(), ref, func_name, file, line);
if (builder.get_wrapped_ptr() != nullptr){
pointer_compare_(builder.get_wrapped_ptr(), ref, func_name, file, line);
}
}
//----------------------------------------------------------------------
#define check_pointer_vals(VALS, REF, FUNC_NAME) \
pointer_compare_(VALS, REF, FUNC_NAME, __FILE__, __LINE__);
#define check_arr_vals(VALS, REF, FUNC_NAME) \
compare_against_arr_(VALS, REF, FUNC_NAME, __FILE__, __LINE__);
#define check_builder_arr(BUILDER, REF, FUNC_NAME) \
compare_builder_arr_(BUILDER, REF, FUNC_NAME, __FILE__, __LINE__);
//----------------------------------------------------------------------
class SimpleInitializationTests{
// This class holds tests used to check the simple initialization of
// CelloArray. Unfortunately, it is not really possible to completely
// disentangle the following set of features and test them completely
// independently of each other:
// 1. direct initialization of an instance that wraps an existing pointer
// 2. direct initialization of an instance which manages its own data
// 3. retrieval operations
public:
void test_init_simple_managed_memory(){
// all values are assumed to be zero-initialized
std::string template_message_str =
("There is an issue in either the constructor for instance of %dD "
"CelloArrays that manage own memory, or in CelloArray::operator()");
const char *template_message = template_message_str.c_str();
CelloArray<double, 1> arr1D(8);
for (int i = 0; i<8; i++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
1, arr1D(i) == 0);
}
CelloArray<double, 2> arr2D(2,4);
for (int i = 0; i<2; i++){
for (int j = 0; j<4; j++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
2, arr2D(i,j) == 0);
}
}
CelloArray<double, 3> arr3D(2,3,4);
for (int i = 0; i<2; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<4; k++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
3, arr3D(i,j,k) == 0);
}
}
}
CelloArray<double, 4> arr4D(2,3,4,5);
for (int i = 0; i<2; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<4; k++){
for (int l = 0; l<5; l++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
4, arr4D(i,j,k,l) == 0);
}
}
}
}
}
void test_init_simple_wrapped_pointer(){
// all values are assumed to be zero-initialized
std::string template_message_str =
("There is an issue in either the constructor for instance of %dD "
"CelloArrays that wraps a pointer, or in CelloArray::operator()");
const char *template_message = template_message_str.c_str();
double zero_values[120] = { };
double* ptr = &(zero_values[0]);
CelloArray<double, 1> arr1D(ptr, 8);
for (int i = 0; i<8; i++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
1, arr1D(i) == 0);
}
CelloArray<double, 2> arr2D(ptr,2,4);
for (int i = 0; i<2; i++){
for (int j = 0; j<4; j++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
2, arr2D(i,j) == 0);
}
}
CelloArray<double, 3> arr3D(ptr,2,3,4);
for (int i = 0; i<2; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<4; k++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
3, arr3D(i,j,k) == 0);
}
}
}
CelloArray<double, 4> arr4D(ptr,2,3,4,5);
for (int i = 0; i<2; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<4; k++){
for (int l = 0; l<5; l++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
4, arr4D(i,j,k,l) == 0);
}
}
}
}
}
void test_init_nonzero_wrapped_pointer(){
std::string template_message_str =
("There is an issue in either the constructor for instance of %dD "
"CelloArrays that wraps a pointer, or in CelloArray::operator()");
const char *template_message = template_message_str.c_str();
double arr_vals[24] = { 0., 1., 2., 3., 4., 5.,
6., 7., 8., 9., 10., 11.,
12., 13., 14., 15., 16., 17.,
18., 19., 20., 21., 22., 23.};
double* ptr = &(arr_vals[0]);
CelloArray<double, 1> arr1D(ptr, 13);
for (int i = 0; i<13; i++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
1, arr1D(i) == arr_vals[i]);
}
CelloArray<double, 2> arr2D(ptr,3,5);
for (int i = 0; i<3; i++){
for (int j = 0; j<5; j++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
2, arr2D(i,j) == arr_vals[j+i*5]);
}
}
CelloArray<double, 3> arr3D(ptr,2,3,4);
for (int i = 0; i<2; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<4; k++){
ASSERT1("IrreducibleTests::test_managed_memory", template_message,
3, arr3D(i,j,k) == arr_vals[k+4*(j+3*i)]);
}
}
}
}
void run_tests(){
test_init_simple_managed_memory();
// it is not possible to initialize a non-zero pointer
test_init_simple_wrapped_pointer();
test_init_nonzero_wrapped_pointer();
}
};
//----------------------------------------------------------------------
class SimpleElementAssignmentTests{
// Used to test whether individual element assignments actually work
private:
std::string get_assignment_template_msg_(bool wrapped_pointer){
std::string template_message_str;
if (wrapped_pointer){
template_message_str =
("There is an issue with operator() for instances of %dD CelloArrays "
"that own their own memory");
} else {
template_message_str =
("There is an issue with operator() for instances of %dD CelloArrays "
"that wrap existing pointers");
}
return template_message_str;
}
void test_assignment_1D_(unsigned int seed, double *wrapped_pointer,
CelloArray<double, 1> &arr1D, int length)
{
std::string template_message_str =
get_assignment_template_msg_(wrapped_pointer != NULL);
const char *template_message = template_message_str.c_str();
int npasses = 2;
if (wrapped_pointer != NULL) { npasses++;}
for (int t = 0; t<npasses; t++){
std::srand(seed);
for (int i = 0; i<8; i++){
double val = ((double)std::rand()/RAND_MAX);
if (t == 0){
arr1D(i) = val;
} else if (t == 1){
ASSERT1("IrreducibleTests::test_assignment_managed_memory",
template_message, 1, arr1D(i) == val);
} else {
ASSERT1("IrreducibleTests::test_assignment_managed_memory",
"The wrapped pointer of a 1D CelloArray is not updated",
1, wrapped_pointer[i] == val);
}
}
}
}
void test_assignment_3D_(unsigned int seed, double *wrapped_pointer,
CelloArray<double, 3> &arr3D, int mz, int my,
int mx)
{
std::string template_message_str =
get_assignment_template_msg_(wrapped_pointer != NULL);
const char *template_message = template_message_str.c_str();
int npasses = 2;
if (wrapped_pointer != NULL) { npasses++;}
for (int t = 0; t<npasses; t++){
std::srand(seed);
for (int iz = 0; iz<mz; iz++){
for (int iy = 0; iy<my; iy++){
for (int ix = 0; ix<mx; ix++){
double val = ((double)std::rand()/RAND_MAX);
if (t == 0){
arr3D(iz,iy,ix) = val;
} else if (t == 1){
ASSERT1("IrreducibleTests::test_assignment_3D_",
template_message, 3, arr3D(iz,iy,ix) == val);
} else {
ASSERT("IrreducibleTests::test_assignment_3D_",
"The wrapped pointer of a 3D CelloArray has not been "
"appropriately updated",
wrapped_pointer[ix+mx*(iy+my*iz)] == val);
}
}
}
}
}
}
void test_assignment_4D_(unsigned int seed, double *wrapped_pointer,
CelloArray<double, 4> &arr4D, int mz, int my,
int mx, int mw)
{
std::string template_message_str =
get_assignment_template_msg_(wrapped_pointer != NULL);
const char *template_message = template_message_str.c_str();
int npasses = 2;
if (wrapped_pointer != NULL) { npasses++;}
for (int t = 0; t<npasses; t++){
std::srand(seed);
for (int iz = 0; iz<mz; iz++){
for (int iy = 0; iy<my; iy++){
for (int ix = 0; ix<mx; ix++){
for (int iw = 0; iw<mw; iw++){
double val = ((double)std::rand()/RAND_MAX);
if (t == 0){
arr4D(iz,iy,ix,iw) = val;
} else if (t == 1){
ASSERT1("IrreducibleTests::test_assignment_4D_",
template_message, 4, arr4D(iz,iy,ix,iw) == val);
} else {
ASSERT("IrreducibleTests::test_assignment_4D_",
"The wrapped pointer of a 4D CelloArray has not been "
"appropriately updated",
wrapped_pointer[iw+mw*(ix+mx*(iy+my*iz))] == val);
}
}
}
}
}
}
}
void test_assignment_managed_memory(){
unsigned int seed = 5342342;
CelloArray<double, 1> arr1D(8);
test_assignment_1D_(seed, NULL, arr1D, 8);
CelloArray<double, 3> arr3D(2,3,4);
test_assignment_3D_(seed, NULL, arr3D, 2,3,4);
CelloArray<double, 4> arr4D(2,3,4,5);
test_assignment_4D_(seed, NULL, arr4D, 2,3,4,5);
}
void test_assignment_wrapped_ptr(){
unsigned int seed = 5342342;
double *ptr;
double temp_arr1[120] = {};
ptr = &(temp_arr1[0]);
CelloArray<double, 1> arr1D(ptr,8);
test_assignment_1D_(seed, ptr, arr1D, 8);
double temp_arr3[120] = {};
ptr = &(temp_arr3[0]);
CelloArray<double, 3> arr3D(ptr,2,3,4);
test_assignment_3D_(seed, ptr, arr3D, 2,3,4);
double temp_arr4[120] = {};
ptr = &(temp_arr4[0]);
CelloArray<double, 4> arr4D(ptr,2,3,4,5);
test_assignment_4D_(seed, ptr, arr4D, 2,3,4,5);
}
public:
void run_tests(){
test_assignment_managed_memory();
test_assignment_wrapped_ptr();
}
};
//----------------------------------------------------------------------
class SizeShapeTests{
// Used to test the size and shape methods of CelloArray
private:
template<std::size_t D>
void check_expected_size_shape_(CelloArray<double, D> &arr,
std::initializer_list<int> expect_shape){
static_assert(D>0, "D must always be positive.");
ASSERT("SizeShapeTests::check_expected_size_shape_",
"the length of the expect_shape initializer_list is wrong",
expect_shape.size() == D);
std::size_t axis_ind = 0;
std::size_t cur_size = 1;
for (const int axis_length : expect_shape){
ASSERT("SizeShapeTests::check_expected_size_shape_",
("the expect_shape initializer_list should only include positive "
"values"), axis_length > 0);
ASSERT3("SizeShapeTests::check_expected_size_shape_",
"the length along axis %d was %d. It should be %d.",
(int)axis_ind, arr.shape(axis_ind), axis_length,
((int)arr.shape(axis_ind)) == ((int)axis_length));
cur_size *= (std::size_t)axis_length;
axis_ind++;
}
ASSERT("SizeShapeTests::check_expected_size_shape_",
"did not get the expected result for size",
(std::size_t)arr.size() == (std::size_t)cur_size);
}
void test_size_shape_1D_(double* ptr, int length){
if (ptr != NULL){
CelloArray<double, 1> arr(ptr,length);
check_expected_size_shape_(arr,{length});
} else {
CelloArray<double, 1> arr(length);
check_expected_size_shape_(arr,{length});
}
}
void test_size_shape_2D_(double* ptr, int my, int mx){
if (ptr != NULL){
CelloArray<double, 2> arr(ptr,my,mx);
check_expected_size_shape_(arr,{my,mx});
} else {
CelloArray<double, 2> arr(my,mx);
check_expected_size_shape_(arr,{my,mx});
}
}
void test_size_shape_3D_(double* ptr, int mz, int my, int mx){
if (ptr != NULL){
CelloArray<double, 3> arr(ptr,mz,my,mx);
check_expected_size_shape_(arr,{mz,my,mx});
} else {
CelloArray<double, 3> arr(mz,my,mx);
check_expected_size_shape_(arr,{mz,my,mx});
}
}
void test_size_shape_4D_(double* ptr, int mz, int my, int mx, int mw){
if (ptr != NULL){
CelloArray<double, 4> arr(ptr,mz,my,mx,mw);
check_expected_size_shape_(arr,{mz,my,mx,mw});
} else {
CelloArray<double, 4> arr(mz,my,mx,mw);
check_expected_size_shape_(arr,{mz,my,mx,mw});
}
}
void test_size_shape_5D_(double* ptr, int mz, int my, int mx, int mw, int mv){
if (ptr != NULL){
CelloArray<double, 5> arr(ptr,mz,my,mx,mw,mv);
check_expected_size_shape_(arr,{mz,my,mx,mw,mv});
} else {
CelloArray<double, 5> arr(mz,my,mx,mw,mv);
check_expected_size_shape_(arr,{mz,my,mx,mw,mv});
}
}
void test_size_shape_managed_(bool wrapped){
double carray[750] = { };
double *ptr = (wrapped) ? &(carray[0]) : NULL;
test_size_shape_1D_(ptr, 1);
test_size_shape_1D_(ptr, 24);
test_size_shape_2D_(ptr, 1, 1);
test_size_shape_2D_(ptr, 24, 1);
test_size_shape_2D_(ptr, 1, 24);
test_size_shape_3D_(ptr, 1, 1, 1);
test_size_shape_3D_(ptr, 24, 1, 1);
test_size_shape_3D_(ptr, 1, 58, 1);
test_size_shape_3D_(ptr, 1, 1, 7);
test_size_shape_3D_(ptr, 83, 5, 1);
test_size_shape_3D_(ptr, 26, 1, 15);
test_size_shape_3D_(ptr, 1, 42, 11);
test_size_shape_3D_(ptr, 2, 3, 4);
test_size_shape_4D_(ptr, 1, 1, 1, 1);
test_size_shape_4D_(ptr, 2, 3, 4, 5);
test_size_shape_5D_(ptr, 1, 1, 1, 1, 6);
test_size_shape_5D_(ptr, 2, 3, 4, 5, 6);
}
public:
void run_tests(){
test_size_shape_managed_(false);
test_size_shape_managed_(true);
}
};
//----------------------------------------------------------------------
class VariableAssignmentTests{
// these are tests that check that check the assignments of arrays to
// variables.
template<template<typename, std::size_t> class Builder>
void test_assignment_(){
// vector used to hold expected results (the contents of this vector will
// be updated throughout this test
std::vector<double> expected;
// construct vectors that hold pointers to shared copies of the tested
// array to simplify the code required to makes sure that all of the
// instances reflect the fact that they are shared copies
std::vector<CelloArray<double, 2>*> array_ptr_vec;
// vectors holding pointers to c-style arrays that at one time or another
// were wrapped by a CelloArray
std::vector<double*> wrapped_ptr_vec;
// holds pointers to vectors containing the expected values that should be
// held by each pointer that was wrapped at one time or another
std::vector<std::vector<double>*> expected_wrapped_ptr_vals;
// define a lambda function to actually carry out the checks on the
// for the expected array values
auto check_shared_copy_ = [&expected, &array_ptr_vec,
&wrapped_ptr_vec, &expected_wrapped_ptr_vals]()
{
for (CelloArray<double,2>* cur_arr_ptr : array_ptr_vec){
check_arr_vals(*cur_arr_ptr, expected,
"VariableAssignmentTests::test_assignment_");
}
for (std::size_t i =0; i<wrapped_ptr_vec.size(); i++){
check_pointer_vals(wrapped_ptr_vec[i],
*(expected_wrapped_ptr_vals[i]),
"VariableAssignmentTests::test_assignment_");
}
};
// now let's set up the initial instance of CelloArray and initialize it
Builder<double, 2> builder(2,3);
CelloArray<double, 2> *arr_ptr = builder.get_arr();
(*arr_ptr)(0,2) = 97.25;
expected.assign({0, 0, 97.25,
0, 0, 0});
// register it in array_ptr_vec and the wrapped array (if applicable) in
// wrapped_ptr_vec
array_ptr_vec.push_back(arr_ptr);
if (builder.get_wrapped_ptr() != nullptr){
wrapped_ptr_vec.push_back(builder.get_wrapped_ptr());
expected_wrapped_ptr_vals.push_back(&expected);
}
// sanity check to confirm that all values are what we would expect
check_shared_copy_();
// Basically, this test consists of defining a collection of variables
// holding CelloArrays that are each defined in a different way. The
// variable is then assigned a shallow copy of the original array
// Then the contents of the underlying values are modified and the contents
// of all shallow copies are checked to make sure they are accurate
// First, consider an initially default-initialized variable
CelloArray<double, 2> second_var; // this is default constructed
// assign the array pointed to by arr_ptr to second_var
second_var = *arr_ptr;
array_ptr_vec.push_back(&second_var);
// confirm that the copy worked
//print_array(second_var);
check_shared_copy_();
// check that they are all actually shallow copies
second_var(0,1) = 4324.5;
(*arr_ptr)(1,0) = -1;
expected.assign({ 0, 4324.5, 97.25,
-1, 0., 0.});
// confirm that the copy worked
check_shared_copy_();
// Next, consider an initially defined array with the same shape
CelloArray<double,2> third_var(2,3);
third_var(1,2) = 42657.5;
// now actually assign the value
third_var = second_var;
array_ptr_vec.push_back(&third_var);
check_shared_copy_();
third_var(1,2) = -43.75;
second_var(0,2) = 1500.;
expected.assign({ 0, 4324.5, 1500.,
-1, 0., -43.75});
// confirm that the copy worked
check_shared_copy_();
// Next, consider an initially defined array with a different shape
CelloArray<double,2> fourth_var(100,53);
fourth_var = third_var;
array_ptr_vec.push_back(&fourth_var);
check_shared_copy_();
third_var(1,1) = 12;
expected.assign({ 0, 4324.5, 1500.,
-1, 12., -43.75});
check_shared_copy_();
// Next, consider an initially defined array that wraps a pointer
double dummy_carray[6] = {0., 1., 2., 3., 4., 5.};
double* dummy_wrapped_ptr = &(dummy_carray[0]);
std::vector<double> expected_dummy_carray_vals(dummy_wrapped_ptr,
dummy_wrapped_ptr + 6);
// sanity check
CelloArray<double,2> fifth_var(dummy_wrapped_ptr, 2,3);
array_ptr_vec.push_back(&fifth_var);
wrapped_ptr_vec.push_back(dummy_wrapped_ptr);
expected_wrapped_ptr_vals.push_back(&expected_dummy_carray_vals);
fifth_var = *arr_ptr;
// make sure that all values are expected!
check_shared_copy_();
// make sure that all shallow copies remain consistent after modification
second_var(0,0) = -546734;
expected.assign({ -546734, 4324.5, 1500.,
-1, 12., -43.75});
check_shared_copy_();
// finally make sure that modifications to the wrapped vector doesn't
// change values in each of the shallow copies of the original array
dummy_carray[3] = 526;
expected_dummy_carray_vals[3] = 526;
check_shared_copy_();
// Things that could still be checked:
// 1. What happens when we deallocate an array (whether it's the root one
// or not)? [for the root copy case, when the array wraps an existing
// pointer, it would be interesting to ensure that the underlying
// pointer is modified]
// 2. What happens when we assign an array to another array (similar to
// deallocation questions)
// 3. What happens when we assign an existing shallow copy equal to another
// shallow copy of the same underlying array?
}
template<template<typename, std::size_t> class Builder1,
template<typename, std::size_t> class Builder2>
void test_deepcopy_assignment_(){
std::string func_name =
("VariableAssignmentTests::test_deepcopy_assignment_<" +
Builder1<double, 2>::name() + "," +
Builder2<double, 2>::name() + ">");
Builder1<double, 2> builder_a(2,3);
CelloArray<double, 2> *arr_ptr_a = builder_a.get_arr();
(*arr_ptr_a)(0,2) = 97.25;
Builder2<double, 2> builder_b(4,4);
CelloArray<double, 2> *arr_ptr_b = builder_b.get_arr();
(*arr_ptr_b)(1,1) = 15;
*arr_ptr_a = arr_ptr_b->deepcopy();
(*arr_ptr_a)(2,3) = -42;
(*arr_ptr_b)(3,2) = 42;
check_arr_vals(*arr_ptr_a, std::vector<double>({0, 0, 0, 0,
0, 15, 0, 0,
0, 0, 0, -42,
0, 0, 0, 0}),
func_name);
if (builder_a.get_wrapped_ptr() != nullptr){
check_pointer_vals(builder_a.get_wrapped_ptr(),
std::vector<double>({0,0,97.25, 0, 0, 0}),
func_name);
}
check_builder_arr(builder_b,
std::vector<double>({0, 0, 0, 0,
0, 15, 0, 0,
0, 0, 0, 0,
0, 0, 42, 0}), func_name);
}
public:
void run_tests(){
test_assignment_<MemManagedArrayBuilder>();
test_assignment_<PtrWrapArrayBuilder>();
test_deepcopy_assignment_<MemManagedArrayBuilder, PtrWrapArrayBuilder>();
test_deepcopy_assignment_< PtrWrapArrayBuilder,MemManagedArrayBuilder>();
test_deepcopy_assignment_<MemManagedArrayBuilder,MemManagedArrayBuilder>();
test_deepcopy_assignment_< PtrWrapArrayBuilder, PtrWrapArrayBuilder>();
}
};
//----------------------------------------------------------------------
class BulkAssignmentTest{
// this is inspired by some tests that indicated that there were problems
// with the bulk assignment machinery
public:
template<template<typename, std::size_t> class Builder>
void test_assign_from_scalar_(){
std::string func_name = "BulkAssignmentTest::test_assign_from_scalar_";
Builder<double, 2> builder(2,3);
CelloArray<double, 2> *arr_ptr = builder.get_arr();
(*arr_ptr)(0,2) = 97.25;
(*arr_ptr).subarray() = 57.24;
check_builder_arr(builder, std::vector<double>({57.24, 57.24, 57.24,
57.24, 57.24, 57.24}),
func_name);
(*arr_ptr).subarray(CSlice(0,2), CSlice(0,-1)) = -3;
check_builder_arr(builder, std::vector<double>({-3, -3, 57.24,
-3, -3, 57.24}),
func_name);
CelloArray<double, 2> subarray = arr_ptr->subarray(CSlice(0,2),
CSlice(1,3));
subarray.subarray() = 15;
check_arr_vals(subarray, std::vector<double>({15,15,15,15}), func_name);
check_builder_arr(builder, std::vector<double>({-3, 15, 15,
-3, 15, 15}), func_name);
}
template<template<typename, std::size_t> class Builder1,
template<typename, std::size_t> class Builder2>
void test_assign_from_array_(){
std::string func_name =
("BulkAssignmentTest::test_assign_from_array_<" +
Builder1<double, 2>::name() + "," +
Builder2<double, 2>::name() + ">");
Builder1<double, 2> builder_1(2,3);
CelloArray<double, 2> *arr_ptr_a = builder_1.get_arr();
(*arr_ptr_a)(0,2) = 97.25;
Builder2<double, 2> builder_2a(2,3);
CelloArray<double, 2> *arr_ptr_2a = builder_2a.get_arr();
Builder2<double, 2> builder_2b(2,3);
CelloArray<double, 2> *arr_ptr_2b = builder_2b.get_arr();
double val_2a = 0;
double val_2b = -1;
for (int iy = 0; iy<2; iy++){
for (int ix = 0; ix <3; ix++){
(*arr_ptr_2a)(iy,ix) = val_2a;
(*arr_ptr_2b)(iy,ix) = val_2b;
val_2a++;
val_2b--;
}
}
// sanity checks!
check_builder_arr(builder_2a, std::vector<double>({0, 1, 2,
3, 4, 5}), func_name);
check_builder_arr(builder_2b, std::vector<double>({-1, -2, -3,
-4, -5, -6}),
func_name);
// now lets try an assignment of a full array
(*arr_ptr_a).subarray() = *arr_ptr_2a;
(*arr_ptr_a)(1,1)= -36;
check_builder_arr(builder_1, std::vector<double>({0, 1, 2,
3, -36, 5}), func_name);
// make sure array_2a is unaffected
check_builder_arr(builder_2a, std::vector<double>({0, 1, 2,
3, 4, 5}), func_name);
// now lets try another assignment
(*arr_ptr_a).subarray() = *arr_ptr_2b;
(*arr_ptr_a)(0,0)= 5;
check_builder_arr(builder_1, std::vector<double>({ 5, -2, -3,
-4, -5, -6}), func_name);
// make sure array_2a is unaffected
check_builder_arr(builder_2b, std::vector<double>({-1, -2, -3,
-4, -5, -6}),
func_name);
}
template<template<typename, std::size_t> class Builder1,
template<typename, std::size_t> class Builder2>
void test_assign_subarrays_(){
// These tests actually uncovered a longstanding bug
std::string func_name =
("BulkAssignmentTest::test_assign_subarrays_<" +
Builder1<double, 2>::name() + "," +
Builder2<double, 2>::name() + ">");
Builder1<double, 2> builder_1(4,4);
CelloArray<double, 2> *arr_ptr_a = builder_1.get_arr();
(*arr_ptr_a)(2,2) = 97.25;
CelloArray<double, 2> subarray_1 = arr_ptr_a->subarray(CSlice(1,3),
CSlice(1,3));
subarray_1(0,1) = 5;
// sanity check:
check_arr_vals(subarray_1, std::vector<double>({0, 5,
0, 97.25}), func_name);
check_builder_arr(builder_1, std::vector<double>({0, 0, 0, 0,
0, 0, 5, 0,
0, 0, 97.25, 0,
0, 0, 0, 0}),
func_name);
Builder2<double, 2> builder_2(4,5);
CelloArray<double, 2> *arr_ptr_2 = builder_2.get_arr();
CelloArray<double, 2> subarray_2 = arr_ptr_2->subarray(CSlice(1,3),
CSlice(1,4));
double val_2 = 0;
for (int iy = 0; iy<4; iy++){
for (int ix = 0; ix <5; ix++){
(*arr_ptr_2)(iy,ix) = val_2;
val_2++;
}
}
// sanity check:
check_builder_arr(builder_2, std::vector<double>({ 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19}),
func_name);
check_arr_vals(subarray_2, std::vector<double>({ 6, 7, 8,
11, 12, 13}), func_name);
// NOW TO ACTUALLY PERFORM A TEST
subarray_1.subarray() = subarray_2.subarray(CSlice(0,2),
CSlice(0,2));
check_arr_vals(subarray_1, std::vector<double>({ 6, 7,
11, 12}), func_name);
check_builder_arr(builder_1, std::vector<double>({0, 0, 0, 0,
0, 6, 7, 0,
0, 11, 12, 0,
0, 0, 0, 0}),
func_name);
// extra sanity checks!
subarray_1(0,0) = 97;
check_arr_vals(subarray_1, std::vector<double>({97, 7,
11, 12}), func_name);
check_builder_arr(builder_1, std::vector<double>({0, 0, 0, 0,
0, 97, 7, 0,
0, 11, 12, 0,
0, 0, 0, 0}),
func_name);
check_builder_arr(builder_2, std::vector<double>({ 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19}),
func_name);
check_arr_vals(subarray_2, std::vector<double>({ 6, 7, 8,
11, 12, 13}), func_name);
// SECOND TEST:
subarray_1.subarray(CSlice(0,2),
CSlice(0,2)) = subarray_2.subarray(CSlice(0,2),
CSlice(1,3));
check_arr_vals(subarray_1, std::vector<double>({ 7, 8,
12, 13}), func_name);
check_builder_arr(builder_1, std::vector<double>({0, 0, 0, 0,
0, 7, 8, 0,
0, 12, 13, 0,
0, 0, 0, 0}),
func_name);
}
void run_tests(){
test_assign_from_scalar_<MemManagedArrayBuilder>();
test_assign_from_scalar_<PtrWrapArrayBuilder>();
test_assign_from_array_<MemManagedArrayBuilder, PtrWrapArrayBuilder>();
test_assign_from_array_< PtrWrapArrayBuilder,MemManagedArrayBuilder>();
test_assign_from_array_<MemManagedArrayBuilder,MemManagedArrayBuilder>();
test_assign_from_array_< PtrWrapArrayBuilder, PtrWrapArrayBuilder>();
test_assign_subarrays_<MemManagedArrayBuilder,MemManagedArrayBuilder>();
test_assign_subarrays_<MemManagedArrayBuilder, PtrWrapArrayBuilder>();
test_assign_subarrays_< PtrWrapArrayBuilder,MemManagedArrayBuilder>();
test_assign_subarrays_< PtrWrapArrayBuilder, PtrWrapArrayBuilder>();
}
};
//----------------------------------------------------------------------
class PassByValueTests{
private:
// an array of 0 should be passed to this function
void pass_by_val(CelloArray<double,2> arr,std::string func_name){
// sanity check:
check_arr_vals(arr, std::vector<double>({ 0, 0, 0,
0, 0, 0}), func_name.c_str());
arr(0,1) = 1;
check_arr_vals(arr, std::vector<double>({ 0, 1, 0,
0, 0, 0}), func_name.c_str());
}
public:
template<template<typename, std::size_t> class Builder>
void test_pass_by_val_(){
Builder<double, 2> builder(2,3);
CelloArray<double, 2> *arr_ptr = builder.get_arr();
pass_by_val(*arr_ptr, "PassByValueTests::test_pass_by_val");
check_builder_arr(builder, std::vector<double>({ 0, 1, 0,
0, 0, 0}),
"PassByValueTests::test_pass_by_val");
}
void run_tests(){
test_pass_by_val_<MemManagedArrayBuilder>();
test_pass_by_val_<PtrWrapArrayBuilder>();
}
};
//----------------------------------------------------------------------
class IsAliasTests{
public:
void test_is_alias_independent_ptr_wrapping_(){
PtrWrapArrayBuilder<double, 2> builder(2,3);
CelloArray<double, 2> *arr_ptr = builder.get_arr();
double *ptr = builder.get_wrapped_ptr();
CelloArray<double, 2> array_2(ptr + 3, 1, 3);
ASSERT("IsAliasTests::test_is_alias_independent_ptr_wrapping_",
"The arrays aren't aliases because they only partially overlap.",
!arr_ptr->is_alias(array_2));
CelloArray<double, 2> subarray = arr_ptr->subarray(CSlice(1,2),
CSlice(0,3));
ASSERT("IsAliasTests::test_is_alias_independent_ptr_wrapping_",
("The arrays are aliases even though they were constructed "
"independently from each other"),
subarray.is_alias(array_2));
CelloArray<double, 1> array_3(ptr + 3, 3);
ASSERT("IsAliasTests::test_is_alias_independent_ptr_wrapping_",
("The arrays are not perfect aliases because they have different "
"numbers of dimensions."), !subarray.is_alias(array_3));
}
template<template<typename, std::size_t> class Builder>
void test_is_alias_(){
Builder<double, 2> builder(2,3);
CelloArray<double, 2> *arr_ptr = builder.get_arr();
double data[6] = {0, 0, 0, 0, 0, 0};
CelloArray<double, 2> array_2(data, 2, 3);
ASSERT("IsAliasTests::test_is_alias_", "The arrays aren't aliases.",
!arr_ptr->is_alias(array_2));
CelloArray<double, 2> array_3(2, 3);
ASSERT("IsAliasTests::test_is_alias_", "The arrays aren't aliases.",
!arr_ptr->is_alias(array_3));
CelloArray<double, 2> subarray1 = arr_ptr->subarray(CSlice(0,2),
CSlice(1,3));
CelloArray<double, 2> subarray2 = arr_ptr->subarray(CSlice(0,2),
CSlice(0,2));
ASSERT("IsAliasTests::test_is_alias_",
"The arrays have partial but are not aliases.",
!arr_ptr->is_alias(subarray1));
ASSERT("IsAliasTests::test_is_alias_",
"The arrays have partial but are not aliases.",
!arr_ptr->is_alias(subarray2));
CelloArray<double, 2> subarray1a = subarray1.subarray(CSlice(0,2),
CSlice(0,1));
CelloArray<double, 2> subarray2a = subarray2.subarray(CSlice(0,2),
CSlice(1,2));
ASSERT("IsAliasTests::test_is_alias_", "The arrays are aliases.",
subarray1a.is_alias(subarray2a));
ASSERT("IsAliasTests::test_is_alias_", "The arrays are aliases.",
subarray1a.is_alias(arr_ptr->subarray(CSlice(0,2),
CSlice(1,2)))
);
}
void run_tests(){
test_is_alias_<MemManagedArrayBuilder>();
test_is_alias_<PtrWrapArrayBuilder>();
test_is_alias_independent_ptr_wrapping_();
}
};
//----------------------------------------------------------------------
PARALLEL_MAIN_BEGIN
{
PARALLEL_INIT;
unit_init(0,1);
unit_class("CelloArray");
SimpleInitializationTests init_tests;
init_tests.run_tests();
SimpleElementAssignmentTests element_assign_tests;
element_assign_tests.run_tests();
SizeShapeTests size_shape_tests;
size_shape_tests.run_tests();
VariableAssignmentTests var_assign_tests;
var_assign_tests.run_tests();
BulkAssignmentTest bulk_assignment_tests;
bulk_assignment_tests.run_tests();
PassByValueTests pass_by_val_tests;
pass_by_val_tests.run_tests();
IsAliasTests is_alias_tests;
is_alias_tests.run_tests();
unit_finalize();
exit_();
}
PARALLEL_MAIN_END
| 35.552212 | 80 | 0.559193 | aoife-flood |
646da392d67b6610ae0ac4fffead06487b4f34ba | 660 | cpp | C++ | src/sim_bounds.cpp | cbosoft/BEARS | 9c62df5f4fbb6a2130ea37c925567797b4abfd87 | [
"MIT"
] | null | null | null | src/sim_bounds.cpp | cbosoft/BEARS | 9c62df5f4fbb6a2130ea37c925567797b4abfd87 | [
"MIT"
] | null | null | null | src/sim_bounds.cpp | cbosoft/BEARS | 9c62df5f4fbb6a2130ea37c925567797b4abfd87 | [
"MIT"
] | null | null | null | #include <cmath>
#include "sim.hpp"
// https://en.wikipedia.org/wiki/Periodic_boundary_conditions#Practical_implementation:_continuity_and_the_minimum_image_convention
Vec Sim::enforce_bounds(const Vec &p) const
{
Vec rv;
for (unsigned int i = 0; i < p.v.size(); i++) {
rv.v[i] = std::fmod(p.v[i], this->side_length);
if (rv.v[i] < 0.0) rv.v[i] += this->side_length;
}
return rv;
}
Vec Sim::enforce_bounds(const Vec &p1, const Vec &p2) const
{
Vec dp;
for (unsigned int i = 0; i < p1.v.size(); i++) {
dp.v[i] = p2.v[i] - p1.v[i];
dp.v[i] -= this->side_length * std::nearbyint(dp.v[i] * this->inv_side_length);
}
return dp;
}
| 26.4 | 131 | 0.636364 | cbosoft |
646e5bf66c5cee923ad5da2e8ad7df8ab90aee90 | 6,918 | cpp | C++ | lib/djvViewApp/EditSystem.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | lib/djvViewApp/EditSystem.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | lib/djvViewApp/EditSystem.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2004-2020 Darby Johnston
// All rights reserved.
#include <djvViewApp/EditSystem.h>
#include <djvViewApp/Media.h>
#include <djvViewApp/MediaWidget.h>
#include <djvViewApp/WindowSystem.h>
#include <djvUI/Action.h>
#include <djvUI/Menu.h>
#include <djvUI/ShortcutDataFunc.h>
#include <djvSystem/Context.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
using namespace djv::Core;
namespace djv
{
namespace ViewApp
{
struct EditSystem::Private
{
bool hasUndo = false;
bool hasRedo = false;
std::shared_ptr<MediaWidget> activeWidget;
std::map<std::string, std::shared_ptr<UI::Action> > actions;
std::shared_ptr<UI::Menu> menu;
std::shared_ptr<Observer::Value<std::shared_ptr<MediaWidget> > > activeWidgetObserver;
std::shared_ptr<Observer::Value<bool> > hasUndoObserver;
std::shared_ptr<Observer::Value<bool> > hasRedoObserver;
};
void EditSystem::_init(const std::shared_ptr<System::Context>& context)
{
IViewAppSystem::_init("djv::ViewApp::EditSystem", context);
DJV_PRIVATE_PTR();
p.actions["Undo"] = UI::Action::create();
p.actions["Redo"] = UI::Action::create();
_addShortcut(DJV_TEXT("shortcut_undo"), GLFW_KEY_Z, UI::getSystemModifier());
_addShortcut(DJV_TEXT("shortcut_redo"), GLFW_KEY_Z, UI::getSystemModifier() | GLFW_MOD_SHIFT);
p.menu = UI::Menu::create(context);
p.menu->addAction(p.actions["Undo"]);
p.menu->addAction(p.actions["Redo"]);
_actionsUpdate();
_textUpdate();
_shortcutsUpdate();
auto weak = std::weak_ptr<EditSystem>(std::dynamic_pointer_cast<EditSystem>(shared_from_this()));
p.actions["Undo"]->setClickedCallback(
[weak]
{
if (auto system = weak.lock())
{
if (auto widget = system->_p->activeWidget)
{
widget->getMedia()->undo();
}
}
});
p.actions["Redo"]->setClickedCallback(
[weak]
{
if (auto system = weak.lock())
{
if (auto widget = system->_p->activeWidget)
{
widget->getMedia()->redo();
}
}
});
if (auto windowSystem = context->getSystemT<WindowSystem>())
{
auto contextWeak = std::weak_ptr<System::Context>(context);
p.activeWidgetObserver = Observer::Value<std::shared_ptr<MediaWidget> >::create(
windowSystem->observeActiveWidget(),
[weak, contextWeak](const std::shared_ptr<MediaWidget>& value)
{
if (auto system = weak.lock())
{
system->_p->activeWidget = value;
if (system->_p->activeWidget)
{
system->_p->hasUndoObserver = Observer::Value<bool>::create(
system->_p->activeWidget->getMedia()->observeHasUndo(),
[weak](bool value)
{
if (auto system = weak.lock())
{
system->_p->hasUndo = value;
system->_actionsUpdate();
}
});
system->_p->hasRedoObserver = Observer::Value<bool>::create(
system->_p->activeWidget->getMedia()->observeHasRedo(),
[weak](bool value)
{
if (auto system = weak.lock())
{
system->_p->hasRedo = value;
system->_actionsUpdate();
}
});
}
else
{
system->_p->hasUndo = false;
system->_p->hasRedo = false;
system->_p->hasUndoObserver.reset();
system->_p->hasRedoObserver.reset();
system->_actionsUpdate();
}
}
});
}
_logInitTime();
}
EditSystem::EditSystem() :
_p(new Private)
{}
EditSystem::~EditSystem()
{}
std::shared_ptr<EditSystem> EditSystem::create(const std::shared_ptr<System::Context>& context)
{
auto out = context->getSystemT<EditSystem>();
if (!out)
{
out = std::shared_ptr<EditSystem>(new EditSystem);
out->_init(context);
}
return out;
}
std::map<std::string, std::shared_ptr<UI::Action> > EditSystem::getActions() const
{
return _p->actions;
}
MenuData EditSystem::getMenuData() const
{
return
{
{ _p->menu },
2
};
}
void EditSystem::_actionsUpdate()
{
DJV_PRIVATE_PTR();
if (p.actions.size())
{
p.actions["Undo"]->setEnabled(p.hasUndo);
p.actions["Redo"]->setEnabled(p.hasRedo);
}
}
void EditSystem::_textUpdate()
{
DJV_PRIVATE_PTR();
if (p.actions.size())
{
p.actions["Undo"]->setText(_getText(DJV_TEXT("menu_edit_undo")));
p.actions["Redo"]->setText(_getText(DJV_TEXT("menu_edit_redo")));
p.menu->setText(_getText(DJV_TEXT("menu_edit")));
}
}
void EditSystem::_shortcutsUpdate()
{
DJV_PRIVATE_PTR();
if (p.actions.size())
{
p.actions["Undo"]->setShortcuts(_getShortcuts("shortcut_undo"));
p.actions["Redo"]->setShortcuts(_getShortcuts("shortcut_redo"));
}
}
} // namespace ViewApp
} // namespace djv
| 34.59 | 109 | 0.433651 | pafri |
647170c9feec043e3caa404fd95aa348793cea24 | 42,055 | cpp | C++ | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Implementation/GLFormat.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Implementation/GLFormat.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Implementation/GLFormat.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Defines the required information about image formats used
// by DXMETAL as well as utility functions.
#include <StdAfx.h>
#include "GLFormat.hpp"
namespace NCryMetal
{
#define DXGL_DXGI_FORMAT(_FormatID) DXGI_FORMAT_ ## _FormatID
#define DXGL_UNCOMPRESSED_LAYOUT(_FormatID) g_kUncompressedLayout_ ## _FormatID
#define DXGL_TEXTURE_FORMAT(_FormatID) g_kTextureFormat_ ## _FormatID
#define DXGL_GL_INTERNAL_FORMAT(_InternalID) GL ## _InternalID
#define DXGL_GI_CHANNEL_TYPE(_Type) eGICT_ ## _Type
#define _PTR_MAP(_Type) _Type ## PtrMap
#define _PTR_MAP_DEFAULT(_Type, _Enum, _Ptr) \
template <_Enum eValue> \
struct _PTR_MAP(_Type){static const _Type* ms_pPtr; }; \
template <_Enum eValue> \
const _Type * _PTR_MAP(_Type) < eValue > ::ms_pPtr = _Ptr;
#define _PTR_MAP_VALUE(_Type, _Value, _Ptr) \
template <> \
struct _PTR_MAP(_Type) < _Value > {static const _Type* ms_pPtr; }; \
const _Type* _PTR_MAP(_Type) < _Value > ::ms_pPtr = _Ptr;
#define _UINT_MAP(_Name) S ## _Name ## UintMap
#define _UINT_MAP_DEFAULT(_Name, _Enum, _UIntVal) \
template <_Enum eValue> \
struct _UINT_MAP(_Name){enum {VALUE = _UIntVal}; };
#define _UINT_MAP_VALUE(_Name, _Value, _UIntVal) \
template <> \
struct _UINT_MAP(_Name) < _Value > {enum {VALUE = _UIntVal}; };
////////////////////////////////////////////////////////////////////////////////
// Uncompressed layouts for renderable formats
////////////////////////////////////////////////////////////////////////////////
_PTR_MAP_DEFAULT(SUncompressedLayout, EGIFormat, NULL)
#define _UNCOMPR_LAY(_FormatID, _NumR, _NumG, _NumB, _NumA, _ShiftR, _ShiftG, _ShiftB, _ShiftA, _TypeRGBA, _Depth, _TypeD, _Stencil, _TypeS, _Spare) \
static const SUncompressedLayout DXGL_UNCOMPRESSED_LAYOUT(_FormatID) = \
{ \
_NumR, _NumG, _NumB, _NumA, \
_ShiftR, _ShiftG, _ShiftB, _ShiftA, \
DXGL_GI_CHANNEL_TYPE(_TypeRGBA), \
_Depth, DXGL_GI_CHANNEL_TYPE(_TypeD), \
_Stencil, DXGL_GI_CHANNEL_TYPE(_TypeS), \
_Spare \
}; \
_PTR_MAP_VALUE(SUncompressedLayout, DXGL_GI_FORMAT(_FormatID), &DXGL_UNCOMPRESSED_LAYOUT(_FormatID))
// | FORMAT_ID | RGBA_SIZES | RGBA_SHIFTS | RGBA | DEPTH | STENCIL | - |
// | | NR NG NB NA | SR SG SB SA | TYPE | N TYPE | N TYPE | X |
_UNCOMPR_LAY(R32G32B32A32_FLOAT, 32, 32, 32, 32, 0, 32, 64, 96, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32B32A32_UINT, 32, 32, 32, 32, 0, 32, 64, 96, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32B32A32_SINT, 32, 32, 32, 32, 0, 32, 64, 96, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32B32_FLOAT, 32, 32, 32, 0, 0, 32, 64, 96, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32B32_UINT, 32, 32, 32, 0, 0, 32, 64, 96, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32B32_SINT, 32, 32, 32, 0, 0, 32, 64, 96, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16B16A16_FLOAT, 16, 16, 16, 16, 0, 16, 32, 48, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16B16A16_UNORM, 16, 16, 16, 16, 0, 16, 32, 48, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16B16A16_UINT, 16, 16, 16, 16, 0, 16, 32, 48, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16B16A16_SNORM, 16, 16, 16, 16, 0, 16, 32, 48, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16B16A16_SINT, 16, 16, 16, 16, 0, 16, 32, 48, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32_FLOAT, 32, 32, 0, 0, 0, 32, -1, -1, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32_UINT, 32, 32, 0, 0, 0, 32, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32G32_SINT, 32, 32, 0, 0, 0, 32, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R10G10B10A2_UNORM, 10, 10, 10, 2, 0, 10, 20, 30, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R10G10B10A2_UINT, 10, 10, 10, 2, 0, 10, 20, 30, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R11G11B10_FLOAT, 11, 11, 10, 0, 0, 11, 22, -1, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8B8A8_UNORM, 8, 8, 8, 8, 0, 8, 16, 24, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8B8A8_UNORM_SRGB, 8, 8, 8, 8, 0, 8, 16, 24, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8B8A8_UINT, 8, 8, 8, 8, 0, 8, 16, 24, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8B8A8_SNORM, 8, 8, 8, 8, 0, 8, 16, 24, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8B8A8_SINT, 8, 8, 8, 8, 0, 8, 16, 24, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16_FLOAT, 16, 16, 0, 0, 0, 16, -1, -1, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16_UNORM, 16, 16, 0, 0, 0, 16, -1, -1, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16_UINT, 16, 16, 0, 0, 0, 16, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16_SNORM, 16, 16, 0, 0, 0, 16, -1, -1, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16G16_SINT, 16, 16, 0, 0, 0, 16, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(D32_FLOAT, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 32, FLOAT, 0, UNUSED, 0)
_UNCOMPR_LAY(R32_FLOAT, 32, 0, 0, 0, 0, -1, -1, -1, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32_UINT, 32, 0, 0, 0, 0, -1, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R32_SINT, 32, 0, 0, 0, 0, -1, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(D32_FLOAT_S8X24_UINT, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 32, FLOAT, 8, UINT, 24)
_UNCOMPR_LAY(X32_TYPELESS_G8X24_UINT, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 32, FLOAT, 8, UINT, 24)
_UNCOMPR_LAY(D24_UNORM_S8_UINT, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 24, UNORM, 8, UINT, 0)
_UNCOMPR_LAY(X24_TYPELESS_G8_UINT, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 24, UNORM, 8, UINT, 0)
_UNCOMPR_LAY(R24_UNORM_X8_TYPELESS, 24, 0, 0, 0, -1, -1, -1, -1, UNORM, 0, UNUSED, 0, UNUSED, 8)
_UNCOMPR_LAY(R8G8_UNORM, 8, 8, 0, 0, 0, 8, -1, -1, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8_UINT, 8, 8, 0, 0, 0, 8, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8_SNORM, 8, 8, 0, 0, 0, 8, -1, -1, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8G8_SINT, 8, 8, 0, 0, 0, 8, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16_FLOAT, 16, 0, 0, 0, 0, -1, -1, -1, FLOAT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(D16_UNORM, 0, 0, 0, 0, -1, -1, -1, -1, UNUSED, 16, UNORM, 0, UNUSED, 0)
_UNCOMPR_LAY(R16_UNORM, 16, 0, 0, 0, 0, -1, -1, -1, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16_UINT, 16, 0, 0, 0, 0, -1, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16_SNORM, 16, 0, 0, 0, 0, -1, -1, -1, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R16_SINT, 16, 0, 0, 0, 0, -1, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8_UNORM, 8, 0, 0, 0, 0, -1, -1, -1, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8_UINT, 8, 0, 0, 0, 0, -1, -1, -1, UINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8_SNORM, 8, 0, 0, 0, 0, -1, -1, -1, SNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(R8_SINT, 8, 0, 0, 0, 0, -1, -1, -1, SINT, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(A8_UNORM, 0, 0, 0, 8, -1, -1, -1, 0, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(B5G6R5_UNORM, 5, 6, 5, 0, 11, 5, 0, -1, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(B5G5R5A1_UNORM, 5, 5, 5, 1, 10, 5, 0, 15, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(B8G8R8A8_UNORM, 8, 8, 8, 8, 16, 8, 0, 24, UNORM, 0, UNUSED, 0, UNUSED, 0)
_UNCOMPR_LAY(B8G8R8X8_UNORM, 8, 8, 8, 0, 16, 8, 0, -1, UNORM, 0, UNUSED, 0, UNUSED, 8)
#undef _UNCOMPR_LAY
////////////////////////////////////////////////////////////////////////////////
// Swizzle required to map each texture format to the corresponding DXGI format
////////////////////////////////////////////////////////////////////////////////
#define DXGL_SWIZZLE_RED 0
#define DXGL_SWIZZLE_GREEN 1
#define DXGL_SWIZZLE_BLUE 2
#define DXGL_SWIZZLE_ALPHA 3
#define DXGL_SWIZZLE_ZERO 4
#define DXGL_SWIZZLE_ONE 5
#define _SWIZZLE_MASK(_Red, _Green, _Blue, _Alpha) \
DXGL_SWIZZLE_ ## _Red << 9 | \
DXGL_SWIZZLE_ ## _Green << 6 | \
DXGL_SWIZZLE_ ## _Blue << 3 | \
DXGL_SWIZZLE_ ## _Alpha
_UINT_MAP_DEFAULT(DXGITextureSwizzle, TSwizzleMask, _SWIZZLE_MASK(RED, GREEN, BLUE, ALPHA))
#define _DXGI_TEX_SWIZZLE(_FormatID, _Red, _Green, _Blue, _Alpha) _UINT_MAP_VALUE(DXGITextureSwizzle, DXGL_GI_FORMAT(_FormatID), _SWIZZLE_MASK(_Red, _Green, _Blue, _Alpha))
_DXGI_TEX_SWIZZLE(A8_UNORM, ZERO, ZERO, ZERO, RED)
_DXGI_TEX_SWIZZLE(B8G8R8A8_UNORM, BLUE, GREEN, RED, ALPHA)
_DXGI_TEX_SWIZZLE(B8G8R8X8_UNORM, BLUE, GREEN, RED, ZERO)
#undef _DXGI_TEX_SWIZZLE
#undef _SWIZZLE_MASK
////////////////////////////////////////////////////////////////////////////////
// Texturable formats (split between uncompressed and compressed)
////////////////////////////////////////////////////////////////////////////////
_PTR_MAP_DEFAULT(STextureFormat, EGIFormat, NULL)
// Confetti BEGIN: Igor Lobanchikov
#define _TEX(_FormatID, _GLInternalFormat, _GLBaseFormat, _Compressed, _GLType, _BlockWidth, _BlockHeight, _BlockDepth, _NumBlockBytes, _SRGB, _METALPixelType, _METALVertexType) \
static const STextureFormat DXGL_TEXTURE_FORMAT(_FormatID) = \
{ \
_Compressed, \
_SRGB, \
_BlockWidth, \
_BlockHeight, \
_BlockDepth, \
_NumBlockBytes, \
_METALPixelType, \
_METALVertexType \
}; \
_PTR_MAP_VALUE(STextureFormat, DXGL_GI_FORMAT(_FormatID), &DXGL_TEXTURE_FORMAT(_FormatID))
#define _UNCOMPR_TEX(_FormatID, _GLInternalFormat, _GLBaseFormat, _GLType, _SRGB, _Bytes, _METALPixelType, _METALVertexType) _TEX(_FormatID, _GLInternalFormat, _GLBaseFormat, false, _GLType, 1, 1, 1, _Bytes, _SRGB, _METALPixelType, _METALVertexType)
#define _COMPR_TEX(_FormatID, _GLInternalFormat, _GLBaseFormat, _BlockWidth, _BlockHeight, _BlockDepth, _NumBlockBytes, _SRGB, _METALPixelType) _TEX(_FormatID, _GLInternalFormat, _GLBaseFormat, true, 0, _BlockWidth, _BlockHeight, _BlockDepth, _NumBlockBytes, _SRGB, _METALPixelType, MTLVertexFormatInvalid)
// | FORMAT_ID | GL_INTERNAL_FORMAT | GL_FORMAT | GL_TYPE | SRGB | BYTES | MTLPixelFormat | MTLVertexFormat
// | | | | | SRGB | BYTES | |
_UNCOMPR_TEX(R32G32B32A32_FLOAT, GL_RGBA32F, GL_RGBA, GL_FLOAT, false, 16, MTLPixelFormatRGBA32Float, MTLVertexFormatFloat4)
_UNCOMPR_TEX(R32G32B32A32_UINT, GL_RGBA32UI, GL_RGBA, GL_UNSIGNED_INT, false, 16, MTLPixelFormatRGBA32Uint, MTLVertexFormatUInt4)
_UNCOMPR_TEX(R32G32B32A32_SINT, GL_RGBA32I, GL_RGBA, GL_INT, false, 16, MTLPixelFormatRGBA32Sint, MTLVertexFormatInt4)
_UNCOMPR_TEX(R32G32B32_FLOAT, GL_RGB32F, GL_RGB, GL_FLOAT, false, 12, MTLPixelFormatInvalid, MTLVertexFormatFloat3)
_UNCOMPR_TEX(R32G32B32_UINT, GL_RGB32UI, GL_RGB, GL_UNSIGNED_INT, false, 12, MTLPixelFormatInvalid, MTLVertexFormatUInt3)
_UNCOMPR_TEX(R32G32B32_SINT, GL_RGB32I, GL_RGB, GL_INT, false, 12, MTLPixelFormatInvalid, MTLVertexFormatInt3)
_UNCOMPR_TEX(R16G16B16A16_FLOAT, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, false, 8, MTLPixelFormatRGBA16Float, MTLVertexFormatHalf4)
_UNCOMPR_TEX(R16G16B16A16_UNORM, GL_RGBA16UI, GL_RGBA, GL_UNSIGNED_SHORT, false, 8, MTLPixelFormatRGBA16Unorm, MTLVertexFormatUShort4Normalized)
_UNCOMPR_TEX(R16G16B16A16_UINT, GL_RGBA16UI, GL_RGBA, GL_UNSIGNED_SHORT, false, 8, MTLPixelFormatRGBA16Uint, MTLVertexFormatUShort4)
_UNCOMPR_TEX(R16G16B16A16_SNORM, GL_NONE, GL_RGBA, GL_SHORT, false, 8, MTLPixelFormatRGBA16Snorm, MTLVertexFormatShort4Normalized)
_UNCOMPR_TEX(R16G16B16A16_SINT, GL_RGBA16I, GL_RGBA, GL_SHORT, false, 8, MTLPixelFormatRGBA16Sint, MTLVertexFormatShort4)
_UNCOMPR_TEX(R32G32_FLOAT, GL_RG32F, GL_RG, GL_FLOAT, false, 8, MTLPixelFormatRG32Float, MTLVertexFormatFloat2)
_UNCOMPR_TEX(R32G32_UINT, GL_RG32UI, GL_RG, GL_UNSIGNED_INT, false, 8, MTLPixelFormatRG32Uint, MTLVertexFormatUInt2)
_UNCOMPR_TEX(R32G32_SINT, GL_RG32I, GL_RG, GL_INT, false, 8, MTLPixelFormatRG32Sint, MTLVertexFormatInt2)
_UNCOMPR_TEX(R10G10B10A2_UNORM, GL_RGB10_A2UI, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false, 4, MTLPixelFormatRGB10A2Unorm, MTLVertexFormatUInt1010102Normalized)
_UNCOMPR_TEX(R10G10B10A2_UINT, GL_RGB10_A2UI, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false, 4, MTLPixelFormatRGB10A2Uint, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R11G11B10_FLOAT, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false, 4, MTLPixelFormatRG11B10Float, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8G8B8A8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatRGBA8Unorm, MTLVertexFormatUChar4Normalized)
_UNCOMPR_TEX(R8G8B8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, true, 4, MTLPixelFormatRGBA8Unorm_sRGB, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8G8B8A8_UINT, GL_RGBA8UI, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatRGBA8Uint, MTLVertexFormatUChar4)
_UNCOMPR_TEX(R8G8B8A8_SNORM, GL_RGBA8_SNORM, GL_RGBA, GL_BYTE, false, 4, MTLPixelFormatRGBA8Snorm, MTLVertexFormatChar4Normalized)
_UNCOMPR_TEX(R8G8B8A8_SINT, GL_RGBA8I, GL_RGBA, GL_BYTE, false, 4, MTLPixelFormatRGBA8Sint, MTLVertexFormatChar4)
_UNCOMPR_TEX(R16G16_FLOAT, GL_RG16F, GL_RG, GL_HALF_FLOAT, false, 4, MTLPixelFormatRG16Float, MTLVertexFormatHalf2)
_UNCOMPR_TEX(R16G16_UNORM, GL_RG16UI, GL_RG, GL_UNSIGNED_SHORT, false, 4, MTLPixelFormatRG16Unorm, MTLVertexFormatUShort2Normalized)
_UNCOMPR_TEX(R16G16_UINT, GL_RG16UI, GL_RG, GL_UNSIGNED_SHORT, false, 4, MTLPixelFormatRG16Uint, MTLVertexFormatUShort2)
_UNCOMPR_TEX(R16G16_SINT, GL_RG16I, GL_RG, GL_SHORT, false, 4, MTLPixelFormatRG16Sint, MTLVertexFormatShort2)
_UNCOMPR_TEX(D32_FLOAT, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false, 4, MTLPixelFormatDepth32Float, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R32_FLOAT, GL_R32F, GL_RED, GL_FLOAT, false, 4, MTLPixelFormatR32Float, MTLVertexFormatFloat)
_UNCOMPR_TEX(R32_UINT, GL_R32UI, GL_RED, GL_UNSIGNED_INT, false, 4, MTLPixelFormatR32Uint, MTLVertexFormatUInt)
_UNCOMPR_TEX(R32_SINT, GL_R32I, GL_RED, GL_INT, false, 4, MTLPixelFormatR32Sint, MTLVertexFormatInt)
_UNCOMPR_TEX(R8G8_UNORM, GL_RG8, GL_RG, GL_UNSIGNED_BYTE, false, 2, MTLPixelFormatRG8Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8G8_UINT, GL_RG8UI, GL_RG, GL_UNSIGNED_BYTE, false, 2, MTLPixelFormatRG8Uint, MTLVertexFormatUChar2Normalized)
_UNCOMPR_TEX(R8G8_SNORM, GL_RG8_SNORM, GL_RG, GL_BYTE, false, 2, MTLPixelFormatRG8Snorm, MTLVertexFormatChar2Normalized)
_UNCOMPR_TEX(R8G8_SINT, GL_RG8I, GL_RG, GL_BYTE, false, 2, MTLPixelFormatRG8Sint, MTLVertexFormatChar2)
_UNCOMPR_TEX(R16_FLOAT, GL_R16F, GL_RED, GL_HALF_FLOAT, false, 2, MTLPixelFormatR16Float, MTLVertexFormatInvalid)
_UNCOMPR_TEX(D16_UNORM, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false, 2, MTLPixelFormatInvalid, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R16_UNORM, GL_R16UI, GL_RED, GL_UNSIGNED_SHORT, false, 2, MTLPixelFormatR16Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R16_UINT, GL_R16UI, GL_RED, GL_UNSIGNED_SHORT, false, 2, MTLPixelFormatR16Uint, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R16_SINT, GL_R16I, GL_RED, GL_SHORT, false, 2, MTLPixelFormatR16Sint, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8_UNORM, GL_R8, GL_RED, GL_UNSIGNED_BYTE, false, 1, MTLPixelFormatR8Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8_UINT, GL_R8UI, GL_RED, GL_UNSIGNED_BYTE, false, 1, MTLPixelFormatR8Uint, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8_SNORM, GL_R8_SNORM, GL_RED, GL_BYTE, false, 1, MTLPixelFormatR8Snorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R8_SINT, GL_R8I, GL_RED, GL_BYTE, false, 1, MTLPixelFormatR8Sint, MTLVertexFormatInvalid)
_UNCOMPR_TEX(A8_UNORM, GL_A8, GL_ALPHA, GL_UNSIGNED_BYTE, false, 1, MTLPixelFormatA8Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R9G9B9E5_SHAREDEXP, GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, false, 4, MTLPixelFormatRGB9E5Float, MTLVertexFormatInvalid)
_UNCOMPR_TEX(B8G8R8A8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatBGRA8Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(B8G8R8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatBGRA8Unorm_sRGB, MTLVertexFormatInvalid)
_UNCOMPR_TEX(B8G8R8X8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatBGRA8Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(B8G8R8X8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, 4, MTLPixelFormatBGRA8Unorm_sRGB, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R16_SNORM, GL_R16_SNORM, GL_RED, GL_SHORT, false, 2, MTLPixelFormatR16Snorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(R16G16_SNORM, GL_RG16_SNORM, GL_RG, GL_SHORT, false, 4, MTLPixelFormatRG16Snorm, MTLVertexFormatShort2Normalized)
_UNCOMPR_TEX(D32_FLOAT_S8X24_UINT, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, false, 8, MTLPixelFormatDepth32Float_Stencil8, MTLVertexFormatInvalid)
_UNCOMPR_TEX(X32_TYPELESS_G8X24_UINT, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, false, 8, MTLPixelFormatX32_Stencil8, MTLVertexFormatInvalid)
#if defined(AZ_PLATFORM_MAC)
_UNCOMPR_TEX(D24_UNORM_S8_UINT, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false, 4, MTLPixelFormatDepth24Unorm_Stencil8, MTLVertexFormatInvalid)
_UNCOMPR_TEX(X24_TYPELESS_G8_UINT, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false, 4, MTLPixelFormatX24_Stencil8, MTLVertexFormatInvalid)
_COMPR_TEX(BC1_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, 4, 4, 1, 8, false, MTLPixelFormatBC1_RGBA)
_COMPR_TEX(BC1_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, 4, 4, 1, 8, true, MTLPixelFormatBC1_RGBA_sRGB)
_COMPR_TEX(BC2_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, 4, 4, 1, 16, false, MTLPixelFormatBC2_RGBA)
_COMPR_TEX(BC2_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, 4, 4, 1, 16, true, MTLPixelFormatBC2_RGBA_sRGB)
_COMPR_TEX(BC3_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, 4, 4, 1, 16, false, MTLPixelFormatBC3_RGBA)
_COMPR_TEX(BC3_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, 4, 4, 1, 16, true, MTLPixelFormatBC3_RGBA_sRGB)
_COMPR_TEX(BC4_UNORM, GL_COMPRESSED_RED_RGTC1, GL_RED, 4, 4, 1, 8, false, MTLPixelFormatBC4_RUnorm)
_COMPR_TEX(BC4_SNORM, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED, 4, 4, 1, 8, false, MTLPixelFormatBC4_RSnorm)
_COMPR_TEX(BC5_UNORM, GL_COMPRESSED_RG_RGTC2, GL_RG, 4, 4, 1, 16, false, MTLPixelFormatBC5_RGUnorm)
_COMPR_TEX(BC5_SNORM, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG, 4, 4, 1, 16, false, MTLPixelFormatBC5_RGSnorm)
_COMPR_TEX(BC6H_UF16, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_RGB, 4, 4, 1, 16, false, MTLPixelFormatBC6H_RGBUfloat)
_COMPR_TEX(BC6H_SF16, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_RGB, 4, 4, 1, 16, false, MTLPixelFormatBC6H_RGBFloat)
_COMPR_TEX(BC7_UNORM, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_RGBA, 4, 4, 1, 16, false, MTLPixelFormatBC7_RGBAUnorm)
_COMPR_TEX(BC7_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_RGBA, 4, 4, 1, 16, true, MTLPixelFormatBC7_RGBAUnorm_sRGB)
#else
_UNCOMPR_TEX(B5G6R5_UNORM, GL_RGB565, GL_BGR, GL_UNSIGNED_SHORT_5_6_5_REV, false, 2, MTLPixelFormatB5G6R5Unorm, MTLVertexFormatInvalid)
_UNCOMPR_TEX(B5G5R5A1_UNORM, GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_SHORT_5_5_5_1, false, 2, MTLPixelFormatA1BGR5Unorm, MTLVertexFormatInvalid)
// | FORMAT_ID | GL_INTERNAL_FORMAT | GL_FORMAT | BLOCK | SRGB | MTLPixelFormat |
// | | | | X | Y | Z | BYTES | | |
_COMPR_TEX(EAC_R11_UNORM, GL_COMPRESSED_R11_EAC, GL_RED, 4, 4, 1, 8, false, MTLPixelFormatEAC_R11Unorm)
_COMPR_TEX(EAC_R11_SNORM, GL_COMPRESSED_SIGNED_R11_EAC, GL_RED, 4, 4, 1, 8, false, MTLPixelFormatEAC_R11Snorm)
_COMPR_TEX(EAC_RG11_UNORM, GL_COMPRESSED_RG11_EAC, GL_RG, 4, 4, 1, 16, false, MTLPixelFormatEAC_RG11Unorm)
_COMPR_TEX(EAC_RG11_SNORM, GL_COMPRESSED_SIGNED_RG11_EAC, GL_RG, 4, 4, 1, 16, false, MTLPixelFormatEAC_RG11Snorm)
_COMPR_TEX(ETC2_UNORM, GL_COMPRESSED_RGB8_ETC2, GL_RGB, 4, 4, 1, 8, false, MTLPixelFormatETC2_RGB8)
_COMPR_TEX(ETC2_UNORM_SRGB, GL_COMPRESSED_SRGB8_ETC2, GL_RGB, 4, 4, 1, 8, true, MTLPixelFormatETC2_RGB8_sRGB)
_COMPR_TEX(ETC2A_UNORM, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_RGBA, 4, 4, 1, 16, false, MTLPixelFormatETC2_RGB8A1)
_COMPR_TEX(ETC2A_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_RGBA, 4, 4, 1, 16, true, MTLPixelFormatETC2_RGB8A1_sRGB)
// Igor: no sRGB support for GL ES 3.0 on iPhone?
//#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
//#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
_COMPR_TEX(PVRTC2_UNORM, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_RGBA, 8, 4, 1, 8, false, MTLPixelFormatPVRTC_RGBA_2BPP)
_COMPR_TEX(PVRTC2_UNORM_SRGB, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_RGBA, 8, 4, 1, 8, true, MTLPixelFormatPVRTC_RGBA_2BPP_sRGB)
_COMPR_TEX(PVRTC4_UNORM, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_RGBA, 4, 4, 1, 8, false, MTLPixelFormatPVRTC_RGBA_4BPP)
_COMPR_TEX(PVRTC4_UNORM_SRGB, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_RGBA, 4, 4, 1, 8, true, MTLPixelFormatPVRTC_RGBA_4BPP_sRGB)
// Confetti End: Igor Lobanchikov
_COMPR_TEX(ASTC_4x4_UNORM, GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_RGBA, 4, 4, 1, 16, false, MTLPixelFormatASTC_4x4_LDR)
_COMPR_TEX(ASTC_4x4_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, GL_RGBA, 4, 4, 1, 16, true, MTLPixelFormatASTC_4x4_sRGB)
_COMPR_TEX(ASTC_5x4_UNORM, GL_COMPRESSED_RGBA_ASTC_5x4_KHR, GL_RGBA, 5, 4, 1, 16, false, MTLPixelFormatASTC_5x4_LDR)
_COMPR_TEX(ASTC_5x4_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, GL_RGBA, 5, 4, 1, 16, true, MTLPixelFormatASTC_5x4_sRGB)
_COMPR_TEX(ASTC_5x5_UNORM, GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_RGBA, 5, 5, 1, 16, false, MTLPixelFormatASTC_5x5_LDR)
_COMPR_TEX(ASTC_5x5_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, GL_RGBA, 5, 5, 1, 16, true, MTLPixelFormatASTC_5x5_sRGB)
_COMPR_TEX(ASTC_6x5_UNORM, GL_COMPRESSED_RGBA_ASTC_6x5_KHR, GL_RGBA, 6, 5, 1, 16, false, MTLPixelFormatASTC_6x5_LDR)
_COMPR_TEX(ASTC_6x5_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, GL_RGBA, 6, 5, 1, 16, true, MTLPixelFormatASTC_6x5_sRGB)
_COMPR_TEX(ASTC_6x6_UNORM, GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_RGBA, 6, 6, 1, 16, false, MTLPixelFormatASTC_6x6_LDR)
_COMPR_TEX(ASTC_6x6_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, GL_RGBA, 6, 6, 1, 16, true, MTLPixelFormatASTC_6x6_sRGB)
_COMPR_TEX(ASTC_8x5_UNORM, GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_RGBA, 8, 5, 1, 16, false, MTLPixelFormatASTC_8x5_LDR)
_COMPR_TEX(ASTC_8x5_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, GL_RGBA, 8, 5, 1, 16, true, MTLPixelFormatASTC_8x5_sRGB)
_COMPR_TEX(ASTC_8x6_UNORM, GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_RGBA, 8, 6, 1, 16, false, MTLPixelFormatASTC_8x6_LDR)
_COMPR_TEX(ASTC_8x6_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, GL_RGBA, 8, 6, 1, 16, true, MTLPixelFormatASTC_8x6_sRGB)
_COMPR_TEX(ASTC_8x8_UNORM, GL_COMPRESSED_RGBA_ASTC_8x8_KHR, GL_RGBA, 8, 8, 1, 16, false, MTLPixelFormatASTC_8x8_LDR)
_COMPR_TEX(ASTC_8x8_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, GL_RGBA, 8, 8, 1, 16, true, MTLPixelFormatASTC_8x8_sRGB)
_COMPR_TEX(ASTC_10x5_UNORM, GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_RGBA, 10, 5, 1, 16, false, MTLPixelFormatASTC_10x5_LDR)
_COMPR_TEX(ASTC_10x5_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, GL_RGBA, 10, 5, 1, 16, true, MTLPixelFormatASTC_10x5_sRGB)
_COMPR_TEX(ASTC_10x6_UNORM, GL_COMPRESSED_RGBA_ASTC_10x6_KHR, GL_RGBA, 10, 6, 1, 16, false, MTLPixelFormatASTC_10x6_LDR)
_COMPR_TEX(ASTC_10x6_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, GL_RGBA, 10, 6, 1, 16, true, MTLPixelFormatASTC_10x6_sRGB)
_COMPR_TEX(ASTC_10x8_UNORM, GL_COMPRESSED_RGBA_ASTC_10x8_KHR, GL_RGBA, 10, 8, 1, 16, false, MTLPixelFormatASTC_10x8_LDR)
_COMPR_TEX(ASTC_10x8_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, GL_RGBA, 10, 8, 1, 16, true, MTLPixelFormatASTC_10x8_sRGB)
_COMPR_TEX(ASTC_10x10_UNORM, GL_COMPRESSED_RGBA_ASTC_10x10_KHR, GL_RGBA, 10, 10, 1, 16, false, MTLPixelFormatASTC_10x10_LDR)
_COMPR_TEX(ASTC_10x10_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, GL_RGBA, 10, 10, 1, 16, true, MTLPixelFormatASTC_10x10_sRGB)
_COMPR_TEX(ASTC_12x10_UNORM, GL_COMPRESSED_RGBA_ASTC_12x10_KHR, GL_RGBA, 12, 10, 1, 16, false, MTLPixelFormatASTC_12x10_LDR)
_COMPR_TEX(ASTC_12x10_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, GL_RGBA, 12, 10, 1, 16, true, MTLPixelFormatASTC_12x10_sRGB)
_COMPR_TEX(ASTC_12x12_UNORM, GL_COMPRESSED_RGBA_ASTC_12x12_KHR, GL_RGBA, 12, 12, 1, 16, false, MTLPixelFormatASTC_12x12_LDR)
_COMPR_TEX(ASTC_12x12_UNORM_SRGB, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, GL_RGBA, 12, 12, 1, 16, true, MTLPixelFormatASTC_12x12_sRGB)
// Confetti End: Igor Lobanchikov
#endif
#undef _TEX
#undef _UNCOMPR_TEX
#undef _COMPR_TEX
////////////////////////////////////////////////////////////////////////////////
// Default support for each format
////////////////////////////////////////////////////////////////////////////////
_UINT_MAP_DEFAULT(DefaultSupport, EGIFormat, 0)
#define _SUPPORT(_FormatID, _Mask) _UINT_MAP_VALUE(DefaultSupport, DXGL_GI_FORMAT(_FormatID), _Mask)
DXGL_TODO("Add here hardcoded default support masks (see _SUPPORT) for each format to use when format queries are not supported and for particular features")
#undef _SUPPORT
////////////////////////////////////////////////////////////////////////////////
// Typeless format mappings
////////////////////////////////////////////////////////////////////////////////
_UINT_MAP_DEFAULT(TypelessFormat, EGIFormat, eGIF_NUM)
_UINT_MAP_DEFAULT(TypelessConversion, EGIFormat, eGIFC_UNSUPPORTED)
#define _TYPED_CONVERT(_FormatID, _TypelessID, _Conversion) \
_UINT_MAP_VALUE(TypelessFormat, DXGL_GI_FORMAT(_FormatID), DXGL_GI_FORMAT(_TypelessID)) \
_UINT_MAP_VALUE(TypelessConversion, DXGL_GI_FORMAT(_FormatID), eGIFC_ ## _Conversion)
#define _TYPED_DEFAULT(_FormatID, _TypelessID) \
_PTR_MAP_VALUE(STextureFormat, DXGL_GI_FORMAT(_TypelessID), &DXGL_TEXTURE_FORMAT(_FormatID)) \
_PTR_MAP_VALUE(SUncompressedLayout, DXGL_GI_FORMAT(_TypelessID), _PTR_MAP(SUncompressedLayout) < DXGL_GI_FORMAT(_FormatID) > ::ms_pPtr) \
_TYPED_CONVERT(_FormatID, _TypelessID, NONE)
_TYPED_DEFAULT(R32G32B32A32_FLOAT, R32G32B32A32_TYPELESS)
_TYPED_CONVERT(R32G32B32A32_UINT, R32G32B32A32_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R32G32B32A32_SINT, R32G32B32A32_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(R32G32B32_FLOAT, R32G32B32_TYPELESS)
_TYPED_CONVERT(R32G32B32_UINT, R32G32B32_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R32G32B32_SINT, R32G32B32_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(R16G16B16A16_FLOAT, R16G16B16A16_TYPELESS)
_TYPED_CONVERT(R16G16B16A16_UNORM, R16G16B16A16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16B16A16_UINT, R16G16B16A16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16B16A16_SNORM, R16G16B16A16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16B16A16_SINT, R16G16B16A16_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(R32G32_FLOAT, R32G32_TYPELESS)
_TYPED_CONVERT(R32G32_UINT, R32G32_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R32G32_SINT, R32G32_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(D32_FLOAT_S8X24_UINT, R32G8X24_TYPELESS)
_TYPED_CONVERT(R32_FLOAT_X8X24_TYPELESS, R32G8X24_TYPELESS, DEPTH_TO_RED)
_TYPED_CONVERT(X32_TYPELESS_G8X24_UINT, R32G8X24_TYPELESS, STENCIL_TO_RED)
_TYPED_DEFAULT(R10G10B10A2_UNORM, R10G10B10A2_TYPELESS)
_TYPED_CONVERT(R10G10B10A2_UINT, R10G10B10A2_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(R8G8B8A8_UNORM, R8G8B8A8_TYPELESS)
_TYPED_CONVERT(R8G8B8A8_UNORM_SRGB, R8G8B8A8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8G8B8A8_UINT, R8G8B8A8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8G8B8A8_SNORM, R8G8B8A8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8G8B8A8_SINT, R8G8B8A8_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(R16G16_FLOAT, R16G16_TYPELESS)
_TYPED_CONVERT(R16G16_UNORM, R16G16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16_UINT, R16G16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16_SNORM, R16G16_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R16G16_SINT, R16G16_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(D32_FLOAT, R32_TYPELESS)
_TYPED_CONVERT(R32_FLOAT, R32_TYPELESS, DEPTH_TO_RED)
_TYPED_DEFAULT(R8G8_UNORM, R8G8_TYPELESS)
_TYPED_CONVERT(R8G8_UINT, R8G8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8G8_SNORM, R8G8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8G8_SINT, R8G8_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(D16_UNORM, R16_TYPELESS)
_TYPED_CONVERT(R16_UNORM, R16_TYPELESS, DEPTH_TO_RED)
_TYPED_DEFAULT(R8_UNORM, R8_TYPELESS)
_TYPED_CONVERT(R8_UINT, R8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8_SNORM, R8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(R8_SINT, R8_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(B8G8R8A8_UNORM, B8G8R8A8_TYPELESS)
_TYPED_CONVERT(B8G8R8A8_UNORM_SRGB, B8G8R8A8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(EAC_R11_SNORM, EAC_R11_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(EAC_RG11_SNORM, EAC_RG11_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(ETC2_UNORM_SRGB, ETC2_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(ETC2A_UNORM_SRGB, ETC2A_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(B8G8R8X8_UNORM, B8G8R8X8_TYPELESS)
_TYPED_CONVERT(B8G8R8X8_UNORM_SRGB, B8G8R8X8_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(PVRTC2_UNORM_SRGB, PVRTC2_TYPELESS, TEXTURE_VIEW)
_TYPED_CONVERT(PVRTC4_UNORM_SRGB, PVRTC4_TYPELESS, TEXTURE_VIEW)
#if defined(AZ_PLATFORM_MAC)
_TYPED_DEFAULT(D24_UNORM_S8_UINT, R24G8_TYPELESS)
_TYPED_CONVERT(R24_UNORM_X8_TYPELESS, R24G8_TYPELESS, DEPTH_TO_RED)
_TYPED_CONVERT(X24_TYPELESS_G8_UINT, R24G8_TYPELESS, STENCIL_TO_RED)
_TYPED_DEFAULT(BC1_UNORM, BC1_TYPELESS)
_TYPED_CONVERT(BC1_UNORM_SRGB, BC1_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(BC2_UNORM, BC2_TYPELESS)
_TYPED_CONVERT(BC2_UNORM_SRGB, BC2_TYPELESS, TEXTURE_VIEW)
_TYPED_DEFAULT(BC3_UNORM, BC3_TYPELESS)
_TYPED_CONVERT(BC3_UNORM_SRGB, BC3_TYPELESS, TEXTURE_VIEW)
#else
_TYPED_DEFAULT(EAC_R11_UNORM, EAC_R11_TYPELESS)
_TYPED_DEFAULT(EAC_RG11_UNORM, EAC_RG11_TYPELESS)
_TYPED_DEFAULT(ETC2_UNORM, ETC2_TYPELESS)
_TYPED_DEFAULT(ETC2A_UNORM, ETC2A_TYPELESS)
// Confetti BEGIN: Igor Lobanchikov
_TYPED_DEFAULT(PVRTC2_UNORM, PVRTC2_TYPELESS)
_TYPED_DEFAULT(PVRTC4_UNORM, PVRTC4_TYPELESS)
// Confetti End: Igor Lobanchikov
#endif
#undef _TYPED_DEFAULT
#undef _TYPED_CONVERT
////////////////////////////////////////////////////////////////////////////////
// Format information accessors
////////////////////////////////////////////////////////////////////////////////
static SGIFormatInfo g_akFormatInfo[] =
{
#define _FORMAT_INFO(_FormatID) \
{ \
DXGL_DXGI_FORMAT(_FormatID), \
_UINT_MAP(DefaultSupport) < DXGL_GI_FORMAT(_FormatID) > ::VALUE, \
_PTR_MAP(STextureFormat) < DXGL_GI_FORMAT(_FormatID) > ::ms_pPtr, \
_PTR_MAP(SUncompressedLayout) < DXGL_GI_FORMAT(_FormatID) > ::ms_pPtr, \
static_cast<EGIFormat>(_UINT_MAP(TypelessFormat) < DXGL_GI_FORMAT(_FormatID) > ::VALUE), \
static_cast<EGIFormatConversion>(_UINT_MAP(TypelessConversion) < DXGL_GI_FORMAT(_FormatID) > ::VALUE), \
_UINT_MAP(DXGITextureSwizzle) < DXGL_GI_FORMAT(_FormatID) > ::VALUE, \
},
DXGL_GI_FORMATS(_FORMAT_INFO)
#undef _FORMAT_INFO
};
const SGIFormatInfo* GetGIFormatInfo(EGIFormat eGIFormat)
{
assert(eGIFormat < eGIF_NUM);
return &g_akFormatInfo[eGIFormat];
}
DXGI_FORMAT GetDXGIFormat(EGIFormat eGIFormat)
{
const SGIFormatInfo* pFormatInfo(GetGIFormatInfo(eGIFormat));
return (pFormatInfo == NULL) ? DXGI_FORMAT_INVALID : pFormatInfo->m_eDXGIFormat;
}
EGIFormat GetGIFormat(DXGI_FORMAT eDXGIFormat)
{
switch (eDXGIFormat)
{
#define _FORMAT_CASE(_FormatID, ...) \
case DXGL_DXGI_FORMAT(_FormatID): \
return DXGL_GI_FORMAT(_FormatID);
DXGL_GI_FORMATS(_FORMAT_CASE)
#undef _FORMAT_CASE
default:
return eGIF_NUM;
}
}
#undef _PTR_MAP_VALUE
#undef _PTR_MAP_DEFAULT
#undef _PTR_MAP
#undef _UINT_MAP_VALUE
#undef _UINT_MAP_DEFAULT
#undef _UINT_MAP
#undef DXGL_DXGI_FORMAT
#undef DXGL_UNCOMPRESSED_LAYOUT
#undef DXGL_TEXTURE_FORMAT
#undef DXGL_GL_INTERNAL_FORMAT
#undef DXGL_GI_CHANNEL_TYPE
////////////////////////////////////////////////////////////////////////////////
// Texture swizzle encoding
////////////////////////////////////////////////////////////////////////////////
DXMETAL_TODO("Consider removing swizzling data from the texture format structure.");
#ifndef GL_RED
#define GL_RED 0x1903
#define GL_GREEN 0x1904
#define GL_BLUE 0x1905
#define GL_ALPHA 0x1906
#define GL_ZERO 0
#define GL_ONE 1
#endif
void SwizzleMaskToRGBA(TSwizzleMask uMask, int aiRGBA[4])
{
uint32 uChannel(4);
while (uChannel--)
{
switch (uMask & 7)
{
case DXGL_SWIZZLE_RED:
aiRGBA[uChannel] = GL_RED;
break;
case DXGL_SWIZZLE_GREEN:
aiRGBA[uChannel] = GL_GREEN;
break;
case DXGL_SWIZZLE_BLUE:
aiRGBA[uChannel] = GL_BLUE;
break;
case DXGL_SWIZZLE_ALPHA:
aiRGBA[uChannel] = GL_ALPHA;
break;
case DXGL_SWIZZLE_ZERO:
aiRGBA[uChannel] = GL_ZERO;
break;
case DXGL_SWIZZLE_ONE:
aiRGBA[uChannel] = GL_ONE;
break;
default:
assert(false);
}
uMask >>= 3;
}
}
bool RGBAToSwizzleMask(const int aiRGBA[4], TSwizzleMask& uMask)
{
uMask = 0;
uint32 uChannel;
for (uChannel = 0; uChannel < 4; ++uChannel, uMask <<= 3)
{
switch (aiRGBA[uChannel])
{
case GL_RED:
uMask |= DXGL_SWIZZLE_RED;
break;
case GL_GREEN:
uMask |= DXGL_SWIZZLE_GREEN;
break;
case GL_BLUE:
uMask |= DXGL_SWIZZLE_BLUE;
break;
case GL_ALPHA:
uMask |= DXGL_SWIZZLE_ALPHA;
break;
case GL_ZERO:
uMask |= DXGL_SWIZZLE_ZERO;
break;
case GL_ONE:
uMask |= DXGL_SWIZZLE_ONE;
break;
default:
return false;
}
}
return true;
}
#undef DXGL_SWIZZLE_RED
#undef DXGL_SWIZZLE_GREEN
#undef DXGL_SWIZZLE_BLUE
#undef DXGL_SWIZZLE_ALPHA
#undef DXGL_SWIZZLE_ZERO
#undef DXGL_SWIZZLE_ONE
#undef GL_RED
#undef GL_GREEN
#undef GL_BLUE
#undef GL_ALPHA
#undef GL_ZERO
#undef GL_ONE
}
| 72.508621 | 306 | 0.612507 | jeikabu |
6471de1a62fe2223ca6889cae4634b83bd518566 | 721 | cpp | C++ | C++/Number_of_steps_hackerearth.cpp | arpitarunkumaar/Hacktoberfest2021 | 0af40f90a6c0716caadbbfff44ece947b6146f60 | [
"MIT"
] | 125 | 2021-10-01T19:05:26.000Z | 2021-10-03T13:32:42.000Z | C++/Number_of_steps_hackerearth.cpp | arpitarunkumaar/Hacktoberfest2021 | 0af40f90a6c0716caadbbfff44ece947b6146f60 | [
"MIT"
] | 201 | 2021-10-30T20:40:01.000Z | 2022-03-22T17:26:28.000Z | C++/Number_of_steps_hackerearth.cpp | arpitarunkumaar/Hacktoberfest2021 | 0af40f90a6c0716caadbbfff44ece947b6146f60 | [
"MIT"
] | 294 | 2021-10-01T18:46:05.000Z | 2021-10-03T14:25:07.000Z | //Number of steps
//Basic Programming> Input/Output> Basics of Input/Output
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;scanf("%d",&n);
int a[n],b[n];
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
}
int s=a[0];
for(int i=0;i<n;i++) {
scanf("%d",&b[i]);
}
for(int i=0;i<n;i++) {
if(a[i]<s) {
s=a[i];
}
}
int count=0,f=0;
for(int i=0;i<n;i++) {
while(s<a[i] && b!=0) {
a[i]-=b[i];
count++;
}
if(a[i]<s) {
s=a[i];i=-1;
}
if(a[i]<0){
f=1;
break;
}
}
if(f==1)
cout<<"-1";
else
cout<<count;
} | 18.025 | 57 | 0.367545 | arpitarunkumaar |
647285c31cbc3b417b3305e3c8a46ae8e24c48c3 | 1,467 | cpp | C++ | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 3 | 2018-04-02T06:00:51.000Z | 2018-05-29T04:46:29.000Z | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-03-31T17:54:30.000Z | 2018-05-02T11:31:06.000Z | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-10-07T00:08:06.000Z | 2021-06-28T11:02:59.000Z | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int LMAX = 2600;
int T, N, M;
char A[LMAX], B[LMAX];
bool star[LMAX];
bool f[LMAX][LMAX][2];
bool match(char x, char y)
{
if(x == '.' || y == '.')
return true;
return x == y;
}
int main()
{
int t, i, j, k;
scanf("%d", &T);
for(t = 0;t < T;t += 1)
{
memset(f, 0, sizeof(f));
memset(star, 0, sizeof(star));
scanf("%s %s", A + 1, B + 1);
N = strlen(A + 1);
M = strlen(B + 1);
for(i = 1, j = 0;i <= M;i += 1)
{
if(B[i] == '*')
{
star[j] = true;
continue;
}
B[++j] = B[i];
}
M = j;
f[0][0][0] = true;
for(i = 0;i <= N;i += 1)
{
for(j = 0;j <= M;j += 1)
{
for(k = 0;k < 2;k += 1)
{
if(!f[i][j][k])
continue;
//printf("f[%d][%d][%d]\n", i, j, k);
if(j + 1 <= M)
{
if(i + 1 <= N)
{
if((!star[j + 1] || !k) && match(A[i + 1], B[j + 1]))
{
//printf("1 to %d %d %d\n", i + 1, j + 1, 0);
f[i + 1][j + 1][0] = true;
}
if(star[j + 1] && ((k && match(A[i + 1], A[i])) || (!k && match(A[i + 1], B[j + 1]))))
{
//printf("2 to %d %d %d\n", i + 1, j, 1);
f[i + 1][j][1] = true;
}
}
if(star[j + 1])
{
//printf("3 to %d %d %d\n", i, j + 1, 0);
f[i][j + 1][0] = true;
}
}
}
}
}
printf("%s\n", (f[N][M][0] || f[N][M][1])?"yes":"no");
}
exit(0);
}
| 18.111111 | 93 | 0.373551 | tangjz |
6472ca4aae3de7657a2ba8e0bcbc16cf3a3dbab4 | 821 | cpp | C++ | Algorithm-Note/4-Algorithm-Preliminary/4.3-Recursion/Eight-Queen.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | Algorithm-Note/4-Algorithm-Preliminary/4.3-Recursion/Eight-Queen.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | Algorithm-Note/4-Algorithm-Preliminary/4.3-Recursion/Eight-Queen.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | //
// Created by authetic on 2018/8/16.
//
#include <cstdio>
#include <cmath>
#include <cstdlib>
const int maxn = 10;
bool hashtable[10] = {false};
int p[maxn]={0},n=8,count=0;
void generate(int index) {
if (index == n+1) {
count++;
return;
}
for (int i=1; i<=n; i++) {
if (!hashtable[i]) {
bool flag = true;
for (int pre=1; pre<index; pre++) {
if (abs(index-pre)==abs(i-p[pre])) {
flag = false;
break;
}
}
if (flag) {
p[index] = i;
hashtable[i] = true;
generate(index+1);
hashtable[i] = false;
}
}
}
}
int main() {
generate(1);
printf("%d", count);
return 0;
}
| 20.02439 | 52 | 0.411693 | authetic-x |
64761fb25e33e1481807347cd7fe9d1ac6810106 | 1,304 | hpp | C++ | src/phase_field/PFBaseClass.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/phase_field/PFBaseClass.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/phase_field/PFBaseClass.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null |
# ifndef PFBASECLASS_H
# define PFBASECLASS_H
# include "../utils/CommonParams.h"
# include "../utils/GetPot"
using namespace std;
// ---------------------------------------------------------------------
// This is the base class for phase-field classes in the PF App.
// This class serves as an interface, and contains a factory method.
// ---------------------------------------------------------------------
class PFBaseClass {
public:
// -------------------------------------------------------------------
// Factory method that creates objects of sub-classes:
// -------------------------------------------------------------------
static PFBaseClass* PFFactory(const CommonParams&, const GetPot&);
// -------------------------------------------------------------------
// pure virtual functions:
// -------------------------------------------------------------------
virtual void initPhaseField() = 0;
virtual void updatePhaseField() = 0;
virtual void outputPhaseField() = 0;
virtual void setTimeStep(int) = 0;
// -------------------------------------------------------------------
// virtual destructor:
// -------------------------------------------------------------------
virtual ~PFBaseClass()
{
}
};
# endif // PFBASECLASS_H
| 29.636364 | 73 | 0.382669 | flowzario |
64783d070f0a46328f1073e894c7afb53ce20bbd | 6,222 | cpp | C++ | src/core/utility.cpp | Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3 | d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20 | [
"MIT"
] | 1 | 2020-11-29T18:04:31.000Z | 2020-11-29T18:04:31.000Z | src/core/utility.cpp | Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3 | d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20 | [
"MIT"
] | 1 | 2020-09-27T14:53:34.000Z | 2020-09-27T14:53:34.000Z | src/core/utility.cpp | Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3 | d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20 | [
"MIT"
] | null | null | null | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "utility.h"
#include "../MarlinCore.h"
#include "../module/temperature.h"
void safe_delay(millis_t ms) {
while (ms > 50) {
ms -= 50;
delay(50);
thermalManager.manage_heater();
}
delay(ms);
thermalManager.manage_heater(); // This keeps us safe if too many small safe_delay() calls are made
}
// A delay to provide brittle hosts time to receive bytes
#if ENABLED(SERIAL_OVERRUN_PROTECTION)
#include "../gcode/gcode.h" // for set_autoreport_paused
void serial_delay(const millis_t ms) {
const bool was = gcode.set_autoreport_paused(true);
safe_delay(ms);
gcode.set_autoreport_paused(was);
}
#endif
#if ENABLED(DEBUG_LEVELING_FEATURE)
#include "../module/probe.h"
#include "../module/motion.h"
#include "../module/stepper.h"
#include "../libs/numtostr.h"
#include "../feature/bedlevel/bedlevel.h"
void log_machine_info() {
SERIAL_ECHOLNPGM("Machine Type: "
#if ENABLED(DELTA)
"Delta"
#elif IS_SCARA
"SCARA"
#elif IS_CORE
"Core"
#else
"Cartesian"
#endif
);
SERIAL_ECHOLNPGM("Probe: "
#if ENABLED(PROBE_MANUALLY)
"PROBE_MANUALLY"
#elif ENABLED(NOZZLE_AS_PROBE)
"NOZZLE_AS_PROBE"
#elif ENABLED(FIX_MOUNTED_PROBE)
"FIX_MOUNTED_PROBE"
#elif ENABLED(BLTOUCH)
"BLTOUCH"
#elif HAS_Z_SERVO_PROBE
"SERVO PROBE"
#elif ENABLED(TOUCH_MI_PROBE)
"TOUCH_MI_PROBE"
#elif ENABLED(Z_PROBE_SLED)
"Z_PROBE_SLED"
#elif ENABLED(Z_PROBE_ALLEN_KEY)
"Z_PROBE_ALLEN_KEY"
#elif ENABLED(SOLENOID_PROBE)
"SOLENOID_PROBE"
#else
"NONE"
#endif
);
#if HAS_BED_PROBE
#if !HAS_PROBE_XY_OFFSET
SERIAL_ECHOPAIR("Probe Offset X0 Y0 Z", probe.offset.z, " (");
#else
SERIAL_ECHOPAIR_P(PSTR("Probe Offset X"), probe.offset_xy.x, SP_Y_STR, probe.offset_xy.y, SP_Z_STR, probe.offset.z);
if (probe.offset_xy.x > 0)
SERIAL_ECHOPGM(" (Right");
else if (probe.offset_xy.x < 0)
SERIAL_ECHOPGM(" (Left");
else if (probe.offset_xy.y != 0)
SERIAL_ECHOPGM(" (Middle");
else
SERIAL_ECHOPGM(" (Aligned With");
if (probe.offset_xy.y > 0) {
#if IS_SCARA
SERIAL_ECHOPGM("-Distal");
#else
SERIAL_ECHOPGM("-Back");
#endif
}
else if (probe.offset_xy.y < 0) {
#if IS_SCARA
SERIAL_ECHOPGM("-Proximal");
#else
SERIAL_ECHOPGM("-Front");
#endif
}
else if (probe.offset_xy.x != 0)
SERIAL_ECHOPGM("-Center");
SERIAL_ECHOPGM(" & ");
#endif
if (probe.offset.z < 0)
SERIAL_ECHOPGM("Below");
else if (probe.offset.z > 0)
SERIAL_ECHOPGM("Above");
else
SERIAL_ECHOPGM("Same Z as");
SERIAL_ECHOLNPGM(" Nozzle)");
#endif
#if HAS_ABL_OR_UBL
SERIAL_ECHOLNPGM("Auto Bed Leveling: "
#if ENABLED(AUTO_BED_LEVELING_LINEAR)
"LINEAR"
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
"BILINEAR"
#elif ENABLED(AUTO_BED_LEVELING_3POINT)
"3POINT"
#elif ENABLED(AUTO_BED_LEVELING_UBL)
"UBL"
#endif
);
if (planner.leveling_active) {
SERIAL_ECHOLNPGM(" (enabled)");
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height)
SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height);
#endif
#if ABL_PLANAR
SERIAL_ECHOPGM("ABL Adjustment X");
LOOP_XYZ(a) {
float v = planner.get_axis_position_mm(AxisEnum(a)) - current_position[a];
SERIAL_CHAR(' ', 'X' + char(a));
if (v > 0) SERIAL_CHAR('+');
SERIAL_ECHO(v);
}
#else
#if ENABLED(AUTO_BED_LEVELING_UBL)
SERIAL_ECHOPGM("UBL Adjustment Z");
const float rz = ubl.get_z_correction(current_position);
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
SERIAL_ECHOPGM("ABL Adjustment Z");
const float rz = bilinear_z_offset(current_position);
#endif
SERIAL_ECHO(ftostr43sign(rz, '+'));
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height) {
SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position.z), '+'));
SERIAL_CHAR(')');
}
#endif
#endif
}
else
SERIAL_ECHOLNPGM(" (disabled)");
SERIAL_EOL();
#elif ENABLED(MESH_BED_LEVELING)
SERIAL_ECHOPGM("Mesh Bed Leveling");
if (planner.leveling_active) {
SERIAL_ECHOLNPGM(" (enabled)");
SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position), '+'));
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height) {
SERIAL_ECHOPAIR(" (", ftostr43sign(
mbl.get_z(current_position, planner.fade_scaling_factor_for_z(current_position.z)), '+'
));
SERIAL_CHAR(')');
}
#endif
}
else
SERIAL_ECHOPGM(" (disabled)");
SERIAL_EOL();
#endif // MESH_BED_LEVELING
}
#endif // DEBUG_LEVELING_FEATURE
| 29.211268 | 124 | 0.605754 | Sundancer78 |
6478dc632d122fc4ea2f681786afadefa92854b2 | 2,910 | cpp | C++ | 06_Multithreading/src/SFML-Book/Stats.cpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 75 | 2015-01-18T21:29:03.000Z | 2022-02-09T14:11:05.000Z | 06_Multithreading/src/SFML-Book/Stats.cpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 7 | 2015-03-12T10:41:55.000Z | 2020-11-23T11:15:58.000Z | 06_Multithreading/src/SFML-Book/Stats.cpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 33 | 2015-12-01T07:34:46.000Z | 2022-03-23T03:37:42.000Z | #include <SFML-Book/Stats.hpp>
#include <SFML-Book/Configuration.hpp>
#define FONT_SIZE 24
namespace book
{
Stats::Stats()
{
reset();
}
void Stats::reset()
{
_nb_rows = 0;
_nb_score = 0;
_nb_lvl = 0;
_is_game_over = false;
_initial_lvl = 0;
_text_rows.setFont(Configuration::fonts.get(Configuration::Fonts::Gui));
_text_rows.setString("rows : 0");
_text_rows.setCharacterSize(FONT_SIZE);
_text_rows.setPosition(0,0);
_text_score.setFont(Configuration::fonts.get(Configuration::Gui));
_text_score.setString("score : 0");
_text_score.setCharacterSize(FONT_SIZE);
_text_score.setPosition(0,FONT_SIZE + 1);
_text_lvl.setFont(Configuration::fonts.get(Configuration::Gui));
_text_lvl.setCharacterSize(FONT_SIZE);
_text_lvl.setPosition(0,(FONT_SIZE + 1)*2);
setLevel(0);
_text_game_over.setFont(Configuration::fonts.get(Configuration::Gui));
_text_game_over.setString("Game Over");
_text_game_over.setCharacterSize(72);
_text_game_over.setPosition(0,0);
}
bool Stats::isGameOver()const
{
return _is_game_over;
}
void Stats::setGameOver(bool g)
{
_is_game_over = g;
}
void Stats::setLevel(int lvl)
{
_initial_lvl = lvl;
_text_lvl.setString("lvl : "+std::to_string(lvl));
}
int Stats::getLevel()const
{
return _initial_lvl + _nb_lvl;
}
void Stats::addLines(int lines)
{
if(lines > 0)
{
//update number of lines
_nb_rows += lines;
_text_rows.setString("rows : "+std::to_string(_nb_rows));
//update the score
_text_score.setString("score : "+std::to_string(_nb_score));
switch (lines)
{
case 1 : _nb_score += 40 * ( _initial_lvl+_nb_lvl+1);break;
case 2 : _nb_score += 100 * ( _initial_lvl+_nb_lvl+1);break;
case 3 : _nb_score += 300 * ( _initial_lvl+_nb_lvl+1);break;
default : _nb_score += 1200 * ( _initial_lvl+_nb_lvl+1);break;
}
_nb_lvl = _initial_lvl + (_nb_rows / 10);
//update the lvl
_text_lvl.setString("lvl : "+std::to_string(_nb_lvl));
}
}
unsigned int Stats::getLvl()const
{
return _nb_lvl;
}
void Stats::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
if(not _is_game_over)
{
//make states
states.transform *= getTransform();
//draw
target.draw(_text_rows,states);
target.draw(_text_score,states);
target.draw(_text_lvl,states);
}
else
target.draw(_text_game_over,states);
}
}
| 25.982143 | 80 | 0.564948 | Krozark |
647b799e3c4f615e86414b398073408f20771b30 | 476 | cpp | C++ | Hashing/colorful.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | Hashing/colorful.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | Hashing/colorful.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int colorful(int A) {
vector<int> digits;
while(A) {
digits.push_back(A % 10);
A /= 10;
}
reverse(digits.begin(), digits.end());
unordered_set<int> seen;
for(int i = 0; i < digits.size(); ++i) {
int prd = 1;
for(int j = i; j < digits.size(); ++j) {
prd *= digits[j];
if(seen.find(prd) != seen.end()) {
return 0;
}
else {
seen.insert(prd);
}
}
}
return 1;
}
int main(void) {
} | 14.424242 | 42 | 0.537815 | aneesh001 |
647beafa61b468ae327ee06d91311e250936812c | 445 | hpp | C++ | include/ncurses++/widget.hpp | lukaszgemborowski/ncursesplusplus | e104281812dfe47720a8185fe1351393cf66e366 | [
"MIT"
] | 3 | 2019-12-07T19:54:15.000Z | 2021-01-10T18:38:20.000Z | include/ncurses++/widget.hpp | lukaszgemborowski/ncursesplusplus | e104281812dfe47720a8185fe1351393cf66e366 | [
"MIT"
] | 16 | 2019-12-10T13:46:59.000Z | 2019-12-15T00:39:05.000Z | include/ncurses++/widget.hpp | lukaszgemborowski/ncursesplusplus | e104281812dfe47720a8185fe1351393cf66e366 | [
"MIT"
] | null | null | null | #ifndef NCURSESPP_WIDGET_HPP
#define NCURSESPP_WIDGET_HPP
#include <ncurses++/rect.hpp>
namespace ncursespp
{
template<class Base>
class widget
{
public:
widget() = default;
void resize(rect_i r)
{
static_cast<Base *>(this)->do_resize (r);
size_ = r;
}
constexpr auto size() const
{
return size_;
}
private:
rect_i size_;
};
} // namespace ncursespp
#endif // NCURSESPP_WIDGET_HPP
| 13.484848 | 49 | 0.638202 | lukaszgemborowski |
647f3c18364d461350dcc578c06c138e60b4b202 | 2,240 | cc | C++ | libhashkit/one_at_a_time.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 712 | 2016-07-02T03:32:22.000Z | 2022-03-23T14:23:02.000Z | libhashkit/one_at_a_time.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 294 | 2016-07-03T16:17:41.000Z | 2022-03-30T04:37:49.000Z | libhashkit/one_at_a_time.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 163 | 2016-07-08T10:03:38.000Z | 2022-01-21T05:03:48.000Z | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* HashKit library
*
* Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
* Copyright (C) 2006-2009 Brian Aker All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
This has is Jenkin's "One at A time Hash".
http://en.wikipedia.org/wiki/Jenkins_hash_function
*/
#include <libhashkit/common.h>
uint32_t hashkit_one_at_a_time(const char *key, size_t key_length, void *context)
{
const char *ptr= key;
uint32_t value= 0;
(void)context;
while (key_length--)
{
uint32_t val= (uint32_t) *ptr++;
value += val;
value += (value << 10);
value ^= (value >> 6);
}
value += (value << 3);
value ^= (value >> 11);
value += (value << 15);
return value;
}
| 34.461538 | 81 | 0.716518 | TOT0RoKR |
64809ddbe4a8edde7a892c5098c0a46b18bcc170 | 2,240 | cpp | C++ | libtumbler/test/speaker_test.cpp | FairyDevicesRD/tumbler | e847d9770e7b4d64f3eb936cfcd72e3588176138 | [
"Apache-2.0"
] | 12 | 2018-01-16T01:55:24.000Z | 2021-10-05T21:59:05.000Z | libtumbler/test/speaker_test.cpp | FairyDevicesRD/tumbler | e847d9770e7b4d64f3eb936cfcd72e3588176138 | [
"Apache-2.0"
] | 2 | 2019-04-16T09:21:44.000Z | 2019-07-04T06:57:48.000Z | libtumbler/test/speaker_test.cpp | FairyDevicesRD/tumbler | e847d9770e7b4d64f3eb936cfcd72e3588176138 | [
"Apache-2.0"
] | 4 | 2018-02-22T08:13:07.000Z | 2019-03-13T16:53:21.000Z | /*
* @file speaker_test.cpp
* \~english
* @brief Test for speaker
* \~japanese
* @brief スピーカーテスト
* \~
* @copyright Copyright 2018 Fairy Devices Inc. http://www.fairydevices.jp/
* @copyright Apache License, Version 2.0
* @author Masato Fujino, created on: 2018/02/19
*
* Copyright 2018 Fairy Devices Inc. http://www.fairydevices.jp/
*
* 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 <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <unistd.h>
#include "tumbler/tumbler.h"
#include "tumbler/speaker.h"
std::vector<short> FileReader(const std::string& filename)
{
std::vector<short> filedata;
std::ifstream inputfs(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
if(!inputfs.is_open()){
throw std::runtime_error("FileReader: Could not open file");
}
size_t inputsize = inputfs.tellg();
filedata.resize(inputsize/2);
inputfs.seekg(0, std::ios::beg);
inputfs.read(reinterpret_cast<char*>(&filedata[0]),inputsize);
inputfs.close();
return filedata;
}
int main(int argc, char** argv)
{
using namespace tumbler;
std::vector<short> audio = FileReader("data/test1.raw");
std::vector<short> ad;
for(size_t i=0;i<audio.size();++i){
ad.push_back(audio[i]);
}
for(size_t i=0;i<audio.size();++i){
ad.push_back(audio[i]);
}
for(size_t i=0;i<audio.size();++i){
ad.push_back(audio[i]);
}
{
std::cout << "Initialize ALSA 1" << std::endl;
Speaker& spk = Speaker::getInstance();
std::cout << "Batch Play..." << std::endl;
spk.batchPlay(ad, 44100, 0.05, Speaker::PlayBackMode::overwrite_);
std::cout << "Batch End..." << std::endl;
while(spk.state()){
usleep(1000*100);
}
}
return 0;
}
| 27.654321 | 86 | 0.687054 | FairyDevicesRD |
6481578a08d372f27bd4a5df8390b6eb516a4e2c | 1,906 | cpp | C++ | libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp | tcmaker/ConOnRails | 97656120dbc9a5bf773538e021b768d0515ae333 | [
"Apache-2.0"
] | 1 | 2021-02-07T21:33:42.000Z | 2021-02-07T21:33:42.000Z | libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp | tcmaker/ConOnRails | 97656120dbc9a5bf773538e021b768d0515ae333 | [
"Apache-2.0"
] | null | null | null | libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp | tcmaker/ConOnRails | 97656120dbc9a5bf773538e021b768d0515ae333 | [
"Apache-2.0"
] | null | null | null | #include "rr.h"
#include "v8_try_catch.h"
#include "v8_message.h"
using namespace v8;
namespace {
VALUE TryCatchClass;
TryCatch *unwrap(VALUE self) {
TryCatch *tc = 0;
Data_Get_Struct(self, class TryCatch, tc);
if (RTEST(rb_iv_get(self, "dead"))) {
rb_raise(rb_eScriptError, "out of scope access of %s", RSTRING_PTR(rb_inspect(self)));
return false;
} else {
return tc;
}
}
VALUE Try(int argc, VALUE *argv, VALUE self) {
if (rb_block_given_p()) {
HandleScope scope;
TryCatch tc;
VALUE try_catch = Data_Wrap_Struct(TryCatchClass, 0, 0, &tc);
rb_iv_set(try_catch, "dead", Qfalse);
VALUE result = rb_yield(try_catch);
rb_iv_set(try_catch, "dead", Qtrue);
tc.Reset();
return result;
} else {
return Qnil;
}
}
VALUE HasCaught(VALUE self) {
TryCatch *tc = unwrap(self);
return tc ? rr_v82rb(tc->HasCaught()) : Qnil;
}
VALUE _Exception(VALUE self) {
TryCatch *tc = unwrap(self);
return tc ? rr_v82rb(tc->Exception()) : Qnil;
}
VALUE _StackTrace(VALUE self) {
TryCatch *tc = unwrap(self);
return tc ? rr_v82rb(tc->StackTrace()) : Qnil;
}
VALUE _Message(VALUE self) {
TryCatch *tc = unwrap(self);
return tc ? rr_v82rb(tc->Message()) : Qnil;
}
VALUE CanContinue(VALUE self) {
TryCatch *tc = unwrap(self);
return tc ? rr_v82rb(tc->CanContinue()) : Qnil;
}
}
void rr_init_v8_try_catch() {
TryCatchClass = rr_define_class("TryCatch");
rr_define_singleton_method(TryCatchClass, "try", Try, -1);
rr_define_method(TryCatchClass, "HasCaught", HasCaught, 0);
rr_define_method(TryCatchClass, "Exception", _Exception, 0);
rr_define_method(TryCatchClass, "StackTrace", _StackTrace, 0);
rr_define_method(TryCatchClass, "Message", _Message, 0);
rr_define_method(TryCatchClass, "CanContinue", CanContinue, 0);
}
| 26.84507 | 92 | 0.650052 | tcmaker |