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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58e353a0160167535f5ffddfb4f21c049eec11bc | 9,729 | cpp | C++ | src/coreclr/src/vm/exinfo.cpp | davidsh/runtime | e5274e41fe13a8cfeeb4e87e39a1452cf8968f8c | [
"MIT"
] | 2 | 2020-05-27T10:46:24.000Z | 2020-05-27T10:46:27.000Z | src/coreclr/src/vm/exinfo.cpp | witchakorn1999/runtime | cfd0172f89d237f79c47de51b64d5778c440bbc6 | [
"MIT"
] | 2 | 2020-06-06T09:07:48.000Z | 2020-06-06T09:13:07.000Z | src/coreclr/src/vm/exinfo.cpp | witchakorn1999/runtime | cfd0172f89d237f79c47de51b64d5778c440bbc6 | [
"MIT"
] | 1 | 2020-08-04T14:01:38.000Z | 2020-08-04T14:01:38.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
#include "common.h"
#include "exinfo.h"
#include "dbginterface.h"
#ifndef FEATURE_EH_FUNCLETS
#ifndef DACCESS_COMPILE
//
// Destroy the handle within an ExInfo. This respects the fact that we can have preallocated global handles living
// in ExInfo's.
//
void ExInfo::DestroyExceptionHandle(void)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Never, ever destroy a preallocated exception handle.
if ((m_hThrowable != NULL) && !CLRException::IsPreallocatedExceptionHandle(m_hThrowable))
{
DestroyHandle(m_hThrowable);
}
m_hThrowable = NULL;
}
//
// CopyAndClearSource copies the contents of the given ExInfo into the current ExInfo, then re-initializes the
// given ExInfo.
//
void ExInfo::CopyAndClearSource(ExInfo *from)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
if (GetThread() != NULL) MODE_COOPERATIVE; else MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
#ifdef TARGET_X86
LOG((LF_EH, LL_INFO100, "In ExInfo::CopyAndClearSource: m_dEsp=%08x, %08x <- [%08x], stackAddress = 0x%p <- 0x%p\n",
from->m_dEsp, &(this->m_dEsp), &from->m_dEsp, this->m_StackAddress, from->m_StackAddress));
#endif // TARGET_X86
// If we have a handle to an exception object in this ExInfo already, then go ahead and destroy it before we
// loose it.
DestroyExceptionHandle();
// The stack address is handled differently. Save the original value.
void* stackAddress = this->m_StackAddress;
// Blast the entire record. Note: we're copying the handle from the source ExInfo to this object. That's okay,
// since we're going to clear out the source ExInfo right below this.
memcpy(this, from, sizeof(ExInfo));
// Preserve the stack address. It should never change.
m_StackAddress = stackAddress;
// This ExInfo just took ownership of the handle to the exception object, so clear out that handle in the
// source ExInfo.
from->m_hThrowable = NULL;
// Finally, initialize the source ExInfo.
from->Init();
#ifndef TARGET_UNIX
// Clear the Watson Bucketing information as well since they
// have been transferred over by the "memcpy" above.
from->GetWatsonBucketTracker()->Init();
#endif // TARGET_UNIX
}
void ExInfo::Init()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
m_ExceptionFlags.Init();
m_StackTraceInfo.Init();
m_DebuggerExState.Init();
m_pSearchBoundary = NULL;
STRESS_LOG3(LF_EH, LL_INFO10000, "ExInfo::Init: setting ExInfo:0x%p m_pBottomMostHandler from 0x%p to 0x%p\n",
this, m_pBottomMostHandler, NULL);
m_pBottomMostHandler = NULL;
m_pPrevNestedInfo = NULL;
m_ExceptionCode = 0xcccccccc;
m_pExceptionRecord = NULL;
m_pContext = NULL;
m_pShadowSP = NULL;
m_StackAddress = this;
DestroyExceptionHandle();
m_hThrowable = NULL;
// By default, mark the tracker as not having delivered the first
// chance exception notification
m_fDeliveredFirstChanceNotification = FALSE;
m_pTopMostHandlerDuringSO = NULL;
#if defined(TARGET_X86) && defined(DEBUGGING_SUPPORTED)
m_InterceptionContext.Init();
m_ValidInterceptionContext = FALSE;
#endif //TARGET_X86 && DEBUGGING_SUPPORTED
}
ExInfo::ExInfo()
{
WRAPPER_NO_CONTRACT;
m_hThrowable = NULL;
Init();
#ifndef TARGET_UNIX
// Init the WatsonBucketTracker
m_WatsonBucketTracker.Init();
#endif // TARGET_UNIX
}
//*******************************************************************************
// When we hit an endcatch or an unwind and have nested handler info, either
// 1) we have contained a nested exception and will continue handling the original
// exception
// - or -
// 2) the nested exception was not contained, and was thrown beyond the original
// bounds where the first exception occurred.
//
// The way we can tell this is from the stack pointer. The topmost nested handler is
// installed at the point where the exception occurred. For a nested exception to be
// contained, it must be caught within the scope of any code that is called after
// the nested handler is installed. (remember: after is a lower stack address.)
//
// If it is caught by anything earlier on the stack, it was not contained, and we
// unwind the nested handlers until we get to one that is higher on the stack
// than the esp we will unwind to.
//
// If we still have a nested handler, then we have successfully handled a nested
// exception and should restore the exception settings that we saved so that
// processing of the original exception can continue.
// Otherwise the nested exception has gone beyond where the original exception was
// thrown and therefore replaces the original exception.
//
// We will always remove the current exception info from the chain.
//
void ExInfo::UnwindExInfo(VOID* limit)
{
CONTRACTL
{
NOTHROW; // This function does not throw.
GC_NOTRIGGER;
if (GetThread() != NULL) MODE_COOPERATIVE; else MODE_ANY;
}
CONTRACTL_END;
// We must be in cooperative mode to do the chaining below
#ifdef DEBUGGING_SUPPORTED
// The debugger thread will be using this, even though it has no
// Thread object associated with it.
_ASSERTE((GetThread() != NULL && GetThread()->PreemptiveGCDisabled()) ||
((g_pDebugInterface != NULL) && (g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId())));
#endif // DEBUGGING_SUPPORTED
LOG((LF_EH, LL_INFO100, "UnwindExInfo: unwind limit is 0x%p, prevNested is 0x%p\n", limit, m_pPrevNestedInfo));
ExInfo *pPrevNestedInfo = m_pPrevNestedInfo;
// At first glance, you would think that each nested exception has
// been unwound by it's corresponding NestedExceptionHandler. But that's
// not necessarily the case. The following assertion cannot be made here,
// and the loop is necessary.
//
//_ASSERTE(pPrevNestedInfo == 0 || (DWORD)pPrevNestedInfo >= limit);
//
// Make sure we've unwound any nested exceptions that we're going to skip over.
//
while (pPrevNestedInfo && pPrevNestedInfo->m_StackAddress < limit)
{
STRESS_LOG1(LF_EH, LL_INFO100, "UnwindExInfo: PopExInfo(): popping nested ExInfo at 0x%p\n", pPrevNestedInfo->m_StackAddress);
if (pPrevNestedInfo->m_hThrowable != NULL)
{
pPrevNestedInfo->DestroyExceptionHandle();
}
#ifndef TARGET_UNIX
// Free the Watson bucket details when ExInfo
// is being released
pPrevNestedInfo->GetWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // TARGET_UNIX
pPrevNestedInfo->m_StackTraceInfo.FreeStackTrace();
#ifdef DEBUGGING_SUPPORTED
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->DeleteInterceptContext(pPrevNestedInfo->m_DebuggerExState.GetDebuggerInterceptContext());
}
#endif
// Get the next nested handler detail...
ExInfo* pPrev = pPrevNestedInfo->m_pPrevNestedInfo;
if (pPrevNestedInfo->IsHeapAllocated())
{
delete pPrevNestedInfo;
}
pPrevNestedInfo = pPrev;
}
// either clear the one we're about to copy over or the topmost one
m_StackTraceInfo.FreeStackTrace();
if (pPrevNestedInfo)
{
// found nested handler info that is above the esp restore point so succesfully caught nested
STRESS_LOG2(LF_EH, LL_INFO100, "UnwindExInfo: resetting nested ExInfo to 0x%p stackaddress:0x%p\n", pPrevNestedInfo, pPrevNestedInfo->m_StackAddress);
// Remember if this ExInfo is heap allocated or not.
BOOL isHeapAllocated = pPrevNestedInfo->IsHeapAllocated();
// Copy pPrevNestedInfo to 'this', clearing pPrevNestedInfo in the process.
CopyAndClearSource(pPrevNestedInfo);
if (isHeapAllocated)
{
delete pPrevNestedInfo; // Now delete the old record if we needed to.
}
}
else
{
STRESS_LOG0(LF_EH, LL_INFO100, "UnwindExInfo: clearing topmost ExInfo\n");
// We just do a basic Init of the current top ExInfo here.
Init();
#ifndef TARGET_UNIX
// Init the Watson buckets as well
GetWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // TARGET_UNIX
}
}
#endif // DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
ExInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
// ExInfo is embedded so don't enum 'this'.
OBJECTHANDLE_EnumMemoryRegions(m_hThrowable);
m_pExceptionRecord.EnumMem();
m_pContext.EnumMem();
}
#endif // #ifdef DACCESS_COMPILE
void ExInfo::SetExceptionCode(const EXCEPTION_RECORD *pCER)
{
#ifndef DACCESS_COMPILE
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
_ASSERTE(pCER != NULL);
m_ExceptionCode = pCER->ExceptionCode;
if (IsInstanceTaggedSEHCode(pCER->ExceptionCode) && ::WasThrownByUs(pCER, pCER->ExceptionCode))
{
m_ExceptionFlags.SetWasThrownByUs();
}
else
{
m_ExceptionFlags.ResetWasThrownByUs();
}
#else // DACCESS_COMPILE
// This method is invoked by the X86 version of CLR's exception handler for
// managed code. There is no reason why DAC would be invoking this.
DacError(E_UNEXPECTED);
#endif // !DACCESS_COMPILE
}
#endif // !FEATURE_EH_FUNCLETS
| 31.898361 | 158 | 0.687429 | davidsh |
58e39b090824caa2296db363e3210b40126cde16 | 2,898 | hpp | C++ | include/LightBulbApp/Repositories/TrainingPlanRepository.hpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 5 | 2016-02-04T06:14:42.000Z | 2017-02-06T02:21:43.000Z | include/LightBulbApp/Repositories/TrainingPlanRepository.hpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 41 | 2015-04-15T21:05:45.000Z | 2015-07-09T12:59:02.000Z | include/LightBulbApp/Repositories/TrainingPlanRepository.hpp | domin1101/LightBulb | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | null | null | null | #pragma once
#ifndef _TRAININGPLANREPOSITORY_H_
#define _TRAININGPLANREPOSITORY_H_
// Library includes
#include <vector>
#include <memory>
// Includes
#include "LightBulb/Event/Observable.hpp"
namespace LightBulb
{
class AbstractTrainingPlan;
/**
* \brief All events the training plan repository can throw.
*/
enum TrainingPlanRepositoryEvents : unsigned int
{
/**
* \brief Is thrown if the training plans have been changed.
*/
EVT_TP_CHANGED
};
/**
* \brief A repository which stores all training plans which are currently executed in the LightBulbApp.
*/
class TrainingPlanRepository : public LightBulb::Observable<TrainingPlanRepositoryEvents, TrainingPlanRepository>
{
template <class Archive>
friend void serialize(Archive& archive, TrainingPlanRepository& trainingPlanRepository);
private:
/**
* \brief The training plan storage.
*/
std::vector<std::unique_ptr<AbstractTrainingPlan>> trainingPlans;
public:
/**
* \brief Returns all training plans.
* \return A vector of all training plans.
*/
const std::vector<std::unique_ptr<AbstractTrainingPlan>>& getTrainingPlans() const;
/**
* \brief Returns the index of a given training plan.
* \param trainingPlan The training plan.
* \return The index of the training plan in the training plan storage vector.
*/
int getIndexOfTrainingPlan(const AbstractTrainingPlan& trainingPlan) const;
/**
* \brief Adds a new training plan to the repository.
* \param trainingPlan The new training plan.
*/
void Add(AbstractTrainingPlan* trainingPlan);
/**
* \brief Saves the training plan with the given index as a file.
* \param path The path where to store the file.
* \param trainingPlanIndex The index of the training plan to save.
*/
void save(const std::string& path, int trainingPlanIndex) const;
/**
* \brief Loads a training plan from file and stores it in the repository.
* \param path The path of the file to load.
*/
AbstractTrainingPlan& load(const std::string& path);
/**
* \brief Returns the training plan with the given name.
* \param name The name to search for.
* \return The training plan with the given name.
* \note If no training plan can be found, an exception is thrown.
*/
AbstractTrainingPlan& getByName(const std::string& name) const;
/**
* \brief Sets the name of the training plan with the given index.
* \param trainingPlanIndex The index of the training plan.
* \param newName The new name.
*/
void setTrainingPlanName(int trainingPlanIndex, const std::string& newName);
/**
* \brief Returns if a training plan with the given name exists.
* \param name The name to search for.
* \return True, if a training plan with this name exists.
*/
bool exists(const std::string& name) const;
void clear();
};
}
#include "LightBulbApp/IO/TrainingPlanRepositoryIO.hpp"
#endif
| 31.5 | 114 | 0.722222 | domin1101 |
58e3c50f3103af4afd1da0237a20460b57faf4cc | 831 | cc | C++ | openssl-examples/lib/openssl++/certificate_stack.cc | falk-werner/playground | 501b425d4c8161bdd89ad92b78a4741d81af9acb | [
"MIT"
] | null | null | null | openssl-examples/lib/openssl++/certificate_stack.cc | falk-werner/playground | 501b425d4c8161bdd89ad92b78a4741d81af9acb | [
"MIT"
] | null | null | null | openssl-examples/lib/openssl++/certificate_stack.cc | falk-werner/playground | 501b425d4c8161bdd89ad92b78a4741d81af9acb | [
"MIT"
] | null | null | null | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#include <openssl++/certificate_stack.hpp>
#include <openssl++/exception.hpp>
namespace openssl
{
CertificateStack::CertificateStack()
: stack(sk_X509_new_null())
{
if (nullptr == stack)
{
throw new OpenSSLException("failed to create CertificateStack");
}
}
CertificateStack::~CertificateStack()
{
sk_X509_free(stack);
}
CertificateStack::operator STACK_OF(X509) *()
{
return stack;
}
void CertificateStack::push(X509 * certificate)
{
int rc = sk_X509_push(stack, certificate);
if (0 == rc)
{
throw new OpenSSLException("failed to push certificate to stack");
}
}
}
| 20.775 | 74 | 0.685921 | falk-werner |
58e494b05e6f6f66ea3c8f2bc66f07a8795c3bd9 | 1,889 | cpp | C++ | Source/FishEngine/Component/Rigidbody.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-12-20T02:38:44.000Z | 2018-12-20T02:38:44.000Z | Source/FishEngine/Component/Rigidbody.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | null | null | null | Source/FishEngine/Component/Rigidbody.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-10-25T19:40:22.000Z | 2018-10-25T19:40:22.000Z | #include <FishEngine/Component/Rigidbody.hpp>
#include <FishEngine/Transform.hpp>
#include <FishEngine/GameObject.hpp>
#include <FishEngine/Component/BoxCollider.hpp>
#include <FishEngine/Component/SphereCollider.hpp>
#include <FishEngine/Physics/PhysxAPI.hpp>
using namespace physx;
inline physx::PxVec3 PxVec3(const FishEngine::Vector3& v)
{
return physx::PxVec3(v.x, v.y, v.z);
}
namespace FishEngine
{
void Rigidbody::Initialize(PxShape* shape)
{
auto& px = PhysxWrap::GetInstance();
auto t = GetTransform();
const Vector3& p = t->GetPosition();
const auto& q = t->GetRotation();
m_physxRigidDynamic = px.physics->createRigidDynamic(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
m_physxRigidDynamic->userData = (void*)this;
m_physxRigidDynamic->setMass(m_Mass);
if (shape)
{
m_physxRigidDynamic->attachShape(*shape);
shape->release();
}
}
void Rigidbody::Start()
{
auto& px = PhysxWrap::GetInstance();
Collider* collider = GetGameObject()->GetComponent<Collider>();
if (collider != nullptr)
Initialize(collider->GetPhysicsShape());
else
Initialize(nullptr);
auto t = GetTransform();
const Vector3 p = t->GetPosition();
const auto& q = t->GetRotation();
m_physxRigidDynamic->setGlobalPose(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
PxRigidBodyExt::updateMassAndInertia(*m_physxRigidDynamic, 10.0f);
m_physxRigidDynamic->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_UseGravity);
px.scene->addActor(*m_physxRigidDynamic);
}
void Rigidbody::Update()
{
const auto& t = m_physxRigidDynamic->getGlobalPose();
GetTransform()->SetPosition(t.p.x, t.p.y, t.p.z);
GetTransform()->SetRotation(Quaternion(t.q.x, t.q.y, t.q.z, t.q.w));
}
void Rigidbody::OnDestroy()
{
m_physxRigidDynamic = nullptr;
}
bool Rigidbody::IsInitialized() const
{
return m_physxRigidDynamic != nullptr;
}
}
| 27.376812 | 111 | 0.712546 | yushroom |
58e7c849efc2e4c6af1e6793bc4ed54321b23997 | 6,475 | cc | C++ | wasp_exec/src/waspexecutor.cc | tuloski/wasp_exec | 00ac1e3d00e974c380a9d498a346b50996bee2e7 | [
"MIT"
] | null | null | null | wasp_exec/src/waspexecutor.cc | tuloski/wasp_exec | 00ac1e3d00e974c380a9d498a346b50996bee2e7 | [
"MIT"
] | null | null | null | wasp_exec/src/waspexecutor.cc | tuloski/wasp_exec | 00ac1e3d00e974c380a9d498a346b50996bee2e7 | [
"MIT"
] | null | null | null | #include "ros/ros.h"
#include <boost/thread.hpp>
#include "std_msgs/String.h"
#include <iostream>
#include <sstream>
#include <queue>
#include "lrs_msgs_tst/ConfirmReq.h"
#include "mms_msgs/Cmd.h"
#include "lrs_srvs_exec/TSTCreateExecutor.h"
#include "lrs_msgs_tst/OperatorRequest.h"
#include "executors/flyto.h"
#include "executors/takeoff.h"
#include "executors/land.h"
#include "executors/takepictures.h"
#include "executors/scangroundsingle.h"
#include "executors/rotateyaw.h"
#include "executors/leashing.h"
#include "executors/start_data_stream.h"
#include "executors/stop_data_stream.h"
#include "executors/operator_control.h"
#include "executors/inairgoal.h"
#include "executors/inairtest.h"
#include "guidance_node_amsl/Reference.h"
#include "executil.h"
std::map<std::string, Executor *> execmap;
std::map<std::string, boost::thread *> threadmap;
ros::NodeHandle * global_nh;
ros::Publisher * global_confirm_pub;
ros::Publisher * global_tell_operator_content_pub;
ros::Publisher * global_tell_operator_content_pub_proxy;
ros::Publisher * global_cmd_pub;
int16_t global_seq = 1;
//reference_class global_last_reference;
guidance_node_amsl::Reference latest_reference;
boost::mutex mutex;
boost::mutex seq_mutex; //mutex to handle shared variable seq
boost::mutex ref_mutex; //mutex to handle shared class reference_class
boost::mutex thread_map_lock;
using namespace std;
void callbackReference(const guidance_node_amsl::Reference::ConstPtr& msg){
{
boost::mutex::scoped_lock lock(ref_mutex);
//ROS_INFO ("WaspExecutor::Received Reference: %d - %d",msg->Latitude, msg->Longitude);
latest_reference.Latitude = msg->Latitude;
latest_reference.Longitude = msg->Longitude;
latest_reference.AltitudeRelative = msg->AltitudeRelative;
latest_reference.Yawangle = msg->Yawangle;
latest_reference.frame = msg->frame;
}
}
bool create_executor (lrs_srvs_exec::TSTCreateExecutor::Request &req,
lrs_srvs_exec::TSTCreateExecutor::Response &res ) {
boost::mutex::scoped_lock lock(mutex);
ROS_INFO("quadexecutor: create_executor: %s %d - %d", req.ns.c_str(), req.id, req.run_prepare);
ostringstream os;
os << req.ns << "-" << req.id;
if (execmap.find (os.str()) != execmap.end()) {
ROS_INFO ("Executor already exists, overwrites it: %s %d", req.ns.c_str(), req.id);
}
string type = get_node_type (req.ns, req.id);
bool found = false;
Executor * cres = check_exec(type, req.ns, req.id);
if (cres) {
execmap[os.str()] = cres;
found = true;
}
if (type == "fly-to") {
execmap[os.str()] = new Exec::FlyTo (req.ns, req.id);
found = true;
}
if (type == "take-off") {
execmap[os.str()] = new Exec::TakeOff (req.ns, req.id);
found = true;
}
if (type == "land") {
execmap[os.str()] = new Exec::Land (req.ns, req.id);
found = true;
}
if (type == "take-pictures") {
execmap[os.str()] = new Exec::TakePictures (req.ns, req.id);
found = true;
}
if (type == "scan-ground-single") {
execmap[os.str()] = new Exec::ScanGroundSingle (req.ns, req.id);
found = true;
}
if (type == "yaw") {
execmap[os.str()] = new Exec::RotateYaw (req.ns, req.id);
found = true;
}
if (type == "leashing") {
execmap[os.str()] = new Exec::Leashing (req.ns, req.id);
found = true;
}
/*if (type == "stop-data-stream") { ///FUCKING IMPOSSIBLE ERROR ON THIS
execmap[os.str()] = new Exec::StopDataStream (req.ns, req.id);
found = true;
}*/
if (type == "start-data-stream") {
execmap[os.str()] = new Exec::StartDataStream (req.ns, req.id);
found = true;
}
if (type == "operator-control") {
execmap[os.str()] = new Exec::OperatorControl (req.ns, req.id);
found = true;
}
if (type == "in-air-goal") {
execmap[os.str()] = new Exec::InAirGoal (req.ns, req.id);
found = true;
}
if (type == "in-air-test") {
execmap[os.str()] = new Exec::InAirTest (req.ns, req.id);
found = true;
}
if (found) {
res.success = true;
res.error = 0;
if (req.run_prepare) {
bool prep = execmap[os.str()]->prepare ();
if (!prep) {
res.success = false;
res.error = 2;
}
}
} else {
ROS_ERROR ("Could not create executor of type: %s", type.c_str());
res.success = false;
res.error = 1;
}
return true;
}
int main(int argc, char **argv) {
ros::init(argc, argv, "waspexecutor");
ros::NodeHandle n;
global_nh = &n;
ros::Publisher confirm_pub = n.advertise<lrs_msgs_tst::ConfirmReq>("confirm_request", 1, true); // queue size 1 and latched
global_confirm_pub = &confirm_pub;
ros::Publisher content_pub = n.advertise<lrs_msgs_tst::OperatorRequest>("/operator", 1);
ros::Publisher content_pub_proxy = n.advertise<lrs_msgs_tst::OperatorRequest>("/operator_proxy", 1);
global_tell_operator_content_pub = &content_pub;
global_tell_operator_content_pub_proxy = &content_pub_proxy;
ros::Publisher cmd_pub = n.advertise<mms_msgs::Cmd>("sent_command", 10); // command topic
global_cmd_pub = &cmd_pub;
ros::Subscriber reference_sub; //subscriber to reference topic
reference_sub = n.subscribe("reference", 10, callbackReference);
std::vector<ros::ServiceServer> services;
std::string prefix = "tst_executor/";
services.push_back (n.advertiseService(prefix + "destroy_executor", destroy_executor));
services.push_back (n.advertiseService(prefix + "create_executor", create_executor));
services.push_back (n.advertiseService(prefix + "executor_check", executor_check));
services.push_back (n.advertiseService(prefix + "executor_continue", executor_continue));
services.push_back (n.advertiseService(prefix + "executor_expand", executor_expand));
services.push_back (n.advertiseService(prefix + "executor_is_delegation_expandable", executor_is_delegation_expandable));
services.push_back (n.advertiseService(prefix + "executor_request_pause", executor_request_pause));
services.push_back (n.advertiseService(prefix + "executor_get_constraints", executor_get_constraints));
services.push_back (n.advertiseService(prefix + "start_executor", start_executor));
services.push_back (n.advertiseService(prefix + "abort_executor", abort_executor));
services.push_back (n.advertiseService(prefix + "pause_executor", pause_executor));
services.push_back (n.advertiseService(prefix + "continue_executor", continue_executor));
services.push_back (n.advertiseService(prefix + "enough_executor", enough_executor));
ROS_INFO("Ready to be an executor factory");
ros::spin();
return 0;
}
| 32.375 | 125 | 0.707181 | tuloski |
58ea53943e8075e73f722610a62f77ff657ad16a | 1,446 | hpp | C++ | cho_util/vis/vtk_viewer/include/cho_util/vis/vtk_viewer/handler/poly_point_source.hpp | yycho0108/ChoUtils | ce701d4c7bb21c6b17e218d584ad68bbb63fba0a | [
"MIT"
] | null | null | null | cho_util/vis/vtk_viewer/include/cho_util/vis/vtk_viewer/handler/poly_point_source.hpp | yycho0108/ChoUtils | ce701d4c7bb21c6b17e218d584ad68bbb63fba0a | [
"MIT"
] | null | null | null | cho_util/vis/vtk_viewer/include/cho_util/vis/vtk_viewer/handler/poly_point_source.hpp | yycho0108/ChoUtils | ce701d4c7bb21c6b17e218d584ad68bbb63fba0a | [
"MIT"
] | null | null | null | #pragma once
#include <vtkPolyDataAlgorithm.h>
class vtkPoints;
class vtkUnsignedCharArray;
namespace cho {
namespace vis {
/**
* @brief Adaptation of vtkPolyPointSource that also enables vertex-wise color
* assignment.
*/
class ColoredPolyPointSource : public vtkPolyDataAlgorithm {
public:
vtkTypeMacro(ColoredPolyPointSource, vtkPolyDataAlgorithm);
static ColoredPolyPointSource* New();
void PrintSelf(ostream& os, vtkIndent indent) override;
void SetNumberOfPoints(vtkIdType numPoints);
vtkIdType GetNumberOfPoints();
void SetNumberOfColors(vtkIdType numPoints);
vtkIdType GetNumberOfColors();
// Since resize is ambiguous (what should the color be?),
// just explicitly call SetNumberOf{Points|Colors}.
// void Resize(vtkIdType numPoints);
vtkMTimeType GetMTime() override;
void SetPoints(vtkPoints* points);
vtkGetObjectMacro(Points, vtkPoints);
void SetColors(vtkUnsignedCharArray* colors);
vtkGetObjectMacro(Colors, vtkUnsignedCharArray);
protected:
ColoredPolyPointSource();
~ColoredPolyPointSource() override;
int RequestData(vtkInformation*, vtkInformationVector**,
vtkInformationVector*) override;
vtkSmartPointer<vtkUnsignedCharArray> Colors;
vtkSmartPointer<vtkPoints> Points;
private:
ColoredPolyPointSource(const ColoredPolyPointSource&) = delete;
void operator=(const ColoredPolyPointSource&) = delete;
};
} // namespace vis
} // namespace cho
| 25.821429 | 78 | 0.771093 | yycho0108 |
58ebde0ceaa882d8d5f0035f5039c41409d992aa | 524 | cpp | C++ | Easing/PolygonEquation.cpp | DiegoSLTS/EasingFunctions | 38951f19a3069c9ac20aee482dfe1f8c0953408d | [
"MIT"
] | null | null | null | Easing/PolygonEquation.cpp | DiegoSLTS/EasingFunctions | 38951f19a3069c9ac20aee482dfe1f8c0953408d | [
"MIT"
] | null | null | null | Easing/PolygonEquation.cpp | DiegoSLTS/EasingFunctions | 38951f19a3069c9ac20aee482dfe1f8c0953408d | [
"MIT"
] | null | null | null | #include "PolygonEquation.h"
#include <math.h>
PolygonEquation::PolygonEquation(int grade) : grade(grade) {}
PolygonEquation::~PolygonEquation() {}
double PolygonEquation::Evaluate() const {
float temp = GetTime();
switch(this->ease) {
case EasingType::IN:
return pow(temp, grade);
case EasingType::OUT:
return 1 - pow(1 - temp, grade);
case EasingType::IN_OUT:
if (temp < 0.5)
return pow(temp, grade) * (1 << (grade - 1));
return 1 - pow(1 - temp, grade) * (1 << (grade - 1));
default:
return 0;
}
}
| 22.782609 | 61 | 0.652672 | DiegoSLTS |
58ef2e13fb05b3a6506e4dd43ff1752365fc36cd | 1,271 | cc | C++ | src/base/tests/Exception_unittest.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | 2 | 2019-07-15T08:34:38.000Z | 2019-08-07T12:27:23.000Z | src/base/tests/Exception_unittest.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | src/base/tests/Exception_unittest.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | /*
* @Author: py.wang
* @Date: 2019-06-06 17:19:02
* @Last Modified by: py.wang
* @Last Modified time: 2019-06-06 18:34:59
*/
#include "src/base/Exception.h"
#include "src/base/CurrentThread.h"
#include <vector>
#include <string>
#include <functional>
#include <stdio.h>
class Bar
{
public:
void test(std::vector<std::string> names = {})
{
printf("Stack: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
// lambda
[] {
printf("Stack inside lambda: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
} ();
// function
std::function<void ()> func([] {
printf("Stack inside function: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
});
func();
func = std::bind(&Bar::callback, this);
func();
throw slack::Exception("oops");
}
private:
void callback()
{
printf("Stack inside std::bind: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
}
};
void foo()
{
Bar b;
b.test();
}
int main()
{
try
{
foo();
}
catch (const slack::Exception &ex)
{
printf("reason: %s\n", ex.what());
printf("stack trace: \n%s\n", ex.stackTrace());
}
}
| 19.859375 | 100 | 0.543666 | plantree |
58efcb8552b7f549b1bf3d88b2254a589dbcb3f7 | 22,079 | cpp | C++ | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/StackRestorer.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/StackRestorer.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/StackRestorer.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------------------------
// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome).
// All rights reserved.
//------------------------------------------------------------------------------------------------
/*******************************************************************************************************************************************************************************************
* LICENSE NOTICE
********************************************************************************************************************************************************************************************
* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change
* this code.
********************************************************************************************************************************************************************************************
* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at
* g.iannello@unicampus.it for further details.
* 2. You agree to appropriately cite this work in your related studies and publications.
*
* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316.
*
* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war-
* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the
* copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil-
* ity, 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.
* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without
* specific prior written permission.
********************************************************************************************************************************************************************************************/
#include "StackRestorer.h"
#include "vmVirtualStack.h"
#include <fstream>
#include "S_config.h"
using namespace volumemanager;
StackRestorer::StackRestorer(VirtualVolume* stk_org)
{
this->STK_ORG = stk_org;
N_ROWS = stk_org->getN_ROWS();
N_COLS = stk_org->getN_COLS();
this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS];
for(int i=0; i < N_ROWS; i++)
STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS];
this->SUBSTKS_DESCRIPTORS = NULL;
}
StackRestorer::StackRestorer(VirtualVolume* stk_org, char* file_path)
{
this->STK_ORG = stk_org;
N_ROWS = stk_org->getN_ROWS();
N_COLS = stk_org->getN_COLS();
this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS];
for(int i=0; i < N_ROWS; i++)
STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS];
this->SUBSTKS_DESCRIPTORS = NULL;
load(file_path);
}
StackRestorer::StackRestorer(VirtualVolume* stk_org, int D_subvols)
{
this->STK_ORG = stk_org;
N_ROWS = stk_org->getN_ROWS();
N_COLS = stk_org->getN_COLS();
this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS];
for(int i=0; i < N_ROWS; i++)
STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS];
SD_DIM_i = N_ROWS;
SD_DIM_j = N_COLS;
SD_DIM_k = D_subvols;
this->SUBSTKS_DESCRIPTORS = new vol_descr_t**[SD_DIM_i];
for(int i=0; i < SD_DIM_i; i++)
{
SUBSTKS_DESCRIPTORS[i] = new vol_descr_t *[SD_DIM_j];
for(int j=0; j < SD_DIM_j; j++)
SUBSTKS_DESCRIPTORS[i][j] = new vol_descr_t[SD_DIM_k];
}
}
StackRestorer::~StackRestorer(void)
{
if(SUBSTKS_DESCRIPTORS)
{
for(int i=0; i < SD_DIM_i; i++)
{
for(int j=0; j < SD_DIM_j; j++)
delete[] SUBSTKS_DESCRIPTORS[i][j];
delete[] SUBSTKS_DESCRIPTORS[i];
}
delete[] SUBSTKS_DESCRIPTORS;
}
if(STKS_DESCRIPTORS)
{
for(int i=0; i < N_ROWS; i++)
delete[] STKS_DESCRIPTORS[i];
delete[] STKS_DESCRIPTORS;
}
}
void StackRestorer::computeSubvolDescriptors(iom::real_t* data, VirtualStack* stk_p, int subvol_idx, int subvol_D_dim) throw (iom::exception)
{
int i = stk_p->getROW_INDEX();
int j = stk_p->getCOL_INDEX();
SUBSTKS_DESCRIPTORS[i][j][subvol_idx].init(stk_p, true, stk_p->getHEIGHT(), stk_p->getWIDTH(), subvol_D_dim);
SUBSTKS_DESCRIPTORS[i][j][subvol_idx].computeSubvolDescriptors(data);
}
void StackRestorer::computeStackDescriptors(VirtualStack* stk_p) throw (iom::exception)
{
int i = stk_p->getROW_INDEX();
int j = stk_p->getCOL_INDEX();
if(!SUBSTKS_DESCRIPTORS || !SUBSTKS_DESCRIPTORS[i] || !SUBSTKS_DESCRIPTORS[i][j])
{
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::computeStackDescriptors(VirtualStack[%d,%d]): no computed subvol descriptors found.\n", i, j);
throw iom::exception(err_msg);
}
int D_dim_acc = 0;
for(int k=0; k< SD_DIM_k; k++)
if(SUBSTKS_DESCRIPTORS[i][j][k].isSubvolDescriptor() && SUBSTKS_DESCRIPTORS[i][j][k].isFinalized())
D_dim_acc+= SUBSTKS_DESCRIPTORS[i][j][k].D_dim;
else
{
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::computeStackDescriptors(VirtualStack[%d,%d]): no computed subvol descriptors found.\n", i, j);
throw iom::exception(err_msg);
}
STKS_DESCRIPTORS[i][j].init(SUBSTKS_DESCRIPTORS[i][j][0].stk_p, false, SUBSTKS_DESCRIPTORS[i][j][0].V_dim, SUBSTKS_DESCRIPTORS[i][j][0].H_dim, D_dim_acc);
STKS_DESCRIPTORS[i][j].computeStackDescriptors(SUBSTKS_DESCRIPTORS[i][j], SD_DIM_k);
}
void StackRestorer::finalizeAllDescriptors()
{
for(int i=0; i<N_ROWS; i++)
for(int j=0; j<N_COLS; j++)
computeStackDescriptors(STK_ORG->getSTACKS()[i][j]);
}
void StackRestorer::printSubvolDescriptors(VirtualStack* stk_p, int subvol_idx)
{
int i = stk_p->getROW_INDEX();
int j = stk_p->getCOL_INDEX();
SUBSTKS_DESCRIPTORS[i][j][subvol_idx].print();
}
void StackRestorer::printVolDescriptors(VirtualStack* stk_p)
{
int i = stk_p->getROW_INDEX();
int j = stk_p->getCOL_INDEX();
STKS_DESCRIPTORS[i][j].print();
}
void StackRestorer::save(char* file_path) throw (iom::exception)
{
if(STKS_DESCRIPTORS)
{
//some checks
bool ready_to_save = true;
for(int i=0; i<N_ROWS && ready_to_save; i++)
for(int j=0; j<N_COLS && ready_to_save; j++)
ready_to_save = (!STKS_DESCRIPTORS[i][j].isSubvolDescriptor()) && STKS_DESCRIPTORS[i][j].isFinalized();
if(!ready_to_save)
{
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::save(file_path[%s]): VirtualStack descriptors not found.\n", file_path);
throw iom::exception(err_msg);
}
//saving procedure
std::ofstream file(file_path, std::ios::out | std::ios::binary);
//int ID = STK_ORG->getID();
//file.write((char*)&ID, sizeof(int));
file.write((char*)&N_ROWS, sizeof(int));
file.write((char*)&N_COLS, sizeof(int));
for(int i=0; i<N_ROWS; i++)
for(int j=0; j<N_COLS; j++)
{
file.write((char*)&(STKS_DESCRIPTORS[i][j].max_val), sizeof(iom::real_t));
file.write((char*)&(STKS_DESCRIPTORS[i][j].mean_val), sizeof(iom::real_t));
file.write((char*)&(STKS_DESCRIPTORS[i][j].V_dim), sizeof(int));
file.write((char*)&(STKS_DESCRIPTORS[i][j].H_dim), sizeof(int));
file.write((char*)&(STKS_DESCRIPTORS[i][j].D_dim), sizeof(int));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].V_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].V_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].H_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].H_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].D_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].D_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].V_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].V_MIP[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].H_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].H_MIP[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].D_dim; ii++)
file.write((char*)&(STKS_DESCRIPTORS[i][j].D_MIP[ii]), sizeof(iom::real_t));
}
file.close();
}
else
{
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::save(file_path[%s]): VirtualStack descriptors not found.\n", file_path);
throw iom::exception(err_msg);
}
}
void StackRestorer::load(char* file_path) throw (iom::exception)
{
std::ifstream file (file_path, std::ios::in | std::ios::binary);
if(!file)
{
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::load(file_path[%s]): unable to load given file.\n", file_path);
throw iom::exception(err_msg);
}
int new_N_ROWS=-1, new_N_COLS=-1;
file.read((char*)&new_N_ROWS, sizeof(int));
file.read((char*)&new_N_COLS, sizeof(int));
if(new_N_ROWS != N_ROWS || new_N_COLS != N_COLS)
{
file.close();
char err_msg[1000];
sprintf(err_msg, "in StackRestorer::load(file_path[%s]): the description file refers to a different acquisition.\n", file_path);
throw iom::exception(err_msg);
}
for(int i=0; i<N_ROWS; i++)
for(int j=0; j<N_COLS; j++)
{
file.read((char*)&(STKS_DESCRIPTORS[i][j].max_val), sizeof(iom::real_t));
file.read((char*)&(STKS_DESCRIPTORS[i][j].mean_val), sizeof(iom::real_t));
file.read((char*)&(STKS_DESCRIPTORS[i][j].V_dim), sizeof(int));
file.read((char*)&(STKS_DESCRIPTORS[i][j].H_dim), sizeof(int));
file.read((char*)&(STKS_DESCRIPTORS[i][j].D_dim), sizeof(int));
STKS_DESCRIPTORS[i][j].stk_p=STK_ORG->getSTACKS()[i][j];
STKS_DESCRIPTORS[i][j].V_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].V_dim];
STKS_DESCRIPTORS[i][j].H_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].H_dim];
STKS_DESCRIPTORS[i][j].D_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].D_dim];
STKS_DESCRIPTORS[i][j].V_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].V_dim];
STKS_DESCRIPTORS[i][j].H_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].H_dim];
STKS_DESCRIPTORS[i][j].D_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].D_dim];
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].V_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].V_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].H_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].H_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].D_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].D_profile[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].V_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].V_MIP[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].H_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].H_MIP[ii]), sizeof(iom::real_t));
for(int ii=0; ii<STKS_DESCRIPTORS[i][j].D_dim; ii++)
file.read((char*)&(STKS_DESCRIPTORS[i][j].D_MIP[ii]), sizeof(iom::real_t));
STKS_DESCRIPTORS[i][j].is_subvol_descriptor = false;
STKS_DESCRIPTORS[i][j].is_finalized = true;
}
file.close();
}
void StackRestorer::repairSlice(iom::real_t* data, int slice_idx, VirtualStack* stk_p, int direction) throw (iom::exception)
{
//some checks
bool ready_to_repair = true;
for(int i=0; i<N_ROWS && ready_to_repair; i++)
for(int j=0; j<N_COLS && ready_to_repair; j++)
ready_to_repair = STKS_DESCRIPTORS && (!STKS_DESCRIPTORS[i][j].isSubvolDescriptor()) && STKS_DESCRIPTORS[i][j].isFinalized();
if(!ready_to_repair)
{
char err_msg[1000];
sprintf(err_msg, "in repairSlice::repairSlice(...): VirtualStack descriptors not found.\n");
throw iom::exception(err_msg);
}
if(direction != S_RESTORE_V_DIRECTION && direction != S_RESTORE_H_DIRECTION)
{
char err_msg[1000];
sprintf(err_msg, "in repairSlice::repairSlice(...): selected restoring direction (%d) is not supported.\n", direction);
throw iom::exception(err_msg);
}
int i, j;
iom::real_t *p_scanpxl = data;
iom::real_t max_val = 0;
iom::real_t corr_fact;
int row = stk_p->getROW_INDEX();
int col = stk_p->getCOL_INDEX();
int v_dim = stk_p->getHEIGHT();
int h_dim = stk_p->getWIDTH();
vol_descr_t *vol_desc = &(STKS_DESCRIPTORS[row][col]);
iom::real_t *V_profile = vol_desc->V_profile;
iom::real_t *H_profile = vol_desc->H_profile;
iom::real_t *V_MIP = vol_desc->V_MIP;
iom::real_t *H_MIP = vol_desc->H_MIP;
switch ( direction )
{
case S_RESTORE_V_DIRECTION:
{
//correct pixels
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) /= V_profile[i];
//computing new max_val
for ( i=0; i<v_dim; i++ )
if(V_MIP[i] / V_profile[i] > max_val)
max_val = V_MIP[i] / V_profile[i];
break;
}
case S_RESTORE_H_DIRECTION:
{
//correct pixels
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) /= H_profile[j];
//computing new max_val
for ( i=0; i<h_dim; i++ )
if(H_MIP[i] / H_profile[i] > max_val)
max_val = H_MIP[i] / H_profile[i];
break;
}
}
// rescale VirtualStack
corr_fact = ISR_MIN((vol_desc->mean_val),(1 / max_val));
p_scanpxl = data;
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) *= corr_fact;
#ifdef S_RESTORE_VZ
iom::real_t *D_profile = vol_desc->D_profile;
p_scanpxl = data;
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) = ((*p_scanpxl)/D_profile[slice_idx])*vol_desc->mean_val;
#endif
}
void StackRestorer::repairStack(iom::real_t* data, VirtualStack* stk_p, int direction) throw (iom::exception)
{
//some checks
bool ready_to_repair = true;
for(int i=0; i<N_ROWS && ready_to_repair; i++)
for(int j=0; j<N_COLS && ready_to_repair; j++)
ready_to_repair = STKS_DESCRIPTORS && (!STKS_DESCRIPTORS[i][j].isSubvolDescriptor()) && STKS_DESCRIPTORS[i][j].isFinalized();
if(!ready_to_repair)
{
char err_msg[1000];
sprintf(err_msg, "in repairSlice::repairStack(...): VirtualStack descriptors not found.\n");
throw iom::exception(err_msg);
}
if(direction != S_RESTORE_V_DIRECTION && direction != S_RESTORE_H_DIRECTION)
{
char err_msg[1000];
sprintf(err_msg, "in repairSlice::repairSlice(...): selected restoring direction (%d) is not supported.\n", direction);
throw iom::exception(err_msg);
}
int i, j, k;
iom::real_t *p_scanpxl=0;
iom::real_t max_val = 0;
iom::real_t corr_fact;
int row = stk_p->getROW_INDEX();
int col = stk_p->getCOL_INDEX();
int v_dim = stk_p->getHEIGHT();
int h_dim = stk_p->getWIDTH();
int d_dim = stk_p->getDEPTH();
vol_descr_t *vol_desc = &(STKS_DESCRIPTORS[row][col]);
iom::real_t *V_profile = vol_desc->V_profile;
iom::real_t *H_profile = vol_desc->H_profile;
iom::real_t *V_MIP = vol_desc->V_MIP;
iom::real_t *H_MIP = vol_desc->H_MIP;
switch ( direction )
{
case S_RESTORE_V_DIRECTION:
{
//correct pixels
for( k=0; k<d_dim; k++)
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) /= V_profile[i];
//computing new max_val
for(int k=0; k<d_dim; k++)
for ( i=0; i<v_dim; i++ )
if(V_MIP[i] / V_profile[i] > max_val)
max_val = V_MIP[i] / V_profile[i];
break;
}
case S_RESTORE_H_DIRECTION:
{
//correct pixels
for( k=0; k<d_dim; k++)
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) /= H_profile[j];
//computing new max_val
for(int k=0; k<d_dim; k++)
for ( i=0; i<h_dim; i++ )
if(H_MIP[i] / H_profile[i] > max_val)
max_val = H_MIP[i] / H_profile[i];
break;
}
}
// rescale VirtualStack
corr_fact = ISR_MIN((vol_desc->mean_val),(1 / max_val));
p_scanpxl = data;
for( k=0; k<d_dim; k++)
for ( i=0; i<v_dim; i++ )
for ( j=0; j<h_dim; j++, p_scanpxl++ )
(*p_scanpxl) *= corr_fact;
}
/******************************************************
********** SUBSTACK_DESCR_T DEFINITIONS **************
******************************************************/
StackRestorer::vol_descr_t::vol_descr_t()
{
this->stk_p = NULL;
this->max_val = 0;
this->mean_val = 0;
this->V_dim = -1;
this->H_dim = -1;
this->D_dim = -1;
this->V_profile = NULL;
this->H_profile = NULL;
this->D_profile = NULL;
this->V_MIP = NULL;
this->H_MIP = NULL;
this->D_MIP = NULL;
this->is_subvol_descriptor = false;
this->is_finalized = false;
}
void StackRestorer::vol_descr_t::init(VirtualStack *new_stk_p, bool is_subvol_desc, int new_V_dim, int new_H_dim, int new_D_dim)
{
this->stk_p = new_stk_p;
this->V_dim = new_V_dim;
this->H_dim = new_H_dim;
this->D_dim = new_D_dim;
this->V_profile = new iom::real_t[V_dim];
this->H_profile = new iom::real_t[H_dim];
this->D_profile = new iom::real_t[D_dim];
this->V_MIP = new iom::real_t[V_dim];
this->H_MIP = new iom::real_t[H_dim];
this->D_MIP = new iom::real_t[D_dim];
this->is_subvol_descriptor = is_subvol_desc;
}
StackRestorer::vol_descr_t::~vol_descr_t()
{
if(V_profile)
delete[] V_profile;
if(H_profile)
delete[] H_profile;
if(D_profile)
delete[] D_profile;
if(V_MIP)
delete[] V_MIP;
if(H_MIP)
delete[] H_MIP;
if(D_MIP)
delete[] D_MIP;
}
void StackRestorer::vol_descr_t::computeSubvolDescriptors(iom::real_t *subvol) throw (iom::exception)
{
//initialization of MIPs and profiles
for(int i=0; i<V_dim; i++)
V_MIP[i] = V_profile[i] = 0;
for(int j=0; j<H_dim; j++)
H_MIP[j] = H_profile[j] = 0;
for(int k=0; k<D_dim; k++)
D_MIP[k] = D_profile[k] = 0;
//one-shot computing of accumulation profiles and MIPs
iom::real_t *p_scanpxl = subvol;
iom::real_t val;
for ( int k=0; k<D_dim; k++ )
for ( int i=0; i<V_dim; i++ )
for ( int j=0; j<H_dim; j++, p_scanpxl++ )
{
val = *p_scanpxl;
//accumulations
V_profile[i] += val;
H_profile[j] += val;
D_profile[k] += val;
//maximum selection for maximum intensity projections
if(val > V_MIP[i])
V_MIP[i] = val;
if(val > H_MIP[j])
H_MIP[j] = val;
if(val > D_MIP[k])
D_MIP[k] = val;
}
//computing max value as the maximum of maxs
for(int i=0; i<V_dim; i++)
if(V_MIP[i] > max_val)
max_val = V_MIP[i];
for(int j=0; j<H_dim; j++)
if(H_MIP[j] > max_val)
max_val = H_MIP[j];
for(int k=0; k<D_dim; k++)
if(D_MIP[k] > max_val)
max_val = D_MIP[k];
this->is_finalized = true;
}
void StackRestorer::vol_descr_t::computeStackDescriptors(vol_descr_t *subvol_desc, int D_subvols) throw (iom::exception)
{
//initialization of MIPs and profiles (that are mean intensity projections)
for(int i=0; i<V_dim; i++)
V_MIP[i] = V_profile[i] = 0;
for(int j=0; j<H_dim; j++)
H_MIP[j] = H_profile[j] = 0;
for(int k=0; k<D_dim; k++)
D_MIP[k] = D_profile[k] = 0;
//one-shot computing of accumulation profiles and MIPs
int d_acc=0;
for(int k=0; k<D_subvols; k++)
{
for(int i=0; i<V_dim; i++)
{
V_profile[i]+=subvol_desc[k].V_profile[i];
if(subvol_desc[k].V_MIP[i] > V_MIP[i])
V_MIP[i] = subvol_desc[k].V_MIP[i];
}
for(int j=0; j<H_dim; j++)
{
H_profile[j]+=subvol_desc[k].H_profile[j];
if(subvol_desc[k].H_MIP[j] > H_MIP[j])
H_MIP[j] = subvol_desc[k].H_MIP[j];
}
for(int kk=d_acc; kk<d_acc+subvol_desc[k].D_dim; kk++)
{
D_profile[kk] = subvol_desc[k].D_profile[kk-d_acc];
D_MIP[kk] = subvol_desc[k].D_MIP[kk-d_acc];
}
d_acc+=subvol_desc[k].D_dim;
}
//refining mean intensity projections
for ( int i=0; i<V_dim; i++ )
{
mean_val+=V_profile[i];
V_profile[i] /= D_dim*H_dim;
if ( V_profile[i] == 0 )
V_profile[i] = S_MIN_PROF_VAL;
}
for ( int j=0; j<H_dim; j++ )
{
H_profile[j] /= D_dim*V_dim;
if ( H_profile[j] == 0 )
H_profile[j] = S_MIN_PROF_VAL;
}
for ( int k=0; k<D_dim; k++ )
{
D_profile[k] /= V_dim*H_dim;
if ( D_profile[k] == 0 )
D_profile[k] = S_MIN_PROF_VAL;
}
//computing mean value
mean_val /= (D_dim*H_dim*V_dim);
//computing max value as the maximum of maxs
for(int k=0; k<D_subvols; k++)
if(subvol_desc[k].max_val > max_val)
max_val = subvol_desc[k].max_val;
this->is_finalized = true;
}
void StackRestorer::vol_descr_t::print()
{
printf("\tvol_decr[%d,%d] PRINTING:\n", stk_p->getROW_INDEX(), stk_p->getCOL_INDEX());
printf("\tDIMS = %d(V) x %d(H) x %d(D)\n", V_dim, H_dim, D_dim);
printf("\tmean = %.5f\n", mean_val);
printf("\tmax = %.5f\n", max_val);
printf("\tarray data:\n\n");
for(int i=0; i<V_dim; i++)
printf("\t\tV_profile[%d] = %.5f\n", i, V_profile[i]);
for(int i=0; i<H_dim; i++)
printf("\t\tH_profile[%d] = %.5f\n", i, H_profile[i]);
for(int i=0; i<D_dim; i++)
printf("\t\tD_profile[%d] = %.5f\n", i, D_profile[i]);
for(int i=0; i<V_dim; i++)
printf("\t\tV_MIP[%d] = %.5f\n", i, V_MIP[i]);
for(int i=0; i<H_dim; i++)
printf("\t\tH_MIP[%d] = %.5f\n", i, H_MIP[i]);
for(int i=0; i<D_dim; i++)
printf("\t\tD_MIP[%d] = %.5f\n", i, D_MIP[i]);
printf("\n\n");
}
| 35.269968 | 190 | 0.617782 | zzhmark |
58f34ecd609e36c29fc423ba6154ebfa776c18a3 | 1,282 | cpp | C++ | Example/serialization_13/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/serialization_13/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/serialization_13/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | #include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
#include <iostream>
#include <sstream>
std::stringstream ss;
class animal
{
public:
animal() = default;
animal(int legs) : legs_{legs} {}
virtual int legs() const { return legs_; }
virtual ~animal() = default;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version) { ar & legs_; }
int legs_;
};
class bird : public animal
{
public:
bird() = default;
bird(int legs, bool can_fly) :
animal{legs}, can_fly_{can_fly} {}
bool can_fly() const { return can_fly_; }
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::base_object<animal>(*this);
ar & can_fly_;
}
bool can_fly_;
};
void save()
{
boost::archive::text_oarchive oa{ss};
oa.register_type<bird>();
animal *a = new bird{2, false};
oa << a;
delete a;
}
void load()
{
boost::archive::text_iarchive ia{ss};
ia.register_type<bird>();
animal *a;
ia >> a;
std::cout << a->legs() << '\n';
delete a;
}
int main()
{
save();
load();
} | 18.314286 | 73 | 0.664587 | KwangjoJeong |
58f5e87c88fc029411d0193072ec526dc6ec06db | 894 | cpp | C++ | numeric/modulo.cpp | ankushkhanna1998/competitive-programming | 97c772f3bc029dcd9f573f2e3d616ba068eab8b5 | [
"MIT"
] | 3 | 2020-06-02T07:39:24.000Z | 2020-09-02T14:04:52.000Z | numeric/modulo.cpp | ankushkhanna1998/competitive-programming | 97c772f3bc029dcd9f573f2e3d616ba068eab8b5 | [
"MIT"
] | null | null | null | numeric/modulo.cpp | ankushkhanna1998/competitive-programming | 97c772f3bc029dcd9f573f2e3d616ba068eab8b5 | [
"MIT"
] | null | null | null | const int64_t MOD = static_cast<int64_t>(1e9 + 7);
inline int64_t add(int64_t a, const int64_t b, const int64_t M = MOD) {
return ((a += b) >= M ? a - M : a);
}
inline int64_t sub(int64_t a, const int64_t b, const int64_t M = MOD) {
return ((a -= b) < 0 ? a + M : a);
}
inline int64_t mul(const int64_t a, const int64_t b, const int64_t M = MOD) {
return a * b % M;
}
inline int64_t power(int64_t a, int64_t b, const int64_t M = MOD) {
assert(b >= 0);
int64_t ans = 1;
while (b) {
if (b & 1) {
ans = mul(ans, a, M);
}
a = mul(a, a, M);
b >>= 1;
}
return ans;
}
inline int64_t inverse(int64_t a, const int64_t M = MOD) {
int64_t b = M, u = 0, v = 1;
while (a) {
int64_t t = b / a;
b -= t * a; swap(a, b);
u -= t * v; swap(u, v);
}
assert(b == 1);
return sub(u, 0, M);
}
| 23.526316 | 77 | 0.506711 | ankushkhanna1998 |
58f696aa6218731be901e86298876227be963492 | 17,565 | cpp | C++ | src/Physics/Vehicle.cpp | NotCamelCase/Grad-Project-Arcade-Sim | 4574cf1a11878829c75dec1aaa9834d40221cdbc | [
"MIT"
] | 7 | 2015-01-12T21:46:22.000Z | 2021-11-19T19:15:37.000Z | src/Physics/Vehicle.cpp | NotCamelCase/Grad-Project-Arcade-Sim | 4574cf1a11878829c75dec1aaa9834d40221cdbc | [
"MIT"
] | null | null | null | src/Physics/Vehicle.cpp | NotCamelCase/Grad-Project-Arcade-Sim | 4574cf1a11878829c75dec1aaa9834d40221cdbc | [
"MIT"
] | 3 | 2015-07-28T08:32:19.000Z | 2021-02-19T11:16:48.000Z | /*
The MIT License (MIT)
Copyright (c) 2015 Tayfun Kayhan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Physics\Vehicle.h"
#include <Ogre.h>
#include <btBulletDynamicsCommon.h>
#include "Physics\BtOgrePG.h"
#include "Physics\BtOgreGP.h"
#include "Physics\BtOgreExtras.h"
#include "World\GameObjectManager.h"
#include "Physics\PhysicsManager.h"
#include "Event\EventManager.h"
#include "Audio\AudioManager.h"
#include "Audio\SoundEffect.h"
#include "Network\NetworkManager.h"
#include "Player\PlayerManager.h"
#include "Player\RaceManager.h"
#include "Network\GameClient.h"
#include "Physics\Waypoint.h"
#include "Player\Player.h"
#include "GODLoader.h"
#include "InputMap.h"
#include "Utils.h"
#define FOLLOW_CAMERA_OFFSET Vector3(0, -12.5, 25)
#define LIGHT_OFFSET Vector3(0, -20, 20)
#define AIR_DENSITY 1.2f
#define CHASE_CAM_AUTO 1
#define CHASE_CAM_LIMITED 0
using namespace Ogre;
Vehicle::Vehicle(GameObjectManager* mng, SceneNode* node, Entity* entity, const String& id)
: PhysicsObject(mng, node, entity, id),
m_vehicleRaycaster(NULL), m_btVehicle(NULL), m_ownerPlayer(NULL),
m_engineForce(0), m_brakeForce(0), m_steering(0), m_sceneMgr(NULL),
m_engineSound(NULL), m_brakeSound(NULL), m_props(NULL), m_raceTimer(NULL),
m_vehicleState(VehicleState::INIT), m_lastPassedWaypointIndex(-1), m_latestWaypointPos(NULL)
{
m_sceneMgr = m_manager->getSceneManager();
m_props = GODLoader::getSingleton().getGameObjectDefinitionByTag(m_tag);
const String engineSound = m_props->getParameters()["engineSound"];
m_engineSound = AudioManager::getSingleton().createSoundEffect(engineSound, AudioType::SOUND_2D_LOOPING);
assert(m_engineSound != NULL && "Vehicle engine sound is NULL!");
const String brakeSound = m_props->getParameters()["brakeSound"];
m_brakeSound = AudioManager::getSingleton().createSoundEffect(brakeSound);
assert(m_engineSound != NULL && "Vehicle brake sound is NULL!");
updateSounds();
// Get location indexes of Waypoints from GameObjectManager's CheckPoints
for (const GameObject* cp : m_manager->getGameObjects())
{
if (cp->getType() == GameObjectType::TYPE_CHECKPOINT)
{
const int wpIndex = StringConverter::parseInt(cp->getID());
Waypoint* waypoint = new Waypoint(wpIndex);
m_trackWaypoints.insert(std::make_pair(wpIndex, waypoint));
}
}
EventManager::getSingleton().registerListener(EventType::COLLISION_STARTED, this);
EventManager::getSingleton().registerListener(EventType::COLLISION_TIME, this);
EventManager::getSingleton().registerListener(EventType::COLLISION_ENDED, this);
EventManager::getSingleton().registerListener(EventType::START_OFF_FIRE, this);
EventManager::getSingleton().registerListener(EventType::VEHICLE_UPSIDE_DOWN, this);
m_raceTimer = new Timer();
m_logger->logMessage("Vehicle created");
}
Vehicle::~Vehicle()
{
AudioManager::getSingleton().release(m_engineSound);
AudioManager::getSingleton().release(m_brakeSound);
SAFE_DELETE(m_btVehicle);
SAFE_DELETE(m_vehicleRaycaster);
SAFE_DELETE(m_raceTimer);
for (auto& it : m_trackWaypoints)
{
#if _DEBUG
Waypoint* wp = NULL;
wp = it.second;
if (wp != NULL)
m_logger->logMessage("Destroying Waypoint of index: " + wp->getLocationIndex());
#endif
SAFE_DELETE(it.second);
}
m_trackWaypoints.clear();
for (int i = 0; i < WHEEL_COUNT; i++)
{
m_sceneMgr->destroyRibbonTrail(m_trailMO[i]);
}
m_logger->logMessage("Tire trails destroyed");
EventManager::getSingleton().unregisterListener(EventType::COLLISION_STARTED, this);
EventManager::getSingleton().unregisterListener(EventType::COLLISION_TIME, this);
EventManager::getSingleton().unregisterListener(EventType::COLLISION_ENDED, this);
EventManager::getSingleton().unregisterListener(EventType::START_OFF_FIRE, this);
EventManager::getSingleton().unregisterListener(EventType::VEHICLE_UPSIDE_DOWN, this);
m_logger->logMessage("Vehicle destroyed");
}
int Vehicle::getCurrentSpeed() const
{
return m_btVehicle->getCurrentSpeedKmHour();
}
void Vehicle::applyDynamicAirPressure(int* currentSpeed)
{
float v = *currentSpeed * (1.0f / 3.6f);
float q = 0.5f * AIR_DENSITY * v * v;
m_rigidBody->applyCentralForce(btVector3(0, -4.5 * q, 0));
}
void Vehicle::initFineTuningValues()
{
m_maxReverse = -1 * StringConverter::parseInt(m_props->getParameters()["maxReverseSpeed"]);
m_steeringIdeal = StringConverter::parseReal(m_props->getParameters()["steeringIncrementIdeal"]);
m_idealBrakeGain = StringConverter::parseReal(m_props->getParameters()["brakeGainIdeal"]);
m_boostLimit = StringConverter::parseInt(m_props->getParameters()["startUpBoostLimit"]);
m_boostGain = StringConverter::parseInt(m_props->getParameters()["startUpBoost"]);
m_logger->logMessage("Assigned initial Vehicle physics paramaters");
}
void Vehicle::update(Real delta)
{
switch (m_vehicleState)
{
case VehicleState::INIT_COMPLETE:
initFineTuningValues();
setupVisuals();
m_vehicleState = VehicleState::IDLE;
break;
case VehicleState::IDLE:
if (m_rigidBody->getActivationState() != DISABLE_SIMULATION)
{
m_rigidBody->forceActivationState(DISABLE_SIMULATION);
m_logger->logMessage("Vehicle chassis simulation disabled");
}
updatePhysics(delta);
break;
case VehicleState::IN_RACE:
updatePhysics(delta);
break;
case VehicleState::END_RACE:
break;
default:
break;
}
syncVehicle();
updateSounds();
updatePlayerStats();
}
void Vehicle::updatePhysics(Real delta)
{
int currentSpeed = getCurrentSpeed();
applyDynamicAirPressure(¤tSpeed);
bool tireTrailVis = false;
unsigned int keyFlag = NULL;
if (!m_ownerPlayer->isLocal())
{
GameClient* remoteClient = NetworkManager::getSingleton().getGameClientByPlayer(m_ownerPlayer);
assert(remoteClient && "Error finding remote GameClient by Player");
keyFlag = remoteClient->getKeyFlags();
m_logger->logMessage("Checking input with client data");
}
if (InputMap::isKeyActive(InputType::BRAKE, keyFlag))
{
if (currentSpeed <= 0.f)
{
if (currentSpeed > m_maxReverse)
{
m_brakeForce = 0.f;
m_engineForce += -m_speedGain;
}
else {
m_brakeForce = 0.f;
handleNeutral(¤tSpeed);
}
}
else {
tireTrailVis = true;
adjustBrake(¤tSpeed);
m_brakeForce += m_brakeGain;
m_engineForce = 0.f;
}
}
else if (InputMap::isKeyActive(InputType::ACCELERATE, keyFlag))
{
adjustEngineForce(¤tSpeed);
m_engineForce += m_speedGain;
if (m_engineForce > m_maxEngineForce)
m_engineForce = m_maxEngineForce;
m_brakeForce = 0.f;
}
else
{
handleNeutral(¤tSpeed);
}
if (InputMap::isKeyActive(InputType::STEER_LEFT, keyFlag))
{
adjustSteering(¤tSpeed);
m_steering += m_steeringIncrement;
if (m_steering > m_steeringClamp)
m_steering = m_steeringClamp;
}
else if (InputMap::isKeyActive(InputType::STEER_RIGHT, keyFlag))
{
adjustSteering(¤tSpeed);
m_steering -= m_steeringIncrement;
if (m_steering < -m_steeringClamp)
m_steering = -m_steeringClamp;
}
else
{
// TODO: Further investigate steering relief reduction !!!
static Real neutralSteering = 0.02;
if (Math::Abs(m_steering) < neutralSteering)
m_steering = 0.0f;
else if (m_steering > 0.0f)
m_steering -= neutralSteering;
else
m_steering += neutralSteering;
}
// DOUBT: Should unroll the loop ?!
for (int i = 0; i < m_btVehicle->getNumWheels(); i++)
{
if (i < 2)
{
m_btVehicle->setSteeringValue(m_steering, i);
}
else
{
m_btVehicle->applyEngineForce(m_engineForce, i);
m_btVehicle->setBrake(m_brakeForce, i);
}
RibbonTrail* trail = (RibbonTrail*) m_trailMO[i];
assert(trail && "Error indexing RibbonTrail");
if (!tireTrailVis && trail)
{
trail->clearAllChains();
}
trail->setVisible(tireTrailVis);
}
}
bool Vehicle::updatePlayerStats()
{
PlayerStats* stats = m_ownerPlayer->getPlayerStats();
stats->vehicleSpeed = getCurrentSpeed();
const unsigned long currentTiming = m_raceTimer->getMilliseconds();
const unsigned long sumSec = currentTiming / 1000;
stats->min = sumSec / 60;
stats->sec = sumSec % 60;
stats->splitSec = (currentTiming - (sumSec * 1000)) / 10;
return true;
}
void Vehicle::syncVehicle()
{
for (int i = 0; i < m_wheels.size(); i++)
{
m_btVehicle->updateWheelTransform(i, true);
const btTransform& w = m_btVehicle->getWheelInfo(i).m_worldTransform;
SceneNode* node = m_wheels[i]->getNode();
node->setPosition(w.getOrigin()[0], w.getOrigin()[1], w.getOrigin()[2]);
node->setOrientation(w.getRotation().getW(), w.getRotation().getX(), w.getRotation().getY(), w.getRotation().getZ());
}
}
void Vehicle::adjustSteering(int* currentSpeed)
{
static const int fd = 1000;
static const int bd = 500;
if (*currentSpeed >= m_steeringReductionSpeed)
{
const float step = (m_steeringIdeal - m_steeringReduced) / fd;
const float asi = std::max(m_steeringReduced + step, (m_steeringIncrement - step));
m_steeringIncrement = asi;
}
else
{
if (*currentSpeed <= (m_steeringReductionSpeed / 2)) m_steeringIncrement = m_steeringIdeal;
else {
const float step = (m_steeringIdeal - m_steeringReduced) / bd;
const float asi = std::min(m_steeringIdeal, (m_steeringIncrement + step));
m_steeringIncrement = asi;
}
}
}
void Vehicle::adjustBrake(int* currentSpeed)
{
static const int fd = 100;
static const int bd = 75;
if (*currentSpeed >= m_brakeReductionSpeed)
{
const float step = (m_idealBrakeGain - m_brakeReduced) / fd;
const float abf = std::max(m_brakeReduced + step, (m_brakeGain - step));
m_brakeGain = abf;
}
else {
const float step = (m_idealBrakeGain - m_steeringReduced) / bd;
const float abf = std::min(m_idealBrakeGain, (m_brakeGain + step));
m_brakeGain = abf;
}
}
void Vehicle::adjustEngineForce(int* currentSpeed)
{
if (*currentSpeed < m_boostLimit)
{
m_speedGain += m_boostGain;
}
}
void Vehicle::updateSounds()
{
if (m_btVehicle && m_vehicleState != VehicleState::END_RACE)
{
const int cv = getCurrentSpeed();
if (InputMap::isKeyActive(InputType::BRAKE))
{
if (!m_brakeSound->isPlaying() && cv >= 30.f) m_brakeSound->play();
}
else {
m_brakeSound->stop();
}
if (!m_engineSound->isPlaying()) m_engineSound->play(); m_engineSound->setVolume(.6);
const float factor = cv / 100.f;
m_engineSound->setPitch(std::max(0.2f, std::min(factor, 2.f)));
}
}
void Vehicle::onEvent(int type, void* data)
{
CollisionListener::onEvent(type, data);
switch (type)
{
case EventType::VEHICLE_UPSIDE_DOWN:
if (m_ownerPlayer->isLocal())
readjustVehicle();
break;
case EventType::START_OFF_FIRE:
if (m_raceTimer == NULL)
m_raceTimer = new Timer();
else
m_raceTimer->reset();
m_rigidBody->forceActivationState(DISABLE_DEACTIVATION);
m_logger->logMessage("Vehicle chassis simulation enabled");
m_vehicleState = VehicleState::IN_RACE;
m_ownerPlayer->setPlayerState(PlayerState::RACING);
break;
default:
break;
}
}
void Vehicle::onCollisionStart(CollisionEventData* colData)
{
PhysicsObject* other = getOtherOffCollision(colData);
switch (other->getType())
{
case GameObjectType::TYPE_CHECKPOINT:
if (m_vehicleState != VehicleState::IN_RACE) // Skip CountDown CheckPoint collisions
{
break;
}
const int wpIndex = StringConverter::parseInt(other->getID());
if (m_lastPassedWaypointIndex < 0)
{
if (wpIndex != 2)
break;
}
else if (m_lastPassedWaypointIndex == wpIndex)
{
break;
}
// Store last checkpoint's position so when crashed, vehicle will be moved onto it
m_latestWaypointPos = const_cast<Vector3*> (&other->getNode()->_getDerivedPosition());
Waypoint* passedWaypoint = NULL;
auto finder = m_trackWaypoints.find(wpIndex);
if (finder == m_trackWaypoints.end())
{
assert(passedWaypoint != NULL && "Indexed Waypoint couldn't be fetched!");
break;
}
passedWaypoint = finder->second;
passedWaypoint->onPass();
m_logger->logMessage("Waypoint " + StringConverter::toString(wpIndex) + " visited");
if (passedWaypoint->isPassed())
{
m_trackWaypoints.erase(wpIndex);
m_manager->destroy(other);
}
PlayerStats* stats = m_ownerPlayer->getPlayerStats();
if (m_trackWaypoints.empty()) // Player completed track
{
m_engineSound->stop();
m_brakeSound->stop();
m_logger->logMessage("Vehicle Sound FX stopped");
SoundEffect* celebration = AudioManager::getSingleton().createSoundEffect("finish_line.aiff");
celebration->play();
stats->currentLap++;
assert(stats->currentLap <= MAX_LAP_COUNT);
const unsigned long overallTime = m_raceTimer->getMilliseconds();
// Check to prevent 1-lapped track ending
if (stats->currentLap == 1)
{
stats->lapTimes[0] = overallTime;
}
else
{
// If the track is not 1-lapped, previous lap timing is current - sum of all previous laps' timing
stats->lapTimes[stats->currentLap - 1] = overallTime - RaceManager::getSingleton().computePrevLapsSum(m_ownerPlayer);
}
m_vehicleState = VehicleState::END_RACE;
m_manager->getPhysicsManager()->destroyVehicle(this);
EventManager::getSingleton().notify(EventType::TRACK_COMPLETE, m_ownerPlayer);
}
else
{
if (wpIndex == 1) // Passing first waypoint whose location index is 1 means one lap's completed.
{
if (m_lastPassedWaypointIndex > 0)
{
stats->currentLap++;
assert(stats->currentLap <= MAX_LAP_COUNT && "Lap count exceeds PlayerStats!");
const unsigned long overallTime = m_raceTimer->getMilliseconds();
if (stats->currentLap == 1)
{
stats->lapTimes[0] = overallTime;
}
else
{
stats->lapTimes[stats->currentLap - 1] = overallTime - RaceManager::getSingleton().computePrevLapsSum(m_ownerPlayer);
}
EventManager::getSingleton().notify(EventType::LAP_COMPLETE, m_ownerPlayer);
}
}
}
m_lastPassedWaypointIndex = wpIndex;
break;
}
}
void Vehicle::onCollisionTime(CollisionEventData* colData)
{
PhysicsObject* other = getOtherOffCollision(colData);
}
void Vehicle::onCollisionEnd(CollisionEventData* data)
{
PhysicsObject* other = getOtherOffCollision(data);
}
void Vehicle::handleNeutral(int* currentSpeed)
{
// TODO: Handle neutral vehicle !!!
m_engineForce = 0.f;
if (*currentSpeed != 0)
{
if (*currentSpeed >= 100)
m_brakeForce += (m_brakeGain * .005);
else
m_brakeForce += (m_brakeGain * .0025);
}
}
bool Vehicle::readjustVehicle()
{
static const btVector3& zero = btVector3(0, 0, 0);
m_rigidBody->forceActivationState(DISABLE_SIMULATION);
m_logger->logMessage("Vehicle chassis disabled !");
if (m_vehicleState != VehicleState::IN_RACE) return false;
m_rigidBody->setLinearVelocity(zero);
m_rigidBody->setAngularVelocity(zero);
btTransform currentTransform = m_btVehicle->getChassisWorldTransform();
btVector3& pos = currentTransform.getOrigin();
btQuaternion rot = currentTransform.getRotation();
pos.setY(pos.y() + 2.5);
float angle = 0.f;
if (pos.x() * pos.x() + pos.z() * pos.z() > 0)
{
angle += Math::ATan2(-pos.x(), -pos.z()).valueDegrees();
}
rot.setRotation(btVector3(0, 1, 0), angle);
currentTransform.setRotation(rot);
if (m_lastPassedWaypointIndex < 0 || m_latestWaypointPos == NULL)
{
const Vector3& pos = m_manager->getGameObjectByID(StringConverter::toString(m_trackWaypoints.find(1)->second->getLocationIndex()))->getNode()->_getDerivedPosition();
m_latestWaypointPos = const_cast<Vector3*> (&pos);
}
currentTransform.setOrigin(BtOgre::Convert::toBullet(*m_latestWaypointPos));
m_rigidBody->setWorldTransform(currentTransform);
m_rigidBody->forceActivationState(DISABLE_DEACTIVATION);
m_logger->logMessage("Vehicle chassis enabled!");
m_logger->logMessage("Vehicle readjusted!");
return false;
}
void Vehicle::setupVisuals()
{
for (size_t i = 0; i < WHEEL_COUNT; i++)
{
NameValuePairList params;
params["numberOfChains"] = "1";
params["maxElements"] = "100";
RibbonTrail* trail = (RibbonTrail*) m_sceneMgr->createMovableObject("RibbonTrail", ¶ms);
m_sceneMgr->getRootSceneNode()->attachObject(trail);
trail->setMaterialName("TireTrail");
trail->setTrailLength(100);
trail->setInitialColour(0, 0.1, 0.1, 0.1);
//trail->setInitialColour(0, 0.1, 0.1, 0.1, 0);
trail->setColourChange(0, 0.08, 0.08, 0.08, 0.08);
trail->setFaceCamera(false, Vector3::UNIT_Y);
//trail->setUseTextureCoords(true);
trail->setCastShadows(false);
trail->setUseVertexColours(true);
trail->setInitialWidth(0, 1);
trail->setRenderQueueGroup(m_entity->getRenderQueueGroup() + 1);
trail->addNode(m_wheels[i]->getNode());
m_trailMO[i] = trail;
}
m_logger->logMessage("Vehicle visuals set up");
} | 28.842365 | 167 | 0.728779 | NotCamelCase |
58fa12fcd221fec27eca3ae7f5202804d6b04b2a | 3,172 | hpp | C++ | src/libblockchain/transaction_sponsoring.hpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | 4 | 2019-11-20T17:27:57.000Z | 2021-01-05T09:46:20.000Z | src/libblockchain/transaction_sponsoring.hpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | null | null | null | src/libblockchain/transaction_sponsoring.hpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | 2 | 2019-01-10T14:10:26.000Z | 2020-03-01T05:55:05.000Z | #pragma once
#include "global.hpp"
#include "message.hpp"
#include "node.hpp"
#include "state.hpp"
#include <string>
#include <vector>
namespace publiqpp
{
// sponsoring stuff
std::vector<std::string> action_owners(BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
std::vector<std::string> action_participants(BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
void action_validate(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
bool check_complete);
bool action_is_complete(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
bool action_can_apply(publiqpp::detail::node_internals const& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
void action_apply(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
void action_revert(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
// cancel sponsoring stuff
std::vector<std::string> action_owners(BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
std::vector<std::string> action_participants(BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
void action_validate(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
bool check_complete);
bool action_is_complete(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
bool action_can_apply(publiqpp::detail::node_internals const& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
void action_apply(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
void action_revert(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
}
| 48.8 | 125 | 0.728247 | publiqnet |
58fbaa3a1b2267f5ad48045b5966096805c1ac18 | 601 | cpp | C++ | 999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp | Binamra7/Data-Structure-and-Algorithms | 1232fdeba041c678b4c651f6a702d50b344ed4cc | [
"MIT"
] | 126 | 2019-12-22T17:49:08.000Z | 2021-12-14T18:45:51.000Z | 999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp | Divyanshi-03/Data-Structure-and-Algorithms | 21b02dd312105411621242731106411defbd6ddb | [
"MIT"
] | 7 | 2019-12-25T18:03:41.000Z | 2021-02-20T06:25:27.000Z | 999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp | Divyanshi-03/Data-Structure-and-Algorithms | 21b02dd312105411621242731106411defbd6ddb | [
"MIT"
] | 54 | 2019-12-26T06:28:39.000Z | 2022-02-01T05:04:43.000Z | // Check if there exists two elements in an array such that their sum is equal to given k.
#include <iostream>
using namespace std;
bool pairSum(int arr[], int n, int k)
{
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(arr[i] + arr[j] == k)
{
cout<<i<<" & "<<j<<endl;
return true;
}
}
}
return false;
}
int main()
{
int n;
cin>>n;
int k;
cin>>k;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<pairSum(arr, n, k)<<endl;
} | 15.410256 | 90 | 0.432612 | Binamra7 |
58fff242aa8aa3db3d4faceb6c54aa4fac6556f2 | 966 | hpp | C++ | utils/resource_loader.hpp | UnnamedOrange/osu-kps | b893d1fb75f001ac6bb5951182590dc0096a1e0e | [
"MIT"
] | 21 | 2021-02-15T17:10:50.000Z | 2022-01-23T05:02:12.000Z | utils/resource_loader.hpp | UnnamedOrange/osu-kps | b893d1fb75f001ac6bb5951182590dc0096a1e0e | [
"MIT"
] | 4 | 2021-02-15T16:23:52.000Z | 2021-12-30T14:04:01.000Z | utils/resource_loader.hpp | UnnamedOrange/osu-kps | b893d1fb75f001ac6bb5951182590dc0096a1e0e | [
"MIT"
] | 2 | 2021-07-23T02:29:11.000Z | 2021-09-05T04:09:55.000Z | // Copyright (c) UnnamedOrange. Licensed under the MIT Licence.
// See the LICENSE file in the repository root for full licence text.
#pragma once
#include <vector>
#include <string_view>
#include <stdexcept>
#include <Windows.h>
#undef min
#undef max
class resource_loader
{
public:
static auto load(const wchar_t* resource_name, const wchar_t* type_name)
{
HINSTANCE hInstance = GetModuleHandleW(nullptr);
HRSRC hResInfo = FindResourceW(hInstance,
resource_name, type_name);
if (!hResInfo)
throw std::runtime_error("fail to FindResourceW.");
HGLOBAL hResource = LoadResource(hInstance, hResInfo);
if (!hResource)
throw std::runtime_error("fail to LoadResource.");
DWORD dwSize = SizeofResource(hInstance, hResInfo);
if (!dwSize)
throw std::runtime_error("fail to SizeofResource.");
BYTE* p = reinterpret_cast<BYTE*>(LockResource(hResource));
std::vector<BYTE> ret(p, p + dwSize);
FreeResource(hResource);
return ret;
}
}; | 26.833333 | 73 | 0.736025 | UnnamedOrange |
4502d349f350bfdd903d9c815ad937a7a387f148 | 1,547 | cpp | C++ | src/source/zombye/gameplay/states/play_state.cpp | kasoki/project-zombye | 30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05 | [
"MIT"
] | 1 | 2019-05-29T01:37:44.000Z | 2019-05-29T01:37:44.000Z | src/source/zombye/gameplay/states/play_state.cpp | atomicptr/project-zombye | 30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05 | [
"MIT"
] | 1 | 2015-08-31T22:44:27.000Z | 2015-08-31T22:44:27.000Z | src/source/zombye/gameplay/states/play_state.cpp | kasoki/project-zombye | 30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05 | [
"MIT"
] | null | null | null | #include <cmath>
#include <glm/gtc/matrix_transform.hpp>
#include <SDL2/SDL.h>
#include <zombye/core/game.hpp>
#include <zombye/ecs/entity_manager.hpp>
#include <zombye/gameplay/states/play_state.hpp>
#include <zombye/input/input_manager.hpp>
#include <zombye/input/input_system.hpp>
#include <zombye/input/joystick.hpp>
#include <zombye/input/mouse.hpp>
#include <zombye/physics/shapes/box_shape.hpp>
#include <zombye/physics/physics_component.hpp>
#include <zombye/rendering/animation_component.hpp>
#include <zombye/rendering/camera_component.hpp>
#include <zombye/rendering/rendering_system.hpp>
#include <zombye/scripting/scripting_system.hpp>
#include <zombye/utils/logger.hpp>
#include <zombye/utils/state_machine.hpp>
zombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) {
auto input = sm->get_game()->input();
input_ = input->create_manager();
input_->register_actions(*sm->get_game(), "scripts/input/play_state.as");
input_->load_config(*sm->get_game(), "config/input/play_state.json");
}
void zombye::play_state::enter() {
zombye::log("enter play state");
auto& game = *sm_->get_game();
auto& scripting_system = game.scripting_system();
scripting_system.begin_module("MyModule");
scripting_system.load_script("scripts/test.as");
scripting_system.end_module();
scripting_system.exec("void main()", "MyModule");
}
void zombye::play_state::leave() {
zombye::log("leave play state");
}
void zombye::play_state::update(float delta_time) {
input_->handle_input();
}
| 31.571429 | 77 | 0.740142 | kasoki |
450499a351910ff7c5892fd42be79f0ddd030383 | 6,340 | cpp | C++ | src/third_party/swiftshader/third_party/subzero/pnacl-llvm/NaClBitcodeDecoders.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | src/third_party/swiftshader/third_party/subzero/pnacl-llvm/NaClBitcodeDecoders.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | src/third_party/swiftshader/third_party/subzero/pnacl-llvm/NaClBitcodeDecoders.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | //===- NaClBitcodeDecoders.cpp --------------------------------------------===//
// Internal implementation of decoder functions for PNaCl Bitcode files.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h"
namespace llvm {
namespace naclbitc {
bool DecodeCastOpcode(uint64_t NaClOpcode,
Instruction::CastOps &LLVMOpcode) {
switch (NaClOpcode) {
default:
LLVMOpcode = Instruction::BitCast;
return false;
case naclbitc::CAST_TRUNC:
LLVMOpcode = Instruction::Trunc;
return true;
case naclbitc::CAST_ZEXT:
LLVMOpcode = Instruction::ZExt;
return true;
case naclbitc::CAST_SEXT:
LLVMOpcode = Instruction::SExt;
return true;
case naclbitc::CAST_FPTOUI:
LLVMOpcode = Instruction::FPToUI;
return true;
case naclbitc::CAST_FPTOSI:
LLVMOpcode = Instruction::FPToSI;
return true;
case naclbitc::CAST_UITOFP:
LLVMOpcode = Instruction::UIToFP;
return true;
case naclbitc::CAST_SITOFP:
LLVMOpcode = Instruction::SIToFP;
return true;
case naclbitc::CAST_FPTRUNC:
LLVMOpcode = Instruction::FPTrunc;
return true;
case naclbitc::CAST_FPEXT:
LLVMOpcode = Instruction::FPExt;
return true;
case naclbitc::CAST_BITCAST:
LLVMOpcode = Instruction::BitCast;
return true;
}
}
bool DecodeLinkage(uint64_t NaClLinkage,
GlobalValue::LinkageTypes &LLVMLinkage) {
switch (NaClLinkage) {
default:
LLVMLinkage = GlobalValue::InternalLinkage;
return false;
case naclbitc::LINKAGE_EXTERNAL:
LLVMLinkage = GlobalValue::ExternalLinkage;
return true;
case naclbitc::LINKAGE_INTERNAL:
LLVMLinkage = GlobalValue::InternalLinkage;
return true;
}
}
bool DecodeBinaryOpcode(uint64_t NaClOpcode, Type *Ty,
Instruction::BinaryOps &LLVMOpcode) {
switch (NaClOpcode) {
default:
LLVMOpcode = Instruction::Add;
return false;
case naclbitc::BINOP_ADD:
LLVMOpcode = Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
return true;
case naclbitc::BINOP_SUB:
LLVMOpcode = Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
return true;
case naclbitc::BINOP_MUL:
LLVMOpcode = Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
return true;
case naclbitc::BINOP_UDIV:
LLVMOpcode = Instruction::UDiv;
return true;
case naclbitc::BINOP_SDIV:
LLVMOpcode = Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
return true;
case naclbitc::BINOP_UREM:
LLVMOpcode = Instruction::URem;
return true;
case naclbitc::BINOP_SREM:
LLVMOpcode = Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
return true;
case naclbitc::BINOP_SHL:
LLVMOpcode = Instruction::Shl;
return true;
case naclbitc::BINOP_LSHR:
LLVMOpcode = Instruction::LShr;
return true;
case naclbitc::BINOP_ASHR:
LLVMOpcode = Instruction::AShr;
return true;
case naclbitc::BINOP_AND:
LLVMOpcode = Instruction::And;
return true;
case naclbitc::BINOP_OR:
LLVMOpcode = Instruction::Or;
return true;
case naclbitc::BINOP_XOR:
LLVMOpcode = Instruction::Xor;
return true;
}
}
bool DecodeCallingConv(uint64_t NaClCallingConv,
CallingConv::ID &LLVMCallingConv) {
switch (NaClCallingConv) {
default:
LLVMCallingConv = CallingConv::C;
return false;
case naclbitc::C_CallingConv:
LLVMCallingConv = CallingConv::C;
return true;
}
}
bool DecodeFcmpPredicate(uint64_t NaClPredicate,
CmpInst::Predicate &LLVMPredicate) {
switch (NaClPredicate) {
default:
LLVMPredicate = CmpInst::FCMP_FALSE;
return false;
case naclbitc::FCMP_FALSE:
LLVMPredicate = CmpInst::FCMP_FALSE;
return true;
case naclbitc::FCMP_OEQ:
LLVMPredicate = CmpInst::FCMP_OEQ;
return true;
case naclbitc::FCMP_OGT:
LLVMPredicate = CmpInst::FCMP_OGT;
return true;
case naclbitc::FCMP_OGE:
LLVMPredicate = CmpInst::FCMP_OGE;
return true;
case naclbitc::FCMP_OLT:
LLVMPredicate = CmpInst::FCMP_OLT;
return true;
case naclbitc::FCMP_OLE:
LLVMPredicate = CmpInst::FCMP_OLE;
return true;
case naclbitc::FCMP_ONE:
LLVMPredicate = CmpInst::FCMP_ONE;
return true;
case naclbitc::FCMP_ORD:
LLVMPredicate = CmpInst::FCMP_ORD;
return true;
case naclbitc::FCMP_UNO:
LLVMPredicate = CmpInst::FCMP_UNO;
return true;
case naclbitc::FCMP_UEQ:
LLVMPredicate = CmpInst::FCMP_UEQ;
return true;
case naclbitc::FCMP_UGT:
LLVMPredicate = CmpInst::FCMP_UGT;
return true;
case naclbitc::FCMP_UGE:
LLVMPredicate = CmpInst::FCMP_UGE;
return true;
case naclbitc::FCMP_ULT:
LLVMPredicate = CmpInst::FCMP_ULT;
return true;
case naclbitc::FCMP_ULE:
LLVMPredicate = CmpInst::FCMP_ULE;
return true;
case naclbitc::FCMP_UNE:
LLVMPredicate = CmpInst::FCMP_UNE;
return true;
case naclbitc::FCMP_TRUE:
LLVMPredicate = CmpInst::FCMP_TRUE;
return true;
}
}
bool DecodeIcmpPredicate(uint64_t NaClPredicate,
CmpInst::Predicate &LLVMPredicate) {
switch (NaClPredicate) {
default:
LLVMPredicate = CmpInst::ICMP_EQ;
return false;
case naclbitc::ICMP_EQ:
LLVMPredicate = CmpInst::ICMP_EQ;
return true;
case naclbitc::ICMP_NE:
LLVMPredicate = CmpInst::ICMP_NE;
return true;
case naclbitc::ICMP_UGT:
LLVMPredicate = CmpInst::ICMP_UGT;
return true;
case naclbitc::ICMP_UGE:
LLVMPredicate = CmpInst::ICMP_UGE;
return true;
case naclbitc::ICMP_ULT:
LLVMPredicate = CmpInst::ICMP_ULT;
return true;
case naclbitc::ICMP_ULE:
LLVMPredicate = CmpInst::ICMP_ULE;
return true;
case naclbitc::ICMP_SGT:
LLVMPredicate = CmpInst::ICMP_SGT;
return true;
case naclbitc::ICMP_SGE:
LLVMPredicate = CmpInst::ICMP_SGE;
return true;
case naclbitc::ICMP_SLT:
LLVMPredicate = CmpInst::ICMP_SLT;
return true;
case naclbitc::ICMP_SLE:
LLVMPredicate = CmpInst::ICMP_SLE;
return true;
}
}
}
}
| 27.68559 | 80 | 0.677445 | rhencke |
4505cdbd048ad5797de47fbbefcacffec70c99d9 | 3,815 | cpp | C++ | tests/test_queries.cpp | sinkarl/asp_db | 8dc5b40257b438872a689f5894416ae80db7d7ca | [
"MIT"
] | null | null | null | tests/test_queries.cpp | sinkarl/asp_db | 8dc5b40257b438872a689f5894416ae80db7d7ca | [
"MIT"
] | null | null | null | tests/test_queries.cpp | sinkarl/asp_db | 8dc5b40257b438872a689f5894416ae80db7d7ca | [
"MIT"
] | null | null | null | #include "asp_db/db_queries_setup.h"
#include "asp_db/db_queries_setup_select.h"
#include "asp_db/db_tables.h"
#include "asp_db/db_where.h"
#include "library_tables.h"
#include "gtest/gtest.h"
#include <filesystem>
#include <iostream>
#include <numeric>
#include <assert.h>
LibraryDBTables ldb;
TEST(db_where_tree, DBTableBetween) {
// text field
WhereTreeConstructor<table_book> adb(&ldb);
// todo: не прозрачна связь между параметром шаблона и id столбца
auto between_t = adb.Between(BOOK_TITLE, "a", "z");
std::string btstr = std::string(BOOK_TITLE_NAME) + " between 'a' and 'z'";
EXPECT_STRCASEEQ(between_t->GetString().c_str(), btstr.c_str());
// int field
auto between_p = adb.Between(BOOK_PUB_YEAR, 1920, 1985);
std::string bpstr =
std::string(BOOK_PUB_YEAR_NAME) + " between 1920 and 1985";
EXPECT_STRCASEEQ(between_p->GetString().c_str(), bpstr.c_str());
// вынесены в test_excpression.cpp
}
TEST(db_where_tree, DBTable2Operations) {
WhereTreeConstructor<table_author> adb(&ldb);
auto eq_t = adb.Eq(AUTHOR_NAME, "Leo Tolstoy");
std::string eqtstr = std::string(AUTHOR_NAME_NAME) + " = 'Leo Tolstoy'";
EXPECT_STRCASEEQ(eq_t->GetString().c_str(), eqtstr.c_str());
// todo: add cases for other operators
}
TEST(db_where_tree, DBTableAnd) {
WhereTreeConstructor<table_book> adb(&ldb);
auto eq_t1 = adb.Eq(BOOK_TITLE, "Hobbit");
// todo: how about instatnces for enums???
auto eq_t2 = adb.Eq(BOOK_LANG, (int)lang_eng);
auto gt_t3 = adb.Gt(BOOK_PUB_YEAR, 1900);
// check
// and1
auto and1 = adb.And(eq_t1, eq_t2);
std::string and1_s = "(" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_LANG_NAME + " = 2)";
EXPECT_STRCASEEQ(and1->GetString().c_str(), and1_s.c_str());
// and2
auto and2 = adb.And(eq_t1, gt_t3);
std::string and2_s = "(" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_PUB_YEAR_NAME + " > 1900)";
EXPECT_STRCASEEQ(and2->GetString().c_str(), and2_s.c_str());
// and3
auto and3 = adb.And(eq_t1, eq_t2, gt_t3);
std::string and3_s = "((" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_LANG_NAME + " = 2" +
")) AND (" BOOK_PUB_YEAR_NAME + " > 1900)";
EXPECT_STRCASEEQ(and3->GetString().c_str(), and3_s.c_str());
// check nullptr
// and4
wns::node_ptr null_t4 = nullptr;
eq_t1 = adb.Eq(BOOK_TITLE, "Hobbit");
auto and4 = adb.And(eq_t1, null_t4);
std::string and4_s = std::string(BOOK_TITLE_NAME) + " = 'Hobbit'";
EXPECT_STRCASEEQ(and4->GetString().c_str(), and4_s.c_str());
// and5
wns::node_ptr null_t5 = nullptr;
auto and5 = adb.And(null_t4, null_t5);
EXPECT_STRCASEEQ(and5->GetString().c_str(), "");
}
TEST(WhereTreeConstructor, Init) {
WhereTreeConstructor<table_translation> ts(&ldb);
WhereTree<table_translation> wt(ts);
wt.Init(ts.And(ts.Ge(TRANS_ID, 3), ts.Lt(TRANS_ID, 10),
ts.Eq(TRANS_LANG, int(lang_rus))));
// проверим результат инициализации
std::string wts = std::string("((") + TRANS_ID_NAME + " >= 3) AND (" +
TRANS_ID_NAME + " < 10)) AND (" + TRANS_LANG_NAME + " = " +
std::to_string(int(lang_rus)) + ")";
EXPECT_STRCASEEQ(wt.GetWhereTree()->GetString().c_str(), wts.c_str());
// продолжим
wt.AddOr(ts.And(ts.Gt(TRANS_ID, 13), ts.Lt(TRANS_ID, 15)));
// снова проверим
std::string wfs = std::string("(((") + TRANS_ID_NAME + " >= 3) AND (" +
TRANS_ID_NAME + " < 10)) AND (" + TRANS_LANG_NAME + " = " +
std::to_string(int(lang_rus)) + ")) OR ((" + TRANS_ID_NAME +
" > 13" + ") AND (" + TRANS_ID_NAME + " < 15))";
EXPECT_STRCASEEQ(wt.GetWhereTree()->GetString().c_str(), wfs.c_str());
}
| 37.772277 | 80 | 0.630406 | sinkarl |
450634b23083e5eadbd140eda6fe4f83cbf77aaf | 4,278 | cpp | C++ | Lab3/src/Utils.cpp | Farmijo/VA | 3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b | [
"MIT"
] | null | null | null | Lab3/src/Utils.cpp | Farmijo/VA | 3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b | [
"MIT"
] | null | null | null | Lab3/src/Utils.cpp | Farmijo/VA | 3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b | [
"MIT"
] | null | null | null | #include "Utils.h"
#include <sstream>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include "includes.h"
#include "Application.h"
#include "Camera.h"
long getTime()
{
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday( &tv, NULL );
return (int)( tv.tv_sec * 1000 + ( tv.tv_usec / 1000 ) );
#endif
}
//Draw the grid
void drawGrid( float dist )
{
int num_lines = 20;
glLineWidth( 1 );
glColor3f( 0.5, 0.5, 0.5 );
glDisable( GL_TEXTURE_2D );
glBegin( GL_LINES );
for( int i = 0; i <= num_lines >> 1; ++i )
{
float a = float(dist * num_lines) * 0.5f;
float b = i * dist;
if( i == num_lines >> 1 )
glColor3f( 1.f, 0.25f, 0.25f );
else if( i % 2 )
glColor3f( 0.25f, 0.25f, 0.25f );
else
glColor3f( 0.5f, 0.5f, 0.5f );
glVertex3f( a, b, -a );
glVertex3f( -a, b, -a );
glVertex3f( a, -b, -a );
glVertex3f( -a, -b, -a );
glVertex3f( b, a, -a );
glVertex3f( b, -a, -a );
glVertex3f( -b, a, -a );
glVertex3f( -b, -a, -a );
glVertex3f( a, b, a );
glVertex3f( -a, b, a );
glVertex3f( a, -b, a );
glVertex3f( -a, -b, a );
glVertex3f( b, a, a );
glVertex3f( b, -a, a );
glVertex3f( -b, a, a );
glVertex3f( -b, -a, a );
glVertex3f( a, -a, b );
glVertex3f( -a, -a, b );
glVertex3f( a, -a, -b );
glVertex3f( -a, -a, -b );
glVertex3f( b, -a, a );
glVertex3f( b, -a, -a );
glVertex3f( -b, -a, a );
glVertex3f( -b, -a, -a );
glVertex3f( -a, a, b );
glVertex3f( -a, -a, b );
glVertex3f( -a, a, -b );
glVertex3f( -a, -a, -b );
glVertex3f( -a, b, a );
glVertex3f( -a, b, -a );
glVertex3f( -a, -b, a );
glVertex3f( -a, -b, -a );
glVertex3f( a, a, b );
glVertex3f( a, -a, b );
glVertex3f( a, a, -b );
glVertex3f( a, -a, -b );
glVertex3f( a, b, a );
glVertex3f( a, b, -a );
glVertex3f( a, -b, a );
glVertex3f( a, -b, -a );
}
glEnd();
glColor3f( 1, 1, 1 );
}
//this function is used to access OpenGL Extensions (special features not supported by all cards)
void* getGLProcAddress( const char* name )
{
return SDL_GL_GetProcAddress( name );
}
//Retrieve the current path of the application
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
std::string getPath()
{
std::string fullpath;
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL( mainBundle );
char path[ PATH_MAX ];
if( !CFURLGetFileSystemRepresentation( resourcesURL, TRUE, (UInt8 *)path, PATH_MAX ) )
{
// error!
}
CFRelease( resourcesURL );
chdir( path );
fullpath = path;
#else
char cCurrentPath[ 1024 ];
if( !GetCurrentDir( cCurrentPath, sizeof( cCurrentPath ) ) )
return "";
cCurrentPath[ sizeof( cCurrentPath ) - 1 ] = '\0';
fullpath = cCurrentPath;
#endif
return fullpath;
}
bool checkGLErrors()
{
#ifdef _DEBUG
GLenum errCode;
const GLubyte *errString;
if( ( errCode = glGetError() ) != GL_NO_ERROR )
{
errString = gluErrorString( errCode );
std::cerr << "OpenGL Error: " << errString << std::endl;
return false;
}
#endif
return true;
}
std::vector<std::string> &split( const std::string &s, char delim, std::vector<std::string> &elems )
{
std::stringstream ss( s );
std::string item;
while( std::getline( ss, item, delim ) )
{
elems.push_back( item );
}
return elems;
}
std::vector<std::string> split( const std::string &s, char delim )
{
std::vector<std::string> elems;
split( s, delim, elems );
return elems;
}
Vector2 getDesktopSize( int display_index )
{
SDL_DisplayMode current;
// Get current display mode of all displays.
int should_be_zero = SDL_GetCurrentDisplayMode( display_index, ¤t );
return Vector2( float( current.w ), float( current.h ) );
}
std::string addCurrentPath( const std::string& p_sInputFile )
{
const char* cCurrentPath = SDL_GetBasePath();
std::stringstream asePathfile;
asePathfile << cCurrentPath << p_sInputFile;
return asePathfile.str();
} | 21.826531 | 119 | 0.625993 | Farmijo |
4508cb48c16844eb379ebe2492f4d32313d48d1b | 9,011 | cpp | C++ | src/BldRecons/DualContouring/HistGrid.cpp | liuxinren/UrbanReconstruction | 079d9b0c9089aa9cdb15d31d76155e50a5e72f00 | [
"MIT"
] | 94 | 2017-07-20T05:32:07.000Z | 2022-03-02T03:38:54.000Z | src/BldRecons/DualContouring/HistGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 3 | 2017-09-12T00:07:05.000Z | 2020-03-08T21:12:36.000Z | src/BldRecons/DualContouring/HistGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 38 | 2017-07-25T06:00:52.000Z | 2022-03-19T10:01:06.000Z | #include "StdAfx.h"
#include "HistGrid.h"
#include "Grid\StreamingGrid.h"
#include "Streaming\SPBReader.h"
#include "nr\nr.h"
#include "nr\nrutil.h"
CHistGrid::CHistGrid(void)
{
m_nGridNumber[ 0 ] = m_nGridNumber[ 1 ] = 0;
}
CHistGrid::~CHistGrid(void)
{
}
void CHistGrid::Init( char filename[], char histfilename[] )
{
LoadFromHist( histfilename );
CStreamingGrid grid;
CSPBReader reader;
reader.OpenFile( filename );
reader.RegisterGrid( & grid );
reader.ReadHeader();
reader.CloseFile();
m_cBoundingBox = grid.m_cBoundingBox;
m_nGridNumber[ 0 ] = ( int )( m_cBoundingBox.GetLength( 0 ) / m_cHeader.center_distance ) + 1;
m_nGridNumber[ 1 ] = ( int )( m_cBoundingBox.GetLength( 1 ) / m_cHeader.center_distance ) + 1;
}
void CHistGrid::LoadFromHist( char filename[] )
{
m_cReader.OpenFile( filename );
m_cHeader = m_cReader.ReadHeader();
m_vecCenter.resize( m_cHeader.number );
m_vecHistogram.resize( m_cHeader.number );
for ( int i = 0; i < m_cHeader.number; i++ ) {
m_cReader.ReadCenter( m_vecCenter[ i ] );
m_cReader.ReadHistogram( m_vecHistogram[ i ] );
}
m_cReader.CloseFile();
}
CHistogram & CHistGrid::LocateHistogram( CVector3D & v )
{
CVector3D diff = v - m_cBoundingBox.m_vMin;
int x = ( int )( diff[0] / m_cHeader.center_distance );
if ( x < 0 )
x = 0;
if ( x >= m_nGridNumber[ 0 ] )
x = m_nGridNumber[ 0 ] - 1;
int y = ( int )( diff[1] / m_cHeader.center_distance );
if ( y < 0 )
y = 0;
if ( y >= m_nGridNumber[ 1 ] )
y = m_nGridNumber[ 1 ] - 1;
return m_vecHistogram[ x * m_nGridNumber[ 1 ] + y ];
}
void CHistGrid::Simplify( CDCContourer & contourer, double error_tolerance, double minimum_length )
{
m_pMesh = & contourer.m_cMesh;
m_pBoundary = & contourer.m_cBoundary;
m_pGrid = contourer.m_pGrid;
m_dbErrorTolerance = error_tolerance;
m_dbMinimumLength = minimum_length;
m_pBoundary->Init( m_pMesh );
for ( int i = 0; i < ( int )m_pBoundary->m_vecBoundary.size(); i++ ) {
FittingPrincipalDirection( m_pBoundary->m_vecBoundarySeq[ i ] );
FixVertices( m_pBoundary->m_vecBoundarySeq[ i ] );
}
}
void CHistGrid::FittingPrincipalDirection( int ibdr )
{
CMeshBoundary::CAuxBoundary & bdr = m_pBoundary->m_vecBoundary[ ibdr ];
int loop_num = ( int )bdr.vi.size();
std::vector< AuxVertex > verts( bdr.vi.size() );
std::vector< AuxLine > lines;
bool line_added = true;
while ( line_added ) {
line_added = false;
AuxLine max_line;
max_line.acc_length = 0.0;
max_line.acc_error = 0.0;
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
if ( verts[ i ].t == FT_Free || ( verts[ i ].t == FT_HalfFixed && verts[ i ].li[ 1 ] != -1 ) ) {
CVector3D loc( m_pMesh->m_vecVertex[ vi ].v );
std::vector< double > & peak = LocateHistogram( loc ).m_vecPeak;
for ( int j = 0; j < ( int )peak.size(); j++ ) {
CLine temp_line;
temp_line.p = CVector3D( m_pMesh->m_vecVertex[ vi ].v );
temp_line.d = CVector3D( cos( peak[j] ), sin( peak[j] ), 0.0 );
int k_forward = 0, k_backward = 0;
int iteration_step = m_pBoundary->m_vecGroupInfo[ vi ].fixed ? 1 : 3;
double acc_length = 0.0;
double acc_error = 0.0;
for ( int step = 0; step < iteration_step; step++ ) {
acc_length = 0.0;
acc_error = 0.0;
if ( ( acc_error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ vi ].v ) ) ) > m_dbErrorTolerance ) {
k_forward = k_backward = 0;
break;
}
for ( k_forward = 1; k_forward < loop_num; k_forward++ ) {
int idx = ( i + k_forward ) % loop_num;
double error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) );
if ( m_pBoundary->m_vecGroupInfo[ bdr.vi[ idx ] ].fixed
|| verts[ idx ].t == FT_Fixed
|| ( verts[ idx ].t == FT_HalfFixed && verts[ idx ].li[1] != -1 )
|| error > m_dbErrorTolerance )
{
break;
} else if ( verts[ idx ].t == FT_HalfFixed )
{
if ( lines[ verts[ idx ].li[ 0 ] ].pi == j ) {
break;
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_forward - 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
k_forward++;
break;
}
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_forward - 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
}
}
if ( k_forward < loop_num ) {
for ( k_backward = -1; k_backward > -loop_num; k_backward-- ) {
int idx = ( i + k_backward + loop_num ) % loop_num;
double error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) );
if ( m_pBoundary->m_vecGroupInfo[ bdr.vi[ idx ] ].fixed
|| verts[ idx ].t == FT_Fixed
|| ( verts[ idx ].t == FT_HalfFixed && verts[ idx ].li[1] != -1 )
|| error > m_dbErrorTolerance )
{
break;
} else if ( verts[ idx ].t == FT_HalfFixed )
{
if ( lines[ verts[ idx ].li[ 0 ] ].pi == j ) {
break;
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_backward + loop_num + 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
k_backward--;
break;
}
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_backward + loop_num + 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
}
}
k_backward++;
}
if ( m_pBoundary->m_vecGroupInfo[ vi ].fixed == false ) {
// use iteration
// update temp_line.p
if ( acc_length > m_dbMinimumLength ) {
temp_line.p = CVector3D( 0.0, 0.0, 0.0 );
for ( int k = k_backward; k < k_forward; k++ ) {
temp_line.p += CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k + loop_num ) % loop_num ] ].v );
}
temp_line.p /= ( double )( k_forward - k_backward );
}
}
}
int k_number = k_forward - k_backward;
if ( acc_length > m_dbMinimumLength && IsBetterMaxLine( acc_length, acc_error, max_line ) ) {
//printf_s( "%8.6f\n", peak[ j ] );
max_line.l = temp_line;
max_line.pi = j;
max_line.acc_length = acc_length;
max_line.vi.clear();
for ( int k = k_backward; k < k_forward; k++ ) {
max_line.vi.push_back( ( i + k + loop_num ) % loop_num );
}
}
}
}
}
if ( max_line.acc_length > m_dbMinimumLength && ( int )max_line.vi.size() < loop_num ) {
// push max_line to aux
int line_idx = ( int )lines.size();
lines.push_back( max_line );
for ( int i = 0; i <= ( int )( max_line.vi.size() - 1 ); i += ( int )( max_line.vi.size() - 1 ) ) {
verts[ max_line.vi[ i ] ].t = FT_HalfFixed;
if ( verts[ max_line.vi[ i ] ].li[ 0 ] == -1 ) {
verts[ max_line.vi[ i ] ].li[ 0 ] = line_idx;
} else {
verts[ max_line.vi[ i ] ].li[ 1 ] = line_idx;
}
}
for ( int i = 1; i < ( int )max_line.vi.size() - 1; i++ ) {
verts[ max_line.vi[ i ] ].t = FT_Fixed;
verts[ max_line.vi[ i ] ].li[ 0 ] = line_idx;
}
line_added = true;
}
}
FittingSimplify( bdr, verts, lines );
}
void CHistGrid::FittingSimplify( CMeshBoundary::CAuxBoundary & bdr, std::vector< AuxVertex > & verts, std::vector< AuxLine > & lines )
{
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
CVector3D v( m_pMesh->m_vecVertex[ vi ].v );
if ( verts[ i ].t == FT_Fixed || ( verts[ i ].t == FT_HalfFixed && verts[ i ].li[ 1 ] == -1 ) ) {
v = lines[ verts[ i ].li[ 0 ] ].l.project( v );
} else if ( verts[ i ].t == FT_HalfFixed ) {
CVector3D inter = lines[ verts[ i ].li[ 0 ] ].l ^ lines[ verts[ i ].li[ 1 ] ].l;
inter.pVec[ 2 ] = v.pVec[ 2 ];
if ( ( inter - v ).length() < m_dbErrorTolerance * 1.414 ) {
v = inter;
}
} else {
// do nothing
}
m_pMesh->m_vecVertex[ vi ].v[ 0 ] = v.pVec[ 0 ];
m_pMesh->m_vecVertex[ vi ].v[ 1 ] = v.pVec[ 1 ];
}
}
void CHistGrid::FixVertices( int ibdr )
{
CMeshBoundary::CAuxBoundary & bdr = m_pBoundary->m_vecBoundary[ ibdr ];
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
CMeshBoundary::CVertexGroupInfo & hi = m_pBoundary->m_vecGroupInfo[ vi ];
for ( int j = 0; j < hi.number; j++ ) {
int vvi = vi - hi.index + j;
m_pMesh->m_vecVertex[ vvi ].v[ 0 ] = m_pMesh->m_vecVertex[ vi ].v[ 0 ];
m_pMesh->m_vecVertex[ vvi ].v[ 1 ] = m_pMesh->m_vecVertex[ vi ].v[ 1 ];
m_pBoundary->m_vecGroupInfo[ vvi ].fixed = true;
}
}
}
| 31.506993 | 177 | 0.577183 | liuxinren |
4509d3c0968ba0bba96943f5365a8882fdc6d99b | 11,188 | cpp | C++ | view/src/dialogs/create_strategy_dialog.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 21 | 2020-06-07T20:34:47.000Z | 2021-08-10T20:19:59.000Z | view/src/dialogs/create_strategy_dialog.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | null | null | null | view/src/dialogs/create_strategy_dialog.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 4 | 2020-07-13T10:19:44.000Z | 2022-03-11T12:15:43.000Z | /*
* Copyright (c) 2020, Rapprise.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "include/dialogs/create_strategy_dialog.h"
#include "include/dialogs/bb_advanced_settings_dialog.h"
#include "include/dialogs/bb_settings_dialog.h"
#include "include/dialogs/ema_settings_dialog.h"
#include "include/dialogs/moving_average_crossing_settings_dialog.h"
#include "include/dialogs/rsi_settings_dialog.h"
#include "include/dialogs/sma_settings_dialog.h"
#include "include/dialogs/stochastic_oscillator_dialog.h"
namespace auto_trader {
namespace view {
namespace dialogs {
CreateStrategyDialog::CreateStrategyDialog(common::AppListener &appListener,
common::GuiListener &guiListener, DialogType dialogType,
QWidget *parent)
: QDialog(parent),
appListener_(appListener),
guiListener_(guiListener),
dialogType_(dialogType) {
dialog_.setupUi(this);
dialog_.listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
dialog_.listView_2->setSelectionMode(QAbstractItemView::SingleSelection);
dialog_.listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
dialog_.listView_2->setEditTriggers(QAbstractItemView::NoEditTriggers);
customStrategySettings_ = std::make_unique<model::CustomStrategySettings>();
strategySettingsFactory_ = std::make_unique<model::StrategySettingsFactory>();
initStrategiesList();
sizeHint();
checkOkButtonStatus(QString());
connect(dialog_.pushButton, SIGNAL(clicked()), this, SLOT(selectStrategy()));
connect(dialog_.pushButton_2, SIGNAL(clicked()), this, SLOT(removeStrategy()));
connect(dialog_.pushButton_3, SIGNAL(clicked()), this, SLOT(editStrategy()));
connect(dialog_.buttonBox, SIGNAL(accepted()), this, SLOT(closeDialog()));
connect(dialog_.buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
connect(dialog_.lineEdit, SIGNAL(textChanged(const QString &)), this,
SLOT(checkOkButtonStatus(const QString &)));
connect(this, SIGNAL(strategiesNumberChanged(const QString &)), this,
SLOT(checkOkButtonStatus(const QString &)));
}
void CreateStrategyDialog::setupDefaultParameters(const model::CustomStrategySettings &settings) {
customStrategyName_ = settings.name_;
dialog_.textEdit->insertPlainText(QString::fromStdString(settings.description_));
dialog_.lineEdit->setText(QString::fromStdString(customStrategyName_));
for (int index = 0; index < settings.strategies_.size(); index++) {
auto strategy = settings.strategies_.at(index).get();
selectedStrategiesList_->append(QString::fromStdString(strategy->name_));
strategySettings_.insert(std::make_pair<>(strategy->strategiesType_, strategy->clone()));
}
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
checkOkButtonStatus(QString());
}
void CreateStrategyDialog::selectStrategy() {
for (const QModelIndex &index : dialog_.listView->selectionModel()->selectedIndexes()) {
auto selectedStrategy = currentStrategiesModel_->data(index).toString();
if (selectedStrategiesList_->indexOf(selectedStrategy) == -1) {
selectedStrategiesList_->append(selectedStrategy);
common::StrategiesType type =
common::convertStrategyTypeFromString(selectedStrategy.toStdString());
const std::string strategyName = selectedStrategy.toStdString();
auto strategySettings = strategySettingsFactory_->createStrategySettings(type);
strategySettings->strategiesType_ = type;
strategySettings->name_ = strategyName;
strategySettings_.insert(std::make_pair<>(type, std::move(strategySettings)));
}
}
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
emit strategiesNumberChanged(QString());
}
void CreateStrategyDialog::removeStrategy() {
QModelIndex modelIndex = dialog_.listView_2->currentIndex();
QString itemText = modelIndex.data(Qt::DisplayRole).toString();
common::StrategiesType type = common::convertStrategyTypeFromString(itemText.toStdString());
strategySettings_.erase(type);
int indexToRemove = selectedStrategiesList_->indexOf(itemText);
selectedStrategiesList_->removeAt(indexToRemove);
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
emit strategiesNumberChanged(QString());
}
void CreateStrategyDialog::editStrategy() {
QModelIndex modelIndex = dialog_.listView_2->currentIndex();
QString itemText = modelIndex.data(Qt::DisplayRole).toString();
common::StrategiesType type = common::convertStrategyTypeFromString(itemText.toStdString());
openEditStrategySettingsDialog(type);
}
void CreateStrategyDialog::initStrategiesList() {
currentStrategiesList_ = new QStringList();
selectedStrategiesList_ = new QStringList();
auto lastElement = (unsigned short)common::StrategiesType::UNKNOWN;
for (unsigned short index = 0; index < lastElement; ++index) {
auto type = (common::StrategiesType)index;
// TODO: Add MACD indicator to UI
if (type != common::StrategiesType::CUSTOM && type != common::StrategiesType::MACD) {
const std::string strategyStr = common::convertStrategyTypeToString(type);
currentStrategiesList_->append(QString::fromStdString(strategyStr));
}
}
currentStrategiesModel_ = new QStringListModel(*currentStrategiesList_, this);
selectedStrategiesModel_ = new QStringListModel(*selectedStrategiesList_, this);
dialog_.listView->setModel(currentStrategiesModel_);
dialog_.listView_2->setModel(selectedStrategiesModel_);
}
void CreateStrategyDialog::openEditStrategySettingsDialog(common::StrategiesType type) {
auto &strategySettings = strategySettings_[type];
switch (type) {
case common::StrategiesType::BOLLINGER_BANDS: {
auto bbSettings = dynamic_cast<model::BollingerBandsSettings *>(strategySettings.get());
auto dialog = new BBSettingsDialog(*bbSettings, appListener_, guiListener_,
BBSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::BOLLINGER_BANDS_ADVANCED: {
auto bbAdvancedSettings =
dynamic_cast<model::BollingerBandsAdvancedSettings *>(strategySettings.get());
auto dialog = new BBAdvancedSettingsDialog(*bbAdvancedSettings, appListener_, guiListener_,
BBAdvancedSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::SMA: {
auto smaSettings = dynamic_cast<model::SmaSettings *>(strategySettings.get());
auto dialog = new SmaSettingsDialog(*smaSettings, appListener_, guiListener_,
SmaSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::EMA: {
auto emaSettings = dynamic_cast<model::EmaSettings *>(strategySettings.get());
auto dialog = new EmaSettingsDialog(*emaSettings, appListener_, guiListener_,
EmaSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::RSI: {
auto rsiSettings = dynamic_cast<model::RsiSettings *>(strategySettings.get());
auto dialog = new RsiSettingsDialog(*rsiSettings, appListener_, guiListener_,
RsiSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::MA_CROSSING: {
auto maCrossings =
dynamic_cast<model::MovingAveragesCrossingSettings *>(strategySettings.get());
auto dialog = new MovingAverageCrossingSettingsDialog(
*maCrossings, appListener_, guiListener_, MovingAverageCrossingSettingsDialog::CREATE,
this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::STOCHASTIC_OSCILLATOR: {
auto stochasticOscillator =
dynamic_cast<model::StochasticOscillatorSettings *>(strategySettings.get());
auto dialog =
new StochasticOscillatorSettingsDialog(*stochasticOscillator, appListener_, guiListener_,
StochasticOscillatorSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
default:
break;
}
}
void CreateStrategyDialog::closeDialog() {
customStrategySettings_->name_ = dialog_.lineEdit->text().toStdString();
customStrategySettings_->description_ = dialog_.textEdit->toPlainText().toStdString();
customStrategySettings_->strategiesType_ = common::StrategiesType::CUSTOM;
for (auto &strategy : strategySettings_) {
auto strategySetting = std::move(strategy.second);
customStrategySettings_->strategies_.push_back(std::move(strategySetting));
}
refreshStrategySettings();
accept();
}
void CreateStrategyDialog::refreshStrategySettings() {
switch (dialogType_) {
case DialogType::CREATE: {
guiListener_.createCustomStrategy(std::move(customStrategySettings_));
} break;
case DialogType::EDIT: {
guiListener_.editCustomStrategy(std::move(customStrategySettings_), customStrategyName_);
} break;
default:
break;
}
}
void CreateStrategyDialog::checkOkButtonStatus(const QString &text) {
bool isStrategiesEmpty = selectedStrategiesList_->isEmpty();
bool isStrategyNameEmpty = dialog_.lineEdit->text().isEmpty();
bool isButtonDisabled = isStrategiesEmpty || isStrategyNameEmpty;
dialog_.buttonBox->button(QDialogButtonBox::StandardButton::Ok)->setDisabled(isButtonDisabled);
}
} // namespace dialogs
} // namespace view
} // namespace auto_trader
| 44.752 | 99 | 0.734448 | Rapprise |
45101effd84ca56fc730178726b7cfc86c423223 | 2,961 | hxx | C++ | main/chart2/source/controller/dialogs/res_LegendPosition.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/chart2/source/controller/dialogs/res_LegendPosition.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/chart2/source/controller/dialogs/res_LegendPosition.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _CHART2_RES_LEGENPOSITION_HXX
#define _CHART2_RES_LEGENPOSITION_HXX
// header for class CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#include <vcl/fixed.hxx>
// header for class SfxItemSet
#include <svl/itemset.hxx>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
class LegendPositionResources
{
public:
//constructor without Display checkbox
LegendPositionResources( Window* pParent );
//constructor inclusive Display checkbox
LegendPositionResources( Window* pParent, const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext>& xCC );
virtual ~LegendPositionResources();
void writeToResources( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xChartModel );
void writeToModel( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xChartModel ) const;
void initFromItemSet( const SfxItemSet& rInAttrs );
void writeToItemSet( SfxItemSet& rOutAttrs ) const;
void SetChangeHdl( const Link& rLink );
DECL_LINK( PositionEnableHdl, void* );
DECL_LINK( PositionChangeHdl, RadioButton* );
void SetAccessibleRelationMemberOf(Window* pMemberOf);
private:
void impl_setRadioButtonToggleHdl();
private:
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext> m_xCC;
CheckBox m_aCbxShow;
RadioButton m_aRbtLeft;
RadioButton m_aRbtRight;
RadioButton m_aRbtTop;
RadioButton m_aRbtBottom;
Link m_aChangeLink;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
| 33.269663 | 82 | 0.602837 | Grosskopf |
4510d4458aa07eb868185955251224615ae7b445 | 2,034 | cpp | C++ | sandbox-app/source/camera_controller.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | sandbox-app/source/camera_controller.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | sandbox-app/source/camera_controller.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Konstanty Misiak
*
* SPDX-License-Identifier: MIT
*/
#include "camera_controller.hpp"
CameraController::CameraController(float aspectRatio) :
m_aspectRatio(aspectRatio),
m_zoomLevel(1.f),
m_camera(-aspectRatio*2.f, aspectRatio*2.f, -2.f, 2.f),
m_cameraPosition(0.f, 0.f),
m_cameraMoveSpeed(2.f) {}
void CameraController::onUpdate(float dt)
{
glm::vec2 move{};
if (k2d::Input::isKeyPressed(k2d::Key::W))
move.y = m_cameraMoveSpeed;
else if (k2d::Input::isKeyPressed(k2d::Key::S))
move.y = -m_cameraMoveSpeed;
if (k2d::Input::isKeyPressed(k2d::Key::A))
move.x = -m_cameraMoveSpeed;
else if (k2d::Input::isKeyPressed(k2d::Key::D))
move.x = m_cameraMoveSpeed;
if (move.x != 0.f || move.y != 0)
{
move = glm::normalize(move);
m_cameraPosition += move * dt * m_zoomLevel;
m_camera.setPosition(m_cameraPosition);
}
}
void CameraController::onEvent(k2d::Event& event)
{
k2d::EventDispatcher dispatcher(event);
dispatcher.dispatch<k2d::MouseScrollEvent>(K2D_BIND_EVENT_FUNC(CameraController::onMouseScroll));
dispatcher.dispatch<k2d::WindowResizeEvent>(K2D_BIND_EVENT_FUNC(CameraController::onWindowResize));
}
bool CameraController::onMouseScroll(k2d::MouseScrollEvent& event)
{
m_zoomLevel -= (event.getYOffset() * 0.05f);
if (m_zoomLevel < 0.01f)
m_zoomLevel = 0.01f;
else if (m_zoomLevel > 10.f)
m_zoomLevel = 10.f;
m_camera.setProjection(
-m_aspectRatio * m_zoomLevel * 2.f, m_aspectRatio * m_zoomLevel * 2.f,
-m_zoomLevel * 2.f, m_zoomLevel * 2.f
);
return true;
}
bool CameraController::onWindowResize(k2d::WindowResizeEvent& event)
{
m_aspectRatio = static_cast<float>(event.getWidth()) / static_cast<float>(event.getHeight());
m_camera.setProjection(
-m_aspectRatio * m_zoomLevel * 2.f, m_aspectRatio * m_zoomLevel * 2.f,
-m_zoomLevel * 2.f, m_zoomLevel * 2.f
);
return false;
}
| 29.478261 | 103 | 0.666175 | Kostu96 |
451269f6cda1663e1fe712d02e3fa2eb39c1f1c0 | 546 | cpp | C++ | hackerrank/algorithms/2-implementation/047.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | null | null | null | hackerrank/algorithms/2-implementation/047.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | null | null | null | hackerrank/algorithms/2-implementation/047.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | 2 | 2018-10-04T19:01:52.000Z | 2018-10-05T08:49:57.000Z | #include<stdio.h>
#include<time.h>
int ackerman(int m, int n){
int result;
if(m == 0){
result = n + 1;
}
else if(n == 0){
result = ackerman(m - 1, 1);
}
else{
result = ackerman(m - 1, ackerman(m, n - 1));
}
return result;
}
int main(void){
int i,j;
clock_t begin = clock();
for(i = 0; i < 6 ; i ++){
for(j = 0; j < 6; j ++){
printf("i = %d j = %d ackerman(i, j) = %d\t%f\n",i,j,ackerman(i, j),(double)(clock() - begin) / CLOCKS_PER_SEC);
}
}
}
| 21.84 | 126 | 0.454212 | him1411 |
451303bf0bff68686094fb1683725c2755543be8 | 11,453 | hpp | C++ | include/snowflake/ecs/component_storage.hpp | robclu/glow | 4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2 | [
"MIT"
] | 1 | 2021-12-08T09:23:55.000Z | 2021-12-08T09:23:55.000Z | include/snowflake/ecs/component_storage.hpp | robclu/snowflake | 4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2 | [
"MIT"
] | null | null | null | include/snowflake/ecs/component_storage.hpp | robclu/snowflake | 4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2 | [
"MIT"
] | null | null | null | //==--- snowflake/ecs/component_storage.hpp ---------------- -*- C++ -*- ---==//
//
// Snowflake
//
// Copyright (c) 2020 Rob Clucas
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//==------------------------------------------------------------------------==//
//
/// \file component_storage.hpp
/// \brief This file defines storage for component.
//
//==------------------------------------------------------------------------==//
#ifndef SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
#define SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
#include "sparse_set.hpp"
namespace snowflake {
/**
* Implemenatation of a storage class for components. This is essentially just
* a wrapper around a SparseSet which stores the entities and components such
* that they are ordered the same way, and both contiguously.
*
* \note The ordering of the components and the entities are the same, so random
* access into the containers is valid.
*
* \note The order of insertion into the container is not preserved.
*
* \see SparseSet
*
* \tparam Entity The type of the entity.
* \tparam Component The type of the component.
* \tparam EntityAllocator The type of the entity allocator.
*/
template <
typename Entity,
typename Component,
typename EntityAllocator = wrench::ObjectPoolAllocator<Entity>>
class ComponentStorage : public SparseSet<Entity, EntityAllocator> {
// clang-format off
/** Storage type for the entities */
using Entities = SparseSet<Entity, EntityAllocator>;
/** Defines the type for the components. */
using Components = std::vector<Component>;
// clang-format on
public:
// clang-format off
/** The size type. */
using SizeType = size_t;
/** The iterator type used for the components. */
using Iterator = ReverseIterator<Components, false>;
/** The const iterator type for the components. */
using ConstIterator = ReverseIterator<Components, true>;
/** The reverse iterator type for the components. */
using ReverseIterator = Component*;
/** The const reverse iterator type for the components. */
using ConstReverseIterator = const Component*;
// clang-format on
/** The page size for the storage. */
static constexpr size_t page_size = Entities::page_size;
/**
* Default constructor for storage -- this does not use an allocator for
* entities.
*/
ComponentStorage() noexcept = default;
/**
* Constructor which sets the allocator for the entities.
* \param allocator The allocator for the entities.
*/
ComponentStorage(EntityAllocator* allocator) noexcept : Entities{allocator} {}
/**
* Reserves enough space to emplace \p size compoennts.
* \param size The number of entities to reserve.
*/
auto reserve(SizeType size) noexcept -> void {
components_.reserve(size);
Entities::reserve(size);
}
/**
* Emplaces a component into the storage.
*
* \note If the entity is already assosciated with this component, then this
* will cause undefined behaviour in release, or assert in debug.
*
* \param entity The entity to emplace the component for.
* \param args Arguments for the construciton of the component.
* \tparam Args The type of the args.
*/
template <typename... Args>
auto emplace(const Entity& entity, Args&&... args) -> void {
// Many components are aggregates, and emplace back doesn't work with
// aggregates, so we need to differentiate.
if constexpr (std::is_aggregate_v<Component>) {
if constexpr (constexpr_component_id_v<Component>) {
components_.push_back(Component{{}, std::forward<Args>(args)...});
} else {
components_.push_back(Component{std::forward<Args>(args)...});
}
} else {
components_.emplace_back(std::forward<Args>(args)...);
}
Entities::emplace(entity);
}
/**
* Removes the component assosciated with the entity from the storage.
*
* \note If the entity does not exist then this will assert in debug builds,
* while in release builds it will cause undefined behaviour.
*
* \param entity The entity to remove.
*/
auto erase(const Entity& entity) noexcept -> void {
auto back = std::move(components_.back());
components_[Entities::index(entity)] = std::move(back);
components_.pop_back();
Entities::erase(entity);
}
/**
* Swaps two components in the storage.
*
*
* \note If either of the entities assosciated with the components are not
* present then this will cause undefined behaviour in release, or
* assert in debug.
*
* \param a A component to swap with.
* \param b A component to swap with.
*/
auto swap(const Entity& a, const Entity& b) noexcept -> void {
std::swap(components_[Entities::index(a)], components_[Entities::index(b)]);
Entities::swap(a, b);
}
/**
* Gets the component assosciated with the given entity.
*
* \note If the entity does not exist, this causes endefined behaviour in
* release, or asserts in debug.
*
* \param entity The entity to get the component for.
* \return A reference to the component.
*/
auto get(const Entity& entity) -> Component& {
return components_[Entities::index(entity)];
}
/**
* Gets the component assosciated with the given entity.
*
* \note If the entity does not exist, this causes endefined behaviour in
* release, or asserts in debug.
*
* \param entity The entity to get the component for.
* \return A const reference to the component.
*/
auto get(const Entity& entity) const -> const Component& {
return components_[Entities::index(entity)];
}
/*==--- [iteration] ------------------------------------------------------==*/
/**
* Returns an iterator to the beginning of the components.
*
* The returned iterator points to the *most recently inserted* component and
* iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto begin() noexcept -> Iterator {
using size_type = typename Iterator::difference_type;
return Iterator{components_, static_cast<size_type>(components_.size())};
}
/**
* Returns an iterator to the end of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto end() noexcept -> Iterator {
using size_type = typename Iterator::difference_type;
return Iterator{components_, size_type{0}};
}
/**
* Returns a const iterator to the beginning of components.
*
* The returned iterator points to the *most recently inserted* component and
* iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto cbegin() const noexcept -> ConstIterator {
using size_type = typename ConstIterator::difference_type;
return ConstIterator{
components_, static_cast<size_type>(components_.size())};
}
/**
* Returns a const iterator to the end of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto cend() const noexcept -> ConstIterator {
using size_type = typename ConstIterator::difference_type;
return ConstIterator{components_, size_type{0}};
}
/**
* Returns a reverse iterator to the beginning of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *lest* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto rbegin() const noexcept -> ReverseIterator {
return components_.data();
}
/**
* Returns a reverse iterator to the end of the set.
*
* The returned iterator points to the *most recently inserted* component
* and iterates from *least* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto rend() const noexcept -> ReverseIterator {
return rbegin() + components_.size();
}
/**
* Returns a const reverse iterator to the beginning of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *lest* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto crbegin() const noexcept -> ConstReverseIterator {
return components_.data();
}
/**
* Returns a const reverse iterator to the end of the set.
*
* The returned iterator points to the *most recently inserted* component
* and iterates from *least* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto crend() const noexcept -> ConstReverseIterator {
return rbegin() + components_.size();
}
/*==--- [algorithms] -----------------------------------------------------==*/
/**
* Finds a component, if it exists.
*
* If the component doesn't exist, this returns an iterator to the end of the
* set, otherwise it returns an iterator to the found component.
*
* \param entity The entity to find.
* \return A valid iterator if found, otherwise an iterator to the end of the
* storage.
*/
snowflake_nodiscard auto find(const Entity& entity) noexcept -> Iterator {
return Entities::exists(entity)
? --Iterator(end() - Entities::index(entity))
: end();
}
/**
* Finds a component, if it exists.
*
* If the component doesn't exist, this returns an iterator to the end of the
* set, otherwise it returns an iterator to the found component.
*
* \param entity The entity to find.
* \return A valid iterator if found, otherwise an iterator to the end of the
* storage.
*/
snowflake_nodiscard auto
find(const Entity& entity) const noexcept -> ConstIterator {
return Entities::exists(entity)
? --ConstIterator(end() - Entities::index(entity))
: end();
}
private:
Components components_ = {}; //!< Container of components.
};
} // namespace snowflake
#endif // SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
| 33.985163 | 80 | 0.660788 | robclu |
4516c247599a1f56ec33c0806ba26fb381f3d9b2 | 11,413 | hpp | C++ | src/lapack_like/spectral/HessenbergSchur/Util/Gather.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 473 | 2015-01-11T03:22:11.000Z | 2022-03-31T05:28:39.000Z | src/lapack_like/spectral/HessenbergSchur/Util/Gather.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 205 | 2015-01-10T20:33:45.000Z | 2021-07-25T14:53:25.000Z | src/lapack_like/spectral/HessenbergSchur/Util/Gather.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 109 | 2015-02-16T14:06:42.000Z | 2022-03-23T21:34:26.000Z | /*
Copyright (c) 2009-2016, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef EL_HESS_SCHUR_UTIL_GATHER_HPP
#define EL_HESS_SCHUR_UTIL_GATHER_HPP
namespace El {
namespace hess_schur {
namespace util {
template<typename Field>
void GatherSubdiagonal
( const DistMatrix<Field,MC,MR,BLOCK>& H,
const IR& winInd,
DistMatrix<Field,STAR,STAR>& hSubWin )
{
EL_DEBUG_CSE
const Int winSize = winInd.end - winInd.beg;
const Int blockSize = H.BlockHeight();
const Grid& grid = H.Grid();
const auto& HLoc = H.LockedMatrix();
EL_DEBUG_ONLY(
if( H.BlockHeight() != H.BlockWidth() )
LogicError("Assumed square distribution blocks");
if( H.ColCut() != H.RowCut() )
LogicError("Assumed symmetric cuts");
if( blockSize < 2 )
LogicError("Assumed blocks of size at least two");
)
Zeros( hSubWin, winSize-1, 1 );
// TODO(poulson): Optimize these redistributions
hSubWin.Reserve( winSize-1 );
Int localRowOffset = H.LocalRowOffset( winInd.beg );
Int localColOffset = H.LocalColOffset( winInd.beg );
int rowOwner = H.RowOwner( winInd.beg );
int colOwner = H.ColOwner( winInd.beg );
Int thisCut = Mod( H.ColCut()+winInd.beg, H.BlockHeight() );
Int winIndex = 0;
while( winIndex < winSize )
{
const Int thisBlockSize = Min( blockSize-thisCut, winSize-winIndex );
const int nextRowOwner = Mod( rowOwner+1, grid.Height() );
const int nextColOwner = Mod( colOwner+1, grid.Width() );
// ---------------------------
// | x x x x x x | x x x x x x |
// | s x x x x x | x x x x x x |
// | s x x x x | x x x x x x |
// | s x x x | x x x x x x |
// | s x x | x x x x x x |
// | s x | x x x x x x |
// |-------------|-------------|
// | s | x x x x x x |
// | | s x x x x x |
// | | s x x x x |
// | | s x x x |
// | | s x x |
// | | s x |
// ---------------------------
const bool haveLastOff = (winSize > winIndex+thisBlockSize);
// Handle this main diagonal block
if( colOwner == grid.Col() && rowOwner == grid.Row() )
{
for( Int offset=0; offset<thisBlockSize; ++offset )
{
if( offset < thisBlockSize-1 )
hSubWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset+1,localColOffset+offset) );
}
}
// Handle the last subdiagonal (if it exists)
if( haveLastOff &&
nextRowOwner == grid.Row() && colOwner == grid.Col() )
{
const Int subLocalRowOffset = localRowOffset +
( grid.Height() == 1 ? thisBlockSize : 0 );
hSubWin.QueueUpdate
( winIndex+thisBlockSize-1, 0,
HLoc(subLocalRowOffset,localColOffset+thisBlockSize-1) );
}
winIndex += thisBlockSize;
thisCut = 0;
if( colOwner == grid.Col() )
localColOffset += thisBlockSize;
if( rowOwner == grid.Row() )
localRowOffset += thisBlockSize;
rowOwner = nextRowOwner;
colOwner = nextColOwner;
}
hSubWin.ProcessQueues();
}
template<typename Field>
void GatherBidiagonal
( const DistMatrix<Field,MC,MR,BLOCK>& H,
const IR& winInd,
DistMatrix<Field,STAR,STAR>& hMainWin,
DistMatrix<Field,STAR,STAR>& hSubWin )
{
EL_DEBUG_CSE
const Int winSize = winInd.end - winInd.beg;
const Int blockSize = H.BlockHeight();
const Grid& grid = H.Grid();
const auto& HLoc = H.LockedMatrix();
EL_DEBUG_ONLY(
if( H.BlockHeight() != H.BlockWidth() )
LogicError("Assumed square distribution blocks");
if( H.ColCut() != H.RowCut() )
LogicError("Assumed symmetric cuts");
if( blockSize < 2 )
LogicError("Assumed blocks of size at least two");
)
Zeros( hMainWin, winSize, 1 );
Zeros( hSubWin, winSize-1, 1 );
// TODO(poulson): Optimize these redistributions
hMainWin.Reserve( winSize );
hSubWin.Reserve( winSize-1 );
Int localRowOffset = H.LocalRowOffset( winInd.beg );
Int localColOffset = H.LocalColOffset( winInd.beg );
int rowOwner = H.RowOwner( winInd.beg );
int colOwner = H.ColOwner( winInd.beg );
Int thisCut = Mod( H.ColCut()+winInd.beg, H.BlockHeight() );
Int winIndex = 0;
while( winIndex < winSize )
{
const Int thisBlockSize = Min( blockSize-thisCut, winSize-winIndex );
const int nextRowOwner = Mod( rowOwner+1, grid.Height() );
const int nextColOwner = Mod( colOwner+1, grid.Width() );
// ---------------------------
// | m x x x x x | x x x x x x |
// | s m x x x x | x x x x x x |
// | s m x x x | x x x x x x |
// | s m x x | x x x x x x |
// | s m x | x x x x x x |
// | s m | x x x x x x |
// |-------------|-------------|
// | s | m x x x x x |
// | | s m x x x x |
// | | s m x x x |
// | | s m x x |
// | | s m x |
// | | s m |
// ---------------------------
const bool haveLastOff = (winSize > winIndex+thisBlockSize);
// Handle this main diagonal block
if( colOwner == grid.Col() && rowOwner == grid.Row() )
{
for( Int offset=0; offset<thisBlockSize; ++offset )
{
hMainWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset,localColOffset+offset) );
if( offset < thisBlockSize-1 )
hSubWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset+1,localColOffset+offset) );
}
}
// Handle the last subdiagonal (if it exists)
if( haveLastOff &&
nextRowOwner == grid.Row() && colOwner == grid.Col() )
{
const Int subLocalRowOffset = localRowOffset +
( grid.Height() == 1 ? thisBlockSize : 0 );
hSubWin.QueueUpdate
( winIndex+thisBlockSize-1, 0,
HLoc(subLocalRowOffset,localColOffset+thisBlockSize-1) );
}
winIndex += thisBlockSize;
thisCut = 0;
if( colOwner == grid.Col() )
localColOffset += thisBlockSize;
if( rowOwner == grid.Row() )
localRowOffset += thisBlockSize;
rowOwner = nextRowOwner;
colOwner = nextColOwner;
}
hMainWin.ProcessQueues();
hSubWin.ProcessQueues();
}
template<typename Field>
void GatherTridiagonal
( const DistMatrix<Field,MC,MR,BLOCK>& H,
const IR& winInd,
DistMatrix<Field,STAR,STAR>& hMainWin,
DistMatrix<Field,STAR,STAR>& hSubWin,
DistMatrix<Field,STAR,STAR>& hSuperWin )
{
EL_DEBUG_CSE
const Int winSize = winInd.end - winInd.beg;
const Int blockSize = H.BlockHeight();
const Grid& grid = H.Grid();
const auto& HLoc = H.LockedMatrix();
EL_DEBUG_ONLY(
if( H.BlockHeight() != H.BlockWidth() )
LogicError("Assumed square distribution blocks");
if( H.ColCut() != H.RowCut() )
LogicError("Assumed symmetric cuts");
if( blockSize < 2 )
LogicError("Assumed blocks of size at least two");
)
Zeros( hMainWin, winSize, 1 );
Zeros( hSubWin, winSize-1, 1 );
Zeros( hSuperWin, winSize-1, 1 );
// TODO(poulson): Optimize these redistributions
hMainWin.Reserve( winSize );
hSubWin.Reserve( winSize-1 );
hSuperWin.Reserve( winSize-1 );
Int localRowOffset = H.LocalRowOffset( winInd.beg );
Int localColOffset = H.LocalColOffset( winInd.beg );
int rowOwner = H.RowOwner( winInd.beg );
int colOwner = H.ColOwner( winInd.beg );
Int thisCut = Mod( H.ColCut()+winInd.beg, H.BlockHeight() );
Int winIndex = 0;
while( winIndex < winSize )
{
const Int thisBlockSize = Min( blockSize-thisCut, winSize-winIndex );
const int nextRowOwner = Mod( rowOwner+1, grid.Height() );
const int nextColOwner = Mod( colOwner+1, grid.Width() );
// ---------------------------
// | m S x x x x | x x x x x x |
// | s m S x x x | x x x x x x |
// | s m S x x | x x x x x x |
// | s m S x | x x x x x x |
// | s m S | x x x x x x |
// | s m | S x x x x x |
// |-------------|-------------|
// | s | m S x x x x |
// | | s m S x x x |
// | | s m S x x |
// | | s m S x |
// | | s m S |
// | | s m |
// ---------------------------
const bool haveLastOff = (winSize > winIndex+thisBlockSize);
// Handle this main diagonal block
if( colOwner == grid.Col() && rowOwner == grid.Row() )
{
for( Int offset=0; offset<thisBlockSize; ++offset )
{
hMainWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset,localColOffset+offset) );
if( offset < thisBlockSize-1 )
hSubWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset+1,localColOffset+offset) );
if( offset < thisBlockSize-1 )
hSuperWin.QueueUpdate
( winIndex+offset, 0,
HLoc(localRowOffset+offset,localColOffset+offset+1) );
}
}
// Handle the last subdiagonal (if it exists)
if( haveLastOff &&
nextRowOwner == grid.Row() && colOwner == grid.Col() )
{
const Int subLocalRowOffset = localRowOffset +
( grid.Height() == 1 ? thisBlockSize : 0 );
hSubWin.QueueUpdate
( winIndex+thisBlockSize-1, 0,
HLoc(subLocalRowOffset,localColOffset+thisBlockSize-1) );
}
// Handle the last superdiagonal (if it exists)
if( haveLastOff &&
rowOwner == grid.Row() && nextColOwner == grid.Col() )
{
const Int subLocalColOffset = localColOffset +
( grid.Width() == 1 ? thisBlockSize : 0 );
hSuperWin.QueueUpdate
( winIndex+thisBlockSize-1, 0,
HLoc(localRowOffset+thisBlockSize-1,subLocalColOffset) );
}
winIndex += thisBlockSize;
thisCut = 0;
if( colOwner == grid.Col() )
localColOffset += thisBlockSize;
if( rowOwner == grid.Row() )
localRowOffset += thisBlockSize;
rowOwner = nextRowOwner;
colOwner = nextColOwner;
}
hMainWin.ProcessQueues();
hSubWin.ProcessQueues();
hSuperWin.ProcessQueues();
}
} // namespace util
} // namespace hess_schur
} // namespace El
#endif // ifndef EL_HESS_SCHUR_UTIL_GATHER_HPP
| 36.003155 | 77 | 0.520021 | pjt1988 |
4516faa79538976d1b92aa56906527ee1f50373a | 777 | cpp | C++ | Basic Structure/UniformInitialization.cpp | JhonatanGuilherme/LearningCpp | 7b641357a8a934fc5672c03f0381c4d801f13649 | [
"MIT"
] | null | null | null | Basic Structure/UniformInitialization.cpp | JhonatanGuilherme/LearningCpp | 7b641357a8a934fc5672c03f0381c4d801f13649 | [
"MIT"
] | null | null | null | Basic Structure/UniformInitialization.cpp | JhonatanGuilherme/LearningCpp | 7b641357a8a934fc5672c03f0381c4d801f13649 | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
struct Pessoa {
int idade;
string nome;
};
class Veiculo {
public:
int tipo;
string nome;
};
int main() {
int num = 10; // Inicialização antiga;
int num2 {10}; // Inicialização uniforme (C++11);
string nome {"John"};
vector<int> valores {1, 2, 3, 4, 5};
map<string, string> capitais {{"Paraiba", "Joao Pessoa"}};
for (auto &i : valores)
cout << i << endl;
for (auto &i : capitais)
cout << i.first << " - " << i.second << endl;
Pessoa p1 {20, "John"};
cout << p1.idade << endl;
cout << p1.nome << endl;
Veiculo v1 {1, "Carro"}; // Sem necessidade de construtor;
cout << v1.tipo << endl;
cout << v1.nome << endl;
return 0;
}
| 18.069767 | 60 | 0.585586 | JhonatanGuilherme |
931d42551fb51e265e6a60e0d6555d15cbe5056b | 467 | cpp | C++ | minggu-2/Modul_3/tugas-2(3.5).cpp | samuelbudi03/praktikum_algoritma_1 | cf359ec3ad84399f90d3e39207e7d1feb95b4fa9 | [
"MIT"
] | null | null | null | minggu-2/Modul_3/tugas-2(3.5).cpp | samuelbudi03/praktikum_algoritma_1 | cf359ec3ad84399f90d3e39207e7d1feb95b4fa9 | [
"MIT"
] | null | null | null | minggu-2/Modul_3/tugas-2(3.5).cpp | samuelbudi03/praktikum_algoritma_1 | cf359ec3ad84399f90d3e39207e7d1feb95b4fa9 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int x,y,z,m,n;
x = 9 + 4; /* menghitung 9+4 */
y = 9 -4; /* menghitung 9-4 */
z = 9 * 4; /* menghitung 9*4 */
m = 9 / 4; /* menghitung 9/4 */
m2 = 9.0 / 4.0; /* menghitung 9/4 */
n = 9 % 4; /* menghitung 9%4 */
clrscr();
cout << "Nilai dari 9 + 4 = "<< x;
cout << "\nNilai dari 9 -4 = "<< y;
cout << "\nNilai dari 9 * 4= "<< z;
cout << "\nNilai dari 9 / 4= "<< m;
cout << "\nNilai dari 9 mod 4= "<< n;
return 0;
}
| 24.578947 | 37 | 0.513919 | samuelbudi03 |
931eecdd1ec71cbf5845a36e58701fff3e6b2dfd | 4,704 | cpp | C++ | Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 8 | 2021-02-13T17:07:27.000Z | 2021-08-20T08:20:40.000Z | Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | null | null | null | Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 5 | 2021-02-17T18:12:20.000Z | 2021-10-10T17:49:34.000Z | // Problem: https://leetcode.com/problems/3sum/
// Ref: https://www.youtube.com/watch?v=onLoX6Nhvmg
// https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
/****************************************************************************************************/
// METHOD - 1 (Using Hashing)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vvi _3_sum(vi &v) {
vvi res;
int n = (int)v.size();
if(n == 0) return res;
map<int, int> m;
for(int i = 0; i < n; i++) m[v[i]]++;
set<vi> s;
for(int i = 0; i < n; i++) {
m[v[i]]--;
for(int j = i + 1; j < n; j++) {
m[v[j]]--;
int x = v[i] + v[j];
x = -x;
if(m[x] > 0) {
vi tmp(3);
tmp[0] = v[i]; tmp[1] = v[j]; tmp[2] = x;
sort(tmp.begin(), tmp.end());
s.insert(tmp);
}
m[v[j]]++;
}
m[v[i]]++;
}
for(auto vec: s) res.pb(vec);
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vvi res = _3_sum(v);
for(auto vec: res) {
for(auto x: vec) cout << x << " ";
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// TC: O(n^2 x log(m))
// SC: O(n + m), where m are the possible triplets
/*****************************************************************************************************/
// METHOD - 2 (Using 2 Pointers)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vvi _3_sum(vi &v) {
vvi res;
int n = (int)v.size();
if(n == 0) return res;
sort(v.begin(), v.end());
for(int i = 0; i + 2 < n; i++) {
// to avoid duplicacy
if(i and v[i] == v[i-1]) continue;
// from here it is normal 2 sum problem
int lo = i + 1, hi = n - 1, sum = 0 - v[i];
while(lo < hi) {
if(v[lo] + v[hi] == sum) {
vi tmp(3);
tmp[0] = v[i]; tmp[1] = v[lo]; tmp[2] = v[hi];
res.pb(tmp);
// to avoid duplicacy
while(lo < hi and v[lo] == v[lo+1]) lo++;
while(lo < hi and v[hi] == v[hi-1]) hi--;
lo++; hi--;
}
else if(v[lo] + v[hi] < sum) lo++;
else hi--;
}
}
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vvi res = _3_sum(v);
for(auto vec: res) {
for(auto x: vec) cout << x << " ";
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// TC: O(n^2)
// SC: O(m), where m are the possible triplets | 22.188679 | 103 | 0.533376 | Edith-3000 |
9324f514a998255d1a37ccd9a54f9373ad40f265 | 503 | cc | C++ | primer-answer/chapter11/11.11.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | 1 | 2018-02-23T11:12:17.000Z | 2018-02-23T11:12:17.000Z | primer-answer/chapter11/11.11.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | primer-answer/chapter11/11.11.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
using namespace std;
// using compareFuncType = bool(*)(const int, const int);
using compareFuncType = function<bool(const int, const int)>;
// descending;
bool compareFunc(const int x, const int y) {
cout << x << " " << y << endl;
return x > y;
}
int main(int argc, char **argv) {
multiset<int, compareFuncType> ms(compareFunc);
ms.insert(10);
ms.insert(1000);
ms.insert(1);
ms.insert(1);
for (const auto &e : ms) {
cout << e << " ";
}
return 0;
}
| 17.964286 | 61 | 0.634195 | Becavalier |
9327459ab1deac943ba7022292b56483e3032554 | 395 | cpp | C++ | sdktools/debuggers/oca/oca_tools/ocadata/ocadata.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | sdktools/debuggers/oca/oca_tools/ocadata/ocadata.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | sdktools/debuggers/oca/oca_tools/ocadata/ocadata.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // OCAData.cpp : Implementation of DLL Exports.
#include "stdafx.h"
#include "resource.h"
// The module attribute causes DllMain, DllRegisterServer and DllUnregisterServer to be automatically implemented for you
[ module(dll, uuid = "{D264DB42-7095-489E-B84D-404CBB3FF668}",
name = "OCAData",
helpstring = "OCAData 1.0 Type Library",
resource_name = "IDR_OCADATA") ];
| 30.384615 | 122 | 0.708861 | npocmaka |
932a0d7c5d3ce6e1df92a4b6caeaa2412214f2a8 | 3,676 | cpp | C++ | src/Column.cpp | raincheque/qwelk | e78ee0ccf7a7f1af91d823d0563b0af360933237 | [
"MIT"
] | 25 | 2017-11-22T13:48:05.000Z | 2021-12-29T05:49:01.000Z | src/Column.cpp | netboy3/qwelk-vcvrack-plugins | e78ee0ccf7a7f1af91d823d0563b0af360933237 | [
"MIT"
] | 12 | 2017-11-20T20:45:27.000Z | 2021-12-08T20:35:06.000Z | src/Column.cpp | netboy3/qwelk-vcvrack-plugins | e78ee0ccf7a7f1af91d823d0563b0af360933237 | [
"MIT"
] | 4 | 2018-01-11T21:02:12.000Z | 2019-09-29T12:32:50.000Z | #include "qwelk.hpp"
#define CHANNELS 4
struct ModuleColumn : Module {
enum ParamIds {
PARAM_MASTER,
PARAM_AVG,
PARAM_WEIGHTED,
NUM_PARAMS
};
enum InputIds {
IN_SIG,
IN_UPSTREAM = IN_SIG + CHANNELS,
NUM_INPUTS = IN_UPSTREAM + CHANNELS
};
enum OutputIds {
OUT_SIDE,
OUT_DOWNSTREAM = OUT_SIDE + CHANNELS,
NUM_OUTPUTS = OUT_DOWNSTREAM + CHANNELS
};
enum LightIds {
NUM_LIGHTS
};
bool allow_neg_weights = false;
ModuleColumn() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(ModuleColumn::PARAM_AVG, 0.0, 1.0, 1.0, "");
configParam(ModuleColumn::PARAM_WEIGHTED, 0.0, 1.0, 1.0, "");
}
void process(const ProcessArgs& args) override;
};
void ModuleColumn::process(const ProcessArgs& args)
{
bool avg = params[PARAM_AVG].getValue() == 0.0;
bool weighted = params[PARAM_WEIGHTED].getValue() == 0.0;
float total = 0;
float on_count = 0;
for (int i = 0; i < CHANNELS; ++i) {
float in_upstream = inputs[IN_UPSTREAM + i].getVoltage();
float in_sig = inputs[IN_SIG + i].getVoltage();
// just forward the input signal as the side stream,
// used for chaining multiple Columns together
outputs[OUT_SIDE + i].setVoltage(in_sig);
if (inputs[IN_UPSTREAM + i].isConnected()) {
if (weighted)
on_count += allow_neg_weights ? in_upstream : fabs(in_upstream);
else if (in_upstream != 0.0)
on_count += 1;
}
if (!weighted && in_sig != 0.0)
on_count += 1;
float product = weighted ? (in_upstream * in_sig) : (in_upstream + in_sig);
total += product;
outputs[OUT_DOWNSTREAM + i].setVoltage(avg ? ((on_count != 0) ? (total / on_count) : 0) : (total));
}
}
struct MenuItemAllowNegWeights : MenuItem {
ModuleColumn *col;
void onAction(const event::Action &e) override
{
col->allow_neg_weights ^= true;
}
void step () override
{
rightText = (col->allow_neg_weights) ? "✔" : "";
}
};
struct WidgetColumn : ModuleWidget {
WidgetColumn(ModuleColumn *module) {
setModule(module);
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Column.svg")));
addChild(createWidget<ScrewSilver>(Vec(15, 0)));
addChild(createWidget<ScrewSilver>(Vec(15, 365)));
addParam(createParam<CKSS>(Vec(3.5, 30), module, ModuleColumn::PARAM_AVG));
addParam(createParam<CKSS>(Vec(42, 30), module, ModuleColumn::PARAM_WEIGHTED));
float x = 2.5, xstep = 15, ystep = 23.5;
for (int i = 0; i < CHANNELS; ++i)
{
float y = 80 + i * 80;
addInput(createInput<PJ301MPort>(Vec(x + xstep, y - ystep), module, ModuleColumn::IN_UPSTREAM + i));
addOutput(createOutput<PJ301MPort>(Vec(x + xstep*2, y), module, ModuleColumn::OUT_SIDE + i));
addInput(createInput<PJ301MPort>(Vec(x, y), module, ModuleColumn::IN_SIG + i));
addOutput(createOutput<PJ301MPort>(Vec(x + xstep, y + ystep), module, ModuleColumn::OUT_DOWNSTREAM + i));
}
}
void appendContextMenu(Menu *menu) override {
if (module) {
ModuleColumn *column = dynamic_cast<ModuleColumn *>(module);
assert(column);
MenuLabel *spacer = new MenuLabel();
menu->addChild(spacer);
MenuItemAllowNegWeights *item = new MenuItemAllowNegWeights();
item->text = "Allow Negative Weights";
item->col = column;
menu->addChild(item);
}
}
};
Model *modelColumn = createModel<ModuleColumn, WidgetColumn>("Column");
| 29.886179 | 113 | 0.613983 | raincheque |
932e4ac2c56cf29fda71c25188d7f8d7af643ffe | 4,501 | hpp | C++ | samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp | btempleton/sg-aics3mac-plugins | e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67 | [
"Intel",
"Unlicense"
] | 1 | 2021-10-09T18:23:44.000Z | 2021-10-09T18:23:44.000Z | samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp | btempleton/sg-aics3mac-plugins | e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67 | [
"Intel",
"Unlicense"
] | null | null | null | samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp | btempleton/sg-aics3mac-plugins | e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67 | [
"Intel",
"Unlicense"
] | null | null | null | //========================================================================================
//
// $File: //ai/ai13/devtech/sdk/public/samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp $
//
// $Revision: #3 $
//
// Copyright 1987-2007 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
#ifndef __MarkedObjectsPreferences_hpp__
#define __MarkedObjectsPreferences_hpp__
#include "MarkedObjectsPlugin.hpp"
class MarkedObjectsDialog;
class MarkedObjectsPreferencesDialog : public BaseADMDialog
{
private:
ASRealPoint subLoc;
string subFontName;
AIReal subFontSize;
ASRealPoint labelLoc;
string labelFontName;
AIReal labelFontSize;
string labelDefaultText;
long precision;
AIBoolean autoSort;
public:
MarkedObjectsPreferencesDialog();
virtual ~MarkedObjectsPreferencesDialog();
int Modal(SPPluginRef pluginRef, char* name, int dialogID, ADMDialogStyle style = kADMModalDialogStyle, int options = 0);
ASErr Init();
void Notify( IADMNotifier notifier );
void Destroy();
ASRealPoint GetSubStringLocation( void ) { return subLoc; }
const string GetSubStringFontName( void ) { return subFontName; }
AIReal GetSubStringFontSize( void ) { return subFontSize; }
ASRealPoint GetLabelStringLocation( void ) { return labelLoc; }
const string GetLabelStringFontName( void ) { return labelFontName; }
AIReal GetLabelStringFontSize( void ) { return labelFontSize; }
const string GetLabelStringDefaultText( void ) { return labelDefaultText; }
void SetSubStringLocation( ASRealPoint inPoint ) { subLoc = inPoint; }
void SetSubStringFontName( const string fontName ) { subFontName = fontName; }
void SetSubStringFontSize( AIReal fontSize ) { subFontSize = fontSize; }
void SetLabelStringLocation( ASRealPoint inPoint ) { labelLoc = inPoint; }
void SetLabelStringFontName( const string fontName ) { labelFontName = fontName; }
void SetLabelStringFontSize( AIReal fontSize ) { labelFontSize = fontSize; }
void SetLabelStringDefaultText( const string newText ) { labelDefaultText = newText; }
void SetPrecision( long p ) { precision = p; }
long GetPrecision( void ) { return precision; }
void SetAutoSort( AIBoolean as ) { autoSort = as; }
AIBoolean GetAutoSort( void ) { return autoSort; }
};
class MarkedObjectsPreferences
{
private:
MarkedObjectsDialog* moDialog;
ASRealPoint subLoc;
string subFontName;
AIReal subFontSize;
ASRealPoint labelLoc;
string labelFontName;
AIReal labelFontSize;
string labelDefaultText;
long precision;
AIBoolean autoSort;
public:
MarkedObjectsPreferences();
~MarkedObjectsPreferences();
void SetDialogPreferences( MarkedObjectsDialog* dp );
int DoModalPrefs( void );
ASRealPoint GetSubStringLocation( void ) { return subLoc; }
const string GetSubStringFontName( void ) { return subFontName; }
AIReal GetSubStringFontSize( void ) { return subFontSize; }
ASRealPoint GetLabelStringLocation( void ) { return labelLoc; }
const string GetLabelStringFontName( void ) { return labelFontName; }
AIReal GetLabelStringFontSize( void ) { return labelFontSize; }
const string GetLabelStringDefaultText( void ) { return labelDefaultText; }
void SetSubStringLocation( ASRealPoint inPoint ) { subLoc = inPoint; }
void SetSubStringFontName( const string fontName ) { subFontName = fontName; }
void SetSubStringFontSize( AIReal fontSize ) { subFontSize = fontSize; }
void SetLabelStringLocation( ASRealPoint inPoint ) { labelLoc = inPoint; }
void SetLabelStringFontName( const string fontName ) { labelFontName = fontName; }
void SetLabelStringFontSize( AIReal fontSize ) { labelFontSize = fontSize; }
void SetLabelStringDefaultText( const string newText ) { labelDefaultText = newText; }
void SetPrecision( long p ) { precision = p; }
long GetPrecision( void ) { return precision; }
void SetAutoSort( AIBoolean as ) { autoSort = as; }
AIBoolean GetAutoSort( void ) { return autoSort; }
};
extern MarkedObjectsPreferences* gPreferences;
#endif
// end MarkedObjectsPreferences.hpp | 36.008 | 122 | 0.723617 | btempleton |
932f1cbf474b4015b56963583ef5ad5986f56a70 | 17,324 | cc | C++ | content/browser/web_package/signed_exchange_certificate_chain_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/web_package/signed_exchange_certificate_chain_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/web_package/signed_exchange_certificate_chain_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 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 "content/browser/web_package/signed_exchange_certificate_chain.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/optional.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "components/cbor/cbor_values.h"
#include "components/cbor/cbor_writer.h"
#include "content/public/common/content_paths.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
base::Optional<std::vector<base::StringPiece>> GetCertChain(
const uint8_t* input,
size_t input_size) {
return SignedExchangeCertificateChain::GetCertChainFromMessage(
base::make_span(input, input_size));
}
cbor::CBORValue CBORByteString(base::StringPiece str) {
return cbor::CBORValue(str, cbor::CBORValue::Type::BYTE_STRING);
}
} // namespace
TEST(SignedExchangeCertificateParseB0Test, OneCert) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x07, // certificate list size
0x00, 0x00, 0x02, // cert data size
0x11, 0x22, // cert data
0x00, 0x00, // extensions size
// clang-format on
};
base::Optional<std::vector<base::StringPiece>> certs =
GetCertChain(input, arraysize(input));
ASSERT_TRUE(certs);
ASSERT_EQ(1u, certs->size());
const uint8_t kExpected[] = {
// clang-format off
0x11, 0x22, // cert data
// clang-format on
};
EXPECT_THAT((*certs)[0],
testing::ElementsAreArray(kExpected, arraysize(kExpected)));
}
TEST(SignedExchangeCertificateParseB0Test, OneCertWithExtension) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x0A, // certificate list size
0x00, 0x00, 0x02, // cert data size
0x11, 0x22, // cert data
0x00, 0x03, // extensions size
0xE1, 0xE2, 0xE3, // extensions data
// clang-format on
};
base::Optional<std::vector<base::StringPiece>> certs =
GetCertChain(input, arraysize(input));
ASSERT_TRUE(certs);
ASSERT_EQ(1u, certs->size());
const uint8_t kExpected[] = {
// clang-format off
0x11, 0x22, // cert data
// clang-format on
};
EXPECT_THAT((*certs)[0],
testing::ElementsAreArray(kExpected, arraysize(kExpected)));
}
TEST(SignedExchangeCertificateParseB0Test, TwoCerts) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x01, 0x13, // certificate list size
0x00, 0x01, 0x04, // cert data size
// cert data
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x00, // extensions size
0x00, 0x00, 0x05, // cert data size
0x33, 0x44, 0x55, 0x66, 0x77, // cert data
0x00, 0x00, // extensions size
// clang-format on
};
const uint8_t kExpected1[] = {
// clang-format off
// cert data
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
// clang-format on
};
const uint8_t kExpected2[] = {
// clang-format off
0x33, 0x44, 0x55, 0x66, 0x77, // cert data
// clang-format on
};
base::Optional<std::vector<base::StringPiece>> certs =
GetCertChain(input, sizeof(input));
ASSERT_TRUE(certs);
ASSERT_EQ(2u, certs->size());
EXPECT_THAT((*certs)[0],
testing::ElementsAreArray(kExpected1, arraysize(kExpected1)));
EXPECT_THAT((*certs)[1],
testing::ElementsAreArray(kExpected2, arraysize(kExpected2)));
}
TEST(SignedExchangeCertificateParseB0Test, Empty) {
EXPECT_FALSE(GetCertChain(nullptr, 0));
}
TEST(SignedExchangeCertificateParseB0Test, InvalidRequestContextSize) {
const uint8_t input[] = {
// clang-format off
0x01, // request context size: must be zero
0x20, // request context
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CanNotReadCertListSize1) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x01, // certificate list size: must be 3 bytes
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CanNotReadCertListSize2) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x01, // certificate list size: must be 3 bytes
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CertListSizeError) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x01, 0x01, // certificate list size: 257 (This must be 7)
0x00, 0x00, 0x02, // cert data size
0x11, 0x22, // cert data
0x00, 0x00, // extensions size
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CanNotReadCertDataSize) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x02, // certificate list size
0x00, 0x01, // cert data size: must be 3 bytes
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CertDataSizeError) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x04, // certificate list size
0x00, 0x00, 0x02, // cert data size
0x11, // cert data: Need 2 bytes
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, CanNotReadExtensionsSize) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x06, // certificate list size
0x00, 0x00, 0x02, // cert data size
0x11, 0x22, // cert data
0x00, // extensions size : must be 2 bytes
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB0Test, ExtensionsSizeError) {
const uint8_t input[] = {
// clang-format off
0x00, // request context size
0x00, 0x00, 0x07, // certificate list size
0x00, 0x00, 0x02, // cert data size
0x11, 0x22, // cert data
0x00, 0x01, // extensions size
// clang-format on
};
EXPECT_FALSE(GetCertChain(input, arraysize(input)));
}
TEST(SignedExchangeCertificateParseB1Test, Empty) {
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::span<const uint8_t>(), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseB1Test, EmptyChain) {
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseB1Test, MissingCert) {
cbor::CBORValue::MapValue cbor_map;
cbor_map[cbor::CBORValue("sct")] = CBORByteString("SCT");
cbor_map[cbor::CBORValue("ocsp")] = CBORByteString("OCSP");
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map)));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseB1Test, OneCert) {
net::CertificateList certs;
ASSERT_TRUE(
net::LoadCertificateFiles({"subjectAltName_sanity_check.pem"}, &certs));
ASSERT_EQ(1U, certs.size());
base::StringPiece cert_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
cbor::CBORValue::MapValue cbor_map;
cbor_map[cbor::CBORValue("sct")] = CBORByteString("SCT");
cbor_map[cbor::CBORValue("cert")] = CBORByteString(cert_der);
cbor_map[cbor::CBORValue("ocsp")] = CBORByteString("OCSP");
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map)));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
ASSERT_TRUE(parsed);
EXPECT_EQ(cert_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->cert_buffer()));
ASSERT_EQ(0U, parsed->cert()->intermediate_buffers().size());
EXPECT_EQ(parsed->ocsp(), base::make_optional<std::string>("OCSP"));
EXPECT_EQ(parsed->sct(), base::make_optional<std::string>("SCT"));
}
TEST(SignedExchangeCertificateParseB1Test, MissingOCSPInFirstCert) {
net::CertificateList certs;
ASSERT_TRUE(
net::LoadCertificateFiles({"subjectAltName_sanity_check.pem"}, &certs));
ASSERT_EQ(1U, certs.size());
base::StringPiece cert_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
cbor::CBORValue::MapValue cbor_map;
cbor_map[cbor::CBORValue("sct")] = CBORByteString("SCT");
cbor_map[cbor::CBORValue("cert")] = CBORByteString(cert_der);
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map)));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseB1Test, TwoCerts) {
net::CertificateList certs;
ASSERT_TRUE(net::LoadCertificateFiles(
{"subjectAltName_sanity_check.pem", "root_ca_cert.pem"}, &certs));
ASSERT_EQ(2U, certs.size());
base::StringPiece cert1_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
base::StringPiece cert2_der =
net::x509_util::CryptoBufferAsStringPiece(certs[1]->cert_buffer());
cbor::CBORValue::MapValue cbor_map1;
cbor_map1[cbor::CBORValue("sct")] = CBORByteString("SCT");
cbor_map1[cbor::CBORValue("cert")] = CBORByteString(cert1_der);
cbor_map1[cbor::CBORValue("ocsp")] = CBORByteString("OCSP");
cbor::CBORValue::MapValue cbor_map2;
cbor_map2[cbor::CBORValue("cert")] = CBORByteString(cert2_der);
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map1)));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map2)));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
ASSERT_TRUE(parsed);
EXPECT_EQ(cert1_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->cert_buffer()));
ASSERT_EQ(1U, parsed->cert()->intermediate_buffers().size());
EXPECT_EQ(cert2_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->intermediate_buffers()[0].get()));
EXPECT_EQ(parsed->ocsp(), base::make_optional<std::string>("OCSP"));
EXPECT_EQ(parsed->sct(), base::make_optional<std::string>("SCT"));
}
TEST(SignedExchangeCertificateParseB1Test, HavingOCSPInSecnodCert) {
net::CertificateList certs;
ASSERT_TRUE(net::LoadCertificateFiles(
{"subjectAltName_sanity_check.pem", "root_ca_cert.pem"}, &certs));
ASSERT_EQ(2U, certs.size());
base::StringPiece cert1_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
base::StringPiece cert2_der =
net::x509_util::CryptoBufferAsStringPiece(certs[1]->cert_buffer());
cbor::CBORValue::MapValue cbor_map1;
cbor_map1[cbor::CBORValue("sct")] = CBORByteString("SCT");
cbor_map1[cbor::CBORValue("cert")] = CBORByteString(cert1_der);
cbor_map1[cbor::CBORValue("ocsp")] = CBORByteString("OCSP1");
cbor::CBORValue::MapValue cbor_map2;
cbor_map2[cbor::CBORValue("cert")] = CBORByteString(cert2_der);
cbor_map2[cbor::CBORValue("ocsp")] = CBORByteString("OCSP2");
cbor::CBORValue::ArrayValue cbor_array;
cbor_array.push_back(cbor::CBORValue(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map1)));
cbor_array.push_back(cbor::CBORValue(std::move(cbor_map2)));
auto serialized =
cbor::CBORWriter::Write(cbor::CBORValue(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseB1Test, ParseGoldenFile) {
base::FilePath path;
base::PathService::Get(content::DIR_TEST_DATA, &path);
path = path.AppendASCII("htxg").AppendASCII(
"wildcard_example.org.public.pem.cbor");
std::string contents;
ASSERT_TRUE(base::ReadFileToString(path, &contents));
auto parsed = SignedExchangeCertificateChain::Parse(
SignedExchangeVersion::kB1, base::as_bytes(base::make_span(contents)),
nullptr);
ASSERT_TRUE(parsed);
}
} // namespace content
| 37.742919 | 78 | 0.68206 | zipated |
932f2c75359c94129abe01a1e6953136184ff83b | 2,907 | cpp | C++ | trie/src/node.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | trie/src/node.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | trie/src/node.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | #include "wordsearch_solver/trie/node.hpp"
#include <algorithm>
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <bitset>
#include <cassert>
#include <cstddef>
#include <limits>
#include <memory>
#include <ostream>
#include <string_view>
namespace trie {
const Node* search(const Node& node, std::string_view word) {
const Node* p = &node;
for (; !word.empty(); word.remove_prefix(1)) {
p = p->test(word.front());
if (!p) {
return nullptr;
}
}
return p;
}
Node::Node(const bool is_end_of_word) : is_end_of_word_(is_end_of_word) {}
std::ostream& operator<<(std::ostream& os, const Node& node) {
fmt::memory_buffer buff;
fmt::format_to(buff, "{{");
for (const auto& edge : node.edges_) {
fmt::format_to(buff, "{}", edge.c);
}
fmt::format_to(buff, "{}", node.is_end_of_word() ? "|" : " ");
fmt::format_to(buff, "}}");
return os << fmt::to_string(buff);
}
Node* Node::add_char(const char c) {
// assert(c >= 97 && c < 123);
// Note comparator lambda here compares an edge and a char, not two edges
// Insertion is sorted
auto it = std::lower_bound(
edges_.begin(), edges_.end(), c,
[](const auto& edge0, const char c) { return edge0.c < c; });
if (it == edges_.end() || it->c > c) {
it = edges_.emplace(it, Edge{std::make_unique<Node>(), c});
}
assert(it->child.get() != nullptr);
return it->child.get();
}
void Node::set_is_end_of_word(const bool is_end_of_word) {
is_end_of_word_ = is_end_of_word;
}
/** Test if a node has an edge containing the character @p c
*
* @note We use linear search here. Could use binary search. For the English
* alphabet, nodes tend to be fairly sparse and small, especially once beyond
* the first few letters. On the massive_wordsearch benchmark,
* using binary search is noticably (~8%) slower.
*/
const Node* Node::test(const char c) const {
const auto it = std::find_if(edges_.begin(), edges_.end(),
[c](const auto& edge) { return edge.c == c; });
// const auto it = std::lower_bound(
// edges_.begin(), edges_.end(), c,
// [](const auto& edge, const char c) { return edge.c < c; });
// if (it == edges_.end() || it->c != c) {
if (it == edges_.end()) {
return nullptr;
}
return it->child.get();
}
bool Node::any() const { return !edges_.empty(); }
bool Node::is_end_of_word() const { return is_end_of_word_; }
const Node::Edges& Node::edges() const { return edges_; }
// Node::PrecedingType Node::preceding() const
// {
// return preceding_;
// }
} // namespace trie
// void print_sizes()
// {
// fmt::print("bits_: {}\n", sizeof(bits_));
// fmt::print("preceding_: {}\n", sizeof(preceding_));
// fmt::print("is_end_of_word_: {}\n", sizeof(is_end_of_word_));
// fmt::print("sizeof(Node): {}\n", sizeof(Node));
// // static_assert(sizeof(Node) <= 8);
// static_assert(alignof(Node) == 8);
// }
| 28.223301 | 78 | 0.631579 | Arghnews |
932f521504f0babcf1b37c09669703f82bee9981 | 8,154 | hpp | C++ | include/RootMotion/FinalIK/IKExecutionOrder.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/IKExecutionOrder.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/IKExecutionOrder.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
// Forward declaring type: IK
class IK;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0x29
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.IKExecutionOrder
// [TokenAttribute] Offset: FFFFFFFF
class IKExecutionOrder : public UnityEngine::MonoBehaviour {
public:
// [TooltipAttribute] Offset: 0xEA0294
// public RootMotion.FinalIK.IK[] IKComponents
// Size: 0x8
// Offset: 0x18
::Array<RootMotion::FinalIK::IK*>* IKComponents;
// Field size check
static_assert(sizeof(::Array<RootMotion::FinalIK::IK*>*) == 0x8);
// [TooltipAttribute] Offset: 0xEA02CC
// public UnityEngine.Animator animator
// Size: 0x8
// Offset: 0x20
UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(UnityEngine::Animator*) == 0x8);
// private System.Boolean fixedFrame
// Size: 0x1
// Offset: 0x28
bool fixedFrame;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: IKExecutionOrder
IKExecutionOrder(::Array<RootMotion::FinalIK::IK*>* IKComponents_ = {}, UnityEngine::Animator* animator_ = {}, bool fixedFrame_ = {}) noexcept : IKComponents{IKComponents_}, animator{animator_}, fixedFrame{fixedFrame_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field: public RootMotion.FinalIK.IK[] IKComponents
::Array<RootMotion::FinalIK::IK*>* _get_IKComponents();
// Set instance field: public RootMotion.FinalIK.IK[] IKComponents
void _set_IKComponents(::Array<RootMotion::FinalIK::IK*>* value);
// Get instance field: public UnityEngine.Animator animator
UnityEngine::Animator* _get_animator();
// Set instance field: public UnityEngine.Animator animator
void _set_animator(UnityEngine::Animator* value);
// Get instance field: private System.Boolean fixedFrame
bool _get_fixedFrame();
// Set instance field: private System.Boolean fixedFrame
void _set_fixedFrame(bool value);
// private System.Boolean get_animatePhysics()
// Offset: 0x18374F8
bool get_animatePhysics();
// private System.Void Start()
// Offset: 0x1837594
void Start();
// private System.Void Update()
// Offset: 0x1837604
void Update();
// private System.Void FixedUpdate()
// Offset: 0x18376C0
void FixedUpdate();
// private System.Void LateUpdate()
// Offset: 0x18376FC
void LateUpdate();
// private System.Void FixTransforms()
// Offset: 0x1837638
void FixTransforms();
// public System.Void .ctor()
// Offset: 0x1837788
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IKExecutionOrder* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::IKExecutionOrder::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IKExecutionOrder*, creationType>()));
}
}; // RootMotion.FinalIK.IKExecutionOrder
#pragma pack(pop)
static check_size<sizeof(IKExecutionOrder), 40 + sizeof(bool)> __RootMotion_FinalIK_IKExecutionOrderSizeCheck;
static_assert(sizeof(IKExecutionOrder) == 0x29);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKExecutionOrder*, "RootMotion.FinalIK", "IKExecutionOrder");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::get_animatePhysics
// Il2CppName: get_animatePhysics
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::get_animatePhysics)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "get_animatePhysics", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::FixedUpdate
// Il2CppName: FixedUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::FixedUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "FixedUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::LateUpdate
// Il2CppName: LateUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::LateUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "LateUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::FixTransforms
// Il2CppName: FixTransforms
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::FixTransforms)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "FixTransforms", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 50.645963 | 226 | 0.719034 | marksteward |
93304097224c1c3b55474e6a5746b7978d452391 | 4,853 | cpp | C++ | Core/logging/src/Logger.cpp | ChewyGumball/bengine | a993471b1b135bcfe848de25ec539d93ed97445f | [
"MIT"
] | null | null | null | Core/logging/src/Logger.cpp | ChewyGumball/bengine | a993471b1b135bcfe848de25ec539d93ed97445f | [
"MIT"
] | null | null | null | Core/logging/src/Logger.cpp | ChewyGumball/bengine | a993471b1b135bcfe848de25ec539d93ed97445f | [
"MIT"
] | null | null | null | #include "Core/Logging/Logger.h"
#define SPDLOG_FMT_EXTERNAL
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <thread>
// We don't use the Core contaienrs here so that we don't have any external dependencies, allowing this library to be
// used by any other library.
#include <unordered_map>
#include <unordered_set>
namespace {
std::mutex* LoggerCreationMutex;
std::mutex* FilterMutex;
std::mutex* SinkMutex;
std::mutex* DisplayNameMutex;
void InitLocks() {
if(LoggerCreationMutex == nullptr) {
LoggerCreationMutex = new std::mutex();
FilterMutex = new std::mutex();
SinkMutex = new std::mutex();
DisplayNameMutex = new std::mutex();
}
}
std::unordered_map<std::string, Core::LogLevel>& Filters() {
static std::unordered_map<std::string, Core::LogLevel> FilterMap;
return FilterMap;
}
std::unordered_set<spdlog::sink_ptr>& Sinks() {
static std::unordered_set<spdlog::sink_ptr> SinkMap{std::make_shared<spdlog::sinks::stdout_color_sink_mt>()};
return SinkMap;
}
std::unordered_map<const Core::LogCategory*, std::string>& DisplayNames() {
static std::unordered_map<const Core::LogCategory*, std::string> DisplayNameMap;
return DisplayNameMap;
}
std::string& GetDisplayName(const Core::LogCategory* category) {
InitLocks();
std::scoped_lock lock(*DisplayNameMutex);
std::string& displayName = DisplayNames()[category];
if(displayName.empty()) {
const Core::LogCategory* currentCategory = category;
while(currentCategory != nullptr) {
displayName = std::string(currentCategory->name) + displayName;
currentCategory = currentCategory->parent;
}
}
return displayName;
}
Core::LogLevel GlobalLogLevel = Core::LogLevel::Trace;
} // namespace
namespace Core::LogManager {
void SetGlobalMinimumLevel(LogLevel minimumLevel) {
if(minimumLevel == GlobalLogLevel) {
return;
}
GlobalLogLevel = minimumLevel;
spdlog::drop_all();
}
void SetCategoryLevel(const LogCategory& category, LogLevel minimumLevel) {
SetCategoryLevel(GetDisplayName(&category), minimumLevel);
}
void SetCategoryLevel(const std::string& loggerName, LogLevel minimumLevel) {
InitLocks();
{
std::scoped_lock lock(*FilterMutex);
Filters()[loggerName] = minimumLevel;
}
// We drop all loggers so they get recreated with the filter levels
// since we don't know all the children of the logger that just changed
spdlog::drop_all();
}
void AddSinks(const std::vector<spdlog::sink_ptr>& sinks) {
InitLocks();
{
std::scoped_lock lock(*SinkMutex);
for(auto& sink : sinks) {
Sinks().emplace(sink);
}
}
// We drop all loggers so they get recreated with the new sinks
spdlog::drop_all();
}
std::shared_ptr<spdlog::logger> GetLogger(const LogCategory& category) {
std::string& displayName = GetDisplayName(&category);
std::shared_ptr<spdlog::logger> logger = spdlog::get(displayName);
if(logger == nullptr) {
InitLocks();
std::scoped_lock creationLock(*LoggerCreationMutex);
// Check again, just in case there was a race to create the logger
logger = spdlog::get(displayName);
if(logger != nullptr) {
return logger;
}
{
std::scoped_lock lock(*SinkMutex);
logger = std::make_shared<spdlog::logger>(displayName, Sinks().begin(), Sinks().end());
spdlog::register_logger(logger);
}
{
std::scoped_lock lock(*FilterMutex);
LogLevel level = GlobalLogLevel;
const LogCategory* currentCategory = &category;
while(currentCategory != nullptr) {
auto filter = Filters().find(GetDisplayName(currentCategory));
if(filter != Filters().end() && filter->second > level) {
level = filter->second;
}
currentCategory = currentCategory->parent;
}
logger->set_level(MapLevel(level));
}
}
return logger;
}
spdlog::level::level_enum MapLevel(LogLevel level) {
switch(level) {
case LogLevel::Always: return spdlog::level::level_enum::off;
case LogLevel::Critical: return spdlog::level::level_enum::critical;
case LogLevel::Error: return spdlog::level::level_enum::err;
case LogLevel::Warning: return spdlog::level::level_enum::warn;
case LogLevel::Info: return spdlog::level::level_enum::info;
case LogLevel::Debug: return spdlog::level::level_enum::debug;
case LogLevel::Trace: return spdlog::level::level_enum::trace;
default: return spdlog::level::level_enum::off;
}
}
} // namespace Core::LogManager | 30.522013 | 117 | 0.650319 | ChewyGumball |
9330ecd5ab8c292836145ebf50f8b8ea1be465e9 | 2,406 | hpp | C++ | libs/GFX/ResourceManager.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | 1 | 2019-08-14T12:31:50.000Z | 2019-08-14T12:31:50.000Z | libs/GFX/ResourceManager.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | libs/GFX/ResourceManager.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | #include <utility>
//
// Created by nhyarlathotep on 14/11/18.
//
#pragma once
#include <memory>
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include <experimental/filesystem>
#include <SFML/Audio/Music.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Texture.hpp>
#include "../LOG/Logger.hpp"
#include "Singleton.hpp"
namespace fs = std::experimental::filesystem;
template<typename Resource>
class ResourceHolder{
public:
explicit ResourceHolder() noexcept = default;
template<typename ...Args>
std::shared_ptr<Resource> openFromFile(const std::string &id, Args &&...args) {
auto res = new Resource();
if (!res->openFromFile(std::forward<Args>(args)...)) {
throw std::runtime_error("Impossible to loadFromFile file");
}
_resources.emplace(id, std::shared_ptr<Resource>(res));
return get(id);
}
template<typename ...Args>
std::shared_ptr<Resource> loadFromFile(const std::string &id, Args &&...args) {
auto res = new Resource();
if (!res->loadFromFile(std::forward<Args>(args)...)) {
throw std::runtime_error("Impossible to loadFromFile file");
}
_resources.emplace(id, std::shared_ptr<Resource>(res));
return get(id);
}
std::shared_ptr<Resource> get(const std::string &id) {
return _resources.at(id);
}
private:
std::unordered_map<std::string, std::shared_ptr<Resource>> _resources;
};
class ResourceManager : public gfx::Singleton<ResourceManager> {
friend class gfx::Singleton<ResourceManager>;
public:
std::shared_ptr<sf::Font> loadFont(fs::path &&filename);
std::shared_ptr<sf::Music> loadMusic(fs::path &&filename);
std::shared_ptr<sf::Texture> loadTexture(fs::path &&filename);
std::shared_ptr<sf::Font> getFont(const std::string &id);
std::shared_ptr<sf::Music> getMusic(const std::string &id);
std::shared_ptr<sf::Texture> getTexture(const std::string &id);
private:
/**
* @brief Set the root assets path
*/
explicit ResourceManager(fs::path &&resourceDirectoryPath = (fs::current_path() / "assets")) noexcept;
ResourceManager(const ResourceManager &rMgr){}
fs::path _resourceDirectoryPath;
ResourceHolder<sf::Font> _fontRegistry;
ResourceHolder<sf::Music> _musicRegistry;
ResourceHolder<sf::Texture> _textureRegistry;
};
| 29.341463 | 106 | 0.674564 | KillianG |
933122662c79f3b7e7e0b405a5d2253f8845e3d0 | 1,053 | hpp | C++ | organism.hpp | piero0/myNEAT | b2c5a4e98274d20fd18765a624ad5f8347ffaaa1 | [
"MIT"
] | null | null | null | organism.hpp | piero0/myNEAT | b2c5a4e98274d20fd18765a624ad5f8347ffaaa1 | [
"MIT"
] | 1 | 2018-02-14T20:48:18.000Z | 2018-03-18T15:04:03.000Z | organism.hpp | piero0/myNEAT | b2c5a4e98274d20fd18765a624ad5f8347ffaaa1 | [
"MIT"
] | null | null | null | #pragma once
#include "genome.hpp"
namespace pneat {
class Organism {
Genome g;
float fitness;
float thresh;
float normFitness;
public:
Organism(const Genome& g);
Genome& getGenome() { return g; }
void setFitness(float fitness) { this->fitness = fitness; }
float getFitness() const { return fitness; }
float getThresh() const { return thresh; }
float setThresh(float lastThresh, float totalFitness) {
normFitness = fitness/totalFitness;
thresh = lastThresh + normFitness;
return normFitness;
}
void dump();
void dumpGraph(std::string name);
static float adder(const float& sum, const Organism& org) {
return sum + org.fitness;
}
static bool compareThresh(const Organism& o, const float& th) {
return o.thresh <= th;
}
};
}
| 28.459459 | 76 | 0.509972 | piero0 |
93312b905894c3538918f697647bbd1046298c92 | 311 | cpp | C++ | TestApp/src/TestApp/TestApp.cpp | Critteros/DataReforged | 891dbbd2ae0648d25d10ab95cb017e1e5991f28f | [
"Apache-2.0"
] | null | null | null | TestApp/src/TestApp/TestApp.cpp | Critteros/DataReforged | 891dbbd2ae0648d25d10ab95cb017e1e5991f28f | [
"Apache-2.0"
] | null | null | null | TestApp/src/TestApp/TestApp.cpp | Critteros/DataReforged | 891dbbd2ae0648d25d10ab95cb017e1e5991f28f | [
"Apache-2.0"
] | null | null | null | #include <DataReforged.h>
#include <iostream>
#define print(x) std::cout << x << std::endl
using namespace DataReforged;
int main()
{
Test();
ArrayList<int> a(1);
for (int i = 1; i < 11; i++)
{
a.push(i);
}
for (int i = 0; i < 10; i++)
{
print(a.get(i));
}
print(a.getLast());
return 0;
} | 11.107143 | 44 | 0.55627 | Critteros |
933161e885e42bba10c87e925d9a00badb801cc5 | 357 | cpp | C++ | src/executor/executor_ProcessResource.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 5 | 2019-02-24T06:42:52.000Z | 2021-04-09T19:16:24.000Z | src/executor/executor_ProcessResource.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 40 | 2019-02-24T15:25:54.000Z | 2021-05-17T04:22:43.000Z | src/executor/executor_ProcessResource.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 2 | 2019-02-23T22:58:36.000Z | 2019-02-27T01:27:42.000Z |
#include "executor/executor_ProcessResource.h"
namespace mutgos
{
namespace executor
{
// ----------------------------------------------------------------------
ProcessResource::ProcessResource(void)
{
}
// ----------------------------------------------------------------------
ProcessResource::~ProcessResource()
{
}
}
}
| 18.789474 | 77 | 0.380952 | hyena |
9333962cfc5a2abed5e0c24f03a19472267d6447 | 5,210 | cpp | C++ | src/ServerMsg.cpp | FenomenCoyote/ProyectoRedes | 4db4434c964d6afe089e8f752eb59e2cfcf66267 | [
"MIT"
] | null | null | null | src/ServerMsg.cpp | FenomenCoyote/ProyectoRedes | 4db4434c964d6afe089e8f752eb59e2cfcf66267 | [
"MIT"
] | null | null | null | src/ServerMsg.cpp | FenomenCoyote/ProyectoRedes | 4db4434c964d6afe089e8f752eb59e2cfcf66267 | [
"MIT"
] | null | null | null | #include "ServerMsg.h"
namespace ServerMsg
{
void ServerMsg::to_bin()
{
size_t totalSize = sizeof(size_t); //totalSize
uint8_t numOfAsteroids = (asPool == nullptr) ? 0 : asPool->getNumOfAsteroid();
uint8_t numOfBullets = (buPool == nullptr) ? 0 :buPool->getNumOfBullets();
totalSize += sizeof(ServerMsgId); //type
totalSize += sizeof(uint8_t) + numOfAsteroids * objectInfoSize; //Asteroids (changes)
totalSize += sizeof(uint8_t) + numOfBullets * objectInfoSize; //Bullets (changes)
totalSize += 2 * objectInfoSize; //Ship1 + Ship2
totalSize += sizeof(SoundId); //Sound
totalSize += sizeof(bool); //won
alloc_data(totalSize);
memset(_data, 0, totalSize);
char* pointer = _data;
//Write totalSize (needed to reconstruct this msg because the lenght depends on the state of the world)
memcpy(pointer, &totalSize, sizeof(size_t));
pointer += sizeof(size_t);
memcpy(pointer, &type, sizeof(size_t));
pointer += sizeof(ServerMsgId);
//Asteroids
memcpy(pointer, &numOfAsteroids, sizeof(uint8_t));
pointer += sizeof(uint8_t);
if(numOfAsteroids > 0){
for (Asteroid* a : asPool->getPool()) {
if(a->getInUse()){
to_bin_object(pointer, a->getPos(), a->getWidth(), a->getHeight(), a->getRot());
pointer += objectInfoSize;
}
}
}
//Bullets
memcpy(pointer, &numOfBullets, sizeof(uint8_t));
pointer += sizeof(uint8_t);
if(numOfBullets > 0){
for (Bullet* b : buPool->getPool()) {
if(b->getInUse()){
to_bin_object(pointer, b->getPos(), b->getWidth(), b->getHeight(), b->getRot());
pointer += objectInfoSize;
}
}
}
//Ship
if(shipTr1 == nullptr)
to_bin_object(pointer, Vector2D(), -1, -1, 0);
else
to_bin_object(pointer, shipTr1->getPos(), shipTr1->getW(), shipTr1->getH(), shipTr1->getRot());
pointer += objectInfoSize;
//Ship2
if(shipTr2 == nullptr)
to_bin_object(pointer, Vector2D(), -1, -1, 0);
else
to_bin_object(pointer, shipTr2->getPos(), shipTr2->getW(), shipTr2->getH(), shipTr2->getRot());
pointer += objectInfoSize;
//Sound
memcpy(pointer, &sound, sizeof(SoundId));
pointer += sizeof(SoundId);
//Won
memcpy(pointer, &won, sizeof(bool));
}
void ServerMsg::to_bin_object(char* pointer, Vector2D pos, int width, int height, double rot)
{
//Pos
double pos_ = pos.getX();
memcpy(pointer, &pos_, sizeof(double));
pointer += sizeof(double);
pos_ = pos.getY();
memcpy(pointer, &pos_, sizeof(double));
pointer += sizeof(double);
//Size
memcpy(pointer, &width, sizeof(int));
pointer += sizeof(int);
memcpy(pointer, &height, sizeof(int));
pointer += sizeof(int);
//Rot
memcpy(pointer, &rot, sizeof(double));
}
ServerMsg::ObjectInfo ServerMsg::from_bin_object(char* pointer)
{
ObjectInfo obj;
//Pos
memcpy(&obj.posX, pointer, sizeof(double));
pointer += sizeof(double);
memcpy(&obj.posY, pointer, sizeof(double));
pointer += sizeof(double);
//Size
memcpy(&obj.width, pointer,sizeof(int));
pointer += sizeof(int);
memcpy(&obj.height, pointer, sizeof(int));
pointer += sizeof(int);
//Rot
memcpy(&obj.rot, pointer,sizeof(double));
return obj;
}
int ServerMsg::from_bin(char * bobj)
{
size_t totalSize;
//First i read the totalSize of the msg
memcpy(&totalSize, bobj, sizeof(size_t));
//Alloc totalSize - sizeof(totalSize) because i dont need to store totalSize variable
alloc_data(totalSize - sizeof(size_t));
char* pointer = bobj + sizeof(size_t);
//Type
memcpy(&type, pointer, sizeof(size_t));
pointer += sizeof(ServerMsgId);
uint8_t numOfAsteroids;
uint8_t numOfBullets;
//Asteroids
memcpy(&numOfAsteroids, pointer, sizeof(uint8_t));
pointer += sizeof(uint8_t);
for (int i = 0; i < numOfAsteroids; ++i) {
asteroids.push_back(from_bin_object(pointer));
pointer += objectInfoSize;
}
//Bullets
memcpy(&numOfBullets, pointer, sizeof(uint8_t));
pointer += sizeof(uint8_t);
for (int i = 0; i < numOfBullets; ++i) {
bullets.push_back(from_bin_object(pointer));
pointer += objectInfoSize;
}
//Ships
ship1 = from_bin_object(pointer);
pointer += objectInfoSize;
ship2 = from_bin_object(pointer);
pointer += objectInfoSize;
//Sound
memcpy(&sound, pointer, sizeof(SoundId));
pointer += sizeof(SoundId);
//Won
memcpy(&won, pointer, sizeof(bool));
return 0;
}
}
| 31.011905 | 111 | 0.556814 | FenomenCoyote |
9338808403d50b9feeba727c2b0840807a4d42be | 16,112 | hpp | C++ | src/rynx/math/vector.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | 11 | 2019-08-19T08:44:14.000Z | 2020-09-22T20:04:46.000Z | src/rynx/math/vector.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null | src/rynx/math/vector.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null | #pragma once
#ifdef _WIN32
#include <intrin.h>
#endif
#include <rynx/system/assert.hpp>
#include <rynx/math/math.hpp>
#include <rynx/tech/serialization.hpp>
#include <cinttypes>
#include <cmath>
#include <limits>
#include <string>
#pragma warning (disable : 4201) // language extension used, anonymous structs
#define RYNX_VECTOR_SIMD 0
namespace rynx {
// generic 3d vector template.
template <class T>
struct alignas(16) vec3 {
vec3(T x = 0, T y = 0, T z = 0) : x(x), y(y), z(z) {}
vec3(const vec3&) = default;
vec3(vec3&&) = default;
vec3& operator = (vec3&&) = default;
vec3& operator = (const vec3&) = default;
template<typename U> explicit operator vec3<U>() const { return vec3<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z)); }
vec3 normal() { T l = length() + std::numeric_limits<float>::epsilon(); return *this * (1.0f / l); }
vec3& normalize() { T l = length() + std::numeric_limits<float>::epsilon(); *this *= 1.0f / l; return *this; }
vec3& operator*=(T scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; }
vec3& operator/=(T scalar) { x /= scalar; y /= scalar; z /= scalar; return *this; }
vec3& operator+=(vec3<T> other) { x += other.x; y += other.y; z += other.z; return *this; }
vec3& operator-=(vec3<T> other) { x -= other.x; y -= other.y; z -= other.z; return *this; }
vec3& operator*=(vec3<T> other) { x *= other.x; y *= other.y; z *= other.z; return *this; }
vec3& operator/=(vec3<T> other) { x /= other.x; y /= other.y; z /= other.z; return *this; }
vec3 operator+(const vec3<T>& other) const { return vec3(x + other.x, y + other.y, z + other.z); }
vec3 operator-(const vec3<T>& other) const { return vec3(x - other.x, y - other.y, z - other.z); }
vec3 operator*(const vec3<T>& other) const { return vec3(x * other.x, y * other.y, z * other.z); }
vec3 operator/(const vec3<T>& other) const { return vec3(x / other.x, y / other.y, z / other.z); }
vec3 operator*(const T & scalar) const { return vec3(x * scalar, y * scalar, z * scalar); }
vec3 operator/(const T & scalar) const { return vec3(x / scalar, y / scalar, z / scalar); }
vec3 operator-() const { return vec3(-x, -y, -z); }
bool operator != (const vec3 & other) { return (x != other.x) | (y != other.y) | (z != other.z); }
bool operator == (const vec3 & other) { return !((*this) != other); }
vec3& set(T xx, T yy, T zz) { x = xx; y = yy; z = zz; return *this; }
vec3 cross(const vec3 & other) const { return vec3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); }
vec3 normal2d() const { return vec3(-y, +x, 0); }
float cross2d(const vec3 & other) const { return x * other.y - y * other.x; }
T dot(const vec3 & other) const { return x * other.x + y * other.y + z * other.z; }
T length() const { return math::sqrt_approx(length_squared()); }
T length_squared() const { return dot(*this); }
operator std::string() const {
return std::string("(") + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
T x;
T y;
T z;
};
namespace serialization {
template<typename T> struct Serialize<rynx::vec3<T>> {
template<typename IOStream>
void serialize(const rynx::vec3<T>& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
}
template<typename IOStream>
void deserialize(rynx::vec3<T>& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
}
};
}
#if defined(_WIN32) && RYNX_VECTOR_SIMD
template<>
struct alignas(16) vec3<float> {
vec3(__m128 vec) : xmm(vec) {}
vec3(const vec3& other) : xmm(other.xmm) {}
vec3(float x = 0, float y = 0, float z = 0) { set(x, y, z); }
template<typename U> explicit operator vec3<U>() const { return vec3<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z)); }
vec3 operator * (const vec3& v) const { return vec3(_mm_mul_ps(xmm, v.xmm)); }
vec3 operator + (const vec3& v) const { return vec3(_mm_add_ps(xmm, v.xmm)); }
vec3 operator - (const vec3& v) const { return vec3(_mm_sub_ps(xmm, v.xmm)); }
vec3 operator / (const vec3& v) const { return vec3(_mm_div_ps(xmm, v.xmm)); }
vec3& operator *= (const vec3& v) { xmm = _mm_mul_ps(xmm, v.xmm); return *this; }
vec3& operator += (const vec3& v) { xmm = _mm_add_ps(xmm, v.xmm); return *this; }
vec3& operator -= (const vec3& v) { xmm = _mm_sub_ps(xmm, v.xmm); return *this; }
vec3& operator /= (const vec3& v) { xmm = _mm_div_ps(xmm, v.xmm); return *this; }
vec3 operator -() const { return operator *(-1.0f); }
vec3 operator * (float s) const {
const __m128 scalar = _mm_set1_ps(s);
return _mm_mul_ps(xmm, scalar);
}
vec3& operator *= (float s) {
const __m128 scalar = _mm_set1_ps(s);
return operator *= (scalar);
}
vec3 operator / (float scalar) const { return operator*(1.0f / scalar); }
vec3& operator /= (float scalar) { return operator *= (1.0f / scalar); }
float length() const {
return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(xmm, xmm, 0xff)));
}
float length_squared() const {
return _mm_cvtss_f32(_mm_dp_ps(xmm, xmm, 0xff));
}
vec3 cross(const vec3 v2) const {
__m128 t1 = _mm_shuffle_ps(xmm, xmm, 0xc9);
__m128 t2 = _mm_shuffle_ps(xmm, xmm, 0xd2);
__m128 t3 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xd2);
__m128 t4 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xc9);
__m128 t5 = _mm_mul_ps(t1, t3);
__m128 t6 = _mm_mul_ps(t2, t4);
return _mm_sub_ps(t5, t6);
}
operator std::string() const {
return std::string("(") + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
vec3 normal() { w = 0; float l = length() + std::numeric_limits<float>::epsilon(); return *this * (1.0f / l); }
vec3& normalize() { w = 0; float l = length() + std::numeric_limits<float>::epsilon(); *this *= 1.0f / l; return *this; }
// vec3 normal() const { return _mm_div_ps(xmm, _mm_sqrt_ps(_mm_dp_ps(xmm, xmm, 0xff))); }
// vec3& normalize() { xmm = normal().xmm; return *this; }
vec3 normal2d() const { return vec3(-y, +x, 0); }
float cross2d(vec3 other) const { return x * other.y - y * other.x; }
bool operator != (const vec3& other) {
__m128i vcmp = _mm_castps_si128(_mm_cmpneq_ps(xmm, other.xmm));
int32_t test = _mm_movemask_epi8(vcmp);
return test != 0;
}
bool operator == (const vec3& other) { return !((*this) != other); }
vec3& set(float xx, float yy, float zz) { xmm = _mm_set_ps(0.0f, zz, yy, xx); return *this; }
float dot(const vec3& other) const {
__m128 r1 = _mm_mul_ps(xmm, other.xmm);
__m128 shuf = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(2, 3, 0, 1));
__m128 sums = _mm_add_ps(r1, shuf);
shuf = _mm_movehl_ps(shuf, sums);
sums = _mm_add_ss(sums, shuf);
return _mm_cvtss_f32(sums);
}
union {
__m128 xmm;
struct {
float x;
float y;
float z;
float w;
};
};
};
#endif
// not simd representation of four consecutive float values.
struct floats4 {
#pragma warning (disable : 4201)
float x, y, z, w;
floats4(float x, const vec3<float>& other) : x(x), y(other.x), z(other.y), w(other.z) {}
floats4(const vec3<float>& other, float w) : x(other.x), y(other.y), z(other.z), w(w) {}
floats4(const floats4& other) : x(other.x), y(other.y), z(other.z), w(other.w) {}
constexpr floats4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
floats4() : x(0), y(0), z(0), w(0) {}
floats4 operator*(float scalar) const { return floats4(x * scalar, y * scalar, z * scalar, w * scalar); }
floats4 operator/(float scalar) const { return operator*(1.0f / scalar); }
floats4 operator+(float scalar) const { return floats4(x + scalar, y + scalar, z + scalar, w + scalar); }
floats4 operator-(float scalar) const { return floats4(x - scalar, y - scalar, z - scalar, w - scalar); }
floats4 operator/(const floats4& other) const { return floats4(x / other.x, y / other.y, z / other.z, w / other.w); }
floats4 operator*(const floats4& other) const { return floats4(x * other.x, y * other.y, z * other.z, w * other.w); }
floats4 operator+(const floats4& other) const { return floats4(x + other.x, y + other.y, z + other.z, w + other.w); }
floats4 operator-(const floats4& other) const { return floats4(x - other.x, y - other.y, z - other.z, w - other.w); }
floats4 operator-() { return floats4(-x, -y, -z, -w); }
floats4& operator+=(const floats4& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; }
floats4& operator-=(const floats4& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; }
/*
const float& operator [](int index) const {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return data[index];
}
float& operator [](int index) {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return data[index];
}
*/
};
namespace serialization {
template<> struct Serialize<rynx::floats4> {
template<typename IOStream>
void serialize(const rynx::floats4& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
writer(s.w);
}
template<typename IOStream>
void deserialize(rynx::floats4& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
reader(s.w);
}
};
}
template <class T>
struct alignas(16) vec4 {
vec4(const vec4 & other) : x(other.x), y(other.y), z(other.z), w(other.w) {}
vec4(vec3<float> other, float w) : x(other.x), y(other.y), z(other.z), w(w) {}
vec4(float w, vec3<float> other) : x(w), y(other.x), z(other.y), w(other.z) {}
constexpr vec4(T x = 0, T y = 0, T z = 0, T w = 0) : x(x), y(y), z(z), w(w) {}
template<typename U> explicit operator vec4<U>() const { return vec4<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z), static_cast<U>(w)); }
operator floats4() const { return floats4(x, y, z, w); }
vec3<T> xyz() const { return vec3<T>(x, y, z); }
vec4 normal() { T l = 1.0f / length(); return *this * l; }
vec4& normalize() { T l = 1.0f / length(); *this *= l; return *this; }
vec4& operator*=(T scalar) { x *= scalar; y *= scalar; z *= scalar; w *= scalar; return *this; }
vec4& operator/=(T scalar) { x /= scalar; y /= scalar; z /= scalar; w /= scalar; return *this; }
vec4& operator+=(const vec4 & other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; }
vec4& operator-=(const vec4 & other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; }
vec4 operator+(const vec4 & other) const { return vec4(x + other.x, y + other.y, z + other.z, w + other.w); }
vec4 operator-(const vec4 & other) const { return vec4(x - other.x, y - other.y, z - other.z, w - other.w); }
vec4 operator*(const vec4 & other) const { return vec4(x * other.x, y * other.y, z * other.z, w * other.w); }
vec4 operator*(T scalar) const { return vec4(x * scalar, y * scalar, z * scalar, w * scalar); }
vec4 operator/(T scalar) const { return vec4(x / scalar, y / scalar, z / scalar, w / scalar); }
vec4 operator-() const { return vec4(-x, -y, -z, -w); }
bool operator != (const vec4 & other) { return (x != other.x) | (y != other.y) | (z != other.z) | (w != other.w); }
bool operator == (const vec4 & other) { return !((*this) != other); }
vec4& set(T xx, T yy, T zz, T ww) { x = xx; y = yy; z = zz; w = ww; return *this; }
T dot(const vec4<T> & other) const { return x * other.x + y * other.y + z * other.z + w * other.w; }
T length() const { return math::sqrt_approx(length_squared()); }
T length_squared() const { return dot(*this); }
const T& operator [](int index) const {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return *((&x) + index);
}
T& operator [](int index) {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return *((&x) + index);
}
T x, y, z, w;
};
namespace serialization {
template<typename T> struct Serialize<rynx::vec4<T>> {
template<typename IOStream>
void serialize(const rynx::vec4<T>& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
writer(s.w);
}
template<typename IOStream>
void deserialize(rynx::vec4<T>& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
reader(s.w);
}
};
}
#if defined(_WIN32) && RYNX_VECTOR_SIMD
template<>
struct vec4<float> {
union {
struct {
float x, y, z, w;
};
struct {
float r, g, b, a;
};
__m128 xmm;
};
vec4() : vec4(0.0f) {}
vec4(__m128 v) : xmm(v) {}
vec4(float v) : xmm(_mm_set_ps(0, v, v, v)) {}
vec4(float x, float y, float z, float w = 0.0f) : xmm(_mm_set_ps(w, z, y, x)) {}
vec4(vec3<float> const& other, float w = 0.0f) : xmm(_mm_set_ps(w, other.z, other.y, other.x)) {}
operator __m128() const { return xmm; }
vec4 operator * (const vec4& v) const { return vec4(_mm_mul_ps(xmm, v.xmm)); }
vec4 operator + (const vec4& v) const { return vec4(_mm_add_ps(xmm, v.xmm)); }
vec4 operator - (const vec4& v) const { return vec4(_mm_sub_ps(xmm, v.xmm)); }
vec4 operator / (const vec4& v) const { return vec4(_mm_div_ps(xmm, v.xmm)); }
vec4& operator *= (const vec4& v) { xmm = _mm_mul_ps(xmm, v.xmm); return *this; }
vec4& operator += (const vec4& v) { xmm = _mm_add_ps(xmm, v.xmm); return *this; }
vec4& operator -= (const vec4& v) { xmm = _mm_sub_ps(xmm, v.xmm); return *this; }
vec4& operator /= (const vec4& v) { xmm = _mm_div_ps(xmm, v.xmm); return *this; }
vec4 operator -() const { return operator *(-1.0f); }
floats4 to_floats() const {
floats4 result;
_mm_storeu_ps(result.data, xmm);
return result;
}
operator floats4() const {
return to_floats();
}
vec3<float> xyz() const {
return vec3<float>(x, y, z);
}
vec4 cross(const vec4& v2) const {
__m128 t1 = _mm_shuffle_ps(xmm, xmm, 0xc9);
__m128 t2 = _mm_shuffle_ps(xmm, xmm, 0xd2);
__m128 t3 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xd2);
__m128 t4 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xc9);
__m128 t5 = _mm_mul_ps(t1, t3);
__m128 t6 = _mm_mul_ps(t2, t4);
return _mm_sub_ps(t5, t6);
}
vec4 operator * (float s) const {
const __m128 scalar = _mm_set1_ps(s);
return _mm_mul_ps(xmm, scalar);
}
vec4& operator *= (float s) {
const __m128 scalar = _mm_set1_ps(s);
return operator *= (scalar);
}
vec4 operator / (float scalar) const { return operator*(1.0f / scalar); }
vec4& operator /= (float scalar) { return operator *= (1.0f / scalar); }
float length() const {
return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(xmm, xmm, 0xff)));
}
float length_squared() const {
return _mm_cvtss_f32(_mm_dp_ps(xmm, xmm, 0xff));
}
vec4 normal() const {
return _mm_div_ps(xmm, _mm_sqrt_ps(_mm_dp_ps(xmm, xmm, 0xff)));
}
vec4& normalize() { xmm = normal().xmm; return *this; }
bool operator != (const vec4& other) {
__m128i vcmp = _mm_castps_si128(_mm_cmpneq_ps(xmm, other.xmm));
int32_t test = _mm_movemask_epi8(vcmp);
return test != 0;
}
bool operator == (const vec4& other) { return !((*this) != other); }
vec4& set(float xx, float yy, float zz, float ww = 0.0f) { xmm = _mm_set_ps(ww, zz, yy, xx); return *this; }
float dot(const vec4& other) const {
__m128 r1 = _mm_mul_ps(xmm, other.xmm);
__m128 shuf = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(2, 3, 0, 1));
__m128 sums = _mm_add_ps(r1, shuf);
shuf = _mm_movehl_ps(shuf, sums);
sums = _mm_add_ss(sums, shuf);
return _mm_cvtss_f32(sums);
}
float horizontal_add() const {
__m128 t1 = _mm_movehl_ps(xmm, xmm);
__m128 t2 = _mm_add_ps(xmm, t1);
__m128 t3 = _mm_shuffle_ps(t2, t2, 1);
__m128 t4 = _mm_add_ss(t2, t3);
return _mm_cvtss_f32(t4);
}
vec4 normal2d() const { return vec4(_mm_shuffle_ps(xmm, xmm, _MM_SHUFFLE(3, 3, 0, 1))) * vec4(-1, +1, 0, 0); }
float cross2d(const vec4& other) const {
// TODO: this is madness.
floats4 kek1 = *this;
floats4 kek2 = other;
return kek1.x * kek2.y - kek1.y * kek2.x;
}
};
#endif
inline vec3<float> operator * (float x, const vec3<float>& other) {
return other * x;
}
using vec4f = vec4<float>;
using vec3f = vec3<float>;
} | 35.964286 | 152 | 0.614883 | Apodus |
933a197141578a972f34ef9ff332cfd44ceb90ff | 24,621 | hpp | C++ | applications/FSIApplication/custom_utilities/mvqn_recursive_convergence_accelerator.hpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/FSIApplication/custom_utilities/mvqn_recursive_convergence_accelerator.hpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/FSIApplication/custom_utilities/mvqn_recursive_convergence_accelerator.hpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ \.
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Original author: Ruben Zorrilla
//
#if !defined(KRATOS_MVQN_RECURSIVE_CONVERGENCE_ACCELERATOR)
#define KRATOS_MVQN_RECURSIVE_CONVERGENCE_ACCELERATOR
/* System includes */
/* External includes */
/* Project includes */
#include "includes/ublas_interface.h"
#include "solving_strategies/convergence_accelerators/convergence_accelerator.h"
#include "utilities/svd_utils.h"
#include "utilities/qr_utility.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/** @brief Jacobian emulator
*/
template<class TSpace>
class JacobianEmulator
{
public:
///@name Type Definitions
///@{
typedef typename std::unique_ptr< JacobianEmulator<TSpace> > Pointer;
typedef typename TSpace::VectorType VectorType;
typedef typename TSpace::VectorPointerType VectorPointerType;
typedef typename TSpace::MatrixType MatrixType;
typedef typename TSpace::MatrixPointerType MatrixPointerType;
///@}
///@name Public member Variables
///@{
///@}
///@name Life Cycle
///@{
/**
* Old Jacobian pointer constructor.
* The inverse Jacobian emulator will use information from the previous Jacobian
*/
JacobianEmulator( Pointer&& OldJacobianEmulatorPointer )
{
mpOldJacobianEmulator = std::unique_ptr<JacobianEmulator<TSpace>>(std::move(OldJacobianEmulatorPointer));
}
/**
* Old Jacobian pointer constructor with recursive previous Jacobian deleting.
* The inverse Jacobian emulator will use information from the previous Jacobian
*/
JacobianEmulator( Pointer&& OldJacobianEmulatorPointer, const unsigned int EmulatorBufferSize )
{
mpOldJacobianEmulator = std::unique_ptr<JacobianEmulator<TSpace> >(std::move(OldJacobianEmulatorPointer));
// Get the last pointer out of buffer
if(EmulatorBufferSize > 1) {
JacobianEmulator* p = (mpOldJacobianEmulator->mpOldJacobianEmulator).get();
for(unsigned int i = 1; i < (EmulatorBufferSize); i++) {
if(i == EmulatorBufferSize-1) {
(p->mpOldJacobianEmulator).reset();
} else {
p = (p->mpOldJacobianEmulator).get();
}
}
} else { // If Jacobian buffer size equals 1 directly destroy the previous one
(mpOldJacobianEmulator->mpOldJacobianEmulator).reset();
}
}
/**
* Empty constructor.
* The Jacobian emulator will consider minus the identity matrix as previous Jacobian
*/
JacobianEmulator( ) {}
/**
* Copy Constructor.
*/
JacobianEmulator( const JacobianEmulator& rOther )
{
mpOldJacobianEmulator = rOther.mpOldJacobianEmulator;
}
/**
* Destructor.
*/
virtual ~JacobianEmulator() {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* Projects the approximated inverse Jacobian onto a vector
* @param rWorkVector: Vector in where the inverse Jacobian is to be projected
* @param rProjectedVector: Projected vector output
*/
void ApplyJacobian(
const VectorPointerType pWorkVector,
VectorPointerType pProjectedVector)
{
const auto data_cols = this->GetNumberOfDataCols();
// Security check for the empty observation matrices case (when no correction has been done in the previous step)
if (data_cols == 0) {
if (mpOldJacobianEmulator != nullptr) { // If it is available, consider the previous step Jacobian
mpOldJacobianEmulator->ApplyJacobian(pWorkVector, pProjectedVector);
} else { // When the JacobianEmulator has no PreviousJacobianEmulator consider minus the identity matrix as inverse Jacobian
TSpace::Assign(*pProjectedVector, -1.0, *pWorkVector);
}
} else {
const unsigned int residual_size = this->GetResidualSize();
// Set V and trans(V)
MatrixPointerType pV = Kratos::make_shared<MatrixType>(residual_size, data_cols);
MatrixPointerType pVtrans = Kratos::make_shared<MatrixType>(data_cols,residual_size);
for (std::size_t i = 0; i < data_cols; ++i){
const auto i_row = mJacobianObsMatrixV[i];
for (std::size_t j = 0; j < residual_size; ++j){
(*pV)(j, i) = i_row(j);
(*pVtrans)(i, j) = i_row(j);
}
}
// Set trans(V)*V
MatrixPointerType pVtransV = Kratos::make_shared<MatrixType>(data_cols, data_cols);
for (std::size_t i_row = 0; i_row < data_cols; ++i_row){
for (std::size_t i_col = 0; i_col < data_cols; ++i_col){
(*pVtransV)(i_row, i_col) = TSpace::Dot(mJacobianObsMatrixV[i_row],mJacobianObsMatrixV[i_col]);
}
}
// Compute trans(V)*pWorkVector
VectorPointerType pVtransWorkVect = Kratos::make_shared<VectorType>(data_cols);
TSpace::Mult(*pVtrans,*pWorkVector,*pVtransWorkVect);
// Do the QR decomp of trans(V)*V and solve ((trans(V)*V)^-1)*trans(V)*res
QR<double, row_major> QRUtil;
QRUtil.compute(data_cols, data_cols, &(*pVtransV)(0,0));
VectorPointerType pLambda = Kratos::make_shared<VectorType>(data_cols);
QRUtil.solve(&(*pVtransWorkVect)(0), &(*pLambda)(0));
// Compute (res - V*Lambda). Note that it is save in pY
VectorPointerType pY = Kratos::make_shared<VectorType>(residual_size);
TSpace::Mult(*pV,*pLambda,*pY);
TSpace::UnaliasedAdd(*pY, -1.0, *pWorkVector);
// Project over the previous step Jacobian
if (mpOldJacobianEmulator == nullptr) {
TSpace::Copy(*pY, *pProjectedVector); // Consider minus the identity as previous step Jacobian
} else {
VectorPointerType pYminus(new VectorType(*pY));
TSpace::Assign(*pYminus, -1.0, *pY);
mpOldJacobianEmulator->ApplyJacobian(pYminus, pProjectedVector); // The minus comes from the fact that we want to apply r_k - V_k*zQR
}
// w = W_k*z
VectorPointerType pW(new VectorType(residual_size));
TSpace::SetToZero(*pW);
for (unsigned int j = 0; j < data_cols; ++j) {
// TSpace::UnaliasedAdd(*pW, (*pzQR)(j), mJacobianObsMatrixW[j]);
TSpace::UnaliasedAdd(*pW, (*pLambda)(j), mJacobianObsMatrixW[j]);
}
TSpace::UnaliasedAdd(*pProjectedVector, 1.0, *pW);
}
}
/**
* Appends a two new columns to the observation matrices V and W
* Then, it checks if the new information columns are linear dependent
* to the existent ones by computing a QR decomposition and checking
* the diagonal coefficients of matrix R. If any value is less than
* the stablished threshold criterion, it is assume that the related
* column is close to be linear deppendent and is dropped.
* @param rNewColV new column to be appended to V observation matrix
* @param rNewColW new column to be appended to W observation matrix
* @param AbsCutOffEps epsilon value for the absolut cut-off criteria
* @return Returns true if the columns have been added
*/
bool AppendDataColumns(
const VectorType& rNewColV,
const VectorType& rNewColW,
const double AbsCutOff = 1e-8)
{
// Add the provided iformation to the observation matrices
mJacobianObsMatrixV.push_back(rNewColV);
mJacobianObsMatrixW.push_back(rNewColW);
// Loop to store a std::vector<VectorType> type as Matrix type
const std::size_t data_cols = this->GetNumberOfDataCols();
// Set trans(V)*V
MatrixPointerType ptransV_V = Kratos::make_shared<MatrixType>(data_cols, data_cols);
for (std::size_t i_row = 0; i_row < data_cols; ++i_row){
for (std::size_t i_col = 0; i_col < data_cols; ++i_col){
(*ptransV_V)(i_row, i_col) = TSpace::Dot(mJacobianObsMatrixV[i_row],mJacobianObsMatrixV[i_col]);
}
}
// Perform the Singular Value Decomposition (SVD) of matrix trans(V)*V
// SVD decomposition of matrix A yields two orthogonal matrices "u_svd"
// and "v_svd" as well as a diagonal matrix "w_svd" cotaining matrix
// A eigenvalues such that A = u_svd * w_svd * v_svd
MatrixType u_svd; // Orthogonal matrix (m x m)
MatrixType w_svd; // Rectangular diagonal matrix (m x n)
MatrixType v_svd; // Orthogonal matrix (n x n)
const std::string svd_type = "Jacobi"; // SVD decomposition type
const double svd_rel_tol = 1.0e-6; // Relative tolerance of the SVD decomposition (it will be multiplied by the input matrix norm)
SVDUtils<double>::SingularValueDecomposition(*ptransV_V, u_svd, w_svd, v_svd, svd_type, svd_rel_tol);
// Get the eigenvalues vector. Remember that eigenvalues
// of trans(A)*A are equal to the eigenvalues of A^2
std::vector<double> eig_vector(data_cols);
for (std::size_t i_col = 0; i_col < data_cols; ++i_col){
const double i_col_eig = std::sqrt(w_svd(i_col,i_col));
eig_vector[i_col] = i_col_eig;
}
// Get the maximum and minimum eigenvalues
double max_eig_V = 0.0;
double min_eig_V = std::numeric_limits<double>::max();
for (std::size_t i_col = 0; i_col < data_cols; ++i_col){
if (max_eig_V < eig_vector[i_col]) {
max_eig_V = eig_vector[i_col];
} else if (min_eig_V > eig_vector[i_col]) {
min_eig_V = eig_vector[i_col];
}
}
// Check the representativity of each eigenvalue and its value.
// If its value is close to zero or out of the representativity
// the correspondent data columns are dropped from both V and W.
if (min_eig_V < AbsCutOff * max_eig_V){
KRATOS_WARNING("MVQNRecursiveJacobianConvergenceAccelerator")
<< "Dropping info for eigenvalue " << min_eig_V << " (tolerance " << AbsCutOff * max_eig_V << " )" << std::endl;
mJacobianObsMatrixV.pop_back();
mJacobianObsMatrixW.pop_back();
return false;
}
// }
return true;
}
/**
* Calls the AppendDataColumns() method to add the new data columns
* to the observation matrices (provided that the new data columns
* are not linear dependent to the previous data). Then, if the
* information has been added, the oldest column is dropped to avoid
* the number of data columns become larger than the problem size.
* @param rNewColV new column to be appended to V observation matrix
* @param rNewColW new column to be appended to W observation matrix
* @param CutOffEps epsilon value for the cut-off criteria
*/
bool DropAndAppendDataColumns(
const VectorType& rNewColV,
const VectorType& rNewColW,
const double AbsCutOffEps = 1e-8)
{
// std::cout << "DropAndAppendDataColumns()" << std::endl;
const bool info_added = this->AppendDataColumns(rNewColV, rNewColW, AbsCutOffEps);
// If a new column has been added, drop the oldest data
if (info_added){
// Move the current data (oldest data is dropped)
for (unsigned int i = 0; i < (this->GetResidualSize() - 1); ++i) {
mJacobianObsMatrixV[i] = mJacobianObsMatrixV[i+1];
mJacobianObsMatrixW[i] = mJacobianObsMatrixW[i+1];
}
// Pop the last term (keep the amount of data columns as the problem size)
mJacobianObsMatrixV.pop_back();
mJacobianObsMatrixW.pop_back();
}
return info_added;
}
/**
* @brief Get the Number Of Data Cols object
* This function returns the number of data columns stored.
* Since the data columns is assumed (and must be) the same in
* both observation matrices, it is computed using V matrix.
* @return std::size_t number of data columns
*/
inline std::size_t GetNumberOfDataCols() const
{
return mJacobianObsMatrixV.size();
}
/**
* @brief Get the Residual Size object
* This function returns the interface residual size.
* Since the residual size is assumed (and must be) the same in
* every column for both observation matrices, it is computed
* using the first column of V matrix.
* @return std::size_t residual size
*/
inline std::size_t GetResidualSize() const
{
return TSpace::Size(mJacobianObsMatrixV[0]);
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
Pointer mpOldJacobianEmulator; // Pointer to the old Jacobian
std::vector<VectorType> mJacobianObsMatrixV; // Residual increment observation matrix
std::vector<VectorType> mJacobianObsMatrixW; // Solution increment observation matrix
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Serialization
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class JacobianEmulator */
/** @brief Recursive MVQN acceleration scheme
* Recursive MultiVectorQuasiNewton convergence accelerator. This convergence accelerator
* is an alternative implementation of the standard MVQN that avoids the storage of the
* @tparam TSparseSpace Linear algebra sparse space
* @tparam TDenseSpace Linear algebra dense space
*/
template<class TSparseSpace, class TDenseSpace>
class MVQNRecursiveJacobianConvergenceAccelerator: public ConvergenceAccelerator<TSparseSpace, TDenseSpace> {
public:
///@name Type Definitions
///@{
KRATOS_CLASS_POINTER_DEFINITION( MVQNRecursiveJacobianConvergenceAccelerator );
typedef ConvergenceAccelerator<TSparseSpace, TDenseSpace> BaseType;
typedef typename BaseType::Pointer BaseTypePointer;
typedef typename JacobianEmulator<TDenseSpace>::Pointer JacobianEmulatorPointerType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::VectorPointerType VectorPointerType;
typedef typename BaseType::MatrixType MatrixType;
typedef typename BaseType::MatrixPointerType MatrixPointerType;
///@}
///@name Life Cycle
///@{
/**
* Constructor.
* MVQN convergence accelerator
*/
explicit MVQNRecursiveJacobianConvergenceAccelerator(Parameters rConvAcceleratorParameters)
{
Parameters mvqn_recursive_default_parameters(R"(
{
"solver_type" : "MVQN_recursive",
"w_0" : 0.825,
"buffer_size" : 10,
"abs_cut_off_tol" : 1e-8
}
)");
rConvAcceleratorParameters.ValidateAndAssignDefaults(mvqn_recursive_default_parameters);
mOmega_0 = rConvAcceleratorParameters["w_0"].GetDouble();
mAbsCutOff = rConvAcceleratorParameters["abs_cut_off_tol"].GetDouble();
mJacobianBufferSize = rConvAcceleratorParameters["buffer_size"].GetInt();
mConvergenceAcceleratorStep = 0;
mConvergenceAcceleratorIteration = 0;
mConvergenceAcceleratorFirstCorrectionPerformed = false;
}
MVQNRecursiveJacobianConvergenceAccelerator(
double OmegaInitial = 0.825,
unsigned int JacobianBufferSize = 10,
double AbsCutOff = 1e-8)
{
mOmega_0 = OmegaInitial;
mAbsCutOff = AbsCutOff;
mJacobianBufferSize = JacobianBufferSize;
mConvergenceAcceleratorStep = 0;
mConvergenceAcceleratorIteration = 0;
mConvergenceAcceleratorFirstCorrectionPerformed = false;
}
/**
* Copy Constructor.
*/
MVQNRecursiveJacobianConvergenceAccelerator( const MVQNRecursiveJacobianConvergenceAccelerator& rOther ) = delete;
/**
* Destructor.
*/
virtual ~MVQNRecursiveJacobianConvergenceAccelerator() {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Initialize the Jacobian emulator
* This method constructs the very first Jacobian emulator of the simulation
*/
void Initialize() override
{
KRATOS_TRY;
mpCurrentJacobianEmulatorPointer = Kratos::make_unique<JacobianEmulator<TDenseSpace>>();
KRATOS_CATCH( "" );
}
/**
* @brief
* This method initializes the internal counters and constructs the previous step Jacobian emulator.
* The Jacobian emulator is recursively build at each time step according to the buffer size.
*/
void InitializeSolutionStep() override
{
KRATOS_TRY;
mConvergenceAcceleratorStep += 1;
mConvergenceAcceleratorIteration = 0;
if (mConvergenceAcceleratorStep <= mJacobianBufferSize) {
// Construct the inverse Jacobian emulator
mpCurrentJacobianEmulatorPointer = Kratos::make_unique<JacobianEmulator<TDenseSpace>>(std::move(mpCurrentJacobianEmulatorPointer));
} else {
// Construct the inverse Jacobian emulator considering the recursive elimination
mpCurrentJacobianEmulatorPointer = Kratos::make_unique<JacobianEmulator<TDenseSpace>>(std::move(mpCurrentJacobianEmulatorPointer), mJacobianBufferSize);
}
KRATOS_CATCH( "" );
}
/**
* @brief Performs the solution update
* The correction is computed using an inverse Jacobian approximation obtained with a recursive matrix-free version of the MVQN (MultiVector Quasi-Newton method).
* @param rResidualVector: Residual vector from the residual evaluation
* @param rIterationGuess: Current iteration guess to be corrected. Should be initialized outside the convergence accelerator.
*/
void UpdateSolution(
const VectorType& rResidualVector,
VectorType& rIterationGuess) override
{
KRATOS_TRY;
const auto problem_size = TSparseSpace::Size(rResidualVector);
VectorPointerType pAuxResidualVector(new VectorType(rResidualVector));
VectorPointerType pAuxIterationGuess(new VectorType(rIterationGuess));
std::swap(mpResidualVector_1, pAuxResidualVector);
std::swap(mpIterationValue_1, pAuxIterationGuess);
if (mConvergenceAcceleratorIteration == 0) {
if (mConvergenceAcceleratorFirstCorrectionPerformed == false) {
// The very first correction of the problem is done with a fixed point iteration
TSparseSpace::UnaliasedAdd(rIterationGuess, mOmega_0, *mpResidualVector_1);
mConvergenceAcceleratorFirstCorrectionPerformed = true;
} else {
VectorPointerType pInitialCorrection(new VectorType(rResidualVector));
// The first correction of the current step is done with the previous step inverse Jacobian approximation
mpCurrentJacobianEmulatorPointer->ApplyJacobian(mpResidualVector_1, pInitialCorrection);
TSparseSpace::UnaliasedAdd(rIterationGuess, -1.0, *pInitialCorrection); // Recall the minus sign coming from the Taylor expansion of the residual (Newton-Raphson)
}
} else {
// Gather the new observation matrices column information
VectorPointerType pNewColV(new VectorType(*mpResidualVector_1));
VectorPointerType pNewColW(new VectorType(*mpIterationValue_1));
TSparseSpace::UnaliasedAdd(*pNewColV, -1.0, *mpResidualVector_0); // NewColV = ResidualVector_1 - ResidualVector_0
TSparseSpace::UnaliasedAdd(*pNewColW, -1.0, *mpIterationValue_0); // NewColW = IterationValue_1 - IterationValue_0
// Observation matrices information filling
bool info_added = false;
const std::size_t n_data_cols = mpCurrentJacobianEmulatorPointer->GetNumberOfDataCols();
if (n_data_cols < problem_size) {
info_added = (mpCurrentJacobianEmulatorPointer)->AppendDataColumns(*pNewColV, *pNewColW, mAbsCutOff);
} else {
info_added = (mpCurrentJacobianEmulatorPointer)->DropAndAppendDataColumns(*pNewColV, *pNewColW, mAbsCutOff);
}
KRATOS_WARNING_IF("MVQNRecursiveJacobianConvergenceAccelerator", !info_added) << "Information not added to the observation matrices." << std::endl;
// Apply the current step inverse Jacobian emulator to the residual vector
VectorPointerType pIterationCorrection(new VectorType(rResidualVector));
mpCurrentJacobianEmulatorPointer->ApplyJacobian(mpResidualVector_1, pIterationCorrection);
TSparseSpace::UnaliasedAdd(rIterationGuess, -1.0, *pIterationCorrection); // Recall the minus sign coming from the Taylor expansion of the residual (Newton-Raphson)
}
KRATOS_CATCH( "" );
}
/**
* @brief Do the MVQN variables update
* Updates the MVQN iteration variables for the next non-linear iteration
*/
void FinalizeNonLinearIteration() override
{
KRATOS_TRY;
// Variables update
mpIterationValue_0 = mpIterationValue_1;
mpResidualVector_0 = mpResidualVector_1;
mConvergenceAcceleratorIteration += 1;
KRATOS_CATCH( "" );
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
double mOmega_0; // Relaxation factor for the initial fixed point iteration
double mAbsCutOff; // Tolerance for the absolute cut-off criterion
unsigned int mJacobianBufferSize; // User-defined Jacobian buffer-size
unsigned int mConvergenceAcceleratorStep; // Convergence accelerator steps counter
unsigned int mConvergenceAcceleratorIteration; // Convergence accelerator iteration counter
bool mConvergenceAcceleratorFirstCorrectionPerformed; // Indicates that the initial fixed point iteration has been already performed
VectorPointerType mpResidualVector_0; // Previous iteration residual vector pointer
VectorPointerType mpResidualVector_1; // Current iteration residual vector pointer
VectorPointerType mpIterationValue_0; // Previous iteration guess pointer
VectorPointerType mpIterationValue_1; // Current iteration guess pointer
JacobianEmulatorPointerType mpCurrentJacobianEmulatorPointer; // Current step Jacobian approximator pointer
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Serialization
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class MVQNRecursiveJacobianConvergenceAccelerator */
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_MVQN_RECURSIVE_CONVERGENCE_ACCELERATOR defined */
| 36.260677 | 178 | 0.627594 | ma6yu |
933a3eba09ee7058ecbf4375bc4bbd7a39214df4 | 2,082 | cpp | C++ | foobar2000/SDK/console.cpp | ttsping/foo_fix | 4a0b950ccb8c10c912a9abeeffdd85e777463309 | [
"Info-ZIP"
] | 294 | 2017-11-20T17:42:08.000Z | 2022-03-31T04:15:13.000Z | foobar2000/SDK/console.cpp | ttsping/foo_fix | 4a0b950ccb8c10c912a9abeeffdd85e777463309 | [
"Info-ZIP"
] | 108 | 2021-04-08T10:57:27.000Z | 2022-03-27T08:02:15.000Z | foobar2000/SDK/console.cpp | ttsping/foo_fix | 4a0b950ccb8c10c912a9abeeffdd85e777463309 | [
"Info-ZIP"
] | 14 | 2018-03-10T12:47:03.000Z | 2021-11-11T09:00:08.000Z | #include "foobar2000.h"
void console::info(const char * p_message) {print(p_message);}
void console::error(const char * p_message) {complain("Error", p_message);}
void console::warning(const char * p_message) {complain("Warning", p_message);}
void console::info_location(const playable_location & src) {print_location(src);}
void console::info_location(const metadb_handle_ptr & src) {print_location(src);}
void console::print_location(const metadb_handle_ptr & src)
{
print_location(src->get_location());
}
void console::print_location(const playable_location & src)
{
FB2K_console_formatter() << src;
}
void console::complain(const char * what, const char * msg) {
FB2K_console_formatter() << what << ": " << msg;
}
void console::complain(const char * what, std::exception const & e) {
complain(what, e.what());
}
void console::print(const char* p_message)
{
if (core_api::are_services_available()) {
service_ptr_t<console_receiver> ptr;
service_enum_t<console_receiver> e;
while(e.next(ptr)) ptr->print(p_message,~0);
}
}
void console::printf(const char* p_format,...)
{
va_list list;
va_start(list,p_format);
printfv(p_format,list);
va_end(list);
}
void console::printfv(const char* p_format,va_list p_arglist)
{
pfc::string8_fastalloc temp;
uPrintfV(temp,p_format,p_arglist);
print(temp);
}
namespace {
class event_logger_recorder_impl : public event_logger_recorder {
public:
void playback( event_logger::ptr playTo ) {
for(auto i = m_entries.first(); i.is_valid(); ++i ) {
playTo->log_entry( i->line.get_ptr(), i->severity );
}
}
void log_entry( const char * line, unsigned severity ) {
auto rec = m_entries.insert_last();
rec->line = line;
rec->severity = severity;
}
private:
struct entry_t {
pfc::string_simple line;
unsigned severity;
};
pfc::chain_list_v2_t< entry_t > m_entries;
};
}
event_logger_recorder::ptr event_logger_recorder::create() {
return new service_impl_t<event_logger_recorder_impl>();
}
| 25.084337 | 82 | 0.690202 | ttsping |
933ce72b5fe5ab5c82eb4813b347590d5c28c7da | 4,816 | cpp | C++ | Source/V2World/V2Localisation.cpp | Zemurin/EU3ToVic2 | 7df6de2039986ed46683d792ec0c72bbdf6a2f18 | [
"MIT"
] | 114 | 2015-06-07T20:27:45.000Z | 2020-08-16T05:05:56.000Z | EU3ToV2/Source/V2World/V2Localisation.cpp | iamdafu/paradoxGameConverters | 674364a22917155642ade923e5dfbe38a5fa9610 | [
"MIT"
] | 553 | 2015-07-20T23:58:26.000Z | 2019-06-13T21:45:56.000Z | EU3ToV2/Source/V2World/V2Localisation.cpp | iamdafu/paradoxGameConverters | 674364a22917155642ade923e5dfbe38a5fa9610 | [
"MIT"
] | 106 | 2015-07-27T00:21:16.000Z | 2020-06-10T10:13:13.000Z | /*Copyright (c) 2014 The Paradox Game Converters Project
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/
#include "V2Localisation.h"
#include <Windows.h>
#include "..\EU3World\EU3Country.h"
#include "..\Log.h"
#include "..\WinUtils.h"
const std::array<std::string, V2Localisation::numLanguages> V2Localisation::languages =
{ "code", "english", "french", "german", "spanish" };
void V2Localisation::SetTag(const std::string& newTag)
{
tag = newTag;
}
void V2Localisation::ReadFromCountry(const EU3Country& source)
{
for (size_t i = 1; i < numLanguages; ++i)
{
if (!languages[i].empty())
{
name[i - 1] = source.getName(i);
adjective[i - 1] = source.getAdjective(i);
}
}
}
void V2Localisation::SetPartyKey(size_t partyIndex, const std::string& partyKey)
{
if (parties.size() <= partyIndex)
{
parties.resize(partyIndex + 1);
}
parties[partyIndex].key = partyKey;
}
void V2Localisation::SetPartyName(size_t partyIndex, const std::string& language, const std::string& name)
{
if (parties.size() <= partyIndex)
{
parties.resize(partyIndex + 1);
}
auto languageIter = std::find(languages.begin(), languages.end(), language);
if (languageIter != languages.end())
{
size_t languageIndex = std::distance(languages.begin(), languageIter);
parties[partyIndex].name[languageIndex] = name;
}
}
void V2Localisation::WriteToStream(std::ostream& out) const
{
out << Convert(tag);
for (const auto& localisedName : name)
{
out << ';' << Convert(localisedName);
}
out << "x\n";
out << Convert(tag) << "_ADJ";
for (const auto& localisedAdjective : adjective)
{
out << ';' << Convert(localisedAdjective);
}
out << "x\n";
for (const auto& party : parties)
{
out << Convert(party.key);
for (const auto& localisedPartyName : party.name)
{
out << ';' << Convert(localisedPartyName);
}
out << "x\n";
}
}
std::string V2Localisation::convertCountryFileName(const std::string countryFileName) const
{
return Convert(countryFileName);
}
std::string V2Localisation::Convert(const std::string& text)
{
if (text.empty())
{
return "";
}
int utf16Size = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), text.size(), NULL, 0);
if (utf16Size == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to UTF-16: " << WinUtils::GetLastWindowsError();
return "";
}
std::vector<wchar_t> utf16Text(utf16Size, L'\0');
int result = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), text.size(), &utf16Text[0], utf16Size);
if (result == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to UTF-16: " << WinUtils::GetLastWindowsError();
return "";
}
int latin1Size = WideCharToMultiByte(1252, WC_NO_BEST_FIT_CHARS | WC_COMPOSITECHECK | WC_DEFAULTCHAR, &utf16Text[0], utf16Size, NULL, 0, "0", NULL);
if (latin1Size == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to Latin-1: " << WinUtils::GetLastWindowsError();
return "";
}
std::vector<char> latin1Text(latin1Size, '\0');
result = WideCharToMultiByte(1252, WC_NO_BEST_FIT_CHARS | WC_COMPOSITECHECK | WC_DEFAULTCHAR, &utf16Text[0], utf16Size, &latin1Text[0], latin1Size, "0", NULL);
if (result == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to Latin-1: " << WinUtils::GetLastWindowsError();
return "";
}
return std::string(latin1Text.begin(), latin1Text.end());
}
std::string V2Localisation::GetLocalName()
{
for (std::string thisname : name)
{
if (!thisname.empty())
{
return thisname;
}
}
return "";
}
std::string V2Localisation::GetLocalAdjective()
{
for (std::string thisname : adjective)
{
if (!thisname.empty())
{
return thisname;
}
}
return "";
}
| 28.497041 | 161 | 0.670473 | Zemurin |
933db5aeb9fa89518a14f7f027f19c2f902cb16c | 7,014 | hpp | C++ | cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | #pragma once
// Description: C++18 Table Object interface for CFInt.
/*
* org.msscf.msscf.CFInt
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFInt 2.13 Internet Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory 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.
*
* MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
#include <cfint/ICFIntPublic.hpp>
namespace cfint {
class ICFIntSchemaObj;
class ICFIntClusterObj;
class ICFIntClusterEditObj;
class ICFIntClusterTableObj;
class ICFIntHostNodeObj;
class ICFIntHostNodeEditObj;
class ICFIntHostNodeTableObj;
class ICFIntISOCcyObj;
class ICFIntISOCcyEditObj;
class ICFIntISOCcyTableObj;
class ICFIntISOCtryObj;
class ICFIntISOCtryEditObj;
class ICFIntISOCtryTableObj;
class ICFIntISOCtryCcyObj;
class ICFIntISOCtryCcyEditObj;
class ICFIntISOCtryCcyTableObj;
class ICFIntISOCtryLangObj;
class ICFIntISOCtryLangEditObj;
class ICFIntISOCtryLangTableObj;
class ICFIntISOLangObj;
class ICFIntISOLangEditObj;
class ICFIntISOLangTableObj;
class ICFIntISOTZoneObj;
class ICFIntISOTZoneEditObj;
class ICFIntISOTZoneTableObj;
class ICFIntLicenseObj;
class ICFIntLicenseEditObj;
class ICFIntLicenseTableObj;
class ICFIntMajorVersionObj;
class ICFIntMajorVersionEditObj;
class ICFIntMajorVersionTableObj;
class ICFIntMimeTypeObj;
class ICFIntMimeTypeEditObj;
class ICFIntMimeTypeTableObj;
class ICFIntMinorVersionObj;
class ICFIntMinorVersionEditObj;
class ICFIntMinorVersionTableObj;
class ICFIntSecAppObj;
class ICFIntSecAppEditObj;
class ICFIntSecAppTableObj;
class ICFIntSecDeviceObj;
class ICFIntSecDeviceEditObj;
class ICFIntSecDeviceTableObj;
class ICFIntSecFormObj;
class ICFIntSecFormEditObj;
class ICFIntSecFormTableObj;
class ICFIntSecGroupObj;
class ICFIntSecGroupEditObj;
class ICFIntSecGroupTableObj;
class ICFIntSecGroupFormObj;
class ICFIntSecGroupFormEditObj;
class ICFIntSecGroupFormTableObj;
class ICFIntSecGrpIncObj;
class ICFIntSecGrpIncEditObj;
class ICFIntSecGrpIncTableObj;
class ICFIntSecGrpMembObj;
class ICFIntSecGrpMembEditObj;
class ICFIntSecGrpMembTableObj;
class ICFIntSecSessionObj;
class ICFIntSecSessionEditObj;
class ICFIntSecSessionTableObj;
class ICFIntSecUserObj;
class ICFIntSecUserEditObj;
class ICFIntSecUserTableObj;
class ICFIntServiceObj;
class ICFIntServiceEditObj;
class ICFIntServiceTableObj;
class ICFIntServiceTypeObj;
class ICFIntServiceTypeEditObj;
class ICFIntServiceTypeTableObj;
class ICFIntSubProjectObj;
class ICFIntSubProjectEditObj;
class ICFIntSubProjectTableObj;
class ICFIntSysClusterObj;
class ICFIntSysClusterEditObj;
class ICFIntSysClusterTableObj;
class ICFIntTSecGroupObj;
class ICFIntTSecGroupEditObj;
class ICFIntTSecGroupTableObj;
class ICFIntTSecGrpIncObj;
class ICFIntTSecGrpIncEditObj;
class ICFIntTSecGrpIncTableObj;
class ICFIntTSecGrpMembObj;
class ICFIntTSecGrpMembEditObj;
class ICFIntTSecGrpMembTableObj;
class ICFIntTenantObj;
class ICFIntTenantEditObj;
class ICFIntTenantTableObj;
class ICFIntTldObj;
class ICFIntTldEditObj;
class ICFIntTldTableObj;
class ICFIntTopDomainObj;
class ICFIntTopDomainEditObj;
class ICFIntTopDomainTableObj;
class ICFIntTopProjectObj;
class ICFIntTopProjectEditObj;
class ICFIntTopProjectTableObj;
class ICFIntURLProtocolObj;
class ICFIntURLProtocolEditObj;
class ICFIntURLProtocolTableObj;
}
#include <cfintobj/ICFIntMimeTypeObj.hpp>
#include <cfintobj/ICFIntMimeTypeEditObj.hpp>
namespace cfint {
class ICFIntMimeTypeTableObj
{
public:
ICFIntMimeTypeTableObj();
virtual ~ICFIntMimeTypeTableObj();
virtual cfint::ICFIntSchemaObj* getSchema() = 0;
virtual void setSchema( cfint::ICFIntSchemaObj* value ) = 0;
virtual void minimizeMemory() = 0;
virtual const std::string getTableName() = 0;
virtual const std::string getTableDbName() = 0;
virtual const classcode_t* getObjQualifyingClassCode() = 0;
virtual cfint::ICFIntMimeTypeObj* newInstance() = 0;
virtual cfint::ICFIntMimeTypeEditObj* newEditInstance( cfint::ICFIntMimeTypeObj* orig ) = 0;
virtual cfint::ICFIntMimeTypeObj* realizeMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
virtual void deepDisposeByIdIdx( const int32_t MimeTypeId ) = 0;
virtual void deepDisposeByUNameIdx( const std::string& Name ) = 0;
virtual void reallyDeepDisposeMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
virtual cfint::ICFIntMimeTypeObj* createMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeType( cfint::CFIntMimeTypePKey* pkey,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* lockMimeType( cfint::CFIntMimeTypePKey* pkey ) = 0;
virtual std::vector<cfint::ICFIntMimeTypeObj*> readAllMimeType( bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByIdIdx( const int32_t MimeTypeId,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByUNameIdx(const std::string& Name,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeType( cfint::CFIntMimeTypePKey* pkey ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByIdIdx(const int32_t MimeTypeId ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByUNameIdx(const std::string& Name ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByLookupUNameIdx(const std::string& Name,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByLookupUNameIdx(const std::string& Name ) = 0;
virtual cfint::ICFIntMimeTypeObj* updateMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual void deleteMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual void deleteMimeTypeByIdIdx( const int32_t MimeTypeId ) = 0;
virtual void deleteMimeTypeByUNameIdx(const std::string& Name ) = 0;
virtual void reallyDetachFromIndexesMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
};
}
| 32.929577 | 101 | 0.795979 | msobkow |
933ed79568df20fbe3b6c80e554625477769863e | 5,289 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/ScrollerItem.cc,v 1.4 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: ScrollerItem.cc,v $
* Revision 1.4 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.3 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
*
*
*
*/
#include "StreamUtils.hh"
#include "CheckBox.hh"
#include "Dialog.hh"
#include "Scroller.hh"
#include "CommandNumbers.hh"
#include "ScrollerItem.hh"
#include "ScrollerInfo.hh"
#include "ViewItemInfo.hh"
class SetScrollerInfoCommand : public Command {
public:
SetScrollerInfoCommand (ScrollerItem& item, ScrollerInfo& info);
override void DoIt ();
override void UnDoIt ();
private:
ScrollerItem& fItem;
Command* fItemInfoCommand;
Point fNewScrollSize;
Point fOldScrollSize;
Boolean fOldVSBar;
Boolean fNewVSBar;
Boolean fOldHSBar;
Boolean fNewHSBar;
};
/*
********************************************************************************
****************************** ScrollerItemType ********************************
********************************************************************************
*/
ScrollerItemType::ScrollerItemType () :
ItemType (eBuildGroup, "Scroller", (ItemBuilderProc)&ScrollerItemBuilder)
{
Require (sThis == Nil);
sThis = this;
}
ScrollerItemType& ScrollerItemType::Get ()
{
RequireNotNil (sThis);
return (*sThis);
}
ViewItem* ScrollerItemType::ScrollerItemBuilder ()
{
return (new ScrollerItem ());
}
ScrollerItemType* ScrollerItemType::sThis = Nil;
/*
********************************************************************************
****************************** ScrollerItem ************************************
********************************************************************************
*/
ScrollerItem::ScrollerItem () :
GroupItem (ScrollerItemType::Get (), True),
fHasVerticalSBar (True),
fHasHorizontalSBar (True)
{
SetMaxVersion (2);
}
ScrollerItem::ScrollerItem (ItemType& type) :
GroupItem (type, True),
fHasVerticalSBar (True),
fHasHorizontalSBar (True)
{
SetMaxVersion (2);
}
Boolean ScrollerItem::GetHasVerticalSBar () const
{
return (fHasVerticalSBar);
}
void ScrollerItem::SetHasVerticalSBar (Boolean hasSBar)
{
if (hasSBar != fHasVerticalSBar) {
fHasVerticalSBar = hasSBar;
GetGroupItemView ().SetVerticalScrollBar (hasSBar ? Scroller::kBuildDefaultSlider : Scroller::kBuildNoSlider);
}
Ensure (hasSBar == fHasVerticalSBar);
}
Boolean ScrollerItem::GetHasHorizontalSBar () const
{
return (fHasHorizontalSBar);
}
void ScrollerItem::SetHasHorizontalSBar (Boolean hasSBar)
{
if (hasSBar != fHasHorizontalSBar) {
fHasHorizontalSBar = hasSBar;
GetGroupItemView ().SetHorizontalScrollBar (hasSBar ? Scroller::kBuildDefaultSlider : Scroller::kBuildNoSlider);
}
Ensure (hasSBar == fHasHorizontalSBar);
}
String ScrollerItem::GetHeaderFileName ()
{
static const String kHeaderFileName = "Scroller.hh";
return (kHeaderFileName);
}
void ScrollerItem::DoRead_ (class istream& from)
{
GroupItem::DoRead_ (from);
if (GetVersion () > 1) {
Boolean h, v;
from >> v >> h;
SetHasVerticalSBar (v);
SetHasHorizontalSBar (h);
}
}
void ScrollerItem::DoWrite_ (class ostream& to, int tabCount) const
{
GroupItem::DoWrite_ (to, tabCount);
to << tab (tabCount) << GetHasVerticalSBar () << GetHasHorizontalSBar () << newline;
}
void ScrollerItem::WriteParameters (class ostream& to, int tabCount, CommandNumber language, CommandNumber gui)
{
GroupItem::WriteParameters (to, tabCount, language, gui);
}
void ScrollerItem::WriteBuilder (class ostream& to, int tabCount)
{
ViewItem::WriteBuilder (to, tabCount);
to << "(";
if (GetHasVerticalSBar ()) {
to << "Scroller::kBuildDefaultSlider, ";
}
else {
to << "Scroller::kBuildNoSlider, ";
}
if (GetHasHorizontalSBar ()) {
to << "Scroller::kBuildDefaultSlider";
}
else {
to << "Scroller::kBuildNoSlider";
}
to << ")," << newline;
}
SetScrollerInfoCommand::SetScrollerInfoCommand (ScrollerItem& item, ScrollerInfo& info) :
Command (eSetItemInfo, kUndoable),
fItem (item),
fItemInfoCommand (Nil),
fNewScrollSize (info.GetScrollBounds ()),
fOldScrollSize (item.GetScrollSize ()),
fOldVSBar (item.GetHasVerticalSBar ()),
fNewVSBar (info.GetVSBarField ().GetOn ()),
fOldHSBar (item.GetHasHorizontalSBar ()),
fNewHSBar (info.GetHSBarField ().GetOn ())
{
fItemInfoCommand = new SetItemInfoCommand (item, info.GetViewItemInfo ());
}
void SetScrollerInfoCommand::DoIt ()
{
fItemInfoCommand->DoIt ();
fItem.SetScrollSize (fNewScrollSize);
fItem.SetHasVerticalSBar (fNewVSBar);
fItem.SetHasHorizontalSBar (fNewHSBar);
Command::DoIt ();
}
void SetScrollerInfoCommand::UnDoIt ()
{
fItemInfoCommand->UnDoIt ();
fItem.SetScrollSize (fOldScrollSize);
fItem.SetHasVerticalSBar (fOldVSBar);
fItem.SetHasHorizontalSBar (fOldHSBar);
Command::UnDoIt ();
}
void ScrollerItem::SetItemInfo ()
{
ScrollerInfo info = ScrollerInfo (*this);
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetScrollerInfoCommand (*this, info));
DirtyDocument ();
}
}
| 22.896104 | 114 | 0.656646 | SophistSolutions |
9343eddb8090e93ce379fe6e757a74f1c43adb29 | 53,922 | cpp | C++ | Matrix4f.cpp | PankeyCR/aMonkeyEngine | 83e631a6185a65e88d6eea95c73475b0da59ea54 | [
"BSD-3-Clause"
] | 1 | 2021-07-02T11:47:10.000Z | 2021-07-02T11:47:10.000Z | Matrix4f.cpp | PankeyCR/aMonkeyEngine | 83e631a6185a65e88d6eea95c73475b0da59ea54 | [
"BSD-3-Clause"
] | null | null | null | Matrix4f.cpp | PankeyCR/aMonkeyEngine | 83e631a6185a65e88d6eea95c73475b0da59ea54 | [
"BSD-3-Clause"
] | null | null | null |
#ifndef Matrix4f_cpp
#define Matrix4f_cpp
#include "Matrix4f.h"
ame::Matrix4f *ame::Matrix4f::ZERO = new ame::Matrix4f(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
ame::Matrix4f *ame::Matrix4f::IDENTITY = new ame::Matrix4f();
ame::Matrix4f::Matrix4f() {
//this->loadIdentity();
}
ame::Matrix4f::Matrix4f(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
this->m00 = m00;
this->m01 = m01;
this->m02 = m02;
this->m03 = m03;
this->m10 = m10;
this->m11 = m11;
this->m12 = m12;
this->m13 = m13;
this->m20 = m20;
this->m21 = m21;
this->m22 = m22;
this->m23 = m23;
this->m30 = m30;
this->m31 = m31;
this->m32 = m32;
this->m33 = m33;
}
ame::Matrix4f::Matrix4f(ame::List<float> *array) {
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
ame::Matrix4f ame::Matrix4f::fromFrame(Vector3f location, Vector3f direction, Vector3f up, Vector3f left) {
// TempVars vars = TempVars.get();
// try {
// Vector3f fwdVector = vars.vect1.set(direction);
// Vector3f leftVector = vars.vect2.set(fwdVector).crossLocal(up);
// Vector3f upVector = vars.vect3.set(leftVector).crossLocal(fwdVector);
// m00 = leftVector.x;
// m01 = leftVector.y;
// m02 = leftVector.z;
// m03 = -leftVector.dot(location);
// m10 = upVector.x;
// m11 = upVector.y;
// m12 = upVector.z;
// m13 = -upVector.dot(location);
// m20 = -fwdVector.x;
// m21 = -fwdVector.y;
// m22 = -fwdVector.z;
// m23 = fwdVector.dot(location);
// m30 = 0f;
// m31 = 0f;
// m32 = 0f;
// m33 = 1f;
// } finally {
// vars.release();
// }
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::fromFrameLocal(Vector3f location, Vector3f direction, Vector3f up, Vector3f left) {
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
ame::List<float> *ame::Matrix4f::get(ame::List<float> *matrix) {
return this->get(matrix, true);
}
ame::List<float> *ame::Matrix4f::get(ame::List<float> *matrix, bool rowMajor) {
if (matrix == nullptr) {
return nullptr;
}
if (matrix->getPosition() == 0) {
if (rowMajor) {
matrix->addLValue(m00);
matrix->addLValue(m01);
matrix->addLValue(m02);
matrix->addLValue(m03);
matrix->addLValue(m10);
matrix->addLValue(m11);
matrix->addLValue(m12);
matrix->addLValue(m13);
matrix->addLValue(m20);
matrix->addLValue(m21);
matrix->addLValue(m22);
matrix->addLValue(m23);
matrix->addLValue(m30);
matrix->addLValue(m31);
matrix->addLValue(m32);
matrix->addLValue(m33);
} else {
matrix->addLValue(m00);
matrix->addLValue(m10);
matrix->addLValue(m20);
matrix->addLValue(m30);
matrix->addLValue(m01);
matrix->addLValue(m11);
matrix->addLValue(m21);
matrix->addLValue(m31);
matrix->addLValue(m02);
matrix->addLValue(m12);
matrix->addLValue(m22);
matrix->addLValue(m32);
matrix->addLValue(m03);
matrix->addLValue(m13);
matrix->addLValue(m23);
matrix->addLValue(m33);
}
}
return matrix;
}
// ame::List<float> ame::Matrix4f::get() {
// return get(true);
// }
// ame::List<float> ame::Matrix4f::get(bool rowMajor) {
// Arrayame::List<float> matrix();
// if (rowMajor) {
// matrix->addLValue(m00);
// matrix->addLValue(m01);
// matrix->addLValue(m02);
// matrix->addLValue(m03);
// matrix->addLValue(m10);
// matrix->addLValue(m11);
// matrix->addLValue(m12);
// matrix->addLValue(m13);
// matrix->addLValue(m20);
// matrix->addLValue(m21);
// matrix->addLValue(m22);
// matrix->addLValue(m23);
// matrix->addLValue(m30);
// matrix->addLValue(m31);
// matrix->addLValue(m32);
// matrix->addLValue(m33);
// } else {
// matrix->addLValue(m00);
// matrix->addLValue(m10);
// matrix->addLValue(m20);
// matrix->addLValue(m30);
// matrix->addLValue(m01);
// matrix->addLValue(m11);
// matrix->addLValue(m21);
// matrix->addLValue(m31);
// matrix->addLValue(m02);
// matrix->addLValue(m12);
// matrix->addLValue(m22);
// matrix->addLValue(m32);
// matrix->addLValue(m03);
// matrix->addLValue(m13);
// matrix->addLValue(m23);
// matrix->addLValue(m33);
// }
// return Arrayame::List<float>(&matrix);
// }
float ame::Matrix4f::get(int i, int j) {
switch (i) {
case 0:
switch (j) {
case 0:
return m00;
case 1:
return m01;
case 2:
return m02;
case 3:
return m03;
}
case 1:
switch (j) {
case 0:
return m10;
case 1:
return m11;
case 2:
return m12;
case 3:
return m13;
}
case 2:
switch (j) {
case 0:
return m20;
case 1:
return m21;
case 2:
return m22;
case 3:
return m23;
}
case 3:
switch (j) {
case 0:
return m30;
case 1:
return m31;
case 2:
return m32;
case 3:
return m33;
}
}
return 0.0f;
}
// ame::List<float> ame::Matrix4f::getColumn(int i) {
// return getColumn(i, NULL);
// }
ame::List<float> *ame::Matrix4f::getColumn(int i, ame::List<float> *store) {
if (store == nullptr) {
return nullptr;
}
if (store->getPosition() == 0) {
switch (i) {
case 0:
store->addLValue(this->m00);
store->addLValue(this->m10);
store->addLValue(this->m20);
store->addLValue(this->m30);
break;
case 1:
store->addLValue(this->m01);
store->addLValue(this->m11);
store->addLValue(this->m21);
store->addLValue(this->m31);
break;
case 2:
store->addLValue(this->m02);
store->addLValue(this->m12);
store->addLValue(this->m22);
store->addLValue(this->m32);
break;
case 3:
store->addLValue(this->m03);
store->addLValue(this->m13);
store->addLValue(this->m23);
store->addLValue(this->m33);
break;
default:
return nullptr;
}
}
return store;
}
ame::Matrix4f ame::Matrix4f::setColumn(int i, ame::List<float> *column) {
if (column == nullptr) {
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
if (column->getPosition() >= 4) {
}
switch (i) {
case 0:
this->m00 = *column->getByPosition(0);
this->m10 = *column->getByPosition(1);
this->m20 = *column->getByPosition(2);
this->m30 = *column->getByPosition(3);
break;
case 1:
this->m01 = *column->getByPosition(0);
this->m11 = *column->getByPosition(1);
this->m21 = *column->getByPosition(2);
this->m31 = *column->getByPosition(3);
break;
case 2:
this->m02 = *column->getByPosition(0);
this->m12 = *column->getByPosition(1);
this->m22 = *column->getByPosition(2);
this->m32 = *column->getByPosition(3);
break;
case 3:
this->m03 = *column->getByPosition(0);
this->m13 = *column->getByPosition(1);
this->m23 = *column->getByPosition(2);
this->m33 = *column->getByPosition(3);
break;
default:
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::set(int i, int j, float value) {
switch (i) {
case 0:
switch (j) {
case 0:
this->m00 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m01 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m02 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m03 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 1:
switch (j) {
case 0:
this->m10 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m11 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m12 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m13 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 2:
switch (j) {
case 0:
this->m20 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m21 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m22 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m23 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 3:
switch (j) {
case 0:
this->m30 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m31 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m32 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m33 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
}
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
// ame::Matrix4f ame::Matrix4f::set(float[4][4] matrix) {
// if (matrix.length != 4 || matrix[0].length != 4) {
// return;
// }
// this->m00 = matrix[0][0];
// this->m01 = matrix[0][1];
// this->m02 = matrix[0][2];
// this->m03 = matrix[0][3];
// this->m10 = matrix[1][0];
// this->m11 = matrix[1][1];
// this->m12 = matrix[1][2];
// this->m13 = matrix[1][3];
// this->m20 = matrix[2][0];
// this->m21 = matrix[2][1];
// this->m22 = matrix[2][2];
// this->m23 = matrix[2][3];
// this->m30 = matrix[3][0];
// this->m31 = matrix[3][1];
// this->m32 = matrix[3][2];
// this->m33 = matrix[3][3];
// return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
// this->m10, this->m11, this->m12, this->m13,
// this->m20, this->m21, this->m22, this->m23,
// this->m30, this->m31, this->m32, this->m33);
// }
ame::Matrix4f ame::Matrix4f::set(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
this->m00 = m00;
this->m01 = m01;
this->m02 = m02;
this->m03 = m03;
this->m10 = m10;
this->m11 = m11;
this->m12 = m12;
this->m13 = m13;
this->m20 = m20;
this->m21 = m21;
this->m22 = m22;
this->m23 = m23;
this->m30 = m30;
this->m31 = m31;
this->m32 = m32;
this->m33 = m33;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::set(ame::Matrix4f matrix) {
this->m00 = matrix.m00;
this->m01 = matrix.m01;
this->m02 = matrix.m02;
this->m03 = matrix.m03;
this->m10 = matrix.m10;
this->m11 = matrix.m11;
this->m12 = matrix.m12;
this->m13 = matrix.m13;
this->m20 = matrix.m20;
this->m21 = matrix.m21;
this->m22 = matrix.m22;
this->m23 = matrix.m23;
this->m30 = matrix.m30;
this->m31 = matrix.m31;
this->m32 = matrix.m32;
this->m33 = matrix.m33;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
/////////////////////////////////////////////////////////////////////////////////////////
/*
ame::List<float> *ame::Matrix4f::set(ame::List<float> *matrix) {
return this->set(matrix, true);
}
ame::List<float> *ame::Matrix4f::set(ame::List<float> *matrix, bool rowMajor) {
if (matrix == nullptr) {
return nullptr;
}
if (matrix->getPosition() < 16) {
return matrix;
}
if (rowMajor) {
this->m00 = *matrix->getByPosition(0);
this->m01 = *matrix->getByPosition(1);
this->m02 = *matrix->getByPosition(2);
this->m03 = *matrix->getByPosition(3);
this->m10 = *matrix->getByPosition(4);
this->m11 = *matrix->getByPosition(5);
this->m12 = *matrix->getByPosition(6);
this->m13 = *matrix->getByPosition(7);
this->m20 = *matrix->getByPosition(8);
this->m21 = *matrix->getByPosition(9);
this->m22 = *matrix->getByPosition(10);
this->m23 = *matrix->getByPosition(11);
this->m30 = *matrix->getByPosition(12);
this->m31 = *matrix->getByPosition(13);
this->m32 = *matrix->getByPosition(14);
this->m33 = *matrix->getByPosition(15);
} else {
this->m00 = *matrix->getByPosition(0);
this->m01 = *matrix->getByPosition(4);
this->m02 = *matrix->getByPosition(8);
this->m03 = *matrix->getByPosition(12);
this->m10 = *matrix->getByPosition(1);
this->m11 = *matrix->getByPosition(5);
this->m12 = *matrix->getByPosition(9);
this->m13 = *matrix->getByPosition(13);
this->m20 = *matrix->getByPosition(2);
this->m21 = *matrix->getByPosition(6);
this->m22 = *matrix->getByPosition(10);
this->m23 = *matrix->getByPosition(14);
this->m30 = *matrix->getByPosition(3);
this->m31 = *matrix->getByPosition(7);
this->m32 = *matrix->getByPosition(11);
this->m33 = *matrix->getByPosition(15);
}
return matrix;
}
ame::Matrix4f ame::Matrix4f::transpose() {
float tmp[16];
get(tmp, true);
return ame::Matrix4f(tmp);
}
ame::Matrix4f ame::Matrix4f::transposeLocal() {
float tmp = m01;
m01 = m10;
m10 = tmp;
tmp = m02;
m02 = m20;
m20 = tmp;
tmp = m03;
m03 = m30;
m30 = tmp;
tmp = m12;
m12 = m21;
m21 = tmp;
tmp = m13;
m13 = m31;
m31 = tmp;
tmp = m23;
m23 = m32;
m32 = tmp;
return ame::Matrix4f(this);
}
void ame::Matrix4f::loadIdentity() {
m01 = m02 = m03 = 0.0f;
m10 = m12 = m13 = 0.0f;
m20 = m21 = m23 = 0.0f;
m30 = m31 = m32 = 0.0f;
m00 = m11 = m22 = m33 = 1.0f;
}
void ame::Matrix4f::fromFrustum(float near, float far, float left, float right, float top, float bottom, bool parallel) {
loadIdentity();
if (parallel) {
// scale
m00 = 2.0f / (right - left);
//m11 = 2.0f / (bottom - top);
m11 = 2.0f / (top - bottom);
m22 = -2.0f / (far - near);
m33 = 1f;
// translation
m03 = -(right + left) / (right - left);
//m31 = -(bottom + top) / (bottom - top);
m13 = -(top + bottom) / (top - bottom);
m23 = -(far + near) / (far - near);
} else {
m00 = (2.0f * near) / (right - left);
m11 = (2.0f * near) / (top - bottom);
m32 = -1.0f;
m33 = -0.0f;
// A
m02 = (right + left) / (right - left);
// B
m12 = (top + bottom) / (top - bottom);
// C
m22 = -(far + near) / (far - near);
// D
m23 = -(2.0f * far * near) / (far - near);
}
}
void ame::Matrix4f::fromAngleAxis(float angle, Vector3f axis) {
Vector3f normAxis = axis.normalize();
fromAngleNormalAxis(angle, normAxis);
}
void ame::Matrix4f::fromAngleNormalAxis(float angle, Vector3f axis) {
zero();
m33 = 1;
float fCos = FastMath.cos(angle);
float fSin = FastMath.sin(angle);
float fOneMinusCos = ((float) 1.0) - fCos;
float fX2 = axis.x * axis.x;
float fY2 = axis.y * axis.y;
float fZ2 = axis.z * axis.z;
float fXYM = axis.x * axis.y * fOneMinusCos;
float fXZM = axis.x * axis.z * fOneMinusCos;
float fYZM = axis.y * axis.z * fOneMinusCos;
float fXSin = axis.x * fSin;
float fYSin = axis.y * fSin;
float fZSin = axis.z * fSin;
m00 = fX2 * fOneMinusCos + fCos;
m01 = fXYM - fZSin;
m02 = fXZM + fYSin;
m10 = fXYM + fZSin;
m11 = fY2 * fOneMinusCos + fCos;
m12 = fYZM - fXSin;
m20 = fXZM - fYSin;
m21 = fYZM + fXSin;
m22 = fZ2 * fOneMinusCos + fCos;
}
void ame::Matrix4f::multLocal(float scalar) {
m00 *= scalar;
m01 *= scalar;
m02 *= scalar;
m03 *= scalar;
m10 *= scalar;
m11 *= scalar;
m12 *= scalar;
m13 *= scalar;
m20 *= scalar;
m21 *= scalar;
m22 *= scalar;
m23 *= scalar;
m30 *= scalar;
m31 *= scalar;
m32 *= scalar;
m33 *= scalar;
}
ame::Matrix4f ame::Matrix4f::mult(float scalar) {
ame::Matrix4f out = new ame::Matrix4f();
out.set(this);
out.multLocal(scalar);
return out;
}
ame::Matrix4f ame::Matrix4f::mult(float scalar, ame::Matrix4f store) {
store.set(this);
store.multLocal(scalar);
return store;
}
ame::Matrix4f ame::Matrix4f::mult(ame::Matrix4f in2) {
return mult(in2, null);
}
ame::Matrix4f ame::Matrix4f::mult(ame::Matrix4f in2, ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float temp00, temp01, temp02, temp03;
float temp10, temp11, temp12, temp13;
float temp20, temp21, temp22, temp23;
float temp30, temp31, temp32, temp33;
temp00 = m00 * in2.m00
+ m01 * in2.m10
+ m02 * in2.m20
+ m03 * in2.m30;
temp01 = m00 * in2.m01
+ m01 * in2.m11
+ m02 * in2.m21
+ m03 * in2.m31;
temp02 = m00 * in2.m02
+ m01 * in2.m12
+ m02 * in2.m22
+ m03 * in2.m32;
temp03 = m00 * in2.m03
+ m01 * in2.m13
+ m02 * in2.m23
+ m03 * in2.m33;
temp10 = m10 * in2.m00
+ m11 * in2.m10
+ m12 * in2.m20
+ m13 * in2.m30;
temp11 = m10 * in2.m01
+ m11 * in2.m11
+ m12 * in2.m21
+ m13 * in2.m31;
temp12 = m10 * in2.m02
+ m11 * in2.m12
+ m12 * in2.m22
+ m13 * in2.m32;
temp13 = m10 * in2.m03
+ m11 * in2.m13
+ m12 * in2.m23
+ m13 * in2.m33;
temp20 = m20 * in2.m00
+ m21 * in2.m10
+ m22 * in2.m20
+ m23 * in2.m30;
temp21 = m20 * in2.m01
+ m21 * in2.m11
+ m22 * in2.m21
+ m23 * in2.m31;
temp22 = m20 * in2.m02
+ m21 * in2.m12
+ m22 * in2.m22
+ m23 * in2.m32;
temp23 = m20 * in2.m03
+ m21 * in2.m13
+ m22 * in2.m23
+ m23 * in2.m33;
temp30 = m30 * in2.m00
+ m31 * in2.m10
+ m32 * in2.m20
+ m33 * in2.m30;
temp31 = m30 * in2.m01
+ m31 * in2.m11
+ m32 * in2.m21
+ m33 * in2.m31;
temp32 = m30 * in2.m02
+ m31 * in2.m12
+ m32 * in2.m22
+ m33 * in2.m32;
temp33 = m30 * in2.m03
+ m31 * in2.m13
+ m32 * in2.m23
+ m33 * in2.m33;
store.m00 = temp00;
store.m01 = temp01;
store.m02 = temp02;
store.m03 = temp03;
store.m10 = temp10;
store.m11 = temp11;
store.m12 = temp12;
store.m13 = temp13;
store.m20 = temp20;
store.m21 = temp21;
store.m22 = temp22;
store.m23 = temp23;
store.m30 = temp30;
store.m31 = temp31;
store.m32 = temp32;
store.m33 = temp33;
return store;
}
ame::Matrix4f ame::Matrix4f::multLocal(ame::Matrix4f in2) {
return mult(in2, this);
}
Vector3f ame::Matrix4f::mult(Vector3f vec) {
return mult(vec, null);
}
Vector3f ame::Matrix4f::mult(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz + m03;
store.y = m10 * vx + m11 * vy + m12 * vz + m13;
store.z = m20 * vx + m21 * vy + m22 * vz + m23;
return store;
}
Vector4f ame::Matrix4f::mult(Vector4f vec) {
return mult(vec, null);
}
Vector4f ame::Matrix4f::mult(Vector4f vec, Vector4f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector4f();
}
float vx = vec.x, vy = vec.y, vz = vec.z, vw = vec.w;
store.x = m00 * vx + m01 * vy + m02 * vz + m03 * vw;
store.y = m10 * vx + m11 * vy + m12 * vz + m13 * vw;
store.z = m20 * vx + m21 * vy + m22 * vz + m23 * vw;
store.w = m30 * vx + m31 * vy + m32 * vz + m33 * vw;
return store;
}
Vector4f ame::Matrix4f::multAcross(Vector4f vec) {
return multAcross(vec, null);
}
Vector4f ame::Matrix4f::multAcross(Vector4f vec, Vector4f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector4f();
}
float vx = vec.x, vy = vec.y, vz = vec.z, vw = vec.w;
store.x = m00 * vx + m10 * vy + m20 * vz + m30 * vw;
store.y = m01 * vx + m11 * vy + m21 * vz + m31 * vw;
store.z = m02 * vx + m12 * vy + m22 * vz + m32 * vw;
store.w = m03 * vx + m13 * vy + m23 * vz + m33 * vw;
return store;
}
Vector3f ame::Matrix4f::multNormal(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz;
store.y = m10 * vx + m11 * vy + m12 * vz;
store.z = m20 * vx + m21 * vy + m22 * vz;
return store;
}
Vector3f ame::Matrix4f::multNormalAcross(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m10 * vy + m20 * vz;
store.y = m01 * vx + m11 * vy + m21 * vz;
store.z = m02 * vx + m12 * vy + m22 * vz;
return store;
}
float ame::Matrix4f::multProj(Vector3f vec, Vector3f store) {
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz + m03;
store.y = m10 * vx + m11 * vy + m12 * vz + m13;
store.z = m20 * vx + m21 * vy + m22 * vz + m23;
return m30 * vx + m31 * vy + m32 * vz + m33;
}
Vector3f ame::Matrix4f::multAcross(Vector3f vec, Vector3f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m10 * vy + m20 * vz + m30 * 1;
store.y = m01 * vx + m11 * vy + m21 * vz + m31 * 1;
store.z = m02 * vx + m12 * vy + m22 * vz + m32 * 1;
return store;
}
Quaternion ame::Matrix4f::mult(Quaternion vec, Quaternion store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Quaternion();
}
float x = m00 * vec.x + m10 * vec.y + m20 * vec.z + m30 * vec.w;
float y = m01 * vec.x + m11 * vec.y + m21 * vec.z + m31 * vec.w;
float z = m02 * vec.x + m12 * vec.y + m22 * vec.z + m32 * vec.w;
float w = m03 * vec.x + m13 * vec.y + m23 * vec.z + m33 * vec.w;
store.x = x;
store.y = y;
store.z = z;
store.w = w;
return store;
}
float *ame::Matrix4f::mult(float[] vec4f) {
if (null == vec4f || vec4f.length != 4) {
logger.warning("invalid array given, must be nonnull and length 4");
return null;
}
float x = vec4f[0], y = vec4f[1], z = vec4f[2], w = vec4f[3];
vec4f[0] = m00 * x + m01 * y + m02 * z + m03 * w;
vec4f[1] = m10 * x + m11 * y + m12 * z + m13 * w;
vec4f[2] = m20 * x + m21 * y + m22 * z + m23 * w;
vec4f[3] = m30 * x + m31 * y + m32 * z + m33 * w;
return vec4f;
}
float *ame::Matrix4f::multAcross(float[] vec4f) {
if (null == vec4f || vec4f.length != 4) {
logger.warning("invalid array given, must be nonnull and length 4");
return null;
}
float x = vec4f[0], y = vec4f[1], z = vec4f[2], w = vec4f[3];
vec4f[0] = m00 * x + m10 * y + m20 * z + m30 * w;
vec4f[1] = m01 * x + m11 * y + m21 * z + m31 * w;
vec4f[2] = m02 * x + m12 * y + m22 * z + m32 * w;
vec4f[3] = m03 * x + m13 * y + m23 * z + m33 * w;
return vec4f;
}
ame::Matrix4f ame::Matrix4f::invert() {
return invert(null);
}
ame::Matrix4f ame::Matrix4f::invert(ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
if (FastMath.abs(fDet) <= 0f) {
throw new ArithmeticException("This matrix cannot be inverted");
}
store.m00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
store.m10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
store.m20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
store.m30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
store.m01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
store.m11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
store.m21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
store.m31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
store.m02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
store.m12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
store.m22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
store.m32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
store.m03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
store.m13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
store.m23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
store.m33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
float fInvDet = 1.0f / fDet;
store.multLocal(fInvDet);
return store;
}
ame::Matrix4f ame::Matrix4f::invertLocal() {
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
if (FastMath.abs(fDet) <= 0f) {
return zero();
}
float f00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
float f10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
float f20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
float f30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
float f01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
float f11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
float f21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
float f31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
float f02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
float f12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
float f22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
float f32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
float f03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
float f13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
float f23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
float f33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
m00 = f00;
m01 = f01;
m02 = f02;
m03 = f03;
m10 = f10;
m11 = f11;
m12 = f12;
m13 = f13;
m20 = f20;
m21 = f21;
m22 = f22;
m23 = f23;
m30 = f30;
m31 = f31;
m32 = f32;
m33 = f33;
float fInvDet = 1.0f / fDet;
multLocal(fInvDet);
return this;
}
ame::Matrix4f ame::Matrix4f::adjoint() {
return adjoint(null);
}
void ame::Matrix4f::setTransform(Vector3f position, Vector3f scale, Matrix3f rotMat) {
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
// Set up final matrix with scale, rotation and translation
m00 = scale.x * rotMat.m00;
m01 = scale.y * rotMat.m01;
m02 = scale.z * rotMat.m02;
m03 = position.x;
m10 = scale.x * rotMat.m10;
m11 = scale.y * rotMat.m11;
m12 = scale.z * rotMat.m12;
m13 = position.y;
m20 = scale.x * rotMat.m20;
m21 = scale.y * rotMat.m21;
m22 = scale.z * rotMat.m22;
m23 = position.z;
// No projection term
m30 = 0;
m31 = 0;
m32 = 0;
m33 = 1;
}
ame::Matrix4f ame::Matrix4f::adjoint(ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
store.m00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
store.m10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
store.m20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
store.m30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
store.m01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
store.m11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
store.m21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
store.m31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
store.m02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
store.m12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
store.m22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
store.m32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
store.m03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
store.m13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
store.m23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
store.m33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
return store;
}
float ame::Matrix4f::determinant() {
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
return fDet;
}
ame::Matrix4f ame::Matrix4f::zero() {
m00 = m01 = m02 = m03 = 0.0f;
m10 = m11 = m12 = m13 = 0.0f;
m20 = m21 = m22 = m23 = 0.0f;
m30 = m31 = m32 = m33 = 0.0f;
return this;
}
ame::Matrix4f ame::Matrix4f::addLValue(ame::Matrix4f mat) {
ame::Matrix4f result = new ame::Matrix4f();
result.m00 = this.m00 + mat.m00;
result.m01 = this.m01 + mat.m01;
result.m02 = this.m02 + mat.m02;
result.m03 = this.m03 + mat.m03;
result.m10 = this.m10 + mat.m10;
result.m11 = this.m11 + mat.m11;
result.m12 = this.m12 + mat.m12;
result.m13 = this.m13 + mat.m13;
result.m20 = this.m20 + mat.m20;
result.m21 = this.m21 + mat.m21;
result.m22 = this.m22 + mat.m22;
result.m23 = this.m23 + mat.m23;
result.m30 = this.m30 + mat.m30;
result.m31 = this.m31 + mat.m31;
result.m32 = this.m32 + mat.m32;
result.m33 = this.m33 + mat.m33;
return result;
}
void ame::Matrix4f::addLValueLocal(ame::Matrix4f mat) {
m00 += mat.m00;
m01 += mat.m01;
m02 += mat.m02;
m03 += mat.m03;
m10 += mat.m10;
m11 += mat.m11;
m12 += mat.m12;
m13 += mat.m13;
m20 += mat.m20;
m21 += mat.m21;
m22 += mat.m22;
m23 += mat.m23;
m30 += mat.m30;
m31 += mat.m31;
m32 += mat.m32;
m33 += mat.m33;
}
Vector3f ame::Matrix4f::toTranslationVector() {
return new Vector3f(m03, m13, m23);
}
void ame::Matrix4f::toTranslationVector(Vector3f vector) {
vector.set(m03, m13, m23);
}
Quaternion ame::Matrix4f::toRotationQuat() {
Quaternion quat = new Quaternion();
quat.fromRotationMatrix(toRotationMatrix());
return quat;
}
void ame::Matrix4f::toRotationQuat(Quaternion q) {
q.fromRotationMatrix(toRotationMatrix());
}
Matrix3f ame::Matrix4f::toRotationMatrix() {
return new Matrix3f(m00, m01, m02, m10, m11, m12, m20, m21, m22);
}
void ame::Matrix4f::toRotationMatrix(Matrix3f mat) {
mat.m00 = m00;
mat.m01 = m01;
mat.m02 = m02;
mat.m10 = m10;
mat.m11 = m11;
mat.m12 = m12;
mat.m20 = m20;
mat.m21 = m21;
mat.m22 = m22;
}
Vector3f ame::Matrix4f::toScaleVector() {
Vector3f result = new Vector3f();
this.toScaleVector(result);
return result;
}
void ame::Matrix4f::toScaleVector(Vector3f vector) {
float scaleX = (float) Math.sqrt(m00 * m00 + m10 * m10 + m20 * m20);
float scaleY = (float) Math.sqrt(m01 * m01 + m11 * m11 + m21 * m21);
float scaleZ = (float) Math.sqrt(m02 * m02 + m12 * m12 + m22 * m22);
vector.set(scaleX, scaleY, scaleZ);
}
void ame::Matrix4f::setScale(float x, float y, float z) {
TempVars vars = TempVars.get();
vars.vect1.set(m00, m10, m20);
vars.vect1.normalizeLocal().multLocal(x);
m00 = vars.vect1.x;
m10 = vars.vect1.y;
m20 = vars.vect1.z;
vars.vect1.set(m01, m11, m21);
vars.vect1.normalizeLocal().multLocal(y);
m01 = vars.vect1.x;
m11 = vars.vect1.y;
m21 = vars.vect1.z;
vars.vect1.set(m02, m12, m22);
vars.vect1.normalizeLocal().multLocal(z);
m02 = vars.vect1.x;
m12 = vars.vect1.y;
m22 = vars.vect1.z;
vars.release();
}
void ame::Matrix4f::setScale(Vector3f scale) {
this.setScale(scale.x, scale.y, scale.z);
}
void ame::Matrix4f::setTranslation(float[] translation) {
if (translation.length != 3) {
throw new IllegalArgumentException(
"Translation size must be 3.");
}
m03 = translation[0];
m13 = translation[1];
m23 = translation[2];
}
void ame::Matrix4f::setTranslation(float x, float y, float z) {
m03 = x;
m13 = y;
m23 = z;
}
void ame::Matrix4f::setTranslation(Vector3f translation) {
m03 = translation.x;
m13 = translation.y;
m23 = translation.z;
}
void ame::Matrix4f::setInverseTranslation(float[] translation) {
if (translation.length != 3) {
throw new IllegalArgumentException(
"Translation size must be 3.");
}
m03 = -translation[0];
m13 = -translation[1];
m23 = -translation[2];
}
void ame::Matrix4f::angleRotation(Vector3f angles) {
float angle;
float sr, sp, sy, cr, cp, cy;
angle = (angles.z * FastMath.DEG_TO_RAD);
sy = FastMath.sin(angle);
cy = FastMath.cos(angle);
angle = (angles.y * FastMath.DEG_TO_RAD);
sp = FastMath.sin(angle);
cp = FastMath.cos(angle);
angle = (angles.x * FastMath.DEG_TO_RAD);
sr = FastMath.sin(angle);
cr = FastMath.cos(angle);
// matrix = (Z * Y) * X
m00 = cp * cy;
m10 = cp * sy;
m20 = -sp;
m01 = sr * sp * cy + cr * -sy;
m11 = sr * sp * sy + cr * cy;
m21 = sr * cp;
m02 = (cr * sp * cy + -sr * -sy);
m12 = (cr * sp * sy + -sr * cy);
m22 = cr * cp;
m03 = 0.0f;
m13 = 0.0f;
m23 = 0.0f;
}
void ame::Matrix4f::setRotationQuaternion(Quaternion quat) {
quat.toRotationMatrix(this);
}
void ame::Matrix4f::setInverseRotationRadians(float[] angles) {
if (angles.length != 3) {
throw new IllegalArgumentException(
"Angles must be of size 3.");
}
double cr = FastMath.cos(angles[0]);
double sr = FastMath.sin(angles[0]);
double cp = FastMath.cos(angles[1]);
double sp = FastMath.sin(angles[1]);
double cy = FastMath.cos(angles[2]);
double sy = FastMath.sin(angles[2]);
m00 = (float) (cp * cy);
m10 = (float) (cp * sy);
m20 = (float) (-sp);
double srsp = sr * sp;
double crsp = cr * sp;
m01 = (float) (srsp * cy - cr * sy);
m11 = (float) (srsp * sy + cr * cy);
m21 = (float) (sr * cp);
m02 = (float) (crsp * cy + sr * sy);
m12 = (float) (crsp * sy - sr * cy);
m22 = (float) (cr * cp);
}
void ame::Matrix4f::setInverseRotationDegrees(float[] angles) {
if (angles.length != 3) {
throw new IllegalArgumentException(
"Angles must be of size 3.");
}
float vec[] = new float[3];
vec[0] = (angles[0] * FastMath.RAD_TO_DEG);
vec[1] = (angles[1] * FastMath.RAD_TO_DEG);
vec[2] = (angles[2] * FastMath.RAD_TO_DEG);
setInverseRotationRadians(vec);
}
void ame::Matrix4f::inverseTranslateVect(float[] vec) {
if (vec.length != 3) {
throw new IllegalArgumentException(
"vec must be of size 3.");
}
vec[0] = vec[0] - m03;
vec[1] = vec[1] - m13;
vec[2] = vec[2] - m23;
}
void ame::Matrix4f::inverseTranslateVect(Vector3f data) {
data.x -= m03;
data.y -= m13;
data.z -= m23;
}
void ame::Matrix4f::translateVect(Vector3f data) {
data.x += m03;
data.y += m13;
data.z += m23;
}
void ame::Matrix4f::inverseRotateVect(Vector3f vec) {
float vx = vec.x, vy = vec.y, vz = vec.z;
vec.x = vx * m00 + vy * m10 + vz * m20;
vec.y = vx * m01 + vy * m11 + vz * m21;
vec.z = vx * m02 + vy * m12 + vz * m22;
}
void ame::Matrix4f::rotateVect(Vector3f vec) {
float vx = vec.x, vy = vec.y, vz = vec.z;
vec.x = vx * m00 + vy * m01 + vz * m02;
vec.y = vx * m10 + vy * m11 + vz * m12;
vec.z = vx * m20 + vy * m21 + vz * m22;
}
String ame::Matrix4f::toString() {
StringBuilder result = new StringBuilder("ame::Matrix4f\n[\n");
result.append(" ");
result.append(m00);
result.append(" ");
result.append(m01);
result.append(" ");
result.append(m02);
result.append(" ");
result.append(m03);
result.append(" \n");
result.append(" ");
result.append(m10);
result.append(" ");
result.append(m11);
result.append(" ");
result.append(m12);
result.append(" ");
result.append(m13);
result.append(" \n");
result.append(" ");
result.append(m20);
result.append(" ");
result.append(m21);
result.append(" ");
result.append(m22);
result.append(" ");
result.append(m23);
result.append(" \n");
result.append(" ");
result.append(m30);
result.append(" ");
result.append(m31);
result.append(" ");
result.append(m32);
result.append(" ");
result.append(m33);
result.append(" \n]");
return result.toString();
}
bool ame::Matrix4f::equals(Object *o) {
if (!(o instanceof ame::Matrix4f) || o == null) {
return false;
}
if (this == o) {
return true;
}
ame::Matrix4f comp = (ame::Matrix4f) o;
if (Float.compare(m00, comp.m00) != 0) {
return false;
}
if (Float.compare(m01, comp.m01) != 0) {
return false;
}
if (Float.compare(m02, comp.m02) != 0) {
return false;
}
if (Float.compare(m03, comp.m03) != 0) {
return false;
}
if (Float.compare(m10, comp.m10) != 0) {
return false;
}
if (Float.compare(m11, comp.m11) != 0) {
return false;
}
if (Float.compare(m12, comp.m12) != 0) {
return false;
}
if (Float.compare(m13, comp.m13) != 0) {
return false;
}
if (Float.compare(m20, comp.m20) != 0) {
return false;
}
if (Float.compare(m21, comp.m21) != 0) {
return false;
}
if (Float.compare(m22, comp.m22) != 0) {
return false;
}
if (Float.compare(m23, comp.m23) != 0) {
return false;
}
if (Float.compare(m30, comp.m30) != 0) {
return false;
}
if (Float.compare(m31, comp.m31) != 0) {
return false;
}
if (Float.compare(m32, comp.m32) != 0) {
return false;
}
if (Float.compare(m33, comp.m33) != 0) {
return false;
}
return true;
}
// void write(JmeExporter e) throws IOException {
// OutputCapsule cap = e.getCapsule(this);
// cap.write(m00, "m00", 1);
// cap.write(m01, "m01", 0);
// cap.write(m02, "m02", 0);
// cap.write(m03, "m03", 0);
// cap.write(m10, "m10", 0);
// cap.write(m11, "m11", 1);
// cap.write(m12, "m12", 0);
// cap.write(m13, "m13", 0);
// cap.write(m20, "m20", 0);
// cap.write(m21, "m21", 0);
// cap.write(m22, "m22", 1);
// cap.write(m23, "m23", 0);
// cap.write(m30, "m30", 0);
// cap.write(m31, "m31", 0);
// cap.write(m32, "m32", 0);
// cap.write(m33, "m33", 1);
// }
// void read(JmeImporter e) throws IOException {
// InputCapsule cap = e.getCapsule(this);
// m00 = cap.readFloat("m00", 1);
// m01 = cap.readFloat("m01", 0);
// m02 = cap.readFloat("m02", 0);
// m03 = cap.readFloat("m03", 0);
// m10 = cap.readFloat("m10", 0);
// m11 = cap.readFloat("m11", 1);
// m12 = cap.readFloat("m12", 0);
// m13 = cap.readFloat("m13", 0);
// m20 = cap.readFloat("m20", 0);
// m21 = cap.readFloat("m21", 0);
// m22 = cap.readFloat("m22", 1);
// m23 = cap.readFloat("m23", 0);
// m30 = cap.readFloat("m30", 0);
// m31 = cap.readFloat("m31", 0);
// m32 = cap.readFloat("m32", 0);
// m33 = cap.readFloat("m33", 1);
// }
bool ame::Matrix4f::isIdentity() {
return (m00 == 1 && m01 == 0 && m02 == 0 && m03 == 0)
&& (m10 == 0 && m11 == 1 && m12 == 0 && m13 == 0)
&& (m20 == 0 && m21 == 0 && m22 == 1 && m23 == 0)
&& (m30 == 0 && m31 == 0 && m32 == 0 && m33 == 1);
}
void ame::Matrix4f::scale(Vector3f scale) {
m00 *= scale.getX();
m10 *= scale.getX();
m20 *= scale.getX();
m30 *= scale.getX();
m01 *= scale.getY();
m11 *= scale.getY();
m21 *= scale.getY();
m31 *= scale.getY();
m02 *= scale.getZ();
m12 *= scale.getZ();
m22 *= scale.getZ();
m32 *= scale.getZ();
}
bool ame::Matrix4f::equalIdentity(ame::Matrix4f mat) {
if (Math.abs(mat.m00 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m11 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m22 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m33 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m01) > 1e-4) {
return false;
}
if (Math.abs(mat.m02) > 1e-4) {
return false;
}
if (Math.abs(mat.m03) > 1e-4) {
return false;
}
if (Math.abs(mat.m10) > 1e-4) {
return false;
}
if (Math.abs(mat.m12) > 1e-4) {
return false;
}
if (Math.abs(mat.m13) > 1e-4) {
return false;
}
if (Math.abs(mat.m20) > 1e-4) {
return false;
}
if (Math.abs(mat.m21) > 1e-4) {
return false;
}
if (Math.abs(mat.m23) > 1e-4) {
return false;
}
if (Math.abs(mat.m30) > 1e-4) {
return false;
}
if (Math.abs(mat.m31) > 1e-4) {
return false;
}
if (Math.abs(mat.m32) > 1e-4) {
return false;
}
return true;
}
void ame::Matrix4f::multLocal(Quaternion rotation) {
Vector3f axis = new Vector3f();
float angle = rotation.toAngleAxis(axis);
ame::Matrix4f ame::Matrix4f = new ame::Matrix4f();
ame::Matrix4f.fromAngleAxis(angle, axis);
multLocal(ame::Matrix4f);
}
ame::Matrix4f *ame::Matrix4f::clone() {
}
*/
#endif
| 31.944313 | 125 | 0.473109 | PankeyCR |
9344a6ad1befd9f84148b291e984f69434968892 | 8,354 | cpp | C++ | src/hpglopenglparser.cpp | jusirkka/qopencpn | 5e514ae8f43199c4d52278df6e4df85c46bd1ddc | [
"ISC",
"X11",
"MIT"
] | 2 | 2021-07-09T14:13:55.000Z | 2022-02-11T06:41:03.000Z | src/hpglopenglparser.cpp | jusirkka/qopencpn | 5e514ae8f43199c4d52278df6e4df85c46bd1ddc | [
"ISC",
"X11",
"MIT"
] | null | null | null | src/hpglopenglparser.cpp | jusirkka/qopencpn | 5e514ae8f43199c4d52278df6e4df85c46bd1ddc | [
"ISC",
"X11",
"MIT"
] | 2 | 2022-02-11T06:41:05.000Z | 2022-03-17T09:29:46.000Z | /* -*- coding: utf-8-unix -*-
*
* File: src/hpglparser.cpp
*
* Copyright (C) 2021 Jukka Sirkka
*
* 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 "hpglopenglparser.h"
#include <QDebug>
#include <glm/glm.hpp>
#include "triangulator.h"
#include "geomutils.h"
HPGL::OpenGLParser::OpenGLParser(const QString &src, const QString& colors,
const QPointF& pivot)
: Parser(colors)
, m_started(false)
, m_penDown(false)
, m_pivot(pivot)
{
parse(src);
if (!m_ok) {
return;
}
while (m_sketches.size() > 0) {
edgeSketch();
}
edgeSketch();
DataIterator it = m_storage.begin();
while (it != m_storage.end()) {
m_data.append(it.value());
it = m_storage.erase(it);
}
}
void HPGL::OpenGLParser::setColor(char c) {
if (!m_cmap.contains(c)) {
qWarning() << c << "not in colormap";
m_ok = false;
return;
}
const quint32 index = m_cmap[c];
if (!m_started) {
m_started = true;
m_currentSketch.color = S52::Color(index);
m_currentSketch.lineWidth = 0.;
LineString ls;
ls.closed = false;
m_currentSketch.parts.append(ls);
} else if (m_currentSketch.color.index != index) {
Sketch sketch = m_currentSketch.clone();
sketch.color.index = index;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::setAlpha(int a) {
auto alpha = as_enum<S52::Alpha>(a, S52::AllAlphas);
if (m_currentSketch.color.alpha == S52::Alpha::Unset) {
m_currentSketch.color.alpha = alpha;
} else if (m_currentSketch.color.alpha != alpha) {
Sketch sketch = m_currentSketch.clone();
sketch.color.alpha = alpha;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::setWidth(int w) {
const qreal lw = S52::LineWidthMM(w);
if (m_currentSketch.lineWidth == 0.) {
m_currentSketch.lineWidth = lw;
} else if (m_currentSketch.lineWidth != lw) {
Sketch sketch = m_currentSketch.clone();
sketch.lineWidth = lw;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::movePen(const RawPoints &ps) {
if (ps.size() % 2 != 0) {
qWarning() << ps << "contains odd number of coordinates";
m_ok = false;
return;
}
m_pen = makePoint(ps[ps.size() - 2], ps[ps.size() - 1]);
LineString ls;
ls.closed = false;
m_currentSketch.parts.append(ls);
m_penDown = false;
}
void HPGL::OpenGLParser::drawLineString(const RawPoints &ps) {
if (ps.isEmpty()) {
// draw a single point
drawPoint();
m_penDown = true;
return;
}
if (ps.size() % 2 != 0) {
qWarning() << ps << "contains odd number of coordinates";
m_ok = false;
return;
}
if (!m_penDown) {
m_currentSketch.parts.last().points.append(m_pen);
}
for (int i = 0; i < ps.size() / 2; i++) {
m_currentSketch.parts.last().points.append(makePoint(ps[2 * i], ps[2 * i + 1]));
}
m_currentSketch.parts.last().closed =
m_currentSketch.parts.last().points.first() ==
m_currentSketch.parts.last().points.last();
m_pen = m_currentSketch.parts.last().points.last();
m_penDown = true;
}
void HPGL::OpenGLParser::drawPoint() {
pushSketch();
// opaque fill
m_currentSketch.color.alpha = S52::Alpha::P0;
const qreal lw = m_currentSketch.lineWidth == 0. ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const QPointF q = .5 * QPointF(lw, lw);
const QPointF p = .5 * QPointF(lw, -lw);
m_currentSketch.parts.last().closed = true;
m_currentSketch.parts.last().points.append(m_pen - q);
m_currentSketch.parts.last().points.append(m_pen + p);
m_currentSketch.parts.last().points.append(m_pen + q);
m_currentSketch.parts.last().points.append(m_pen - p);
m_currentSketch.parts.last().points.append(m_pen - q);
fillSketch();
}
void HPGL::OpenGLParser::drawCircle(int r0) {
LineString ls;
ls.closed = true;
const qreal lw = m_currentSketch.lineWidth == 0 ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const qreal r = mmUnit * r0;
auto n = qMin(90, 3 + 4 * static_cast<int>(r / lw));
for (int i = 0; i <= n; i++) {
const qreal a = 2 * i * M_PI / n;
const QPointF p = m_pen + QPointF(r * cos(a), r * sin(a));
ls.points.append(p);
}
m_currentSketch.parts.append(ls);
LineString ls2;
ls2.closed = false;
if (m_penDown) {
ls2.points.append(m_pen);
}
m_currentSketch.parts.append(ls2);
}
void HPGL::OpenGLParser::drawArc(int x0, int y0, int a0) {
LineString ls;
ls.closed = false;
const qreal lw = m_currentSketch.lineWidth == 0 ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const QPointF c = makePoint(x0, y0);
const QPointF d = m_pen - c;
const qreal r = sqrt(QPointF::dotProduct(d, d));
const int n = qMin(90., std::ceil((3. + 4 * r / lw) * a0 / 360.));
for (int i = 0; i <= n; i++) {
const qreal a = a0 / 180. * i * M_PI / n;
const qreal ca = cos(a);
const qreal sa = sin(a);
const QPointF p = c + QPointF(ca * d.x() - sa * d.y(), sa * d.x() + ca * d.y());
ls.points.append(p);
}
m_currentSketch.parts.append(ls);
LineString ls2;
ls2.closed = false;
if (m_penDown) {
ls2.points.append(m_pen);
}
m_currentSketch.parts.append(ls2);
}
void HPGL::OpenGLParser::pushSketch() {
Sketch sketch = m_currentSketch.clone();
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
void HPGL::OpenGLParser::endSketch() {
// noop
}
void HPGL::OpenGLParser::fillSketch() {
// triangulate
Data d;
d.color = m_currentSketch.color;
if (d.color.alpha == S52::Alpha::Unset) {
d.color.alpha = S52::Alpha::P0;
}
for (const LineString& part: m_currentSketch.parts) {
if (!part.closed) continue;
if (part.points.size() < 3) continue;
triangulate(part.points, d);
}
// merge storage
if (!d.vertices.isEmpty()) {
if (m_storage.contains(d.color)) {
mergeData(m_storage[d.color], d);
} else {
m_storage.insert(d.color, d);
}
}
// pop sketch
if (!m_sketches.isEmpty()) {
m_currentSketch = m_sketches.pop();
}
}
void HPGL::OpenGLParser::edgeSketch() {
// thicker lines
Data d;
d.color.index = m_currentSketch.color.index;
d.color.alpha = S52::Alpha::P0;
const qreal lw = m_currentSketch.lineWidth == 0. ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
for (const LineString& part: m_currentSketch.parts) {
if (part.points.size() < 2) continue;
thickerlines(part, lw, d);
}
// merge storage
if (!d.vertices.isEmpty()) {
if (m_storage.contains(d.color)) {
mergeData(m_storage[d.color], d);
} else {
m_storage.insert(d.color, d);
}
}
// pop sketch
if (!m_sketches.isEmpty()) {
m_currentSketch = m_sketches.pop();
}
}
void HPGL::OpenGLParser::mergeData(Data &tgt, const Data &d) {
const GLuint offset = tgt.vertices.size() / 2;
tgt.vertices.append(d.vertices);
for (auto index: d.indices) {
tgt.indices << offset + index;
}
}
QPointF HPGL::OpenGLParser::makePoint(int x, int y) const {
return QPointF(x * mmUnit - m_pivot.x(),
m_pivot.y() - y * mmUnit);
}
void HPGL::OpenGLParser::triangulate(const PointList& points, Data& out) {
GL::VertexVector vertices;
for (const QPointF p0: points) {
vertices << p0.x() << p0.y();
}
Triangulator tri(vertices);
tri.addPolygon(0, vertices.size() / 2 - 1);
auto indices = tri.triangulate();
const GLuint offset = out.vertices.size() / 2;
out.vertices.append(vertices);
for (auto index: indices) {
out.indices << offset + index;
}
}
void HPGL::OpenGLParser::thickerlines(const LineString &ls, qreal lw, Data &out) {
thickerLines(ls.points, ls.closed, lw, out.vertices, out.indices);
}
| 26.605096 | 84 | 0.645918 | jusirkka |
9348ac4b6b5ccb7f5f9c9bbb26cafb7bccfa9571 | 692 | cpp | C++ | src/getenv.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | src/getenv.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | src/getenv.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/getenv.hpp>
#include <fcppt/optional_std_string.hpp>
#include <fcppt/config/external_begin.hpp>
#include <cstdlib>
#include <string>
#include <fcppt/config/external_end.hpp>
fcppt::optional_std_string
fcppt::getenv(
std::string const &_val
)
{
char const *const ret{
std::getenv(
_val.c_str()
)
};
return
ret
==
nullptr
?
fcppt::optional_std_string{}
:
fcppt::optional_std_string{
std::string(
ret
)
}
;
}
| 17.3 | 61 | 0.669075 | vinzenz |
934930d25543e1a3a1034663733da437300199c0 | 1,161 | cpp | C++ | 2021.09.08-Lesson-1/Project3/Source.cpp | 021213/programming-c-eng--2021-autumn | 84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348 | [
"Apache-2.0"
] | null | null | null | 2021.09.08-Lesson-1/Project3/Source.cpp | 021213/programming-c-eng--2021-autumn | 84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348 | [
"Apache-2.0"
] | null | null | null | 2021.09.08-Lesson-1/Project3/Source.cpp | 021213/programming-c-eng--2021-autumn | 84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int a = 3;
int b = 5;
int c = 0;
c = a + b;
c = a - b;
c = a * b;
c = a / b;
c = a % b;
a += b;
a *= b;
a /= b; // a = a / b;
a %= b; // a = a / b;
a -= b; // a = a - b;
float f = 0;
a = 5;
b = 2;
f = a / b; // 2.0
f = (float)a / b;
f = 1.0f * a / b;
c = a | b;
c = a & b;
c = a ^ b;
cout << a << " " << b << endl;
a ^= b ^= a ^= b;
cout << a << " " << b << "\n";
a = 7; // 0000 0111
a = a << 2; // 0001 1100
cout << a << endl;
a = 7; // 0000 0111
a = a >> 1; // 0000 0011
cout << a << endl;
a++;
++a;
a--;
--a;
a = 7;
// 7 + 9 + 10 + 10
a = a++ + ++a + ++a + a++;
cout << a << endl; //38
a = 7;
a = ~a; // -8
a = 9;
a = ~a; // -10
// 1 1111 111
// 9 = 0000 1001
// -9 = 1111 0111
//9-9 = 1 0000 0000
// 9 = 0000 1001
// ~9 = 1111 0110 == -10
// ~9+1 = 1111 0111 == -9
bool bA = true;
bool bB = true;
bool bC = true;
bC = bA && bB;
bC = bA || bB;
bC = bA ^ bB;
bC = bA == bB;
bC = !bA;
a = 10;
b = 19;
c = (a > b ? a : b);
if (a > b)
{
c = a;
}
else
{
c = b;
}
return EXIT_SUCCESS;
} | 12.619565 | 31 | 0.356589 | 021213 |
934c600d122f6a3511d7502524cfc3b75b81f64c | 1,039 | cpp | C++ | IA/C++/7.4/3.cpp | worthl3ss/random-small | ffb60781f57eb865acbd81aaa07056046bad32fe | [
"MIT"
] | 1 | 2022-02-23T12:47:00.000Z | 2022-02-23T12:47:00.000Z | IA/C++/7.4/3.cpp | worthl3ss/random-small | ffb60781f57eb865acbd81aaa07056046bad32fe | [
"MIT"
] | null | null | null | IA/C++/7.4/3.cpp | worthl3ss/random-small | ffb60781f57eb865acbd81aaa07056046bad32fe | [
"MIT"
] | null | null | null | #include <iostream>
class NrComplex{
public:
NrComplex(int real, int imaginar) : re(real), im(imaginar) { instante++; }
NrComplex() {}
//aparent nu
//~NrComplex() { instante--; }
static NrComplex Adunare(NrComplex& a, NrComplex& b) {
return NrComplex(a.re+b.re,a.im+b.im);
}
void Afisare() {
im<0 ? std::cout << re << im << "i\n" : std::cout << re << "+" << im << "i\n";
}
static void AfisareNrInstante();
friend NrComplex Inmultire(NrComplex& a, NrComplex& b);
private:
int re, im;
static int instante;
};
int NrComplex::instante = 1;
void NrComplex::AfisareNrInstante() {
std::cout << instante << "\n";
}
NrComplex Inmultire(NrComplex &a, NrComplex &b) {
return NrComplex(a.re*b.re-a.im*b.im,a.re*b.im+a.im*b.re);
}
void Citire(NrComplex& nr) {
int r,c;
std::cin >> r >> c;
nr = NrComplex(r,c);
}
//(a1a2-b1b2)+(a1b2+a2b1)i
int main(){
NrComplex a,b;
Citire(a);
Citire(b);
NrComplex c = Inmultire(a,b);
c.Afisare();
}
| 18.890909 | 86 | 0.578441 | worthl3ss |
934e5aef93fda065b64434dfaa69269c0db2d171 | 16,781 | cpp | C++ | iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp | River707/iree | 09b7742466ce7fb48742fd900e6c1f66cf51d3f3 | [
"Apache-2.0"
] | 1 | 2020-08-16T17:38:25.000Z | 2020-08-16T17:38:25.000Z | iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp | georgemitenkov/iree | 77d2f8b4fd53f1dbe7ef03b4b4a7ba7be06f2416 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp | georgemitenkov/iree | 77d2f8b4fd53f1dbe7ef03b4b4a7ba7be06f2416 | [
"Apache-2.0"
] | 1 | 2021-01-29T09:30:09.000Z | 2021-01-29T09:30:09.000Z | // Copyright 2020 Google LLC
//
// 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
//
// https://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.
//===- LinalgTilingOnBuffers.cpp - Tile and fuse Linalg on Buffers --------===//
//
// Implements a pass to tile and fuse linalg operations on buffers.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/Conversion/LinalgToSPIRV/Attributes.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/MarkerUtils.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/MemorySpace.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/Passes.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/Utils.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/Linalg/Utils/Utils.h"
#include "mlir/Dialect/SPIRV/SPIRVOps.h"
#include "mlir/Dialect/SPIRV/TargetAndABI.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Identifier.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/FoldUtils.h"
#define DEBUG_TYPE "iree-linalg-tile-and-fuse-buffer"
static std::string PromotionMarker = "promotion";
namespace mlir {
namespace iree_compiler {
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
static ArrayRef<int64_t> dropTrailingOnes(ArrayRef<int64_t> vector) {
if (vector.empty()) return vector;
auto numTrailingOnes = 0;
for (unsigned i = vector.size() - 1; i > 0; --i) {
if (vector[i] != 1) {
break;
}
numTrailingOnes++;
}
return vector.drop_back(numTrailingOnes);
}
/// Returns true if the linalg op has padding attribute, and that it has
/// non-zero entries.
template <typename OpTy>
static bool hasPadding(OpTy op) {
Optional<DenseIntElementsAttr> padding = op.padding();
if (!padding) return false;
return llvm::any_of(padding.getValue(),
[](APInt v) -> bool { return !v.isNullValue(); });
}
namespace {
/// Computes tile sizes (and workgroup size) to use based on operations within
/// the function, and resource constraints on the module.
class TileSizeCalculator {
public:
TileSizeCalculator(FuncOp funcOp)
: resourceLimits(spirv::lookupTargetEnv(funcOp).getResourceLimits()) {
if (DenseIntElementsAttr attr = spirv::lookupLocalWorkGroupSize(funcOp)) {
for (auto val : attr.getValues<APInt>())
workgroupSize.push_back(val.getSExtValue());
}
workgroupSize.resize(3, 1);
}
/// Compute the tile sizes based on workgroup size specified.
LogicalResult setTileSizesBasedOnWorkgroupSize(
ArrayRef<int64_t> vWorkGroupSize) {
if (!vWorkGroupSize.empty()) {
vWorkGroupSize = dropTrailingOnes(vWorkGroupSize);
workgroupSize.assign(vWorkGroupSize.begin(), vWorkGroupSize.end());
auto rev = reverse(workgroupSize);
tileSizes.assign(rev.begin(), rev.end());
}
return success();
}
/// Compute the tile sizes based on the Linalg Ops within the dispatch region.
LogicalResult setTileSizesBasedOnOps(ArrayRef<linalg::LinalgOp> linalgOps);
/// Get the current tile size computed.
ArrayRef<int64_t> getTileSizes() const { return tileSizes; }
/// Returns the workgroup size to use based on the tile sizes.
ArrayRef<int64_t> getWorkGroupSize() const { return workgroupSize; }
private:
/// Current tile size configuration.
SmallVector<int64_t, 4> tileSizes;
/// Workgroup size to use.
SmallVector<int64_t, 3> workgroupSize;
/// Attribute for device constraints.
spirv::ResourceLimitsAttr resourceLimits;
};
} // namespace
LogicalResult TileSizeCalculator::setTileSizesBasedOnOps(
ArrayRef<linalg::LinalgOp> linalgOps) {
tileSizes.clear();
if (linalgOps.empty()) {
tileSizes = {1, 1, 1};
workgroupSize = {1, 1, 1};
return success();
}
// The tile size will be driven by operations like matmul, conv, etc. within
// the list. So see what operation exists in the list to decide the tile size.
// If there are two such operations in the list, return error.
enum OpInfo : uint32_t {
None = 0x0,
Convolution = 0x1,
Matmul = 0x2,
Pooling = 0x4,
};
uint32_t opInfo = OpInfo::None;
for (linalg::LinalgOp linalgOp : linalgOps) {
Operation *op = linalgOp.getOperation();
if (isa<linalg::ConvOp>(op)) opInfo |= OpInfo::Convolution;
if (isa<linalg::MatmulOp>(op)) opInfo |= OpInfo::Matmul;
if (isa<linalg::PoolingMaxOp>(op)) opInfo |= OpInfo::Pooling;
if (isa<linalg::PoolingMinOp>(op)) opInfo |= OpInfo::Pooling;
if (isa<linalg::PoolingSumOp>(op)) opInfo |= OpInfo::Pooling;
}
// If there are no tilable ops, there is nothing to do here.
if (!opInfo) return success();
Operation *linalgOp = *(linalgOps.begin());
if (llvm::countPopulation(opInfo) != 1)
return linalgOp->getParentOfType<FuncOp>().emitError(
"unhandled fusion of ops in dispatch function");
// TODO(ravishanarm, antiagainst): Only the maximum workgroup size is used
// here for computing tile sizes. In reality we also need the maximum
// workgroup memory size available (per workgroup) to compute the tile sizes
// effectively.
unsigned maxWorkgroupSize =
resourceLimits.max_compute_workgroup_invocations().getInt();
if (opInfo & OpInfo::Convolution) {
// TODO(ravishankarm): This tiling is meant to enable promotion to workgroup
// memory, but doesnt actually get us to a state where we can do this. The
// promotion is possible only when the subviews created are constant
// size. For now this doesnt really matter. Revisit this later.
int64_t tileSizeX = 32;
int64_t tileSizeY = maxWorkgroupSize / 32;
tileSizes = {1, tileSizeY, tileSizeX};
workgroupSize = {tileSizeX, tileSizeY, 1};
return success();
}
if (opInfo & OpInfo::Matmul) {
// TODO: For now just hard wire this, but we can do better.
tileSizes = {8, 8, 4};
workgroupSize = {8, 8, 1};
return success();
}
if (opInfo & OpInfo::Pooling) {
int64_t tileSizeX = 32;
int64_t tileSizeY = maxWorkgroupSize / 32;
tileSizes = {tileSizeY, tileSizeX};
workgroupSize = {tileSizeX, tileSizeY, 1};
return success();
}
return linalgOp->getParentOfType<FuncOp>().emitError(
"unable to find tile size for ops in this dispatch function");
}
//===----------------------------------------------------------------------===//
// Pass and patterns
//===----------------------------------------------------------------------===//
/// Allocation callback for allocation workgroup local memory.
static Value allocateWorkgroupMemory(OpBuilder &b, SubViewOp subview,
ArrayRef<Value> boundingSubViewSize,
OperationFolder *folder) {
// The bounding subview size is expected to be constant. This specified the
// shape of the allocation.
SmallVector<int64_t, 2> shape(boundingSubViewSize.size(),
ShapedType::kDynamicSize);
return b.create<AllocOp>(
subview.getLoc(),
MemRefType::get(shape, subview.getType().getElementType(), {},
getWorkgroupMemorySpace()),
boundingSubViewSize);
}
/// Deallocation callback for allocation workgroup local memory.
static LogicalResult deallocateWorkgroupMemory(OpBuilder &b, Value buffer) {
auto allocOp = buffer.getDefiningOp<AllocOp>();
b.create<DeallocOp>(allocOp.getLoc(), buffer);
return success();
}
/// Insert barrier after `op`.
static void insertBarrierAfter(OpBuilder &b, Location loc, Operation *op) {
OpBuilder::InsertionGuard guard(b);
b.setInsertionPointAfter(op);
b.create<spirv::ControlBarrierOp>(loc, spirv::Scope::Workgroup,
spirv::Scope::Workgroup,
spirv::MemorySemantics::AcquireRelease);
}
/// Function used as callback for copyin/copyout in promotion pattern used to
/// promote subviews to workgroup memory.
static LogicalResult copyToFromWorkgroupMemory(
OpBuilder &b, Value src, Value dst, StringRef marker = PromotionMarker) {
auto copyOp = b.create<linalg::CopyOp>(src.getLoc(), src, dst);
setMarker(copyOp, marker);
return success();
}
namespace {
/// Function pass that implements tiling and fusion in Linalg on buffers.
struct LinalgTileAndFusePass
: public PassWrapper<LinalgTileAndFusePass, FunctionPass> {
LinalgTileAndFusePass(ArrayRef<int64_t> workGroupSize = {},
bool useWorkgroupMem = false)
: workGroupSize(workGroupSize.begin(), workGroupSize.end()) {
this->useWorkgroupMemory = useWorkgroupMem;
}
LinalgTileAndFusePass(const LinalgTileAndFusePass &pass) {}
void runOnFunction() override;
Option<bool> useWorkgroupMemory{
*this, "use-workgroup-memory",
llvm::cl::desc("Promote subviews to use workgroup memory"),
llvm::cl::init(false)};
private:
SmallVector<int64_t, 3> workGroupSize;
};
/// Pattern for tiling operations. Updates the workgroup size in the surrounding
/// function operation if tiling succeeds.
template <typename OpTy>
struct TilingPattern : public linalg::LinalgTilingPattern<OpTy> {
using Base = linalg::LinalgTilingPattern<OpTy>;
TilingPattern(MLIRContext *context, linalg::LinalgTilingOptions options,
ArrayRef<int64_t> workgroupSize,
linalg::LinalgMarker marker = linalg::LinalgMarker(),
PatternBenefit benefit = 1)
: Base(context, options, marker, benefit),
workgroupSize(workgroupSize.begin(), workgroupSize.end()) {}
virtual LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const {
// Find the parent FuncOp before tiling. If tiling succeeds, the op will be
// erased.
FuncOp funcOp = op->getParentOfType<FuncOp>();
if (!funcOp || failed(Base::matchAndRewrite(op, rewriter)) ||
failed(updateWorkGroupSize(funcOp, workgroupSize)))
return failure();
funcOp.setAttr(getWorkgroupCountAttrName(),
rewriter.getI32IntegerAttr(static_cast<int32_t>(
WorkgroupCountMethodology::ResultShape)));
return success();
}
SmallVector<int64_t, 3> workgroupSize;
};
/// Pattern for tiling convolution and pooling operations. Currently is just a
/// way to not tile when the operation has padding.
template <typename OpTy>
struct TileConvPoolPattern : public TilingPattern<OpTy> {
using Base = TilingPattern<OpTy>;
using Base::TilingPattern;
LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
if (hasPadding(cast<OpTy>(op))) return failure();
FuncOp funcOp = op->getParentOfType<FuncOp>();
if (!funcOp || failed(Base::matchAndRewrite(op, rewriter)) ||
failed(updateWorkGroupSize(funcOp, this->workgroupSize)))
return failure();
funcOp.setAttr(getWorkgroupCountAttrName(),
rewriter.getI32IntegerAttr(static_cast<int32_t>(
WorkgroupCountMethodology::Default)));
return success();
}
};
/// Pattern to promote subviews to memory.
// TODO(ravishankarm): Generalize this for other operations.
struct PromoteSubviewsPattern
: public linalg::LinalgPromotionPattern<linalg::MatmulOp> {
PromoteSubviewsPattern(MLIRContext *context,
linalg::LinalgPromotionOptions options,
linalg::LinalgMarker marker = linalg::LinalgMarker(),
PatternBenefit benefit = 1)
: linalg::LinalgPromotionPattern<linalg::MatmulOp>(
context,
options.setOperandsToPromote({0, 1}).setUseFullTileBuffers(
{false, false}),
marker, benefit) {}
LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
if (!hasWorkGroupMarker(op)) return failure();
return linalg::LinalgPromotionPattern<linalg::MatmulOp>::matchAndRewrite(
op, rewriter);
}
};
} // namespace
void LinalgTileAndFusePass::runOnFunction() {
MLIRContext *context = &getContext();
FuncOp funcOp = getFunction();
Region &body = funcOp.getBody();
if (!llvm::hasSingleElement(body.getBlocks())) {
funcOp.emitError("unhandled dispatch function with multiple blocks");
return signalPassFailure();
}
Block &block = body.front();
auto linalgOps = block.getOps<linalg::LinalgOp>();
if (linalgOps.empty()) return;
TileSizeCalculator tileSizeCalculator(funcOp);
if (workGroupSize.empty()) {
// Get the tile sizes to use for the lowering.
SmallVector<int64_t, 3> tileSizes;
SmallVector<linalg::LinalgOp, 1> opsVec(linalgOps.begin(), linalgOps.end());
if (failed(tileSizeCalculator.setTileSizesBasedOnOps(opsVec)))
return signalPassFailure();
} else {
tileSizeCalculator.setTileSizesBasedOnWorkgroupSize(workGroupSize);
}
LLVM_DEBUG({
llvm::dbgs() << "--- IREE Linalg tile and fuse configuration ---\n";
llvm::dbgs() << "# workgroup sizes at start: [";
interleaveComma(workGroupSize, llvm::dbgs());
llvm::dbgs() << "]\ntile sizes: [";
interleaveComma(tileSizeCalculator.getTileSizes(), llvm::dbgs());
llvm::dbgs() << "]\n";
});
OwningRewritePatternList tilingPatterns;
tilingPatterns.insert<TileConvPoolPattern<linalg::ConvOp>,
TilingPattern<linalg::MatmulOp>,
TileConvPoolPattern<linalg::PoolingMaxOp>,
TileConvPoolPattern<linalg::PoolingMinOp>,
TileConvPoolPattern<linalg::PoolingSumOp>>(
context,
linalg::LinalgTilingOptions()
.setTileSizes(tileSizeCalculator.getTileSizes())
.setLoopType(linalg::LinalgTilingLoopType::ParallelLoops),
tileSizeCalculator.getWorkGroupSize(),
linalg::LinalgMarker(ArrayRef<Identifier>(),
Identifier::get(getWorkGroupMarker(), context)));
applyPatternsAndFoldGreedily(getOperation(), tilingPatterns);
if (useWorkgroupMemory) {
// The promotion patterns are put separate from the tiling patterns to make
// sure that the allocated scratchspace memory is constant sizes which
// requires some folding to trigger.
OwningRewritePatternList promotionPatterns;
promotionPatterns.insert<PromoteSubviewsPattern>(
context,
linalg::LinalgPromotionOptions()
.setAllocationDeallocationFns(allocateWorkgroupMemory,
deallocateWorkgroupMemory)
.setCopyInOutFns(
[&](OpBuilder &b, Value src, Value dst) -> LogicalResult {
return copyToFromWorkgroupMemory(b, src, dst);
},
[&](OpBuilder &b, Value src, Value dst) -> LogicalResult {
return copyToFromWorkgroupMemory(b, src, dst);
}),
linalg::LinalgMarker(Identifier::get(getWorkGroupMarker(), context),
Identifier::get(PromotionMarker, context)));
applyPatternsAndFoldGreedily(getOperation(), promotionPatterns);
}
// Add barrier after all linalg operations marked with workitem marker.
OpBuilder builder(context);
funcOp.walk([&builder](linalg::LinalgOp linalgOp) {
if (hasMarker(linalgOp, PromotionMarker)) {
setWorkGroupMarker(linalgOp);
insertBarrierAfter(builder, linalgOp.getLoc(), linalgOp);
}
});
}
//===----------------------------------------------------------------------===//
// Pass entry point and registration
//===----------------------------------------------------------------------===//
std::unique_ptr<OperationPass<FuncOp>> createLinalgTileAndFusePass(
ArrayRef<int64_t> workGroupSize, bool useWorkgroupMemory) {
return std::make_unique<LinalgTileAndFusePass>(workGroupSize,
useWorkgroupMemory);
}
static PassRegistration<LinalgTileAndFusePass> pass(
"iree-codegen-linalg-tile-and-fuse",
"Tile and fuse Linalg operations on buffers",
[] { return std::make_unique<LinalgTileAndFusePass>(); });
} // namespace iree_compiler
} // namespace mlir
| 39.954762 | 80 | 0.663012 | River707 |
9350f8ba18aa434405f0b4cf415cf2e97241f204 | 152 | hpp | C++ | src/tokenizer.hpp | sischkg/nxnsattack | c20896e40187bbcacb5c0255ff8f3cc7d0592126 | [
"MIT"
] | 5 | 2020-05-22T10:01:51.000Z | 2022-01-01T04:45:14.000Z | src/tokenizer.hpp | sischkg/dns-fuzz-server | 6f45079014e745537c2f564fdad069974e727da1 | [
"MIT"
] | 1 | 2020-06-07T14:09:44.000Z | 2020-06-07T14:09:44.000Z | src/tokenizer.hpp | sischkg/dns-fuzz-server | 6f45079014e745537c2f564fdad069974e727da1 | [
"MIT"
] | 2 | 2020-03-10T03:06:20.000Z | 2021-07-25T15:07:45.000Z | #ifndef TOKENIZER_HPP
#define TOKENIZER_HPP
#include <string>
#include <vector>
std::vector<std::string> tokenize( const std::string &line );
#endif
| 15.2 | 61 | 0.743421 | sischkg |
93512b9e6cb0fef8ac747c2a714e04b563eddf0b | 1,569 | cpp | C++ | src/graphics/texture.cpp | luihabl/tinysdl | 5159577b4d7dd58d42df4f6790fabcd86e78491b | [
"MIT"
] | 2 | 2021-09-10T20:34:55.000Z | 2021-11-27T11:25:23.000Z | src/graphics/texture.cpp | luihabl/tinysdl | 5159577b4d7dd58d42df4f6790fabcd86e78491b | [
"MIT"
] | 1 | 2021-10-21T19:23:23.000Z | 2021-10-21T21:25:29.000Z | src/graphics/texture.cpp | luihabl/tinysdl | 5159577b4d7dd58d42df4f6790fabcd86e78491b | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include "tinysdl/graphics/texture.h"
#include "tinysdl/platform/log.h"
#include "tinysdl/platform/file.h"
using namespace TinySDL;
Image::Image(const char * path) {
this->data = File::load_image(path, &this->w, &this->h, &this->n_comp);
if(!data) Log::error("File does not exist: %s", path);
}
Image::~Image() {
if(data) free_image_data();
}
void Image::free_image_data() {
File::free_image(data);
data = nullptr;
}
void Texture::bind() const {
glBindTexture(GL_TEXTURE_2D, this->id);
}
Texture::Texture(int w, int h, int n_comp, unsigned char * data) : w(w), h(h){
glGenTextures(1, &this->id);
glBindTexture(GL_TEXTURE_2D, this->id);
GLint format = n_comp == 3 ? GL_RGB : GL_RGBA;
glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, data);
full_rect = {0, 0, (float) w, (float) h};
// add a way to set these parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture Texture::from_sprite(Image * spr) {
return Texture(spr->w, spr->h, spr->n_comp, spr->data);
}
Texture Texture::from_file(const char * path) {
Image spr(path);
return Texture(spr.w, spr.h, spr.n_comp, spr.data);
}
Texture Texture::empty(int w, int h) {
return Texture(w, h, 4, NULL);
} | 27.051724 | 84 | 0.684512 | luihabl |
9351f495baae43d2bac2e71d00a05116e4ae57f3 | 1,972 | cpp | C++ | src/main/_2018/day11.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | src/main/_2018/day11.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | 6 | 2018-12-03T04:43:00.000Z | 2020-12-12T12:42:02.000Z | src/main/_2018/day11.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include "../util/helpers.cpp"
using namespace std;
// http://adventofcode.com/2018/day/11
int get_power(int x, int y, int grid_serial_number) {
int rack = x + 10;
int power = rack * y;
power += grid_serial_number;
power *= rack;
int hundreds = (power / 100) % 10;
return hundreds - 5;
}
// No output value
// Manually determine the correct output
string solve(int input, bool part_two) {
// build 2d partial sums
// row and column 0 are blank
// remember to offset when doing calculations
vector<vector<long>> grid(301, vector<long>(301, 0));
for (size_t i = 1; i < grid.size(); i++) {
for (size_t j = 1; j < grid.size(); j++) {
int power = get_power(j-1, i-1, input);
grid[i][j] = power + grid[i][j-1] + grid[i-1][j] - grid[i-1][j-1];
}
}
long max_power = numeric_limits<long>::min();
size_t max_power_size = 1;
pair<size_t, size_t> coords;
size_t start = (part_two ? 1 : 3);
size_t end = (part_two ? grid.size()-1 : 3);
for (size_t size = start; size <= end; size++) {
for (size_t i = 0; i < grid.size() - size; i++) {
for (size_t j = 0; j < grid[i].size() - size; j++) {
long sum = grid[i][j] - grid[i][j+size] - grid[i+size][j] + grid[i+size][j+size];
if (sum > max_power) {
max_power = sum;
max_power_size = size;
coords = make_pair(j , i);
}
}
}
}
stringstream ss;
ss << coords.first << "," << coords.second;
if (part_two) {
ss << "," << max_power_size;
}
return ss.str();
}
int main() {
int input;
cin >> input;
assert(get_power(3, 5, 8) == 4);
assert(get_power(122, 79, 57) == -5);
assert(get_power(217, 196, 39) == 0);
assert(get_power(101, 153, 71) == 4);
// part 1
assert(solve(18, false) == "33,45");
assert(solve(42, false) == "21,61");
// part 2
assert(solve(18, true) == "90,269,16");
assert(solve(42, true) == "232,251,12");
cout << "Part 1: " << solve(input, false) << endl;
cout << "Part 2: " << solve(input, true) << endl;
}
| 24.345679 | 85 | 0.590771 | Namdrib |
9355019fd7bcf514e4ac35bbedb784badb1fad57 | 4,892 | cpp | C++ | examples/project3/src/rrt.cpp | harsha336/rrt_sig | 1afa8ad45562f20850360d691c2cc29faf18565b | [
"Apache-2.0"
] | null | null | null | examples/project3/src/rrt.cpp | harsha336/rrt_sig | 1afa8ad45562f20850360d691c2cc29faf18565b | [
"Apache-2.0"
] | null | null | null | examples/project3/src/rrt.cpp | harsha336/rrt_sig | 1afa8ad45562f20850360d691c2cc29faf18565b | [
"Apache-2.0"
] | null | null | null | #include "rrt.h"
RRTGraph::RRTGraph()
{
walls_ = new Walls;
alpha_ = 1;
maxi_ = 3000;
}
void RRTGraph::init(GsPnt2 start, float rt, float win_w, float win_h, GsMat *pos)
{
gsout << "RRTGraph::init: Got the matrix: " << gsnl;
position_ = pos;
root_ = new Node;
path_computed_ = false;
root_->parent = NULL;
root_->p = start;
last_node_ = root_;
nodes_.push_back(root_);
win_width_ = win_w;
win_height_ = win_h;
reach_thresh_ = rt;
new_goal_ = true;
robo_= new Robot;
robo_->pos = GsVec(start.x, start.y, 0);
robo_->m = 2.0f;
robo_->vel = GsVec2(0.0f,0.0f);
robo_->max_force = 2.0f;
robo_->max_speed = 0.1f;
robo_->steer_dir = GsVec(0.0f, 0.0f, 0.0f);
}
Node* RRTGraph::getRandomNode()
{
float x = rand() % 201 + (-100);
float y = rand() % 201 + (-100);
pnt p(x,y);
Node *ret;
//gsout << "Getting random node: " << p << gsnl;
if(x >= -100 && x <= 100 && y >= -100 && y <= 100)
{
ret = new Node;
ret->p = p;
return ret;
}
return NULL;
}
Node* RRTGraph::nearestPoint(pnt p)
{
float minDist = 1e9;
Node* nearest = NULL;
for(int i=0; i<nodes_.size(); i++)
{
float d = dist(p,nodes_[i]->p);
if(d < minDist)
{
minDist = d;
nearest = nodes_[i];
}
}
return nearest;
}
pnt RRTGraph::findConfig(Node *c, Node *c_near)
{
pnt to = c->p;
pnt from = c_near->p;
pnt inter = to - from;
inter = inter / inter.norm();
pnt ai(alpha_*inter.x, alpha_*inter.y);
pnt ret = from + ai;
return ret;
}
void RRTGraph::addConfig(Node *c_near, Node *c_new)
{
c_new->parent = c_near;
c_near->children.push_back(c_new);
nodes_.push_back(c_new);
last_node_ = c_new;
}
bool RRTGraph::reached()
{
if(dist(last_node_->p, goal_) < reach_thresh_)
{
gsout << "Goal reached" << gsnl;
return true;
}
return false;
}
void RRTGraph::performRRT(SnLines *pl, SnLines *gl)
{
while(!new_goal_);
for(int i=0; i<maxi_; i++)
{
Node *c = getRandomNode();
if(c)
{
Node *c_near = nearestPoint(c->p);
if(dist(c->p, c_near->p) > alpha_)
{
pnt new_config = findConfig(c, c_near);
if(walls_->queryIntersection(new_config, c_near->p))
{
Node *c_new = new Node;
c_new->p = new_config;
pl->push(c_new->p.x, c_new->p.y, 0.0f);
addConfig(c_near, c_new);
}
}
}
if(reached())
{
break;
}
}
Node *c;
if(reached())
c = last_node_;
else
c = nearestPoint(goal_);
while(c != NULL)
{
path_.push_back(c);
gl->push(c->p.x, c->p.y, 0.0f);
gsout << "Path of the goal: " << c->p << gsnl;
c = c->parent;
}
if(c != NULL)
{
new_goal_ = false;
path_computed_ = true;
}
gsout << "Start: " << root_->p << " goal: " << goal_ << gsnl;
}
std::vector<pnt> RRTGraph::getNodePoints()
{
std::vector<pnt> ret;
for(int i = 0;i < nodes_.size();i++)
ret.push_back(nodes_[i]->p);
return ret;
}
std::vector<pnt> RRTGraph::getPathPoints()
{
std::vector<pnt> ret;
for(int i = 0;i < path_.size();i++)
ret.push_back(path_[i]->p);
return ret;
}
void RRTGraph::eulerIntegration()
{
gsout << "RRTGraph::eulerIntegration: " << robo_->pos << " to " <<
goal_ << gsnl;
while(!path_computed_);
for(int i=0;i<path_.size();i++)
{
GsVec cur_g(path_[i]->p.x,path_[i]->p.y,0.0f);
gsout << "Traversing intermidiate path: " << cur_g << gsnl;
while(::dist(robo_->pos,cur_g) > 0.5)
{
gsout << "++++++++++++++++++++++++++++++++++++++++" << gsnl;
gsout << "RRTGraph::eulerIntegration: Distance to goal: " << cur_g <<
" is " << ::dist(robo_->pos,cur_g) << gsnl;
steering(cur_g);
GsVec steering_force = truncate(robo_->steer_dir, robo_->max_force);
gsout << "Steering force: " << steering_force << gsnl;
GsVec a = steering_force/robo_->m;
robo_->vel = truncate(robo_->vel + a, robo_->max_speed);
gsout << "Velocity: " << robo_->vel << gsnl;
robo_->pos = robo_->pos + robo_->vel;
gsout << "Robot position: " << robo_->pos << gsnl;
position_->setrans(robo_->pos);
gsout << "++++++++++++++++++++++++++++++++++++++++++" << gsnl;
}
}
path_.clear();
path_computed_ = false;
}
GsVec RRTGraph::truncate(GsVec v, float t)
{
gsout << "RRTGraph::truncate: v: " << v << "clip: " << t << gsnl;
GsVec ret;
ret.x = v.x>t?t:v.x;
ret.y = v.y>t?t:v.y;
ret.z = v.z>t?t:v.z;
}
void RRTGraph::steering( GsVec g)
{
gsout << "--------------------------" << gsnl;
GsVec target_offset = g - robo_->pos;
float distance = magnitude(target_offset);
gsout << "Magnitude: " << distance << gsnl;
float ramped_speed = robo_->max_speed * (distance/slowing_distance);
float clipped_speed = std::min(ramped_speed, robo_->max_speed);
gsout << "Clipped speed: " << clipped_speed << gsnl;
GsVec desired_vel = (clipped_speed/distance)*target_offset;
gsout << "Desired velocity: " << desired_vel << gsnl;
robo_->steer_dir = desired_vel - robo_->vel;
gsout << "RRTGraph::steering: " << robo_->steer_dir << gsnl;
gsout << "----------------------------" << gsnl;
}
| 23.295238 | 81 | 0.591578 | harsha336 |
935927654a534a8a0ca4c10ca582ee2d59074ad8 | 3,520 | cpp | C++ | ScriptingProject/Item_Timer.cpp | CITMProject3/Project3 | 5076dbaf4eced4eb69bb43b811684206e62eded4 | [
"MIT"
] | 3 | 2017-04-02T19:37:52.000Z | 2018-11-06T13:37:33.000Z | ScriptingProject/Item_Timer.cpp | CITMProject3/Project3 | 5076dbaf4eced4eb69bb43b811684206e62eded4 | [
"MIT"
] | 74 | 2017-04-03T14:32:09.000Z | 2017-06-08T10:12:56.000Z | ScriptingProject/Item_Timer.cpp | CITMProject3/Project3 | 5076dbaf4eced4eb69bb43b811684206e62eded4 | [
"MIT"
] | 3 | 2017-06-06T17:10:46.000Z | 2019-10-28T16:25:27.000Z | #include "stdafx.h"
#include <string>
#include <map>
#include "../ModuleScripting.h"
#include "../GameObject.h"
#include "../ComponentScript.h"
#include "../ComponentCollider.h"
#include "../ComponentCar.h"
#include "../ComponentMesh.h"
#include "../ComponentAudioSource.h"
#include "../ComponentParticleSystem.h"
#include "../Time.h"
#include "../Globals.h"
#include "../PhysBody3D.h"
bool isHitodama = false;
float timer = 0.0f;
float max_time = 0.0f;
ComponentCollider* go_col = nullptr;
ComponentMesh* go_mesh = nullptr;
ComponentParticleSystem* go_part = nullptr;
ComponentAudioSource* audio_source = nullptr;
bool taken = false;
void Item_Timer_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
{
public_float->insert(pair<const char*, float>("max_time",max_time));
public_bools->insert(pair<const char*, bool>("isHitodama", isHitodama));
public_bools->insert(pair<const char*, bool>("taken", taken));
}
void Item_Timer_UpdatePublics(GameObject* game_object)
{
ComponentScript* script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
go_col = (ComponentCollider*)game_object->GetComponent(C_COLLIDER);
go_part = (ComponentParticleSystem*)game_object->GetComponent(C_PARTICLE_SYSTEM);
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
isHitodama = script->public_bools.at("isHitodama");
taken = script->public_bools.at("taken");
max_time = script->public_floats.at("max_time");
}
void Item_Timer_ActualizePublics(GameObject* game_object)
{
ComponentScript* script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
script->public_bools.at("taken") = taken;
}
void Item_Timer_Start(GameObject* game_object)
{
go_col = (ComponentCollider*)game_object->GetComponent(C_COLLIDER);
if (isHitodama)
{
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
}
else
{
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
}
taken = false;
audio_source = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
}
void Item_Timer_Update(GameObject* game_object)
{
Item_Timer_UpdatePublics(game_object);
if (taken)
{
if (isHitodama)
{
timer += time->DeltaTime();
if (timer >= max_time)
{
go_col->SetActive(true);
//Particle sytem here no mesh
go_mesh->SetActive(true);
taken = false;
timer = 0.0f;
}
}
else
{
timer += time->DeltaTime();
if (timer >= max_time)
{
go_col->SetActive(true);
go_mesh->SetActive(true);
taken = false;
timer = 0.0f;
}
}
}
}
void Item_Timer_OnCollision(GameObject* game_object, PhysBody3D* col)
{
ComponentCar* car = col->GetCar();
ComponentTransform* trs = (ComponentTransform*)game_object->GetComponent(C_TRANSFORM);
if (car && trs && taken == false)
{
Item_Timer_UpdatePublics(game_object);
if (go_col->IsActive())
{
if (isHitodama)
{
taken = car->AddHitodama();
if (taken)
{
go_col->SetActive(false);
//Particle sytem here no mesh
go_mesh->SetActive(false);
// Playing Hitodama sound
if (audio_source) audio_source->PlayAudio(0);
}
}
else
{
taken = true;
//Pep do your magic
if (taken)
{
go_col->SetActive(false);
go_mesh->SetActive(false);
// Playing ItemBox sound
if (audio_source) audio_source->PlayAudio(0);
}
}
}
}
} | 26.074074 | 222 | 0.70483 | CITMProject3 |
935a367f373c8b72d2d75dee4d2023c3bda40867 | 7,702 | cpp | C++ | test/map/HashMapProbingTest.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | test/map/HashMapProbingTest.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | test/map/HashMapProbingTest.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
#include <map/HashMapProbing.h>
#include <map/HashMapTree.h>
#include <test/gcstruct.h>
template <typename MAP>
static void
test_simple(MAP &map) {
using TK = typename MAP::key_type;
using TV = typename MAP::value_type;
const std::size_t c_key_one = 1;
std::size_t key_one = 1;
const TK c_tt_one(1);
TK tt_one(1);
{
ASSERT_FALSE(lookup(map, 1));
ASSERT_FALSE(lookup(map, c_key_one));
ASSERT_FALSE(lookup(map, key_one));
ASSERT_EQ(key_one, 1);
ASSERT_FALSE(lookup(map, c_tt_one));
ASSERT_FALSE(lookup(map, tt_one));
}
{ //
ASSERT_FALSE(lookup(map, 2));
}
{
{
TV *const i = insert(map, 1, 2);
ASSERT_TRUE(i);
ASSERT_FALSE(lookup(map, 2));
TV *const l = lookup(map, 1);
ASSERT_TRUE(l);
ASSERT_EQ(*i, 2);
ASSERT_EQ(*l, 2);
ASSERT_EQ(l, i);
}
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_FALSE(lookup(map, 2));
{
TV *i = insert(map, 2, 3);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
TV *l = lookup(map, 2);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 3);
ASSERT_EQ(l, i);
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_TRUE(lookup(map, 2));
{
TV *i = insert(map, 1, 10);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 10);
TV *l = lookup(map, 1);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
ASSERT_EQ(l, i);
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_TRUE(lookup(map, 2));
}
TEST(HashMapProbingTest, test_probing) {
sp::HashMapProbing<int, int> map;
test_simple(map);
}
TEST(HashMapProbingTest, test_probing_dtor) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<int, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_probing_dtor2) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<sp::GcStruct, int> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_probing_dtor3) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<sp::GcStruct, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree) {
sp::HashMapTree<int, int> map;
test_simple(map);
}
TEST(HashMapProbingTest, test_tree_dtor) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<int, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree_dtor2) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<sp::GcStruct, int> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree_dtor3) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<sp::GcStruct, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
template <typename MAP>
static void
test_gc_value(MAP &map) {
sp::GcStruct::ctor = 0;
ASSERT_EQ(0, sp::GcStruct::ctor);
{
sp::GcStruct *const i = insert(map, 0, 1);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 1);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
const int c_value = 3;
sp::GcStruct *const i = insert(map, 2, c_value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
int value = 4;
sp::GcStruct *const i = insert(map, 3, value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 4);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(4, value);
}
sp::GcStruct::ctor = 0;
#if 0
{
const sp::GcStruct c_value(6);
sp::GcStruct *const i = insert(map, 5, c_value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 6);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct value(8);
sp::GcStruct *const i = insert(map, 7, value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 8);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(value, 8);
}
sp::GcStruct::ctor = 0;
#endif
#if 0
{
sp::GcStruct *const i = insert(map, 9, sp::GcStruct(10));
ASSERT_TRUE(i);
ASSERT_EQ(*i, 10);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct value(12);
sp::GcStruct *const i = insert(map, 11, std::move(value));
ASSERT_TRUE(i);
ASSERT_EQ(*i, 12);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
#endif
}
TEST(HashMapProbingTest, test_probing_gc_value) {
sp::HashMapProbing<int, sp::GcStruct> map;
test_gc_value(map);
}
TEST(HashMapProbingTest, test_tree_gc_value) {
sp::HashMapTree<int, sp::GcStruct> map;
test_gc_value(map);
}
template <typename MAP>
static void
test_gc_key(MAP &map) {
sp::GcStruct::ctor = 0;
ASSERT_EQ(0, sp::GcStruct::ctor);
{
int *const i = insert(map, 0, 1);
ASSERT_TRUE(i);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
const int c_key = 3;
int *const i = insert(map, c_key, 2);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 2);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
int key = 4;
int *const i = insert(map, key, 3);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(4, key);
}
sp::GcStruct::ctor = 0;
#if 0
{
const sp::GcStruct c_key(6);
int *const i = insert(map, c_key, 5);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 5);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(8);
int *const i = insert(map, key, 7);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 7);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(key, 8);
}
sp::GcStruct::ctor = 0;
#endif
#if 0
{
int *const i = insert(map, sp::GcStruct(10), 9);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 9);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(12);
int *const i = insert(map, std::move(key), 11);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 12);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(12);
int *const i = insert(map, 11, std::move(key));
ASSERT_TRUE(i);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
#endif
}
TEST(HashMapProbingTest, test_probing_gc_key) {
sp::HashMapProbing<sp::GcStruct, int> map;
test_gc_key(map);
}
TEST(HashMapProbingTest, test_tree_gc_key) {
sp::HashMapTree<sp::GcStruct, int> map;
test_gc_key(map);
}
| 20.3219 | 62 | 0.589977 | zpooky |
93612d7e4efc504ab2aa8a024bc874af40d6b4ba | 2,202 | hpp | C++ | CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | // Geometric Tools LLC, Redmond WA 98052
// Copyright (c) 1998-2015
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 1.0.2 (2014/12/13)
// The TVector template parameter allows you to create solvers with
// Vector<N,Real> when the dimension N is known at compile time or
// GVector<Real> when the dimension N is known at run time. Both classes
// have 'int GetSize() const' that allow OdeSolver-derived classes to query
// for the dimension.
#ifndef CMNMATH_NUMERICALMETHOD_ODEEULER_HPP__
#define CMNMATH_NUMERICALMETHOD_ODEEULER_HPP__
#include "ode_solver.hpp"
namespace CmnMath
{
namespace numericalmethod
{
template <typename Real, typename TVector>
class OdeEuler : public OdeSolver<Real,TVector>
{
public:
// Construction and destruction.
virtual ~OdeEuler();
OdeEuler(Real tDelta,
std::function<TVector(Real, TVector const&)> const& F);
// Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may allow
// xIn and xOut to be the same object.
virtual void Update(Real tIn, TVector const& xIn, Real& tOut,
TVector& xOut);
};
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
OdeEuler<Real, TVector>::~OdeEuler()
{
}
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
OdeEuler<Real, TVector>::OdeEuler(Real tDelta,
std::function<TVector(Real, TVector const&)> const& F)
:
OdeSolver<Real, TVector>(tDelta, F)
{
}
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
void OdeEuler<Real, TVector>::Update(Real tIn, TVector const& xIn,
Real& tOut, TVector& xOut)
{
TVector fVector = this->mFunction(tIn, xIn);
tOut = tIn + this->mTDelta;
xOut = xIn + this->mTDelta * fVector;
}
//----------------------------------------------------------------------------
} // namespace numericalmethod
} // namespace CmnMath
#endif /* CMNMATH_NUMERICALMETHOD_GAUSSIANELIMINATION_HPP__ */ | 33.363636 | 78 | 0.619437 | Khoronus |
9361b0b8990a7777692301a3bd08e43f4979bf0a | 8,409 | cpp | C++ | third_party/vss/GoogleVssAgent/VssAgent.cpp | playplay/compute-image-windows | 9f45829af870e7801ac9b9cdb2e3fe9820244e84 | [
"Apache-2.0"
] | 97 | 2015-06-03T03:05:10.000Z | 2021-11-13T13:52:20.000Z | third_party/vss/GoogleVssAgent/VssAgent.cpp | playplay/compute-image-windows | 9f45829af870e7801ac9b9cdb2e3fe9820244e84 | [
"Apache-2.0"
] | 112 | 2015-06-04T00:37:34.000Z | 2022-03-25T10:39:02.000Z | third_party/vss/GoogleVssAgent/VssAgent.cpp | playplay/compute-image-windows | 9f45829af870e7801ac9b9cdb2e3fe9820244e84 | [
"Apache-2.0"
] | 70 | 2015-06-01T23:57:45.000Z | 2022-02-22T06:15:20.000Z | // The VssAgent service logs the service start and stop information to
// the application event log, and runs the main function of the
// service in a thread pool worker thread.
#include "stdafx.h"
#include "VssAgent.h"
#include "../snapshot.h"
#include "GoogleVssClient.h"
#include "util.h"
VssService::VssService(PWSTR serviceName)
: GServiceBase(serviceName, TRUE, TRUE, FALSE),
srv_stopping_(false),
processing_thread_should_wakeup_(false),
adapter_(std::make_unique<Adapter>()) {
}
VssService::~VssService(void) {
}
// The function is executed when a Start command is sent to the service by
// the SCM or when the operating system starts when a service is configured
// to start automatically.
//
// Argumants:
// argc - number of command line arguments
// argv - array of command line arguments
void VssService::OnStart(DWORD argc, LPWSTR* argv) {
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(argv);
RegisterEvtLogHandle();
// Log a service start message to the Application log.
LogDebugMessage(L"VssService OnStart");
// Cancel any stray inquery requests in progress to unblock in case of
// previous server unclean exit like crash.
if (!adapter_->SendSnapshotIoctl(IOCTL_SNAPSHOT_DISCARD, NULL, NULL, 0)) {
// This will only happen in tests where there is no PD device.
// In that case, we don't need to start this service.
throw ERROR_NOT_SUPPORTED;
}
listening_thread_ = std::thread(&VssService::ListeningThreadWorker, this);
LogOperationalMessage(L"GoogleVssAgent service started successfully.");
}
void FinishBackupAfterThaw(GoogleVssClient* vssClient, BOOL ifSuccessful);
HRESULT PrepareVolumes(GoogleVssClient* vssClient,
const vector<wstring>& volume_names);
void VssService::ListeningThreadWorker() {
processing_thread_ = std::thread(&VssService::ProcessingThreadWorker, this);
while (!srv_stopping_.load()) {
LogDebugMessage(L"Sending IOCTL_SNAPSHOT_REQUESTED");
UCHAR target;
UCHAR lun;
// IOCTL_SNAPSHOT_REQUESTED will be in pending state until host sends a
// snapshot request or Agent cancel the operation in another thread.
BOOL ioctl_res =
adapter_->SendSnapshotIoctl(IOCTL_SNAPSHOT_REQUESTED, &target, &lun, 0);
LogDebugMessage(L"IOCTL_SNAPSHOT_REQUESTED returned.");
if (srv_stopping_.load()) {
LogDebugMessage(L"Listening Thread is exiting.");
break;
}
if (ioctl_res) {
SnapshotTarget snapshot_target;
snapshot_target.Target = target;
snapshot_target.Lun = lun;
{
std::lock_guard<std::mutex> lock(cv_wakeup_m_);
snapshot_targets_.push_back(snapshot_target);
processing_thread_should_wakeup_ = true;
}
cv_wakeup_.notify_one();
LogDebugMessage(L"Snapshot is requested for target %d, lun %d.", target,
lun);
}
}
// Wakeup and exit processing thread.
{
std::lock_guard<std::mutex> lock(cv_wakeup_m_);
processing_thread_should_wakeup_ = true;
}
cv_wakeup_.notify_one();
LogDebugMessage(L"Waiting for Processing Thread to be torn down.");
processing_thread_.join();
}
void VssService::ProcessingThreadWorker() {
while (!srv_stopping_.load()) {
std::vector<SnapshotTarget> st_local;
LogDebugMessage(L"ProcessingThreadWorker starts to wait.");
{
std::unique_lock<std::mutex> lk(cv_wakeup_m_);
cv_wakeup_.wait(lk, [this](){return processing_thread_should_wakeup_;});
processing_thread_should_wakeup_ = false;
st_local.swap(snapshot_targets_);
}
LogDebugMessage(L"ProcessingThreadWorker wakes up.");
for (const auto& st : st_local) {
UCHAR target = st.Target;
UCHAR lun = st.Lun;
vector<wstring> volumes;
DWORD ret;
ret = GetVolumesForScsiTarget(&volumes, adapter_->PortNumber(),
target, lun);
if (ERROR_SUCCESS != ret) {
LogDebugMessage(L"GetVolumesForScsiTarget failed with error %d", ret);
continue;
}
if (volumes.empty()) {
LogOperationalMessage(
L"Snapshot is requested for a disk which has no volumes");
// Stoport allows only one outstanding IOCTL for miniport drivers per
// given file handle. Since we are already having an IOCTL pending for
// adapter, we need to open a separate handle for that.
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(IOCTL_SNAPSHOT_CAN_PROCEED,
&target, &lun,
VIRTIO_SCSI_SNAPSHOT_PREPARE_COMPLETE)) {
LogDebugMessage(
L"IOCTL_SNAPSHOT_CAN_PROCEED failed for target %d, lun %d",
st.Target, st.Lun);
}
continue;
}
WCHAR event_name[64];
HANDLE event_handle = NULL;
if (SUCCEEDED(StringCchPrintf(event_name, ARRAYSIZE(event_name),
kSnapshotEventFormatString, (ULONG)target,
(ULONG)lun))) {
// Create a global event with default security descriptor which allow
// only owner (local system) and admin account access.
event_handle = CreateEvent(NULL, TRUE, FALSE, event_name);
if (event_handle == NULL) {
LogDebugMessage(L"CreateEvent failed with error %d", GetLastError());
}
}
if (event_handle != NULL) {
GoogleVssClient vssClient;
HRESULT hr = PrepareVolumes(&vssClient, volumes);
LogDebugMessage(L"PrepareVolumes return status %x", hr);
if (!SUCCEEDED(hr)) {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(IOCTL_SNAPSHOT_CAN_PROCEED,
&target, &lun, VIRTIO_SCSI_SNAPSHOT_PREPARE_ERROR)) {
LogDebugMessage(
L"IOCTL_SNAPSHOT_CAN_PROCEED failed for target %d, lun %d",
st.Target, st.Lun);
}
} else {
hr = vssClient.DoSnapshotSet();
if (!SUCCEEDED(hr)) {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(
IOCTL_SNAPSHOT_CAN_PROCEED, &target, &lun,
VIRTIO_SCSI_SNAPSHOT_ERROR)) {
LogDebugMessage(
L"Failed to report snapshot status for target %d, lun %d",
st.Target, st.Lun);
}
} else {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(
IOCTL_SNAPSHOT_CAN_PROCEED, &target, &lun,
VIRTIO_SCSI_SNAPSHOT_COMPLETE)) {
LogDebugMessage(
L"Failed to report snapshot status for target %d, lun %d",
st.Target, st.Lun);
}
}
}
FinishBackupAfterThaw(&vssClient, SUCCEEDED(hr));
{
vector<EVENT_DATA_DESCRIPTOR> data_descr(volumes.size() + 3);
DWORD idx = 0;
DWORD num_volumes = (DWORD)volumes.size();
EventDataDescCreate(&data_descr[idx++], &st.Target, sizeof(UCHAR));
EventDataDescCreate(&data_descr[idx++], &st.Lun, sizeof(UCHAR));
EventDataDescCreate(&data_descr[idx++], &num_volumes,
sizeof(num_volumes));
for (auto& volume : volumes) {
EventDataDescCreate(
&data_descr[idx++], volume.c_str(),
(ULONG)((volume.length() + 1) * sizeof(WCHAR)));
}
LogSnapshotEvent(SUCCEEDED(hr) ? &SNAPSHOT_SUCCEED : &SNAPSHOT_FAILED,
(ULONG)data_descr.size(), data_descr.data());
}
CloseHandle(event_handle);
}
}
}
}
// The function is executed when a Stop command is sent to the service by SCM.
void VssService::OnStop() {
// Log a service stop message to the Application log.
LogDebugMessage(L"VssService OnStop");
srv_stopping_.store(true);
// Cancel the inquery request in progress. Note that Windows allow only one
// outstanding IOCTL_SCSI_MINIPORT per file handle. So, we need to use
// another adapter object (a new handle) to send a new ioctl down.
Adapter adapter_for_cancel;
adapter_for_cancel.SendSnapshotIoctl(IOCTL_SNAPSHOT_DISCARD, NULL, NULL, 0);
listening_thread_.join();
LogOperationalMessage(L"GoogleVssAgent service is stopped.");
UnregisterEvtLogHandle();
}
| 40.23445 | 92 | 0.649899 | playplay |
93625416414a0d18b63cb3cde4c761b162ba849a | 982 | cpp | C++ | tournaments/subsetsSequence/subsetsSequence.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 5 | 2020-02-06T09:51:22.000Z | 2021-03-19T00:18:44.000Z | tournaments/subsetsSequence/subsetsSequence.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | null | null | null | tournaments/subsetsSequence/subsetsSequence.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 3 | 2019-09-27T13:06:21.000Z | 2021-04-20T23:13:17.000Z | bool subsetsSequence(std::vector<std::vector<int>> sets) {
struct Helper {
bool isSubset(std::vector<int>& setA, std::vector<int>& setB) {
int j = 0;
for (int i = 0; i < setB.size(); i++) {
if (j < setA.size() && setA[j] == setB[i]) {
j++;
}
}
if (j == setA.size()) {
return true;
}
else {
return false;
}
}
};
Helper h;
std::vector<int> supersets(sets.size(), 0);
for (int i = 0; i < sets.size(); i++) {
std::sort(sets[i].begin(), sets[i].end());
}
for (int i = 0; i < sets.size(); i++) {
for (int j = i + 1; j < sets.size(); j++) {
if (h.isSubset(sets[i], sets[j])) {
supersets[i]++;
}
if (h.isSubset(sets[j], sets[i])) {
supersets[j]++;
}
}
}
std::sort(supersets.begin(), supersets.end());
for (int i = 0; i < sets.size(); i++) {
if (supersets[i] < i) {
return false;
}
}
return true;
}
| 20.040816 | 67 | 0.453157 | gurfinkel |
936418de8bc21450a377175496bf3bbe5f36d4f5 | 984 | cpp | C++ | arc.cpp | hepeidong/Graph | f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9 | [
"Apache-2.0"
] | null | null | null | arc.cpp | hepeidong/Graph | f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9 | [
"Apache-2.0"
] | null | null | null | arc.cpp | hepeidong/Graph | f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9 | [
"Apache-2.0"
] | null | null | null | #include "arc.h"
#include <algorithm>
template<typename Tp>
Arc<Tp>::Arc():m_adjVertex(-1)
{
}
template<typename Tp>
Arc<Tp>::~Arc()
{
}
template<typename Tp>
Arc<Tp>* Arc<Tp>::CreateArc(value_t weight, site_t adjVertex)
{
Arc<Tp>* arc = new (std::nothrow) Arc();
if (arc->InitArc(weight, adjVertex))
{
arc->AutoReleasse();
}
else
{
SAFE_DELETE(arc);
}
return arc;
}
template<typename Tp>
bool Arc<Tp>::InitArc(value_t weight, site_t adjVertex)
{
m_weight = weight;
m_adjVertex = adjVertex;
return true;
}
template<typename Tp>
void Arc<Tp>::SetAdjVertex(site_t adjVertex)
{
m_adjVertex = adjVertex;
}
template<typename Tp>
inline typename Arc<Tp>::site_t Arc<Tp>::GetAdjVertex() const
{
return m_adjVertex;
}
template<typename Tp>
void Arc<Tp>::SetWeight(value_t weight)
{
m_weight = weight;
}
template<typename Tp>
inline typename Arc<Tp>::value_t Arc<Tp>::GetWeight() const
{
return m_weight;
}
| 15.870968 | 61 | 0.661585 | hepeidong |
9364706c8ae59aca17b5e39ea17a8bebb360734e | 4,315 | cpp | C++ | src/count_kmers_per_bin.cpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | src/count_kmers_per_bin.cpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | src/count_kmers_per_bin.cpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <fstream>
#include <chrono>
#include <numeric>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <seqan3/argument_parser/all.hpp>
#include <seqan3/io/sequence_file/input.hpp>
#include <seqan3/search/views/kmer_hash.hpp>
#include <chopper/build/read_chopper_split_file.hpp>
struct cmd_arguments
{
std::filesystem::path chopper_split_filename{};
uint8_t k{25};
size_t overlap{250};
bool verbose;
};
void initialize_argument_parser(seqan3::argument_parser & parser, cmd_arguments & args)
{
parser.info.author = "Avenja";
parser.info.short_description = "Count unique kmers in bins.";
parser.info.version = "1.0.0";
parser.add_option(args.chopper_split_filename, 'f', "files", "Give me a file produced by chopper split.",
seqan3::option_spec::required);
parser.add_option(args.k, 'k', "kmer-size", "The kmer to count with.");
parser.add_option(args.overlap, 'l', "overlap", "The overlap between splitted bins.");
parser.add_flag(args.verbose, 'v', "verbose", "Display more information.");
}
struct file_type_traits : public seqan3::sequence_file_input_default_traits_dna
{
using sequence_alphabet = seqan3::dna4;
};
using seq_file_type = seqan3::sequence_file_input<file_type_traits,
seqan3::fields<seqan3::field::seq, seqan3::field::id>,
seqan3::type_list<seqan3::format_fasta, seqan3::format_fastq>>;
auto read_sequences(std::vector<std::string> const & filenames)
{
std::unordered_map<std::string, seqan3::dna4_vector> info;
for (auto const & filename : filenames)
for (auto && [seq, id] : seq_file_type{filename})
info.emplace(filename + id, std::move(seq));
return info;
}
auto hash_infix(cmd_arguments const & args, auto const & seq, auto const begin, auto const end)
{
return seq | seqan3::views::drop(begin)
| seqan3::views::take(end + args.overlap - begin) // views::take never goes over the end
| seqan3::views::kmer_hash(seqan3::ungapped{args.k});
};
int main(int const argc, char const ** argv)
{
seqan3::argument_parser myparser{"count_kmers_per_bin", argc, argv};
cmd_arguments args{};
initialize_argument_parser(myparser, args);
try
{
myparser.parse();
}
catch (seqan3::argument_parser_error const & ext)
{
std::cout << "[ERROR] " << ext.what() << "\n";
return -1;
}
auto [data, batches] = read_chopper_split_file(args.chopper_split_filename);
std::vector<std::unordered_set<uint64_t>> kmer_counts;
for (auto const & batch_record : batches)
{
auto && info = read_sequences(batch_record.filenames);
if (batch_record.libf_num_bins > 0) // merged bin
{
kmer_counts.resize(batch_record.libf_num_bins);
for (auto const & [combined_id, seq] : info)
for (auto const & reg : data.region_map.at(combined_id))
for (auto hash : hash_infix(args, seq, reg.begin, reg.end))
kmer_counts[reg.lidx].insert(hash);
for (size_t i = 0; i < batch_record.libf_num_bins; ++i)
std::cout << batch_record.hibf_bins[0] << '_' << i << '\t' << kmer_counts[i].size() << '\n';
// also output size of merged bin
std::unordered_set<uint64_t> hibf_kmer_count{};
for (auto & set : kmer_counts)
{
hibf_kmer_count.merge(set);
set.clear();
}
std::cout << batch_record.hibf_bins[0] << '\t' << hibf_kmer_count.size();
}
else // split bin
{
kmer_counts.resize(batch_record.hibf_bins.size());
for (auto const & [combined_id, seq] : info)
for (auto const & reg : data.region_map.at(combined_id))
for (auto hash : hash_infix(args, seq, reg.begin, reg.end))
kmer_counts[reg.hidx].insert(hash);
for (size_t i = 0; i < batch_record.hibf_bins.size(); ++i)
std::cout << batch_record.hibf_bins[i] << '\t' << kmer_counts[i].size() << '\n';
}
kmer_counts.clear();
}
}
| 35.081301 | 113 | 0.609502 | Felix-Droop |
936719eb694d275d2b3d1a7acad921e888c92889 | 10,453 | cp | C++ | Win32/Sources/Application/Speech/CSpeechSynthesis.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Win32/Sources/Application/Speech/CSpeechSynthesis.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Win32/Sources/Application/Speech/CSpeechSynthesis.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007-2009 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// CSpeechSynthesis.cp
// Class to handle speech sythesis
#include "CSpeechSynthesis.h"
#include "CAddressList.h"
#include "CEnvelope.h"
#include "CErrorHandler.h"
#include "CMbox.h"
#include "CMessage.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
// === Static Members ===
CComPtr<ISpVoice> CSpeechSynthesis::sSpVoice;
bool CSpeechSynthesis::sAvailable = false;
#ifdef __MULBERRY
cdmutex CSpeechSynthesis::_mutex;
#endif
cdstrqueue CSpeechSynthesis::sSpeakQueue;
bool CSpeechSynthesis::sTopDone = false;
cdstrvect CSpeechSynthesis::sItemList;
// === constants ===
const char* cSpeakPause = ", ";
const char* cSpeakEndSentence = ". ";
#pragma ARM_conform on
// __________________________________________________________________________________________________
// C L A S S __ C A B O U T D I A L O G
// __________________________________________________________________________________________________
CSpeechSynthesis::CSpeechSynthesis()
{
}
CSpeechSynthesis::~CSpeechSynthesis()
{
}
// Check for speech and install menus etc
bool CSpeechSynthesis::InstallSpeechSynthesis()
{
CMenu* speak_menu = NULL;
// Load COM
CoInitialize(NULL);
try
{
// First check to see if the Speech Manager extension is present
HRESULT result = sSpVoice.CoCreateInstance(CLSID_SpVoice);
// Check state
if (SUCCEEDED(result))
{
// Get descriptor strings
for(short i = IDS_SPEAK_FROM1; i <= IDS_SPEAK_NONE; i++)
{
cdstring str;
str.FromResource(i);
sItemList.push_back(str);
}
sAvailable = true;
}
}
catch (...)
{
CLOG_LOGCATCH(...);
// Not loaded - do nothing
sAvailable = false;
}
return sAvailable;
}
// Remove speech
void CSpeechSynthesis::RemoveSpeechSynthesis()
{
// Explicitly release COM object here rather than rely on static destructor to do it
// Release COM object
sSpVoice.Release();
// Unload COM
CoUninitialize();
}
// Create menu
void CSpeechSynthesis::InstallMenu(CMenu* menu)
{
}
bool CSpeechSynthesis::OnUpdateEditSpeak(UINT nID, CCmdUI* pCmdUI)
{
bool handled = false;
if (!Available())
{
pCmdUI->Enable(false);
return false;
}
#ifdef __MULBERRY
switch(nID)
{
case IDM_EDIT_SPEAK:
if (Speaking())
{
CString txt;
txt.LoadString(IDS_SPEAK_STOPSPEAKING);
OnUpdateMenuTitle(pCmdUI, txt);
pCmdUI->Enable(true); // Always
handled = true;
}
break;
default:;
}
#endif
return handled;
}
bool CSpeechSynthesis::OnEditSpeak(UINT nID)
{
bool handled = false;
#ifdef __MULBERRY
switch(nID)
{
case IDM_EDIT_SPEAK:
if (Speaking())
{
StopSpeaking();
handled = true;
}
break;
default:;
}
#endif
return handled;
}
bool CSpeechSynthesis::Speaking(void)
{
if (!Available())
return false;
SPVOICESTATUS status;
HRESULT result = sSpVoice->GetStatus(&status, NULL);
if (SUCCEEDED(result))
return status.dwRunningState == SPRS_IS_SPEAKING;
else
return false;
}
void CSpeechSynthesis::SpeakText(char* txt, long length)
{
if (!Available())
return;
std::auto_ptr<wchar_t> wtxt(new wchar_t[::strlen(txt) + 1]);
const char* p = txt;
wchar_t* q = wtxt.get();
while(*p)
*q++ = *p++;
*q++ = *p++;
sSpVoice->Speak(wtxt.get(), SPF_ASYNC | SPF_IS_NOT_XML, 0);
}
void CSpeechSynthesis::StopSpeaking(void)
{
if (!Available())
return;
// Stop actual speech
sSpVoice->Speak(NULL, SPF_PURGEBEFORESPEAK, 0);
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Clear all from queue
while(!sSpeakQueue.empty())
sSpeakQueue.pop();
sTopDone = false;
}
// Speak items from queue (remember that Speech Manager 'captures' text buffer while speaking)
void CSpeechSynthesis::SpendTime(void)
{
if (!Available())
return;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Ignore if speaking or empty queue
if (sSpeakQueue.empty() || Speaking())
return;
// Pop off top item if done
if (sTopDone)
{
sSpeakQueue.pop();
sTopDone = false;
}
// Check for next item
if (!sSpeakQueue.empty())
{
cdstring& spk = sSpeakQueue.front();
SpeakText(spk, spk.length());
sTopDone = true;
}
}
// Speak specific text item
void CSpeechSynthesis::SpeakString(const cdstring& txt)
{
if (!Available())
return;
cdstring spk = txt;
// Add end of sentence
spk += cSpeakEndSentence;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Add item to speech queue
sSpeakQueue.push(spk);
}
void CSpeechSynthesis::SpeakNewMessages(CMbox* mbox)
{
if (!Available())
return;
}
void CSpeechSynthesis::SpeakMessage(CMessage* msg, CAttachment* attach, bool letter)
{
if (!Available())
return;
if (!msg)
return;
CEnvelope* env = msg->GetEnvelope();
if (!env)
return;
cdstring spk;
const CMessageSpeakVector* items;
// Adjust for first text part
if (!attach)
attach = msg->FirstDisplayPart();
// Got appropriate item array
if (letter)
items = &CPreferences::sPrefs->mSpeakLetterItems.GetValue();
else
items = &CPreferences::sPrefs->mSpeakMessageItems.GetValue();
// Assume text read in
for(CMessageSpeakVector::const_iterator iter = items->begin(); iter != items->end(); iter++)
{
// Add user item to text and add pause after
spk = (*iter).mItemText;
spk += cSpeakPause;
switch((*iter).mItem)
{
case eMessageSpeakFrom1: // Speak single from address
if (!env->GetFrom()->empty())
spk += env->GetFrom()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakFromAll: // Speak all from addresses
if (!env->GetFrom()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetFrom()->begin(); iter2 < env->GetFrom()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakTo1:
if (!env->GetTo()->empty()) // Speak single to address
spk += env->GetTo()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakToAll: // Speak all to addresses
if (!env->GetTo()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetTo()->begin(); iter2 < env->GetTo()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakCC1: // Speak single CC address
if (!env->GetCC()->empty())
spk += env->GetCC()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakCCAll: // Speak all CC addresses
if (!env->GetCC()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetCC()->begin(); iter2 < env->GetCC()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakDate: // Speak date
if (env->GetTextDate(true, true).length())
spk += env->GetTextDate(true, true);
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakSubject: // Speak subject
if (env->GetSubject().length())
spk += env->GetSubject();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakNumParts: // Speak number of parts
spk += cdstring(msg->GetBody()->CountParts());
break;
case eMessageSpeakBodyNoHdr: // Speak message text without header
{
const char* body = nil;
try
{
if (attach)
body = attach->ReadPart(msg);
}
catch (...)
{
CLOG_LOGCATCH(...);
}
if (body && ::strlen(body))
{
// Limit size to user specified maximum
size_t len = ::strlen(body);
if (len > CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue())
len = CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue();
spk += cdstring(body, len);
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
}
case eMessageSpeakBodyHdr: // Speak message text with header
{
const char* body = nil;
char* hdr = msg->GetHeader();
try
{
if (attach)
body = attach->ReadPart(msg);
}
catch (...)
{
CLOG_LOGCATCH(...);
}
if ((!hdr || !::strlen(hdr)) && (!body || !::strlen(body)))
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
else
{
if (hdr)
spk += cdstring(hdr, ::strlen(hdr));
spk += cSpeakPause;
if (body)
{
// Limit size to user specified maximum
size_t len = ::strlen(body);
if (len > CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue())
len = CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue();
spk += cdstring(body, len);
}
}
break;
}
case eMessageSpeakNone: // Do not speak any extra text
default:
break;
}
// Add end of sentence
spk += cSpeakEndSentence;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Add item to speech queue
sSpeakQueue.push(spk);
}
}
| 22.923246 | 110 | 0.647565 | mulberry-mail |
9368165cf6fefe25843710913b94afec7f6edb5d | 1,539 | cpp | C++ | test_mbed/src/main.cpp | chris3069/BLDC_Project | 69f6b7ed810d091dd430d93554056e34af130d2d | [
"BSL-1.0"
] | null | null | null | test_mbed/src/main.cpp | chris3069/BLDC_Project | 69f6b7ed810d091dd430d93554056e34af130d2d | [
"BSL-1.0"
] | null | null | null | test_mbed/src/main.cpp | chris3069/BLDC_Project | 69f6b7ed810d091dd430d93554056e34af130d2d | [
"BSL-1.0"
] | null | null | null | #include <mbed.h>
#define MAXIMUM_BUFFER_SIZE 32
// Open Loop Betrieb
// Timer lauft, y Values verändern sich alle 100ms
// y-Value in pulsewidth laden
// IN2 startet von Value 20,
// IN3 starte von Value 40
// mit Poti einstellbar
InterruptIn button_stop(D7); // Stop Taster, Falling Edge glaub ich
InterruptIn button_start(D8); // Start Taster, Falling Edge
InterruptIn rotary_encoder1(D12); // Rotary Encoder, Falling Edge glaub ich
InterruptIn rotary_encoder2(D13); // Rotary Encoder, Falling Edge
DigitalOut
uint8_t sine_wave[] = {49, 54, 59, 64, 69, 73, 78, 82, 85, 89, 91, 94, 95, 97, 97, 97, 97, 96, 95, 93, 90, 87, 84, 80, 76, 71, 66, 61, 56, 51, 46, 41, 36, 31, 26, 21, 17, 13, 10, 7, 4, 2, 1, 0, 0, 0, 0, 2, 3, 6, 8, 12, 15, 19, 24, 28, 33, 38, 43, 48}
// Create a BufferedSerial object with a default baud rate.
static BufferedSerial serial_port(USBTX, USBRX);
int main() {
// Set desired properties (9600-8-N-1).
serial_port.set_baud(9600);
serial_port.set_format(
/* bits */ 8,
/* parity */ BufferedSerial::None,
/* stop bit */ 1
);
char buf[MAXIMUM_BUFFER_SIZE] = {0};
// put your setup code here, to run once:
PwmOut IN1(D9);
PwmOut IN2(D10);
PwmOut IN3(D11);
// DigitalOut
// Timer t
// t.
IN1.period_us(100);
IN1.pulsewidth_us(10);
// uint32_t periodlength = TIM3->CCR2;
// serial_port.write(buf, periodlength);
while(1) {
serial_port.write(buf, periodlength);
// D9.
// put your main code here, to run repeatedly:
}
} | 24.046875 | 250 | 0.647823 | chris3069 |
9368e8d205917185bb5283b5357ee477c0ac22f5 | 1,878 | cpp | C++ | frameworks/native/hitrace.cpp | openharmony-gitee-mirror/hiviewdfx_hitrace | a8efefe3894dda36857d6a5bf2db43c81490a5e5 | [
"Apache-2.0"
] | null | null | null | frameworks/native/hitrace.cpp | openharmony-gitee-mirror/hiviewdfx_hitrace | a8efefe3894dda36857d6a5bf2db43c81490a5e5 | [
"Apache-2.0"
] | null | null | null | frameworks/native/hitrace.cpp | openharmony-gitee-mirror/hiviewdfx_hitrace | a8efefe3894dda36857d6a5bf2db43c81490a5e5 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:21:28.000Z | 2021-09-13T11:21:28.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hitrace/hitrace.h"
#include "hitrace_inner.h"
using namespace std;
namespace OHOS {
namespace HiviewDFX {
HiTraceId HiTrace::Begin(const string& name, int flags)
{
return HiTraceId(::HiTraceBegin(name.c_str(), flags));
}
void HiTrace::End(const HiTraceId& id)
{
::HiTraceEnd(&(id.id_));
return;
}
HiTraceId HiTrace::GetId()
{
return HiTraceId(::HiTraceGetId());
}
void HiTrace::SetId(const HiTraceId& id)
{
::HiTraceSetId(&(id.id_));
return;
}
void HiTrace::ClearId()
{
::HiTraceClearId();
return;
}
HiTraceId HiTrace::CreateSpan()
{
return HiTraceId(::HiTraceCreateSpan());
}
void HiTrace::Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
::HiTraceTracepointInner(HITRACE_CM_DEFAULT, type, &(id.id_), fmt, args);
va_end(args);
return;
}
void HiTrace::Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id,
const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
::HiTraceTracepointInner(mode, type, &(id.id_), fmt, args);
va_end(args);
return;
}
} // namespace HiviewDFX
} // namespace OHOS | 23.475 | 105 | 0.671991 | openharmony-gitee-mirror |
9369612ad0aefa91d8096ef96145ae7b170b1650 | 10,170 | cpp | C++ | flight-simulator/hackflight/sim/indoors/msppg.cpp | CobraPi/Gesture-Controled-Drone | 94053b27f1ecd4d667ea603d45a5e29ffbfe2787 | [
"CC0-1.0"
] | 1 | 2020-03-02T16:38:21.000Z | 2020-03-02T16:38:21.000Z | flight-simulator/hackflight/sim/indoors/msppg.cpp | CobraPi/Gesture-Controled-Drone | 94053b27f1ecd4d667ea603d45a5e29ffbfe2787 | [
"CC0-1.0"
] | null | null | null | flight-simulator/hackflight/sim/indoors/msppg.cpp | CobraPi/Gesture-Controled-Drone | 94053b27f1ecd4d667ea603d45a5e29ffbfe2787 | [
"CC0-1.0"
] | null | null | null | // AUTO-GENERATED CODE: DO NOT EDIT!!!
#include "msppg.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static byte CRC8(byte * data, int n) {
byte crc = 0x00;
for (int k=0; k<n; ++k) {
crc ^= data[k];
}
return crc;
}
byte MSP_Message::start() {
this->pos = 0;
return this->getNext();
}
bool MSP_Message::hasNext() {
return this->pos <= this->len;
}
byte MSP_Message::getNext() {
return this->bytes[this->pos++];
}
MSP_Parser::MSP_Parser() {
this->state = 0;
}
void MSP_Parser::parse(byte b) {
switch (this->state) {
case 0: // sync char 1
if (b == 36) { // $
this->state++;
}
break;
case 1: // sync char 2
if (b == 77) { // M
this->state++;
}
else { // restart and try again
this->state = 0;
}
break;
case 2: // direction (should be >)
if (b == 62) { // >
this->message_direction = 1;
}
else { // <
this->message_direction = 0;
}
this->state++;
break;
case 3:
this->message_length_expected = b;
this->message_checksum = b;
// setup arraybuffer
this->message_length_received = 0;
this->state++;
break;
case 4:
this->message_id = b;
this->message_checksum ^= b;
if (this->message_length_expected > 0) {
// process payload
this->state++;
}
else {
// no payload
this->state += 2;
}
break;
case 5: // payload
this->message_buffer[this->message_length_received] = b;
this->message_checksum ^= b;
this->message_length_received++;
if (this->message_length_received >= this->message_length_expected) {
this->state++;
}
break;
case 6:
this->state = 0;
if (this->message_checksum == b) {
// message received, process
switch (this->message_id) {
case 108: {
short angx;
memcpy(&angx, &this->message_buffer[0], sizeof(short));
short angy;
memcpy(&angy, &this->message_buffer[2], sizeof(short));
short heading;
memcpy(&heading, &this->message_buffer[4], sizeof(short));
this->handlerForATTITUDE->handle_ATTITUDE(angx, angy, heading);
} break;
case 105: {
short c1;
memcpy(&c1, &this->message_buffer[0], sizeof(short));
short c2;
memcpy(&c2, &this->message_buffer[2], sizeof(short));
short c3;
memcpy(&c3, &this->message_buffer[4], sizeof(short));
short c4;
memcpy(&c4, &this->message_buffer[6], sizeof(short));
short c5;
memcpy(&c5, &this->message_buffer[8], sizeof(short));
short c6;
memcpy(&c6, &this->message_buffer[10], sizeof(short));
short c7;
memcpy(&c7, &this->message_buffer[12], sizeof(short));
short c8;
memcpy(&c8, &this->message_buffer[14], sizeof(short));
this->handlerForRC->handle_RC(c1, c2, c3, c4, c5, c6, c7, c8);
} break;
case 109: {
int altitude;
memcpy(&altitude, &this->message_buffer[0], sizeof(int));
short vario;
memcpy(&vario, &this->message_buffer[4], sizeof(short));
this->handlerForALTITUDE->handle_ALTITUDE(altitude, vario);
} break;
case 127: {
short x;
memcpy(&x, &this->message_buffer[0], sizeof(short));
short y;
memcpy(&y, &this->message_buffer[2], sizeof(short));
short z;
memcpy(&z, &this->message_buffer[4], sizeof(short));
short theta;
memcpy(&theta, &this->message_buffer[6], sizeof(short));
this->handlerForSLAM_POSE->handle_SLAM_POSE(x, y, z, theta);
} break;
}
}
break;
default:
break;
}
}
MSP_Message MSP_Parser::serialize_SET_HEAD(short head) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 2;
msg.bytes[4] = 205;
memcpy(&msg.bytes[5], &head, sizeof(short));
msg.bytes[7] = CRC8(&msg.bytes[3], 4);
msg.len = 8;
return msg;
}
void MSP_Parser::set_ATTITUDE_Handler(class ATTITUDE_Handler * handler) {
this->handlerForATTITUDE = handler;
}
MSP_Message MSP_Parser::serialize_ATTITUDE_Request() {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 60;
msg.bytes[3] = 0;
msg.bytes[4] = 108;
msg.bytes[5] = 108;
msg.len = 6;
return msg;
}
MSP_Message MSP_Parser::serialize_ATTITUDE(short angx, short angy, short heading) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 6;
msg.bytes[4] = 108;
memcpy(&msg.bytes[5], &angx, sizeof(short));
memcpy(&msg.bytes[7], &angy, sizeof(short));
memcpy(&msg.bytes[9], &heading, sizeof(short));
msg.bytes[11] = CRC8(&msg.bytes[3], 8);
msg.len = 12;
return msg;
}
void MSP_Parser::set_RC_Handler(class RC_Handler * handler) {
this->handlerForRC = handler;
}
MSP_Message MSP_Parser::serialize_RC_Request() {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 60;
msg.bytes[3] = 0;
msg.bytes[4] = 105;
msg.bytes[5] = 105;
msg.len = 6;
return msg;
}
MSP_Message MSP_Parser::serialize_RC(short c1, short c2, short c3, short c4, short c5, short c6, short c7, short c8) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 16;
msg.bytes[4] = 105;
memcpy(&msg.bytes[5], &c1, sizeof(short));
memcpy(&msg.bytes[7], &c2, sizeof(short));
memcpy(&msg.bytes[9], &c3, sizeof(short));
memcpy(&msg.bytes[11], &c4, sizeof(short));
memcpy(&msg.bytes[13], &c5, sizeof(short));
memcpy(&msg.bytes[15], &c6, sizeof(short));
memcpy(&msg.bytes[17], &c7, sizeof(short));
memcpy(&msg.bytes[19], &c8, sizeof(short));
msg.bytes[21] = CRC8(&msg.bytes[3], 18);
msg.len = 22;
return msg;
}
MSP_Message MSP_Parser::serialize_SET_RAW_RC(short c1, short c2, short c3, short c4, short c5, short c6, short c7, short c8) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 16;
msg.bytes[4] = 200;
memcpy(&msg.bytes[5], &c1, sizeof(short));
memcpy(&msg.bytes[7], &c2, sizeof(short));
memcpy(&msg.bytes[9], &c3, sizeof(short));
memcpy(&msg.bytes[11], &c4, sizeof(short));
memcpy(&msg.bytes[13], &c5, sizeof(short));
memcpy(&msg.bytes[15], &c6, sizeof(short));
memcpy(&msg.bytes[17], &c7, sizeof(short));
memcpy(&msg.bytes[19], &c8, sizeof(short));
msg.bytes[21] = CRC8(&msg.bytes[3], 18);
msg.len = 22;
return msg;
}
void MSP_Parser::set_ALTITUDE_Handler(class ALTITUDE_Handler * handler) {
this->handlerForALTITUDE = handler;
}
MSP_Message MSP_Parser::serialize_ALTITUDE_Request() {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 60;
msg.bytes[3] = 0;
msg.bytes[4] = 109;
msg.bytes[5] = 109;
msg.len = 6;
return msg;
}
MSP_Message MSP_Parser::serialize_ALTITUDE(int altitude, short vario) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 6;
msg.bytes[4] = 109;
memcpy(&msg.bytes[5], &altitude, sizeof(int));
memcpy(&msg.bytes[9], &vario, sizeof(short));
msg.bytes[11] = CRC8(&msg.bytes[3], 8);
msg.len = 12;
return msg;
}
void MSP_Parser::set_SLAM_POSE_Handler(class SLAM_POSE_Handler * handler) {
this->handlerForSLAM_POSE = handler;
}
MSP_Message MSP_Parser::serialize_SLAM_POSE_Request() {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 60;
msg.bytes[3] = 0;
msg.bytes[4] = 127;
msg.bytes[5] = 127;
msg.len = 6;
return msg;
}
MSP_Message MSP_Parser::serialize_SLAM_POSE(short x, short y, short z, short theta) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 8;
msg.bytes[4] = 127;
memcpy(&msg.bytes[5], &x, sizeof(short));
memcpy(&msg.bytes[7], &y, sizeof(short));
memcpy(&msg.bytes[9], &z, sizeof(short));
memcpy(&msg.bytes[11], &theta, sizeof(short));
msg.bytes[13] = CRC8(&msg.bytes[3], 10);
msg.len = 14;
return msg;
}
MSP_Message MSP_Parser::serialize_SET_MOTOR(short m1, short m2, short m3, short m4) {
MSP_Message msg;
msg.bytes[0] = 36;
msg.bytes[1] = 77;
msg.bytes[2] = 62;
msg.bytes[3] = 8;
msg.bytes[4] = 214;
memcpy(&msg.bytes[5], &m1, sizeof(short));
memcpy(&msg.bytes[7], &m2, sizeof(short));
memcpy(&msg.bytes[9], &m3, sizeof(short));
memcpy(&msg.bytes[11], &m4, sizeof(short));
msg.bytes[13] = CRC8(&msg.bytes[3], 10);
msg.len = 14;
return msg;
}
| 23.651163 | 126 | 0.505506 | CobraPi |
936af9b8ad9566e2240c331bcde20230fb73b7dd | 614 | cc | C++ | src/code_writen_when_learning/standard_grammer/cpp17/declaration/member_operator_overload/main.cc | NobodyXu/snippet | 8f0308e48dab1d166dc9e5ff43b00db2d35b616b | [
"MIT"
] | 1 | 2019-04-02T04:38:15.000Z | 2019-04-02T04:38:15.000Z | src/code_writen_when_learning/standard_grammer/cpp17/declaration/member_operator_overload/main.cc | NobodyXu/snippet | 8f0308e48dab1d166dc9e5ff43b00db2d35b616b | [
"MIT"
] | null | null | null | src/code_writen_when_learning/standard_grammer/cpp17/declaration/member_operator_overload/main.cc | NobodyXu/snippet | 8f0308e48dab1d166dc9e5ff43b00db2d35b616b | [
"MIT"
] | null | null | null | template <class T>
struct wrapper {
using self = wrapper;
T obj;
auto operator + () const noexcept { return *this; }
auto operator - () const noexcept { return self{0} - *this; }
auto operator + (const self &other) const noexcept { return self{*this} += other; }
auto operator - (const self &other) const noexcept { return self{*this} -= other; }
# define DEF_ASSIGN(OP)\
auto& operator OP ## = (const self &other) noexcept {\
obj OP ## = other.obj;\
return *this;\
}
DEF_ASSIGN(+)
};
int main() {
auto result = wrapper<int>{3} + wrapper<int>{4};
}
| 25.583333 | 87 | 0.592834 | NobodyXu |
936f3d5cb6bac5250cb89fa26c545896ab356914 | 4,160 | cpp | C++ | utils/ShaderUtil.cpp | sarahayu/Fibonacci-Spring-Tree | bf6809d5d8b7f9d13e1acf6af29edb14cec0805a | [
"MIT"
] | null | null | null | utils/ShaderUtil.cpp | sarahayu/Fibonacci-Spring-Tree | bf6809d5d8b7f9d13e1acf6af29edb14cec0805a | [
"MIT"
] | null | null | null | utils/ShaderUtil.cpp | sarahayu/Fibonacci-Spring-Tree | bf6809d5d8b7f9d13e1acf6af29edb14cec0805a | [
"MIT"
] | null | null | null | #include "ShaderUtil.h"
#include <SFML\Graphics.hpp>
namespace
{
void load(const GLenum & shaderType, const std::string & file, unsigned int & shader)
{
int success;
char infoLog[512];
std::ifstream shaderFile;
shaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
std::stringstream shaderStream;
try
{
shaderFile.open(file);
shaderStream << shaderFile.rdbuf();
}
catch (...)
{
std::cout << "\nShader file could not be read!";
}
std::string shaderString = shaderStream.str();
const char *shaderCode = shaderString.c_str();
const bool isVertex = shaderType == GL_VERTEX_SHADER;
shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &shaderCode, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "\n" << (isVertex ? "Vertex" : "Fragment") << " compilation failed! " << infoLog;
}
}
}
void ShaderUtil::linkShader(unsigned int & ID, const std::string & vertexFile, const std::string & fragmentFile)
{
unsigned int vert, frag;
int success;
char infoLog[512];
load(GL_VERTEX_SHADER, "resources/shaders/" + vertexFile + ".vs", vert);
load(GL_FRAGMENT_SHADER, "resources/shaders/" + (fragmentFile == "" ? vertexFile : fragmentFile) + ".fs", frag);
ID = glCreateProgram();
glAttachShader(ID, vert);
glAttachShader(ID, frag);
glLinkProgram(ID);
glGetProgramiv(ID, GL_LINK_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(ID, 512, NULL, infoLog);
std::cout << "\nShader linking failed!";
}
else
{
std::cout << "\nShader '" << vertexFile << "' successfully loaded!";
}
glDeleteShader(vert);
glDeleteShader(frag);
}
void ShaderUtil::loadTexture(unsigned int &texture, const std::string & file, const TexParams & params)
{
sf::Image image;
if (!image.loadFromFile("resources/" + file)) throw std::runtime_error("Could not load file '" + file + "'!");
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, params.internalFormat, image.getSize().x, image.getSize().y, 0, params.format, params.type, image.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, params.wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, params.wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, params.filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, params.filter);
}
void ShaderUtil::loadCubeTexture(unsigned int & texture, const std::array<std::string, 6> &faces, const TexParams & params)
{
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
unsigned int offset = 0;
for (const auto &face : faces)
{
sf::Image image;
if (!image.loadFromFile("resources/" + face)) throw std::runtime_error("Could not load file '" + face + "'!");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + offset++, 0, params.internalFormat, image.getSize().x, image.getSize().y, 0, params.format, params.type, image.getPixelsPtr());
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, params.filter);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, params.filter);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, params.wrap);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, params.wrap);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, params.wrap);
}
void ShaderUtil::createTexture(unsigned int & texture, const glm::vec2 & size, const TexParams & params, const void *pixels)
{
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, params.internalFormat, size.x, size.y, 0, params.format, params.type, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, params.wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, params.wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, params.filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, params.filter);
}
TexParams::TexParams()
: wrap(GL_REPEAT), filter(GL_LINEAR), internalFormat(GL_RGBA), format(GL_RGBA), type(GL_UNSIGNED_BYTE)
{
}
| 34.666667 | 175 | 0.740865 | sarahayu |
9370df570a0ad5b979edcff5c6b44d9018735660 | 4,660 | cpp | C++ | src/svLibrary/src/resource/ResourceFolderPC.cpp | sevanspowell/sev | c678aaab3a9e6bd4e5b98774205c8775c9a3291d | [
"MIT"
] | null | null | null | src/svLibrary/src/resource/ResourceFolderPC.cpp | sevanspowell/sev | c678aaab3a9e6bd4e5b98774205c8775c9a3291d | [
"MIT"
] | 1 | 2017-06-11T06:34:50.000Z | 2017-06-11T06:34:50.000Z | src/svLibrary/src/resource/ResourceFolderPC.cpp | sevanspowell/sev | c678aaab3a9e6bd4e5b98774205c8775c9a3291d | [
"MIT"
] | null | null | null | #include <sv/System.h>
#if SV_PLATFORM_POSIX
#include <cstdio>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <fstream>
#include <sstream>
#include <sv/resource/ResourceFolderPC.h>
namespace sv {
bool ResourceFolderPC::open() {
isFolderOpen = true;
// No need to 'open' a folder
return true;
}
bool ResourceFolderPC::isOpen() { return isFolderOpen; }
int32_t ResourceFolderPC::getRawResourceSize(const Resource &r) {
std::stringstream fullPath;
fullPath << folderPath << "/" << r.name;
std::ifstream in(fullPath.str(),
std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
int32_t ResourceFolderPC::getRawResource(const Resource &r,
void *const buffer) {
// http://stackoverflow.com/questions/18816126/c-read-the-whole-file-in-buffer
std::stringstream fullPath;
fullPath << folderPath << "/" << r.name;
std::ifstream in(fullPath.str(),
std::ifstream::ate | std::ifstream::binary);
std::streamsize size = in.tellg();
in.seekg(0, std::ios::beg);
if (in.read((char *const)buffer, size)) {
// Successful
return size;
} else {
return -1;
}
}
size_t ResourceFolderPC::getNumResources() const {
return getNumFilesInDir(folderPath);
}
Resource ResourceFolderPC::getResourceIdentifier(size_t index) const {
size_t i = 0;
std::string resourceIdentifier =
getFileNameInDirByIndex(folderPath, index, i);
return Resource(resourceIdentifier);
}
DateTime ResourceFolderPC::getResourceModifiedDate(const Resource &r) const {
DateTime dateTime;
#if SV_PLATFORM_POSIX
struct tm *clock;
struct stat attr;
std::stringstream filePath;
filePath << folderPath << "/" << r.name;
stat(filePath.str().c_str(), &attr);
clock = localtime(&(attr.st_mtime));
dateTime = DateTime(clock->tm_sec, clock->tm_min, clock->tm_hour,
clock->tm_mday, clock->tm_mon, clock->tm_year + 1900);
#else
// TODO Windows
#endif
return dateTime;
}
size_t ResourceFolderPC::getNumFilesInDir(const std::string &dirPath) const {
size_t numFiles = 0;
#if SV_PLATFORM_POSIX
DIR *dp;
struct dirent *ep = nullptr;
dp = opendir(dirPath.c_str());
if (dp != nullptr) {
while ((ep = readdir(dp))) {
// Ignore ., .. and all other hidden files
if (strncmp(ep->d_name, ".", 1) != 0) {
if (ep->d_type == DT_REG) {
++numFiles;
} else if (ep->d_type == DT_DIR) {
std::stringstream newDir;
newDir << dirPath << "/" << std::string(ep->d_name);
numFiles += getNumFilesInDir(newDir.str());
}
}
}
closedir(dp);
}
#else
// TODO Windows
#endif
return numFiles;
}
std::string
ResourceFolderPC::getFileNameInDirByIndex(const std::string &dirPath,
size_t indexToFind) const {
size_t currentIndex = 0;
return getFileNameInDirByIndex(dirPath, indexToFind, currentIndex);
}
std::string
ResourceFolderPC::getFileNameInDirByIndex(const std::string &dirPath,
size_t indexToFind,
size_t ¤tIndex) const {
std::string resourceName = "";
#if SV_PLATFORM_POSIX
DIR *dp;
struct dirent *ep = nullptr;
dp = opendir(dirPath.c_str());
if (dp != nullptr) {
while ((ep = readdir(dp))) {
// Ignore ., .. and all other hidden files
if (strncmp(ep->d_name, ".", 1) != 0) {
if (ep->d_type == DT_REG) {
// For each regular file, check if index we are looking
// for, else increase current index
if (currentIndex == indexToFind) {
resourceName = ep->d_name;
break;
}
++currentIndex;
} else if (ep->d_type == DT_DIR) {
std::stringstream newDir;
newDir << dirPath << "/" << std::string(ep->d_name);
resourceName = getFileNameInDirByIndex(
newDir.str(), indexToFind, currentIndex);
if (resourceName != "") {
break;
}
}
}
}
closedir(dp);
}
#else
// TODO Windows
#endif
return resourceName;
}
}
| 27.251462 | 82 | 0.550429 | sevanspowell |
93710bca8319031063d93ccf1a196ae4359500c4 | 1,381 | hpp | C++ | lib/why3cpp/private/whyml-lextract-listener.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | 8 | 2018-07-13T07:07:08.000Z | 2021-05-18T17:56:59.000Z | lib/why3cpp/private/whyml-lextract-listener.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | null | null | null | lib/why3cpp/private/whyml-lextract-listener.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | null | null | null | #ifndef LIB_WHY3CPP__LOCAL_INCLUDE__L_EXTRACT_LISTENER_HPP
#define LIB_WHY3CPP__LOCAL_INCLUDE__L_EXTRACT_LISTENER_HPP
#include <WhyMLBaseListener.h>
#include "whyml-type-visitor.hpp"
class LextractWhyMLListener : public WhyMLBaseListener {
map<string, string> literals;
stack<pair<string, string>> lstack;
public:
LextractWhyMLListener() {}
inline const map<string, string>& getLiterals() {
unstack();
return literals;
}
inline void unstack() {
while (!lstack.empty()) {
literals.insert(lstack.top());
lstack.pop();
}
}
virtual void exitInteger(WhyMLParser::IntegerContext* ctx) override {
lstack.push(pair<string, string>(ctx->INTEGER()->getText(), INT_TYPESTR));
}
virtual void exitReal(WhyMLParser::RealContext* ctx) override {
lstack.push(pair<string, string>(ctx->REAL()->getText(), REAL_TYPESTR));
}
virtual void exitPriority_expr_tight(WhyMLParser::Priority_expr_tightContext* ctx) override {
if (!lstack.empty() && ctx->tightop() != nullptr) {
// Tight operator extraction
lstack.top().first = ctx->tightop()->getText() + lstack.top().first;
lstack.top().second = prefixTypeConversion(ctx->tightop()->getText(), lstack.top().second);
} else {
unstack();
}
}
};
#endif
| 30.021739 | 103 | 0.645185 | sellamiy |
9373fe179f73403d0d7e13d85b99cb7a94c7332b | 3,797 | hpp | C++ | libs/renderer/include/Skybox.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | null | null | null | libs/renderer/include/Skybox.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | null | null | null | libs/renderer/include/Skybox.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | 1 | 2021-03-21T16:52:22.000Z | 2021-03-21T16:52:22.000Z | #ifndef SKYBOX_H
#define SKYBOX_H
#include <glad/glad.h> // holds all OpenGL type declarations
#include <glm/glm.hpp>
#include <vector>
class Skybox
{
public:
Skybox()
{
}
Skybox(vector<std::string> faces)
{
LoadCubemap(faces);
SetupSkybox();
}
void DrawSkybox(unsigned int shaderID)
{
glDepthFunc(GL_LEQUAL);
// skybox cube
glBindVertexArray(skyboxVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS);
glActiveTexture(GL_TEXTURE0);
}
void ActivateTexture()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
}
private:
unsigned int cubemapTexture;
unsigned int skyboxVAO, skyboxVBO;
void LoadCubemap(vector<std::string> faces)
{
glGenTextures(1, &cubemapTexture);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
void SetupSkybox()
{
float skyboxVertices[] =
{
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
glGenVertexArrays(1, &skyboxVAO);
glGenBuffers(1, &skyboxVBO);
glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
}
};
#endif SKYBOX_H | 28.765152 | 126 | 0.51725 | Sharpyfile |
93740f1fd09685bf8a244b2c138b953501436c45 | 4,389 | cpp | C++ | src/mfx/cmd/lat/TreeList.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/cmd/lat/TreeList.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/cmd/lat/TreeList.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
TreeList.cpp
Author: Laurent de Soras, 2019
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "mfx/cmd/lat/GraphInterface.h"
#include "mfx/cmd/lat/Node.h"
#include "mfx/cmd/lat/Tools.h"
#include "mfx/cmd/lat/TreeList.h"
#include <cassert>
namespace mfx
{
namespace cmd
{
namespace lat
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
void TreeList::init (GraphInterface &graph)
{
const int nbr_nodes = graph.get_nbr_nodes ();
_info_list.clear (); // Max nbr trees = nbr nodes
_node_list.resize (nbr_nodes);
_nbr_trees = 0;
int node_start = 0;
int node_list_start_index = 0;
while (node_start < nbr_nodes)
{
const Node & node = graph.use_node (node_start);
if (! node.is_tree_set ())
{
assert (_nbr_trees == int (_info_list.size ()));
_info_list.emplace_back (node_list_start_index);
TreeInfo & tree_info = _info_list.back ();
build_rec (graph, node_start, _nbr_trees);
node_list_start_index += tree_info._nbr_nodes;
assert (node_list_start_index <= nbr_nodes);
++ _nbr_trees;
}
++ node_start;
}
_info_list.resize (_nbr_trees);
}
void TreeList::restore ()
{
_info_list.clear ();
_node_list.clear ();
_nbr_trees = -1;
}
int TreeList::get_nbr_trees () const
{
assert (_nbr_trees >= 0);
return _nbr_trees;
}
int TreeList::get_nbr_nodes (int tree) const
{
assert (tree >= 0);
assert (tree < get_nbr_trees ());
const TreeInfo & tree_info = _info_list [tree];
const int nbr_nodes = tree_info._nbr_nodes;
assert (nbr_nodes > 0);
return nbr_nodes;
}
int TreeList::get_node (int tree, int index) const
{
assert (tree >= 0);
assert (tree < get_nbr_trees ());
assert (index >= 0);
assert (index < get_nbr_nodes (tree));
const TreeInfo & tree_info = _info_list [tree];
const int pos = tree_info._start_index + index;
const int node_index = _node_list [pos];
return node_index;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
TreeList::TreeInfo::TreeInfo (int start_index)
: _nbr_nodes (0)
, _start_index (start_index)
{
assert (start_index >= 0);
}
void TreeList::build_rec (GraphInterface &graph, int node_index, int cur_tree)
{
assert (node_index >= 0);
assert (node_index < graph.get_nbr_nodes ());
assert (cur_tree >= 0);
assert (cur_tree < int (_info_list.size ()));
assert (cur_tree <= _nbr_trees);
// Associates node to current tree
Node & node = graph.use_node (node_index);
node.set_tree (cur_tree);
TreeInfo & tree_info = _info_list [cur_tree];
// Puts current node index into the node list of this tree
const int node_list_index =
tree_info._start_index + tree_info._nbr_nodes;
_node_list [node_list_index] = node_index;
++ tree_info._nbr_nodes;
// Explores adjacent nodes
for (int dir_cnt = 0; dir_cnt < piapi::Dir_NBR_ELT; ++dir_cnt)
{
const piapi::Dir dir = static_cast <piapi::Dir> (dir_cnt);
const int nbr_cnx = node.get_nbr_cnx (dir);
for (int cnx_pos = 0; cnx_pos < nbr_cnx; ++cnx_pos)
{
const int next_node_index = Tools::get_next_node (
graph,
node_index,
dir,
cnx_pos
);
const Node & next_node = graph.use_node (next_node_index);
if (! next_node.is_tree_set ())
{
build_rec (graph, next_node_index, cur_tree);
}
}
}
}
} // namespace lat
} // namespace cmd
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 21.945 | 78 | 0.57553 | mikelange49 |
9374a2124793d3532000d617cc30248de7baefb5 | 13,428 | hxx | C++ | c++/laolrt/laol/rt/primitives.hxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | c++/laolrt/laol/rt/primitives.hxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | c++/laolrt/laol/rt/primitives.hxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright 2017 kpfalzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* File: primitives.hxx
* Author: kpfalzer
*
* Created on May 15, 2017, 9:50 AM
*/
#ifndef _laol_rt_primitives_hxx_
#define _laol_rt_primitives_hxx_
#include "laol/rt/laol.hxx"
namespace laol {
namespace rt {
//NOTE: while we have these discrete primitive types; we do not (yet?!)
//have proper operator overloads to allow "Int op UnsignedInt"...
class Int;
class UnsignedInt;
class LongInt;
class UnsignedLongInt;
class Char;
class Float;
class Double;
class Bool : public virtual Laol {
public:
explicit Bool(bool val) : m_val(val) {
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
return !m_val;
}
virtual LaolObj complement(const LaolObj&, const LaolObj&) const override {
return ~m_val;
}
virtual std::ostream& print(std::ostream& os) const override {
os << (m_val ? "true" : "false");
return os;
}
//allow copy constructors
const bool m_val;
};
struct INumber : public virtual Laol {
enum EType {
eInt, eUnsignedInt, eLongInt, eUnsignedLongInt,
eChar,
eFloat, eDouble
};
virtual EType getType() const = 0;
template<typename GETFN>
static LaolObj getIntVal(const LaolObj& op, const EType type, GETFN rcvr);
template<typename GETFN>
static LaolObj getIntVal(const LaolObj& op, GETFN rcvr) {
return getIntVal(op, op.toType<INumber>().getType(), rcvr);
}
template<typename GETFN>
static LaolObj getVal(const LaolObj& op, const EType type, GETFN rcvr);
template<typename GETFN>
static LaolObj getVal(const LaolObj& op, GETFN rcvr) {
return getVal(op, op.toType<INumber>().getType(), rcvr);
}
static int toInt(const LaolObj& v);
static unsigned int toUnsignedInt(const LaolObj& v);
static long int toLongInt(const LaolObj& v);
static unsigned long int toUnsignedLongInt(const LaolObj& v);
static double toDouble(const LaolObj& v);
static float toFloat(const LaolObj& v);
};
template<typename T>
class IntBase : public INumber {
public:
explicit IntBase(T val) : m_val(val) {
}
/* Integer only operations
*/
virtual LaolObj left_shift(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val << bb;
});
}
virtual LaolObj right_shift(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val >> bb;
});
}
virtual LaolObj modulus(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val % bb;
});
}
virtual LaolObj logical_and(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val && bb;
});
}
virtual LaolObj logical_or(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val || bb;
});
}
virtual LaolObj bitwise_and(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val & bb;
});
}
virtual LaolObj bitwise_or(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val | bb;
});
}
virtual LaolObj bitwise_xor(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val ^ bb;
});
}
virtual LaolObj complement(const LaolObj&, const LaolObj&) const override {
return ~m_val;
}
// Generate specializations for Int here for performance
virtual LaolObj post_increment(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val++;
}
virtual LaolObj post_decrement(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val--;
}
virtual LaolObj pre_increment(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val + 1;
return self;
}
virtual LaolObj pre_decrement(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val - 1;
return self;
}
virtual LaolObj add(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val + bb;
});
}
virtual LaolObj subtract(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val - bb;
});
}
virtual LaolObj multiply(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val * bb;
});
}
virtual LaolObj divide(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val / bb;
});
}
virtual LaolObj equal(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val == bb;
});
}
virtual LaolObj less(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val < bb;
});
}
virtual LaolObj greater(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val > bb;
});
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
//For an expression e,
//the unary expression !e is equivalent to the expression (e == 0)
return (m_val != 0);
}
virtual std::ostream& print(std::ostream& os) const override {
os << m_val;
return os;
}
private:
friend class INumber;
T m_val;
};
template<typename T>
class FloatBase : public INumber {
public:
explicit FloatBase(T val) : m_val(val) {
}
// Generate specializations for Float here for performance
virtual LaolObj post_increment(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val++;
}
virtual LaolObj post_decrement(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val--;
}
virtual LaolObj pre_increment(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val + 1;
return self;
}
virtual LaolObj pre_decrement(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val - 1;
return self;
}
virtual LaolObj add(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val + bb;
});
}
virtual LaolObj subtract(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val - bb;
});
}
virtual LaolObj multiply(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val * bb;
});
}
virtual LaolObj divide(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val / bb;
});
}
virtual LaolObj equal(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val == bb;
});
}
virtual LaolObj less(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val < bb;
});
}
virtual LaolObj greater(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val > bb;
});
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
//For an expression e,
//the unary expression !e is equivalent to the expression (e == 0)
return (m_val != 0);
}
virtual std::ostream& print(std::ostream& os) const override {
os << m_val;
return os;
}
private:
friend class INumber;
T m_val;
};
#define DEFINE_INTS(_cls, _prim) \
class _cls : public IntBase<_prim> { \
public: explicit _cls(_prim val) : IntBase(val) {} \
EType getType() const override {return e##_cls ;} \
}
DEFINE_INTS(Int, int);
DEFINE_INTS(UnsignedInt, unsigned int);
DEFINE_INTS(LongInt, long int);
DEFINE_INTS(UnsignedLongInt, unsigned long int);
DEFINE_INTS(Char, char);
#undef DEFINE_INTS
#define DEFINE_FLOATS(_cls, _prim) \
class _cls : public FloatBase<_prim> { \
public: explicit _cls(_prim val) : FloatBase(val) {} \
EType getType() const override {return e##_cls ;} \
}
DEFINE_FLOATS(Float, float);
DEFINE_FLOATS(Double, double);
#undef DEFINE_FLOATS
template<typename GETFN>
LaolObj
INumber::getIntVal(const LaolObj& op, const EType type, GETFN rcvr) {
switch (type) {
case eInt:
return rcvr(op.toType<Int>().m_val);
case eUnsignedInt:
return rcvr(op.toType<UnsignedInt>().m_val);
case eLongInt:
return rcvr(op.toType<LongInt>().m_val);
case eUnsignedLongInt:
return rcvr(op.toType<UnsignedLongInt>().m_val);
case eChar:
return rcvr(op.toType<Char>().m_val);
default:
ASSERT_NEVER;
}
return NULLOBJ;
}
template<typename GETFN>
LaolObj
INumber::getVal(const LaolObj& op, const EType type, GETFN rcvr) {
switch (type) {
case eFloat:
return rcvr(op.toType<Float>().m_val);
case eDouble:
return rcvr(op.toType<Double>().m_val);
default:
return getIntVal(op, type, rcvr);
}
return NULLOBJ;
}
}
}
#endif /* _laol_rt_primitives_hxx_ */
| 33.994937 | 96 | 0.524873 | gburdell |
9374f01b5eaee6710c7a94d56f031e5a5859ed9f | 48,416 | cpp | C++ | src/CX_Synth.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | 7 | 2015-02-19T21:21:34.000Z | 2022-03-18T13:38:20.000Z | src/CX_Synth.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | null | null | null | src/CX_Synth.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | 4 | 2018-02-16T12:56:13.000Z | 2022-03-23T01:27:33.000Z | #include "CX_Synth.h"
namespace CX {
namespace Synth {
// Initial id is 0.
uint64_t ModuleControlData::_nextId = 1;
/*! The sinc function, defined as `sin(x)/x`. */
double sinc(double x) {
return sin(x) / x;
}
/*! This function returns the frequency that is `semitoneDifference` semitones from `f`.
\param f The starting frequency.
\param semitoneDifference The difference (positive or negative) from `f` to the desired output frequency.
\return The final frequency. */
double relativeFrequency(double f, double semitoneDifference) {
return f * pow(2.0, semitoneDifference / 12);
}
/*! This operator is used to connect modules together. `l` is set as the input for `r`.
\code{.cpp}
Oscillator osc;
StreamOutput out;
osc >> out; //Connect osc as the input for out.
\endcode
*/
ModuleBase& operator>> (ModuleBase& l, ModuleBase& r) {
r._assignInput(&l);
l._assignOutput(&r);
return r;
}
/*! This operator connects a module to the module parameter. It is not possible to connect a module
parameter as an input for anything: They are dead ends.
\code{.cpp}
using namespace CX::Synth;
Oscillator osc;
Envelope fenv;
Adder add;
add.amount = 500;
fenv >> add >> osc.frequency; //Connect the envelope as the input for the frequency of the oscillator with an offset of 500 Hz.
\endcode
*/
void operator>>(ModuleBase& l, ModuleParameter& r) {
r._input = &l;
r._owner->_setDataIfNotSet(&l);
}
////////////////
// ModuleBase //
////////////////
/*! This function should be overloaded for any derived class that can be used as the input for another module.
\return The value of the next sample from the module. */
double ModuleBase::getNextSample(void) {
return 0;
}
/*! This function sets the data needed by this module in order to function properly. Many modules need this data,
specifically the sample rate that the synth using. If several modules are connected together, you will only need
to set the data for one module and the change will propagate to the other connected modules automatically.
This function does not usually need to be called driectly by the user. If an appropriate input or output is
connected, the data will be set from that module. However, there are some cases where a pattern of reconnecting
previously used modules may result in inappropriate sample rates being set. For that reason, if you are having
a problem with seeing the correct sample rate after reconnecting some modules, try manually calling setData().
\param d The data to set.
*/
void ModuleBase::setData(std::shared_ptr<ModuleControlData> mcd) {
_mcd = mcd;
_dataSet(nullptr);
}
/*! Gets the data used by the module. */
std::shared_ptr<ModuleControlData> ModuleBase::getData(void) {
return _mcd;
}
/*! Disconnect a module that is an input to this module. This is a reciprocal operation:
This module's input is disconnected and `in`'s output to this module is disconnected. */
void ModuleBase::disconnectInput(ModuleBase* in) {
auto input = std::find(_inputs.begin(), _inputs.end(), in);
if (input != _inputs.end()) {
ModuleBase* inputModule = *input;
_inputs.erase(input);
inputModule->disconnectOutput(this);
}
}
/*! Disconnect a module that this module outputs to. This is a reciprocal operation:
This module's output is disconnected and `out`'s input from this module is disconnected. */
void ModuleBase::disconnectOutput(ModuleBase* out) {
auto output = std::find(_outputs.begin(), _outputs.end(), out);
if (output != _outputs.end()) {
ModuleBase* outputModule = *output;
_outputs.erase(output);
outputModule->disconnectInput(this);
}
}
/*! \brief Fully disconnect a module from all inputs and outputs. */
void ModuleBase::disconnect(void) {
while (_inputs.size() > 0) {
this->disconnectInput(_inputs[0]);
}
while (_outputs.size() > 0) {
this->disconnectOutput(_outputs[0]);
}
}
/*! Assigns a module as an input to this module. This is not a reciprocal operation.
\param in The module to assign as an input. */
void ModuleBase::_assignInput(ModuleBase* in) {
if (_maxInputs() == 0) {
return;
}
if (std::find(_inputs.begin(), _inputs.end(), in) == _inputs.end()) { //If it is not in the vector, try to add it.
if (_inputs.size() == _maxInputs()) { //If the vector is full, pop off an element before adding the new one.
disconnectInput(_inputs.back());
}
_inputs.push_back(in);
_setDataIfNotSet(in);
_inputAssignedEvent(in);
}
}
/*! Assigns a module as an output from this module. This is not a reciprocal operation.
\param out The module to asssign as an output. */
void ModuleBase::_assignOutput(ModuleBase* out) {
if (_maxOutputs() == 0) {
return;
}
if (std::find(_outputs.begin(), _outputs.end(), out) == _outputs.end()) {
if (_outputs.size() == _maxOutputs()) {
disconnectOutput(_outputs.back());
}
_outputs.push_back(out);
_setDataIfNotSet(out);
_outputAssignedEvent(out);
}
}
/*! This function is called on a module after the data for that module has been set.
\param caller The module that set the data for this module. */
void ModuleBase::_dataSet(ModuleBase* caller) {
this->_dataSetEvent();
for (unsigned int i = 0; i < _inputs.size(); i++) {
if (_inputs[i] != nullptr && _inputs[i] != caller) {
_setDataIfNotSet(_inputs[i]);
}
}
for (unsigned int i = 0; i < _outputs.size(); i++) {
if (_outputs[i] != nullptr && _outputs[i] != caller) {
_setDataIfNotSet(_outputs[i]);
}
}
for (unsigned int i = 0; i < _parameters.size(); i++) {
if (_parameters[i]->_input != nullptr) {
_setDataIfNotSet(_parameters[i]->_input);
}
}
}
/*! This function sets the data for a target module if the data for that module has not been set.
\param target The target module to set the data for. */
void ModuleBase::_setDataIfNotSet(ModuleBase* target) {
// this is uninitialized: Do nothing
if (this->_mcd == nullptr) {
return;
}
// target is uninitialized: Set it to this
if (target->_mcd == nullptr) {
target->_mcd = this->_mcd; // copy pointer
target->_dataSet(this);
return;
}
if (this->_mcd->isNewerThan(*target->_mcd)) {
// target is older; update it
target->_mcd = this->_mcd; // copy pointer
target->_dataSet(this);
return;
}
}
/*! This function is a sort of callback that is called whenever _dataSet is called. Within this
function, you should do things for your module that depend on the new data values. You should
not attempt to propagate the data values to inputs, outputs, or parameters: that is all done
for you. */
void ModuleBase::_dataSetEvent(void) {
return;
}
/*! If you are using a CX::Synth::ModuleParameter in your module, you must register that ModuleParameter
during construction (or setup) of the module using this function.
\code{.cpp}
class MyModule : public ModuleBase {
public:
MyModule(void) {
this->_registerParameter(&myParam);
//...
}
ModuleParameter myParam;
//...
};
\endcode
*/
void ModuleBase::_registerParameter(ModuleParameter* p) {
if (std::find(_parameters.begin(), _parameters.end(), p) == _parameters.end()) {
_parameters.push_back(p);
p->_owner = this;
}
}
/*! Returns the maximum number of inputs to this module. */
unsigned int ModuleBase::_maxInputs(void) {
return 1;
}
/*! Returns the maximum numer of outputs from this module. */
unsigned int ModuleBase::_maxOutputs(void) {
return 1;
}
/*! Does nothing by default, but can be overridden by inheriting classes. */
void ModuleBase::_inputAssignedEvent(ModuleBase* in) {
return;
}
/*! Does nothing by default, but can be overridden by inheriting classes. */
void ModuleBase::_outputAssignedEvent(ModuleBase* out) {
return;
}
/////////////////////
// ModuleParameter //
/////////////////////
/*! \brief Construct a ModuleParameter with no value. */
ModuleParameter::ModuleParameter(void) :
_owner(nullptr),
_input(nullptr),
_updated(true),
_value(0)
{}
/*! \brief Construct a ModuleParameter with the given start value. */
ModuleParameter::ModuleParameter(double d) :
_owner(nullptr),
_input(nullptr),
_updated(true),
_value(d)
{}
/*! Update the value of the module parameter. This gets the next sample from the module
that is the input for the ModuleParameter, if any. */
void ModuleParameter::updateValue(void) {
if (_input != nullptr) { //If there is no input connected, just keep the same value.
double temp = _input->getNextSample();
if (temp != _value) {
_value = temp;
_updated = true;
}
}
}
/*! Returns `true` if the value of the ModuleParameter has been updated since the last time
this function was called. This should be called right after updateValue() or with `checkForUpdates = true`.
Updates to the value resulting from assignment of a new value with `operator=()` count as updates
to the value.
If you don't care whether the value has been updated before using it, don't call this function.
Instead, just use updateValue() and getValue().
\param checkForUpdates Check for updates before determining whether the value has been updated.
\return `true` if the value has been updated since the last check.
*/
bool ModuleParameter::valueUpdated(bool checkForUpdates) {
if (checkForUpdates) {
updateValue();
}
if (_updated) {
_updated = false;
return true;
}
return false;
}
/*! Gets the current value of the parameter. */
double& ModuleParameter::getValue(void) {
return _value;
}
/*! \brief Implicitly converts the parameter to `double`. */
ModuleParameter::operator double(void) {
return _value;
}
/*! \brief Assign a value to the parameter. */
ModuleParameter& ModuleParameter::operator=(double d) {
_value = d;
_updated = true;
_input = nullptr; //Disconnect the input
return *this;
}
///////////
// Adder //
///////////
Adder::Adder(void) :
amount(0)
{
this->_registerParameter(&amount);
}
Adder::Adder(double amount_) :
Adder()
{
amount = amount_;
}
double Adder::getNextSample(void) {
amount.updateValue();
if (_inputs.size() > 0) {
return amount.getValue() + _inputs.front()->getNextSample();
}
return amount.getValue();
}
///////////////////
// AdditiveSynth //
///////////////////
AdditiveSynth::AdditiveSynth(void) :
fundamental(1)
{
this->_registerParameter(&fundamental);
}
double AdditiveSynth::getNextSample(void) {
double rval = 0;
if (fundamental.valueUpdated(true)) {
_recalculateWaveformPositions();
}
for (unsigned int i = 0; i < _harmonics.size(); i++) {
double waveformPos = _harmonics[i].waveformPosition + _harmonics[i].positionChangePerSample;
waveformPos = fmod(waveformPos, 1);
rval += Oscillator::sine(waveformPos) * _harmonics[i].amplitude;
_harmonics[i].waveformPosition = waveformPos;
}
return rval;
}
/*! This function sets the amplitudes of the harmonics based on the chosen type. The resulting waveform
will only be correct if the harmonic series is the standard harmonic series (see setStandardHarmonicSeries()).
\param a The type of wave calculate amplitudes for.
*/
void AdditiveSynth::setAmplitudes(AmplitudePresets a) {
vector<double> amps = calculateAmplitudes(a, _harmonics.size());
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = amps[i];
}
}
/*! This function sets the amplitudes of the harmonics based on a mixture of the chosen types. The resulting waveform
will only be correct if the harmonic series is the standard harmonic series (see setStandardHarmonicSeries()).
This is a convenient way to morph between waveforms.
\param a1 The first preset.
\param a2 The second present.
\param mixture Should be in the interval [0,1]. The proportion of `a1` that will be used, with the remainder (`1 - mixture`) used from `a2`.
*/
void AdditiveSynth::setAmplitudes(AmplitudePresets a1, AmplitudePresets a2, double mixture) {
vector<double> amps1 = calculateAmplitudes(a1, _harmonics.size());
vector<double> amps2 = calculateAmplitudes(a2, _harmonics.size());
mixture = CX::Util::clamp<double>(mixture, 0, 1);
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = (amps1[i] * mixture) + (amps2[i] * (1 - mixture));
}
}
/*! This function sets the amplitudes of the harmonics to arbitrary values as specified in `amps`.
\param amps The amplitudes of the harmonics. If this vector does not contain as many values as
there are harmonics, the unspecified amplitudes will be set to 0.
*/
void AdditiveSynth::setAmplitudes(std::vector<double> amps) {
while (amps.size() < _harmonics.size()) {
amps.push_back(0.0);
}
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = amps[i];
}
}
/*! This is a specialty function that only works when the standard harmonic series is being used. If so,
it calculates the amplitudes needed for the hamonics so as to produce the specified waveform type.
\param a The type of waveform that should be output from the additive synth.
\param count The number of harmonics.
\return A vector of amplitudes.
*/
std::vector<double> AdditiveSynth::calculateAmplitudes(AmplitudePresets a, unsigned int count) {
std::vector<double> rval(count, 0.0);
if (a == AmplitudePresets::SAW) {
for (unsigned int i = 0; i < count; i++) {
rval[i] = 2 / (PI * (i + 1));
if ((i % 2) == 1) { //Is even-numbered harmonic
rval[i] *= -1;
}
}
} else if (a == AmplitudePresets::SQUARE) {
for (unsigned int i = 0; i < count; i++) {
if ((i % 2) == 0) { //Is odd-numbered harmonic
//rval[i] = 2 / (PI * (i + 1));
rval[i] = 4 / (PI * (i + 1));
}
//Do nothing for even harmonics: they remain at 0.
}
} else if (a == AmplitudePresets::TRIANGLE) {
for (unsigned int i = 0; i < count; i++) {
if ((i % 2) == 0) { //Is odd-numbered harmonic
rval[i] = 8 / ((PI * PI) * pow(i + 1, 2));
if (((i / 2) % 2) == 1) {
rval[i] *= -1;
}
}
//Do nothing for even harmonics: they remain at 0.
}
} else if (a == AmplitudePresets::SINE) {
rval[0] = 1;
}
return rval;
}
/*! This function removes all harmonics that have an amplitude that is less than or equal to a tolerance
times the amplitude of the harmonic with the greatest absolute amplitude. The result of this pruning is that
the synthesizer will be more computationally efficient but provide a less precise approximation of the desired
waveform.
\param tol `tol` is interpreted differently depending on its value. If `tol` is greater than or equal to 0, it is treated
as a proportion of the amplitude of the frequency with the greatest amplitude. If `tol` is less than 0, it is treated as
the difference in decibels between the frequency with the greatest amplitude and the tolerance cutoff point.
\note Because only harmonics with an amplitude less than or equal to the tolerance times an amplitude are pruned,
setting `tol` to 0 will remove harmonics with 0 amplitude, but no others.
*/
void AdditiveSynth::pruneLowAmplitudeHarmonics(double tol) {
double maxAmplitude = 0;
for (unsigned int i = 0; i < _harmonics.size(); i++) {
if (abs(_harmonics[i].amplitude) > maxAmplitude) {
maxAmplitude = abs(_harmonics[i].amplitude);
}
}
if (tol < 0) {
tol = sqrt(pow(10.0f, tol / 10.0f));
}
double cutoffAmplitude = maxAmplitude * tol;
for (unsigned int i = 0; i < _harmonics.size(); i++) {
if (abs(_harmonics[i].amplitude) < cutoffAmplitude) {
_harmonics.erase(_harmonics.begin() + i);
i--;
}
}
}
/*! The standard harmonic series begins with the fundamental frequency f1 and each seccuessive
harmonic has a frequency equal to f1 * n, where n is the harmonic number for the harmonic.
This is the natural harmonic series, one that occurs, e.g., in a vibrating string.
*/
void AdditiveSynth::setStandardHarmonicSeries(unsigned int harmonicCount) {
this->setHarmonicSeries(harmonicCount, HarmonicSeriesType::MULTIPLE, 1.0);
}
/*! Set the harmonic series for the AdditiveSynth.
\param harmonicCount The number of harmonics to use.
\param type The type of harmonic series to generate. Can be either HS_MULTIPLE or HS_SEMITONE. For HS_MULTIPLE, each
harmonic's frequency will be some multiple of the fundamental frequency, depending on the harmonic number and
controlParameter. For HS_SEMITONE, each harmonic's frequency will be some number of semitones above the previous frequency,
based on controlParameter (specifying the number of semitones).
\param controlParameter If `type == HS_MULTIPLE`, the frequency for harmonic `i` will be `i * controlParameter`, where the
fundamental gives the value 1 for `i`. If `type == HS_SEMITONE`, the frequency for harmonic `i` will be
`pow(2, (i - 1) * controlParameter/12)`, where the fundamental gives the value 1 for `i`.
\note If `type == HS_MULTIPLE` and `controlParameter == 1`, then the standard harmonic series will be generated.
\note If `type == HS_SEMITONE`, `controlParameter` does not need to be an integer.
*/
void AdditiveSynth::setHarmonicSeries(unsigned int harmonicCount, HarmonicSeriesType type, double controlParameter) {
_harmonics.resize(harmonicCount);
if (type == HarmonicSeriesType::MULTIPLE) {
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = (i + 1) * controlParameter;
}
} else if (type == HarmonicSeriesType::SEMITONE) {
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = pow(2.0, i * controlParameter / 12);
}
}
_recalculateWaveformPositions();
}
/*! This function applies the harmonic series from a vector of harmonics supplied by the user.
\param harmonicSeries A vector frequencies that create a harmonic series. These values
will be multiplied by the fundamental frequency in order to obtain the final frequency
of each harmonic. The multiplier for the first harmonic is at index 0, so by convention
you might want to set harmonicSeries[0] equal to 1, so that when the fundamental frequency
is set with setFundamentalFrequency(), the first harmonic is actually the fundamental
frequency, but this is not enforced.
\note If `harmonicSeries.size()` is greater than the current number of harmonics, the
new harmonics will have an amplitude of 0. If `harmonicSeries.size()` is less than the
current number of harmonics, the number of harmonics will be reduced to the size of
`harmonicSeries`.
*/
void AdditiveSynth::setHarmonicSeries(std::vector<double> harmonicSeries) {
_harmonics.resize(harmonicSeries.size());
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = harmonicSeries[i];
}
_recalculateWaveformPositions();
}
void AdditiveSynth::_recalculateWaveformPositions(void) {
double firstHarmonicPos = _harmonics[0].waveformPosition;
double normalizedFrequency = fundamental.getValue() / _mcd->getOversamplingSampleRate();
for (unsigned int i = 0; i < _harmonics.size(); ++i) {
double relativeFrequency = _harmonics[i].relativeFrequency;
_harmonics[i].positionChangePerSample = normalizedFrequency * relativeFrequency;
_harmonics[i].waveformPosition = firstHarmonicPos * relativeFrequency; //This keeps the harmonics in phase
}
}
void AdditiveSynth::_dataSetEvent(void) {
_recalculateWaveformPositions();
}
/////////////
// Clamper //
/////////////
Clamper::Clamper(void) :
low(-1),
high(1)
{
this->_registerParameter(&low);
this->_registerParameter(&high);
}
Clamper::Clamper(double low_, double high_) :
Clamper()
{
low = low_;
high = high_;
}
double Clamper::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
double temp = this->_inputs.front()->getNextSample();
low.updateValue();
high.updateValue();
return Util::clamp<double>(temp, low.getValue(), high.getValue());
}
//////////////
// Envelope //
//////////////
Envelope::Envelope(void) :
gateInput(0.5),
_stage(4)
{
this->_registerParameter(&gateInput);
this->_registerParameter(&a);
this->_registerParameter(&d);
this->_registerParameter(&s);
this->_registerParameter(&r);
}
Envelope::Envelope(double a_, double d_, double s_, double r_) :
Envelope()
{
a = a_;
d = d_;
s = s_;
r = r_;
}
double Envelope::getNextSample(void) {
if (gateInput.valueUpdated(true)) {
if (gateInput.getValue() == 1.0) {
this->attack();
} else if (gateInput.getValue() == 0.0) {
this->release();
}
}
if (_stage > 3) {
return 0;
}
if (a.valueUpdated(true)) {
_a = a.getValue();
}
if (d.valueUpdated(true)) {
_d = d.getValue();
}
if (s.valueUpdated(true)) {
_s = s.getValue();
}
if (r.valueUpdated(true)) {
_r = r.getValue();
}
//p is the proportion of the envelope, that controls e.g. how loud the output is.
double p = _lastP; //In case somehow none of the cases is hit, the level is just the last level
switch (_stage) {
//Attack:
case 0:
//If within the attack time
if ((_timeSinceLastStage < _a) && (_a != 0)) {
//The proportion is the amount of time spent in attack so far divided by the length of the attack
p = _timeSinceLastStage / _a;
break;
} else {
_timeSinceLastStage = 0;
_stage++;
//Intentional fall through
}
//Decay:
case 1:
//If within the decay time
if ((_timeSinceLastStage < _d) && (_d != 0)) {
//The proportion the linear interpolation between the max (1) and the sustain
//level (_s) as a function of time in the decay stage
p = 1 - (_timeSinceLastStage / _d) * (1 - _s);
break;
} else {
_timeSinceLastStage = 0;
_stage++;
//Intentional fall through
}
//Sustain:
case 2:
p = _s; //The proportion is just the sustain level. Sustain lasts indefinitely until another event ends the sustain.
break;
//Release:
case 3:
//If within the release time
if ((_timeSinceLastStage < _r) && (_r != 0)) {
//The p is the linear interpolation between the level that the envelope was at when the release
//happened (not neccessarily the sustain level!) as a function of time in the release stage
p = (1 - _timeSinceLastStage / _r) * _levelAtRelease;
break;
} else {
//_timeSinceLastStage = 0;
_stage++;
p = 0;
}
}
_lastP = p;
_timeSinceLastStage += _timePerSample;
double val;
if (_inputs.size() > 0) {
val = _inputs.front()->getNextSample();
} else {
val = 1;
}
return val * p;
}
/*! \brief Trigger the attack of the Envelope. */
void Envelope::attack(void) {
_stage = 0;
_timeSinceLastStage = 0;
}
/*! \brief Trigger the release of the Envelope. */
void Envelope::release(void) {
_stage = 3;
_timeSinceLastStage = 0;
_levelAtRelease = _lastP;
}
void Envelope::_dataSetEvent(void) {
_timePerSample = 1.0 / _mcd->getOversamplingSampleRate();
}
////////////
// Filter //
////////////
Filter::Filter(void) :
cutoff(1000),
bandwidth(50),
_filterType(FilterType::LOW_PASS),
x1(0),
x2(0),
y1(0),
y2(0)
{
this->_registerParameter(&cutoff);
this->_registerParameter(&bandwidth);
}
Filter::Filter(Filter::FilterType type, double cutoff_, double bandwidth_) :
Filter()
{
cutoff = cutoff_;
if (bandwidth_ < 0) {
bandwidth = cutoff_ / 10;
} else {
bandwidth = bandwidth_;
}
setType(type);
}
/*! \brief Set the type of filter to use, from the Filter::FilterType enum. */
void Filter::setType(FilterType type) {
_filterType = type;
_recalculateCoefficients();
}
double Filter::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
if (cutoff.valueUpdated(true) || bandwidth.valueUpdated(true)) {
_recalculateCoefficients();
}
double x0 = _inputs.front()->getNextSample();
double y0;
if (_filterType == FilterType::LOW_PASS || _filterType == FilterType::HIGH_PASS) {
//a2 and b2 are always 0 for LOW_PASS and HIGH_PASS, so they are omitted from the calculation.
y0 = a0*x0 + a1*x1 + b1*y1;
y1 = y0;
x1 = x0;
} else {
y0 = a0*x0 + a1*x1 + a2*x2 + b1*y1 + b2*y2;
y2 = y1;
y1 = y0;
x2 = x1;
x1 = x0;
}
return y0;
}
void Filter::_recalculateCoefficients(void) {
if (_mcd == nullptr) {
return;
}
double frequencyDivisor = _mcd->getOversamplingSampleRate();
double f_angular = 2 * PI * cutoff.getValue() / frequencyDivisor; //Normalized angular frequency
if (_filterType == FilterType::LOW_PASS || _filterType == FilterType::HIGH_PASS) {
double x = exp(-f_angular);
a2 = 0;
b2 = 0;
if (_filterType == FilterType::LOW_PASS) {
a0 = 1 - x;
a1 = 0;
b1 = x;
} else if (_filterType == FilterType::HIGH_PASS) {
a0 = (1 + x) / 2;
a1 = -(1 + x) / 2;
b1 = x;
}
} else if (_filterType == FilterType::BAND_PASS || _filterType == FilterType::NOTCH) {
double R = 1 - (3 * bandwidth.getValue() / frequencyDivisor); //Bandwidth is normalized
double K = (1 - 2 * R*cos(f_angular) + (R*R)) / (2 - 2 * cos(f_angular));
b1 = 2 * R * cos(f_angular);
b2 = -(R*R);
if (_filterType == FilterType::BAND_PASS) {
a0 = 1 - K;
a1 = 2 * (K - R) * cos(f_angular);
a2 = (R*R) - K;
} else if (_filterType == FilterType::NOTCH) {
a0 = K;
a1 = -2 * K * cos(f_angular);
a2 = K;
}
}
}
///////////
// Mixer //
///////////
double Mixer::getNextSample(void) {
double d = 0;
for (unsigned int i = 0; i < _inputs.size(); i++) {
d += _inputs[i]->getNextSample();
}
return d;
}
unsigned int Mixer::_maxInputs(void) {
return 32;
}
////////////////
// Multiplier //
////////////////
Multiplier::Multiplier(void) :
amount(1)
{
this->_registerParameter(&amount);
}
/*! Convenience constructor.
\param amount_ The amount to multiply the input by.
*/
Multiplier::Multiplier(double amount_) :
amount(amount_)
{
this->_registerParameter(&amount);
}
double Multiplier::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
amount.updateValue();
return _inputs.front()->getNextSample() * amount.getValue();
}
/*! Sets the `amount` of the multiplier based on gain in decibels.
\param decibels The gain to apply. If greater than 0, `amount` will be greater than 1. If less than 0, `amount` will be less than 1.
After calling this function, `amount` will never be negative.
*/
void Multiplier::setGain(double decibels) {
amount = sqrt(pow(10.0, decibels / 10.0));
}
////////////////
// Oscillator //
////////////////
Oscillator::Oscillator(void) :
frequency(0),
_waveformPos(0)
{
this->_registerParameter(&frequency);
setGeneratorFunction(Oscillator::sine);
}
Oscillator::Oscillator(std::function<double(double)> generatorFunction, double frequency_) :
Oscillator()
{
setGeneratorFunction(generatorFunction);
frequency = frequency_;
}
double Oscillator::getNextSample(void) {
frequency.updateValue();
double addAmount = frequency.getValue() / _mcd->getOversamplingSampleRate();
_waveformPos = fmod(_waveformPos + addAmount, 1);
return _generatorFunction(_waveformPos);
}
/*! It is very easy to make your own waveform generating functions to be used with an Oscillator.
A waveform generating function takes a value that represents the location in the waveform at
the current point in time. These values are in the interval [0,1).
The waveform generating function should return a double representing the amplitude of the
wave at the given waveform position.
To put this all together, a sine wave generator looks like this:
\code{.cpp}
double sineWaveGeneratorFunction(double waveformPosition) {
return sin(2 * PI * waveformPosition); //The argument for sin() is in radians. 1 cycle is 2*PI radians.
}
\endcode
*/
void Oscillator::setGeneratorFunction(std::function<double(double)> f) {
_generatorFunction = f;
}
/*! Produces a sawtooth wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::saw(double wp) {
return (2 * wp) - 1;
}
/*! Produces a sine wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::sine(double wp) {
return sin(wp * 2 * PI);
}
/*! Produces a square wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::square(double wp) {
if (wp < .5) {
return 1;
} else {
return -1;
}
}
/*! Produces a triangle wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::triangle(double wp) {
if (wp < .5) {
return ((4 * wp) - 1);
} else {
return (3 - (4 * wp));
}
}
/*! Produces white noise.
\param wp This argument is ignored.
\return A random value in the interval [-1, 1].
*/
double Oscillator::whiteNoise(double wp) {
return CX::Instances::RNG.randomDouble(-1, 1);
}
///////////////////
// RingModulator //
///////////////////
double RingModulator::getNextSample(void) {
if (_inputs.size() == 2) {
double i1 = _inputs[0]->getNextSample();
double i2 = _inputs[1]->getNextSample();
return i1 * i2;
} else if (_inputs.size() == 1) {
return _inputs.front()->getNextSample();
}
return 0;
}
unsigned int RingModulator::_maxInputs(void) {
return 2;
}
//////////////
// Splitter //
//////////////
Splitter::Splitter(void) :
_currentSample(0.0),
_fedOutputs(0)
{}
//The way this works is that each output gets the same value from a single
//input, so only once all of the outputs have been fed do we update the
//sample value. If the splitter is feeding, e.g., two different stream outputs,
//there is the potential for substantial desynchronization. Basically, samples
//from all outputs of the splitter must happen at adjacent times.
double Splitter::getNextSample(void) {
if (_fedOutputs >= _outputs.size()) {
_currentSample = _inputs.front()->getNextSample();
_fedOutputs = 0;
}
_fedOutputs++;
return _currentSample;
}
void Splitter::_outputAssignedEvent(ModuleBase* out) {
_fedOutputs = _outputs.size();
}
//////////////////////
// SoundBufferInput //
//////////////////////
SoundBufferInput::SoundBufferInput(void) :
_sb(nullptr),
_currentSample(0)
{}
SoundBufferInput::SoundBufferInput(CX::CX_SoundBuffer *sb, unsigned int channel) :
SoundBufferInput()
{
setup(sb, channel);
}
/*! This function sets the CX_SoundBuffer from which data will be drawn. Because the SoundBufferInput is monophonic,
you must pick one channel of the CX_SoundBuffer to use.
\param sb The CX_SoundBuffer to use. Because this CX_SoundBuffer is taken as a pointer and is not copied,
you should make sure that `sb` remains in existence and unmodified while the SoundBufferInput is in use.
\param channel The channel of the CX_SoundBuffer to use.
*/
void SoundBufferInput::setup(CX::CX_SoundBuffer *sb, unsigned int channel) {
_sb = sb;
_channel = channel;
this->setData(ModuleControlData::construct(_sb->getSampleRate(), 1));
}
/*! Set the playback time of the current CX_SoundBuffer. When playback starts, it will start from this time.
If playback is in progress, playback will skip to the selected time. */
void SoundBufferInput::setTime(CX::CX_Millis t) {
if (_sb != nullptr) {
unsigned int startSample = _sb->getChannelCount() * (unsigned int)(_sb->getSampleRate() * t.seconds());
_currentSample = startSample + _channel;
} else {
_currentSample = _channel;
}
}
double SoundBufferInput::getNextSample(void) {
if (!this->canPlay()) {
return 0;
}
double value = _sb->getRawDataReference().at(_currentSample);
_currentSample += _sb->getChannelCount();
return value;
}
/*! Checks to see if the CX_SoundBuffer that is associated with this SoundBufferInput is able to play.
It is unable to play if CX_SoundBuffer::isReadyToPlay() is false or if the whole sound has been played.*/
bool SoundBufferInput::canPlay(void) {
return (_sb != nullptr) && (_sb->isReadyToPlay()) && (_currentSample < _sb->getTotalSampleCount());
}
void SoundBufferInput::_dataSetEvent(void) {
if (_mcd->getSampleRate() != _sb->getSampleRate()) {
_sb->resample(_mcd->getSampleRate());
}
if (_mcd->getOversampling() > 1) {
this->setData(ModuleControlData::construct(_mcd->getSampleRate(), 1));
}
}
///////////////////////
// SoundBufferOutput //
///////////////////////
SoundBufferOutput::SoundBufferOutput(float sampleRate, unsigned int oversampling) {
setup(sampleRate, oversampling);
}
/*! Configure the output to use a particular sample rate. If this function is not called, the sample rate
of the modular synth may be undefined.
\param sampleRate The sample rate in Hz. */
void SoundBufferOutput::setup(float sampleRate, unsigned int oversampling) {
this->setData(ModuleControlData::construct(sampleRate, oversampling));
sb.clear();
sb.setFromVector(std::vector<float>(), 1, sampleRate);
}
/*! This function samples `t` milliseconds of data at the sample rate given in setup().
The result is stored in the `sb` member of this class. If `sb` is not empty when this function
is called, the data is appended to `sb`. */
void SoundBufferOutput::sampleData(CX::CX_Millis t, bool clear) {
if (_inputs.size() == 0) {
CX::Instances::Log.warning("SoundBufferOutput") << "sampleData(): Attempted to sample data when no inputs were connected.";
return;
}
if (clear) {
sb.clear();
}
unsigned int samplesToTake = ceil(_mcd->getSampleRate() * t.seconds());
std::vector<float> tempData(samplesToTake);
ModuleBase* input = _inputs.front();
unsigned int oversampling = _mcd->getOversampling();
for (unsigned int i = 0; i < samplesToTake; i++) {
double sum = 0;
for (unsigned int ovs = 0; ovs < oversampling; ovs++) {
sum += input->getNextSample();
}
tempData[i] = CX::Util::clamp<float>(sum / oversampling, -1, 1);
}
//for (unsigned int i = 0; i < samplesToTake; i++) {
// tempData[i] = CX::Util::clamp<float>((float)input->getNextSample(), -1, 1);
//}
if (sb.getTotalSampleCount() == 0) {
sb.setFromVector(tempData, 1, _mcd->getSampleRate());
} else {
std::vector<float>& bufData = sb.getRawDataReference();
bufData.insert(bufData.end(), tempData.begin(), tempData.end());
}
}
/////////////////////////////
// StereoSoundBufferOutput //
/////////////////////////////
StereoSoundBufferOutput::StereoSoundBufferOutput(float sampleRate, unsigned int oversampling) {
setup(sampleRate, oversampling);
}
/*! Configure the output to use a particular sample rate. If this function is not called, the sample rate
of the modular synth may be undefined.
\param sampleRate The sample rate in Hz. */
void StereoSoundBufferOutput::setup(float sampleRate, unsigned int oversampling) {
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(sampleRate, oversampling);
left.setData(mcd);
right.setData(mcd);
sb.clear();
sb.setFromVector(std::vector<float>(), 2, sampleRate);
}
/*! This function samples `t` milliseconds of data at the sample rate given in setup().
The result is stored in the `sb` member of this class. If `sb` is not empty when this function
is called, the data is appended to `sb`. */
void StereoSoundBufferOutput::sampleData(CX::CX_Millis t, bool clear) {
if (clear) {
sb.clear();
}
unsigned int samplesToTake = ceil(left.getData()->getSampleRate() * t.seconds());
unsigned int channels = 2; //Stereo
std::vector<float> tempData(samplesToTake * channels);
// GenericOutput deals with oversampling
for (unsigned int i = 0; i < samplesToTake; i++) {
unsigned int index = i * channels;
tempData[index + 0] = CX::Util::clamp<float>((float)left.getNextSample(), -1, 1);
tempData[index + 1] = CX::Util::clamp<float>((float)right.getNextSample(), -1, 1);
}
if (sb.getTotalSampleCount() == 0) {
sb.setFromVector(tempData, channels, left.getData()->getSampleRate());
} else {
std::vector<float>& bufData = sb.getRawDataReference();
bufData.insert(bufData.end(), tempData.begin(), tempData.end());
}
}
/////////////////
// StreamInput //
/////////////////
StreamInput::StreamInput(void) :
_maxBufferSize(4096),
_soundStream(nullptr),
_listeningForEvents(false)
{}
StreamInput::StreamInput(CX::CX_SoundStream* ss) :
StreamInput()
{
setup(ss);
}
StreamInput::~StreamInput(void) {
_listenForEvents(false);
}
/*! Set up the StreamInput with a CX_SoundStream configured for input.
\param stream A pointer to the sound stream. */
void StreamInput::setup(CX::CX_SoundStream* stream) {
if (stream->getConfiguration().inputChannels != 1) {
CX::Instances::Log.error("StreamInput") << "setInputStream(): The provided stream must be"
"configured with a single input channel, but it is not.";
}
_soundStream = stream;
_listenForEvents(true);
}
double StreamInput::getNextSample(void) {
double rval = 0;
if (_maxBufferSize != 0) {
while (_buffer.size() > _maxBufferSize) {
_buffer.pop_front();
}
}
if (_buffer.size() > 0) {
rval = _buffer.front();
_buffer.pop_front();
}
return rval;
}
/*! \brief Clear the contents of the input buffer. */
void StreamInput::clear(void) {
_buffer.clear();
}
/*! Set the maximum number of samples that the input buffer can contain.
\param size The size of the input buffer, in samples. */
void StreamInput::setMaximumBufferSize(unsigned int size) {
_maxBufferSize = size;
}
void StreamInput::_callback(const CX::CX_SoundStream::InputEventArgs& in) {
for (unsigned int sampleFrame = 0; sampleFrame < in.bufferSize; sampleFrame++) {
_buffer.push_back(in.inputBuffer[sampleFrame]);
}
}
void StreamInput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->inputEvent, this, &StreamInput::_callback);
} else {
ofRemoveListener(_soundStream->inputEvent, this, &StreamInput::_callback);
}
_listeningForEvents = listen;
}
unsigned int StreamInput::_maxInputs(void) {
return 0;
}
//////////////////
// StreamOutput //
//////////////////
StreamOutput::StreamOutput(CX::CX_SoundStream* stream, unsigned int oversampling) {
setup(stream, oversampling);
}
StreamOutput::~StreamOutput(void) {
_listenForEvents(false);
}
/*! Set up the StereoStreamOutput with the given CX_SoundStream.
\param stream A CX_SoundStream that is configured for output to any number of channels. */
void StreamOutput::setup(CX::CX_SoundStream* stream, unsigned int oversampling) {
_soundStream = stream;
_listenForEvents(true);
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(_soundStream->getConfiguration().sampleRate, oversampling);
this->setData(mcd);
}
void StreamOutput::_callback(const CX::CX_SoundStream::OutputEventArgs& d) {
if (_inputs.size() == 0) {
return;
}
ModuleBase* input = _inputs.front();
unsigned int oversampling = _mcd->getOversampling();
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
double sum = 0;
for (unsigned int ovs = 0; ovs < oversampling; ovs++) {
sum += input->getNextSample();
}
double mean = CX::Util::clamp<float>(sum / oversampling, -1, 1);
for (int ch = 0; ch < d.outputChannels; ch++) {
d.outputBuffer[(sample * d.outputChannels) + ch] += mean;
}
}
/*
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
float value;
if (_data->oversampling > 1) {
double sum = 0;
for (unsigned int oversamp = 0; oversamp < _data->oversampling; oversamp++) {
sum += input->getNextSample();
}
double mean = sum / _data->oversampling;
value = CX::Util::clamp<float>(mean, -1, 1);
} else {
value = CX::Util::clamp<float>(input->getNextSample(), -1, 1);
}
for (int ch = 0; ch < d.outputChannels; ch++) {
d.outputBuffer[(sample * d.outputChannels) + ch] += value;
}
}
*/
}
void StreamOutput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->outputEvent, this, &StreamOutput::_callback);
} else {
ofRemoveListener(_soundStream->outputEvent, this, &StreamOutput::_callback);
}
_listeningForEvents = listen;
}
////////////////////////
// StereoStreamOutput //
////////////////////////
StereoStreamOutput::StereoStreamOutput(CX::CX_SoundStream* stream, unsigned int oversampling) {
setup(stream, oversampling);
}
StereoStreamOutput::~StereoStreamOutput(void) {
_listenForEvents(false);
}
/*! Set up the StereoStreamOutput with the given CX_SoundStream.
\param stream A CX_SoundStream that is configured for stereo output. */
void StereoStreamOutput::setup(CX::CX_SoundStream* stream, unsigned int oversampling) {
_soundStream = stream;
_listenForEvents(true);
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(_soundStream->getConfiguration().sampleRate, oversampling);
left.setData(mcd);
right.setData(mcd);
}
void StereoStreamOutput::_callback(const CX::CX_SoundStream::OutputEventArgs& d) {
unsigned int oversampling = left.getData()->getOversampling();
// GenericOutput deals with oversampling
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
unsigned int index = sample * d.outputChannels;
d.outputBuffer[index + 0] += CX::Util::clamp<float>(right.getNextSample(), -1, 1); //The buffers only use float, so clamp with float.
d.outputBuffer[index + 1] += CX::Util::clamp<float>(left.getNextSample(), -1, 1);
}
}
void StereoStreamOutput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->outputEvent, this, &StereoStreamOutput::_callback);
} else {
ofRemoveListener(_soundStream->outputEvent, this, &StereoStreamOutput::_callback);
}
_listeningForEvents = listen;
}
//////////////////////
// TrivialGenerator //
//////////////////////
TrivialGenerator::TrivialGenerator(void) :
value(0),
step(0)
{
this->_registerParameter(&value);
this->_registerParameter(&step);
}
TrivialGenerator::TrivialGenerator(double value_, double step_) :
TrivialGenerator()
{
value = value_;
step = step_;
}
double TrivialGenerator::getNextSample(void) {
value.updateValue();
value.getValue() += step;
return value.getValue() - step;
}
///////////////
// FIRFilter //
///////////////
FIRFilter::FIRFilter(void) :
_filterType(FilterType::LOW_PASS),
_coefCount(-1)
{}
FIRFilter::FIRFilter(FilterType filterType, unsigned int coefficientCount) :
FIRFilter()
{
setup(filterType, coefficientCount);
}
FIRFilter::FIRFilter(const std::vector<double>& coefficients) :
FIRFilter()
{
setup(coefficients);
}
/*! Set up the FIRFilter with the given filter type and number of coefficients to use.
\param filterType Should be a type of filter other than FIRFilter::FilterType::FIR_USER_DEFINED. If you want
to define your own filter type, use FIRFilter::setup(std::vector<double>) instead.
\param coefficientCount The number of coefficients sets the length of time, in samples, that the filter will
produce a non-zero output following an impulse. In other words, the filter operates on `coefficientCount`
samples at a time to produce each output sample.
*/
void FIRFilter::setup(FilterType filterType, unsigned int coefficientCount) {
if (filterType == FIRFilter::FilterType::USER_DEFINED) {
CX::Instances::Log.error("FIRFilter") << "setup(): FilterType::FIR_USER_DEFINED should not be used explicity."
"Use FIRFilter::setup(std::vector<double>) if you want to define your own filter type.";
}
_filterType = filterType;
if ((coefficientCount % 2) == 0) {
coefficientCount++; //Must be odd in this implementation
}
_coefCount = coefficientCount;
_coefficients.assign(_coefCount, 0);
_inputSamples.assign(_coefCount, 0); //Fill with zeroes so that we never have to worry about not having enough input data.
}
/*! You can use this function to supply your own filter coefficients, which allows a great
deal of flexibility in the use of the FIRFilter. See the fir1 and fir2 functions from the
//"signal" package for R for a way to design your own filter.
\param coefficients The filter coefficients to use.
*/
void FIRFilter::setup(const std::vector<double>& coefficients) {
_filterType = FilterType::USER_DEFINED;
_coefficients = coefficients;
_coefCount = coefficients.size();
_inputSamples.assign(_coefCount, 0); //Fill with zeroes so that we never have to worry about not having enough input data.
}
/*! If using either FilterType::LOW_PASS or FilterType::HIGH_PASS, this function allows you to
change the cutoff frequency for the filter. This causes the filter coefficients to be recalculated.
\param cutoff The cutoff frequency, in Hz. */
void FIRFilter::setCutoff(double cutoff) {
if (_filterType != FilterType::LOW_PASS && _filterType != FilterType::HIGH_PASS) {
CX::Instances::Log.warning("FIRFilter") << "setCutoff() should only be used when the filter type is LOW_PASS or HIGH_PASS.";
return;
}
//See https://www.mikroe.com/ebooks/digital-filter-design/finite-impulse-response-fir-filter-design-methods (fairly far down the page, table 2-2-1.)
// TODO: Test the difference (also in setBandCutoffs)
double omega = 2 * PI * cutoff / _mcd->getSampleRate();
//double omega = 2 * PI * cutoff / _mcd->getOversampledSampleRate();
int N = _coefCount - 1; //N is the order of the filter
float M = (float)N / 2;
for (int n = 0; n < _coefCount; n++) {
double hn = 0;
if (n == M) {
if (_filterType == FilterType::LOW_PASS) {
hn = omega / PI;
} else if (_filterType == FilterType::HIGH_PASS) {
hn = 1 - omega / PI;
}
} else {
float dif = n - M;
if (_filterType == FilterType::LOW_PASS) {
hn = sin(omega * dif) / (PI * dif);
} else if (_filterType == FilterType::HIGH_PASS) {
hn = -sin(omega * dif) / (PI * dif);
}
}
_coefficients[n] = hn;
}
_applyWindowToCoefs();
}
/*! Sets the upper and lower cutoffs for a band filter mode (i.e. `BAND_PASS` or `BAND_STOP`).
\param lower The lower end of the band (Hz).
\param upper The upper end of the band (Hz).
*/
void FIRFilter::setBandCutoffs(double lower, double upper) {
if (_filterType != FilterType::BAND_PASS && _filterType != FilterType::BAND_STOP) {
CX::Instances::Log.warning("FIRFilter") << "setBandCutoffs() should only be used when the filter type is BAND_PASS or BAND_STOP.";
return;
}
auto commonF = [](double omega, int dif) -> double {
return sin(omega * dif) / (PI * dif);
};
//Super useful page:
//See https://www.mikroe.com/ebooks/digital-filter-design/finite-impulse-response-fir-filter-design-methods (fairly far down the page, table 2-2-1.)
double oc2 = 2 * PI * lower / _mcd->getSampleRate(); // oversampling?
double oc1 = 2 * PI * upper / _mcd->getSampleRate();
int N = _coefCount - 1; //N is the order of the filter
float M = (float)N / 2;
for (int n = 0; n < _coefCount; n++) {
double hn = 0;
if (n == M) {
if (_filterType == FilterType::BAND_PASS) {
hn = (oc2 - oc1) / PI;
} else if (_filterType == FilterType::BAND_STOP) {
hn = 1 - (oc2 - oc1) / PI;
}
} else {
float dif = n - M;
double val1 = commonF(oc1, dif);
double val2 = commonF(oc2, dif);
if (_filterType == FilterType::BAND_PASS) {
hn = val2 - val1;
} else if (_filterType == FilterType::BAND_STOP) {
hn = val1 - val2;
}
}
_coefficients[n] = hn;
}
_applyWindowToCoefs();
}
double FIRFilter::getNextSample(void) {
//Because _inputSamples is set up to have _coefCount elements, you just always pop off an element to start.
_inputSamples.pop_front();
_inputSamples.push_back(_inputs.front()->getNextSample());
double y_n = 0;
for (unsigned int i = 0; i < _coefCount; i++) {
y_n += _inputSamples[i] * _coefficients[i];
}
return y_n;
}
double FIRFilter::_calcH(int n, double omega) {
if (n == 0) {
return omega / PI;
}
return omega / PI * sinc(n*omega);
}
void FIRFilter::_applyWindowToCoefs(void) {
//Do nothing for rectangular window
if (_windowType == WindowType::HANNING) {
for (int i = 0; i < _coefCount; i++) {
_coefficients[i] *= 0.5*(1 - cos(2 * PI*i / (_coefCount - 1)));
}
} else if (_windowType == WindowType::BLACKMAN) {
for (int i = 0; i < _coefCount; i++) {
double a0 = 7938 / 18608;
double a1 = 9240 / 18608;
double a2 = 1430 / 18608;
_coefficients[i] *= a0 - a1 * cos(2 * PI*i / (_coefCount - 1)) + a2*cos(4 * PI*i / (_coefCount - 1));
}
}
}
} //namespace Synth
} //namespace CX
| 29.026379 | 149 | 0.696278 | hardmanko |
9375f66abfa2e3c35ae19cf772d5988fef14ac83 | 1,248 | cpp | C++ | harfang/platform/win32/shared_library.cpp | harfang3dadmin/harfang3d | b4920c18fd53cdab6b3a08f262bd4844364829b4 | [
"BSD-2-Clause"
] | 43 | 2021-10-16T06:33:48.000Z | 2022-03-25T07:55:46.000Z | harfang/platform/win32/shared_library.cpp | harfang3dadmin/harfang3d | b4920c18fd53cdab6b3a08f262bd4844364829b4 | [
"BSD-2-Clause"
] | 1 | 2022-01-25T09:21:47.000Z | 2022-01-25T20:50:01.000Z | harfang/platform/win32/shared_library.cpp | harfang3dadmin/harfang3d | b4920c18fd53cdab6b3a08f262bd4844364829b4 | [
"BSD-2-Clause"
] | 8 | 2021-10-14T08:49:20.000Z | 2022-03-04T21:54:33.000Z | // HARFANG(R) Copyright (C) 2021 Emmanuel Julien, NWNC HARFANG. Released under GPL/LGPL/Commercial Licence, see licence.txt for details.
#include "platform/shared_library.h"
#include "platform/platform.h"
#include "foundation/format.h"
#include "foundation/log.h"
#include "foundation/string.h"
#include "platform/win32/platform.h"
#define WIN32_LEAN_AND_MEAN
#include <Shlobj.h>
#include <Windows.h>
#include <locale.h>
#include <shellapi.h>
namespace hg {
bool SetSharedLibraryPath(const char *path) { return SetDllDirectoryW(utf8_to_wchar(path).c_str()) != 0; }
SharedLib LoadSharedLibrary(const char *path) {
static_assert(sizeof(SharedLib) >= sizeof(HMODULE), "cannot fit HMODULE in SharedLib structure");
HMODULE mod = LoadLibraryW(utf8_to_wchar(path).c_str());
if (mod == 0)
error(format("LoadSharedLibrary('%1') failed, reason: %2").arg(path).arg(GetLastError_Win32()).c_str());
SharedLib h = reinterpret_cast<uintptr_t>(mod);
return h;
}
void *GetFunctionPointer(const SharedLib &h, const char *fn) {
FARPROC proc = GetProcAddress(reinterpret_cast<HMODULE>(h), fn);
if (!proc) {
error(format("GetProcAddress('%1') failed, reason: %2").arg(fn).arg(GetLastError_Win32()).c_str());
}
return proc;
}
} // namespace hg
| 29.714286 | 136 | 0.735577 | harfang3dadmin |
937826ce082e414a4045cbb7aa1e028ee32805d2 | 955 | hpp | C++ | src/tools/tools.hpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/tools/tools.hpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/tools/tools.hpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | #pragma once
#include "pch.hpp"
#include "types.hpp"
#include "scope.hpp"
#if defined(NDEBUG)
#define ND_ASSERT_NOTHROW (true)
#else
#define ND_ASSERT_NOTHROW (false)
#endif
#define ND_DECLARE_BUILDER_FIELD(field) decltype(Type::field) field
#define ND_DEFINE_BUILDER_SET(field) \
Builder& set(const decltype(Type::field)& cfg) noexcept \
{ \
field = cfg; \
return *this; \
}
#define ND_DEFINE_BUILDER_OPERATOR(field) \
Builder& operator<<(const decltype(Type::field)& cfg) noexcept \
{ \
return set(cfg); \
}
namespace nd::src::tools
{
f64
getDt(const f64 min) noexcept;
} // namespace nd::src::tools
| 28.088235 | 68 | 0.464921 | InspectorSolaris |
937a04039a3c3b06f33d76e0bc6442a8980d670c | 1,747 | hpp | C++ | include/Factory/Module/Decoder/RA/Decoder_RA.hpp | FredrikBlomgren/aff3ct | fa616bd923b2dcf03a4cf119cceca51cf810d483 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | include/Factory/Module/Decoder/RA/Decoder_RA.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | include/Factory/Module/Decoder/RA/Decoder_RA.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | /*!
* \file
* \brief Class factory::Decoder_RA.
*/
#ifndef FACTORY_DECODER_RA_HPP
#define FACTORY_DECODER_RA_HPP
#include <vector>
#include <string>
#include <map>
#include <cli.hpp>
#include "Tools/Factory/Header.hpp"
#include "Tools/auto_cloned_unique_ptr.hpp"
#include "Module/Encoder/Encoder.hpp"
#include "Module/Decoder/Decoder_SIHO.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
namespace aff3ct
{
namespace factory
{
extern const std::string Decoder_RA_name;
extern const std::string Decoder_RA_prefix;
class Decoder_RA : public Decoder
{
public:
// ----------------------------------------------------------------------------------------------------- PARAMETERS
// optional parameters
int n_ite = 10;
// depending parameters
tools::auto_cloned_unique_ptr<Interleaver> itl;
// -------------------------------------------------------------------------------------------------------- METHODS
explicit Decoder_RA(const std::string &p = Decoder_RA_prefix);
virtual ~Decoder_RA() = default;
Decoder_RA* clone() const;
virtual std::vector<std::string> get_names () const;
virtual std::vector<std::string> get_short_names() const;
virtual std::vector<std::string> get_prefixes () const;
// parameters construction
void get_description(cli::Argument_map_info &args) const;
void store (const cli::Argument_map_value &vals);
void get_headers (std::map<std::string,tools::header_list>& headers, const bool full = true) const;
// builder
template <typename B = int, typename Q = float>
module::Decoder_SIHO<B,Q>* build(const module::Interleaver<Q> &itl, module::Encoder<B> *encoder = nullptr) const;
};
}
}
#endif /* FACTORY_DECODER_RA_HPP */
| 30.12069 | 116 | 0.655982 | FredrikBlomgren |
937b13734bffb857defc4114a0f1bbee1512662c | 3,197 | cpp | C++ | Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp | calidrelle/Gamecodeur | 4449ea1dce02b8f08e39d258d864546fcc9b2fc6 | [
"CC0-1.0"
] | 29 | 2016-05-04T08:22:46.000Z | 2022-01-27T10:20:55.000Z | Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp | calidrelle/Gamecodeur | 4449ea1dce02b8f08e39d258d864546fcc9b2fc6 | [
"CC0-1.0"
] | 1 | 2018-11-25T14:12:39.000Z | 2018-11-25T14:12:39.000Z | Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp | calidrelle/Gamecodeur | 4449ea1dce02b8f08e39d258d864546fcc9b2fc6 | [
"CC0-1.0"
] | 49 | 2016-04-29T19:43:42.000Z | 2022-02-19T16:13:35.000Z | /*
* Scene_Egypt_Mazeentry.cpp
* enigma
*
* Created by MEKERSA David on 24/11/10.
* Copyright 2010 Casual Games France. All rights reserved.
*
*/
#include "EScene.h"
#include "Scene_Egypt_Mazeentry.h"
#include "ESceneDirector.h"
#include "GlobalBank.h"
/* Constructeur */
Scene_Egypt_Mazeentry::Scene_Egypt_Mazeentry(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector)
{
_lpBgGraphic = KPTK::createKGraphic ();
}
/* Destructeur */
Scene_Egypt_Mazeentry::~Scene_Egypt_Mazeentry()
{
delete _lpBgGraphic;
}
void Scene_Egypt_Mazeentry::Init()
{
SetupItem("egypt_symbol_god04h");
if (!TaskResolved("task_egypt_meetmummy")) {
AddHint("egypt","laby","how");
ResolveTask("task_egypt_meetmummy");
_lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_CINEMATIC, true);
_lpSceneDirector->getSequencer()->PlaySound(NULL,"ghostappear");
_lpSceneDirector->getSequencer()->ShowImage(NULL, "egypt_mummy", true);
int x,y;
GetObjectPosition("egypt_mummy", x, y, true, false);
_lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("EGYPT_MUMMY_RITUAL1"), "", false);
_lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("EGYPT_MUMMY_RITUAL2"), "", false);
_lpSceneDirector->getSequencer()->ShowImage(NULL, "egypt_mummy", false);
_lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_CINEMATIC, false);
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("EGYPT_NEFERES_WHATHAP"), "", true, true);
AddObjective("egypt","laby");
}
// Porte du laby
if (!TaskResolved("task_egypt_openmaze")) {
SetVisible("egypt_mazedoor", true, true);
SetVisible("egypt_maze_zone",false);
}
else {
SetVisible("egypt_mazedoor", false, true);
SetVisible("egypt_maze_zone",true);
}
// Retour après s'être perdu dans le laby
if (getAdditionalName() == "lost") {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("EGYPT_NEFERES_LOST"), "", true, false);
}
}
void Scene_Egypt_Mazeentry::Check()
{
EScene::Check();
#ifdef SCENE_SHORTCUT
if (KInput::isPressed(K_VK_F5))
{
_lpSceneDirector->GoToScene("menu");
}
if (KInput::isPressed(K_VK_F6))
{
}
#endif
}
void Scene_Egypt_Mazeentry::Logic()
{
EScene::Logic();
}
void Scene_Egypt_Mazeentry::Draw()
{
EScene::Draw();
}
void Scene_Egypt_Mazeentry::Close()
{
}
bool Scene_Egypt_Mazeentry::ObjectClicked(const char *szObjectName, float x, float y)
{
if (strcmp(szObjectName, "egypt_symbol_god04h") == 0) {
PickupSimple(szObjectName, "inv_egypt_god04");
}
return false;
}
bool Scene_Egypt_Mazeentry::ObjectOver(char *szObjectName, float x, float y)
{
return false;
}
bool Scene_Egypt_Mazeentry::ItemUsed(const char *szItemName, const char *szObjectName)
{
return false;
}
void Scene_Egypt_Mazeentry::MiniGameDone(const char *szGameName, bool bIsRevolved)
{
if (!bIsRevolved) {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_GATHERFAILED"), "", true, false);
return;
}
}
| 27.324786 | 137 | 0.699093 | calidrelle |
938936970416a05ff2ebb471131e86bcf9a0b165 | 14 | cpp | C++ | src/test.cpp | xpack/xpm-develop-test-xpack | c8f60e64324f751d3848dad12f4add838fa9da8c | [
"MIT"
] | null | null | null | src/test.cpp | xpack/xpm-develop-test-xpack | c8f60e64324f751d3848dad12f4add838fa9da8c | [
"MIT"
] | null | null | null | src/test.cpp | xpack/xpm-develop-test-xpack | c8f60e64324f751d3848dad12f4add838fa9da8c | [
"MIT"
] | null | null | null | // Test file.
| 7 | 13 | 0.571429 | xpack |
93896c5f265e702f4c7628ca39b30322980dde21 | 452 | cxx | C++ | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx | TeoZosa/ITK | bc989624d640b30ee047634eda6acfc4cdd3f39b | [
"Apache-2.0"
] | 1 | 2019-12-10T21:26:08.000Z | 2019-12-10T21:26:08.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx | TeoZosa/ITK | bc989624d640b30ee047634eda6acfc4cdd3f39b | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx | TeoZosa/ITK | bc989624d640b30ee047634eda6acfc4cdd3f39b | [
"Apache-2.0"
] | null | null | null | #include "vnl/vnl_vector_fixed.hxx"
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,2);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,3);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,4);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,5);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,6);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,7);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,8);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,9);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,10);
| 37.666667 | 46 | 0.862832 | TeoZosa |
938a824ddd54e2dee3118af9fc48a77be7451d1b | 23,704 | cc | C++ | components/arc/net/arc_net_host_impl.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | components/arc/net/arc_net_host_impl.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/arc/net/arc_net_host_impl.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "components/arc/net/arc_net_host_impl.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chromeos/login/login_state.h"
#include "chromeos/network/managed_network_configuration_handler.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_type_pattern.h"
#include "chromeos/network/network_util.h"
#include "chromeos/network/onc/onc_utils.h"
#include "components/arc/arc_bridge_service.h"
namespace {
constexpr int kGetNetworksListLimit = 100;
constexpr uint32_t kScanCompletedMinInstanceVersion = 1;
constexpr uint32_t kDefaultNetworkChangedMinInstanceVersion = 2;
constexpr uint32_t kWifiEnabledStateChanged = 3;
chromeos::NetworkStateHandler* GetStateHandler() {
return chromeos::NetworkHandler::Get()->network_state_handler();
}
chromeos::ManagedNetworkConfigurationHandler* GetManagedConfigurationHandler() {
return chromeos::NetworkHandler::Get()
->managed_network_configuration_handler();
}
chromeos::NetworkConnectionHandler* GetNetworkConnectionHandler() {
return chromeos::NetworkHandler::Get()->network_connection_handler();
}
bool IsDeviceOwner() {
// Check whether the logged-in Chrome OS user is allowed to add or
// remove WiFi networks.
return chromeos::LoginState::Get()->GetLoggedInUserType() ==
chromeos::LoginState::LOGGED_IN_USER_OWNER;
}
std::string GetStringFromOncDictionary(const base::DictionaryValue* dict,
const char* key,
bool required) {
std::string value;
dict->GetString(key, &value);
if (required && value.empty())
NOTREACHED();
return value;
}
arc::mojom::SecurityType TranslateONCWifiSecurityType(
const base::DictionaryValue* dict) {
std::string type = GetStringFromOncDictionary(dict, onc::wifi::kSecurity,
true /* required */);
if (type == onc::wifi::kWEP_PSK)
return arc::mojom::SecurityType::WEP_PSK;
else if (type == onc::wifi::kWEP_8021X)
return arc::mojom::SecurityType::WEP_8021X;
else if (type == onc::wifi::kWPA_PSK)
return arc::mojom::SecurityType::WPA_PSK;
else if (type == onc::wifi::kWPA_EAP)
return arc::mojom::SecurityType::WPA_EAP;
else
return arc::mojom::SecurityType::NONE;
}
arc::mojom::WiFiPtr TranslateONCWifi(const base::DictionaryValue* dict) {
arc::mojom::WiFiPtr wifi = arc::mojom::WiFi::New();
// Optional; defaults to 0.
dict->GetInteger(onc::wifi::kFrequency, &wifi->frequency);
wifi->bssid =
GetStringFromOncDictionary(dict, onc::wifi::kBSSID, false /* required */);
wifi->hex_ssid = GetStringFromOncDictionary(dict, onc::wifi::kHexSSID,
true /* required */);
// Optional; defaults to false.
dict->GetBoolean(onc::wifi::kHiddenSSID, &wifi->hidden_ssid);
wifi->security = TranslateONCWifiSecurityType(dict);
// Optional; defaults to 0.
dict->GetInteger(onc::wifi::kSignalStrength, &wifi->signal_strength);
return wifi;
}
mojo::Array<mojo::String> TranslateStringArray(const base::ListValue* list) {
mojo::Array<mojo::String> strings = mojo::Array<mojo::String>::New(0);
for (size_t i = 0; i < list->GetSize(); i++) {
std::string value;
list->GetString(i, &value);
DCHECK(!value.empty());
strings.push_back(static_cast<mojo::String>(value));
}
return strings;
}
mojo::Array<arc::mojom::IPConfigurationPtr> TranslateONCIPConfigs(
const base::ListValue* list) {
mojo::Array<arc::mojom::IPConfigurationPtr> configs =
mojo::Array<arc::mojom::IPConfigurationPtr>::New(0);
for (size_t i = 0; i < list->GetSize(); i++) {
const base::DictionaryValue* ip_dict = nullptr;
arc::mojom::IPConfigurationPtr configuration =
arc::mojom::IPConfiguration::New();
list->GetDictionary(i, &ip_dict);
DCHECK(ip_dict);
// crbug.com/625229 - Gateway is not always present (but it should be).
configuration->gateway = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kGateway, false /* required */);
configuration->ip_address = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kIPAddress, true /* required */);
const base::ListValue* dns_list;
if (!ip_dict->GetList(onc::ipconfig::kNameServers, &dns_list))
NOTREACHED();
configuration->name_servers = TranslateStringArray(dns_list);
if (!ip_dict->GetInteger(onc::ipconfig::kRoutingPrefix,
&configuration->routing_prefix)) {
NOTREACHED();
}
std::string type = GetStringFromOncDictionary(ip_dict, onc::ipconfig::kType,
true /* required */);
configuration->type = type == onc::ipconfig::kIPv6
? arc::mojom::IPAddressType::IPV6
: arc::mojom::IPAddressType::IPV4;
configuration->web_proxy_auto_discovery_url = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kWebProxyAutoDiscoveryUrl,
false /* required */);
configs.push_back(std::move(configuration));
}
return configs;
}
arc::mojom::ConnectionStateType TranslateONCConnectionState(
const base::DictionaryValue* dict) {
std::string connection_state = GetStringFromOncDictionary(
dict, onc::network_config::kConnectionState, true /* required */);
if (connection_state == onc::connection_state::kConnected)
return arc::mojom::ConnectionStateType::CONNECTED;
else if (connection_state == onc::connection_state::kConnecting)
return arc::mojom::ConnectionStateType::CONNECTING;
else if (connection_state == onc::connection_state::kNotConnected)
return arc::mojom::ConnectionStateType::NOT_CONNECTED;
NOTREACHED();
return arc::mojom::ConnectionStateType::NOT_CONNECTED;
}
void TranslateONCNetworkTypeDetails(const base::DictionaryValue* dict,
arc::mojom::NetworkConfiguration* mojo) {
std::string type = GetStringFromOncDictionary(
dict, onc::network_config::kType, true /* required */);
if (type == onc::network_type::kCellular) {
mojo->type = arc::mojom::NetworkType::CELLULAR;
} else if (type == onc::network_type::kEthernet) {
mojo->type = arc::mojom::NetworkType::ETHERNET;
} else if (type == onc::network_type::kVPN) {
mojo->type = arc::mojom::NetworkType::VPN;
} else if (type == onc::network_type::kWiFi) {
mojo->type = arc::mojom::NetworkType::WIFI;
const base::DictionaryValue* wifi_dict = nullptr;
dict->GetDictionary(onc::network_config::kWiFi, &wifi_dict);
DCHECK(wifi_dict);
mojo->wifi = TranslateONCWifi(wifi_dict);
} else if (type == onc::network_type::kWimax) {
mojo->type = arc::mojom::NetworkType::WIMAX;
} else {
NOTREACHED();
}
}
arc::mojom::NetworkConfigurationPtr TranslateONCConfiguration(
const base::DictionaryValue* dict) {
arc::mojom::NetworkConfigurationPtr mojo =
arc::mojom::NetworkConfiguration::New();
mojo->connection_state = TranslateONCConnectionState(dict);
mojo->guid = GetStringFromOncDictionary(dict, onc::network_config::kGUID,
true /* required */);
const base::ListValue* ip_config_list = nullptr;
if (dict->GetList(onc::network_config::kIPConfigs, &ip_config_list)) {
DCHECK(ip_config_list);
mojo->ip_configs = TranslateONCIPConfigs(ip_config_list);
}
mojo->guid = GetStringFromOncDictionary(dict, onc::network_config::kGUID,
true /* required */);
mojo->mac_address = GetStringFromOncDictionary(
dict, onc::network_config::kMacAddress, true /* required */);
TranslateONCNetworkTypeDetails(dict, mojo.get());
return mojo;
}
void ForgetNetworkSuccessCallback(
const arc::mojom::NetHost::ForgetNetworkCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void ForgetNetworkFailureCallback(
const arc::mojom::NetHost::ForgetNetworkCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "ForgetNetworkFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void StartConnectSuccessCallback(
const arc::mojom::NetHost::StartConnectCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void StartConnectFailureCallback(
const arc::mojom::NetHost::StartConnectCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "StartConnectFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void StartDisconnectSuccessCallback(
const arc::mojom::NetHost::StartDisconnectCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void StartDisconnectFailureCallback(
const arc::mojom::NetHost::StartDisconnectCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "StartDisconnectFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void GetDefaultNetworkSuccessCallback(
const arc::ArcNetHostImpl::GetDefaultNetworkCallback& callback,
const std::string& service_path,
const base::DictionaryValue& dictionary) {
// TODO(cernekee): Figure out how to query Chrome for the default physical
// service if a VPN is connected, rather than just reporting the
// default logical service in both fields.
callback.Run(TranslateONCConfiguration(&dictionary),
TranslateONCConfiguration(&dictionary));
}
void GetDefaultNetworkFailureCallback(
const arc::ArcNetHostImpl::GetDefaultNetworkCallback& callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
LOG(ERROR) << "Failed to query default logical network";
callback.Run(nullptr, nullptr);
}
void DefaultNetworkFailureCallback(
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
LOG(ERROR) << "Failed to query default logical network";
}
} // namespace
namespace arc {
ArcNetHostImpl::ArcNetHostImpl(ArcBridgeService* bridge_service)
: ArcService(bridge_service), binding_(this), weak_factory_(this) {
arc_bridge_service()->net()->AddObserver(this);
}
ArcNetHostImpl::~ArcNetHostImpl() {
DCHECK(thread_checker_.CalledOnValidThread());
arc_bridge_service()->net()->RemoveObserver(this);
if (observing_network_state_) {
GetStateHandler()->RemoveObserver(this, FROM_HERE);
}
}
void ArcNetHostImpl::OnInstanceReady() {
DCHECK(thread_checker_.CalledOnValidThread());
mojom::NetHostPtr host;
binding_.Bind(GetProxy(&host));
auto* instance = arc_bridge_service()->net()->GetInstanceForMethod("Init");
DCHECK(instance);
instance->Init(std::move(host));
if (chromeos::NetworkHandler::IsInitialized()) {
GetStateHandler()->AddObserver(this, FROM_HERE);
observing_network_state_ = true;
}
}
void ArcNetHostImpl::OnInstanceClosed() {
if (!observing_network_state_)
return;
GetStateHandler()->RemoveObserver(this, FROM_HERE);
observing_network_state_ = false;
}
void ArcNetHostImpl::GetNetworksDeprecated(
bool configured_only,
bool visible_only,
const GetNetworksDeprecatedCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
if (configured_only && visible_only) {
VLOG(1) << "Illegal arguments - both configured and visible networks "
"requested.";
return;
}
mojom::GetNetworksRequestType type =
mojom::GetNetworksRequestType::CONFIGURED_ONLY;
if (visible_only) {
type = mojom::GetNetworksRequestType::VISIBLE_ONLY;
}
GetNetworks(type, callback);
}
void ArcNetHostImpl::GetNetworks(mojom::GetNetworksRequestType type,
const GetNetworksCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
mojom::NetworkDataPtr data = mojom::NetworkData::New();
bool configured_only = true;
bool visible_only = false;
if (type == mojom::GetNetworksRequestType::VISIBLE_ONLY) {
configured_only = false;
visible_only = true;
}
// Retrieve list of nearby wifi networks
chromeos::NetworkTypePattern network_pattern =
chromeos::onc::NetworkTypePatternFromOncType(onc::network_type::kWiFi);
std::unique_ptr<base::ListValue> network_properties_list =
chromeos::network_util::TranslateNetworkListToONC(
network_pattern, configured_only, visible_only,
kGetNetworksListLimit);
// Extract info for each network and add it to the list.
// Even if there's no WiFi, an empty (size=0) list must be returned and not a
// null one. The explicitly sized New() constructor ensures the non-null
// property.
mojo::Array<mojom::WifiConfigurationPtr> networks =
mojo::Array<mojom::WifiConfigurationPtr>::New(0);
for (const auto& value : *network_properties_list) {
mojom::WifiConfigurationPtr wc = mojom::WifiConfiguration::New();
base::DictionaryValue* network_dict = nullptr;
value->GetAsDictionary(&network_dict);
DCHECK(network_dict);
// kName is a post-processed version of kHexSSID.
std::string tmp;
network_dict->GetString(onc::network_config::kName, &tmp);
DCHECK(!tmp.empty());
wc->ssid = tmp;
tmp.clear();
network_dict->GetString(onc::network_config::kGUID, &tmp);
DCHECK(!tmp.empty());
wc->guid = tmp;
base::DictionaryValue* wifi_dict = nullptr;
network_dict->GetDictionary(onc::network_config::kWiFi, &wifi_dict);
DCHECK(wifi_dict);
if (!wifi_dict->GetInteger(onc::wifi::kFrequency, &wc->frequency))
wc->frequency = 0;
if (!wifi_dict->GetInteger(onc::wifi::kSignalStrength,
&wc->signal_strength))
wc->signal_strength = 0;
if (!wifi_dict->GetString(onc::wifi::kSecurity, &tmp))
NOTREACHED();
DCHECK(!tmp.empty());
wc->security = tmp;
if (!wifi_dict->GetString(onc::wifi::kBSSID, &tmp))
NOTREACHED();
DCHECK(!tmp.empty());
wc->bssid = tmp;
mojom::VisibleNetworkDetailsPtr details =
mojom::VisibleNetworkDetails::New();
details->frequency = wc->frequency;
details->signal_strength = wc->signal_strength;
details->bssid = wc->bssid;
wc->details = mojom::NetworkDetails::New();
wc->details->set_visible(std::move(details));
networks.push_back(std::move(wc));
}
data->networks = std::move(networks);
callback.Run(std::move(data));
}
void ArcNetHostImpl::CreateNetworkSuccessCallback(
const mojom::NetHost::CreateNetworkCallback& mojo_callback,
const std::string& service_path,
const std::string& guid) {
VLOG(1) << "CreateNetworkSuccessCallback";
cached_guid_ = guid;
cached_service_path_ = service_path;
mojo_callback.Run(guid);
}
void ArcNetHostImpl::CreateNetworkFailureCallback(
const mojom::NetHost::CreateNetworkCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "CreateNetworkFailureCallback: " << error_name;
mojo_callback.Run("");
}
void ArcNetHostImpl::CreateNetwork(mojom::WifiConfigurationPtr cfg,
const CreateNetworkCallback& callback) {
if (!IsDeviceOwner()) {
callback.Run("");
return;
}
std::unique_ptr<base::DictionaryValue> properties(new base::DictionaryValue);
std::unique_ptr<base::DictionaryValue> wifi_dict(new base::DictionaryValue);
if (cfg->hexssid.is_null() || !cfg->details) {
callback.Run("");
return;
}
mojom::ConfiguredNetworkDetailsPtr details =
std::move(cfg->details->get_configured());
if (!details) {
callback.Run("");
return;
}
properties->SetStringWithoutPathExpansion(onc::network_config::kType,
onc::network_config::kWiFi);
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kHexSSID,
cfg->hexssid.get());
wifi_dict->SetBooleanWithoutPathExpansion(onc::wifi::kAutoConnect,
details->autoconnect);
if (cfg->security.get().empty()) {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kSecurity,
onc::wifi::kSecurityNone);
} else {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kSecurity,
cfg->security.get());
if (!details->passphrase.is_null()) {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kPassphrase,
details->passphrase.get());
}
}
properties->SetWithoutPathExpansion(onc::network_config::kWiFi,
std::move(wifi_dict));
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->CreateConfiguration(
user_id_hash, *properties,
base::Bind(&ArcNetHostImpl::CreateNetworkSuccessCallback,
weak_factory_.GetWeakPtr(), callback),
base::Bind(&ArcNetHostImpl::CreateNetworkFailureCallback,
weak_factory_.GetWeakPtr(), callback));
}
bool ArcNetHostImpl::GetNetworkPathFromGuid(const std::string& guid,
std::string* path) {
const chromeos::NetworkState* network =
GetStateHandler()->GetNetworkStateFromGuid(guid);
if (network) {
*path = network->path();
return true;
}
if (cached_guid_ == guid) {
*path = cached_service_path_;
return true;
} else {
return false;
}
}
void ArcNetHostImpl::ForgetNetwork(const mojo::String& guid,
const ForgetNetworkCallback& callback) {
if (!IsDeviceOwner()) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
cached_guid_.clear();
GetManagedConfigurationHandler()->RemoveConfiguration(
path, base::Bind(&ForgetNetworkSuccessCallback, callback),
base::Bind(&ForgetNetworkFailureCallback, callback));
}
void ArcNetHostImpl::StartConnect(const mojo::String& guid,
const StartConnectCallback& callback) {
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
GetNetworkConnectionHandler()->ConnectToNetwork(
path, base::Bind(&StartConnectSuccessCallback, callback),
base::Bind(&StartConnectFailureCallback, callback), false);
}
void ArcNetHostImpl::StartDisconnect(const mojo::String& guid,
const StartDisconnectCallback& callback) {
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
GetNetworkConnectionHandler()->DisconnectNetwork(
path, base::Bind(&StartDisconnectSuccessCallback, callback),
base::Bind(&StartDisconnectFailureCallback, callback));
}
void ArcNetHostImpl::GetWifiEnabledState(
const GetWifiEnabledStateCallback& callback) {
bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi());
callback.Run(is_enabled);
}
void ArcNetHostImpl::SetWifiEnabledState(
bool is_enabled,
const SetWifiEnabledStateCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
chromeos::NetworkStateHandler::TechnologyState state =
GetStateHandler()->GetTechnologyState(
chromeos::NetworkTypePattern::WiFi());
// WiFi can't be enabled or disabled in these states.
if ((state == chromeos::NetworkStateHandler::TECHNOLOGY_PROHIBITED) ||
(state == chromeos::NetworkStateHandler::TECHNOLOGY_UNINITIALIZED) ||
(state == chromeos::NetworkStateHandler::TECHNOLOGY_UNAVAILABLE)) {
VLOG(1) << "SetWifiEnabledState failed due to WiFi state: " << state;
callback.Run(false);
} else {
GetStateHandler()->SetTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi(), is_enabled,
chromeos::network_handler::ErrorCallback());
callback.Run(true);
}
}
void ArcNetHostImpl::StartScan() {
GetStateHandler()->RequestScan();
}
void ArcNetHostImpl::ScanCompleted(const chromeos::DeviceState* /*unused*/) {
auto* net_instance = arc_bridge_service()->net()->GetInstanceForMethod(
"ScanCompleted", kScanCompletedMinInstanceVersion);
if (!net_instance)
return;
net_instance->ScanCompleted();
}
void ArcNetHostImpl::GetDefaultNetwork(
const GetDefaultNetworkCallback& callback) {
const chromeos::NetworkState* default_network =
GetStateHandler()->DefaultNetwork();
if (!default_network) {
VLOG(1) << "GetDefaultNetwork: no default network";
callback.Run(nullptr, nullptr);
return;
}
VLOG(1) << "GetDefaultNetwork: default network is "
<< default_network->path();
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->GetProperties(
user_id_hash, default_network->path(),
base::Bind(&GetDefaultNetworkSuccessCallback, callback),
base::Bind(&GetDefaultNetworkFailureCallback, callback));
}
void ArcNetHostImpl::DefaultNetworkSuccessCallback(
const std::string& service_path,
const base::DictionaryValue& dictionary) {
auto* net_instance = arc_bridge_service()->net()->GetInstanceForMethod(
"DefaultNetworkChanged", kDefaultNetworkChangedMinInstanceVersion);
if (!net_instance)
return;
net_instance->DefaultNetworkChanged(TranslateONCConfiguration(&dictionary),
TranslateONCConfiguration(&dictionary));
}
void ArcNetHostImpl::DefaultNetworkChanged(
const chromeos::NetworkState* network) {
if (!network) {
VLOG(1) << "No default network";
auto* net_instance = arc_bridge_service()->net()->GetInstanceForMethod(
"DefaultNetworkChanged", kDefaultNetworkChangedMinInstanceVersion);
if (net_instance)
net_instance->DefaultNetworkChanged(nullptr, nullptr);
return;
}
VLOG(1) << "New default network: " << network->path();
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->GetProperties(
user_id_hash, network->path(),
base::Bind(&ArcNetHostImpl::DefaultNetworkSuccessCallback,
weak_factory_.GetWeakPtr()),
base::Bind(&DefaultNetworkFailureCallback));
}
void ArcNetHostImpl::DeviceListChanged() {
auto* net_instance = arc_bridge_service()->net()->GetInstanceForMethod(
"WifiEnabledStateChanged", kWifiEnabledStateChanged);
if (!net_instance)
return;
bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi());
net_instance->WifiEnabledStateChanged(is_enabled);
}
void ArcNetHostImpl::OnShuttingDown() {
DCHECK(observing_network_state_);
GetStateHandler()->RemoveObserver(this, FROM_HERE);
observing_network_state_ = false;
}
} // namespace arc
| 35.48503 | 80 | 0.69676 | xzhan96 |
938a9b3b4735eff7b5e0f2e76ff57f3c9bc2e92e | 24,094 | cpp | C++ | reg-apps/reg_resample.cpp | Barnonewdm/NiftyReg | 99d584e2b8ea0bffe7e65e40c8dc818751782d92 | [
"BSD-3-Clause"
] | 59 | 2018-06-11T11:21:47.000Z | 2022-02-18T05:33:21.000Z | reg-apps/reg_resample.cpp | Barnonewdm/NiftyReg | 99d584e2b8ea0bffe7e65e40c8dc818751782d92 | [
"BSD-3-Clause"
] | 67 | 2018-05-21T17:17:21.000Z | 2022-03-21T17:17:57.000Z | reg-apps/reg_resample.cpp | Barnonewdm/NiftyReg | 99d584e2b8ea0bffe7e65e40c8dc818751782d92 | [
"BSD-3-Clause"
] | 26 | 2018-11-27T16:41:20.000Z | 2022-02-22T21:05:09.000Z | /**
* @file reg_resample.cpp
* @author Marc Modat
* @date 18/05/2009
*
* Created by Marc Modat on 18/05/2009.
* Copyright (c) 2009, University College London. All rights reserved.
* Centre for Medical Image Computing (CMIC)
* See the LICENSE.txt file in the nifty_reg root folder
*
*/
#include "_reg_ReadWriteImage.h"
#include "_reg_ReadWriteMatrix.h"
#include "_reg_resampling.h"
#include "_reg_globalTrans.h"
#include "_reg_localTrans.h"
#include "_reg_localTrans_jac.h"
#include "_reg_tools.h"
#include "reg_resample.h"
typedef struct
{
char *referenceImageName;
char *floatingImageName;
char *inputTransName;
char *outputResultName;
char *outputBlankName;
float sourceBGValue;
int interpolation;
float paddingValue;
float PSF_Algorithm;
} PARAM;
typedef struct
{
bool referenceImageFlag;
bool floatingImageFlag;
bool inputTransFlag;
bool outputResultFlag;
bool outputBlankFlag;
bool outputBlankXYFlag;
bool outputBlankYZFlag;
bool outputBlankXZFlag;
bool isTensor;
bool usePSF;
} FLAG;
void PetitUsage(char *exec)
{
fprintf(stderr,"Usage:\t%s -ref <referenceImageName> -flo <floatingImageName> [OPTIONS].\n",exec);
fprintf(stderr,"\tSee the help for more details (-h).\n");
return;
}
void Usage(char *exec)
{
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
printf("Usage:\t%s -ref <filename> -flo <filename> [OPTIONS].\n",exec);
printf("\t-ref <filename>\n\t\tFilename of the reference image (mandatory)\n");
printf("\t-flo <filename>\n\t\tFilename of the floating image (mandatory)\n\n");
printf("* * OPTIONS * *\n");
printf("\t-trans <filename>\n\t\tFilename of the file containing the transformation parametrisation (from reg_aladin, reg_f3d or reg_transform)\n");
printf("\t-res <filename>\n\t\tFilename of the resampled image [none]\n");
printf("\t-blank <filename>\n\t\tFilename of the resampled blank grid [none]\n");
printf("\t-inter <int>\n\t\tInterpolation order (0, 1, 3, 4)[3] (0=NN, 1=LIN; 3=CUB, 4=SINC)\n");
printf("\t-pad <int>\n\t\tInterpolation padding value [0]\n");
printf("\t-tensor\n\t\tThe last six timepoints of the floating image are considered to be tensor order as XX, XY, YY, XZ, YZ, ZZ [off]\n");
printf("\t-psf\n\t\tPerform the resampling in two steps to resample an image to a lower resolution [off]\n");
printf("\t-psf_alg <0/1>\n\t\tMinimise the matrix metric (0) or the determinant (1) when estimating the PSF [0]\n");
printf("\t-voff\n\t\tTurns verbose off [on]\n");
#if defined (_OPENMP)
int defaultOpenMPValue=omp_get_num_procs();
if(getenv("OMP_NUM_THREADS")!=NULL)
defaultOpenMPValue=atoi(getenv("OMP_NUM_THREADS"));
printf("\t-omp <int>\n\t\tNumber of thread to use with OpenMP. [%i/%i]\n",
defaultOpenMPValue, omp_get_num_procs());
#endif
printf("\t--version\n\t\tPrint current version and exit (%s)\n",NR_VERSION);
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
return;
}
int main(int argc, char **argv)
{
PARAM *param = (PARAM *)calloc(1,sizeof(PARAM));
FLAG *flag = (FLAG *)calloc(1,sizeof(FLAG));
param->interpolation=3; // Cubic spline interpolation used by default
param->paddingValue=0;
param->PSF_Algorithm=0;
bool verbose=true;
#if defined (_OPENMP)
// Set the default number of thread
int defaultOpenMPValue=omp_get_num_procs();
if(getenv("OMP_NUM_THREADS")!=NULL)
defaultOpenMPValue=atoi(getenv("OMP_NUM_THREADS"));
omp_set_num_threads(defaultOpenMPValue);
#endif
/* read the input parameter */
for(int i=1; i<argc; i++)
{
if(strcmp(argv[i],"-h")==0 ||
strcmp(argv[i],"-H")==0 ||
strcmp(argv[i],"-help")==0 ||
strcmp(argv[i],"--help")==0 ||
strcmp(argv[i],"-HELP")==0 ||
strcmp(argv[i],"--HELP")==0 ||
strcmp(argv[i],"-Help")==0 ||
strcmp(argv[i],"--Help")==0
)
{
Usage(argv[0]);
return EXIT_SUCCESS;
}
else if(strcmp(argv[i], "--xml")==0)
{
printf("%s",xml_resample);
return EXIT_SUCCESS;
}
else if(strcmp(argv[i], "-voff")==0)
{
verbose=false;
}
else if(strcmp(argv[i], "-omp")==0 || strcmp(argv[i], "--omp")==0)
{
#if defined (_OPENMP)
omp_set_num_threads(atoi(argv[++i]));
#else
reg_print_msg_warn("NiftyReg has not been compiled with OpenMP, the \'-omp\' flag is ignored");
++i;
#endif
}
else if( strcmp(argv[i], "-version")==0 ||
strcmp(argv[i], "-Version")==0 ||
strcmp(argv[i], "-V")==0 ||
strcmp(argv[i], "-v")==0 ||
strcmp(argv[i], "--v")==0 ||
strcmp(argv[i], "--version")==0)
{
printf("%s\n",NR_VERSION);
return EXIT_SUCCESS;
}
else if((strcmp(argv[i],"-ref")==0) || (strcmp(argv[i],"-target")==0) ||
(strcmp(argv[i],"--ref")==0))
{
param->referenceImageName=argv[++i];
flag->referenceImageFlag=1;
}
else if((strcmp(argv[i],"-flo")==0) || (strcmp(argv[i],"-source")==0) ||
(strcmp(argv[i],"--flo")==0))
{
param->floatingImageName=argv[++i];
flag->floatingImageFlag=1;
}
else if((strcmp(argv[i],"-res")==0) || (strcmp(argv[i],"-result")==0) ||
(strcmp(argv[i],"--res")==0))
{
param->outputResultName=argv[++i];
flag->outputResultFlag=1;
}
else if(strcmp(argv[i], "-trans") == 0 ||
strcmp(argv[i],"--trans")==0 ||
strcmp(argv[i],"-aff")==0 || // added for backward compatibility
strcmp(argv[i],"-def")==0 || // added for backward compatibility
strcmp(argv[i],"-cpp")==0 ) // added for backward compatibility
{
param->inputTransName=argv[++i];
flag->inputTransFlag=1;
}
else if(strcmp(argv[i], "-inter") == 0 ||
(strcmp(argv[i],"--inter")==0))
{
param->interpolation=atoi(argv[++i]);
}
else if(strcmp(argv[i], "-NN") == 0)
{
param->interpolation=0;
}
else if(strcmp(argv[i], "-LIN") == 0 ||
(strcmp(argv[i],"-TRI")==0))
{
param->interpolation=1;
}
else if(strcmp(argv[i], "-CUB") == 0 ||
(strcmp(argv[i],"-SPL")==0))
{
param->interpolation=3;
}
else if(strcmp(argv[i], "-SINC") == 0)
{
param->interpolation=4;
}
else if(strcmp(argv[i], "-pad") == 0 ||
(strcmp(argv[i],"--pad")==0))
{
param->paddingValue=(float)atof(argv[++i]);
}
else if(strcmp(argv[i], "-blank") == 0 ||
(strcmp(argv[i],"--blank")==0))
{
param->outputBlankName=argv[++i];
flag->outputBlankFlag=1;
}
else if(strcmp(argv[i], "-blankXY") == 0 ||
(strcmp(argv[i],"--blankXY")==0))
{
param->outputBlankName=argv[++i];
flag->outputBlankXYFlag=1;
}
else if(strcmp(argv[i], "-blankYZ") == 0 ||
(strcmp(argv[i],"--blankYZ")==0))
{
param->outputBlankName=argv[++i];
flag->outputBlankYZFlag=1;
}
else if(strcmp(argv[i], "-blankXZ") == 0 ||
(strcmp(argv[i],"--blankXZ")==0))
{
param->outputBlankName=argv[++i];
flag->outputBlankXZFlag=1;
}
else if(strcmp(argv[i], "-tensor") == 0 ||
(strcmp(argv[i],"--tensor")==0))
{
flag->isTensor=true;
}
else if(strcmp(argv[i], "-psf") == 0 ||
(strcmp(argv[i],"--psf")==0))
{
flag->usePSF=true;
}
else if(strcmp(argv[i], "-psf_alg") == 0 ||
(strcmp(argv[i],"--psf_alg")==0))
{
param->PSF_Algorithm=(float)atof(argv[++i]);
}
else
{
fprintf(stderr,"Err:\tParameter %s unknown.\n",argv[i]);
PetitUsage(argv[0]);
return EXIT_FAILURE;
}
}
if(!flag->referenceImageFlag || !flag->floatingImageFlag)
{
fprintf(stderr,"[NiftyReg ERROR] The reference and the floating image have both to be defined.\n");
PetitUsage(argv[0]);
return EXIT_FAILURE;
}
/* Read the reference image */
nifti_image *referenceImage = reg_io_ReadImageHeader(param->referenceImageName);
if(referenceImage == NULL)
{
fprintf(stderr,"[NiftyReg ERROR] Error when reading the reference image: %s\n",
param->referenceImageName);
return EXIT_FAILURE;
}
/* Read the floating image */
nifti_image *floatingImage = reg_io_ReadImageFile(param->floatingImageName);
if(floatingImage == NULL)
{
fprintf(stderr,"[NiftyReg ERROR] Error when reading the floating image: %s\n",
param->floatingImageName);
return EXIT_FAILURE;
}
/* *********************************** */
/* DISPLAY THE RESAMPLING PARAMETERS */
/* *********************************** */
if(verbose){
printf("\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
printf("Command line:\n");
for(int i=0; i<argc; i++) printf(" %s", argv[i]);
printf("\n");
printf("Parameters\n");
printf("Reference image name: %s\n",referenceImage->fname);
printf("\t%ix%ix%i voxels, %i volumes\n",referenceImage->nx,referenceImage->ny,referenceImage->nz,referenceImage->nt);
printf("\t%gx%gx%g mm\n",referenceImage->dx,referenceImage->dy,referenceImage->dz);
printf("Floating image name: %s\n",floatingImage->fname);
printf("\t%ix%ix%i voxels, %i volumes\n",floatingImage->nx,floatingImage->ny,floatingImage->nz,floatingImage->nt);
printf("\t%gx%gx%g mm\n",floatingImage->dx,floatingImage->dy,floatingImage->dz);
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n");
}
/* *********************** */
/* READ THE TRANSFORMATION */
/* *********************** */
nifti_image *inputTransformationImage = NULL;
mat44 inputAffineTransformation;
// Check if a transformation has been specified
if(flag->inputTransFlag)
{
// First check if the input filename is an image
if(reg_isAnImageFileName(param->inputTransName))
{
inputTransformationImage=reg_io_ReadImageFile(param->inputTransName);
if(inputTransformationImage==NULL)
{
fprintf(stderr, "[NiftyReg ERROR] Error when reading the provided transformation: %s\n",
param->inputTransName);
return EXIT_FAILURE;
}
}
else
{
// the transformation is assumed to be affine
reg_tool_ReadAffineFile(&inputAffineTransformation,
param->inputTransName);
}
}
else
{
// No transformation is specified, an identity transformation is used
reg_mat44_eye(&inputAffineTransformation);
}
// Create a deformation field
nifti_image *deformationFieldImage = nifti_copy_nim_info(referenceImage);
deformationFieldImage->dim[0]=deformationFieldImage->ndim=5;
deformationFieldImage->dim[1]=deformationFieldImage->nx=referenceImage->nx;
deformationFieldImage->dim[2]=deformationFieldImage->ny=referenceImage->ny;
deformationFieldImage->dim[3]=deformationFieldImage->nz=referenceImage->nz;
deformationFieldImage->dim[4]=deformationFieldImage->nt=1;
deformationFieldImage->pixdim[4]=deformationFieldImage->dt=1.0;
deformationFieldImage->dim[5]=deformationFieldImage->nu=referenceImage->nz>1?3:2;
deformationFieldImage->dim[6]=deformationFieldImage->nv=1;
deformationFieldImage->dim[7]=deformationFieldImage->nw=1;
deformationFieldImage->nvox =(size_t)deformationFieldImage->nx*
deformationFieldImage->ny*deformationFieldImage->nz*
deformationFieldImage->nt*deformationFieldImage->nu;
deformationFieldImage->scl_slope=1.f;
deformationFieldImage->scl_inter=0.f;
if(inputTransformationImage!=NULL)
{
deformationFieldImage->datatype = inputTransformationImage->datatype;
deformationFieldImage->nbyper = inputTransformationImage->nbyper;
}
else
{
deformationFieldImage->datatype = NIFTI_TYPE_FLOAT32;
deformationFieldImage->nbyper = sizeof(float);
}
deformationFieldImage->data = (void *)calloc(deformationFieldImage->nvox, deformationFieldImage->nbyper);
// Initialise the deformation field with an identity transformation
reg_tools_multiplyValueToImage(deformationFieldImage,deformationFieldImage,0.f);
reg_getDeformationFromDisplacement(deformationFieldImage);
deformationFieldImage->intent_p1=DEF_FIELD;
// Compute the transformation to apply
if(inputTransformationImage!=NULL)
{
switch(static_cast<int>(inputTransformationImage->intent_p1))
{
case LIN_SPLINE_GRID:
case CUB_SPLINE_GRID:
reg_spline_getDeformationField(inputTransformationImage,
deformationFieldImage,
NULL,
false,
true);
break;
case DISP_VEL_FIELD:
reg_getDeformationFromDisplacement(inputTransformationImage);
case DEF_VEL_FIELD:
{
nifti_image *tempFlowField = nifti_copy_nim_info(deformationFieldImage);
tempFlowField->data = (void *)malloc(tempFlowField->nvox*tempFlowField->nbyper);
memcpy(tempFlowField->data,deformationFieldImage->data,
tempFlowField->nvox*tempFlowField->nbyper);
reg_defField_compose(inputTransformationImage,
tempFlowField,
NULL);
tempFlowField->intent_p1=inputTransformationImage->intent_p1;
tempFlowField->intent_p2=inputTransformationImage->intent_p2;
reg_defField_getDeformationFieldFromFlowField(tempFlowField,
deformationFieldImage,
false);
nifti_image_free(tempFlowField);
}
break;
case SPLINE_VEL_GRID:
reg_spline_getDefFieldFromVelocityGrid(inputTransformationImage,
deformationFieldImage,
false);
break;
case DISP_FIELD:
reg_getDeformationFromDisplacement(inputTransformationImage);
default:
reg_defField_compose(inputTransformationImage,
deformationFieldImage,
NULL);
break;
}
nifti_image_free(inputTransformationImage);
inputTransformationImage=NULL;
}
else
{
reg_affine_getDeformationField(&inputAffineTransformation,
deformationFieldImage,
false,
NULL);
}
/* ************************* */
/* WARP THE FLOATING IMAGE */
/* ************************* */
if(flag->outputResultFlag)
{
switch(param->interpolation)
{
case 0:
param->interpolation=0;
break;
case 1:
param->interpolation=1;
break;
case 4:
param->interpolation=4;
break;
default:
param->interpolation=3;
break;
}
nifti_image *warpedImage = nifti_copy_nim_info(referenceImage);
warpedImage->dim[0]=warpedImage->ndim=floatingImage->dim[0];
warpedImage->dim[4]=warpedImage->nt=floatingImage->dim[4];
warpedImage->dim[5]=warpedImage->nu=floatingImage->dim[5];
warpedImage->cal_min=floatingImage->cal_min;
warpedImage->cal_max=floatingImage->cal_max;
warpedImage->scl_slope=floatingImage->scl_slope;
warpedImage->scl_inter=floatingImage->scl_inter;
if(param->paddingValue!=param->paddingValue &&
(floatingImage->datatype!=NIFTI_TYPE_FLOAT32 ||
floatingImage->datatype!=NIFTI_TYPE_FLOAT64)){
warpedImage->datatype = NIFTI_TYPE_FLOAT32;
reg_tools_changeDatatype<float>(floatingImage);
}
else warpedImage->datatype = floatingImage->datatype;
warpedImage->intent_code=floatingImage->intent_code;
memset(warpedImage->intent_name, 0, 16);
strcpy(warpedImage->intent_name,floatingImage->intent_name);
warpedImage->intent_p1=floatingImage->intent_p1;
warpedImage->intent_p2=floatingImage->intent_p2;
warpedImage->nbyper = floatingImage->nbyper;
warpedImage->nvox = (size_t)warpedImage->dim[1] * warpedImage->dim[2] *
warpedImage->dim[3] * warpedImage->dim[4] * warpedImage->dim[5];
warpedImage->data = (void *)calloc(warpedImage->nvox, warpedImage->nbyper);
if((floatingImage->dim[4]==6 || floatingImage->dim[4]==7) && flag->isTensor==true)
{
#ifndef NDEBUG
reg_print_msg_debug("DTI-based resampling\n");
#endif
// Compute first the Jacobian matrices
mat33 *jacobian = (mat33 *)malloc(deformationFieldImage->nx *
deformationFieldImage->ny *
deformationFieldImage->nz *
sizeof(mat33));
reg_defField_getJacobianMatrix(deformationFieldImage,
jacobian);
// resample the DTI image
bool timepoints[7];
for(int i=0; i<7; ++i) timepoints[i]=true;
if(floatingImage->dim[4]==7) timepoints[0]=false;
reg_resampleImage(floatingImage,
warpedImage,
deformationFieldImage,
NULL,
param->interpolation,
std::numeric_limits<float>::quiet_NaN(),
timepoints,
jacobian
);
}
else{
if(flag->usePSF){
// Compute first the Jacobian matrices
mat33 *jacobian = (mat33 *)malloc(deformationFieldImage->nx *
deformationFieldImage->ny *
deformationFieldImage->nz *
sizeof(mat33));
reg_defField_getJacobianMatrix(deformationFieldImage,
jacobian);
reg_resampleImage_PSF(floatingImage,
warpedImage,
deformationFieldImage,
NULL,
param->interpolation,
param->paddingValue,
jacobian,
(char)round(param->PSF_Algorithm));
#ifndef NDEBUG
reg_print_msg_debug("PSF resampling completed\n");
#endif
free(jacobian);
}
else
{
reg_resampleImage(floatingImage,
warpedImage,
deformationFieldImage,
NULL,
param->interpolation,
param->paddingValue);
}
}
memset(warpedImage->descrip, 0, 80);
strcpy (warpedImage->descrip,"Warped image using NiftyReg (reg_resample)");
reg_io_WriteImageFile(warpedImage,param->outputResultName);
if(verbose)
printf("[NiftyReg] Resampled image has been saved: %s\n", param->outputResultName);
nifti_image_free(warpedImage);
}
/* *********************** */
/* RESAMPLE A REGULAR GRID */
/* *********************** */
if(flag->outputBlankFlag ||
flag->outputBlankXYFlag ||
flag->outputBlankYZFlag ||
flag->outputBlankXZFlag )
{
nifti_image *gridImage = nifti_copy_nim_info(floatingImage);
gridImage->cal_min=0;
gridImage->cal_max=255;
gridImage->scl_slope=1.f;
gridImage->scl_inter=0.f;
gridImage->dim[0]=gridImage->ndim=floatingImage->nz>1?3:2;
gridImage->dim[1]=gridImage->nx=floatingImage->nx;
gridImage->dim[2]=gridImage->ny=floatingImage->ny;
gridImage->dim[3]=gridImage->nz=floatingImage->nz;
gridImage->dim[4]=gridImage->nt=1;
gridImage->dim[5]=gridImage->nu=1;
gridImage->nvox=(size_t)gridImage->nx*
gridImage->ny*gridImage->nz;
gridImage->datatype = NIFTI_TYPE_UINT8;
gridImage->nbyper = sizeof(unsigned char);
gridImage->data = (void *)calloc(gridImage->nvox, gridImage->nbyper);
unsigned char *gridImageValuePtr = static_cast<unsigned char *>(gridImage->data);
for(int z=0; z<gridImage->nz; z++)
{
for(int y=0; y<gridImage->ny; y++)
{
for(int x=0; x<gridImage->nx; x++)
{
if(referenceImage->nz>1)
{
if(flag->outputBlankXYFlag)
{
if( x/10==(float)x/10.0 || y/10==(float)y/10.0)
*gridImageValuePtr = 255;
}
else if(flag->outputBlankYZFlag)
{
if( y/10==(float)y/10.0 || z/10==(float)z/10.0)
*gridImageValuePtr = 255;
}
else if(flag->outputBlankXZFlag)
{
if( x/10==(float)x/10.0 || z/10==(float)z/10.0)
*gridImageValuePtr = 255;
}
else
{
if( x/10==(float)x/10.0 || y/10==(float)y/10.0 || z/10==(float)z/10.0)
*gridImageValuePtr = 255;
}
}
else
{
if( x/10==(float)x/10.0 || x==referenceImage->nx-1 || y/10==(float)y/10.0 || y==referenceImage->ny-1)
*gridImageValuePtr = 255;
}
gridImageValuePtr++;
}
}
}
nifti_image *warpedImage = nifti_copy_nim_info(referenceImage);
warpedImage->cal_min=0;
warpedImage->cal_max=255;
warpedImage->scl_slope=1.f;
warpedImage->scl_inter=0.f;
warpedImage->dim[0]=warpedImage->ndim=referenceImage->nz>1?3:2;
warpedImage->dim[1]=warpedImage->nx=referenceImage->nx;
warpedImage->dim[2]=warpedImage->ny=referenceImage->ny;
warpedImage->dim[3]=warpedImage->nz=referenceImage->nz;
warpedImage->dim[4]=warpedImage->nt=1;
warpedImage->dim[5]=warpedImage->nu=1;
warpedImage->datatype =NIFTI_TYPE_UINT8;
warpedImage->nbyper = sizeof(unsigned char);
warpedImage->data = (void *)calloc(warpedImage->nvox,
warpedImage->nbyper);
reg_resampleImage(gridImage,
warpedImage,
deformationFieldImage,
NULL,
1, // linear interpolation
0);
memset(warpedImage->descrip, 0, 80);
strcpy (warpedImage->descrip,"Warped regular grid using NiftyReg (reg_resample)");
reg_io_WriteImageFile(warpedImage,param->outputBlankName);
nifti_image_free(warpedImage);
nifti_image_free(gridImage);
if(verbose)
printf("[NiftyReg] Resampled grid has been saved: %s\n", param->outputBlankName);
}
// // Tell the CLI that we finished
// closeProgress("reg_resample", "Normal exit");
nifti_image_free(referenceImage);
nifti_image_free(floatingImage);
nifti_image_free(deformationFieldImage);
free(flag);
free(param);
return EXIT_SUCCESS;
}
| 38.123418 | 151 | 0.558521 | Barnonewdm |
938cf719dbd42d5ca3727e460f1042314873a7bb | 3,075 | cpp | C++ | codes/tool/Project.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | 3 | 2016-04-16T06:24:20.000Z | 2018-09-29T13:36:51.000Z | codes/tool/Project.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | null | null | null | codes/tool/Project.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | 3 | 2016-04-29T11:46:08.000Z | 2019-09-16T03:27:30.000Z | #include "Project.h"
#include <QAction>
#include <QFileDialog>
#include "modelimport/port.h"
#include "core/binary_reader_writer.h"
namespace tng
{
void ProjectMain::Init()
{
tng::Log* log = new tng::ConsoleLog;
tng::Log::SetLog(log);
string exename, exepath, exeext;
Path::GetExePath().Split(exepath, exename, exeext);
Path::SetWorkPath(exepath);
//ResourceManger::GetInstance()->AddLoader(LocalFilesLoader);
graphics::InitGraphics();
GFXService* gfx = GFXService::CreateGraphics();
InitModelImpPlugin();
QUiLoader loader;
QFile file("../EditorAsset/MainWindow.ui");
file.open(QFile::ReadOnly);
main_frame_ = loader.load(&file);
file.close();
if (main_frame_)
{
main_frame_->setWindowFlags(Qt::SubWindow);
}
setCentralWidget(main_frame_);
QAction* loadbtn = main_frame_->findChild<QAction*>("actionLoad");
connect(loadbtn, SIGNAL(triggered()), this, SLOT(OnLoad()));
QAction* expbtn = main_frame_->findChild<QAction*>("actionExport");
connect(expbtn, SIGNAL(triggered()), this, SLOT(OnExport()));
resize(1024, 768);
}
void ProjectMain::OnLoad()
{
QFileDialog dialog;
dialog.setFileMode(QFileDialog::DirectoryOnly);
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
dialog.setOption(QFileDialog::DontResolveSymlinks);
dialog.setViewMode(QFileDialog::Detail);
int res = dialog.exec();
if (res)
{
QDir directory = dialog.selectedFiles()[0];
LoadProject(directory.absolutePath().toUtf8().data());
}
}
void ProjectMain::OnExport()
{
QFileDialog dialog;
dialog.setFileMode(QFileDialog::DirectoryOnly);
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
dialog.setOption(QFileDialog::DontResolveSymlinks);
dialog.setViewMode(QFileDialog::Detail);
int res = dialog.exec();
if (res)
{
QDir directory = dialog.selectedFiles()[0];
Export(directory.absolutePath().toUtf8().data());
}
}
void ProjectMain::LoadProject(const string& path)
{
runing_path_ = path;
}
void ProjectMain::Export(const string& path)
{
vector<Path> retPath;
FileSystem::FindFiles(runing_path_, retPath, FileSystem::FFile, true);
StreamLoader* loader = ResourceManger::GetInstance()->GetLoader(LocalFilesLoader);
if (loader)
{
for each (Path var in retPath)
{
string fn, ext, dir;
var.Split(dir, fn, ext);
ToLower(ext);
if (ext == "res")
{
continue;
}
Path relativePath = Path(dir).RelativePath(runing_path_);
//use resource processor process every file,if no processor exist just copy to export dir
std::istream* content = loader->Load(var);
ResDecoder* decoder = ResourceManger::GetInstance()->GetDecoder(ext);
if (content)
{
string ext_e = decoder != NULL ? decoder->ResType() : ext;
if (ext_e == "res")
{
continue;
}
string pathexp = path + "/" + string(relativePath);
FileSystem::CreateDirs(pathexp);
FileOutputStream fs(pathexp + fn + "." + ext_e);
content->seekg(0, std::ios::beg);
fs << content->rdbuf();
fs.flush();
}
}
}
}
}
| 25.204918 | 93 | 0.682602 | liangpengcheng |
938d563efe409da780ef3115ba532f41ac67a326 | 1,136 | cpp | C++ | liberty/support/specpriv-profile/escape.cpp | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 18 | 2020-08-14T21:19:59.000Z | 2022-02-22T12:43:52.000Z | liberty/support/specpriv-profile/escape.cpp | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 23 | 2020-08-17T21:04:36.000Z | 2022-03-02T19:29:27.000Z | liberty/support/specpriv-profile/escape.cpp | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 2 | 2020-09-17T17:25:19.000Z | 2021-05-21T11:21:43.000Z | #include "escape.h"
void EscapeTable::report_escape(const AUHolder &au, const CtxHolder &ctx)
{
Escape key(au,ctx);
++escapeFrequencies[key];
}
void EscapeTable::report_local(const AUHolder &au, const CtxHolder &ctx)
{
for(CtxHolder cc=ctx; !cc.is_null(); cc=cc->parent)
{
Escape key(au,cc);
++localFrequencies[key];
}
}
void EscapeTable::print(std::ostream &fout) const
{
for(EscapeMap::const_iterator i=escapeFrequencies.begin(), e=escapeFrequencies.end(); i!=e; ++i)
{
AUHolder au = i->first.first;
CtxHolder ctx = i->first.second;
unsigned count = i->second;
fout << "ESCAPE OBJECT " << au << " ESCAPES " << ctx << " COUNT " << count << " ;\n";
}
for(EscapeMap::const_iterator i=localFrequencies.begin(), e=localFrequencies.end(); i!=e; ++i)
{
Escape key = i->first;
if( escapeFrequencies.count(key) )
continue;
unsigned count = i->second;
fout << "LOCAL OBJECT " << key.first << " IS LOCAL TO " << key.second << " COUNT " << count << " ;\n";
}
}
std::ostream &operator<<(std::ostream &fout, const EscapeTable &et)
{
et.print(fout);
return fout;
}
| 22.72 | 106 | 0.629401 | righier |
938ed5ee46e822eb997eee1f0ece1885b921cc16 | 9,515 | cpp | C++ | src/filesiconv/IconvWorker.cpp | hufuman/filesiconv | 1443469db1a37571c984b64027f8936c87dc3e3d | [
"MIT"
] | 2 | 2015-07-01T01:24:15.000Z | 2017-07-13T14:54:29.000Z | src/filesiconv/IconvWorker.cpp | hufuman/filesiconv | 1443469db1a37571c984b64027f8936c87dc3e3d | [
"MIT"
] | null | null | null | src/filesiconv/IconvWorker.cpp | hufuman/filesiconv | 1443469db1a37571c984b64027f8936c87dc3e3d | [
"MIT"
] | 3 | 2015-02-08T15:24:43.000Z | 2018-03-08T05:18:05.000Z | #include "StdAfx.h"
#include "IconvWorker.h"
#include "FileMap.h"
#include <cassert>
#include <Shlwapi.h>
BYTE g_byUtf8BOM[] = {0xEF, 0xBB, 0xBF};
BYTE g_byUnicodeBOM[] = {0xFF, 0xFE};
BOOL WriteFileHelper(HANDLE hFile, LPCVOID pBuffer, int nSize)
{
DWORD dwWritten = 0;
BOOL bResult = ::WriteFile(hFile, pBuffer, nSize, &dwWritten, NULL);
if(!bResult)
bResult = bResult;
bResult = bResult && (dwWritten == nSize);
if(!bResult)
bResult = bResult;
return bResult;
}
CIconvWorker::CIconvWorker(void)
{
m_arrFiles = NULL;
m_bStop = FALSE;
m_strTargetPath = _T("");
m_bOverwrite = FALSE;
m_bWriteBom = TRUE;
m_nSrcCodepage = CodeAuto;
m_nDstCodepage = CodeAuto;
m_pBuffer = NULL;
m_nBufferSize = 0;
}
CIconvWorker::~CIconvWorker(void)
{
ReleaseBuffer();
}
void CIconvWorker::SetCodepage(CodePageValue nSrcCodepage, CodePageValue nDstCodepage)
{
m_nSrcCodepage = nSrcCodepage;
m_nDstCodepage = nDstCodepage;
}
void CIconvWorker::SetFiles(ATL::CSimpleArray<CString>* arrFiles)
{
m_arrFiles = arrFiles;
}
void CIconvWorker::SetOverwrite(BOOL bOverwrite)
{
m_bOverwrite = bOverwrite;
}
void CIconvWorker::SetWriteBom(BOOL bWriteBom)
{
m_bWriteBom = bWriteBom;
}
void CIconvWorker::SetTargetPath(LPCTSTR szTargetPath)
{
m_strTargetPath = szTargetPath;
m_strTargetPath.Replace(_T('/'), _T('\\'));
if(m_strTargetPath.GetLength() > 0
&& m_strTargetPath[m_strTargetPath.GetLength() - 1] != _T('\\'))
{
m_strTargetPath += _T('\\');
}
}
BOOL CIconvWorker::Convert(ATL::CSimpleArray<CString>* failedFiles, ATL::CSimpleArray<CString>* outFiles)
{
m_bStop = FALSE;
if(failedFiles)
failedFiles->RemoveAll();
if(outFiles)
outFiles->RemoveAll();
CString strSrcTemp = GetTempFilePath();
int nCount = m_arrFiles->GetSize();
for(int i=0; !m_bStop && i<nCount; ++ i)
{
CString strSrc = (*m_arrFiles)[i];
// Get File Data
CFileMap m;
if(!m.MapFile(strSrc))
{
if(failedFiles)
failedFiles->Add(strSrc);
continue;
}
const BYTE * pData = static_cast<const BYTE *>(m.GetData());
int nSize = m.GetSize();
CodePageValue nSrcCodepage = m_nSrcCodepage;
if(nSrcCodepage == CodeAuto)
nSrcCodepage = GetFileCodepage(pData, nSize);
else
GetFileCodepage(pData, nSize);
CString strDstPath;
CodePageValue nDstCodepage = m_nDstCodepage;
if(nSrcCodepage == nDstCodepage)
{
m.Close();
if(!m_bOverwrite)
{
// Copy to dst
strDstPath = GetDstPath(strSrc);
if(CopyFile(strSrc, strDstPath, FALSE))
{
if(outFiles)
outFiles->Add(strSrc);
}
else
{
if(failedFiles)
failedFiles->Add(strSrc);
}
}
continue;
}
for(;;)
{
BOOL bResult = FALSE;
if((nSrcCodepage == CodeUnicode && nDstCodepage != CodeUnicode)
|| (nSrcCodepage != CodeUnicode && nDstCodepage == CodeUnicode))
{
if(!ConvFile(pData, nSize, strSrcTemp, nSrcCodepage, nDstCodepage))
break;
// Copy to dst
strDstPath = GetDstPath(strSrc);
m.Close();
if(!CopyFile(strSrcTemp, strDstPath, FALSE))
break;
if(outFiles)
outFiles->Add(strDstPath);
bResult = TRUE;
}
else
{
// nSrcCodepage != CodeUnicode && nDstCodepage != CodeUnicode
// Convert to unicode first
if(!ConvFile(pData, nSize, strSrcTemp, nSrcCodepage, CodeUnicode))
break;
m.Close();
// Convert to dst codepage
CString strDstTemp = GetTempFilePath();
CFileMap mTemp;
if(!mTemp.MapFile(strSrcTemp))
break;
pData = static_cast<const BYTE *>(mTemp.GetData());
nSize = mTemp.GetSize();
GetFileCodepage(pData, nSize);
if(!ConvFile(pData, nSize, strDstTemp, CodeUnicode, nDstCodepage))
break;
strDstPath = GetDstPath(strSrc);
mTemp.Close();
if(!CopyFile(strDstTemp, strDstPath, FALSE))
break;
if(outFiles)
outFiles->Add(strDstPath);
bResult = TRUE;
}
if(!bResult)
failedFiles->Add(strSrc);
break;
}
}
return (failedFiles->GetSize() == 0);
}
void CIconvWorker::Stop()
{
m_bStop = TRUE;
}
CString CIconvWorker::GetDstPath(LPCTSTR szSrcPath)
{
if(m_bOverwrite)
return szSrcPath;
LPCTSTR szFileName = ::PathFindFileName(szSrcPath);
CString strResult = m_strTargetPath + szFileName;
return strResult;
}
CodePageValue CIconvWorker::GetFileCodepage(const BYTE *& pData, int& nSize)
{
if(nSize >= 3 && memcmp(g_byUtf8BOM, pData, 3) == 0)
{
pData += 3;
nSize -= 3;
return CodeUtf8;
}
else if(nSize >= 2 && memcmp(g_byUnicodeBOM, pData, 2) == 0)
{
pData += 2;
nSize -= 2;
return CodeUnicode;
}
else
{
return CodeAnsi;
}
}
CString CIconvWorker::GetTempFilePath()
{
TCHAR szTmpPath[MAX_PATH];
TCHAR szTmpFile[MAX_PATH];
::GetTempPath(MAX_PATH, szTmpPath);
::GetTempFileName(szTmpPath, _T("iconv"), rand(), szTmpFile);
return szTmpFile;
}
BOOL CIconvWorker::ConvFile(const BYTE * pData, int nSize, LPCTSTR szDstPath, CodePageValue nSrcCodepage, CodePageValue nDstCodepage)
{
BOOL bMultiByteToWideChar = FALSE;
DWORD dwCodepage = GetRealCodepage(nSrcCodepage, nDstCodepage, bMultiByteToWideChar);
if(dwCodepage == -1)
return FALSE;
LPBYTE pBuffer = NULL;
int nBufferSize = 0;
if(bMultiByteToWideChar)
{
nBufferSize = ::MultiByteToWideChar(dwCodepage,
0,
(LPCSTR)pData,
nSize,
NULL,
0);
if(nBufferSize <= 0)
return (nSize == 0);
pBuffer = GetBuffer(nBufferSize * 2 + 2);
if(pBuffer == NULL)
return FALSE;
nBufferSize = ::MultiByteToWideChar(dwCodepage,
0,
(LPCSTR)pData,
nSize,
(LPWSTR)pBuffer,
nBufferSize);
if(nBufferSize == 0)
{
return FALSE;
}
nBufferSize = nBufferSize * 2;
}
else
{
nBufferSize = ::WideCharToMultiByte(dwCodepage,
0,
(LPCTSTR)pData,
nSize / 2,
0,
0,
0,
0);
if(nBufferSize == 0)
return (nSize == 0);
pBuffer = GetBuffer(nBufferSize + 1);
if(::WideCharToMultiByte(dwCodepage,
0,
(LPCTSTR)pData,
nSize / 2,
(LPSTR)pBuffer,
nBufferSize,
0,
0) == 0)
{
return FALSE;
}
}
HANDLE hFile = ::CreateFile(szDstPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if(hFile == INVALID_HANDLE_VALUE)
return FALSE;
BOOL bResult = TRUE;
// Write BOM
if(m_bWriteBom)
{
if(nDstCodepage == CodeUnicode)
{
bResult = WriteFileHelper(hFile, g_byUnicodeBOM, sizeof(g_byUnicodeBOM));
}
else if(nDstCodepage == CodeUtf8)
{
bResult = WriteFileHelper(hFile, g_byUtf8BOM, sizeof(g_byUtf8BOM));
}
}
if(bResult)
{
// Write Content
SetLastError(0);
bResult = WriteFileHelper(hFile, pBuffer, nBufferSize);
if(!bResult)
{
bResult = bResult;
}
}
else
{
bResult = bResult;
}
::CloseHandle(hFile);
return bResult;
}
DWORD CIconvWorker::GetRealCodepage(CodePageValue nSrcCodepage, CodePageValue nDstCodepage, BOOL& bMultiByteToWideChar)
{
DWORD dwCodepage = -1;
assert(nSrcCodepage == CodeUnicode || nDstCodepage == CodeUnicode);
bMultiByteToWideChar = (nDstCodepage == CodeUnicode);
struct
{
CodePageValue codepage;
DWORD dwCodepage;
} data[] =
{
{CodeAnsi, CP_ACP},
{CodeUnicode, CP_ACP},
{CodeUtf8, CP_UTF8},
{CodeChinese, 936},
};
CodePageValue codepage = (nSrcCodepage == CodeUnicode) ? nDstCodepage : nSrcCodepage;
for(int i=0; i<_countof(data); ++ i)
{
if(codepage == data[i].codepage)
dwCodepage = data[i].dwCodepage;
}
return dwCodepage;
}
LPBYTE CIconvWorker::GetBuffer(int nSize)
{
if(nSize <= m_nBufferSize)
return m_pBuffer;
ReleaseBuffer();
m_pBuffer = static_cast<LPBYTE>(malloc(nSize));
if(m_pBuffer)
m_nBufferSize = nSize;
return m_pBuffer;
}
void CIconvWorker::ReleaseBuffer()
{
if(m_pBuffer)
{
free(m_pBuffer);
m_pBuffer = NULL;
m_nBufferSize = 0;
}
}
| 24.714286 | 133 | 0.548292 | hufuman |
9390d396b3f0a13d8508cb8226a5b36d5ac6bff4 | 3,493 | hpp | C++ | Source/boost/scoped_ptr.hpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | 19 | 2018-09-21T09:44:42.000Z | 2022-03-26T03:37:02.000Z | Source/boost/scoped_ptr.hpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | 3 | 2019-07-19T08:58:50.000Z | 2021-02-03T19:42:00.000Z | Source/boost/scoped_ptr.hpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | 1 | 2021-08-23T02:44:27.000Z | 2021-08-23T02:44:27.000Z | #ifndef BOOST_SCOPED_PTR_HPP_INCLUDED
#define BOOST_SCOPED_PTR_HPP_INCLUDED
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001, 2002 Peter Dimov
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// http://www.boost.org/libs/smart_ptr/scoped_ptr.htm
//
// From Boost 1.31.0, http://www.boost.org
// Modified by Ori Peleg for use in NSIS, to reduce the required Boost includes
#include <cassert>
#include "checked_delete.hpp"
#include "detail/workaround.hpp"
#include <memory> // for std::auto_ptr or std::unique_ptr
// std::auto_ptr was deprecated in C++11 and removed in C++17
namespace NSIS { namespace CXX {
#if __cplusplus >= 201103L
template<class T> struct stdsmartptr { typedef std::unique_ptr<T> type; };
#else
template<class T> struct stdsmartptr { typedef std::auto_ptr<T> type; };
#endif
}} //~ NSIS::CXX
namespace boost
{
// scoped_ptr mimics a built-in pointer except that it guarantees deletion
// of the object pointed to, either on destruction of the scoped_ptr or via
// an explicit reset(). scoped_ptr is a simple solution for simple needs;
// use shared_ptr or std::auto_ptr if your needs are more complex.
template<class T> class scoped_ptr // noncopyable
{
private:
T * ptr;
scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &);
typedef scoped_ptr<T> this_type;
public:
typedef T element_type;
explicit scoped_ptr(T * p = 0): ptr(p) // never throws
{
}
explicit scoped_ptr(typename NSIS::CXX::stdsmartptr<T>::type p): ptr(p.release()) // never throws
{
}
~scoped_ptr() // never throws
{
boost::checked_delete(ptr);
}
void reset(T * p = 0) // never throws
{
assert(p == 0 || p != ptr); // catch self-reset errors
this_type(p).swap(*this);
}
T & operator*() const // never throws
{
assert(ptr != 0);
return *ptr;
}
T * operator->() const // never throws
{
assert(ptr != 0);
return ptr;
}
T * get() const // never throws
{
return ptr;
}
// implicit conversion to "bool"
#if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const
{
return ptr != 0;
}
#elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws
{
return ptr == 0? 0: &this_type::get;
}
#else
typedef T * this_type::*unspecified_bool_type;
operator unspecified_bool_type() const // never throws
{
return ptr == 0? 0: &this_type::ptr;
}
#endif
bool operator! () const // never throws
{
return ptr == 0;
}
void swap(scoped_ptr & b) // never throws
{
T * tmp = b.ptr;
b.ptr = ptr;
ptr = tmp;
}
};
template<class T> inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) // never throws
{
a.swap(b);
}
// get_pointer(p) is a generic way to say p.get()
template<class T> inline T * get_pointer(scoped_ptr<T> const & p)
{
return p.get();
}
} // namespace boost
#endif // #ifndef BOOST_SCOPED_PTR_HPP_INCLUDED
| 23.761905 | 101 | 0.643287 | Negrutiu |
939156ea6f4f5d734f26f71d3a7ddbda91b228a6 | 1,868 | cpp | C++ | gui/canvas.cpp | Krzysztof-Ambroziak/Game-of-Life | 41f6aa6814a227bb882f4a84a24e092b66564a4e | [
"MIT"
] | null | null | null | gui/canvas.cpp | Krzysztof-Ambroziak/Game-of-Life | 41f6aa6814a227bb882f4a84a24e092b66564a4e | [
"MIT"
] | null | null | null | gui/canvas.cpp | Krzysztof-Ambroziak/Game-of-Life | 41f6aa6814a227bb882f4a84a24e092b66564a4e | [
"MIT"
] | null | null | null | #include "canvas.h"
#include <QPainter>
#include <QMouseEvent>
Canvas::Canvas(const AbstractModel* const model, QWidget* parent):
QWidget(parent),
model(model) {
const int width = (model->getCellSize() + 1) * model->getColumns() + 1;
const int height = (model->getCellSize() + 1) * model->getRows() + 1;
setMinimumSize(width, height);
}
void Canvas::connectAction(Actions* actions) {
QObject::connect(this, SIGNAL(clicked(int, int)), actions, SLOT(changeCell(int, int)));
}
void Canvas::mousePressEvent(QMouseEvent* event) {
emit clicked(event->x(), event->y());
}
void Canvas::paintEvent(QPaintEvent* event) {
QPainter painter(this);
drawCells(&painter);
drawGrid(&painter);
}
void Canvas::drawCells(QPainter* painter) {
const int rows = model->getRows();
const int columns = model->getColumns();
const int cellSizeInc = model->getCellSize() + 1;
for(int row = 0; row < rows; ++row) {
for(int column = 0; column < columns; ++column) {
if(model->getLife(row, column) == ALIVE) {
painter->fillRect(column * cellSizeInc, row * cellSizeInc, cellSizeInc, cellSizeInc, Qt::black);
}
}
}
}
void Canvas::drawGrid(QPainter* painter) {
painter->setPen(Qt::lightGray);
drawHorizontalLines(painter);
drawVerticalLines(painter);
}
void Canvas::drawHorizontalLines(QPainter* painter) {
const int cellSizeInc = model->getCellSize() + 1;
for(int i = 0; i <= model->getRows(); ++i) {
const int y = i * cellSizeInc;
painter->drawLine(0, y, width(), y);
}
}
void Canvas::drawVerticalLines(QPainter* painter) {
const int cellSizeInc = model->getCellSize() + 1;
for(int i = 0; i <= model->getColumns(); ++i) {
const int x = i * cellSizeInc;
painter->drawLine(x, 0, x, height());
}
}
| 30.129032 | 112 | 0.625803 | Krzysztof-Ambroziak |
9394342d562e3af978f12e87fe18354ce2633bc2 | 2,475 | cpp | C++ | src/utilities/utility_MemoryBuffer.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 5 | 2019-02-24T06:42:52.000Z | 2021-04-09T19:16:24.000Z | src/utilities/utility_MemoryBuffer.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 40 | 2019-02-24T15:25:54.000Z | 2021-05-17T04:22:43.000Z | src/utilities/utility_MemoryBuffer.cpp | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 2 | 2019-02-23T22:58:36.000Z | 2019-02-27T01:27:42.000Z | /*
* MemoryBuffer.cpp
*/
#include "utility_MemoryBuffer.h"
#include <string.h>
#include <stddef.h>
#include <streambuf>
#define INITIAL_BUFFER_SIZE_BYTES 4096
namespace mutgos
{
namespace utility
{
// ----------------------------------------------------------------------
MemoryBuffer::MemoryBuffer(const void *data_ptr, const size_t data_size)
: read_only(true)
{
// Yes, I am undoing the const declaration, but the data
// will not be modified. It is a requirement of streambuf.
setg((char *)data_ptr, (char *)data_ptr, (char *)data_ptr + data_size);
}
// ----------------------------------------------------------------------
MemoryBuffer::MemoryBuffer(void)
: read_only(false)
{
char *buffer_ptr = new char[INITIAL_BUFFER_SIZE_BYTES];
setp(buffer_ptr, buffer_ptr + INITIAL_BUFFER_SIZE_BYTES);
}
// ----------------------------------------------------------------------
MemoryBuffer::~MemoryBuffer()
{
if (not read_only)
{
delete[] pbase();
setp(0, 0);
}
}
// ----------------------------------------------------------------------
bool MemoryBuffer::get_data(char *&data_ptr, size_t &data_size)
{
if (not read_only)
{
data_ptr = pbase();
data_size = pptr() - pbase();
return data_ptr;
}
return false;
}
// ----------------------------------------------------------------------
MemoryBuffer::int_type MemoryBuffer::overflow(MemoryBuffer::int_type c)
{
char *data_ptr = 0;
size_t data_size = 0;
if ((not read_only) and get_data(data_ptr, data_size))
{
const size_t bigger_size = data_size * 2;
char *bigger_data_ptr = new char[bigger_size];
memcpy(bigger_data_ptr, data_ptr, data_size);
setp(bigger_data_ptr, bigger_data_ptr + bigger_size);
pbump(data_size);
delete[] data_ptr;
data_ptr = 0;
if (c != traits_type::eof())
{
// Append character if not EOF
//
*pptr() = (char) c;
pbump(1);
}
return c;
}
else
{
// Not a write buffer or can't get the existing pointer.
return traits_type::eof();
}
}
} // utilities
} // mutgos
| 26.052632 | 79 | 0.460202 | hyena |
9394c693572d896b65a9953bc534cba9690a82eb | 2,749 | cxx | C++ | panda/src/pgraph/loaderFileTypeBam.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/pgraph/loaderFileTypeBam.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/pgraph/loaderFileTypeBam.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file loaderFileTypeBam.cxx
* @author jason
* @date 2000-06-21
*/
#include "loaderFileTypeBam.h"
#include "config_pgraph.h"
#include "bamFile.h"
#include "bamCacheRecord.h"
#include "modelRoot.h"
#include "loaderOptions.h"
#include "dcast.h"
TypeHandle LoaderFileTypeBam::_type_handle;
/**
*
*/
LoaderFileTypeBam::
LoaderFileTypeBam() {
}
/**
*
*/
string LoaderFileTypeBam::
get_name() const {
return "Bam";
}
/**
*
*/
string LoaderFileTypeBam::
get_extension() const {
return "bam";
}
/**
* Returns true if this file type can transparently load compressed files
* (with a .pz or .gz extension), false otherwise.
*/
bool LoaderFileTypeBam::
supports_compressed() const {
return true;
}
/**
* Returns true if the file type can be used to load files, and load_file() is
* supported. Returns false if load_file() is unimplemented and will always
* fail.
*/
bool LoaderFileTypeBam::
supports_load() const {
return true;
}
/**
* Returns true if the file type can be used to save files, and save_file() is
* supported. Returns false if save_file() is unimplemented and will always
* fail.
*/
bool LoaderFileTypeBam::
supports_save() const {
return true;
}
/**
*
*/
PT(PandaNode) LoaderFileTypeBam::
load_file(const Filename &path, const LoaderOptions &options,
BamCacheRecord *record) const {
if (record != (BamCacheRecord *)NULL) {
record->add_dependent_file(path);
}
bool report_errors = (options.get_flags() & LoaderOptions::LF_report_errors) != 0;
BamFile bam_file;
if (!bam_file.open_read(path, report_errors)) {
return NULL;
}
bam_file.get_reader()->set_loader_options(options);
time_t timestamp = bam_file.get_reader()->get_source()->get_timestamp();
PT(PandaNode) node = bam_file.read_node(report_errors);
if (node != (PandaNode *)NULL && node->is_of_type(ModelRoot::get_class_type())) {
ModelRoot *model_root = DCAST(ModelRoot, node.p());
model_root->set_fullpath(path);
model_root->set_timestamp(timestamp);
}
return node;
}
/**
*
*/
bool LoaderFileTypeBam::
save_file(const Filename &path, const LoaderOptions &options,
PandaNode *node) const {
BamFile bam_file;
bool report_errors = (options.get_flags() & LoaderOptions::LF_report_errors) != 0;
bool okflag = false;
if (bam_file.open_write(path, report_errors)) {
if (bam_file.write_object(node)) {
okflag = true;
}
bam_file.close();
}
return okflag;
}
| 21.645669 | 84 | 0.697344 | sean5470 |
9394c96f6fac255fc668b2770bcecf5f8b8a67a6 | 1,016 | cpp | C++ | src/QtFTP/FTP/nBonjourRecord.cpp | Vladimir-Lin/QtFTP | a297ac9cd3dd44407a39adcd87953fb4d2d90f1f | [
"MIT"
] | null | null | null | src/QtFTP/FTP/nBonjourRecord.cpp | Vladimir-Lin/QtFTP | a297ac9cd3dd44407a39adcd87953fb4d2d90f1f | [
"MIT"
] | null | null | null | src/QtFTP/FTP/nBonjourRecord.cpp | Vladimir-Lin/QtFTP | a297ac9cd3dd44407a39adcd87953fb4d2d90f1f | [
"MIT"
] | null | null | null | #include <qtftp.h>
N::BonjourRecord:: BonjourRecord(void)
{
}
N::BonjourRecord:: BonjourRecord (
const QString & name ,
const QString & regType ,
const QString & domain )
: serviceName ( name )
, registeredType ( regType )
, replyDomain ( domain )
{
}
N::BonjourRecord:: BonjourRecord (
const char * name ,
const char * regType ,
const char * domain )
{
serviceName = QString :: fromUtf8 ( name ) ;
registeredType = QString :: fromUtf8 ( regType ) ;
replyDomain = QString :: fromUtf8 ( domain ) ;
}
N::BonjourRecord::~BonjourRecord(void)
{
}
bool N::BonjourRecord::operator == (const BonjourRecord & other) const
{
return ( serviceName == other.serviceName &&
registeredType == other.registeredType &&
replyDomain == other.replyDomain ) ;
}
| 27.459459 | 70 | 0.515748 | Vladimir-Lin |
93966166dcfeeb1355a91268734307e26950ffea | 11,525 | cpp | C++ | src/clp/FileCompressor.cpp | NITROGENousFish/clp-core | 2dcc58aae66a97fca43a139a4ff637005c0f9065 | [
"Apache-2.0"
] | null | null | null | src/clp/FileCompressor.cpp | NITROGENousFish/clp-core | 2dcc58aae66a97fca43a139a4ff637005c0f9065 | [
"Apache-2.0"
] | null | null | null | src/clp/FileCompressor.cpp | NITROGENousFish/clp-core | 2dcc58aae66a97fca43a139a4ff637005c0f9065 | [
"Apache-2.0"
] | null | null | null | #include "FileCompressor.hpp"
// C++ standard libraries
#include <algorithm>
#include <iostream>
#include <set>
// Boost libraries
#include <boost/filesystem/path.hpp>
// libarchive
#include <archive_entry.h>
// Project headers
#include "utils.hpp"
using std::cout;
using std::endl;
using std::set;
using std::string;
using std::vector;
// Local prototypes
/**
* Computes empty directories as directories - parent_directories and adds them to the given archive
* @param directories
* @param parent_directories
* @param parent_path Path that should be the parent of all added directories
* @param archive
*/
static void compute_and_add_empty_directories (const set<string>& directories, const set<string>& parent_directories,
const boost::filesystem::path& parent_path, streaming_archive::writer::Archive& archive);
/**
* Writes the given message to the given encoded file
* @param msg
* @param archive
* @param file
*/
static void write_message_to_encoded_file (const ParsedMessage& msg, streaming_archive::writer::Archive& archive, streaming_archive::writer::File* file);
static void compute_and_add_empty_directories (const set<string>& directories, const set<string>& parent_directories,
const boost::filesystem::path& parent_path, streaming_archive::writer::Archive& archive)
{
// Determine empty directories by subtracting parent directories
vector<string> empty_directories;
auto directories_ix = directories.cbegin();
for (auto parent_directories_ix = parent_directories.cbegin();
directories.cend() != directories_ix && parent_directories.cend() != parent_directories_ix;)
{
const auto& directory = *directories_ix;
const auto& parent_directory = *parent_directories_ix;
if (directory < parent_directory) {
auto boost_path_for_compression = parent_path / directory;
empty_directories.emplace_back(boost_path_for_compression.string());
++directories_ix;
} else if (directory == parent_directory) {
++directories_ix;
++parent_directories_ix;
} else {
++parent_directories_ix;
}
}
for (; directories.cend() != directories_ix; ++directories_ix) {
auto boost_path_for_compression = parent_path / *directories_ix;
empty_directories.emplace_back(boost_path_for_compression.string());
}
archive.add_empty_directories(empty_directories);
}
static void write_message_to_encoded_file (const ParsedMessage& msg, streaming_archive::writer::Archive& archive, streaming_archive::writer::File* file) {
if (msg.has_ts_patt_changed()) {
archive.change_ts_pattern(*file, msg.get_ts_patt());
}
archive.write_msg(*file, msg.get_ts(), msg.get_content(), msg.get_orig_num_bytes());
}
namespace clp {
bool FileCompressor::compress_file (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const FileToCompress& file_to_compress,
streaming_archive::writer::Archive& archive_writer)
{
m_file_reader.open(file_to_compress.get_path());
// Check that file is UTF-8 encoded
auto error_code = m_file_reader.try_read(m_utf8_validation_buf, cUtf8ValidationBufCapacity, m_utf8_validation_buf_length);
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile != error_code) {
SPDLOG_ERROR("Failed to read {}, errno={}", file_to_compress.get_path().c_str(), errno);
return false;
}
}
bool succeeded = true;
if (is_utf8_sequence(m_utf8_validation_buf_length, m_utf8_validation_buf)) {
parse_and_encode(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
file_to_compress.get_path_for_compression(), file_to_compress.get_group_id(), archive_writer, m_file_reader);
} else {
if (false == try_compressing_as_archive(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
file_to_compress, archive_writer))
{
succeeded = false;
}
}
m_file_reader.close();
return succeeded;
}
void FileCompressor::parse_and_encode (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const string& path_for_compression, group_id_t group_id,
streaming_archive::writer::Archive& archive_writer, ReaderInterface& reader)
{
m_parsed_message.clear();
// Open compressed file
auto* file = create_and_open_in_memory_file(archive_writer, path_for_compression, group_id, m_uuid_generator(), 0);
// Parse content from UTF-8 validation buffer
size_t buf_pos = 0;
while (m_message_parser.parse_next_message(false, m_utf8_validation_buf_length, m_utf8_validation_buf, buf_pos, m_parsed_message)) {
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_file_and_archive(archive_user_config, print_archive_ids, path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer,
file);
} else if (file->get_encoded_size_in_bytes() >= target_encoded_file_size) {
split_file(path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer, file);
}
write_message_to_encoded_file(m_parsed_message, archive_writer, file);
}
// Parse remaining content from file
while (m_message_parser.parse_next_message(true, reader, m_parsed_message)) {
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_file_and_archive(archive_user_config, print_archive_ids, path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer,
file);
} else if (file->get_encoded_size_in_bytes() >= target_encoded_file_size) {
split_file(path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer, file);
}
write_message_to_encoded_file(m_parsed_message, archive_writer, file);
}
close_file_and_mark_ready_for_segment(archive_writer, file);
}
bool FileCompressor::try_compressing_as_archive (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const FileToCompress& file_to_compress,
streaming_archive::writer::Archive& archive_writer)
{
auto file_boost_path = boost::filesystem::path(file_to_compress.get_path_for_compression());
auto parent_boost_path = file_boost_path.parent_path();
// Determine path without extension (used if file is a single compressed file, e.g., syslog.gz -> syslog)
std::string filename_if_compressed;
if (file_boost_path.has_stem()) {
filename_if_compressed = file_boost_path.stem().string();
} else {
filename_if_compressed = file_boost_path.filename().string();
}
// Check if it's an archive
auto error_code = m_libarchive_reader.try_open(m_utf8_validation_buf_length, m_utf8_validation_buf, m_file_reader, filename_if_compressed);
if (ErrorCode_Success != error_code) {
SPDLOG_ERROR("Cannot compress {} - not UTF-8 encoded.", file_to_compress.get_path().c_str());
return false;
}
// Compress each file and directory in the archive
bool succeeded = true;
set<string> directories;
set<string> parent_directories;
while (true) {
error_code = m_libarchive_reader.try_read_next_header();
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile == error_code) {
break;
}
SPDLOG_ERROR("Failed to read entry in {}.", file_to_compress.get_path().c_str());
succeeded = false;
break;
}
// Determine what type of file it is
auto file_type = m_libarchive_reader.get_entry_file_type();
if (AE_IFREG != file_type) {
if (AE_IFDIR == file_type) {
// Trim trailing slash
string directory_path(m_libarchive_reader.get_path());
directory_path.resize(directory_path.length() - 1);
directories.emplace(directory_path);
auto directory_parent_path = boost::filesystem::path(directory_path).parent_path().string();
if (false == directory_parent_path.empty()) {
parent_directories.emplace(directory_parent_path);
}
} // else ignore irregular files
continue;
}
auto file_parent_path = boost::filesystem::path(m_libarchive_reader.get_path()).parent_path().string();
if (false == file_parent_path.empty()) {
parent_directories.emplace(file_parent_path);
}
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_archive(archive_user_config, print_archive_ids, archive_writer);
}
m_libarchive_reader.open_file_reader(m_libarchive_file_reader);
// Check that file is UTF-8 encoded
error_code = m_libarchive_file_reader.try_read(m_utf8_validation_buf, cUtf8ValidationBufCapacity, m_utf8_validation_buf_length);
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile != error_code) {
SPDLOG_ERROR("Failed to read {} from {}.", m_libarchive_reader.get_path(), file_to_compress.get_path().c_str());
m_libarchive_file_reader.close();
succeeded = false;
continue;
}
}
if (is_utf8_sequence(m_utf8_validation_buf_length, m_utf8_validation_buf)) {
auto boost_path_for_compression = parent_boost_path / m_libarchive_reader.get_path();
parse_and_encode(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
boost_path_for_compression.string(), file_to_compress.get_group_id(), archive_writer, m_libarchive_file_reader);
} else {
SPDLOG_ERROR("Cannot compress {} - not UTF-8 encoded.", m_libarchive_reader.get_path());
succeeded = false;
}
m_libarchive_file_reader.close();
}
compute_and_add_empty_directories(directories, parent_directories, parent_boost_path, archive_writer);
m_libarchive_reader.close();
return succeeded;
}
}
| 47.427984 | 158 | 0.653189 | NITROGENousFish |
939766ed756a9cf44e433c592abc0ba7a57e6518 | 4,308 | cpp | C++ | mock-eye-module/main.cpp | hogaku/azure-percept-advanced-development | 90177b9f1ec96dee1e7c436af5471007c4092655 | [
"MIT"
] | 52 | 2021-03-02T14:28:37.000Z | 2022-02-07T20:27:52.000Z | mock-eye-module/main.cpp | hogaku/azure-percept-advanced-development | 90177b9f1ec96dee1e7c436af5471007c4092655 | [
"MIT"
] | 29 | 2021-03-03T09:36:33.000Z | 2022-03-12T00:59:10.000Z | mock-eye-module/main.cpp | hogaku/azure-percept-advanced-development | 90177b9f1ec96dee1e7c436af5471007c4092655 | [
"MIT"
] | 30 | 2021-03-02T14:09:14.000Z | 2022-03-11T05:58:54.000Z | /**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*
* Use this application as a test bed for adding new AI models to the Azure Percept DK azureeyemodule.
* This application is small and easy to extend, so can be used for debugging and proving that a model
* works before porting it to the Azure Percept DK.
*/
// Standard Library includes
#include <fstream>
#include <iostream>
#include <signal.h>
#include <string>
#include <vector>
// Local includes
#include "kernels/utils.hpp"
#include "modules/device.hpp"
#include "modules/objectdetection/object_detectors.hpp"
#include "modules/parser.hpp"
/** Arguments for this program (short-arg long-arg | default-value | help message) */
static const std::string keys =
"{ h help | | Print this message }"
"{ d device | CPU | Device to run inference on. Options: CPU, GPU, NCS2 }"
"{ p parser | ssd | Parser kind required for input model. Possible values: ssd }"
"{ w weights | | Weights file }"
"{ x xml | | Network XML file }"
"{ labels | | Path to the labels file }"
"{ show | false | Show output BGR image. Requires graphical environment }"
"{ video_in | | If given, we use this file as input instead of the camera }";
/**
* This is just a helper function for loading a label file.
*
* @param labelfile The path to the label file. Should be a file that contains one label per line.
* @returns The class list from the file.
*/
static std::vector<std::string> load_label(const std::string &labelfile)
{
std::vector<std::string> classes;
std::ifstream file(labelfile);
if (file.is_open())
{
std::string line;
while (std::getline(file, line))
{
// remove \r in the end of line
if (!line.empty() && line[line.size() - 1] == '\r')
{
line.erase(line.size() - 1);
}
classes.push_back(line);
}
file.close();
}
else
{
std::cerr << "Cannot open labelfile " << labelfile << std::endl;
std::cerr << "Labels will not be available." << std::endl;
}
return classes;
}
/** If we receive a SIGINT, we print a message and try to exit cleanly. */
static void interrupt(int)
{
std::cout << "Received interrupt signal." << std::endl;
exit(0);
}
/**
* Here's the main function.
* To add a new AI model, all you need to do is add a corresponding "parser",
* which is the code that is used to load the neural network and post-process its outputs.
*
* 1. Start by adding an enum variant to the parser enum in modules/parser.[c/h]pp.
* 2. Then add a new module into modules/. If you are adding an object detector, you can make use
* of some of the code in modules/object_detectors.[c/h]pp.
*/
int main(int argc, char* argv[])
{
// Parse the command line args
cv::CommandLineParser cmd(argc, argv, keys);
if (cmd.has("help"))
{
cmd.printMessage();
return 0;
}
// Assign application parameters
const auto dev = device::look_up_device(cmd.get<std::string>("device"));
const auto parser = parser::look_up_parser(cmd.get<std::string>("parser"));
const auto weights = cmd.get<std::string>("weights");
const auto xml = cmd.get<std::string>("xml");
const auto labelfile = cmd.get<std::string>("labels");
const auto show = cmd.get<bool>("show");
const auto video_in = cmd.get<std::string>("video_in");
// Set up SIGINT handler - we peform cleanup and exit the application
signal(SIGINT, interrupt);
// Choose the appropriate path based on the parser we've chosen (which indicates which model we are running)
// If you are extending this application, add a new case with your parser here. Take a look at one of the other
// compile_and_run() functions to use as an example.
std::vector<std::string> classes;
switch (parser)
{
case parser::Parser::SSD:
classes = load_label(labelfile);
detection::compile_and_run(video_in, parser, xml, weights, dev, show, classes);
break;
default:
std::cerr << "Programmer error: Please implement the appropriate logic for this Parser." << std::endl;
exit(__LINE__);
}
return 0;
}
| 35.02439 | 115 | 0.639044 | hogaku |
9397a1566ba2f8b4d802fe9b27344fc1e0dac58f | 1,323 | cpp | C++ | shared_mutex.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | null | null | null | shared_mutex.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | null | null | null | shared_mutex.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | 1 | 2021-10-01T04:27:44.000Z | 2021-10-01T04:27:44.000Z | #include <iostream>
#include <boost/thread.hpp>
using namespace std;
boost::mutex io_mu;
class rw_data
{
private:
int m_x;
boost::shared_mutex rw_mu;
public:
rw_data() : m_x(0)
{ }
void write()
{
boost::unique_lock<boost::shared_mutex> ul(rw_mu);
++m_x;
}
void read(int *x)
{
boost::shared_lock<boost::shared_mutex> sl(rw_mu);
*x = m_x;
}
int get_value()
{ return m_x; }
};
void writer(rw_data &d)
{
for (int i = 0; i < 20; ++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(10));
d.write();
boost::mutex::scoped_lock lock(io_mu);
cout << boost::this_thread::get_id() << " write " << d.get_value() << endl;
}
}
void reader(rw_data &d)
{
int x;
for (int i = 0; i < 10; ++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(5));
d.read(&x);
boost::mutex::scoped_lock lock(io_mu);
cout << boost::this_thread::get_id() << " reader: " << x << endl;
}
}
int main()
{
rw_data d;
boost::thread_group pool;
for (int i = 0; i < 4; ++i)
pool.create_thread(bind(reader, boost::ref(d)));
for (int i = 0; i < 2; ++i)
pool.create_thread(bind(writer, boost::ref(d)));
pool.join_all();
return 0;
}
| 18.633803 | 83 | 0.543462 | opensvn |
939ac781007d93639b949611cab142451205015c | 5,313 | cpp | C++ | libraries/PION/src/PION_Network.cpp | joaopedrovbs/arduino-support-test | 1bea23f00040e386b44285f926b6871ba1bcd5fb | [
"MIT"
] | 17 | 2021-07-28T21:57:26.000Z | 2022-02-28T20:32:04.000Z | libraries/PION/src/PION_Network.cpp | joaopedrovbs/arduino-support-test | 1bea23f00040e386b44285f926b6871ba1bcd5fb | [
"MIT"
] | 7 | 2021-08-07T23:20:14.000Z | 2022-03-20T15:05:21.000Z | libraries/PION/src/PION_Network.cpp | joaopedrovbs/arduino-support-test | 1bea23f00040e386b44285f926b6871ba1bcd5fb | [
"MIT"
] | 10 | 2021-08-11T13:47:36.000Z | 2022-03-26T02:41:45.000Z | #include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include "_config.h"
#include "_types.h"
#include "webpage.h"
#include "PION_System.h"
#include "PION_Network.h"
#include "PION_Sensors.h"
#include "PION_Storage.h"
#include "PION_Interface.h"
// External Objects
AsyncWebServer server(80);
char ssidId[32]; // Final ssid buffer
uint32_t chipId; // chipId Holder
String baseName = "PION Satélite "; // WiFi Base SSID to have the id string added
const char* password = "meusatpion"; // Default WiFi Password
TaskHandle_t Network::netTask;
void sendDataWs();
void NetworkTask(void *pvParameters);
void onEvent(AsyncWebSocket *, AsyncWebSocketClient *, AwsEventType , void *, uint8_t *, size_t );
AsyncWebSocket ws("/ws");
const char* sdStatusMessage[] = {"NO_SD","SD_CONNECTED","SD_RECORDING","SD_ERROR"};
const char* sirenMessage[] = {"ALARM_OFF","ALARM_SIREN","ALARM_ERROR","ALARM_LOW_BATTERY"};
__attribute__((weak)) void networkConnect(){
// Transforma o serial number do sistema em uma String
String id = String(System::getSerialNumber());
// Cria uma nova String com o nome PION Satélite + o serial
String ssid = baseName + id;
// Adapta a string para um array de caracteres
ssid.toCharArray(ssidId, sizeof(ssidId));
// Para qualquer aplicação bluetooth que possa existir
btStop();
// Inicializa um WiFi Access Point com um nome + serial e a senha padrão
WiFi.mode(WIFI_AP);
WiFi.softAP(ssidId, password);
WiFi.setHostname("PION Satelite");
}
__attribute__((weak)) void serverResponse(){
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
// Send File
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", DASH_HTML, DASH_HTML_SIZE);
response->addHeader("Content-Encoding","gzip");
request->send(response);
});
}
void Network::init(){
networkConnect();
serverResponse();
ws.onEvent(onEvent);
server.addHandler(&ws);
// Start Web Server
server.begin();
xTaskCreatePinnedToCore(NetworkTask, "NetworkTask", 8192, NULL, 1, &Network::netTask, ARDUINO_RUNNING_CORE);
}
void Network::deInit(){
vTaskSuspend(Network::netTask);
// server.reset();
server.end();
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void NetworkTask(void *pvParameters){
(void) pvParameters;
for (;;){
sendDataWs();
vTaskDelay(1000);
}
}
__attribute__((weak)) void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, "toggleRGB") == 0) {
Interface::shouldChangeRGB = true;
} else if (strcmp((char*)data, "toggleLED") == 0) {
Interface::shouldChangeLed = true;
} else if (strcmp((char*)data, "toggleSiren") == 0) {
Interface::toggleSiren();
} else if (strcmp((char*)data, "toggleSD1") == 0) {
Storage::toggleSD(0);
} else if (strcmp((char*)data, "toggleSD2") == 0) {
Storage::toggleSD(1);
} else if (strcmp((char*)data, "reboot") == 0) {
ESP.restart();
}
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket cliente #%u conectado do %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket cliente #%u desconectado\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
default:
break;
}
}
__attribute__((weak)) void sendDataWs() {
// Faz a alocação de 512 Bytes para o JSON
DynamicJsonDocument jsonBuffer(512);
// Adiciona todas as leituras necessárias com o formato chave:valor do JSON
jsonBuffer["bateria"] = System::battery;
jsonBuffer["pressao"] = Sensors::pressure;
jsonBuffer["temperatura"] = Sensors::temperature;
jsonBuffer["humidade"] = Sensors::humidity;
jsonBuffer["co2"] = Sensors::CO2Level;
jsonBuffer["luminosidade"] = Sensors::luminosity;
jsonBuffer["sdCard"] = sdStatusMessage[Storage::sdStatus];
jsonBuffer["siren"] = sirenMessage[Interface::sirenAction];
// Adiciona as leituras a um array dentro do JSON
JsonArray accel = jsonBuffer.createNestedArray("acelerometro");
accel.add(Sensors::accel[0]);
accel.add(Sensors::accel[1]);
accel.add(Sensors::accel[2]);
JsonArray gyro = jsonBuffer.createNestedArray("giroscopio");
gyro.add(Sensors::gyro[0]);
gyro.add(Sensors::gyro[1]);
gyro.add(Sensors::gyro[2]);
JsonArray mag = jsonBuffer.createNestedArray("magnetometro");
mag.add(Sensors::mag[0]);
mag.add(Sensors::mag[1]);
mag.add(Sensors::mag[2]);
// Mede o tamanho do buffer do JSON
size_t len = measureJson(jsonBuffer);
// Cria um espaço na RAM de (len + 1)
AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len);
if (buffer) {
// Transforma o JSON em um grande texto e o coloca no espaço criado anteriormente
serializeJson(jsonBuffer,(char *)buffer->get(), len + 1);
// Envia pelo WebSocket para todos os usuários
ws.textAll(buffer);
}
}
| 30.534483 | 125 | 0.678336 | joaopedrovbs |
4d34bfb49b84429f084a6ffb47759ba06fecac7f | 5,457 | hpp | C++ | heart/src/problem/AbstractOutputModifier.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-04-05T12:11:54.000Z | 2020-04-05T12:11:54.000Z | heart/src/problem/AbstractOutputModifier.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | heart/src/problem/AbstractOutputModifier.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-04-05T14:26:13.000Z | 2021-03-09T08:18:17.000Z | /*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ABSTRACTOUTPUTMODIFIER_HPP_
#define ABSTRACTOUTPUTMODIFIER_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/string.hpp>
#include "ClassIsAbstract.hpp"
#include <string>
#include "AbstractTetrahedralMesh.hpp"
/**
* A plug-in class for on-the-fly output. This is designed so that a user can insert something in
* order to monitor the progress of a simulation or to produce "post processed" output during the simulation.
*/
class AbstractOutputModifier
{
private:
/** For testing */
friend class TestMonodomainProblem;
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive this modifier. Just calls the base class version.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & mFilename;
archive & mFlushTime;
}
protected:
/** Constructor that does nothing, for archiving */
AbstractOutputModifier()
: mFilename(), mFlushTime(0.0)
{}
std::string mFilename; /**<The file which is eventually produced by this modifier*/
/** Simulation time period between flushes to disk */
double mFlushTime;
public:
/**
* Standard construction method contains only the name of the file which this simulation modifier should produce.
*
* Note that construction occurs before the Solve() loop and probably before initialisation. This means that it
* will not be possible to view certain data (e.g the mesh) at the time of construction
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible.
* @param rFilename The file which is eventually produced by this modifier
* @param flushTime The (simulation) time between flushing the file to disk. Default (0) means don't flush.
*
*/
AbstractOutputModifier(const std::string& rFilename, double flushTime=0.0)
: mFilename(rFilename),
mFlushTime(flushTime)
{}
/**
* Destructor should be overridden when necessary
*/
virtual ~AbstractOutputModifier()
{
}
/**
* Initialise the modifier (open a file or make some memory) when the solve loop is starting
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible. That is, it might have been slicker to pass in the mesh but that would require multiple templates.
* @param pVectorFactory The vector factory which is associated with the calling problem's mesh
* @param rNodePermutation The permutation associated with the calling problem's mesh (when running with parallel partitioning)
*/
virtual void InitialiseAtStart(DistributedVectorFactory* pVectorFactory, const std::vector<unsigned>& rNodePermutation)=0;
/**
* Finalise the modifier (close a file or dump the calculation to disk)
*/
virtual void FinaliseAtEnd()=0;
/**
* Process a solution time-step (dump a small line to file or compute the latest activation times)
* @param time The current simulation time
* @param solution A working copy of the solution at the current time-step. This is the PETSc vector which is distributed across the processes.
* @param problemDim The calling problem dimension. Used here to avoid probing the size of the solution vector
*/
virtual void ProcessSolutionAtTimeStep(double time, Vec solution, unsigned problemDim)=0;
};
CLASS_IS_ABSTRACT(AbstractOutputModifier)
#endif /* ABSTRACTOUTPUTMODIFIER_HPP_ */
| 40.422222 | 149 | 0.741067 | AvciRecep |
4d3760308ef4831c1a67e90b12f03528116f8323 | 2,699 | cpp | C++ | lib/database.cpp | ml4ai/delphi | 9294d2d491f10c297c84f1cd5fdc9b55b6f866d9 | [
"Apache-2.0"
] | 25 | 2018-03-03T11:57:57.000Z | 2022-01-16T21:19:54.000Z | lib/database.cpp | ml4ai/delphi | 9294d2d491f10c297c84f1cd5fdc9b55b6f866d9 | [
"Apache-2.0"
] | 385 | 2018-02-21T16:52:06.000Z | 2022-02-17T07:44:56.000Z | lib/database.cpp | ml4ai/delphi | 9294d2d491f10c297c84f1cd5fdc9b55b6f866d9 | [
"Apache-2.0"
] | 19 | 2018-03-20T01:08:11.000Z | 2021-09-29T01:04:49.000Z | #include "AnalysisGraph.hpp"
#include <nlohmann/json.hpp>
using namespace std;
using namespace delphi::utils;
using json = nlohmann::json;
sqlite3* AnalysisGraph::open_delphi_db(int mode) {
char* pPath;
pPath = getenv ("DELPHI_DB");
if (pPath == NULL) {
cout << "\n\nERROR: DELPHI_DB environment variable containing the path to delphi.db is not set!\n\n";
exit(1);
}
sqlite3* db = nullptr;
if (sqlite3_open_v2(getenv("DELPHI_DB"), &db, mode, NULL) != SQLITE_OK) {
cout << "\n\nERROR: delphi.db does not exist at " << pPath << endl;
cout << sqlite3_errmsg(db) << endl;
exit(1);
}
return db;
}
void AnalysisGraph::write_model_to_db(string model_id) {
if (!model_id.empty()) {
sqlite3* db = this->open_delphi_db(SQLITE_OPEN_READWRITE);
if (db == nullptr) {
cout << "\n\nERROR: opening delphi.db" << endl;
exit(1);
}
char* zErrMsg = 0;
string query = "replace into delphimodel values ('" + model_id + "', '" +
this->serialize_to_json_string(false) + "');";
int rc = sqlite3_exec(db, query.c_str(), NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK) {
cout << "Could not write\n";
cout << zErrMsg << endl;
}
sqlite3_close(db);
db = nullptr;
}
}
/**
* This is a helper function used by construct_theta_pdfs()
*/
AdjectiveResponseMap AnalysisGraph::construct_adjective_response_map(
mt19937 gen,
uniform_real_distribution<double>& uni_dist,
normal_distribution<double>& norm_dist,
size_t n_kernels
) {
sqlite3* db = this->open_delphi_db(SQLITE_OPEN_READONLY);
if (db == nullptr) {
cout << "\n\nERROR: opening delphi.db" << endl;
exit(1);
}
sqlite3_stmt* stmt = nullptr;
const char* query = "select * from gradableAdjectiveData";
int rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
cout << "\n\nERROR: Could not execute query \"" << query << "\" on delphi.db" << endl;
cout << sqlite3_errmsg(db) << endl;
exit(1);
}
AdjectiveResponseMap adjective_response_map;
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
string adjective =
string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2)));
double response = sqlite3_column_double(stmt, 6);
if (!in(adjective_response_map, adjective)) {
adjective_response_map[adjective] = {response};
}
else {
adjective_response_map[adjective].push_back(response);
}
}
for (auto& [k, v] : adjective_response_map) {
v = KDE(v).resample(n_kernels, gen, uni_dist, norm_dist);
}
sqlite3_finalize(stmt);
sqlite3_close(db);
stmt = nullptr;
db = nullptr;
return adjective_response_map;
}
| 26.722772 | 105 | 0.647647 | ml4ai |
4d39fe83633baa3d63db21cd6ab8fff3b5811f85 | 3,792 | cc | C++ | cloud_print/gcp20/prototype/printer.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cloud_print/gcp20/prototype/printer.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cloud_print/gcp20/prototype/printer.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 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 "cloud_print/gcp20/prototype/printer.h"
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "cloud_print/gcp20/prototype/service_parameters.h"
#include "net/base/net_util.h"
namespace {
const char* kServiceType = "_privet._tcp.local";
const char* kServiceNamePrefix = "first_gcp20_device";
const char* kServiceDomainName = "my-privet-device.local";
const uint16 kDefaultTTL = 60*60;
const uint16 kDefaultHttpPort = 10101;
uint16 ReadHttpPortFromCommandLine() {
uint32 http_port_tmp = kDefaultHttpPort;
std::string http_port_string_tmp =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII("http-port");
base::StringToUint(http_port_string_tmp, &http_port_tmp);
if (http_port_tmp > kuint16max) {
LOG(ERROR) << "Port " << http_port_tmp << " is too large (maximum is " <<
kDefaultHttpPort << "). Using default port.";
http_port_tmp = kDefaultHttpPort;
}
VLOG(1) << "HTTP port for responses: " << http_port_tmp;
return static_cast<uint16>(http_port_tmp);
}
uint16 ReadTtlFromCommandLine() {
uint32 ttl = kDefaultTTL;
base::StringToUint(
CommandLine::ForCurrentProcess()->GetSwitchValueASCII("ttl"), &ttl);
VLOG(1) << "TTL for announcements: " << ttl;
return ttl;
}
// Returns local IP address number of first interface found (except loopback).
// Return value is empty if no interface found. Possible interfaces names are
// "eth0", "wlan0" etc. If interface name is empty, function will return IP
// address of first interface found.
net::IPAddressNumber GetLocalIp(const std::string& interface_name,
bool return_ipv6_number) {
net::NetworkInterfaceList interfaces;
bool success = net::GetNetworkList(&interfaces);
DCHECK(success);
size_t expected_address_size = return_ipv6_number ? net::kIPv6AddressSize
: net::kIPv4AddressSize;
for (net::NetworkInterfaceList::iterator iter = interfaces.begin();
iter != interfaces.end(); ++iter) {
if (iter->address.size() == expected_address_size &&
(interface_name.empty() || interface_name == iter->name)) {
LOG(INFO) << net::IPAddressToString(iter->address);
return iter->address;
}
}
return net::IPAddressNumber();
}
} // namespace
Printer::Printer() : initialized_(false) {
}
Printer::~Printer() {
Stop();
}
bool Printer::Start() {
if (initialized_)
return true;
// TODO(maksymb): Add switch for command line to control interface name.
net::IPAddressNumber ip = GetLocalIp("", false);
if (ip.empty()) {
LOG(ERROR) << "No local IP found. Cannot start printer.";
return false;
}
VLOG(1) << "Local address: " << net::IPAddressToString(ip);
// Starting DNS-SD server.
initialized_ = dns_server_.Start(
ServiceParameters(kServiceType,
kServiceNamePrefix,
kServiceDomainName,
ip,
ReadHttpPortFromCommandLine()),
ReadTtlFromCommandLine(),
CreateTxt());
return initialized_;
}
void Printer::Stop() {
if (!initialized_)
return;
dns_server_.Shutdown();
}
std::vector<std::string> Printer::CreateTxt() const {
std::vector<std::string> txt;
txt.push_back("txtvers=1");
txt.push_back("ty=Google Cloud Ready Printer GCP2.0 Prototype");
txt.push_back("note=Virtual printer");
txt.push_back("url=https://www.google.com/cloudprint");
txt.push_back("type=printer");
txt.push_back("id=");
txt.push_back("cs=offline");
return txt;
}
| 28.727273 | 78 | 0.678006 | pozdnyakov |