hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8184158890cf2d536689d788186c10fa5f48e1c | 951 | cpp | C++ | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | #include "prpch.h"
#include "parrot/core/Input.h"
#include "parrot/core/Application.h"
#include <GLFW/glfw3.h>
namespace parrot {
bool Input::isKeyPressed(KeyCode key_code) {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
auto state = glfwGetKey(window, (int)key_code);
return state == GLFW_PRESS || state == GLFW_REPEAT;
}
bool Input::isMouseButtonPressed(MouseButton button) {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
auto state = glfwGetMouseButton(window, (int)button);
return state == GLFW_PRESS;
}
std::pair<float, float> Input::getMousePosition() {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
return { (float)xpos, (float)ypos };
}
} | 31.7 | 97 | 0.660358 | MiloHX |
a81c28f908580e4b72c1a296b135dffb13f02f75 | 266 | cc | C++ | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | 13 | 2020-01-10T00:25:27.000Z | 2020-09-14T20:26:23.000Z | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | null | null | null | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | 19 | 2021-04-07T02:39:30.000Z | 2021-12-12T00:40:22.000Z | #include <math.h>
#include <float.h> /* defines DBL_EPSILON */
#include <assert.h>
#include "gtest/gtest.h"
namespace {
TEST(Examples, Allocation) {
int * x = new int;
double * p = new double[10];
delete x;
delete[] p;
}
}
| 16.625 | 44 | 0.556391 | yxc07 |
a81e53f2970260f975b22689b898ea41f80ff1a0 | 684 | cpp | C++ | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | #include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "CInfoIntermission.h"
LINK_ENTITY_TO_CLASS( info_intermission, CInfoIntermission );
void CInfoIntermission::Spawn( void )
{
SetAbsOrigin( GetAbsOrigin() );
SetSolidType( SOLID_NOT );
GetEffects() = EF_NODRAW;
SetViewAngle( g_vecZero );
SetNextThink( 2 );// let targets spawn!
}
void CInfoIntermission::Think( void )
{
// find my target
CBaseEntity* pTarget = UTIL_FindEntityByTargetname( nullptr, GetTarget() );
if( pTarget )
{
Vector vecViewAngle = UTIL_VecToAngles( ( pTarget->GetAbsOrigin() - GetAbsOrigin() ).Normalize() );
vecViewAngle.x = -vecViewAngle.x;
SetViewAngle( vecViewAngle );
}
} | 22.064516 | 101 | 0.726608 | sohl-modders |
a81fbc3068040a3d53bacb11d79f84ff5eff593e | 7,253 | cpp | C++ | CaWE/MapEditor/Commands/Delete.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/MapEditor/Commands/Delete.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/MapEditor/Commands/Delete.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "Delete.hpp"
#include "Select.hpp"
#include "../CompMapEntity.hpp"
#include "../MapDocument.hpp"
#include "../MapEntRepres.hpp"
#include "../MapPrimitive.hpp"
using namespace MapEditor;
CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, MapElementT* DeleteElem)
: m_MapDoc(MapDoc),
m_Entities(),
m_EntityParents(),
m_EntityIndices(),
m_DeletePrims(),
m_DeletePrimsParents(),
m_CommandSelect(NULL)
{
ArrayT<MapElementT*> DeleteElems;
DeleteElems.PushBack(DeleteElem);
Init(DeleteElems);
}
CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, const ArrayT<MapElementT*>& DeleteElems)
: m_MapDoc(MapDoc),
m_Entities(),
m_EntityParents(),
m_EntityIndices(),
m_DeletePrims(),
m_DeletePrimsParents(),
m_CommandSelect(NULL)
{
Init(DeleteElems);
}
void CommandDeleteT::Init(const ArrayT<MapElementT*>& DeleteElems)
{
// Split the list of elements into a list of primitives and a list of entities.
// The lists are checked for duplicates (and kept free of them).
for (unsigned long ElemNr = 0; ElemNr < DeleteElems.Size(); ElemNr++)
{
MapElementT* Elem = DeleteElems[ElemNr];
if (Elem->GetType() == &MapEntRepresT::TypeInfo)
{
// Double-check that this is really a MapEntRepresT.
wxASSERT(Elem->GetParent()->GetRepres() == Elem);
IntrusivePtrT<cf::GameSys::EntityT> Entity = Elem->GetParent()->GetEntity();
// The root entity (the world) cannot be deleted.
// (The if-tests below are three versions of the logically same check.)
if (Elem->GetParent()->IsWorld()) continue;
if (Entity == Entity->GetRoot()) continue;
if (Entity->GetParent() == NULL) continue;
m_Entities.PushBack(Entity);
m_EntityParents.PushBack(Entity->GetParent());
m_EntityIndices.PushBack(-1);
}
else
{
// Double-check that this is really *not* a MapEntRepresT.
wxASSERT(Elem->GetParent()->GetRepres() != Elem);
MapPrimitiveT* Prim = dynamic_cast<MapPrimitiveT*>(Elem);
wxASSERT(Prim);
if (m_DeletePrims.Find(Prim) == -1)
{
m_DeletePrims.PushBack(Prim);
m_DeletePrimsParents.PushBack(Prim->GetParent());
}
}
}
// Remove entities from m_Entities that are already in the tree of another entity.
// This also removes any duplicates from m_Entities.
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++)
{
if (EntNr != TreeNr && m_Entities[TreeNr]->Has(m_Entities[EntNr]))
{
m_Entities.RemoveAt(EntNr);
m_EntityParents.RemoveAt(EntNr);
m_EntityIndices.RemoveAt(EntNr);
EntNr--;
break;
}
}
}
// Remove primitives from m_DeletePrims whose entire entity is deleted anyways.
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
{
for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++)
{
if (m_Entities[TreeNr]->Has(m_DeletePrims[PrimNr]->GetParent()->GetEntity()))
{
m_DeletePrims.RemoveAt(PrimNr);
m_DeletePrimsParents.RemoveAt(PrimNr);
PrimNr--;
break;
}
}
}
// Build the combined list of all deleted elements in order to unselect them.
ArrayT<MapElementT*> Unselect;
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
Unselect.PushBack(m_DeletePrims[PrimNr]);
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
IntrusivePtrT<CompMapEntityT> MapEnt = GetMapEnt(m_Entities[EntNr]);
Unselect.PushBack(MapEnt->GetAllMapElements());
}
m_CommandSelect = CommandSelectT::Remove(&m_MapDoc, Unselect);
}
CommandDeleteT::~CommandDeleteT()
{
delete m_CommandSelect;
if (m_Done)
{
// for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
// delete m_Entities[EntNr];
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
delete m_DeletePrims[PrimNr];
}
}
bool CommandDeleteT::Do()
{
wxASSERT(!m_Done);
if (m_Done) return false;
if (m_Entities.Size() == 0 && m_DeletePrims.Size() == 0)
{
// If there is nothing to delete, e.g. because only the world representation
// was selected (and dropped in Init()), bail out early.
return false;
}
// Deselect any affected elements that are selected.
m_CommandSelect->Do();
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
{
m_MapDoc.Remove(m_DeletePrims[PrimNr]);
}
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
IntrusivePtrT<cf::GameSys::EntityT> Entity = m_Entities[EntNr];
wxASSERT(m_EntityParents[EntNr]->GetChildren().Find(Entity) >= 0);
// The proper index number can only be determined here, because removing a child
// may change the index numbers of its siblings.
m_EntityIndices[EntNr] = m_EntityParents[EntNr]->GetChildren().Find(Entity);
m_MapDoc.Remove(Entity);
}
// Update all observers.
m_MapDoc.UpdateAllObservers_Deleted(m_DeletePrims);
m_MapDoc.UpdateAllObservers_Deleted(m_Entities);
m_Done = true;
return true;
}
void CommandDeleteT::Undo()
{
wxASSERT(m_Done);
if (!m_Done) return;
for (unsigned long RevNr = 0; RevNr < m_Entities.Size(); RevNr++)
{
const unsigned long EntNr = m_Entities.Size() - RevNr - 1;
// This call to AddChild() should never see a reason to modify the name of the m_Entities[EntNr]
// to make it unique among its siblings -- it used to be there and was unique, after all.
m_MapDoc.Insert(m_Entities[EntNr], m_EntityParents[EntNr], m_EntityIndices[EntNr]);
}
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
m_MapDoc.Insert(m_DeletePrims[PrimNr], m_DeletePrimsParents[PrimNr]);
// Update all observers.
m_MapDoc.UpdateAllObservers_Created(m_Entities);
m_MapDoc.UpdateAllObservers_Created(m_DeletePrims);
// Select the previously selected elements again.
m_CommandSelect->Undo();
m_Done = false;
}
wxString CommandDeleteT::GetName() const
{
const unsigned long Sum = m_Entities.Size() + m_DeletePrims.Size();
if (m_Entities.Size() == 0)
{
return (Sum == 1) ? "Delete 1 primitive" : wxString::Format("Delete %lu primitives", Sum);
}
if (m_DeletePrims.Size() == 0)
{
return (Sum == 1) ? "Delete 1 entity" : wxString::Format("Delete %lu entities", Sum);
}
return (Sum == 1) ? "Delete 1 element" : wxString::Format("Delete %lu elements", Sum);
}
| 30.220833 | 104 | 0.624293 | dns |
a821f5ce6f823d289435a671b6a4dd3dafcac6bc | 1,674 | cpp | C++ | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 731 | 2020-05-07T06:22:59.000Z | 2022-03-31T16:36:03.000Z | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 67 | 2020-07-20T19:46:42.000Z | 2022-03-31T15:34:47.000Z | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 15 | 2021-01-29T04:49:11.000Z | 2022-03-04T22:16:31.000Z | #include "opt/dedicate_to_window.hpp"
#if defined(DEBUG)
#include <iostream>
#endif
#include <windows.h>
#include "bind/emu/edi_change_mode.hpp"
#include "bind/mode/change_mode.hpp"
#include "err_logger.hpp"
#include "g_params.hpp"
#include "io/mouse.hpp"
#include "key/key_absorber.hpp"
#include "key/keycode_def.hpp"
#include "opt/vcmdline.hpp"
namespace
{
HWND target_hwnd = NULL ;
HWND past_hwnd = NULL ;
}
namespace vind
{
Dedicate2Window::Dedicate2Window()
: OptionCreator("dedicate_to_window")
{}
void Dedicate2Window::do_enable() const {
}
void Dedicate2Window::do_disable() const {
}
void Dedicate2Window::enable_targeting() {
if(gparams::get_b("dedicate_to_window")) {
target_hwnd = GetForegroundWindow() ;
past_hwnd = NULL ;
VCmdLine::print(GeneralMessage("-- TARGET ON --")) ;
}
}
void Dedicate2Window::disable_targeting() {
if(gparams::get_b("dedicate_to_window")) {
target_hwnd = NULL ;
past_hwnd = NULL ;
VCmdLine::print(GeneralMessage("-- TARGET OFF --")) ;
}
}
void Dedicate2Window::do_process() const {
if(!target_hwnd) return ;
auto foreground_hwnd = GetForegroundWindow() ;
//is selected window changed?
if(past_hwnd == foreground_hwnd) {
return ;
}
if(target_hwnd == foreground_hwnd) { //other -> target
ToEdiNormal::sprocess(true) ;
}
else if(past_hwnd == target_hwnd) { //target -> other
ToInsert::sprocess(true) ;
}
past_hwnd = foreground_hwnd ;
}
}
| 23.577465 | 65 | 0.608124 | pit-ray |
a82396571fb885084e14cbe0c347a9d3c040b36c | 1,702 | cpp | C++ | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | /**
* @file
* @brief Generate fibonacci sequence
*
* Calculate the the value on Fibonacci's sequence given an
* integer as input.
* \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f]
*
* @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp
*/
#include <cassert>
#include <iostream>
/**
* Recursively compute sequences
* @param n input
* @returns n-th element of the Fbinacci's sequence
*/
uint64_t fibonacci(uint64_t n)
{
/* If the input is 0 or 1 just return the same
This will set the first 2 values of the sequence */
if (n <= 1)
{
return n;
}
/* Add the last 2 values of the sequence to get next */
return fibonacci(n - 1) + fibonacci(n - 2);
}
/**
* Function for testing the fibonacci() function with a few
* test cases and assert statement.
* @returns `void`
*/
static void test()
{
uint64_t test_case_1 = fibonacci(0);
assert(test_case_1 == 0);
std::cout << "Passed Test 1!" << std::endl;
uint64_t test_case_2 = fibonacci(1);
assert(test_case_2 == 1);
std::cout << "Passed Test 2!" << std::endl;
uint64_t test_case_3 = fibonacci(2);
assert(test_case_3 == 1);
std::cout << "Passed Test 3!" << std::endl;
uint64_t test_case_4 = fibonacci(3);
assert(test_case_4 == 2);
std::cout << "Passed Test 4!" << std::endl;
uint64_t test_case_5 = fibonacci(4);
assert(test_case_5 == 3);
std::cout << "Passed Test 5!" << std::endl;
uint64_t test_case_6 = fibonacci(15);
assert(test_case_6 == 610);
std::cout << "Passed Test 6!" << std::endl << std::endl;
}
/// Main function
int main()
{
test();
int n = 0;
std::cin >> n;
assert(n >= 0);
std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl;
}
| 25.029412 | 69 | 0.62926 | dvijaymanohar |
a82466ae6673a5f0ef3d223463a800485c27c369 | 31,786 | cpp | C++ | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************/
/**
* @file TinyXML.cpp
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id: TinyXML.cpp 631 2010-10-10 02:15:35Z naohisa.sakamoto $
*/
/****************************************************************************/
/*
Copyright (c) 2000 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "TinyXML.h"
#include <cctype>
#include <kvs/DebugNew>
namespace { template <typename T> void Ignore( T ){} }
const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] =
{
"No error.",
"Failed to open file.",
"Memory allocation failed.",
"Error parsing Element.",
"Failed to read Element name",
"Error reading Element value.",
"Error reading Attributes.",
"Error: empty tag.",
"Error reading end tag.",
"Error parsing Unknown.",
"Error parsing Comment.",
"Error parsing Declaration.",
};
const char* TiXmlBase::SkipWhiteSpace( const char* p )
{
while ( p && *p &&
( isspace( *p ) || *p == '\n' || *p == '\r' ) )
p++;
return p;
}
const char* TiXmlBase::ReadName( const char* p, std::string* name )
{
*name = "";
const char* start = p;
// Names start with letters or underscores.
// After that, they can be letters, underscores, numbers,
// hyphens, or colons. (Colons are valid ony for namespaces,
// but tinyxml can't tell namespaces from names.)
if ( p && ( isalpha( *p ) || *p == '_' ) )
{
p++;
while( p && *p &&
( isalnum( *p )
|| *p == '_'
|| *p == '-'
|| *p == ':' ) )
{
p++;
}
name->append( start, p - start );
return p;
}
return 0;
}
const char* TiXmlBase::ReadText(
const char* p,
std::string* text,
bool trimWhiteSpace,
const char* endTag,
bool caseInsensitive )
{
::Ignore( caseInsensitive );
*text = "";
if ( !trimWhiteSpace // certain tags always keep whitespace
/*|| !condenseWhiteSpace*/ ) // if true, whitespace is always kept
{
// Keep all the white space.
while ( p && *p
&& strncmp( p, endTag, strlen(endTag) ) != 0
)
{
char c = *(p++);
(* text) += c;
}
}
else
{
bool whitespace = false;
// Remove leading white space:
p = SkipWhiteSpace( p );
while ( p && *p
&& strncmp( p, endTag, strlen(endTag) ) != 0 )
{
if ( *p == '\r' || *p == '\n' )
{
whitespace = true;
++p;
}
else if ( isspace( *p ) )
{
whitespace = true;
++p;
}
else
{
// If we've found whitespace, add it before the
// new character. Any whitespace just becomes a space.
if ( whitespace )
{
(* text) += ' ';
whitespace = false;
}
char c = *(p++);
(* text) += c;
}
}
}
return p + strlen( endTag );
}
const char* TiXmlDocument::Parse( const char* start )
{
// Parse away, at the document level. Since a document
// contains nothing but other tags, most of what happens
// here is skipping white space.
const char* p = start;
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
error = true;
errorDesc = "Document empty.";
}
while ( p && *p )
{
if ( *p != '<' )
{
error = true;
errorDesc = "The '<' symbol that starts a tag was not found.";
break;
}
else
{
TiXmlNode* node = IdentifyAndParse( &p );
if ( node )
{
LinkEndChild( node );
}
}
p = SkipWhiteSpace( p );
}
return 0; // Return null is fine for a document: once it is read, the parsing is over.
}
TiXmlNode* TiXmlNode::IdentifyAndParse( const char** where )
{
const char* p = *where;
TiXmlNode* returnNode = 0;
assert( *p == '<' );
TiXmlDocument* doc = GetDocument();
p = SkipWhiteSpace( p+1 );
// What is this thing?
// - Elements start with a letter or underscore, but xml is reserved.
// - Comments: <!--
// - Everthing else is unknown to tinyxml.
//
if ( tolower( *(p+0) ) == '?'
&& tolower( *(p+1) ) == 'x'
&& tolower( *(p+2) ) == 'm'
&& tolower( *(p+3) ) == 'l' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Declaration\n" );
#endif
returnNode = new TiXmlDeclaration();
}
else if ( isalpha( *p ) || *p == '_' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Element\n" );
#endif
returnNode = new TiXmlElement( "" );
}
else if ( *(p+0) == '!'
&& *(p+1) == '-'
&& *(p+2) == '-' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Comment\n" );
#endif
returnNode = new TiXmlComment();
}
else if ( strncmp(p, "![CDATA[", 8) == 0 )
{
TiXmlNode* cdataNode = new TiXmlCData();
if ( !cdataNode )
{
if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY );
return 0;
}
returnNode = cdataNode;
}
else
{
#ifdef DEBUG_PARSER
printf( "XML parsing Comment\n" );
#endif
returnNode = new TiXmlUnknown();
}
if ( returnNode )
{
// Set the parent, so it can report errors
returnNode->parent = this;
p = returnNode->Parse( p );
}
else
{
if ( doc )
doc->SetError( TIXML_ERROR_OUT_OF_MEMORY );
p = 0;
}
*where = p;
return returnNode;
}
const char* TiXmlElement::Parse( const char* p )
{
TiXmlDocument* document = GetDocument();
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT );
return 0;
}
// Read the name.
p = ReadName( p, &value );
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME );
return 0;
}
std::string endTag = "</";
endTag += value;
endTag += ">";
// Check for and read attributes. Also look for an empty
// tag or an end tag.
while ( p && *p )
{
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
if ( *p == '/' )
{
// Empty tag.
if ( *(p+1) != '>' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY );
return 0;
}
return p+2;
}
else if ( *p == '>' )
{
// Done with attributes (if there were any.)
// Read the value -- which can include other
// elements -- read the end tag, and return.
p = ReadValue( p+1 ); // Note this is an Element method, and will set the error if one happens.
if ( !p )
return 0;
// We should find the end tag now
std::string buf( p, endTag.size() );
if ( endTag == buf )
{
return p+endTag.size();
}
else
{
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG );
return 0;
}
}
else
{
// Try to read an element:
TiXmlAttribute attrib;
attrib.SetDocument( document );
p = attrib.Parse( p );
if ( p )
{
SetAttribute( attrib.Name(), attrib.Value() );
}
}
}
return 0;
}
const char* TiXmlElement::ReadValue( const char* p )
{
TiXmlDocument* document = GetDocument();
// Read in text and elements in any order.
p = SkipWhiteSpace( p );
while ( p && *p )
{
const char* start = p;
while ( *p && *p != '<' )
p++;
if ( !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE );
return 0;
}
if ( p != start )
{
// Take what we have, make a text element.
TiXmlText* text = new TiXmlText();
if ( !text )
{
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY );
return 0;
}
text->Parse( start );
if ( !text->Blank() )
LinkEndChild( text );
else
delete text;
}
else
{
// We hit a '<'
// Have we hit a new element or an end tag?
if ( *(p+1) == '/' )
{
return p; // end tag
}
else
{
// TiXmlElement* element = new TiXmlElement( "" );
//
// if ( element )
// {
// p = element->Parse( p+1 );
// if ( p )
// LinkEndChild( element );
// }
// else
// {
// if ( document ) document->SetError( ERROR_OUT_OF_MEMORY );
// return 0;
// }
TiXmlNode* node = IdentifyAndParse( &p );
if ( node )
{
LinkEndChild( node );
}
else
{
return 0;
}
}
}
}
return 0;
}
const char* TiXmlUnknown::Parse( const char* p )
{
const char* end = strchr( p, '>' );
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_UNKNOWN );
return 0;
}
else
{
value = std::string( p, end-p );
// value.resize( end - p );
return end + 1; // return just past the '>'
}
}
const char* TiXmlComment::Parse( const char* p )
{
assert( *p == '!' && *(p+1) == '-' && *(p+2) == '-' );
// Find the end, copy the parts between to the value of
// this object, and return.
const char* start = p+3;
const char* end = strstr( p, "-->" );
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_COMMENT );
return 0;
}
else
{
// Assemble the comment, removing the white space.
bool whiteSpace = false;
const char* q;
for( q=start; q<end; q++ )
{
if ( isspace( *q ) )
{
if ( !whiteSpace )
{
value += ' ';
whiteSpace = true;
}
}
else
{
value += *q;
whiteSpace = false;
}
}
// value = std::string( start, end-start );
return end + 3; // return just past the '>'
}
}
const char* TiXmlAttribute::Parse( const char* p )
{
// Read the name, the '=' and the value.
p = ReadName( p, &name );
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
p = SkipWhiteSpace( p );
if ( !p || *p != '=' )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
p = SkipWhiteSpace( p+1 );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
const char* end = 0;
const char* start = p+1;
const char* past = 0;
if ( *p == '\'' )
{
end = strchr( start, '\'' );
past = end+1;
}
else if ( *p == '"' )
{
end = strchr( start, '"' );
past = end+1;
}
else
{
// All attribute values should be in single or double quotes.
// But this is such a common error that the parser will try
// its best, even without them.
start--;
for ( end = start; *end; end++ )
{
if ( isspace( *end ) || *end == '/' || *end == '>' )
break;
}
past = end;
}
value = std::string( start, end-start );
return past;
}
const char* TiXmlText::Parse( const char* p )
{
value = "";
bool ignoreWhite = true;
const char* end = "<";
p = ReadText( p, &value, ignoreWhite, end, false );
if ( p )
return p-1; // don't truncate the '<'
return 0;
#if 0
// Remove leading white space:
p = SkipWhiteSpace( p );
while ( *p && *p != '<' )
{
if ( *p == '\r' || *p == '\n' )
{
whitespace = true;
}
else if ( isspace( *p ) )
{
whitespace = true;
}
else
{
// If we've found whitespace, add it before the
// new character. Any whitespace just becomes a space.
if ( whitespace )
{
value += ' ';
whitespace = false;
}
value += *p;
}
p++;
}
// Keep white space before the '<'
if ( whitespace )
value += ' ';
return p;
#endif
}
const char* TiXmlCData::Parse( const char* p )
{
value = "";
bool ignoreWhite = false;
p += 8;
const char* end = "]]>";
p = ReadText( p, &value, ignoreWhite, end, false );
if ( p )
return p;
return 0;
}
const char* TiXmlDeclaration::Parse( const char* p )
{
// Find the beginning, find the end, and look for
// the stuff in-between.
const char* start = p+4;
const char* end = strstr( start, "?>" );
// Be nice to the user:
if ( !end )
{
end = strstr( start, ">" );
end++;
}
else
{
end += 2;
}
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_DECLARATION );
return 0;
}
else
{
const char* p;
p = strstr( start, "version" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
version = attrib.Value();
}
p = strstr( start, "encoding" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
encoding = attrib.Value();
}
p = strstr( start, "standalone" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
standalone = attrib.Value();
}
}
return end;
}
bool TiXmlText::Blank()
{
for ( unsigned i=0; i<value.size(); i++ )
if ( !isspace( value[i] ) )
return false;
return true;
}
TiXmlNode::TiXmlNode( NodeType _type )
{
parent = 0;
type = _type;
firstChild = 0;
lastChild = 0;
prev = 0;
next = 0;
}
TiXmlNode::~TiXmlNode()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
}
void TiXmlNode::Clear()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
firstChild = 0;
lastChild = 0;
}
TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )
{
node->parent = this;
node->prev = lastChild;
node->next = 0;
if ( lastChild )
lastChild->next = node;
else
firstChild = node; // it was an empty list.
lastChild = node;
return node;
}
TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis )
{
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
return LinkEndChild( node );
}
TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis )
{
if ( beforeThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->next = beforeThis;
node->prev = beforeThis->prev;
beforeThis->prev->next = node;
beforeThis->prev = node;
return node;
}
TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis )
{
if ( afterThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->prev = afterThis;
node->next = afterThis->next;
afterThis->next->prev = node;
afterThis->next = node;
return node;
}
TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis )
{
if ( replaceThis->parent != this )
return 0;
TiXmlNode* node = withThis.Clone();
if ( !node )
return 0;
node->next = replaceThis->next;
node->prev = replaceThis->prev;
if ( replaceThis->next )
replaceThis->next->prev = node;
else
lastChild = node;
if ( replaceThis->prev )
replaceThis->prev->next = node;
else
firstChild = node;
delete replaceThis;
return node;
}
bool TiXmlNode::RemoveChild( TiXmlNode* removeThis )
{
if ( removeThis->parent != this )
{
assert( 0 );
return false;
}
if ( removeThis->next )
removeThis->next->prev = removeThis->prev;
else
lastChild = removeThis->prev;
if ( removeThis->prev )
removeThis->prev->next = removeThis->next;
else
firstChild = removeThis->next;
delete removeThis;
return true;
}
TiXmlNode* TiXmlNode::FirstChild( const std::string& value ) const
{
TiXmlNode* node;
for ( node = firstChild; node; node = node->next )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::LastChild( const std::string& value ) const
{
TiXmlNode* node;
for ( node = lastChild; node; node = node->prev )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild();
}
else
{
assert( previous->parent == this );
return previous->NextSibling();
}
}
TiXmlNode* TiXmlNode::IterateChildren( const std::string& val, TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild( val );
}
else
{
assert( previous->parent == this );
return previous->NextSibling( val );
}
}
TiXmlNode* TiXmlNode::NextSibling( const std::string& value ) const
{
TiXmlNode* node;
for ( node = next; node; node = node->next )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::PreviousSibling( const std::string& value ) const
{
TiXmlNode* node;
for ( node = prev; node; node = node->prev )
{
if ( node->Value() == value )
return node;
}
return 0;
}
void TiXmlElement::RemoveAttribute( const std::string& name )
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
{
attributeSet.Remove( node );
delete node;
}
}
TiXmlElement* TiXmlNode::FirstChildElement() const
{
TiXmlNode* node;
for ( node = FirstChild();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::FirstChildElement( const std::string& value ) const
{
TiXmlNode* node;
for ( node = FirstChild( value );
node;
node = node->NextSibling( value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement() const
{
TiXmlNode* node;
for ( node = NextSibling();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement( const std::string& value ) const
{
TiXmlNode* node;
for ( node = NextSibling( value );
node;
node = node->NextSibling( value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlDocument* TiXmlNode::GetDocument() const
{
const TiXmlNode* node;
for( node = this; node; node = node->parent )
{
if ( node->ToDocument() )
return node->ToDocument();
}
return 0;
}
// TiXmlElement::TiXmlElement()
// : TiXmlNode( TiXmlNode::ELEMENT )
// {
// }
TiXmlElement::TiXmlElement( const std::string& _value )
: TiXmlNode( TiXmlNode::ELEMENT )
{
firstChild = lastChild = 0;
value = _value;
}
TiXmlElement::~TiXmlElement()
{
while( attributeSet.First() )
{
TiXmlAttribute* node = attributeSet.First();
attributeSet.Remove( node );
delete node;
}
}
const std::string* TiXmlElement::Attribute( const std::string& name ) const
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
return &(node->Value() );
return 0;
}
const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const
{
const std::string* s = Attribute( name );
if ( s )
*i = atoi( s->c_str() );
else
*i = 0;
return s;
}
void TiXmlElement::SetAttribute( const std::string& name, int val )
{
char buf[64];
sprintf( buf, "%d", val );
std::string v = buf;
SetAttribute( name, v );
}
void TiXmlElement::SetAttribute( const std::string& name, const std::string& value )
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
{
node->SetValue( value );
return;
}
TiXmlAttribute* attrib = new TiXmlAttribute( name, value );
if ( attrib )
{
attributeSet.Add( attrib );
}
else
{
TiXmlDocument* document = GetDocument();
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY );
}
}
void TiXmlElement::Print( FILE* fp, int depth )
{
int i;
for ( i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<%s", value.c_str() );
TiXmlAttribute* attrib;
for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
{
fprintf( fp, " " );
attrib->Print( fp, 0 );
}
// If this node has children, give it a closing tag. Else
// make it an empty tag.
TiXmlNode* node;
if ( firstChild )
{
fprintf( fp, ">" );
for ( node = firstChild; node; node=node->NextSibling() )
{
if ( !node->ToText() )
fprintf( fp, "\n" );
node->Print( fp, depth+1 );
}
fprintf( fp, "\n" );
for ( i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "</%s>", value.c_str() );
}
else
{
fprintf( fp, " />" );
}
}
TiXmlNode* TiXmlElement::Clone() const
{
TiXmlElement* clone = new TiXmlElement( Value() );
if ( !clone )
return 0;
CopyToClone( clone );
// Clone the attributes, then clone the children.
TiXmlAttribute* attribute = 0;
for( attribute = attributeSet.First();
attribute;
attribute = attribute->Next() )
{
clone->SetAttribute( attribute->Name(), attribute->Value() );
}
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
clone->LinkEndChild( node->Clone() );
}
return clone;
}
TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT )
{
error = false;
// factory = new TiXmlFactory();
}
TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT )
{
// factory = new TiXmlFactory();
value = documentName;
error = false;
}
// void TiXmlDocument::SetFactory( TiXmlFactory* f )
// {
// delete factory;
// factory = f;
// }
bool TiXmlDocument::LoadFile()
{
return LoadFile( value );
}
bool TiXmlDocument::SaveFile()
{
return SaveFile( value );
}
bool TiXmlDocument::LoadFile( FILE* fp )
{
// Delete the existing data:
Clear();
unsigned size, first;
first = ftell( fp );
fseek( fp, 0, SEEK_END );
size = ftell( fp ) - first + 1;
fseek( fp, first, SEEK_SET );
char* buf = new char[size];
char* p = buf;
while( fgets( p, size, fp ) )
{
p = strchr( p, 0 );
}
fclose( fp );
Parse( buf );
delete [] buf;
if ( !Error() )
return true;
return false;
}
bool TiXmlDocument::LoadFile( const std::string& filename )
{
// Delete the existing data:
Clear();
// Load the new data:
FILE* fp = fopen( filename.c_str(), "r" );
if ( fp )
{
return LoadFile(fp);
}
else
{
SetError( TIXML_ERROR_OPENING_FILE );
}
return false;
}
bool TiXmlDocument::SaveFile( const std::string& filename )
{
FILE* fp = fopen( filename.c_str(), "w" );
if ( fp )
{
Print( fp, 0 );
fclose( fp );
return true;
}
return false;
}
TiXmlNode* TiXmlDocument::Clone() const
{
TiXmlDocument* clone = new TiXmlDocument();
if ( !clone )
return 0;
CopyToClone( clone );
clone->error = error;
clone->errorDesc = errorDesc;
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
clone->LinkEndChild( node->Clone() );
}
return clone;
}
void TiXmlDocument::Print( FILE* fp, int )
{
TiXmlNode* node;
for ( node=FirstChild(); node; node=node->NextSibling() )
{
node->Print( fp, 0 );
fprintf( fp, "\n" );
}
}
TiXmlAttribute* TiXmlAttribute::Next()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( next->value.empty() && next->name.empty() )
return 0;
return next;
}
TiXmlAttribute* TiXmlAttribute::Previous()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( prev->value.empty() && prev->name.empty() )
return 0;
return prev;
}
void TiXmlAttribute::Print( FILE* fp, int )
{
if ( value.find( '\"' ) != std::string::npos )
fprintf( fp, "%s='%s'", name.c_str(), value.c_str() );
else
fprintf( fp, "%s=\"%s\"", name.c_str(), value.c_str() );
}
void TiXmlComment::Print( FILE* fp, int depth )
{
for ( int i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<!--%s-->", value.c_str() );
}
TiXmlNode* TiXmlComment::Clone() const
{
TiXmlComment* clone = new TiXmlComment();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
void TiXmlText::Print( FILE* fp, int )
{
fprintf( fp, "%s", value.c_str() );
}
TiXmlNode* TiXmlText::Clone() const
{
TiXmlText* clone = 0;
clone = new TiXmlText();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
TiXmlDeclaration::TiXmlDeclaration( const std::string& _version,
const std::string& _encoding,
const std::string& _standalone )
: TiXmlNode( TiXmlNode::DECLARATION )
{
version = _version;
encoding = _encoding;
standalone = _standalone;
}
void TiXmlDeclaration::Print( FILE* fp, int )
{
std::string out = "<?xml ";
if ( !version.empty() )
{
out += "version=\"";
out += version;
out += "\" ";
}
if ( !encoding.empty() )
{
out += "encoding=\"";
out += encoding;
out += "\" ";
}
if ( !standalone.empty() )
{
out += "standalone=\"";
out += standalone;
out += "\" ";
}
out += "?>";
fprintf( fp, "%s", out.c_str() );
}
TiXmlNode* TiXmlDeclaration::Clone() const
{
TiXmlDeclaration* clone = new TiXmlDeclaration();
if ( !clone )
return 0;
CopyToClone( clone );
clone->version = version;
clone->encoding = encoding;
clone->standalone = standalone;
return clone;
}
void TiXmlUnknown::Print( FILE* fp, int depth )
{
for ( int i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<%s>", value.c_str() );
}
TiXmlNode* TiXmlUnknown::Clone() const
{
TiXmlUnknown* clone = new TiXmlUnknown();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
TiXmlAttributeSet::TiXmlAttributeSet()
{
sentinel.next = &sentinel;
sentinel.prev = &sentinel;
}
TiXmlAttributeSet::~TiXmlAttributeSet()
{
assert( sentinel.next == &sentinel );
assert( sentinel.prev == &sentinel );
}
void TiXmlAttributeSet::Add( TiXmlAttribute* addMe )
{
assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set.
addMe->next = &sentinel;
addMe->prev = sentinel.prev;
sentinel.prev->next = addMe;
sentinel.prev = addMe;
}
void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe )
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node == removeMe )
{
node->prev->next = node->next;
node->next->prev = node->prev;
node->next = 0;
node->prev = 0;
return;
}
}
assert( 0 ); // we tried to remove a non-linked attribute.
}
TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node->Name() == name )
return node;
}
return 0;
}
| 22.119694 | 107 | 0.499528 | CCSEPBVR |
a824d6666c16ea26d15ceacbfbee3ebc419a324d | 367 | cpp | C++ | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | #include "exercise_10.h"
void f()
{
string s = "a series of whitespace seperated words";
vector<string> substrings = split(s);
for (auto substring : substrings)
{
cout << substring << endl;
}
}
int main()
{
try
{
f();
}
catch (...)
{
cout << "MAJOR ERROR\n";
return -1;
}
return 0;
} | 14.115385 | 56 | 0.490463 | JohnWoods11 |
a82a53cca49e1fc369df95cd846299eed232c6d7 | 1,855 | cpp | C++ | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 The WizTK Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wiztk/base/string.hpp"
#include <unicode/utf.h>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <unicode/stringpiece.h>
namespace wiztk {
namespace base {
String::String(const char *str) {
// TODO: temporary workaround, optimize this by ICU later:
icu::UnicodeString unicode = icu::UnicodeString::fromUTF8(icu::StringPiece(str));
assign(unicode.getBuffer());
}
String::String(const char16_t *str) {
assign(reinterpret_cast<const UChar *>(str));
}
String::String(const char32_t *str) {
// TODO: temporary workaround, optimize this by ICU later.
icu::UnicodeString unicode =
icu::UnicodeString::fromUTF32(reinterpret_cast<const UChar32 *>(str),
static_cast<uint32_t>(std::char_traits<char32_t>::length(str)));
assign(unicode.getBuffer());
}
std::ostream &operator<<(std::ostream &out, const String &str) {
// TODO: This create and copy the string array from String16 to icu::UnicodeString, find a better way for performance.
return out << icu::UnicodeString(str.data());
}
std::string String::ToUTF8() const {
std::string utf8;
icu::UnicodeString unicode = data();
unicode.toUTF8String(utf8);
return utf8;
}
} // namespace base
} // namespace wiztk
| 30.409836 | 120 | 0.712129 | wiztk |
a82df48d367f2b32a7cc49feef4c00bce3105606 | 15,546 | cpp | C++ | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | 2 | 2021-12-28T15:49:43.000Z | 2022-03-27T08:05:12.000Z | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | null | null | null | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | null | null | null | #include "channel.h"
#include "library.h"
#include "fileinfo.h"
#include "connection.h"
#include "filetransfer.h"
#include "private/cachemanager_p.h"
#include "private/interfacemanager_p.h"
namespace TeamSpeakSdk {
class Channel::Private
{
public:
int getInt(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsInt(channel, flag);
}
uint64 getUInt64(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsUInt64(channel, flag);
}
QString getString(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsString(channel, flag);
}
void setInt(Channel* channel, ChannelProperty flag, int value)
{
api().setChannelVariableAsInt(channel, flag, value);
flushChannelUpdates(channel);
}
void setUInt64(Channel* channel, ChannelProperty flag, uint64 value)
{
api().setChannelVariableAsUInt64(channel, flag, value);
flushChannelUpdates(channel);
}
void setString(Channel* channel, ChannelProperty flag, const QString& value)
{
api().setChannelVariableAsString(channel, flag, value);
flushChannelUpdates(channel);
}
void flushChannelUpdates(Channel* channel)
{
if (channel->id() == 0)
return;
}
ID id = 0;
Connection* connection = nullptr;
struct Cache
{
QString name;
QString topic;
} cached;
};
/*!
* \class Channel
*
* \brief
*/
Channel::Channel(Connection* connection)
: d(new Private)
{
d->connection = connection;
}
Channel::Channel(Connection* connection, ID id, bool waitForProperties)
: Channel(connection)
{
setId(id);
refreshProperties(waitForProperties);
}
Channel::~Channel()
{
delete d;
}
Channel::Channel(const Channel& other) Q_DECL_NOTHROW
: d(new Private)
{
*d = *other.d;
}
Channel::Channel(Channel&& other) Q_DECL_NOTHROW
{
*d = *other.d;
}
void Channel::swap(Channel&& other)
{
qSwap(d, other.d);
}
Channel& Channel::operator=(const Channel& other) Q_DECL_NOTHROW
{
swap(std::move(Channel(other)));
return *this;
}
Channel& Channel::operator=(Channel&& other) Q_DECL_NOTHROW
{
swap(std::move(Channel(std::move(other))));
return *this;
}
bool Channel::operator==(const Channel& o) const Q_DECL_NOTHROW
{
if ((this) == &o)
return true;
return connection() == o.connection() && id() == o.id();
}
/*!
* ID of the channel
*/
Channel::ID Channel::id() const
{
return d->id;
}
void Channel::setId(ID id)
{
d->id = id;
}
/*!
* Server Connection
*/
Connection* Channel::connection() const
{
return d->connection;
}
void Channel::setConnection(Connection* server)
{
d->connection = server;
}
/*!
* The parent channel
*/
Channel* Channel::parent() const
{
return api().getParentChannelOfChannel(this);
}
/*!
* List of all clients in the channel, if the channel is currently subscribed.
*/
QList<Client*> Channel::clients() const
{
return api().getChannelClientList(this);
}
QList<Channel*> Channel::channels() const
{
return QList<Channel*>();
}
/*!
* Name of the channel
*/
QString Channel::name() const
{
return d->cached.name;
}
void Channel::setName(const QString& value)
{
d->setString(this, ChannelProperty::Name, value);
}
/*!
* Single-line channel topic
*/
QString Channel::topic() const
{
return d->cached.topic;
}
void Channel::setTopic(const QString& value)
{
d->setString(this, ChannelProperty::Topic, value);
}
/*!
* Optional channel description. Can have multiple lines.
* Needs to be request with \sa getChannelDescription().
*/
QString Channel::description() const
{
return d->getString(this, ChannelProperty::Description);
}
void Channel::setDescription(const QString& value)
{
d->setString(this, ChannelProperty::Description, value);
}
/*!
* Optional password for password-protected channels.
*/
void Channel::setPassword(const QString& value)
{
d->setString(this, ChannelProperty::Password, value);
}
/*!
* Codec used for this channel
*/
CodecType Channel::codec() const
{
return CodecType(d->getInt(this, ChannelProperty::Codec));
}
void Channel::setCodec(CodecType value)
{
d->setInt(this, ChannelProperty::Codec, utils::underlay(value));
}
/*!
* Quality of channel codec of this channel.
* Valid values range from 0 to 10, default is 7.
* Higher values result in better speech quality but more bandwidth usage
*/
int Channel::codecQuality() const
{
return d->getInt(this, ChannelProperty::CodecQuality);
}
void Channel::setCodecQuality(int value)
{
d->setInt(this, ChannelProperty::CodecQuality, value);
}
/*!
* Number of maximum clients who can join this channel
*/
int Channel::maxClients() const
{
return d->getInt(this, ChannelProperty::Maxclients);
}
void Channel::setMaxClients(int value)
{
d->setInt(this, ChannelProperty::Maxclients, value);
}
/*!
* Number of maximum clients who can join this channel and all subchannels
*/
int Channel::maxFamilyClients() const
{
return d->getInt(this, ChannelProperty::Maxfamilyclients);
}
void Channel::setMaxFamilyClients(int value)
{
d->setInt(this, ChannelProperty::Maxfamilyclients, value);
}
/*!
* \sa order() is the \sa channel() after which this channel is sorted.
* <see lang word="null" meaning its going to be the first \sa channel() under \sa parent()
*/
Channel* Channel::order() const
{
const auto orderId = d->getUInt64(this, ChannelProperty::Order);
return connection()->getChannel(orderId);
}
void Channel::setOrder(const Channel* value)
{
d->setUInt64(this, ChannelProperty::Order, value ? value->id() : 0);
}
/*!
* Permanent channels will be restored when the server restarts.
*/
bool Channel::isPermanent() const
{
return d->getInt(this, ChannelProperty::FlagPermanent) != 0;
}
void Channel::setPermanent(bool value)
{
d->setInt(this, ChannelProperty::FlagPermanent, value ? 1 : 0);
}
/*!
* Semi-permanent channels are not automatically deleted when the last user left
* but will not be restored when the server restarts.
*/
bool Channel::isSemiPermanent() const
{
return d->getInt(this, ChannelProperty::FlagSemiPermanent) != 0;
}
void Channel::setSemiPermanent(bool value)
{
d->setInt(this, ChannelProperty::FlagSemiPermanent, value ? 1 : 0);
}
/*!
* Channel is the default channel.
* There can only be one default channel per server.
* New users who did not configure a channel to join on login in ts3client_startConnection will automatically join the default channel.
*/
bool Channel::isDefault() const
{
return d->getInt(this, ChannelProperty::FlagDefault) != 0;
}
void Channel::setDefault(bool value)
{
d->setInt(this, ChannelProperty::FlagDefault, value ? 1 : 0);
}
/*!
* If set, channel is password protected.
* The password itself is stored in ChannelPassword
*/
bool Channel::isPasswordProtected() const
{
return d->getInt(this, ChannelProperty::FlagPassword) != 0;
}
/*!
* Latency of this channel.
* Allows to increase the packet size resulting in less bandwidth usage at the cost of higher latency.
* A value of 1 (default) is the best setting for lowest latency and best quality.
* If bandwidth or network quality are restricted, increasing the latency factor can help stabilize the connection.
* Higher latency values are only possible for low-quality codec and codec quality settings.
*/
int Channel::codecLatencyFactor() const
{
return d->getInt(this, ChannelProperty::CodecLatencyFactor);
}
void Channel::setCodecLatencyFactor(int value)
{
d->setInt(this, ChannelProperty::CodecLatencyFactor, value);
}
/*!
* If true, this channel is not using encrypted voice data.
* If false, voice data is encrypted for this channel.
* Note that channel voice data encryption can be globally disabled or enabled for the virtual server.
* Changing this flag makes only sense if global voice data encryption is set to be configured per channel.
*/
bool Channel::codecIsUnencrypted() const
{
return d->getInt(this, ChannelProperty::CodecIsUnencrypted) != 0;
}
void Channel::setCodecIsUnencrypted(bool value)
{
d->setInt(this, ChannelProperty::CodecIsUnencrypted, value ? 1 : 0);
}
time::seconds Channel::deleteDelay() const
{
const auto time = d->getInt(this, ChannelProperty::DeleteDelay);
return time::seconds(time);
}
void Channel::setDeleteDelay(const time::seconds& value)
{
d->setInt(this, ChannelProperty::DeleteDelay, int(value.count()));
}
time::seconds Channel::channelEmptyTime() const
{
const auto time = api().getChannelEmptySecs(this);
return time::seconds(time);
}
/*!
* Uploads a local file to the server
* \a "file" Path of the local file, which is to be uploaded.
* \a "overwrite" when false, upload will abort if remote file exists
* \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous upload operation.
*/
void Channel::sendFile(const FileTransferOption& option)
{
api().sendFile(
this,
option.password,
option.file.fileName(),
option.overwrite,
option.resume,
option.file.dir().path(),
TODO_RETURN_CODE
);
}
/*!
* Download a file from the server.
* \a "fileName" Filename of the remote file, which is to be downloaded.
* \a "destinationDirectory" Local target directory name where the download file should be saved.
* \a "overwrite" when false, download will abort if local file exists
* \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* \a "cancellationToken" The token to monitor for cancellation requests. The default value is \sa "CancellationToken.None"
* Returns \c A task that represents the asynchronous download operation.
*/
void Channel::requestFile(const FileTransferOption& option)
{
api().requestFile(
this,
option.password,
option.file.fileName(),
option.overwrite,
option.resume,
option.file.dir().path(),
TODO_RETURN_CODE
);
}
/*!
* Query list of files in a directory.
* \a "path" Path inside the channel, defining the subdirectory. Top level path is ??
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that returns the list of files contained in path
*/
void Channel::getFileList(const QString& path, const QString& channelPassword)
{
api().requestFileList(this, channelPassword, path, TODO_RETURN_CODE);
}
/*!
* Query information of a specified file. The answer from the server will trigger \sa "Connection.FileInfoReceived" with the requested information.
* \a "file" File name we want to request info from, needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::getFileInfo(const QString& file, const QString& channelPassword)
{
api().requestFileInfo(this, channelPassword, file, TODO_RETURN_CODE);
}
/*!
* Create a directory.
* \a path Name of the directory to create. The directory name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a password Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::mkdir(const QString& path, const QString& password)
{
api().requestCreateDirectory(this, password, path, TODO_RETURN_CODE);
}
/*!
* Moves or renames a file. If the source and target channels and paths are the same, the file will simply be renamed.
* \a "file" Old name of the file. The file name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* \a "toFile" New name of the file. The new name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "toChannel" Target channel, to which we want to move the file.
* \a "toChannelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::moveFile(const QString& file, const QString& toFile, const QString& channelPassword, const Channel* toChannel, const QString& toChannelPassword)
{
api().requestRenameFile(
this,
channelPassword,
toChannel ? toChannel : this,
toChannelPassword,
file,
toFile,
TODO_RETURN_CODE
);
}
/*!
* Delete one or more remote files on the server.
* \a "files" List of files we request to be deleted. The file names need to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::deleteFile(const QStringList& files, const QString& channelPassword)
{
api().requestDeleteFile(this, channelPassword, files, TODO_RETURN_CODE);
}
/*!
* Request updating the channel description
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::getChannelDescription() const
{
api().requestChannelDescription(this, TODO_RETURN_CODE);
}
/*!
* Removes the channel from the server
* \a "force" If true, the channel will be deleted even when it is not empty.
* Clients within the deleted channel are transfered to the default channel.
* Any contained subchannels are removed as well.
* If \c false, the server will refuse to delete a channel that is not empty.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::remove(bool force)
{
api().requestChannelDelete(this, force, TODO_RETURN_CODE);
}
/*!
* Send a text message to the channel
* \a "message" The text message
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::sendTextMessage(const QString& message)
{
api().requestSendChannelTextMsg(this, message, TODO_RETURN_CODE);
}
/*!
* Move the channel to a new parent channel
* \a "newParent" The parent channel where the moved channel is to be inserted as child. Use null to insert as top-level channel.
* \a "newChannelOrder" the \sa "Channel" after which <see langword="this" \sa "Channel" is sorted. <see langword="null" meaning its going to be the first \sa "Channel" under <paramref name="newParent".
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::moveTo(Channel* newParent, Channel* newChannelOrder)
{
if (utils::has_null(newParent))
return;
if (!utils::is_same_server(connection(), newParent, newChannelOrder))
return;
api().requestChannelMove(this, newParent, newChannelOrder, TODO_RETURN_CODE);
}
void Channel::flushUpdates()
{
d->flushChannelUpdates(this);
}
void Channel::refreshProperties(bool wait)
{
}
} // namespace TeamSpeakSdk
| 28.010811 | 206 | 0.714782 | faming-wang |
a8311a4c4cfe6fae6f6f99cf742aabb34308bc4b | 14,601 | cpp | C++ | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | 164 | 2019-06-30T18:14:38.000Z | 2022-03-13T14:36:10.000Z | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | null | null | null | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | 11 | 2019-09-11T13:40:59.000Z | 2022-01-28T09:24:24.000Z |
#include "serialization_demo.hpp"
#include "serialization_examples.hpp"
#include "blob.hpp"
#include <iostream>
#include <stdint.h>
#include <stdarg.h>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// Allocator //////////////////////////////////////////////////////////////
void* Allocator::allocate( sizet size, sizet alignment ) {
return malloc( size );
}
void* Allocator::allocate( sizet size, sizet alignment, cstring file, i32 line ) {
return malloc( size );
}
void Allocator::deallocate( void* pointer ) {
free( pointer );
}
// Log ////////////////////////////////////////////////////////////////////
static constexpr u32 k_string_buffer_size = 1024 * 1024;
static char log_buffer[ k_string_buffer_size ];
static void output_console( char* log_buffer_ ) {
printf( "%s", log_buffer_ );
}
static void output_visual_studio( char* log_buffer_ ) {
OutputDebugStringA( log_buffer_ );
}
void hprint( cstring format, ... ) {
va_list args;
va_start( args, format );
vsnprintf_s( log_buffer, k_string_buffer_size, format, args );
log_buffer[ k_string_buffer_size - 1 ] = '\0';
va_end( args );
output_console( log_buffer );
#if defined(_MSC_VER)
output_visual_studio( log_buffer );
#endif // _MSC_VER
}
// CharArray //////////////////////////////////////////////////////////////
void CharArray::init( Allocator* allocator_, cstring string ) {
size = ( u32 )( strlen( string ) + 1 );
capacity = size;
allocator = allocator_;
data = ( char* )halloca( size, allocator );
strcpy( data, string );
}
// File ///////////////////////////////////////////////////////////////////
static long file_get_size( FILE* f ) {
long fileSizeSigned;
fseek( f, 0, SEEK_END );
fileSizeSigned = ftell( f );
fseek( f, 0, SEEK_SET );
return fileSizeSigned;
}
char* file_read_binary( cstring filename, Allocator* allocator, sizet* size ) {
char* out_data = 0;
FILE* file = fopen( filename, "rb" );
if ( file ) {
// TODO: Use filesize or read result ?
sizet filesize = file_get_size( file );
out_data = ( char* )halloca( filesize + 1, allocator );
fread( out_data, filesize, 1, file );
out_data[ filesize ] = 0;
if ( size )
*size = filesize;
fclose( file );
}
return out_data;
}
char* file_read_text( cstring filename, Allocator* allocator, sizet* size ) {
char* text = 0;
FILE* file = fopen( filename, "r" );
if ( file ) {
sizet filesize = file_get_size( file );
text = ( char* )halloca( filesize + 1, allocator );
// Correct: use elementcount as filesize, bytes_read becomes the actual bytes read
// AFTER the end of line conversion for Windows (it uses \r\n).
sizet bytes_read = fread( text, 1, filesize, file );
text[ bytes_read ] = 0;
if ( size )
*size = filesize;
fclose( file );
}
return text;
}
void file_write_binary( cstring filename, void* memory, sizet size ) {
FILE* file = fopen( filename, "wb" );
fwrite( memory, size, 1, file );
fclose( file );
}
// Vec2s //////////////////////////////////////////////////////////////////
// Forward declaration for template specialization.
template<>
void BlobSerializer::serialize<vec2s>( vec2s* data );
// Serialization binary
template<>
void BlobSerializer::serialize<vec2s>( vec2s* data ) {
serialize( &data->x );
serialize( &data->y );
}
// OtherData //////////////////////////////////////////////////////////////
// Data structure added just to have a pointer to test.
//
struct OtherData {
f32 a;
u32 b;
};
template<>
void BlobSerializer::serialize<OtherData>( OtherData* data ) {
serialize( &data->a );
serialize( &data->b );
}
// GameDataV0 /////////////////////////////////////////////////////////////
//
// First version of the game data.
// Used to write older binaries and test versioning.
struct GameDataV0 : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 0;
}; // struct GameDataV0
template<>
void BlobSerializer::serialize<GameDataV0>( GameDataV0* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
serialize( &data->name );
serialize( &data->other_pointer );
}
//
// Second version of game data.
//
struct GameDataV1 : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeArray<u32> all_cs; // Added in V1
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 1;
}; // struct GameDataV1
template<>
void BlobSerializer::serialize<GameDataV1>( GameDataV1* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
if ( serializer_version > 0 ) {
serialize( &data->all_cs );
}
serialize( &data->name );
serialize( &data->other_pointer );
}
//
//
struct GameData : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeArray<u32> all_cs; // Added in V1
Array<u32> all_as; // Added in V2
CharArray new_name; // Added in V2
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 2;
}; // struct GameData
template<>
void BlobSerializer::serialize<GameData>( GameData* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
if ( serializer_version > 0 ) {
serialize( &data->all_cs );
}
else {
data->all_cs.set_empty();
}
if ( serializer_version > 1 ) {
serialize( &data->all_as );
serialize( &data->new_name );
}
else {
}
serialize( &data->name );
serialize( &data->other_pointer );
}
static Allocator s_heap_allocator;
int main() {
hprint( "Serialization demo\n" );
Allocator* allocator = &s_heap_allocator;
// 1. Resource Compilation and Inspection /////////////////////////////
compile_cutscene( allocator, "..//data//articles//serializationdemo//cutscene.json", "..//data//bin//cutscene.bin" );
inspect_cutscene( allocator, "..//data//bin//cutscene.bin" );
compile_scene( allocator, "..//data//articles//serializationdemo//new_game.json", "..//data//bin//new_game.bin" );
inspect_scene( allocator, "..//data//bin//new_game.bin" );
// 2. Write GameDataV0 binary
BlobSerializer write_blob_v0, read_blob_v0;
{
// NOTE: this is a non-optimal way of writing the blob, but still doable.
// Write V0 and read with GameData (V2)
char* memory = (char*)malloc( 1000 );
memset( memory, 0, 1000 );
GameDataV0* writing_data = ( GameDataV0* )memory;
writing_data->position = { 100,200 };
writing_data->other.a = 7.0f;
writing_data->other.b = 0xffff;
u32* effs = ( u32* )( memory + sizeof( GameDataV0 ) );
*effs = 0xffffffff;
char* name_memory = ( char* )( effs + 1 );
strcpy( name_memory, "IncredibleName" );
OtherData* other_pointer = ( OtherData* )( name_memory + strlen( name_memory ) + 1 );
other_pointer->a = 16.f;
other_pointer->b = 0xaaaaaaaa;
// Close to the allocate_and_set method used in blobs.
// Calculate the offset for the arrays
writing_data->all_effs.set( ( char* )effs, 1 );
writing_data->name.set( name_memory, strlen( name_memory ) );
// Calculate the offset for the pointer
writing_data->other_pointer.set( ( char* )other_pointer );
// Write to blob using serialization methods, by passing the writing data.
write_blob_v0.write_and_serialize( allocator, 0, 1000, writing_data );
//
GameData* game_data = read_blob_v0.read<GameData>( allocator, GameData::k_version, write_blob_v0.blob_memory, write_blob_v0.allocated_offset * 2 );
if ( game_data ) {
OtherData* other_data = game_data->other_pointer.get();
hy_assert( game_data->position.x == 100.f );
hy_assert( other_data->a == 16.f );
hy_assert( other_data->b == 0xaaaaaaaa );
hy_assert( strcmp( game_data->name.c_str(), "IncredibleName" ) == 0 );
hy_assert( game_data->all_effs[ 0 ] == 0xffffffff );
hprint( "V0 Read Done %s!\n", game_data->name.c_str() );
}
}
// Write GameDataV1 binary
BlobSerializer write_blob_v1, read_blob_v1;
{
// Use write blob to already fill the data.
// Allocate just a blob with 200 bytes
GameDataV1* game_data_v1 = write_blob_v1.write_and_prepare<GameDataV1>( allocator, 1, 200 );
game_data_v1->position.x = 700.f;
game_data_v1->position.y = 42.f;
u32 all_effs[] = { 0xffffffff, 0xffffffff };
write_blob_v1.allocate_and_set( game_data_v1->all_effs, 2, all_effs );
// other
game_data_v1->other.a = 8.f;
game_data_v1->other.b = 0xbbbbbbbb;
// all c
u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc };
write_blob_v1.allocate_and_set( game_data_v1->all_cs, 3, all_cs );
// name
cstring name_string = "GameDataV1Awesomeness";
write_blob_v1.allocate_and_set( game_data_v1->name, "%s", name_string );
// other pointer
write_blob_v1.allocate_and_set( game_data_v1->other_pointer, nullptr );
OtherData* other_data_pointed = game_data_v1->other_pointer.get();
other_data_pointed->a = 32.f;
other_data_pointed->b = 0xdddddddd;
// Read V1 blob, again with the v2 serializer.
GameData* game_data = read_blob_v1.read<GameData>( allocator, GameData::k_version, write_blob_v1.blob_memory, write_blob_v1.allocated_offset * 2 );
if ( game_data ) {
OtherData* other_data = game_data->other_pointer.get();
hy_assert( game_data->position.x == 700.f );
hy_assert( game_data->other.a == 8.f );
hy_assert( game_data->other.b == 0xbbbbbbbb );
hy_assert( other_data->a == 32.f );
hy_assert( other_data->b == 0xdddddddd );
hy_assert( strcmp( game_data->name.c_str(), "GameDataV1Awesomeness" ) == 0 );
hy_assert( game_data->all_effs[ 1 ] == 0xffffffff );
hy_assert( game_data->other_pointer->a == 32.f );
hprint( "V1 Read Done %s!\n", game_data->name.c_str() );
}
}
// Write GameDataV2 binary
BlobSerializer write_blob_v2, read_blob_v2, read_blob_v2_serialized;
{
GameData* game_data = write_blob_v2.write_and_prepare<GameData>( allocator, GameData::k_version, 300 );
game_data->position.x = 700.f;
game_data->position.y = 42.f;
u32 all_effs[] = { 0xffffffff, 0xffffffff };
write_blob_v2.allocate_and_set( game_data->all_effs, 2, all_effs );
// other
game_data->other.a = 8.f;
game_data->other.b = 0xbbbbbbbb;
// all c
u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc };
write_blob_v2.allocate_and_set( game_data->all_cs, 3, all_cs );
// all as
u32 all_as[] = { 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa };
write_blob_v2.allocate_and_set( game_data->all_as, 4, all_as );
// new name
cstring new_name_string = "GameDataV2Plus";
write_blob_v2.allocate_and_set( game_data->new_name, new_name_string );
// name
cstring name_string = "GameDataV2Awesomeness";
write_blob_v2.allocate_and_set( game_data->name, "%s", name_string );
// other pointer
write_blob_v2.allocate_and_set( game_data->other_pointer, nullptr );
OtherData* other_data_pointed = game_data->other_pointer.get();
other_data_pointed->a = 32.f;
other_data_pointed->b = 0xdddddddd;
// Read V2 blob. This is MEMORY MAPPED.
GameData* mmap_game_data = read_blob_v2.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2 );
// Force serialization of game data and test fields.
GameData* serialized_game_data = read_blob_v2_serialized.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2, true );
if ( mmap_game_data && serialized_game_data ) {
OtherData* mmap_other_data = mmap_game_data->other_pointer.get();
OtherData* serialized_other_data = serialized_game_data->other_pointer.get();
hy_assert( mmap_game_data->position.x == serialized_game_data->position.x );
hy_assert( mmap_game_data->position.x == 700.f );
hy_assert( mmap_other_data->a == serialized_other_data->a );
hy_assert( mmap_other_data->a == 32.f );
hy_assert( mmap_other_data->b == serialized_other_data->b );
hy_assert( mmap_other_data->b == 0xdddddddd );
hy_assert( strcmp( mmap_game_data->name.c_str(), serialized_game_data->name.c_str() ) == 0 );
hy_assert( mmap_game_data->all_effs[ 1 ] == serialized_game_data->all_effs[ 1 ] );
hy_assert( mmap_game_data->all_effs[ 1 ] == 0xffffffff );
hy_assert( mmap_game_data->other_pointer->a == serialized_game_data->other_pointer->a );
hy_assert( mmap_game_data->all_as.get()[3] == serialized_game_data->all_as[ 3 ] );
hy_assert( serialized_game_data->all_as[ 3 ] == 0xaaaaaaaa );
hy_assert( serialized_game_data->all_as[ 0 ] == 0xaaaaaaaa );
hy_assert( mmap_game_data->all_as.get()[ 3 ] == 0xaaaaaaaa );
hy_assert( mmap_game_data->all_as.get()[ 0 ] == 0xaaaaaaaa );
cstring aa0 = mmap_game_data->new_name.get();
hy_assert( strcmp( mmap_game_data->new_name.get(), "GameDataV2Plus" ) == 0 );
cstring aa1 = serialized_game_data->new_name.c_str();
hy_assert( strcmp( serialized_game_data->new_name.c_str(), "GameDataV2Plus" ) == 0 );
hprint( "V2 Read Done %s!\n", mmap_game_data->name.c_str() );
}
}
hprint( "Test finished SUCCESSFULLY!\n" );
}
| 35.183133 | 183 | 0.606465 | rioscode |
a831a4a671483363466c72a4efb8812d5d95a62b | 23,938 | cpp | C++ | lib/Common/Common/Tick.cpp | satheeshravi/ChakraCore | 3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5 | [
"MIT"
] | 1 | 2021-11-07T18:56:21.000Z | 2021-11-07T18:56:21.000Z | lib/Common/Common/Tick.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | null | null | null | lib/Common/Common/Tick.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | 1 | 2021-09-04T23:26:57.000Z | 2021-09-04T23:26:57.000Z | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonCommonPch.h"
#include "Common/Tick.h"
namespace Js {
uint64 Tick::s_luFreq;
uint64 Tick::s_luBegin;
#if DBG
uint64 Tick::s_DEBUG_luStart = 0;
uint64 Tick::s_DEBUG_luSkip = 0;
#endif
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// struct Tick
///
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// Tick::Tick
///
/// Tick() initializes a new Tick instance to an "empty" time. This instance
/// must be assigned to another Tick instance or Now() to have value.
///
///----------------------------------------------------------------------------
Tick::Tick()
{
m_luTick = 0;
}
///----------------------------------------------------------------------------
///
/// Tick::Tick
///
/// Tick() initializes a new Tick instance to a specific time, in native
/// time units.
///
///----------------------------------------------------------------------------
Tick::Tick(
uint64 luTick) // Tick, in internal units
{
m_luTick = luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::FromMicroseconds
///
/// FromMicroseconds() returns a Tick instance from a given time in
/// microseconds.
///
///----------------------------------------------------------------------------
Tick
Tick::FromMicroseconds(
uint64 luTime) // Time, in microseconds
{
//
// Ensure we can convert losslessly.
//
#if DBG
const uint64 luMaxTick = _UI64_MAX / s_luFreq;
AssertMsg(luTime <= luMaxTick, "Ensure time can be converted losslessly");
#endif // DBG
//
// Create the Tick
//
uint64 luTick = luTime * s_luFreq / ((uint64) 1000000);
return Tick(luTick);
}
///----------------------------------------------------------------------------
///
/// Tick::FromQPC
///
/// FromQPC() returns a Tick instance from a given QPC time.
///
///----------------------------------------------------------------------------
Tick
Tick::FromQPC(
uint64 luTime) // Time, in QPC units
{
return Tick(luTime - s_luBegin);
}
///----------------------------------------------------------------------------
///
/// Tick::ToQPC
///
/// ToQPC() returns the QPC time for this time instance
///
///----------------------------------------------------------------------------
uint64
Tick::ToQPC()
{
return (m_luTick + s_luBegin);
}
///----------------------------------------------------------------------------
///
/// Tick::operator +
///
/// operator +()
///
///----------------------------------------------------------------------------
Tick
Tick::operator +(
TickDelta tdChange // RHS TickDelta
) const
{
return Tick(m_luTick + tdChange.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// Tick::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
Tick
Tick::operator -(
TickDelta tdChange // RHS TickDelta
) const
{
return Tick(m_luTick - tdChange.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// Tick::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
TickDelta
Tick::operator -(
Tick timeOther // RHS Tick
) const
{
return TickDelta(m_luTick - timeOther.m_luTick);
}
///----------------------------------------------------------------------------
///
/// Tick::operator ==
///
/// operator ==()
///
///----------------------------------------------------------------------------
bool
Tick::operator ==(
Tick timeOther // RHS Tick
) const
{
return m_luTick == timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator !=
///
/// operator !=()
///
///----------------------------------------------------------------------------
bool
Tick::operator !=(
Tick timeOther // RHS Tick
) const
{
return m_luTick != timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator <
///
/// operator <()
///
///----------------------------------------------------------------------------
bool
Tick::operator <(
Tick timeOther // RHS Tick
) const
{
return m_luTick < timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator <=
///
/// operator <=()
///
///----------------------------------------------------------------------------
bool
Tick::operator <=(
Tick timeOther // RHS Tick
) const
{
return m_luTick <= timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator >
///
/// operator >()
///
///----------------------------------------------------------------------------
bool
Tick::operator >(
Tick timeOther // RHS Tick
) const
{
return m_luTick > timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator >=
///
/// operator >=()
///
///----------------------------------------------------------------------------
bool
Tick::operator >=(
Tick timeOther // RHS Tick
) const
{
return m_luTick >= timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// struct TickDelta
///
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// TickDelta::TickDelta
///
/// TickDelta() initializes a new TickDelta instance to "zero" delta.
///
///----------------------------------------------------------------------------
TickDelta::TickDelta()
{
m_lnDelta = 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::TickDelta
///
/// TickDelta() initializes a new TickDelta instance to a specific time delta,
/// in native time units.
///
///----------------------------------------------------------------------------
TickDelta::TickDelta(
int64 lnDelta)
{
m_lnDelta = lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::ToMicroseconds
///
/// ToMicroseconds() returns the time delta, in microseconds. The time is
/// rounded to the nearest available whole units.
///
///----------------------------------------------------------------------------
int64
TickDelta::ToMicroseconds() const
{
if (*this == Infinite())
{
return _I64_MAX;
}
//
// Ensure we can convert losslessly.
//
const int64 lnMinTimeDelta = _I64_MIN / ((int64) 1000000);
const int64 lnMaxTimeDelta = _I64_MAX / ((int64) 1000000);
AssertMsg((m_lnDelta <= lnMaxTimeDelta) && (m_lnDelta >= lnMinTimeDelta),
"Ensure delta can be converted to microseconds losslessly");
//
// Compute the microseconds.
//
int64 lnFreq = (int64) Tick::s_luFreq;
int64 lnTickDelta = (m_lnDelta * ((int64) 1000000)) / lnFreq;
return lnTickDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMicroseconds
///
/// FromMicroseconds() returns a TickDelta instance from a given delta in
/// microseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMicroseconds(
int64 lnTimeDelta) // Time delta, in 1/1000^2 sec
{
AssertMsg(lnTimeDelta != _I64_MAX, "Use Infinite() to create an infinite TickDelta");
//
// Ensure that we can convert losslessly.
//
int64 lnFreq = (int64) Tick::s_luFreq;
#if DBG
const int64 lnMinTimeDelta = _I64_MIN / lnFreq;
const int64 lnMaxTimeDelta = _I64_MAX / lnFreq;
AssertMsg((lnTimeDelta <= lnMaxTimeDelta) && (lnTimeDelta >= lnMinTimeDelta),
"Ensure delta can be converted to native format losslessly");
#endif // DBG
//
// Create the TickDelta
//
int64 lnTickDelta = (lnTimeDelta * lnFreq) / ((int64) 1000000);
TickDelta td(lnTickDelta);
AssertMsg(td != Infinite(), "Can not create infinite TickDelta");
return td;
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMicroseconds
///
/// FromMicroseconds() returns a TickDelta instance from a given delta in
/// microseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMicroseconds(
int nTimeDelta) // Tick delta, in 1/1000^2 sec
{
AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");
return FromMicroseconds((int64) nTimeDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMilliseconds
///
/// FromMilliseconds() returns a TickDelta instance from a given delta in
/// milliseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMilliseconds(
int nTimeDelta) // Tick delta, in 1/1000^1 sec
{
AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");
return FromMicroseconds(((int64) nTimeDelta) * ((int64) 1000));
}
///----------------------------------------------------------------------------
///
/// TickDelta::Infinite
///
/// Infinite() returns a time-delta infinitely far away.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::Infinite()
{
return TickDelta(_I64_MAX);
}
///----------------------------------------------------------------------------
///
/// TickDelta::IsForward
///
/// IsForward() returns whether adding this TickDelta to a given Tick will
/// not move the time backwards.
///
///----------------------------------------------------------------------------
bool
TickDelta::IsForward() const
{
return m_lnDelta >= 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::IsBackward
///
/// IsBackward() returns whether adding this TickDelta to a given Tick will
/// not move the time forwards.
///
///----------------------------------------------------------------------------
bool
TickDelta::IsBackward() const
{
return m_lnDelta <= 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::Abs
///
/// Abs() returns the absolute value of the TickDelta.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::Abs(TickDelta tdOther)
{
return TickDelta(tdOther.m_lnDelta < 0 ? -tdOther.m_lnDelta : tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator %
///
/// operator %()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator %(
TickDelta tdOther // RHS TickDelta
) const
{
return TickDelta(m_lnDelta % tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator \
///
/// operator \() - Divides one TickDelta by another, in TickDelta units
///
///----------------------------------------------------------------------------
int64
TickDelta::operator /(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta / tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator +
///
/// operator +()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator +(
TickDelta tdOther // RHS TickDelta
) const
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta + tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator -(
TickDelta tdOther // RHS TickDelta
) const
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta - tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator *
///
/// operator *()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator *(
int nScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta * nScale);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator *
///
/// operator *()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator *(
float flScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
return TickDelta((int64) (((double) m_lnDelta) * ((double) flScale)));
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator /
///
/// operator /()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator /(
int nScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
AssertMsg(nScale != 0, "Can not scale by 0");
return TickDelta(m_lnDelta / nScale);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator /
///
/// operator /()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator /(
float flScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
AssertMsg(flScale != 0, "Can not scale by 0");
return TickDelta((int64) (((double) m_lnDelta) / ((double) flScale)));
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator +=
///
/// operator +=()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator +=(
TickDelta tdOther) // RHS TickDelta
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
m_lnDelta = m_lnDelta + tdOther.m_lnDelta;
return *this;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator -=
///
/// operator -=()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator -=(
TickDelta tdOther) // RHS TickDelta
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
m_lnDelta = m_lnDelta - tdOther.m_lnDelta;
return *this;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator ==
///
/// operator ==()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator ==(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta == tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator !=
///
/// operator !=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator !=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta != tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator <
///
/// operator <()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator <(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta < tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator <=
///
/// operator <=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator <=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta <= tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator >
///
/// operator >()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator >(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta > tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator >=
///
/// operator >=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator >=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta >= tdOther.m_lnDelta;
}
void Tick::InitType()
{
/* CheckWin32( */ QueryPerformanceFrequency((LARGE_INTEGER *) &s_luFreq);
/* CheckWin32( */ QueryPerformanceCounter((LARGE_INTEGER *) &s_luBegin);
#if DBG
s_luBegin += s_DEBUG_luStart;
#endif
//
// Ensure that we have a sufficient amount of time so that we can handle useful time operations.
//
uint64 nSec = _UI64_MAX / s_luFreq;
if (nSec < 5 * 60)
{
#if FIXTHIS
PromptInvalid("QueryPerformanceFrequency() will not provide at least 5 minutes");
return Results::GenericFailure;
#endif
}
}
Tick Tick::Now()
{
// Determine our current time
uint64 luCurrent = s_luBegin;
/* Verify( */ QueryPerformanceCounter((LARGE_INTEGER *) &luCurrent);
#if DBG
luCurrent += s_DEBUG_luStart + s_DEBUG_luSkip;
#endif
// Create a Tick instance, using our delta since we started tracking time.
uint64 luDelta = luCurrent - s_luBegin;
return Tick(luDelta);
}
uint64 Tick::ToMicroseconds() const
{
//
// Convert time in microseconds (1 / 1000^2). Because of the finite precision and wrap-around,
// this math depends on where the Tick is.
//
const uint64 luOneSecUs = (uint64) 1000000;
const uint64 luSafeTick = _UI64_MAX / luOneSecUs;
if (m_luTick < luSafeTick)
{
//
// Small enough to convert directly into microseconds.
//
uint64 luTick = (m_luTick * luOneSecUs) / s_luFreq;
return luTick;
}
else
{
//
// Number is too large, so we need to do this is stages.
// 1. Compute the number of seconds
// 2. Convert the remainder
// 3. Add the two parts together
//
uint64 luSec = m_luTick / s_luFreq;
uint64 luRemain = m_luTick - luSec * s_luFreq;
uint64 luTick = (luRemain * luOneSecUs) / s_luFreq;
luTick += luSec * luOneSecUs;
return luTick;
}
}
int TickDelta::ToMilliseconds() const
{
if (*this == Infinite())
{
return _I32_MAX;
}
int64 nTickUs = ToMicroseconds();
int64 lnRound = 500;
if (nTickUs < 0)
{
lnRound = -500;
}
int64 lnDelta = (nTickUs + lnRound) / ((int64) 1000);
AssertMsg((lnDelta <= INT_MAX) && (lnDelta >= INT_MIN), "Ensure no overflow");
return (int) lnDelta;
}
}
| 27.202273 | 105 | 0.346228 | satheeshravi |
a83420610dd94d8b6dd2ecd189c5a44d95f63d08 | 5,146 | cpp | C++ | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 5 | 2020-01-14T06:45:59.000Z | 2021-03-11T11:22:35.000Z | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 2 | 2019-02-12T21:55:08.000Z | 2019-02-20T01:01:24.000Z | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 9 | 2018-09-09T20:48:17.000Z | 2021-03-11T11:22:52.000Z | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtGlobal>
#include <QTimer>
#include "rviz/ogre_helpers/qt_ogre_render_window.h"
#include "rviz/ogre_helpers/initialization.h"
#include "rviz/image/ros_image_texture.h"
#include "ros/ros.h"
#include <ros/package.h>
#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreSceneManager.h>
#include <OgreViewport.h>
#include <OgreRectangle2D.h>
#include <OgreMaterial.h>
#include <OgreMaterialManager.h>
#include <OgreTextureUnitState.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>
#include <OgreSceneNode.h>
#include "image_view.h"
using namespace rviz;
ImageView::ImageView( QWidget* parent )
: QtOgreRenderWindow( parent )
, texture_it_(nh_)
{
setAutoRender(false);
scene_manager_ = ogre_root_->createSceneManager( Ogre::ST_GENERIC, "TestSceneManager" );
}
ImageView::~ImageView()
{
delete texture_;
}
void ImageView::showEvent( QShowEvent* event )
{
QtOgreRenderWindow::showEvent( event );
V_string paths;
paths.push_back(ros::package::getPath(ROS_PACKAGE_NAME) + "/ogre_media/textures");
initializeResources(paths);
setCamera( scene_manager_->createCamera( "Camera" ));
std::string resolved_image = nh_.resolveName("image");
if( resolved_image == "/image" )
{
ROS_WARN("image topic has not been remapped");
}
std::stringstream title;
title << "rviz Image Viewer [" << resolved_image << "]";
setWindowTitle( QString::fromStdString( title.str() ));
texture_ = new ROSImageTexture();
try
{
texture_->clear();
texture_sub_.reset(new image_transport::SubscriberFilter());
texture_sub_->subscribe(texture_it_, "image", 1, image_transport::TransportHints("raw"));
texture_sub_->registerCallback(boost::bind(&ImageView::textureCallback, this, _1));
}
catch (ros::Exception& e)
{
ROS_ERROR("%s", (std::string("Error subscribing: ") + e.what()).c_str());
}
Ogre::MaterialPtr material =
Ogre::MaterialManager::getSingleton().create( "Material",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
material->setCullingMode(Ogre::CULL_NONE);
material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(true);
material->getTechnique(0)->setLightingEnabled(false);
Ogre::TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState();
tu->setTextureName(texture_->getTexture()->getName());
tu->setTextureFiltering( Ogre::TFO_NONE );
Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
rect->setCorners(-1.0f, 1.0f, 1.0f, -1.0f);
rect->setMaterial(material->getName());
rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1);
Ogre::AxisAlignedBox aabb;
aabb.setInfinite();
rect->setBoundingBox(aabb);
Ogre::SceneNode* node = scene_manager_->getRootSceneNode()->createChildSceneNode();
node->attachObject(rect);
node->setVisible(true);
QTimer* timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( onTimer() ));
timer->start( 33 );
}
void ImageView::onTimer()
{
ros::spinOnce();
static bool first = true;
try
{
if( texture_->update() )
{
if( first )
{
first = false;
resize( texture_->getWidth(), texture_->getHeight() );
}
}
ogre_root_->renderOneFrame();
}
catch( UnsupportedImageEncoding& e )
{
ROS_ERROR("%s", e.what());
}
if( !nh_.ok() )
{
close();
}
}
void ImageView::textureCallback(const sensor_msgs::Image::ConstPtr& msg)
{
if (texture_) {
texture_->addMessage(msg);
}
}
| 30.630952 | 108 | 0.70754 | romi2002 |
a8373d2a8b68ee46f2203c509b7341604c44253a | 4,544 | cpp | C++ | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | 4 | 2017-05-31T08:39:37.000Z | 2018-04-22T02:51:18.000Z | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | null | null | null | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | 1 | 2018-03-10T21:25:01.000Z | 2018-03-10T21:25:01.000Z | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2DistanceJoint.h"
#include "../b2Body.h"
#include "../b2World.h"
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def)
: b2Joint(def)
{
m_localAnchor1 = b2MulT(m_body1->m_R, def->anchorPoint1 - m_body1->m_position);
m_localAnchor2 = b2MulT(m_body2->m_R, def->anchorPoint2 - m_body2->m_position);
b2Vec2 d = def->anchorPoint2 - def->anchorPoint1;
m_length = d.Length();
m_impulse = 0.0f;
}
void b2DistanceJoint::InitVelocityConstraints()
{
// Compute the effective mass matrix.
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
m_u = m_body2->m_position + r2 - m_body1->m_position - r1;
// Handle singularity.
float32 length = m_u.Length();
if (length > b2_linearSlop)
{
m_u *= 1.0f / length;
}
else
{
m_u.Set(0.0f, 0.0f);
}
float32 cr1u = b2Cross(r1, m_u);
float32 cr2u = b2Cross(r2, m_u);
m_mass = m_body1->m_invMass + m_body1->m_invI * cr1u * cr1u + m_body2->m_invMass + m_body2->m_invI * cr2u * cr2u;
b2Assert(m_mass > FLT_EPSILON);
m_mass = 1.0f / m_mass;
if (b2World::s_enableWarmStarting)
{
b2Vec2 P = m_impulse * m_u;
m_body1->m_linearVelocity -= m_body1->m_invMass * P;
m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_linearVelocity += m_body2->m_invMass * P;
m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P);
}
else
{
m_impulse = 0.0f;
}
}
void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step)
{
NOT_USED(step);
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
// Cdot = dot(u, v + cross(w, r))
b2Vec2 v1 = m_body1->m_linearVelocity + b2Cross(m_body1->m_angularVelocity, r1);
b2Vec2 v2 = m_body2->m_linearVelocity + b2Cross(m_body2->m_angularVelocity, r2);
float32 Cdot = b2Dot(m_u, v2 - v1);
float32 impulse = -m_mass * Cdot;
m_impulse += impulse;
b2Vec2 P = impulse * m_u;
m_body1->m_linearVelocity -= m_body1->m_invMass * P;
m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_linearVelocity += m_body2->m_invMass * P;
m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P);
}
bool b2DistanceJoint::SolvePositionConstraints()
{
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
b2Vec2 d = m_body2->m_position + r2 - m_body1->m_position - r1;
float32 length = d.Normalize();
float32 C = length - m_length;
C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection);
float32 impulse = -m_mass * C;
m_u = d;
b2Vec2 P = impulse * m_u;
m_body1->m_position -= m_body1->m_invMass * P;
m_body1->m_rotation -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_position += m_body2->m_invMass * P;
m_body2->m_rotation += m_body2->m_invI * b2Cross(r2, P);
m_body1->m_R.Set(m_body1->m_rotation);
m_body2->m_R.Set(m_body2->m_rotation);
return b2Abs(C) < b2_linearSlop;
}
b2Vec2 b2DistanceJoint::GetAnchor1() const
{
return m_body1->m_position + b2Mul(m_body1->m_R, m_localAnchor1);
}
b2Vec2 b2DistanceJoint::GetAnchor2() const
{
return m_body2->m_position + b2Mul(m_body2->m_R, m_localAnchor2);
}
b2Vec2 b2DistanceJoint::GetReactionForce(float32 invTimeStep) const
{
b2Vec2 F = (m_impulse * invTimeStep) * m_u;
return F;
}
float32 b2DistanceJoint::GetReactionTorque(float32 invTimeStep) const
{
NOT_USED(invTimeStep);
return 0.0f;
}
| 30.911565 | 114 | 0.715009 | Rinnegatamante |
a83a6eb63f2269281aac94928d0c6c00d9bcf0f4 | 352 | cpp | C++ | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void)
{
int k, n, time = 210, ans, t;
char z;
bool check = false;
cin >> k >> n;
for (int i = 0; i < n; i++)
{
cin >> t >> z;
if (time - t <= 0 && !check)
{
ans = k;
check = true;
}
else
{
time -= t;
if (z == 'T')
k = (k + 1) > 8 ? 1 : (k + 1);
}
}
cout << ans;
}
| 13.538462 | 34 | 0.431818 | Twinparadox |
a840ed153da786ca61ed206500aa281b57cb970d | 5,840 | cpp | C++ | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | #include "IntroState.hpp"
#include "MainState.hpp"
template<> IntroState* Ogre::Singleton<IntroState>::msSingleton = 0;
IntroState::IntroState():
_physicsMgr(NULL),
_mapMgr(NULL),
_overlayMgr(NULL),
_cameraMgr(NULL),
_shootMgr(NULL),
_collisionMgr(NULL),
_characterMgr(NULL)
{}
void
IntroState::enter ()
{
if (_root == NULL)
{
_root = Ogre::Root::getSingletonPtr();
}
if (_sceneMgr == NULL)
{
_sceneMgr = _root->getSceneManager("SceneManager");
}
if (_camera == NULL)
{
_camera = _sceneMgr->createCamera("MainCamera");
}
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide();
_viewport = _root->getAutoCreatedWindow()->addViewport(_camera);
_viewport->setBackgroundColour(Ogre::ColourValue(0.3, 0.8, 0.8));
// Creating and placing camera
_camera->setPosition( Ogre::Vector3(0, 0, 10) );
_camera->lookAt( Ogre::Vector3(0, 0, 8) );
_camera->setNearClipDistance(0.001);
_camera->setFarClipDistance(1000);
_camera->setFOVy(Ogre::Degree(38));
double width = _viewport->getActualWidth();
double height = _viewport->getActualHeight();
_camera->setAspectRatio(width / height);
_sceneMgr->setAmbientLight( Ogre::ColourValue(1, 1, 1) );
_sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
_sceneMgr->setShadowTextureCount(30);
_sceneMgr->setShadowTextureSize(512);
initializeManagers();
createGUI();
loadBackgroundImage();
_exitGame = false;
}
void IntroState::initializeManagers()
{
if (_physicsMgr == NULL)
{
_physicsMgr = new MyPhysicsManager( _sceneMgr );
}
if (_mapMgr == NULL)
{
_mapMgr = new MapManager( _sceneMgr, MyPhysicsManager::getSingletonPtr()->getPhysicWorld() );
}
if (_overlayMgr == NULL)
{
_overlayMgr = new MyOverlayManager();
}
if (_cameraMgr == NULL)
{
_cameraMgr = new CameraManager( _sceneMgr );
}
if (_shootMgr == NULL)
{
_shootMgr = new ShootManager( _sceneMgr );
}
if (_collisionMgr == NULL)
{
_collisionMgr = new MyCollisionManager( _sceneMgr );
}
if (_characterMgr == NULL)
{
_characterMgr = new CharacterManager( _sceneMgr );
}
}
void
IntroState::exit()
{
_sceneMgr->clearScene();
_root->getAutoCreatedWindow()->removeAllViewports();
}
void
IntroState::pause ()
{
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->hide();
_intro->hide();
}
void
IntroState::resume ()
{
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide();
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show();
_intro->show();
}
bool
IntroState::frameStarted
(const Ogre::FrameEvent& evt)
{
MapManager::getSingletonPtr()->update( evt.timeSinceLastFrame );
return true;
}
bool
IntroState::frameEnded
(const Ogre::FrameEvent& evt)
{
if (_exitGame)
return false;
return true;
}
void
IntroState::keyPressed
(const OIS::KeyEvent &e)
{
}
void
IntroState::keyReleased
(const OIS::KeyEvent &e )
{
if (e.key == OIS::KC_ESCAPE)
{
_exitGame = true;
}
else if (e.key == OIS::KC_SPACE)
{
pushState(MainState::getSingletonPtr());
}
}
void
IntroState::mouseMoved
(const OIS::MouseEvent &e)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(e.state.X.abs, e.state.Y.abs);
}
void
IntroState::mousePressed
(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
}
void
IntroState::mouseReleased
(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
}
IntroState*
IntroState::getSingletonPtr ()
{
return msSingleton;
}
IntroState&
IntroState::getSingleton ()
{
assert(msSingleton);
return *msSingleton;
}
void IntroState::createGUI()
{
if(_intro == NULL)
{
_intro = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("splash.layout");
CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->addChild(_intro);
}
else
{
_intro->show();
}
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show();
}
void IntroState::loadBackgroundImage()
{
// Randmonly select background
std::string _all_backgrounds[3] {"oil.jpg", "cubism.jpg", "glass.jpg"};
unsigned seed = std::time(0);
std::srand(seed);
std::random_shuffle(&_all_backgrounds[0], &_all_backgrounds[sizeof(_all_backgrounds)/sizeof(*_all_backgrounds)]);
Ogre::TexturePtr m_backgroundTexture = Ogre::TextureManager::getSingleton().createManual("BackgroundTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,640, 480, 0, Ogre::PF_BYTE_BGR,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
Ogre::Image m_backgroundImage;
m_backgroundImage.load(_all_backgrounds[0], Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
m_backgroundTexture->loadImage(m_backgroundImage);
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("BackgroundMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
material->getTechnique(0)->getPass(0)->createTextureUnitState("BackgroundTexture");
material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
_rect = new Ogre::Rectangle2D(true);
_rect->setCorners(-1.0, 1.0, 1.0, -1.0);
_rect->setMaterial("BackgroundMaterial");
_rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);
_rect->setBoundingBox(Ogre::AxisAlignedBox(-100000.0*Ogre::Vector3::UNIT_SCALE, 100000.0*Ogre::Vector3::UNIT_SCALE));
_backgroundNode = _sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundMenu");
_backgroundNode->attachObject(_rect);
MapManager::getSingletonPtr()->fadeIn();
}
| 26.188341 | 259 | 0.693836 | CEDV-2016 |
a842b886c04195753104f238791fe553759048cb | 391 | cpp | C++ | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 2 | 2021-04-21T07:59:45.000Z | 2021-05-13T05:53:00.000Z | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | null | null | null | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 1 | 2021-04-17T15:32:18.000Z | 2021-04-17T15:32:18.000Z | #include "../../headers.h"
/*
* Something to remember here is that:
* all these functions - take iterators as I/P's.
* But iterators are more like pointers and they v
* can be incremented or decremented
*/
int main()
{
string s = "accenllt";
string::iterator it = adjacent_find(s.begin()+2,s.end());
cout << "The result is: " << it - s.begin() << endl;
return 0;
} | 24.4375 | 61 | 0.621483 | hariharanragothaman |
61b41538e3a47fea982a03c17debc8f290f63c45 | 935 | cpp | C++ | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | #include "VBoxLayout.h"
#include <QVBoxLayout>
#include <QPoint>
VBoxLayout::VBoxLayout()
: VBoxLayout(nullptr)
{
}
VBoxLayout::VBoxLayout(QWidget* parent)
: QWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setAlignment(Qt::AlignTop);
layout->setSpacing(0);
}
void VBoxLayout::add(QWidget* widget)
{
widget->setParent(this);
layout()->addWidget(widget);
}
void VBoxLayout::drop(QWidget* widget, QPoint pos)
{
QVBoxLayout* m_layout = static_cast<QVBoxLayout*>(layout());
pos.setX(width() / 2);
if (QWidget* child = childAt(pos))
{
if (child == widget) return;
int idx = m_layout->indexOf(child);
int const x = pos.x() - child->pos().x();
int const h = child->height() / 2;
if (x > h) ++idx;
m_layout->insertWidget(idx, widget);
}
else
{
m_layout->addWidget(widget);
}
widget->setParent(this);
}
void VBoxLayout::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
| 19.479167 | 61 | 0.685561 | Evgenii-Evgenevich |
61b65a186189ac6441e0e7609a22f179ba4fc99c | 813 | hpp | C++ | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | //
// util/Math.hpp
// pTK
//
// Created by Robin Gustafsson on 2021-12-11.
//
#ifndef PTK_UTIL_MATH_HPP
#define PTK_UTIL_MATH_HPP
// C++ Headers
#include <cmath>
#include <string>
namespace pTK
{
/** This file is purely for the need of math functions.
Since in Linux apparently some math functions, like ceilf
are defined in the global namespace and not in std.
*/
namespace Math
{
static inline float ceilf(float arg)
{
// This is apparently needed in Linux.
// Since, ceilf is in the global namespace?!
// Can't use std::ceilf.
using namespace std;
// This will call whatever is defined outside this function.
return ::ceilf(arg);
}
}
}
#endif // PTK_UTIL_MATH_HPP
| 19.357143 | 72 | 0.601476 | Knobin |
61b7f2e8c315ca859282984ab3bab03a08b60802 | 15,876 | inl | C++ | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_SharedMemoryStream_inl_
#define _Stroika_Foundation_Streams_SharedMemoryStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <mutex>
#include "../Execution/WaitableEvent.h"
namespace Stroika::Foundation::Streams {
/*
********************************************************************************
******************* SharedMemoryStream<ELEMENT_TYPE>::Rep_ *********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class SharedMemoryStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep {
public:
using ElementType = ELEMENT_TYPE;
private:
bool fIsOpenForRead_{true};
public:
Rep_ ()
: fData_{}
, fReadCursor_{fData_.begin ()}
, fWriteCursor_{fData_.begin ()}
{
}
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: Rep_{}
{
Write (start, end);
}
Rep_ (const Rep_&) = delete;
~Rep_ () = default;
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return true;
}
virtual void CloseWrite () override
{
Require (IsOpenWrite ());
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fClosedForWrites_ = true;
}
fMoreDataWaiter_.Set ();
}
virtual bool IsOpenWrite () const override
{
return not fClosedForWrites_;
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fIsOpenForRead_ = false;
}
virtual bool IsOpenRead () const override
{
return fIsOpenForRead_;
}
virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
Require (IsOpenRead ());
size_t nRequested = intoEnd - intoStart;
tryAgain:
fMoreDataWaiter_.Wait ();
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; // hold lock for everything EXCEPT wait
Assert ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
size_t nAvail = fData_.end () - fReadCursor_;
if (nAvail == 0 and not fClosedForWrites_) {
fMoreDataWaiter_.Reset (); // ?? @todo consider - is this a race? If we reset at same time(apx) as someone else sets
goto tryAgain; // cannot wait while we hold lock
}
size_t nCopied = min (nAvail, nRequested);
{
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#else
copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#endif
fReadCursor_ = fReadCursor_ + nCopied;
}
return nCopied; // this can be zero on EOF
}
virtual optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
size_t nDefinitelyAvail = fData_.end () - fReadCursor_;
if (nDefinitelyAvail > 0) {
return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, nDefinitelyAvail);
}
else if (fClosedForWrites_) {
return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, 0);
}
else {
return {}; // if nothing available, but not closed for write, no idea if more to come
}
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start != nullptr or start == end);
Require (end != nullptr or start == end);
Require (IsOpenWrite ());
if (start != end) {
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
size_t roomLeft = fData_.end () - fWriteCursor_;
size_t roomRequired = end - start;
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
if (roomLeft < roomRequired) {
size_t curReadOffset = fReadCursor_ - fData_.begin ();
size_t curWriteOffset = fWriteCursor_ - fData_.begin ();
const size_t kChunkSize_ = 128; // WAG: @todo tune number...
Containers::ReserveSpeedTweekAddN (fData_, roomRequired - roomLeft, kChunkSize_);
fData_.resize (curWriteOffset + roomRequired);
fReadCursor_ = fData_.begin () + curReadOffset;
fWriteCursor_ = fData_.begin () + curWriteOffset;
Assert (fWriteCursor_ < fData_.end ());
}
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (start, start + roomRequired, fWriteCursor_);
#else
copy (start, start + roomRequired, fWriteCursor_);
#endif
fWriteCursor_ += roomRequired;
Assert (fReadCursor_ < fData_.end ()); // < because we wrote at least one byte and that didnt move read cursor
Assert (fWriteCursor_ <= fData_.end ());
}
}
virtual void Flush () override
{
// nothing todo - write 'writes thru'
}
virtual SeekOffsetType GetReadOffset () const override
{
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uOffset = static_cast<SeekOffsetType> (offset);
if (uOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uOffset);
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
} break;
case Whence::eFromEnd: {
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
} break;
}
Ensure ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
Require (IsOpenWrite ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fWriteCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenWrite ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<SeekOffsetType> (offset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (offset);
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
} break;
case Whence::eFromEnd: {
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
} break;
}
Ensure ((fData_.begin () <= fWriteCursor_) and (fWriteCursor_ <= fData_.end ()));
return fWriteCursor_ - fData_.begin ();
}
vector<ElementType> AsVector () const
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fData_;
}
string AsString () const
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return string (reinterpret_cast<const char*> (Containers::Start (fData_)), reinterpret_cast<const char*> (Containers::End (fData_)));
}
private:
mutable recursive_mutex fMutex_;
Execution::WaitableEvent fMoreDataWaiter_{Execution::WaitableEvent::eManualReset}; // not a race cuz always set/reset when holding fMutex; no need to pre-set cuz auto set when someone adds data (Write)
vector<ElementType> fData_;
typename vector<ElementType>::iterator fReadCursor_;
typename vector<ElementType>::iterator fWriteCursor_;
bool fClosedForWrites_{false};
};
/*
********************************************************************************
********************** SharedMemoryStream<ELEMENT_TYPE> ************************
********************************************************************************
*/
DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wattributes\"")
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New ([[maybe_unused]] Execution::InternallySynchronized internallySynchronized) -> Ptr
{
// always return internally synchronized rep
return make_shared<Rep_> ();
}
DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wattributes\"")
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr
{
return make_shared<Rep_> (start, end);
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr
{
return New (start, end);
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const Memory::BLOB& blob) -> Ptr
{
return New (blob.begin (), blob.end ());
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const Memory::BLOB& blob) -> Ptr
{
return New (blob.begin (), blob.end ());
}
/*
********************************************************************************
****************** SharedMemoryStream<ELEMENT_TYPE>::Ptr ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline SharedMemoryStream<ELEMENT_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from)
: inherited{from}
{
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepConstRef_ () const -> const Rep_&
{
// reinterpret_cast faster than dynamic_cast - check equivalent
Assert (dynamic_cast<const Rep_*> (&inherited::_GetRepConstRef ()) == reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ()));
return *reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ());
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepRWRef_ () const -> Rep_&
{
// reinterpret_cast faster than dynamic_cast - check equivalent
Assert (dynamic_cast<Rep_*> (&inherited::_GetRepRWRef ()) == reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ()));
return *reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ());
}
template <>
template <>
inline vector<byte> SharedMemoryStream<byte>::Ptr::As () const
{
return GetRepConstRef_ ().AsVector ();
}
template <>
template <>
inline vector<Characters::Character> SharedMemoryStream<Characters::Character>::Ptr::As () const
{
return GetRepConstRef_ ().AsVector ();
}
}
#endif /*_Stroika_Foundation_Streams_SharedMemoryStream_inl_*/
| 46.285714 | 223 | 0.536155 | SophistSolutions |
61b8c36017aa8cc5fcde9d64eaa10785fd200957 | 1,468 | hh | C++ | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 122 | 2017-01-06T16:19:31.000Z | 2022-03-08T00:05:50.000Z | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 90 | 2017-01-04T00:23:34.000Z | 2022-02-27T12:55:52.000Z | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 35 | 2017-03-02T13:39:58.000Z | 2022-03-30T17:34:11.000Z | //
// ExpansionHunter
// Copyright (c) 2020 Illumina, Inc.
//
// Author: Konrad Scheffler <[email protected]>
//
// 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.
//
// These utility functions were copied from source code of Strelka Small Variant Caller.
#pragma once
#include <boost/math/special_functions/log1p.hpp>
// returns log(1+x), switches to log1p function when abs(x) is small
static double log1p_switch(const double x)
{
// TODO Justify this switch point. Related discussion:
// http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
static const double smallx_thresh(0.01);
if (std::abs(x) < smallx_thresh)
{
return boost::math::log1p(x);
}
else
{
return std::log(1 + x);
}
}
// Returns the equivalent of log(exp(x1)+exp(x2))
static double getLogSum(double x1, double x2)
{
if (x1 < x2)
std::swap(x1, x2);
return x1 + log1p_switch(std::exp(x2 - x1));
} | 29.959184 | 88 | 0.696185 | bw2 |
61b9074c8ecfb30b5f80214514fc2e3315fae2b0 | 275 | cpp | C++ | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | #include <cassert>
#include <cstdint>
#include <algorithm>
#include <string>
std::string MakeUpperCase(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
int main()
{
assert(MakeUpperCase("hello") == "HELLO");
return 0;
} | 16.176471 | 64 | 0.669091 | GamesTrap |
61be1ed9419420046c10b11190d437708114aa91 | 714 | cpp | C++ | tests/Basic/ConsoleLogger/main.cpp | cash2/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 5 | 2018-12-29T11:47:17.000Z | 2021-04-30T11:40:15.000Z | tests/Basic/ConsoleLogger/main.cpp | aphivantrakul/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 2 | 2019-07-10T15:53:44.000Z | 2021-06-26T17:41:46.000Z | tests/Basic/ConsoleLogger/main.cpp | aphivantrakul/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 10 | 2018-11-25T18:45:50.000Z | 2022-03-21T17:19:42.000Z | // Copyright (c) 2018-2021 The Cash2 developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "gtest/gtest.h"
#include "Logging/ConsoleLogger.h"
using namespace Logging;
// constructor
TEST(ConsoleLogger, 1)
{
ConsoleLogger logger1;
Level level = Level::DEBUGGING;
ConsoleLogger logger2(level);
ConsoleLogger logger3(Level::FATAL);
ConsoleLogger logger4(Level::ERROR);
ConsoleLogger logger5(Level::WARNING);
ConsoleLogger logger6(Level::INFO);
ConsoleLogger logger7(Level::TRACE);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 24.62069 | 71 | 0.747899 | cash2 |
61c258a5695408e8a195255a39381d1ffa2d27eb | 4,066 | hpp | C++ | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 MongoDB Inc.
//
// 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.
#pragma once
#include <string>
#include <vector>
#include <bsoncxx/document/view_or_value.hpp>
#include <bsoncxx/stdx/optional.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/config/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
class client_encryption;
namespace options {
///
/// Class representing options for data key generation for encryption.
///
class MONGOCXX_API data_key {
public:
///
/// Sets a KMS-specific key used to encrypt the new data key.
///
/// If the KMS provider is "aws" the masterKey is required and has the following fields:
///
/// {
/// region: String,
/// key: String, // The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
/// endpoint: Optional<String> // An alternate host identifier to send KMS requests to. May
/// include port number. Defaults to "kms.<region>.amazonaws.com"
/// }
///
/// If the KMS provider is "azure" the masterKey is required and has the following fields:
///
/// {
/// keyVaultEndpoint: String, // Host with optional port. Example: "example.vault.azure.net".
/// keyName: String,
/// keyVersion: Optional<String> // A specific version of the named key, defaults to using
/// the key's primary version.
/// }
///
/// If the KMS provider is "gcp" the masterKey is required and has the following fields:
///
/// {
/// projectId: String,
/// location: String,
/// keyRing: String,
/// keyName: String,
/// keyVersion: Optional<String>, // A specific version of the named key, defaults to using
/// the key's primary version.
/// endpoint: Optional<String> // Host with optional port. Defaults to
/// "cloudkms.googleapis.com".
/// }
///
/// If the KMS provider is "local" the masterKey is not applicable.
///
/// @param master_key
/// The document representing the master key.
///
/// @return
/// A reference to this object.
///
/// @see https://docs.mongodb.com/manual/core/security-client-side-encryption-key-management/
///
data_key& master_key(bsoncxx::document::view_or_value master_key);
///
/// Gets the master key.
///
/// @return
/// An optional document containing the master key.
///
const stdx::optional<bsoncxx::document::view_or_value>& master_key() const;
///
/// Sets an optional list of string alternate names used to reference the key.
/// If a key is created with alternate names, then encryption may refer to the
/// key by the unique alternate name instead of by _id.
///
/// @param key_alt_names
/// The alternate names for the key.
///
/// @return
/// A reference to this object.
///
/// @see https://docs.mongodb.com/manual/reference/method/getClientEncryption/
///
data_key& key_alt_names(std::vector<std::string> key_alt_names);
///
/// Gets the alternate names for the data key.
///
/// @return
/// The alternate names for the data key.
///
const std::vector<std::string>& key_alt_names() const;
private:
friend class mongocxx::client_encryption;
MONGOCXX_PRIVATE void* convert() const;
stdx::optional<bsoncxx::document::view_or_value> _master_key;
std::vector<std::string> _key_alt_names;
};
} // namespace options
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
| 32.015748 | 100 | 0.652484 | lzlzymy |
61c2fc452c05e65d2f31a88f5076353bfb6237a0 | 10,532 | cpp | C++ | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | /*****************************************************************************
export.cpp
Author: Laurent de Soras, 2016
--- 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://sam.zoy.org/wtfpl/COPYING 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 "fstb/Err.h"
#include "mfx/piapi/FactoryTpl.h"
#include "mfx/pi/adsr/EnvAdsr.h"
#include "mfx/pi/adsr/EnvAdsrDesc.h"
#include "mfx/pi/bmp1/BigMuff1.h"
#include "mfx/pi/bmp1/BigMuff1Desc.h"
#include "mfx/pi/click/Click.h"
#include "mfx/pi/click/ClickDesc.h"
#include "mfx/pi/colorme/ColorMe.h"
#include "mfx/pi/colorme/ColorMeDesc.h"
#include "mfx/pi/cpx/Compex.h"
#include "mfx/pi/cpx/CompexDesc.h"
#include "mfx/pi/dclip/DiodeClipper.h"
#include "mfx/pi/dclip/DiodeClipperDesc.h"
#include "mfx/pi/dist1/DistoSimple.h"
#include "mfx/pi/dist1/DistoSimpleDesc.h"
#include "mfx/pi/dist2/Disto2x.h"
#include "mfx/pi/dist2/Disto2xDesc.h"
#include "mfx/pi/dist3/Dist3.h"
#include "mfx/pi/dist3/Dist3Desc.h"
#include "mfx/pi/distapf/DistApf.h"
#include "mfx/pi/distapf/DistApfDesc.h"
#include "mfx/pi/distpwm/DistoPwm.h"
#include "mfx/pi/distpwm/DistoPwmDesc.h"
#include "mfx/pi/distpwm2/DistoPwm2.h"
#include "mfx/pi/distpwm2/DistoPwm2Desc.h"
#include "mfx/pi/dly0/Delay.h"
#include "mfx/pi/dly0/DelayDesc.h"
#include "mfx/pi/dly1/Delay.h"
#include "mfx/pi/dly1/DelayDesc.h"
#include "mfx/pi/dly2/Delay2.h"
#include "mfx/pi/dly2/Delay2Desc.h"
#include "mfx/pi/dtone1/DistTone.h"
#include "mfx/pi/dtone1/DistToneDesc.h"
#include "mfx/pi/dwm/DryWet.h"
#include "mfx/pi/dwm/DryWetDesc.h"
#include "mfx/pi/envf/EnvFollow.h"
#include "mfx/pi/envf/EnvFollowDesc.h"
#include "mfx/pi/freqsh/FrequencyShifter.h"
#include "mfx/pi/freqsh/FreqShiftDesc.h"
#include "mfx/pi/flancho/Flancho.h"
#include "mfx/pi/flancho/FlanchoDesc.h"
#include "mfx/pi/fsplit/FreqSplit.h"
#include "mfx/pi/fsplit/FreqSplitDesc.h"
#include "mfx/pi/fv/Freeverb.h"
#include "mfx/pi/fv/FreeverbDesc.h"
#include "mfx/pi/hcomb/HyperComb.h"
#include "mfx/pi/hcomb/HyperCombDesc.h"
#include "mfx/pi/iifix/IIFix.h"
#include "mfx/pi/iifix/IIFixDesc.h"
#include "mfx/pi/lfo1/Lfo.h"
#include "mfx/pi/lfo1/LfoDesc.h"
#include "mfx/pi/lpfs/Squeezer.h"
#include "mfx/pi/lpfs/SqueezerDesc.h"
#include "mfx/pi/moog1/MoogLpf.h"
#include "mfx/pi/moog1/MoogLpfDesc.h"
#include "mfx/pi/nzbl/NoiseBleach.h"
#include "mfx/pi/nzbl/NoiseBleachDesc.h"
#include "mfx/pi/nzcl/NoiseChlorine.h"
#include "mfx/pi/nzcl/NoiseChlorineDesc.h"
#include "mfx/pi/osdet/OnsetDetect.h"
#include "mfx/pi/osdet/OnsetDetectDesc.h"
//#include "mfx/pi/osdet2/OnsetDetect2.h"
//#include "mfx/pi/osdet2/OnsetDetect2Desc.h"
#include "mfx/pi/peq/PEq.h"
#include "mfx/pi/peq/PEqDesc.h"
#include "mfx/pi/phase1/Phaser.h"
#include "mfx/pi/phase1/PhaserDesc.h"
#include "mfx/pi/phase2/Phaser2.h"
#include "mfx/pi/phase2/Phaser2Desc.h"
#include "mfx/pi/pidet/PitchDetect.h"
#include "mfx/pi/pidet/PitchDetectDesc.h"
#include "mfx/pi/psh1/PitchShift1.h"
#include "mfx/pi/psh1/PitchShift1Desc.h"
#include "mfx/pi/ramp/Ramp.h"
#include "mfx/pi/ramp/RampDesc.h"
#include "mfx/pi/smood/SkoolMood.h"
#include "mfx/pi/smood/SkoolMoodDesc.h"
#include "mfx/pi/syn0/Synth0.h"
#include "mfx/pi/syn0/Synth0Desc.h"
#include "mfx/pi/spkem/SpeakerEmu.h"
#include "mfx/pi/spkem/SpeakerEmuDesc.h"
#include "mfx/pi/testgen/TestGen.h"
#include "mfx/pi/testgen/TestGenDesc.h"
#include "mfx/pi/tost/ToStereo.h"
#include "mfx/pi/tost/ToStereoDesc.h"
#include "mfx/pi/trem1/Tremolo.h"
#include "mfx/pi/trem1/TremoloDesc.h"
#include "mfx/pi/tremh/HarmTrem.h"
#include "mfx/pi/tremh/HarmTremDesc.h"
#include "mfx/pi/tuner/Tuner.h"
#include "mfx/pi/tuner/TunerDesc.h"
#include "mfx/pi/wah1/Wah.h"
#include "mfx/pi/wah1/WahDesc.h"
#include "mfx/pi/wah2/Wah2.h"
#include "mfx/pi/wah2/Wah2Desc.h"
#include "mfx/pi/export.h"
#include <cassert>
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
fstb_EXPORT (int fstb_CDECL enum_factories (std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > &fact_list))
{
int ret_val = fstb::Err_OK;
try
{
static const std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > l =
{
mfx::piapi::FactoryTpl <mfx::pi::dwm::DryWetDesc , mfx::pi::dwm::DryWet >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tuner::TunerDesc , mfx::pi::tuner::Tuner >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist1::DistoSimpleDesc , mfx::pi::dist1::DistoSimple >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::freqsh::FreqShiftDesc , mfx::pi::freqsh::FrequencyShifter >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::trem1::TremoloDesc , mfx::pi::trem1::Tremolo >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::wah1::WahDesc , mfx::pi::wah1::Wah >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dtone1::DistToneDesc , mfx::pi::dtone1::DistTone >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::iifix::IIFixDesc , mfx::pi::iifix::IIFix >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::flancho::FlanchoDesc , mfx::pi::flancho::Flancho >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly1::DelayDesc , mfx::pi::dly1::Delay >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::cpx::CompexDesc , mfx::pi::cpx::Compex >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::fv::FreeverbDesc , mfx::pi::fv::Freeverb >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 4> , mfx::pi::peq::PEq < 4> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 8> , mfx::pi::peq::PEq < 8> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc <16> , mfx::pi::peq::PEq <16> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::phase1::PhaserDesc , mfx::pi::phase1::Phaser >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lpfs::SqueezerDesc , mfx::pi::lpfs::Squeezer >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <false> , mfx::pi::lfo1::Lfo <false> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::envf::EnvFollowDesc , mfx::pi::envf::EnvFollow >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist2::Disto2xDesc , mfx::pi::dist2::Disto2x >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::spkem::SpeakerEmuDesc , mfx::pi::spkem::SpeakerEmu >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tost::ToStereoDesc , mfx::pi::tost::ToStereo >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::distpwm::DistoPwmDesc , mfx::pi::distpwm::DistoPwm >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tremh::HarmTremDesc , mfx::pi::tremh::HarmTrem >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::nzbl::NoiseBleachDesc , mfx::pi::nzbl::NoiseBleach >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::nzcl::NoiseChlorineDesc , mfx::pi::nzcl::NoiseChlorine >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::click::ClickDesc , mfx::pi::click::Click >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::wah2::Wah2Desc , mfx::pi::wah2::Wah2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::ramp::RampDesc , mfx::pi::ramp::Ramp >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly2::Delay2Desc , mfx::pi::dly2::Delay2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::colorme::ColorMeDesc , mfx::pi::colorme::ColorMe >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::phase2::Phaser2Desc , mfx::pi::phase2::Phaser2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::pidet::PitchDetectDesc , mfx::pi::pidet::PitchDetect >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::osdet::OnsetDetectDesc , mfx::pi::osdet::OnsetDetect >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::syn0::Synth0Desc , mfx::pi::syn0::Synth0 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::hcomb::HyperCombDesc , mfx::pi::hcomb::HyperComb >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::testgen::TestGenDesc , mfx::pi::testgen::TestGen >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::psh1::PitchShift1Desc , mfx::pi::psh1::PitchShift1 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::distpwm2::DistoPwm2Desc , mfx::pi::distpwm2::DistoPwm2 >::create ()
// , mfx::piapi::FactoryTpl <mfx::pi::osdet2::OnsetDetect2Desc, mfx::pi::osdet2::OnsetDetect2 >::create () // Does not work well enough
, mfx::piapi::FactoryTpl <mfx::pi::distapf::DistApfDesc , mfx::pi::distapf::DistApf >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <true> , mfx::pi::lfo1::Lfo <true> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::adsr::EnvAdsrDesc , mfx::pi::adsr::EnvAdsr >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly0::DelayDesc , mfx::pi::dly0::Delay >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::fsplit::FreqSplitDesc , mfx::pi::fsplit::FreqSplit >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist3::Dist3Desc , mfx::pi::dist3::Dist3 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::moog1::MoogLpfDesc , mfx::pi::moog1::MoogLpf >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dclip::DiodeClipperDesc , mfx::pi::dclip::DiodeClipper >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::smood::SkoolMoodDesc , mfx::pi::smood::SkoolMood >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::bmp1::BigMuff1Desc , mfx::pi::bmp1::BigMuff1 >::create ()
};
fact_list = l;
}
catch (...)
{
assert (false);
ret_val = fstb::Err_EXCEPTION;
fact_list.clear ();
}
return ret_val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 48.759259 | 140 | 0.613749 | mikelange49 |
61c35abcbffe63b9b7b3707595211d052b775b1d | 7,894 | cpp | C++ | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | // +-------------------------------------------------------------------------
// | Copyright (C) 2017 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 <yaml/yaml.h>
#include <plog/Log.h>
#include "QsConfig.h"
#include "StringUtils.h"
#include <map>
namespace QingStor
{
static const char *CONFIG_KEY_ACCESS_KEY_ID = "access_key_id";
static const char *CONFIG_KEY_SECRET_ACCESS_KEY = "secret_access_key";
static const char *CONFIG_KEY_HOST = "host";
static const char *CONFIG_KEY_PORT = "port";
static const char *CONFIG_KEY_PROTOCOL = "protocol";
static const char *CONFIG_KEY_CONNECTION_RETRIES = "connection_retries";
static const char *CONFIG_KEY_ADDITIONAL_USER_AGENT = "additional_user_agent";
static const char *CONFIG_KEY_TIMEOUT_PERIOD = "timeOutPeriod";
// Default value
static const char *DEFAULT_HOST = "qingstor.com";
static const char *DEFAULT_PROTOCOL = "https";
static const char *DEFAULT_ADDITIONAL_USER_AGENT = "";
static int DEFAULT_RETRIES = 3;
static int DEFAULT_PORT = 443;
static int DEFAULT_TIMEOUT_PERIOD = 3;
QsConfig::QsConfig(const std::string & access_key_id, const std::string & secret_access_key)
: additionalUserAgent(DEFAULT_ADDITIONAL_USER_AGENT),
accessKeyId(access_key_id),secretAccessKey(secret_access_key),
host(DEFAULT_HOST),protocol(DEFAULT_PROTOCOL),
port(DEFAULT_PORT),connectionRetries(DEFAULT_RETRIES),
timeOutPeriod(DEFAULT_TIMEOUT_PERIOD)
{
}
QsError QsConfig::LoadConfigFile(const std::string &config_file)
{
FILE *fh = NULL;
yaml_parser_t parser;
yaml_token_t token;
std::map<std::string, std::string> kvs;
std::string token_key;
std::string token_value;
bool reach_key = false;
bool reach_value = false;
/* Initialize parser */
if (!yaml_parser_initialize(&parser))
{
LOG_FATAL << "couldn't initialize yaml parser";
}
/* Open configuration file */
if ((fh = fopen(config_file.c_str(), "rb")) == NULL)
{
yaml_parser_delete(&parser);
LOG_FATAL << "couldn't open configure file " << config_file.c_str();
}
/* Set input file */
yaml_parser_set_input_file(&parser, fh);
do
{
yaml_parser_scan(&parser, &token);
switch (token.type)
{
case YAML_STREAM_START_TOKEN:
case YAML_STREAM_END_TOKEN:
case YAML_BLOCK_SEQUENCE_START_TOKEN:
case YAML_BLOCK_ENTRY_TOKEN:
case YAML_BLOCK_END_TOKEN:
case YAML_BLOCK_MAPPING_START_TOKEN:
break;
case YAML_KEY_TOKEN:
{
reach_key = true;
}
break;
case YAML_VALUE_TOKEN:
{
reach_value = true;
}
break;
case YAML_SCALAR_TOKEN:
{
bool config_invalid = false;
if (reach_key)
{
token_key = std::string((const char *)(token.data.scalar.value));
reach_key = false;
break;
}
else if (reach_value)
{
token_value = std::string((const char *)(token.data.scalar.value));
reach_value = false;
if (token_key.empty() || token_value.empty())
{
config_invalid = true;
}
}
else
{
config_invalid = true;
}
if (config_invalid)
{
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
LOG_FATAL << "YAML configuration is invalid";
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
kvs.insert(std::pair<std::string, std::string>(token_key, token_value));
token_key.clear();
token_value.clear();
}
}
break;
default:
{
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
LOG_FATAL << "YAML configuration is invalid with token type" << token.type;
return QS_ERR_INVAILD_CONFIG_FILE;
}
break;
}
if (token.type != YAML_STREAM_END_TOKEN)
{
yaml_token_delete(&token);
}
}
while (token.type != YAML_STREAM_END_TOKEN);
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
/* Go through the interested configurations */
if (kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)].empty())
{
LOG_FATAL << "YAML configuration is invalid with token type" << token.type;
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
accessKeyId = kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)];
}
if (kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)].empty())
{
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
secretAccessKey = kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)];
}
if (kvs[std::string(CONFIG_KEY_HOST)].empty())
{
host = DEFAULT_HOST;
}
else
{
host = kvs[std::string(CONFIG_KEY_HOST)];
}
if (kvs[std::string(CONFIG_KEY_PORT)].empty())
{
port = DEFAULT_PORT;
}
else
{
std::string port_str = kvs[std::string(CONFIG_KEY_PORT)];
int tmp_prot = atoi(port_str.c_str());
if (tmp_prot <= 0 || tmp_prot > 65535)
{
LOG_WARNING << "Configuration Port" << port_str.c_str() << "is invalid, using default vaule:" << DEFAULT_PORT;
tmp_prot = DEFAULT_PORT;
}
port = tmp_prot;
}
if (kvs[std::string(CONFIG_KEY_PROTOCOL)].empty())
{
protocol = DEFAULT_PROTOCOL;
}
else
{
protocol = kvs[std::string(CONFIG_KEY_PROTOCOL)];
}
if (kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)].empty())
{
connectionRetries = 3;
}
else
{
std::string retries_str = kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)];
int retries = atoi(retries_str.c_str());
if (retries <= 0 || retries > 16)
{
LOG_WARNING << "Configuration connection retries" << retries_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES;
retries = DEFAULT_RETRIES;
}
connectionRetries = retries;
}
if (kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)].empty())
{
timeOutPeriod = 3;
}
else
{
std::string timeOutPeriod_str = kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)];
int timeOut = atoi(timeOutPeriod_str.c_str());
if (connectionRetries <= 0)
{
LOG_WARNING << "Configuration connection retries" << timeOutPeriod_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES;
timeOutPeriod = DEFAULT_TIMEOUT_PERIOD;
}
timeOutPeriod = timeOut;
}
if (kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)].empty())
{
additionalUserAgent = "";
}
else
{
additionalUserAgent = kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)];
}
return QS_ERR_NO_ERROR;
}
}
| 30.715953 | 149 | 0.589308 | li-lili |
61c4dca75fa183567326eb278e80d3571bf396ab | 2,358 | hpp | C++ | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | #pragma once
#include <hitagi/ecs/world.hpp>
#include <hitagi/utils/concepts.hpp>
#include <memory_resource>
#include <typeindex>
#include <vector>
#include <functional>
namespace hitagi::ecs {
class Schedule {
struct ITask {
virtual void Run(World&) = 0;
};
template <typename Func>
struct Task : public ITask {
Task(std::string_view name, Func&& task)
: task_name(name), task(std::move(task)) {}
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
Task(Task&&) noexcept = default;
Task& operator=(Task&&) noexcept = default;
void Run(World& world) final;
std::pmr::string task_name;
Func task;
};
public:
Schedule(World& world) : m_World(world) {}
// Do task on the entities that contains components indicated at parameters.
template <typename Func>
requires utils::unique_parameter_types<Func>
Schedule& Register(std::string_view name, Func&& task);
void Run() {
for (auto&& task : m_Tasks) {
task->Run(m_World);
}
}
private:
World& m_World;
std::pmr::vector<std::shared_ptr<ITask>> m_Tasks;
};
template <typename Func>
requires utils::unique_parameter_types<Func>
Schedule& Schedule::Register(std::string_view name, Func&& task) {
std::shared_ptr<ITask> task_info = std::make_shared<Task<Func>>(name, std::forward<Func>(task));
m_Tasks.emplace_back(std::move(task_info));
return *this;
}
template <typename Func>
void Schedule::Task<Func>::Run(World& world) {
[&]<std::size_t... I>(std::index_sequence<I...>) {
using traits = utils::function_traits<Func>;
for (const std::shared_ptr<IArchetype>& archetype : world.GetArchetypes<typename traits::template arg<I>::type...>()) {
auto num_entities = archetype->NumEntities();
auto components_array = std::make_tuple(archetype->GetComponentArray<typename traits::template arg<I>::type>()...);
for (std::size_t index = 0; index < num_entities; index++) {
task(std::get<I>(components_array)[index]...);
}
};
}
(std::make_index_sequence<utils::function_traits<Func>::args_size>{});
}
} // namespace hitagi::ecs | 29.848101 | 127 | 0.608991 | L-Sun |
61c68a6f6b29b393cb18a9650126ea67b6df83bd | 7,055 | cpp | C++ | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER 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.
\**************************************************************************/
/*!
\class SoTexture3Transform SoTexture3Transform.h Inventor/nodes/SoTexture3Transform.h
\brief The SoTexture3Transform class is used to define 3D texture transformations.
\ingroup nodes
Textures applied to shapes in the scene can be transformed by
"prefixing" in the state with instances of this node
type. Translations, rotations and scaling in 3D can all be done.
The default settings of this node's fields equals a "null
transform", ie no transformation.
\COIN_CLASS_EXTENSION
<b>FILE FORMAT/DEFAULTS:</b>
\code
Texture3Transform {
translation 0 0 0
rotation 0 0 1 0
scaleFactor 1 1 1
scaleOrientation 0 0 1 0
center 0 0 0
}
\endcode
\sa SoTexture2Transform
\since Coin 2.0
\since TGS Inventor 2.6
*/
// *************************************************************************
#include <Inventor/nodes/SoTexture3Transform.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoPickAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/elements/SoGLMultiTextureMatrixElement.h>
#include <Inventor/elements/SoTextureUnitElement.h>
#include <Inventor/elements/SoGLCacheContextElement.h>
#include <Inventor/C/glue/gl.h>
#include "nodes/SoSubNodeP.h"
// *************************************************************************
/*!
\var SoSFVec3f SoTexture3Transform::translation
Texture coordinate translation. Default value is [0, 0, 0].
*/
/*!
\var SoSFRotation SoTexture3Transform::rotation
Texture coordinate rotation (s is x-axis, t is y-axis and r is
z-axis). Defaults to an identity rotation (ie zero rotation).
*/
/*!
\var SoSFVec3f SoTexture3Transform::scaleFactor
Texture coordinate scale factors. Default value is [1, 1, 1].
*/
/*!
\var SoSFRotation SoTexture3Transform::scaleOrientation
The orientation the texture is set to before scaling. Defaults to
an identity rotation (ie zero rotation).
*/
/*!
\var SoSFVec3f SoTexture3Transform::center
Center for scale and rotation. Default value is [0, 0, 0].
*/
// *************************************************************************
SO_NODE_SOURCE(SoTexture3Transform);
/*!
Constructor.
*/
SoTexture3Transform::SoTexture3Transform(void)
{
SO_NODE_INTERNAL_CONSTRUCTOR(SoTexture3Transform);
SO_NODE_ADD_FIELD(translation, (0.0f, 0.0f, 0.0f));
SO_NODE_ADD_FIELD(rotation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f)));
SO_NODE_ADD_FIELD(scaleFactor, (1.0f, 1.0f, 1.0f));
SO_NODE_ADD_FIELD(scaleOrientation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f)));
SO_NODE_ADD_FIELD(center, (0.0f, 0.0f, 0.0f));
}
/*!
Destructor.
*/
SoTexture3Transform::~SoTexture3Transform()
{
}
// Documented in superclass.
void
SoTexture3Transform::initClass(void)
{
SO_NODE_INTERNAL_INIT_CLASS(SoTexture3Transform, SO_FROM_INVENTOR_1);
SO_ENABLE(SoGLRenderAction, SoGLMultiTextureMatrixElement);
SO_ENABLE(SoCallbackAction, SoMultiTextureMatrixElement);
SO_ENABLE(SoPickAction, SoMultiTextureMatrixElement);
}
// Documented in superclass.
void
SoTexture3Transform::GLRender(SoGLRenderAction * action)
{
SoState * state = action->getState();
int unit = SoTextureUnitElement::get(state);
const cc_glglue * glue =
cc_glglue_instance(SoGLCacheContextElement::get(state));
int maxunits = cc_glglue_max_texture_units(glue);
if (unit < maxunits) {
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
SoMultiTextureMatrixElement::mult(state, this, unit, mat);
}
else {
// we already warned in SoTextureUnit. I think it's best to just
// ignore the texture here so that all textures for non-supported
// units will be ignored. pederb, 2003-11-11
}
}
// Documented in superclass.
void
SoTexture3Transform::doAction(SoAction *action)
{
SoState * state = action->getState();
int unit = SoTextureUnitElement::get(state);
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
SoMultiTextureMatrixElement::mult(action->getState(), this, unit, mat);
}
// Documented in superclass.
void
SoTexture3Transform::callback(SoCallbackAction *action)
{
SoTexture3Transform::doAction(action);
}
// Documented in superclass.
void
SoTexture3Transform::getMatrix(SoGetMatrixAction * action)
{
int unit = SoTextureUnitElement::get(action->getState());
if (unit == 0) {
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
action->getTextureMatrix().multLeft(mat);
action->getTextureInverse().multRight(mat.inverse());
}
}
// Documented in superclass.
void
SoTexture3Transform::pick(SoPickAction * action)
{
SoTexture3Transform::doAction(action);
}
| 32.511521 | 87 | 0.684054 | pniaz20 |
61cb646052d8bf082a49814e04b57dfd0c0c6672 | 603 | cpp | C++ | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | 1 | 2021-08-30T20:33:43.000Z | 2021-08-30T20:33:43.000Z | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | null | null | null | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | null | null | null | #include "Papyrus/ExtendedObjectTypes.h"
auto extendedObjectTypes::RegisterTypes(VM* a_vm) -> bool
{
if (!a_vm) {
logger::critical("Object types - couldn't get VMState"sv);
return false;
}
a_vm->RegisterObjectType(vm_cast<RE::BGSFootstepSet>(), "FootstepSet");
logger::info("Registered footstep set object type"sv);
a_vm->RegisterObjectType(vm_cast<RE::BGSLightingTemplate>(), "LightingTemplate");
logger::info("Registered lighting template object type"sv);
a_vm->RegisterObjectType(vm_cast<RE::BGSDebris>(), "Debris");
logger::info("Registered debris object type"sv);
return true;
}
| 27.409091 | 82 | 0.742952 | fireundubh |
61cc0d987e8dea83ee8fb068e28b4a4f1fda37af | 933 | cpp | C++ | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | 2 | 2018-06-26T09:52:14.000Z | 2018-07-12T15:02:01.000Z | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
map<int, int> m;
int n,k;
scanf("%d%d", &n, &k);
vector<int> a(n);
vector<int> b(n);
for(int i = 0; i<n; i++){
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b.rbegin(), b.rend());
for(int i = 0; i<k; i++)
if(m.find(b[i]) == m.end())
m[b[i]] = 1;
else
m[b[i]] += 1;
int sz = 0;
vector<int> ans;
for(int i = 0; i<n; i++){
sz++;
if(m.find(a[i]) != m.end() && m[a[i]] > 0)
{
ans.push_back(sz);
sz = 0;
m[a[i]] -= 1;
}
if(ans.size() == k-1)
break;
}
sz = 0;
for(int i = 0; i<k; i++)
sz += b[i];
printf("%d\n", sz);
sz = 0;
for(int i = 0; i < (k-1); i++){
printf("%d ", ans[i]);
sz += ans[i];
}
printf("%d\n", n-sz);
return 0;
}
| 15.048387 | 49 | 0.347267 | sidgairo18 |
61cc3f6fe9d8448581fa7c53b86a37faaf36c236 | 1,330 | cpp | C++ | WaveletTL/Rd/regularity.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | WaveletTL/Rd/regularity.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | WaveletTL/Rd/regularity.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for regularity.h
#include <algebra/vector.h>
#include <algebra/matrix.h>
#include <numerics/eigenvalues.h>
using namespace MathTL;
namespace WaveletTL
{
template <class MASK>
AutocorrelationMask<MASK>::AutocorrelationMask()
{
MASK a;
// b(k) = \sum_m a(k+m)*a(m)/2
const int k1 = a.begin().index()[0];
const int k2 = a.rbegin().index()[0];
for (int k = k1-k2; k <= k2-k1; k++)
for (int m = k1; m <= k2; m++)
if (m+k >= k1 && m+k <= k2)
set_coefficient(MultiIndex<int,1>(k),
get_coefficient(MultiIndex<int,1>(k))
+ a.get_coefficient(MultiIndex<int,1>(m))
* a.get_coefficient(MultiIndex<int,1>(m+k))/2.0);
}
template <class MASK>
double
Sobolev_regularity()
{
double r = 0;
// setup the autocorrelation mask according to the given mask
AutocorrelationMask<MASK> b;
// cout << "* the autocorrelation mask of a=" << MASK() << " is " << b << endl;
// setup A=(b_{2i-j})_{i,j\in\Omega}
const int N = b.rbegin().index()[0]; // offset for A
Matrix<double> A(2*N+1, 2*N+1);
for (int i = -N; i <= N; i++)
for (int j = -N; j <= N; j++)
A(N+i, N+j) = b.get_coefficient(MultiIndex<int,1>(2*i-j));
cout << "A=" << endl << A << endl;
// TODO: solve nonsymmetric eigenvalue problem here!
return r;
}
}
| 25.576923 | 83 | 0.586466 | kedingagnumerikunimarburg |
61cc8219de8035df8fdc8782a75bf9ced1f8f25e | 366 | cpp | C++ | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | //Questão: Salario com Bonus
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string NOME;
float SALARIO, TOTALV, TOTAL;
cin >> NOME;
cout << fixed << setprecision(2);
cin >> SALARIO >> TOTALV;
cout << fixed << setprecision(2);
cout << "TOTAL = R$ "<<((TOTALV*15)/100) + SALARIO <<endl;
return 0;
} | 20.333333 | 61 | 0.620219 | CrystianPrintes20 |
61d7917ccdb0209ed5dad36a7111e39482e93646 | 903 | hpp | C++ | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | 3 | 2018-01-13T13:18:42.000Z | 2022-02-24T01:30:55.000Z | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | null | null | null | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | null | null | null | #pragma once
#include "App.hpp"
#include "RisingEdgeButton.h"
#include "SmartCard.h"
#include <LiquidCrystal_I2C.h>
#include <stdint.h>
#include <WString.h>
class PlayerCardCreator : public App
{
public:
PlayerCardCreator();
void init();
void run();
private:
LiquidCrystal_I2C lcd;
RisingEdgeButton charUpButton;
RisingEdgeButton charDownButton;
RisingEdgeButton walkLeftButton;
RisingEdgeButton walkRightButton;
RisingEdgeButton writeButton;
uint8_t rfidKey[MFRC522::MF_KEY_SIZE];
SmartCard smartCard;
String playerName;
uint8_t charIndexUnderCursor;
char *statusLine;
void setupLCD();
void showControlHints();
void showName();
bool executeNameChanges();
void resetName();
bool writeNameToCard();
void clearLine(const int number);
char nextChar(const char current);
char prevChar(const char current);
};
| 21.5 | 42 | 0.717608 | eduardoweiland |
61dfe6113b40ebe81dcd9be9532a0a5149d7ac15 | 745 | tpp | C++ | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 125 | 2015-07-22T11:39:51.000Z | 2022-03-06T13:41:44.000Z | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 45 | 2015-06-03T15:50:08.000Z | 2021-05-26T01:35:01.000Z | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 28 | 2015-06-03T09:26:26.000Z | 2022-03-06T13:42:06.000Z | /* -*- C++ -*- ------------------------------------------------------------
@@COPYRIGHT@@
*-----------------------------------------------------------------------*/
/** @file
*/
#ifndef __CML_VECTOR_SUBVECTOR_OPS_TPP
#error "vector/subvector_ops.tpp not included correctly"
#endif
namespace cml {
template<class Sub> inline auto
subvector(const readable_vector<Sub>& sub, int i)
-> subvector_node<const Sub&>
{
return subvector_node<const Sub&>(sub.actual(), i);
}
template<class Sub> inline auto
subvector(readable_vector<Sub>&& sub, int i)
-> subvector_node<Sub&&>
{
return subvector_node<Sub&&>((Sub&&) sub, i);
}
} // namespace cml
// -------------------------------------------------------------------------
// vim:ft=cpp:sw=2
| 24.032258 | 76 | 0.495302 | egorodet |
61e1c1b3b736b3c6fce106e044aeabd67a4139f0 | 4,112 | cpp | C++ | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | 2 | 2016-09-20T06:01:03.000Z | 2020-12-03T23:22:19.000Z | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | null | null | null | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iterator>
#include <iostream>
#include "mesh.h"
#include "geometry/isect_util.h"
using std::copy;
using std::ostream_iterator;
using std::cerr;
MeshTri::MeshTri(const Mesh* m, int f, const uint v[3]) :
mesh(m), ti(f)
{
copy(v, v+3, vi);
}
scalar_fp ray_triangle_intersection_accel(const Ray& ray, scalar_fp max_t, const MeshTriAccel& accel)
{
auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3;
auto denom = (ray.direction[u] * accel.nu + ray.direction[v] * accel.nv + ray.direction[accel.k]);
if (fabs(denom) < 0.0001)
return sfp_none;
auto num = accel.nd - ray.position[u] * accel.nu - ray.position[v] * accel.nv - ray.position[accel.k];
scalar t = num / denom;
if (t < EPSILON)
return sfp_none;
scalar_fp t_prop(t);
if (max_t < t_prop)
return sfp_none;
scalar hu = ray.position[u] + ray.direction[u] * t;
scalar hv = ray.position[v] + ray.direction[v] * t;
scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d;
if (beta < 0)
return sfp_none;
scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d;
if (gamma < 0)
return sfp_none;
scalar alpha = 1 - beta - gamma;
if (alpha < 0 || alpha > 1)
return sfp_none;
return t_prop;
}
scalar_fp MeshTri::intersect(const Ray& ray, scalar_fp max_t, SubGeo& geo) const
{
return ray_triangle_intersection_accel(ray, max_t, mesh->accel(ti));
}
Vec3 MeshTri::normal(const Vec3& point) const
{
return (_p(1) - _p(0)).cross(_p(2) - _p(0)).normal();
}
bounds::AABB MeshTri::get_bounding_box() const
{
return bounds::AABB(min(min(_p(0), _p(1)), _p(2)),
max(max(_p(0), _p(1)), _p(2)));
}
void MeshTri::texture_coord(const Vec3& pos, const Vec3& normal,
scalar& uv_u, scalar& uv_v) const
{
const auto& accel = mesh->accel(ti);
auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3;
scalar hu = pos[u];
scalar hv = pos[v];
scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d;
scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d;
scalar alpha = 1 - beta - gamma;
auto uv = mesh->uv(vi[0]) * alpha + mesh->uv(vi[1]) * gamma + mesh->uv(vi[2]) * beta;
uv_u = uv[0];
uv_v = uv[1];
}
////////////////////////////////////////////////////////////////////////////////
bounds::AABB Mesh::get_bounding_box() const
{
auto bb = bounds::AABB{Vec3::zero, Vec3::zero};
return accumulate(tris.begin(), tris.end(), bb,
[](const auto& bb, const auto& tri)
{
return bounds::AABB::box_union(bb, tri.get_bounding_box());
});
}
scalar_fp Mesh::intersect(const Ray& r, scalar_fp max_t, SubGeo& subgeo) const
{
scalar_fp best_t = max_t;
for (auto i = 0u; i < tris.size(); ++i)
{
auto& tri = tris[i];
auto t = tri.intersect(r, best_t, subgeo);
if (t < best_t)
{
best_t = t;
subgeo = i;
}
}
return best_t;
}
Vec3 Mesh::normal(SubGeo subgeo, const Vec3& point) const
{
return tris[subgeo].normal(point);
}
void Mesh::texture_coord(SubGeo subgeo, const Vec3& pos, const Vec3& normal,
scalar& u, scalar& v) const
{
return tris[subgeo].texture_coord(pos, normal, u, v);
}
////////////////////////////////////////////////////////////////////////////////
MeshTriAccel::MeshTriAccel(const Vec3& p0, const Vec3& p1, const Vec3& p2)
{
const auto b = p1 - p0;
const auto c = p2 - p0;
const auto N = b.cross(c);
const auto aN = N.abs();
if (aN.x >= aN.y && aN.x >= aN.z)
this->k = 0;
else if (aN.y >= aN.x && aN.y >= aN.z)
this->k = 1;
else
this->k = 2;
int k = this->k;
int u = (this->k + 1) % 3, v = (this->k + 2) % 3;
this->nu = N[u] / N[k];
this->nv = N[v] / N[k];
this->nd = p0.dot(N) / N[k];
scalar inv_area = 1.0 / (b[u] * c[v] - b[v] * c[u]);
this->b_nu = -b[v] * inv_area;
this->b_nv = b[u] * inv_area;
this->b_d = (b[v] * p0[u] - b[u] * p0[v]) * inv_area;
this->c_nu = c[v] * inv_area;
this->c_nv = -c[u] * inv_area;
this->c_d = (c[u] * p0[v] - c[v] * p0[u]) * inv_area;
}
| 26.191083 | 104 | 0.558366 | masonium |
61e4b83cba47ce5809ebef70d0ee6f8febe7a39d | 4,989 | cc | C++ | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | /*
* param_array.cc
*
* Created on: Jan 14, 2014
* Author: nsoblath
*/
#define PARAM_API_EXPORTS
#include <sstream>
using std::string;
using std::stringstream;
#include "param_array.hh"
#include "param_base_impl.hh"
#include "param_node.hh"
namespace param
{
param_array::param_array() :
param(),
f_contents()
{
}
param_array::param_array( const param_array& orig ) :
param( orig ),
f_contents( orig.f_contents.size() )
{
for( unsigned ind = 0; ind < f_contents.size(); ++ind )
{
f_contents[ind] = orig.f_contents[ ind ]->clone();
}
}
param_array::param_array( param_array&& orig ) :
param( std::move(orig) ),
f_contents( orig.f_contents.size() )
{
for( unsigned ind = 0; ind < f_contents.size(); ++ind )
{
f_contents[ind] = orig.f_contents[ ind ]->move_clone();
}
orig.clear();
}
param_array::~param_array()
{
}
param_array& param_array::operator=( const param_array& rhs )
{
this->param::operator=( rhs );
clear();
resize( rhs.size()) ;
for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind )
{
f_contents[ind] = rhs.f_contents[ ind ]->clone();
}
return *this;
}
param_array& param_array::operator=( param_array&& rhs )
{
this->param::operator=( std::move(rhs) );
clear();
resize( rhs.size()) ;
for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind )
{
f_contents[ind] = rhs.f_contents[ ind ]->move_clone();
}
rhs.clear();
return *this;
}
void param_array::resize( unsigned a_size )
{
f_contents.resize( a_size );
for( auto it = f_contents.begin(); it != f_contents.end(); ++it )
{
if( ! *it ) it->reset( new param() );
}
return;
}
bool param_array::has_subset( const param& a_subset ) const
{
if( ! a_subset.is_array() ) return false;
const param_array& t_subset_array = a_subset.as_array();
if( t_subset_array.size() > f_contents.size() ) return false;
contents::const_iterator t_this_it = f_contents.begin();
contents::const_iterator t_that_it = t_subset_array.f_contents.begin();
while( t_that_it != t_subset_array.f_contents.end() ) // loop condition is on a_subset because it's smaller or equal to this
{
if( ! (*t_this_it)->has_subset( **t_that_it ) ) return false;
++t_this_it;
++t_that_it;
}
return true;
}
void param_array::merge( const param_array& a_object )
{
//LDEBUG( dlog, "merging array with " << a_object.size() << " items:\n" << a_object );
if( size() < a_object.size() ) resize( a_object.size() );
for( unsigned index = 0; index < size(); ++index )
{
if( f_contents.at( index )->is_null() )
{
//LDEBUG( dlog, "have a null object at <" << index << ">; adding <" << a_object[index] << ">" );
assign( index, a_object[index] );
continue;
}
param& t_param = (*this)[index];
if( t_param.is_value() && a_object[index].is_value() )
{
//LDEBUG( dlog, "replacing the value at <" << index << "> with <" << a_object[index] << ">" );
t_param.as_value() = a_object[index].as_value();
continue;
}
if( t_param.is_node() && a_object[index].is_node() )
{
//LDEBUG( dlog, "merging nodes at <" << index << ">" )
t_param.as_node().merge( a_object[index].as_node() );
continue;
}
if( t_param.is_array() && a_object[index].is_array() )
{
//LDEBUG( dlog, "merging array at <" << index << ">" );
t_param.as_array().merge( a_object[index].as_array() );
continue;
}
//LDEBUG( dlog, "generic replace" );
assign( index, a_object[index] );
}
return;
}
std::string param_array::to_string() const
{
stringstream out;
string indentation;
for ( unsigned i=0; i<param::s_indent_level; ++i )
indentation += " ";
out << '\n' << indentation << "[\n";
param::s_indent_level++;
for( contents::const_iterator it = f_contents.begin(); it != f_contents.end(); ++it )
{
out << indentation << " " << **it << '\n';
}
param::s_indent_level--;
out << indentation << "]\n";
return out.str();
}
PARAM_API std::ostream& operator<<(std::ostream& out, const param_array& a_value)
{
return out << a_value.to_string();
}
} /* namespace param */
| 29.347059 | 132 | 0.512928 | nsoblath |
61e7823fd086418ee4a9902a56b2d99a1e676e02 | 17,317 | cpp | C++ | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | 3 | 2021-03-15T12:57:32.000Z | 2021-03-15T15:34:07.000Z | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | null | null | null | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | 1 | 2021-03-15T13:36:21.000Z | 2021-03-15T13:36:21.000Z | #include "main.hpp"
//$(sej$(aaa){AAA}$(bajs$(moa){kmkd}){tej$(haha){kmkm}}){kukens fitta}
//$(bajskmkd){tej$(haha){kmkd}}
//template <bool DO_LOUD = true>
struct Process
{
vector <pair <string, string>> declaredVariables;
Context declVar;
// Context pasteVar;
// comment::Context commentVal;
// string str;
Process () : declVar {nullptr, declaredVariables, new STATE ("begin")}
{
// declVar.state -> context = &declVar;
// pasteVar.state -> context = &pasteVar;
// commentVal.state -> context = &commentVal;
}
string process (string str)
{
// cout << endl << "input: " << endl << str << endl;
for (auto i = str.begin(); i < str.end(); ++i)
{
declVar.process (i);
}
str = declVar.result;
if(STATE ("done")* d = dynamic_cast<STATE ("done")*>(declVar.state))
{
} else {
str += declVar.potential;
}
// cout << endl << "declare: " << endl << str << endl;
// cout << endl << "variables: " << endl;
// for (auto& i : declaredVariables)
// {
// cout << i.first << " = " << i.second << endl;
// }
declVar.result.clear ();
return str;
}
};
void fileApp (Process& p, filesystem::path const& inputPath, filesystem::path const& outputPath) {
string input = readFileIntoString (inputPath);
ofstream outputFile (outputPath);
if (!outputFile.is_open ())
throw runtime_error ("could not open file " + outputPath.string());
outputFile << p.process (input);
outputFile.close ();
}
void folderApp (Process& p, filesystem::path inputPath)
{
filesystem::rename (inputPath, filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ())));
inputPath = filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ()));
set <filesystem::path> all;
set <filesystem::path> subdirs;
set <filesystem::path> subfiles;
for (auto& i : filesystem::directory_iterator (inputPath))
{
auto renamed = filesystem::path {i.path().parent_path()} /= p.process (i.path().filename());
all.insert (renamed);
filesystem::rename (i.path(), renamed);
if (filesystem::is_directory (renamed))
{
subdirs.insert (renamed);
} else if (filesystem::is_regular_file (renamed))
{
if (renamed.extension() == ".ph")
{
p.process (readFileIntoString (renamed));
filesystem::remove (renamed);
} else
{
subfiles.insert (renamed);
}
}
}
for (auto const& filename : subfiles)
{
fileApp (p, filename, filename);
}
for (auto const& dirname : subdirs)
{
folderApp (p, dirname);
}
}
//template <bool DO_LOUD = true>
void app (filesystem::path const& inputPath, filesystem::path outputPath) {
// filesystem::path p {inputPath};
// cout << filesystem::exists(inputPath) << endl;
// cout << filesystem::is_directory (p) << endl;
// cout << p.extension() << endl;
// cout << p.stem() << endl;
// cout << p.filename() << endl;
if (not filesystem::exists (inputPath)) {
// string warn = "file " + inputPath + "does not exists";
throw runtime_error ("file " + inputPath.string() + "does not exists");
}
if (filesystem::exists (outputPath)) {
// throw runtime_error ("file already exists");
}
Process p;
// outputPath.replace_filename (p.process (inputPath.filename ()));
// outputPath += p.process (inputPath.stem());
if (filesystem::is_directory (inputPath))
{
// cout << outputPath << endl;
outputPath/=inputPath.filename ();
outputPath = filesystem::path{outputPath}.replace_filename (p.process (outputPath.filename ()));
// cout << outputPath << endl;
// return;
filesystem::copy (inputPath, outputPath, std::filesystem::copy_options::recursive);
folderApp (p, outputPath);
} else if (filesystem::is_regular_file (inputPath))
{
fileApp (p, inputPath, outputPath);
} else
{
throw runtime_error ("");
}
}
string warning = "";
void assert_folder(string const& inputPath, string const& outputPath, string& warning) {
// cout << inputPath << endl;
app (inputPath, outputPath);
}
template <bool DO_LOUD = true>
void assert_file(string const& inputPath, string const& outputPath, string const& facitPath, string& warning) {
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
if constexpr (not DO_LOUD) {
if (result != facit)
{
string warn = "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
throw runtime_error (warn);
}
} else {
if (result != facit)
{
warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
}
}
}
#define LOUD(x) x
#define ASSERT_FILE(file, DO_LOUD) assert_file <DO_LOUD> (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning);
#define ASSERT_FOLDER(folder, DO_LOUD) assert_folder (string (TEST_FOLDERS_PRE_PATH) + string (BOOST_PP_STRINGIZE (folder)), string (TEST_FOLDERS_POST_PATH), warning);
#define ASSERT_FILE_SEQ(r, data, file) assert_file (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning);
#define ASSERT_FILES_2(seqFiles) BOOST_PP_SEQ_FOR_EACH(ASSERT_FILE_SEQ, -, seqFiles);
#define ASSERT_FILES(...) ASSERT_FILES_2 (BOOST_PP_TUPLE_TO_SEQ (__VA_ARGS__));
#define PSTR(x) decltype (const_str {x})
template <class T0, class T1>
concept same = std::is_same_v<T0, T1>;
//byte
namespace input{
struct Context;
struct State
{
virtual void process (char const* str, Context& ctx) {}
};
struct Context
{
State* state {nullptr};
string input;
vector <string> outputs;
void process (char const* str);
};
struct Begin : State
{
virtual void process (char const* str, Context& ctx);
};
struct Input : State
{
virtual void process (char const* str, Context& ctx)
{
// cout << "Input::process" << endl;
ctx.input = str;
ctx.state = new Begin;
// delete this;
}
};
struct Output : State
{
virtual void process (char const* str, Context& ctx)
{
// cout << "Output::process" << endl;
if (strcmp (str, "--input") == 0)
{
ctx.state = new Input;
// delete this;
} else
{
ctx.outputs.push_back (string {str});
}
}
};
void Context::process (char const* str)
{
// cout << "Context::process" << endl;
state -> process (str, *this);
}
void Begin::process (char const* str, Context& ctx)
{
// cout << "Begin::process" << endl;
if (strcmp (str, "--input") == 0)
{
cout << "--input" << endl;
ctx.state = new Input;
// ctx.state = static_cast <Input*> (ctx.state);
// delete this;
} else if (strcmp (str, "--output") == 0)
{
ctx.state = new Output;
} else
{
throw runtime_error ("");
}
}
}
#if defined (Debug)
auto main (int, char**) -> int
{
int argc = 5;
char** argv = new char*[argc]{new char[]{}, new char[]{"--input"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/1.hpp"}, new char[]{"--output"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/1.hpp"}};
input::Context ctx {new input::Begin};
#elif defined (Release)
auto main (int argc, char** argv) -> int
{
#endif
for (char** it = argv + 1; it < argv + argc; ++it)
{
ctx.process (*it);
}
if (ctx.input.empty ())
{
throw runtime_error ("must provide an input file");
} else if (ctx.outputs.empty ())
{
throw runtime_error ("must provide one or more output file");
}
app (ctx.input, ctx.outputs.front ());
return 0;
// int argc = 2;
// auto** argv = new char*[argc]{new char*{"bajs"}, new char*{"--input"}, new char*{"då"}, new char*{"--output"}, new char*{"ssss"}};
#if defined (Release)
#endif
// string ss;
// getline(cin, ss);
#if defined (Debug)
cout << "kuk" << endl;
removeFolderContent (TEST_FOLDERS_POST_PATH);
ASSERT_FILE (4.hpp, LOUD (1))
ASSERT_FOLDER (&(root){philips bibliotek}, LOUD(1))
return 0;
ASSERT_FOLDER ($(root){philip}, LOUD(1))
ASSERT_FILE (1.hpp, LOUD (0))
ASSERT_FILE (declare.hpp, LOUD (0))
ASSERT_FILE (4.hpp, LOUD (0))
ASSERT_FILE (paste.hpp, LOUD (0))
#else
cout << "kiss" << endl;
app (argv [1], argv [2]);
#endif
#ifdef Debug
#define ANTAL TEST_FILE_COUNT
// #define TEST_SINGEL_FILE paste.hpp
#ifdef TEST_SINGEL_FILE
string inputPath = string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
string outputPath = string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
string facitPath = string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
if (result != facit)
{
warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
}
#endif
#ifdef TEST_ALL_FILES
array <string, TEST_FILE_COUNT> test_files_pre;
array <string, TEST_FILE_COUNT> test_files_post;
array <string, TEST_FILE_COUNT> test_files_facit;
#define PRE(z, n, text) test_files_pre [n] = BOOST_PP_CAT (text, n);
#define POST(z, n, text) test_files_post [n] = BOOST_PP_CAT (text, n);
#define FACIT(z, n, text) test_files_facit [n] = BOOST_PP_CAT (text, n);
BOOST_PP_REPEAT (TEST_FILE_COUNT, PRE, TEST_FILE_PRE_)
BOOST_PP_REPEAT (TEST_FILE_COUNT, POST, TEST_FILE_POST_)
BOOST_PP_REPEAT (TEST_FILE_COUNT, FACIT, TEST_FILE_FACIT_)
for (int i = 0; i < ANTAL; ++i)
{
string inputPath = test_files_pre [i];
string outputPath = test_files_post [i];
string facitPath = test_files_facit [i];
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
// string post = readFileIntoString (test_files_post[i]);
// string facit = readFileIntoString (test_files_facit[i]);
if (result != facit)
{
warning += "\n\n\t" + test_files_post[i] + "\n\t != " + "\n\t" + test_files_facit[i] + "\n\n\n";
}
}
#endif
if (warning != "") {
// throw runtime_error (warning);
cout << warning << endl;
}
return 0;
#endif
#ifdef DEBUGGING
ifstream infile;
infile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/test0.hpp");
ofstream outfile;
outfile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/test0.hpp");
#else
ifstream infile;
infile.open (argv[1]);
ofstream outfile;
outfile.open (argv[2]);
#endif
auto remove_beginning_spaces = bind (remove_beginning_chars, _1, ' ');
auto remove_beginning_newlines = bind (remove_beginning_chars, _1, '\n');
string outtext = readFileIntoString(infile);
// auto extractors = array <extractor, 1> {extractor{"${", "}"}};
// auto extractors = array <extractor, 1> {extractor{"${", "}"}};
auto stringVariableDeclerationExtractor = extractor {"$(", ")"};
auto stringValueDeclerationExtractor = extractor {"{", "}"};
auto stringVariablePasterExtractor = extractor {"${", "}"};
// auto stringVariablePasteExtractor = extractor {"${", "}"};
vector <pair <string, string>> declaredVariables;
{
// Process p;
// p.process (outtext);
}
outfile << outtext;
// cout << first_signature (str, first_parser) << endl;
PROCC ((
template <int>
struct gpu;
$(1)
{
a # = comment # ?(name)?{explanation}
€ = _function (_anonymous/_non-anonymous) # ?[?_scope_var = @(_var)?]?(0 ?i? 0)?{}??(_function_name)?
$ = _variable (_non-anonymous){_code} # (_name){}
@ = _paste
template <>
struct gpu <${0 i 10}> # {_public change all in scope}
{
$(0 i 4) # {everyting refering to i will clone for times}
// # int i${i} -> int i0123
@(i)<1 10>
@(i)<1 10> -> {@} 12345678910
@<0 2> -> {ph} phph
2
@(hej) <-> ${0#} 02 02
-1
@(hej#) <-> ${0#} -10 0-1
2
@(#hej) <-> ${0#} 022 02
2
${0#} -> @(#hej) 002 02
kuk @<1 3> &{ph&} kuk ph1ph2ph3
fitta @<1 3> -> {ph&} kuk fitta ph123 kuk
@<1 3> -> &{ph} phphph
@(hej) <-> {0} 0 0
@(hej) () 0
@(hej) <- {1} 1 ()
@(hej) -> {2@} () 21
@(hej) 1 ()
@(hej) <-> {3@} 3 31
@(hej@) <-> {kuk} "snopphejkuk"
@(hej) {philip@} philipkuk
@{i} -> {int i} kommer bli int i int i int i int i
@{i} -> {int@ i@} int0 i0 int1 i1 int2 i2 int3 i3
${i} 0123
$(str){philip} "philip"
${str} -> {int i@} -> {kuk @ hora} "kuk int iphilip hora"
$(hej){kukens fitta} kukens fitta
${hej} kukens fitta
int i${0 10} = 0; #{_private}
int j€(0 5)(k) = 3; #{public}
€[j = @(i)](0 i 3){int i@(i + 1) = @(j);}(myFun)
// €[j = @(i)](0 i 3){int i@(i) = @(j);} anonymous
// 0 i 3 prio före 0 i 10 -> därför sätter vi om namnet till j
// 0 i 3 is internal dvs endast inne i {} och i refererar inget utanför
$(_stat_int){static $(con){constexpr} int} fitta = GPU_COUNT;
ERROR-> $(_stat){kiss}
@(_stat_int) count = GPU_COUNT;
${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D;
@(st) int i = 3;
};
}
)(0)(string s));
// cout << s << endl;
// PROCC ((
// template <int>
// struct gpu;
//
// $(1)
// {
// € = inline
// $ = declare variable, only visible to the current scope
// and to those below
//
// template <>
// struct gpu <$(0 i 10)>
// {
// int $(0 j 10) = 0;
//
// €[j = @(i)](0 i 3){int i@(i) = @(j);}(myFun)
// 0 i 3 prio före 0 i 10 -> därför sätter vi om namnet till j
// 0 i 3 is internal dvs endast inne i {} och i refererar inget utanför
// $(stat){static $(con){constexpr} int} fitta = GPU_COUNT;
// ERROR-> $(stat){kiss}
// @(stat) count = GPU_COUNT;
// ${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D;
// @(st) int i = 3;
// };
// }
// )(0)(string s));
// cout << s << endl;
std::vector<double> input = {1.2, 2.3, 3.4, 4.5};
// cout << "hello world" << endl;
return 0;
}
string first_signature (string const& first, string const& second, string str, auto&& fun)
{
auto a1 = str.find(first);
while (a1 != string::npos)
{
if (int a2 = str.find (second); a2 != string::npos)
{
string replac = fun (string (str.begin() + a1, str.begin() + a2 + 1));
str.replace (str.begin() + a1, str.begin() + a2 + 1, replac);
}
else
{
break;
}
a1 = str.find ("${");
}
// string res;
// for (auto const& i : str)
// res += i;
return str;
}
| 25.097101 | 271 | 0.528671 | phiwen96 |
61ee79cd70ea8ea30a159d70ad57ba85261744be | 1,436 | cpp | C++ | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
USEFORM("UAbout.cpp", AboutBox);
USEFORM("UEdit.cpp", EditFile);
USEFORM("URegInf.cpp", RegInf);
USEFORM("UReg.cpp", Regist);
USEFORM("UMain.cpp", Main);
USEFORM("UEnv.cpp", Env);
//---------------------------------------------------------------------------
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
HANDLE mx = CreateMutex(NULL, true, L"SingleInstanceProgram");
if (GetLastError()) {
ShowMessage("CWTW-Proは既に実行されています!");
return -1;
}
try
{
Application->Initialize();
Application->MainFormOnTaskBar = true;
Application->CreateForm(__classid(TMain), &Main);
Application->CreateForm(__classid(TAboutBox), &AboutBox);
Application->CreateForm(__classid(TEditFile), &EditFile);
Application->CreateForm(__classid(TRegist), &Regist);
Application->CreateForm(__classid(TRegInf), &RegInf);
Application->CreateForm(__classid(TEnv), &Env);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
ReleaseMutex(mx);
return 0;
}
//---------------------------------------------------------------------------
| 26.592593 | 78 | 0.548747 | jr4qpv |
61eecc43c9d264ef7163665bc71d09e160c624ce | 1,865 | cpp | C++ | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | // Merge two Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
} *first = NULL, *second = NULL, *third = NULL;
void Display(struct Node *p)
{
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
void create(int A[], int n)
{
int i;
struct Node *t, *last;
first = (struct Node *)malloc(sizeof(struct Node));
first->data = A[0];
first->next = NULL;
last = first;
}
for (int i = 1; i < n; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
void create2(int A[], int n)
{
int i;
struct Node *t, *last;
second = (struct Node *)malloc(sizeof(struct Node));
second->data = A[0];
second->next = NULL;
last = second;
}
for (i = 1; i < n; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
void Merge(struct Node *p, struct Node *q)
{
struct Node *last;
if (p->data < q->data)
{
third = last = p;
p = p->next;
third->next = NULL;
}
else
{
third = last = q;
q = q->next;
third->next = NULL;
}
while (p && q)
{
if (p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
last->next = NULL;
}
else
{
last->next = q;
last = q;
q = q->next;
last->next = NULL;
}
}
if (p)
{
last->next = p;
}
if (q)
{
last->next = q;
}
}
int main()
{
int A[] = {10, 20, 40, 50, 60};
int B[] = {15, 18, 25, 30, 55};
create(A, 5);
create2(B, 5);
Merge(frist, second);
Display(third);
}
return 0; | 18.284314 | 56 | 0.447721 | M1NH42 |
61f29e1436d2d9c5c30bd40a750d56683c1a3a70 | 1,883 | cc | C++ | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 7 | 2019-03-26T02:47:46.000Z | 2021-03-25T08:05:37.000Z | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 15 | 2017-06-20T10:02:58.000Z | 2021-05-06T02:23:13.000Z | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 13 | 2017-12-06T12:39:29.000Z | 2022-03-29T05:50:44.000Z | // Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <grpc/impl/codegen/port_platform.h>
#include "src/core/lib/config/core_configuration.h"
namespace grpc_core {
std::atomic<CoreConfiguration*> CoreConfiguration::config_{nullptr};
CoreConfiguration::Builder::Builder() = default;
CoreConfiguration* CoreConfiguration::Builder::Build() {
return new CoreConfiguration(this);
}
CoreConfiguration::CoreConfiguration(Builder* builder)
: handshaker_registry_(builder->handshaker_registry_.Build()) {}
const CoreConfiguration& CoreConfiguration::BuildNewAndMaybeSet() {
// Construct builder, pass it up to code that knows about build configuration
Builder builder;
BuildCoreConfiguration(&builder);
// Use builder to construct a confguration
CoreConfiguration* p = builder.Build();
// Try to set configuration global - it's possible another thread raced us
// here, in which case we drop the work we did and use the one that got set
// first
CoreConfiguration* expected = nullptr;
if (!config_.compare_exchange_strong(expected, p, std::memory_order_acq_rel,
std::memory_order_acquire)) {
delete p;
return *expected;
}
return *p;
}
void CoreConfiguration::Reset() {
delete config_.exchange(nullptr, std::memory_order_acquire);
}
} // namespace grpc_core
| 34.236364 | 79 | 0.740308 | blueice123 |
61f5e46c89b2fbc043d053bbca67fe26ad796ae9 | 560 | cpp | C++ | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | /**
* Algorithm and estimation function regarding transform.
* \author Christian Merkl ([email protected])
* \date 2. November 2019
*/
#include "francor_base/algorithm/transform.h"
#include "francor_base/transform.h"
namespace francor {
namespace base {
namespace algorithm {
namespace transform {
void transformPointVector(const Transform2d& transform, Point2dVector& points)
{
for (auto& point : points)
point = transform * point;
}
} // end namespace transform
} // end namespace algorithm
} // end namespace base
} // end namespace francor | 18.666667 | 78 | 0.733929 | franc0r |
61f60ed77aa8cfe906e4913e9326b833cef4ce25 | 5,782 | cpp | C++ | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// ****************************************************************************
// This snippet illustrates simple use of the PxSpatialIndex data structure
//
// Note that spatial index has been marked as deprecated and will be removed
// in future releases
//
// We create a number of spheres, and raycast against them in a random direction
// from the origin. When a raycast hits a sphere, we teleport it to a random
// location
// ****************************************************************************
#include <ctype.h>
#include "PxPhysicsAPI.h"
#include "../SnippetCommon/SnippetPrint.h"
#include "../SnippetUtils/SnippetUtils.h"
using namespace physx;
PxDefaultAllocator gAllocator;
PxDefaultErrorCallback gErrorCallback;
PxFoundation* gFoundation = NULL;
static const PxU32 SPHERE_COUNT = 500;
float rand01()
{
return float(rand())/RAND_MAX;
}
struct Sphere : public PxSpatialIndexItem
{
Sphere()
{
radius = 1;
resetPosition();
}
Sphere(PxReal r)
: radius(r)
{
resetPosition();
}
void resetPosition()
{
do
{
position = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f)*(5+rand01()*5);
}
while (position.normalize()==0.0f);
}
PxBounds3 getBounds()
{
// Geometry queries err on the side of reporting positive results in the face of floating point inaccuracies.
// To ensure that a geometry query only reports true when the bounding boxes in the BVH overlap, use
// getWorldBounds, which has a third parameter that scales the bounds slightly (default is scaling by 1.01f)
return PxGeometryQuery::getWorldBounds(PxSphereGeometry(radius), PxTransform(position));
}
PxVec3 position;
PxReal radius;
PxSpatialIndexItemId id;
};
Sphere gSpheres[SPHERE_COUNT];
PxSpatialIndex* gBvh;
void init()
{
gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback);
gBvh = PxCreateSpatialIndex();
// insert the spheres into the BVH, recording the ID so we can later update them
for(PxU32 i=0;i<SPHERE_COUNT;i++)
gSpheres[i].id = gBvh->insert(gSpheres[i], gSpheres[i].getBounds());
// force a full rebuild of the BVH
gBvh->rebuildFull();
// hint that should rebuild over the course of approximately 20 rebuildStep() calls
gBvh->setIncrementalRebuildRate(20);
}
struct HitCallback : public PxSpatialLocationCallback
{
HitCallback(const PxVec3 p, const PxVec3& d): position(p), direction(d), closest(FLT_MAX), hitSphere(NULL) {}
PxAgain onHit(PxSpatialIndexItem& item, PxReal distance, PxReal& shrunkDistance)
{
PX_UNUSED(distance);
Sphere& s = static_cast<Sphere&>(item);
PxRaycastHit hitData;
// the ray hit the sphere's AABB, now we do a ray-sphere intersection test to find out if the ray hit the sphere
PxU32 hit = PxGeometryQuery::raycast(position, direction,
PxSphereGeometry(s.radius), PxTransform(s.position),
1e6, PxHitFlag::eDEFAULT,
1, &hitData);
// if the raycast hit and it's closer than what we had before, shrink the maximum length of the raycast
if(hit && hitData.distance < closest)
{
closest = hitData.distance;
hitSphere = &s;
shrunkDistance = hitData.distance;
}
// and continue the query
return true;
}
PxVec3 position, direction;
PxReal closest;
Sphere* hitSphere;
};
void step()
{
for(PxU32 hits=0; hits<10;)
{
// raycast in a random direction from the origin, and teleport the closest sphere we find
PxVec3 dir = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f).getNormalized();
HitCallback callback(PxVec3(0), dir);
gBvh->raycast(PxVec3(0), dir, FLT_MAX, callback);
Sphere* hit = callback.hitSphere;
if(hit)
{
hit->resetPosition();
gBvh->update(hit->id, hit->getBounds());
hits++;
}
}
// run an incremental rebuild step in the background
gBvh->rebuildStep();
}
void cleanup()
{
gBvh->release();
gFoundation->release();
printf("SnippetSpatialIndex done.\n");
}
int snippetMain(int, const char*const*)
{
static const PxU32 frameCount = 100;
init();
for(PxU32 i=0; i<frameCount; i++)
step();
cleanup();
return 0;
}
| 29.350254 | 114 | 0.706849 | DoubleTT-Changan |
61f6326e14124616ca2b9fc6968570ca5e135f84 | 2,932 | cpp | C++ | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | #include <array>
#include <cstdlib>
#include <filesystem>
#include <numeric>
#ifdef __linux__
#include <unistd.h>
#include <limits.h>
#endif
#include "util_env.h"
#include "./com/com_include.h"
namespace dxvk::env {
std::string getEnvVar(const char* name) {
#ifdef _WIN32
std::vector<WCHAR> result;
result.resize(MAX_PATH + 1);
DWORD len = ::GetEnvironmentVariableW(str::tows(name).c_str(), result.data(), MAX_PATH);
result.resize(len);
return str::fromws(result.data());
#else
const char* result = std::getenv(name);
return result ? result : "";
#endif
}
size_t matchFileExtension(const std::string& name, const char* ext) {
auto pos = name.find_last_of('.');
if (pos == std::string::npos)
return pos;
bool matches = std::accumulate(name.begin() + pos + 1, name.end(), true,
[&ext] (bool current, char a) {
if (a >= 'A' && a <= 'Z')
a += 'a' - 'A';
return current && *ext && a == *(ext++);
});
return matches ? pos : std::string::npos;
}
std::string getExeName() {
std::string fullPath = getExePath();
auto n = fullPath.find_last_of(env::PlatformDirSlash);
return (n != std::string::npos)
? fullPath.substr(n + 1)
: fullPath;
}
std::string getExeBaseName() {
auto exeName = getExeName();
#ifdef _WIN32
auto extp = matchFileExtension(exeName, "exe");
if (extp != std::string::npos)
exeName.erase(extp);
#endif
return exeName;
}
std::string getExePath() {
#if defined(_WIN32)
std::vector<WCHAR> exePath;
exePath.resize(MAX_PATH + 1);
DWORD len = ::GetModuleFileNameW(NULL, exePath.data(), MAX_PATH);
exePath.resize(len);
return str::fromws(exePath.data());
#elif defined(__linux__)
std::array<char, PATH_MAX> exePath = {};
size_t count = readlink("/proc/self/exe", exePath.data(), exePath.size());
return std::string(exePath.begin(), exePath.begin() + count);
#endif
}
void setThreadName(const std::string& name) {
#ifdef _WIN32
using SetThreadDescriptionProc = HRESULT (WINAPI *) (HANDLE, PCWSTR);
static auto proc = reinterpret_cast<SetThreadDescriptionProc>(
::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription"));
if (proc != nullptr) {
auto wideName = std::vector<WCHAR>(name.length() + 1);
str::tows(name.c_str(), wideName.data(), wideName.size());
(*proc)(::GetCurrentThread(), wideName.data());
}
#else
std::array<char, 16> posixName = {};
dxvk::str::strlcpy(posixName.data(), name.c_str(), 16);
::pthread_setname_np(pthread_self(), posixName.data());
#endif
}
bool createDirectory(const std::string& path) {
#ifdef _WIN32
WCHAR widePath[MAX_PATH];
str::tows(path.c_str(), widePath);
return !!CreateDirectoryW(widePath, nullptr);
#else
return std::filesystem::create_directories(path);
#endif
}
}
| 23.837398 | 92 | 0.632674 | Gcenx |
61f637fa2f200b9157965d01624ea87e69cb5358 | 805 | cpp | C++ | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | //https://codeforces.com/contest/66/problem/B
#include<bits/stdc++.h>
using namespace std ;
#define aakriti long long int
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
aakriti number ;
cin >> number ;
aakriti arr[number], ans = 1 ;
for(int i = 0; i <number ; i++)
cin >> arr[i] ;
for(int i = 0; i < number; i++)
{
aakriti cnt = 1 ;
for(int j = i -1; j >= 0; j--)
{
if(arr[j] <= arr[j + 1])
cnt++;
else
break;
}
for(int j = i + 1; j < number; j++)
{
if(arr[j] <= arr[j - 1])
cnt++;
else
break;
}
ans = max(ans, cnt);
}
cout << ans ;
}
| 23 | 46 | 0.397516 | canis-majoris123 |
61fb39d1e35e1a1b445ad7aef886ef04bdf8e3b9 | 4,017 | cpp | C++ | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | /*
* A344279.cpp
*
* Created on: 14-May-2021
*
* Author: Soumyadeep Dhar
*
* A344279: Numbers a(n)=m such that |m| is the smallest, k=n*m and r=(n^2+1)*m
* for two quadratic equations of the form t^2+k*t+r = 0 and t^2+r*t+k^2 = 0
* have non-zero integer roots, where k is the coefficient of t and r is the
* constant in first equation, which has non-zero roots p and q
* (i.e., {k, r, p, q} ∈ ℤ≠, k=p+q and r=p*q). Also r is the coefficient of t
* and k^2 is the constant in second equation, which has non-zero roots u and v
* (i.e., {r, k, u, v} ∈ ℤ≠, r=u+v and k^2=u*v).
*
* Example: -1, -4, -1, -16, 9, -36, 5, -1, -81, -100, -121, -4, 9, -196, -225,
* -256, 8, 5, -361, -400, -1, -484, -529, -576, -625, -676, -729, -784,
* -841, -900, -961, -1024, -9, 9, -1225, -1296, -1369, -1444, -1521,
* -1600, -1681, -1764, -1849, -1936, -2025, -2116, 5, -2304, -2401, -2500
*
* A344279: https://oeis.org/A344279/b344279.txt
*
* Sequence Author: Soumyadeep Dhar, May 14, 2021
*
*/
#include <map>
#include <tuple>
#include <iomanip>
#include "largeint.h"
#include "processor.h"
using LargeInteger = ns::dn::li::LargeInt;
using LargeIntegerSequence = ns::dn::is::IntegerSequenceProcessor<ns::dn::is::A344279>;
// Process input data to generate next elements of the sequence
template <>
unsigned int LargeIntegerSequence::generate()
{
int _count = 1;
std::pair<unsigned int, std::string> _element;
// keep result values
std::map<long long int, std::tuple
< long long int
, long long int
, long long int
, long long int
, long long int
, long long int
, long long int
, long long int>> _results;
for (long long int n = 1; n <= 225; n++)
{
// Check all numbers upto 100
for (long long int c = 1; c <= 250000; c++)
{
bool isFound = false;
for (auto s : {1, -1})
{
// Find 'a * b' as initial expected 'm'
long long int m = s*c*(n*n + 1);
// Find 'a * b' as initial expected 'k'
long long int k = s*c*n;
// Get k^2 value
long long int kk = (k * k);
// Find possible (a, b) as root of the equation
// x^2 -kx + m (where a + b = k and a * b = m)
long long int a = (k + sqrt(kk - (4 * m))) / 2;
long long int b = k - a;
// Ignore non integer roots
if(m != (a * b)) continue;
// For all possible roots of the equation
// x^2 - mx + k^2 (where x + y = m and x * y = k^2)
long long int y = (m + sqrt((m * m) - (4 * kk))) / 2;
long long int x = m - y;
// If valid roots found
if (kk != (x * y)) continue;
// Store result
_results[n] = std::make_tuple(c*s, k, m, kk, a, b, x, y);
// Print output results
std::cout << " " << std::setw(9) << n;
std::cout << " " << std::setw(9) << c*s;
std::cout << " " << std::setw(9) << k;
std::cout << " " << std::setw(9) << m;
std::cout << " " << std::setw(9) << kk;
std::cout << " " << std::setw(9) << a;
std::cout << " " << std::setw(9) << b;
std::cout << " " << std::setw(9) << x;
std::cout << " " << std::setw(9) << y << std::endl;
// Mark solution found
isFound = true;
break;
}
// No need to search further as result already found
if(isFound) break;
}
}
// Store shorted result data
_count = 1;
for (auto _x : _results)
{
_element.first = _count;
_element.second = std::to_string(std::get<0>(_x.second));
// Write output data
_ouWriter << _element;
// Update element count
_count++;
}
return 0;
}
int main()
{
// Initialize sequence
LargeIntegerSequence seqA344279("../data/oeis/b000290.txt", "../data/oeis/b000290.txt", "../data/A344279.txt");
// Generate sequence
seqA344279.generate();
return 0;
} | 29.108696 | 113 | 0.52004 | SoumyadeepDhar |
61fead47df29906cf3576128c4e49d0d3adf3215 | 840 | cpp | C++ | CEOI/2017/palindrome.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2018-12-14T07:51:26.000Z | 2018-12-14T07:51:26.000Z | CEOI/2017/palindrome.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | null | null | null | CEOI/2017/palindrome.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2019-06-23T10:34:19.000Z | 2019-06-23T10:34:19.000Z | //Palindromic Partitions
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long int lli;
const lli MOD = lli(1e9)+7, base = 31;
lli n;
string S;
lli modpow(lli a, lli b)
{
if(!b) return 1;
else if(b == 1) return a;
else
{
lli res = modpow(a, b/2)%MOD;
res *= res;
res %= MOD;
if(b%2) res *= a;
return res%MOD;
}
}
lli solve(lli L, lli R)
{
if(L > R) return 0;
lli hasha = 0, hashb = 0;
for(lli i = 0;i < n;i++)
{
if(L+i >= R-i) break;
hasha *= base;
hasha %= MOD;
hasha += lli(S[L+i]-'a');
hasha %= MOD;
hashb += lli(S[R-i]-'a')*modpow(base, i);
hashb %= MOD;
if(hasha == hashb) return solve(L+i+1, R-i-1)+2;
}
return 1;
}
int main(void)
{
lli t;
scanf("%lld", &t);
while(t--)
{
cin >> S;
n = lli(S.size());
printf("%lld\n", solve(0, n-1));
}
} | 14.482759 | 50 | 0.54881 | nalinbhardwaj |
11006e9f92d20522e33039acbfc19819486c5c76 | 3,433 | cpp | C++ | examples/3d/easyCamExample/src/ofApp.cpp | creatologist/openFrameworks0084 | aa74f188f105b62fbcecb7baf2b41d56d97cf7bc | [
"MIT"
] | 3 | 2017-12-27T23:02:50.000Z | 2018-10-14T00:50:49.000Z | examples/3d/easyCamExample/src/ofApp.cpp | creatologist/openFrameworks0084 | aa74f188f105b62fbcecb7baf2b41d56d97cf7bc | [
"MIT"
] | null | null | null | examples/3d/easyCamExample/src/ofApp.cpp | creatologist/openFrameworks0084 | aa74f188f105b62fbcecb7baf2b41d56d97cf7bc | [
"MIT"
] | 1 | 2020-02-28T20:39:20.000Z | 2020-02-28T20:39:20.000Z | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
// this uses depth information for occlusion
// rather than always drawing things on top of each other
ofEnableDepthTest();
// this sets the camera's distance from the object
cam.setDistance(100);
ofSetCircleResolution(64);
bShowHelp = true;
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
cam.begin();
ofRotateX(ofRadToDeg(.5));
ofRotateY(ofRadToDeg(-.5));
ofBackground(0);
ofSetColor(255,0,0);
ofFill();
ofDrawBox(30);
ofNoFill();
ofSetColor(0);
ofDrawBox(30);
ofPushMatrix();
ofTranslate(0,0,20);
ofSetColor(0,0,255);
ofFill();
ofDrawBox(5);
ofNoFill();
ofSetColor(0);
ofDrawBox(5);
ofPopMatrix();
cam.end();
drawInteractionArea();
ofSetColor(255);
string msg = string("Using mouse inputs to navigate (press 'c' to toggle): ") + (cam.getMouseInputEnabled() ? "YES" : "NO");
msg += string("\nShowing help (press 'h' to toggle): ")+ (bShowHelp ? "YES" : "NO");
if (bShowHelp) {
msg += "\n\nLEFT MOUSE BUTTON DRAG:\nStart dragging INSIDE the yellow circle -> camera XY rotation .\nStart dragging OUTSIDE the yellow circle -> camera Z rotation (roll).\n\n";
msg += "LEFT MOUSE BUTTON DRAG + TRANSLATION KEY (" + ofToString(cam.getTranslationKey()) + ") PRESSED\n";
msg += "OR MIDDLE MOUSE BUTTON (if available):\n";
msg += "move over XY axes (truck and boom).\n\n";
msg += "RIGHT MOUSE BUTTON:\n";
msg += "move over Z axis (dolly)";
}
msg += "\n\nfps: " + ofToString(ofGetFrameRate(), 2);
ofDrawBitmapStringHighlight(msg, 10, 20);
}
//--------------------------------------------------------------
void ofApp::drawInteractionArea(){
ofRectangle vp = ofGetCurrentViewport();
float r = MIN(vp.width, vp.height) * 0.5f;
float x = vp.width * 0.5f;
float y = vp.height * 0.5f;
ofPushStyle();
ofSetLineWidth(3);
ofSetColor(255, 255, 0);
ofNoFill();
glDepthMask(false);
ofCircle(x, y, r);
glDepthMask(true);
ofPopStyle();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
case 'C':
case 'c':
if(cam.getMouseInputEnabled()) cam.disableMouseInput();
else cam.enableMouseInput();
break;
case 'F':
case 'f':
ofToggleFullscreen();
break;
case 'H':
case 'h':
bShowHelp ^=true;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 24.697842 | 179 | 0.499272 | creatologist |
11021a8038ae3cc9d22b5c7026aebcae6a20e663 | 21,155 | hpp | C++ | include/jet/Utilities.hpp | XanaduAI/jet | c74fd61c7caf821153b05ab9f9a783e779040161 | [
"Apache-2.0"
] | 29 | 2021-07-22T20:32:55.000Z | 2022-03-28T20:36:03.000Z | include/jet/Utilities.hpp | XanaduAI/jet | c74fd61c7caf821153b05ab9f9a783e779040161 | [
"Apache-2.0"
] | 25 | 2021-07-22T21:05:20.000Z | 2021-11-24T17:34:31.000Z | include/jet/Utilities.hpp | XanaduAI/jet | c74fd61c7caf821153b05ab9f9a783e779040161 | [
"Apache-2.0"
] | 7 | 2021-07-23T11:47:12.000Z | 2022-03-23T07:12:39.000Z | #pragma once
#include <algorithm>
#include <complex>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
#include "Abort.hpp"
namespace Jet {
namespace Utilities {
/**
* @brief Determines if an integral value is a power of 2.
* @param value Number to check.
* @return True if `value` is a power of 2.
*/
constexpr inline bool is_pow_2(size_t value)
{
return static_cast<bool>(value && !(value & (value - 1)));
}
/**
* @brief Finds the log2 value of a known power of 2, otherwise finds the floor
* of log2 of the operand.
*
* This works by counting the highest set bit in a size_t by examining the
* number of leading zeros. This value can then be subtracted from the
* number of bits in the size_t value to yield the log2 value.
*
* @param value Value to calculate log2 of. If 0, the result is undefined
* @return size_t log2 result of value. If value is a non power-of-2, returns
* the floor of the log2 operation.
*/
constexpr inline size_t fast_log2(size_t value)
{
return static_cast<size_t>(std::numeric_limits<size_t>::digits -
__builtin_clzll((value)) - 1ULL);
}
/**
* Streams a pair of elements to an output stream.
*
* @tparam T1 Type of the first element in the pair.
* @tparam T2 Type of the second element in the pair.
* @param os Output stream to be modified.
* @param p Pair to be inserted.
* @return Reference to the given output stream.
*/
template <class T1, class T2>
inline std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &p)
{
return os << '{' << p.first << ',' << p.second << '}';
}
/**
* Streams a vector to an output stream.
*
* @tparam T Type of the elements in the vector.
* @param os Output stream to be modified.
* @param v Vector to be inserted.
* @return Reference to the given output stream.
*/
template <class T>
inline std::ostream &operator<<(std::ostream &os, const std::vector<T> &v)
{
os << '{';
for (size_t i = 0; i < v.size(); i++) {
if (i != 0) {
os << " ";
}
os << v[i];
}
os << '}';
return os;
}
/**
* Converts an ID into a unique string index of the form [a-zA-Z][0-9]*.
*
* @param id ID to be converted.
* @return String index associated with the ID.
*/
inline std::string GenerateStringIndex(size_t id)
{
static const std::vector<std::string> alphabet = {
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
const size_t div_id = id / alphabet.size();
const std::string prefix = alphabet[id % alphabet.size()];
const std::string suffix = (div_id == 0) ? "" : std::to_string(div_id - 1);
return prefix + suffix;
}
/**
* Computes the order (i.e., number of rows and columns) of the given square
* matrix.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @return Order of the matrix.
*/
template <class scalar_type_t>
inline size_t Order(const std::vector<std::complex<scalar_type_t>> &mat)
{
// If sqrt() returns a value just under the true square root, increment n.
size_t n = static_cast<size_t>(sqrt(mat.size()));
n += n * n != mat.size();
return n;
}
/**
* Returns the `n` x `n` complex-valued identity matrix.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param n Order of the desired identity matrix.
* @return Vector representing the desired matrix, encoded in row-major order.
*/
template <class scalar_type_t>
inline std::vector<std::complex<scalar_type_t>> Eye(size_t n)
{
std::vector<std::complex<scalar_type_t>> eye(n * n, 0);
for (size_t i = 0; i < n; i++) {
eye[i * n + i] = 1;
}
return eye;
}
/**
* Multiplies the two given square matrices.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param m1 Matrix on the LHS of the multiplication.
* @param m2 Matrix on the RHS of the multiplication.
* @param n Order of the two matrices.
* @return Matrix representing the product of `m1` and `m2`.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
MultiplySquareMatrices(const std::vector<std::complex<scalar_type_t>> &m1,
const std::vector<std::complex<scalar_type_t>> &m2,
size_t n)
{
JET_ABORT_IF_NOT(m1.size() == n * n, "LHS matrix has the wrong order");
JET_ABORT_IF_NOT(m2.size() == n * n, "RHS matrix has the wrong order");
std::vector<std::complex<scalar_type_t>> product(n * n);
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
for (size_t k = 0; k < n; k++) {
product[i * n + j] += m1[i * n + k] * m2[k * n + j];
}
}
}
return product;
}
/**
* Raises the given matrix to the specified exponent.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param mat Matrix at the base of the power.
* @param k Exponent of the power.
* @return Matrix representing `mat` raised to the power of `k`.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
Pow(const std::vector<std::complex<scalar_type_t>> &mat, size_t k)
{
if (k == 1) {
return mat;
}
const auto n = Order(mat);
if (k == 0) {
return Eye<scalar_type_t>(n);
}
std::vector<std::complex<scalar_type_t>> power = mat;
for (size_t i = 2; i <= k; i++) {
power = MultiplySquareMatrices(power, mat, n);
}
return power;
}
/**
* Adds the given matrices.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param m1 Matrix on the LHS of the addition.
* @param m2 Matrix on the RHS of the addition.
* @return Matrix representing the sum of `m1` and `m2`.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
operator+(const std::vector<std::complex<scalar_type_t>> &m1,
const std::vector<std::complex<scalar_type_t>> &m2)
{
JET_ABORT_IF_NOT(m1.size() == m2.size(), "Matrices have different sizes");
std::vector<std::complex<scalar_type_t>> sum(m1.size());
for (size_t i = 0; i < m1.size(); i++) {
sum[i] = m1[i] + m2[i];
}
return sum;
}
/**
* Subtracts the given matrices.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param m1 Matrix on the LHS of the subtraction.
* @param m2 Matrix on the RHS of the subtraction.
* @return Matrix representing `m2` subtracted from `m1`.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
operator-(const std::vector<std::complex<scalar_type_t>> &m1,
const std::vector<std::complex<scalar_type_t>> &m2)
{
JET_ABORT_IF_NOT(m1.size() == m2.size(), "Matrices have different sizes");
std::vector<std::complex<scalar_type_t>> diff(m1.size());
for (size_t i = 0; i < m1.size(); i++) {
diff[i] = m1[i] - m2[i];
}
return diff;
}
/**
* Returns the product of the given scalar and matrix.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param mat Matrix to be scaled.
* @param c Scalar to be applied to the matrix.
* @return Matrix representing the scalar product of `c` and `mat`.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
operator*(const std::vector<std::complex<scalar_type_t>> &mat,
std::complex<scalar_type_t> c)
{
std::vector<std::complex<scalar_type_t>> product = mat;
for (size_t i = 0; i < product.size(); i++) {
product[i] *= c;
}
return product;
}
/**
* Returns a diagonal matrix with the same dimensions of the given matrix where
* each entry along the main diagonal is derived by applying std::exp() to the
* corresponding entry in the given matrix.
*
* @tparam scalar_type_t Template parameter of std::complex.
* @param mat Matrix to be converted into a diagonal matrix.
* @return Matrix representing the diagonal exponentation of the given matrix.
*/
template <typename scalar_type_t>
inline std::vector<std::complex<scalar_type_t>>
DiagExp(const std::vector<std::complex<scalar_type_t>> &mat)
{
const auto n = Order(mat);
std::vector<std::complex<scalar_type_t>> diag(mat.size(), 0);
for (size_t i = 0; i < n; i++) {
diag[i * n + i] = std::exp(mat[i * n + i]);
}
return diag;
}
/**
* Returns a diagonal tensor with the given main diagonal.
*
* @tparam Tensor Type of the tensor.
* @tparam T Type of the diagonal entries.
* @param vec Entries to be copied to the main diagonal of the tensor.
* @return Tensor with the given main diagonal.
*/
template <typename Tensor, typename T>
inline Tensor DiagMatrix(const std::vector<T> &vec)
{
const size_t n = vec.size();
Tensor tens({n, n});
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
tens.SetValue({i, j}, (i == j) ? vec[i] : 0.0);
}
}
return tens;
}
/**
* Reports whether the given element is in the provided vector.
*
* @tparam T Type of the elements in the vector.
* @param e Element being searched for.
* @param v Vector to be searched.
* @return True if the element is in the vector.
*/
template <class T> inline bool InVector(const T &e, const std::vector<T> &v)
{
return std::find(v.cbegin(), v.cend(), e) != v.cend();
}
/**
* Computes the intersection of two small vectors.
*
* @tparam T Type of the elements in the vectors.
* @param v1 Vector on the LHS of the intersection.
* @param v2 Vector on the RHS of the intersection.
* @return Vector containing the elements in both vectors.
*/
template <typename T>
inline std::vector<T> VectorIntersection(const std::vector<T> &v1,
const std::vector<T> &v2)
{
std::vector<T> result;
for (const auto &value : v1) {
if (InVector(value, v2)) {
result.emplace_back(value);
}
}
return result;
}
/**
* Computes the union of two small vectors.
*
* @tparam T Type of the elements in the vectors.
* @param v1 Vector on the LHS of the union.
* @param v2 Vector on the RHS of the union.
* @return Vector containing the elements in at least one vector.
*/
template <typename T>
inline std::vector<T> VectorUnion(const std::vector<T> &v1,
const std::vector<T> &v2)
{
std::vector<T> result = v1;
for (const auto &value : v2) {
if (!InVector(value, v1)) {
result.emplace_back(value);
}
}
return result;
}
/**
* Computes the difference of two small vectors.
*
* @tparam T Type of the elements in the vectors.
* @param v1 Vector on the LHS of the difference.
* @param v2 Vector on the RHS of the difference.
* @return Vector containing the elements only in the first vector.
*/
template <typename T>
inline std::vector<T> VectorSubtraction(const std::vector<T> &v1,
const std::vector<T> &v2)
{
std::vector<T> result;
for (const auto &value : v1) {
if (!InVector(value, v2)) {
result.emplace_back(value);
}
}
return result;
}
/**
* Computes the disjunctive union of two small vectors.
*
* @tparam T Type of the elements in the vectors.
* @param v1 Vector on the LHS of the disjunctive union.
* @param v2 Vector on the RHS of the disjunctive union.
* @return Vector containing the elements in exactly one of the vectors.
*/
template <typename T>
inline std::vector<T> VectorDisjunctiveUnion(const std::vector<T> &v1,
const std::vector<T> &v2)
{
return VectorSubtraction(VectorUnion(v1, v2), VectorIntersection(v1, v2));
}
/**
* Concatenates the strings in the given vector (using "" as the separator).
*
* @param v Vector to be concatenated.
* @return String representing the contatentation of the vector contents.
*/
inline std::string JoinStringVector(const std::vector<std::string> &v)
{
return std::accumulate(v.begin(), v.end(), std::string(""));
}
/**
* Concatenates the elements in the two given vectors.
*
* @tparam T Type of the elements in the vectors.
* @param v1 Prefix of the concatenation.
* @param v2 Suffix of the concatenation.
* @return Vector representing the contatentation of `v1` and `v2`.
*/
template <typename T>
inline std::vector<T> VectorConcatenation(const std::vector<T> &v1,
const std::vector<T> &v2)
{
std::vector<T> concat = v1;
concat.insert(concat.end(), v2.begin(), v2.end());
return concat;
}
/**
* Returns the factorial of the given number.
*
* @warning This function is susceptible to overflow errors for large values of
* `n`.
*
* @param n Number whose factorial is to be computed.
* @return Factorial of the given number.
*/
inline size_t Factorial(size_t n)
{
size_t prod = 1;
for (size_t i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
/**
* @brief Returns the size of a shape.
*
* @param shape Index dimensions.
* @return Product of the index dimensions in the shape.
*/
inline size_t ShapeToSize(const std::vector<size_t> &shape)
{
size_t size = 1;
for (const auto &dim : shape) {
size *= dim;
}
return size;
}
/**
* @brief Converts a linear index into a multi-dimensional index.
*
* The multi-dimensional index is written in row-major order.
*
* Example: To compute the multi-index (i, j) of an element in a 2x2 matrix
* given a linear index of 2, `shape` would be {2, 2} and the result
* would be `{1, 0}`.
* \code{.cpp}
* std::vector<size_t> multi_index = UnravelIndex(2, {2, 2}); // {1, 0}
* \endcode
*
* @param index Linear index to be unraveled.
* @param shape Size of each index dimension.
* @return Multi-index associated with the linear index.
*/
inline std::vector<size_t> UnravelIndex(unsigned long long index,
const std::vector<size_t> &shape)
{
const size_t size = ShapeToSize(shape);
JET_ABORT_IF(size <= index, "Linear index does not fit in the shape.");
std::vector<size_t> multi_index(shape.size());
for (int i = multi_index.size() - 1; i >= 0; i--) {
multi_index[i] = index % shape[i];
index /= shape[i];
}
return multi_index;
}
/**
* @brief Converts a multi-dimensional index into a linear index.
*
* @note This function is the inverse of UnravelIndex().
*
* @param index Multi-index to be raveled, expressed in row-major order.
* @param shape Size of each index dimension.
* @return Linear index associated with the multi-index.
*/
inline unsigned long long RavelIndex(const std::vector<size_t> &index,
const std::vector<size_t> &shape)
{
JET_ABORT_IF_NOT(index.size() == shape.size(),
"Number of index and shape dimensions must match.");
size_t multiplier = 1;
unsigned long long linear_index = 0;
for (int i = index.size() - 1; i >= 0; i--) {
JET_ABORT_IF(index[i] >= shape[i], "Index does not fit in the shape.");
linear_index += index[i] * multiplier;
multiplier *= shape[i];
}
return linear_index;
}
/**
* Splits `s` (at most once) on the given delimiter and stores the result in the
* provided vector. If an instance of the delimiter is found, the contents of
* `s` up to (and including) the first occurrence of the delimiter are erased.
*
* @param s String to be split.
* @param delimiter Delimeter separating each part of the split string.
* @param tokens Vector to store the result of the split.
*/
inline void SplitStringOnDelimiter(std::string &s, const std::string &delimiter,
std::vector<std::string> &tokens)
{
const size_t pos = s.find(delimiter);
if (pos == std::string::npos) {
tokens.emplace_back(s);
return;
}
const auto token = s.substr(0, pos);
tokens.emplace_back(token);
s.erase(0, pos + delimiter.length());
tokens.emplace_back(s);
}
/**
* Splits `s` (at most once) on each of the given delimiters (in order).
*
* @warning All spaces are removed from `s` prior to performing the split.
*
* @param s String to be split.
* @param delimiters Delimiters separating each part of the split string.
* @return Vector containing the result of the split (excluding empty tokens).
*/
inline std::vector<std::string>
SplitStringOnMultipleDelimiters(std::string s,
const std::vector<std::string> &delimiters)
{
// Remove spaces.
s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end());
std::vector<std::string> tokens = {s};
for (std::size_t i = 0; i < delimiters.size(); i++) {
tokens.pop_back();
SplitStringOnDelimiter(s, delimiters[i], tokens);
}
// Remove empty tokens.
const auto empty = [](const std::string &token) { return token.empty(); };
tokens.erase(std::remove_if(tokens.begin(), tokens.end(), empty),
tokens.end());
return tokens;
}
/**
* Splits `s` on the given delimiter (as many times as possible) and stores the
* result in the provided vector.
*
* @param s String to be split.
* @param delimiter Delimeter separating each part of the split string.
* @param tokens Vector to store the result of the split.
*/
inline void SplitStringOnDelimiterRecursively(const std::string &s,
const std::string &delimiter,
std::vector<std::string> &tokens)
{
const size_t pos = s.find(delimiter);
if (pos == std::string::npos) {
tokens.emplace_back(s);
}
else {
tokens.emplace_back(s.begin(), s.begin() + pos);
const auto remaining = s.substr(pos + delimiter.length());
SplitStringOnDelimiterRecursively(remaining, delimiter, tokens);
}
}
/**
* Replaces each occurrence of `from` with `to` in the given string.
*
* @param s String to be searched for occurrences of `from`.
* @param from Substring to be replaced in `s`.
* @param to Replacement string for `from`.
*/
inline void ReplaceAllInString(std::string &s, const std::string &from,
const std::string &to)
{
JET_ABORT_IF(from.empty(), "Cannot replace occurrences of an empty string");
size_t pos = s.find(from, 0);
while (pos != std::string::npos) {
s.replace(pos, from.length(), to);
// Skip over `to` in case part of it matches `from`.
pos = s.find(from, pos + to.length());
}
}
/**
* Returns the total amount of system memory as reported by /proc/meminfo.
*
* Adapted from
* https://github.com/Russellislam08/RAMLogger/blob/master/readproc.h
*
* @return Total amount of system memory (in kB).
* If an error occurs, -1 is returned.
*/
inline int GetTotalMemory()
{
FILE *meminfo = fopen("/proc/meminfo", "r");
if (meminfo == NULL) {
return -1;
}
char line[256];
while (fgets(line, sizeof(line), meminfo)) {
int memTotal;
if (sscanf(line, "MemTotal: %d kB", &memTotal) == 1) {
fclose(meminfo);
return memTotal;
}
}
// Getting here means we were not able to find what we were looking for
fclose(meminfo);
return -1;
}
/**
* Returns the amount of available system memory as reported by /proc/meminfo.
*
* @see GetTotalMemory()
*
* @return Amount of available system memory (in kB).
* If an error occurs, -1 is returned.
*/
inline int GetAvailableMemory()
{
/* Same function as above but it parses the meminfo file
in order to obtain the current amount of physical memory available
*/
FILE *meminfo = fopen("/proc/meminfo", "r");
if (meminfo == NULL) {
return -1;
}
char line[256];
while (fgets(line, sizeof(line), meminfo)) {
int memAvail;
if (sscanf(line, "MemAvailable: %d kB", &memAvail) == 1) {
fclose(meminfo);
return memAvail;
}
}
fclose(meminfo);
return -1;
}
/**
* Use OpenMP when available to copy
*
* @param a vector to copy
* @param b vector to copy to
*/
template <typename T> void FastCopy(const std::vector<T> &a, std::vector<T> &b)
{
#ifdef _OPENMP
size_t max_right_dim = 1024;
size_t size = a.size();
if (b.size() != size)
b.resize(size);
#pragma omp parallel for schedule(static, max_right_dim)
for (std::size_t p = 0; p < size; ++p) {
b[p] = a[p];
}
#else
b = a;
#endif
}
/**
* Determine if vector w contains v
*
* @param v
* @param w
*
* @return true if every element of v is in w
*/
template <typename T>
bool VectorInVector(const std::vector<T> &v, const std::vector<T> &w)
{
for (std::size_t i = 0; i < v.size(); ++i) {
if (!InVector(v[i], w))
return false;
}
return true;
}
}; // namespace Utilities
}; // namespace Jet
| 30.007092 | 80 | 0.623068 | XanaduAI |
1102642a3aa47a79509c1d3c1dc28d7df27dd909 | 76 | hh | C++ | MCDataProducts/inc/GenParticleCollection.hh | michaelmackenzie/Offline | 57bcd11d499af77ed0619deeddace51ed2b0b097 | [
"Apache-2.0"
] | null | null | null | MCDataProducts/inc/GenParticleCollection.hh | michaelmackenzie/Offline | 57bcd11d499af77ed0619deeddace51ed2b0b097 | [
"Apache-2.0"
] | 26 | 2019-11-08T09:56:55.000Z | 2020-09-09T17:25:33.000Z | MCDataProducts/inc/GenParticleCollection.hh | ryuwd/Offline | 92957f111425910274df61dbcbd2bad76885f993 | [
"Apache-2.0"
] | null | null | null | // redirection: FIXME!
#include "Offline/MCDataProducts/inc/GenParticle.hh"
| 25.333333 | 52 | 0.789474 | michaelmackenzie |
11055fd55298017876da7d5cb3b5b4b77dcb6f37 | 229 | cpp | C++ | Codeforces Rating < 1300/A_Word_Capitalization.cpp | Ritu7683/Codeforces-A20J-Ladder | eb9d54c20e2ab4f5eba06379258cf932a9b2d003 | [
"MIT"
] | 1 | 2021-09-15T08:48:10.000Z | 2021-09-15T08:48:10.000Z | Codeforces Rating < 1300/A_Word_Capitalization.cpp | Ritu7683/Codeforces-A20J-Ladder | eb9d54c20e2ab4f5eba06379258cf932a9b2d003 | [
"MIT"
] | null | null | null | Codeforces Rating < 1300/A_Word_Capitalization.cpp | Ritu7683/Codeforces-A20J-Ladder | eb9d54c20e2ab4f5eba06379258cf932a9b2d003 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long int
using namespace std;
int main() {
string s;
cin>>s;
if(s[0]>='a' && s[0]<='z') {
s[0]=toupper(s[0]);
cout<<s<<endl;
}
else
{
cout<<s<<endl;
}
return 0;
} | 12.722222 | 29 | 0.497817 | Ritu7683 |
1107c31cce77f11fbb647436998ceacf4e25fb8f | 54,434 | cpp | C++ | src/edcommon/model.cpp | GarethNelson/ares | fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e | [
"MIT"
] | null | null | null | src/edcommon/model.cpp | GarethNelson/ares | fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e | [
"MIT"
] | null | null | null | src/edcommon/model.cpp | GarethNelson/ares | fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e | [
"MIT"
] | null | null | null | /*
The MIT License
Copyright (c) 2011 by Jorrit Tyberghein
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 <crystalspace.h>
#include "edcommon/model.h"
#include "edcommon/tools.h"
#include "edcommon/uitools.h"
#include "edcommon/listctrltools.h"
#include "edcommon/customcontrol.h"
#include "editor/iuidialog.h"
#include <wx/wx.h>
#include <wx/imaglist.h>
#include <wx/listctrl.h>
#include <wx/treectrl.h>
#include <wx/listbox.h>
#include <wx/choicebk.h>
#include <wx/notebook.h>
#include <wx/xrc/xmlres.h>
namespace Ares
{
// --------------------------------------------------------------------------
Value* StandardValueIterator::NextChild (csString* name)
{
if (name && !names.IsEmpty ()) *name = names[idx];
idx++;
return children[idx-1];
}
// --------------------------------------------------------------------------
csString Value::Dump (bool verbose)
{
csString dump;
switch (GetType ())
{
case VALUE_STRING:
dump.Format ("V(string,'%s'%s)", GetStringValue (), parent ? ",[PAR]": "");
break;
case VALUE_STRINGARRAY:
dump.Format ("V(string[],''%s)", parent ? ",[PAR]": "");
break;
case VALUE_LONG:
dump.Format ("V(long,'%ld'%s)", GetLongValue (), parent ? ",[PAR]": "");
break;
case VALUE_BOOL:
dump.Format ("V(long,'%d'%s)", GetBoolValue (), parent ? ",[PAR]": "");
break;
case VALUE_FLOAT:
dump.Format ("V(float,'%g'%s)", GetFloatValue (), parent ? ",[PAR]": "");
break;
case VALUE_COLLECTION:
dump.Format ("V(collection%s)", parent ? ",[PAR]": "");
break;
case VALUE_COMPOSITE:
dump.Format ("V(composite%s)", parent ? ",[PAR]": "");
break;
case VALUE_NONE:
dump.Format ("V(none%s)", parent ? ",[PAR]": "");
break;
default:
dump.Format ("V(?%s)", parent ? ",[PAR]": "");
break;
}
if (verbose)
{
if (GetType () == VALUE_COLLECTION || GetType () == VALUE_COMPOSITE)
{
csRef<ValueIterator> it = GetIterator ();
while (it->HasNext ())
{
csString name;
Value* val = it->NextChild (&name);
dump.AppendFmt ("\n %s", (const char*)val->Dump (false));
}
}
}
return dump;
}
bool Value::IsChild (Value* value)
{
csRef<ValueIterator> it = GetIterator ();
while (it->HasNext ())
{
if (value == it->NextChild ()) return true;
}
return false;
}
// --------------------------------------------------------------------------
DialogResult AbstractCompositeValue::GetDialogValue ()
{
DialogResult result;
csRef<ValueIterator> it = GetIterator ();
while (it->HasNext ())
{
csString name;
Value* value = it->NextChild (&name);
result.Put (name, View::ValueToString (value));
}
return result;
}
void CompositeValue::AddChildren (ValueType type, ...)
{
va_list args;
va_start (args, type);
AddChildren (type, args);
va_end (args);
}
void CompositeValue::AddChildren (ValueType type, va_list args)
{
while (type != VALUE_NONE)
{
const char* name = va_arg (args, char*);
switch (type)
{
case VALUE_STRING:
{
const char* value = va_arg (args, char*);
AddChild (name, NEWREF(StringValue,new StringValue(value)));
break;
}
case VALUE_LONG:
{
long value = va_arg (args, long);
AddChild (name, NEWREF(LongValue,new LongValue(value)));
break;
}
case VALUE_FLOAT:
{
float value = va_arg (args, double);
AddChild (name, NEWREF(FloatValue,new FloatValue(value)));
break;
}
case VALUE_BOOL:
{
bool value = va_arg (args, int);
AddChild (name, NEWREF(BoolValue,new BoolValue(value)));
break;
}
case VALUE_STRINGARRAY:
{
const csStringArray* value = va_arg (args, csStringArray*);
AddChild (name, NEWREF(StringArrayValue,new StringArrayValue(*value)));
break;
}
case VALUE_COLLECTION:
case VALUE_COMPOSITE:
{
Value* value = va_arg (args, Value*);
AddChild (name, value);
break;
}
default:
break;
}
type = (ValueType) va_arg (args, int);
}
}
// --------------------------------------------------------------------------
CompositeValue* StandardCollectionValue::NewCompositeChild (ValueType type, ...)
{
va_list args;
va_start (args, type);
csRef<CompositeValue> composite = View::CreateComposite (type, args);
va_end (args);
children.Push (composite);
composite->SetParent (this);
return composite;
}
StringArrayValue* StandardCollectionValue::NewStringArrayChild (ValueType type, ...)
{
va_list args;
va_start (args, type);
csRef<StringArrayValue> stringarray = View::CreateStringArray (type, args);
va_end (args);
children.Push (stringarray);
stringarray->SetParent (this);
return stringarray;
}
void StandardCollectionValue::RemoveChild (Value* child)
{
children.Delete (child);
FireValueChanged ();
}
// --------------------------------------------------------------------------
void FilteredCollectionValue::UpdateFilter ()
{
filteredChildren.DeleteAll ();
if (!collection) return;
FilterSetup ();
csRef<ValueIterator> it = collection->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (Filter (child))
filteredChildren.Push (child);
}
}
// --------------------------------------------------------------------------
MirrorValue::MirrorValue (ValueType type) : type (type)
{
changeListener.AttachNew (new SelChangeListener (this));
mirroringValue = &nullValue;
}
MirrorValue::~MirrorValue ()
{
SetMirrorValue (0);
DeleteAll ();
}
void MirrorValue::SetupComposite (Value* compositeValue)
{
CS_ASSERT (compositeValue->GetType () == VALUE_COMPOSITE);
DeleteAll ();
csRef<ValueIterator> it = compositeValue->GetIterator ();
while (it->HasNext ())
{
csString name;
Value* child = it->NextChild (&name);
csRef<MirrorValue> mv;
mv.AttachNew (new MirrorValue (child->GetType ()));
AddChild (name, mv);
}
}
void MirrorValue::SetMirrorValue (Value* value)
{
if (mirroringValue == value) return;
if (mirroringValue && mirroringValue != &nullValue)
{
mirroringValue->RemoveValueChangeListener (changeListener);
for (size_t i = 0 ; i < children.GetSize () ; i++)
// @@@ (remove static_cast if children is again an array of MirrorValue
(static_cast<MirrorValue*> (children[i]))->SetMirrorValue (0);
}
mirroringValue = value;
if (mirroringValue)
{
mirroringValue->AddValueChangeListener (changeListener);
for (size_t i = 0 ; i < children.GetSize () ; i++)
// @@@ (remove static_cast if children is again an array of MirrorValue
(static_cast<MirrorValue*> (children[i]))->SetMirrorValue (value->GetChild (i));
}
else
mirroringValue = &nullValue;
}
void MirrorValue::ValueChanged ()
{
#if DO_DEBUG
printf ("ValueChanged: %s\n", Dump ().GetData ());
#endif
FireValueChanged ();
}
// --------------------------------------------------------------------------
class SelectedBoolValue : public BoolValue
{
private:
long* selection;
public:
SelectedBoolValue (long* s) : selection (s) { }
virtual ~SelectedBoolValue () { }
// Make sure this class doesn't cause crashes if the parent list
// selection value is removed.
void Invalidate () { selection = 0; }
virtual void SetBoolValue (bool fl) { }
virtual bool GetBoolValue ()
{
if (!selection) return false;
return (*selection != -1);
}
};
ListSelectedValue::ListSelectedValue (wxListCtrl* listCtrl, Value* collectionValue, ValueType type) :
wxEvtHandler (), MirrorValue (type), listCtrl (listCtrl),
collectionValue (collectionValue)
{
listCtrl->Connect (wxEVT_COMMAND_LIST_ITEM_SELECTED,
wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this);
listCtrl->Connect (wxEVT_COMMAND_LIST_ITEM_DESELECTED,
wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this);
selection = ListCtrlTools::GetFirstSelectedRow (listCtrl);
UpdateToSelection ();
}
ListSelectedValue::~ListSelectedValue ()
{
if (selectedStateValue) selectedStateValue->Invalidate ();
listCtrl->Disconnect (wxEVT_COMMAND_LIST_ITEM_SELECTED,
wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this);
listCtrl->Disconnect (wxEVT_COMMAND_LIST_ITEM_DESELECTED,
wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this);
}
void ListSelectedValue::UpdateToSelection ()
{
Value* value = 0;
if (selection != -1)
value = collectionValue->GetChild (size_t (selection));
if (value != GetMirrorValue ())
{
SetMirrorValue (value);
FireValueChanged ();
}
}
void ListSelectedValue::OnSelectionChange (wxCommandEvent& event)
{
long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl);
selection = idx;
#if DO_DEBUG
printf ("ListSelectedValue::OnSelectionChange: %s\n", Dump ().GetData ());
#endif
UpdateToSelection ();
if (selectedStateValue)
selectedStateValue->FireValueChanged ();
}
Value* ListSelectedValue::GetSelectedState ()
{
if (!selectedStateValue)
selectedStateValue.AttachNew (new SelectedBoolValue (&selection));
return selectedStateValue;
}
// --------------------------------------------------------------------------
TreeSelectedValue::TreeSelectedValue (wxTreeCtrl* treeCtrl, Value* collectionValue, ValueType type) :
MirrorValue (type), treeCtrl (treeCtrl), collectionValue (collectionValue)
{
treeCtrl->Connect (wxEVT_COMMAND_TREE_SEL_CHANGED,
wxCommandEventHandler (TreeSelectedValue :: OnSelectionChange), 0, this);
selection = treeCtrl->GetSelection ();
UpdateToSelection ();
}
TreeSelectedValue::~TreeSelectedValue ()
{
treeCtrl->Disconnect (wxEVT_COMMAND_TREE_SEL_CHANGED,
wxCommandEventHandler (TreeSelectedValue :: OnSelectionChange), 0, this);
}
/**
* Find a tree item corresponding with a given value.
*/
static wxTreeItemId TreeFromValue (wxTreeCtrl* tree, wxTreeItemId parent, Value* collectionValue, Value* value)
{
wxTreeItemIdValue cookie;
wxTreeItemId treeChild = tree->GetFirstChild (parent, cookie);
csRef<ValueIterator> it = collectionValue->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (value == child) return treeChild;
treeChild = TreeFromValue (tree, treeChild, child, value);
if (treeChild.IsOk ()) return treeChild;
treeChild = tree->GetNextChild (parent, cookie);
}
return wxTreeItemId();
}
/**
* Get a value corresponding with a given tree item.
*/
static Value* ValueFromTree (wxTreeCtrl* tree, wxTreeItemId item, Value* collectionValue)
{
wxTreeItemId parent = tree->GetItemParent (item);
if (parent.IsOk ())
{
Value* value = ValueFromTree (tree, parent, collectionValue);
if (!value) return 0; // Can this happen?
csString name = (const char*)tree->GetItemText (item).mb_str (wxConvUTF8);
csRef<ValueIterator> it = value->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (name == child->GetStringValue ())
return child;
}
return 0; // Can this happen?
}
else
{
return collectionValue;
}
}
void TreeSelectedValue::UpdateToSelection ()
{
Value* value = 0;
if (selection.IsOk ())
value = ValueFromTree (treeCtrl, selection, collectionValue);
if (value != GetMirrorValue ())
{
SetMirrorValue (value);
FireValueChanged ();
}
}
void TreeSelectedValue::OnSelectionChange (wxCommandEvent& event)
{
selection = treeCtrl->GetSelection ();
#if DO_DEBUG
printf ("TreeSelectedValue::OnSelectionChange: %s\n", Dump ().GetData ());
#endif
UpdateToSelection ();
}
// --------------------------------------------------------------------------
bool AbstractNewAction::DoDialog (View* view, wxWindow* component, iUIDialog* dialog,
bool update)
{
Value* origValue = 0;
if (dialog)
{
dialog->Clear ();
if (update)
{
origValue = view->GetSelectedValue (component);
if (!origValue)
update = false;
else
{
csString d = origValue->Dump (true);
printf ("%s\n", d.GetData ()); fflush (stdout);
dialog->SetFieldContents (origValue->GetDialogValue ());
}
}
if (dialog->Show (0) == 0) return false;
}
size_t idx = csArrayItemNotFound;
wxListCtrl* listCtrl = 0;
//wxTreeCtrl* treeCtrl = 0;
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
{
listCtrl = wxStaticCast (component, wxListCtrl);
idx = ListCtrlTools::GetFirstSelectedRow (listCtrl);
}
else if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
//treeCtrl = wxStaticCast (component, wxTreeCtrl);
}
DialogResult dialogResult;
if (dialog) dialogResult = dialog->GetFieldContents ();
if (update)
{
if (!collection->UpdateValue (idx, origValue, dialogResult))
return false;
view->SetSelectedValue (component, origValue);
}
else
{
Value* value = collection->NewValue (idx, view->GetSelectedValue (component),
dialogResult);
if (!value) return false;
view->SetSelectedValue (component, value);
}
return true;
}
bool NewChildAction::Do (View* view, wxWindow* component)
{
return DoDialog (view, component, 0);
}
NewChildDialogAction::NewChildDialogAction (Value* collection, iUIDialog* dialog) :
AbstractNewAction (collection), dialog (dialog)
{
}
NewChildDialogAction::~NewChildDialogAction ()
{
}
bool NewChildDialogAction::Do (View* view, wxWindow* component)
{
csRef<iUIDialog> dlg (scfQueryInterface<iUIDialog> (dialog));
return DoDialog (view, component, dlg);
}
EditChildDialogAction::EditChildDialogAction (Value* collection, iUIDialog* dialog) :
AbstractNewAction (collection), dialog (dialog)
{
}
EditChildDialogAction::~EditChildDialogAction ()
{
}
bool EditChildDialogAction::Do (View* view, wxWindow* component)
{
csRef<iUIDialog> dlg (scfQueryInterface<iUIDialog> (dialog));
return DoDialog (view, component, dlg, true);
}
bool EditChildDialogAction::IsActive (View* view, wxWindow* component)
{
return view->GetSelectedValue (component) != 0;
}
bool DeleteChildAction::Do (View* view, wxWindow* component)
{
Value* value = view->GetSelectedValue (component);
if (!value) return false; // Nothing to do.
return collection->DeleteValue (value);
}
bool DeleteChildAction::IsActive (View* view, wxWindow* component)
{
return view->GetSelectedValue (component) != 0;
}
// --------------------------------------------------------------------------
View::View (wxWindow* parent) : parent (parent), lastContextID (wxID_HIGHEST + 10000), eventHandler (this)
{
changeListener.AttachNew (new ViewChangeListener (this));
}
void View::Reset ()
{
DestroyBindings ();
DestroyActionBindings ();
lastContextID = wxID_HIGHEST + 10000;
bindings.DeleteAll ();
bindingsByComponent.DeleteAll ();
bindingsByValue.DeleteAll ();
disabledComponents.DeleteAll ();
changeListener = 0;
rmbContexts.DeleteAll ();
buttonActions.DeleteAll ();
listToHeading.DeleteAll ();
}
void View::DestroyBindings ()
{
ComponentToBinding::GlobalIterator it = bindingsByComponent.GetIterator ();
while (it.HasNext ())
{
csPtrKey<wxWindow> component;
Binding* binding = it.Next (component);
binding->value->RemoveValueChangeListener (changeListener);
if (binding->eventType == wxEVT_COMMAND_TEXT_UPDATED ||
binding->eventType == wxEVT_COMMAND_LIST_ITEM_SELECTED ||
binding->eventType == wxEVT_COMMAND_CHOICE_SELECTED ||
binding->eventType == wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED ||
binding->eventType == wxEVT_COMMAND_CHECKBOX_CLICKED)
component->Disconnect (binding->eventType,
wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler);
}
}
void View::RemoveBinding (wxWindow* component)
{
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding) return;
binding->value->RemoveValueChangeListener (changeListener);
if (binding->eventType == wxEVT_COMMAND_TEXT_UPDATED ||
binding->eventType == wxEVT_COMMAND_LIST_ITEM_SELECTED ||
binding->eventType == wxEVT_COMMAND_CHOICE_SELECTED ||
binding->eventType == wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED ||
binding->eventType == wxEVT_COMMAND_CHECKBOX_CLICKED)
component->Disconnect (binding->eventType,
wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler);
bindingsByComponent.Delete (component, binding);
bindingsByValue.Delete ((Value*)(binding->value), binding);
bindings.Delete (binding);
}
void View::DestroyActionBindings ()
{
while (rmbContexts.GetSize () > 0)
{
RmbContext lc = rmbContexts.Pop ();
lc.component->Disconnect (wxEVT_CONTEXT_MENU, wxContextMenuEventHandler (EventHandler :: OnRMB), 0, &eventHandler);
while (lc.actionDefs.GetSize () > 0)
{
ActionDef ad = lc.actionDefs.Pop ();
lc.component->Disconnect (ad.id, wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler);
}
}
csHash<csRef<Action>,csPtrKey<wxButton> >::GlobalIterator it = buttonActions.GetIterator ();
while (it.HasNext ())
{
csPtrKey<wxButton> button;
csRef<Action> action = it.Next (button);
button->Disconnect (wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler);
}
buttonActions.DeleteAll ();
}
View::~View ()
{
DestroyBindings ();
DestroyActionBindings ();
}
wxWindow* View::FindComponentByName (wxWindow* container, const char* name)
{
wxWindowList list = container->GetChildren ();
wxWindowList::iterator iter;
for (iter = list.begin (); iter != list.end () ; ++iter)
{
wxWindow* child = *iter;
csString childName = (const char*)child->GetName ().mb_str (wxConvUTF8);
if (childName == name) return child;
size_t i = childName.FindFirst ('_');
if (i != (size_t)-1)
{
childName = childName.Slice (0, i);
if (childName == name) return child;
}
wxWindow* found = FindComponentByName (child, name);
if (found) return found;
}
return 0;
}
bool View::BindEnabled (Value* value, wxWindow* component)
{
RegisterBinding (value, component, wxEVT_NULL, true);
ValueChanged (value);
return true;
}
bool View::BindEnabled (Value* value, const char* compName)
{
//wxString wxcompName = wxString::FromUTF8 (compName);
//wxWindow* comp = parent->FindWindow (wxcompName);
wxWindow* comp = FindComponentByName (parent, compName);
if (!comp)
{
printf ("BindEnabled: Can't find component '%s'!\n", compName);
return false;
}
return BindEnabled (value, comp);
}
bool View::Bind (Value* value, wxWindow* component)
{
if (component->IsKindOf (CLASSINFO (wxTextCtrl)))
return Bind (value, wxStaticCast (component, wxTextCtrl));
if (component->IsKindOf (CLASSINFO (wxChoice)))
return Bind (value, wxStaticCast (component, wxChoice));
if (component->IsKindOf (CLASSINFO (wxComboBox)))
return Bind (value, wxStaticCast (component, wxComboBox));
if (component->IsKindOf (CLASSINFO (wxCheckBox)))
return Bind (value, wxStaticCast (component, wxCheckBox));
if (component->IsKindOf (CLASSINFO (wxPanel)))
return Bind (value, wxStaticCast (component, wxPanel));
if (component->IsKindOf (CLASSINFO (wxDialog)))
return Bind (value, wxStaticCast (component, wxDialog));
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
return Bind (value, wxStaticCast (component, wxListCtrl));
if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
return Bind (value, wxStaticCast (component, wxTreeCtrl));
if (component->IsKindOf (CLASSINFO (wxChoicebook)))
return Bind (value, wxStaticCast (component, wxChoicebook));
CustomControl* customComp (dynamic_cast<CustomControl*> (component));
if (customComp)
return Bind (value, customComp);
csString compName = (const char*)component->GetName ().mb_str (wxConvUTF8);
printf ("Bind: Unsupported type for component '%s'!\n", compName.GetData ());
return false;
}
bool View::Bind (Value* value, const char* compName)
{
//wxString wxcompName = wxString::FromUTF8 (compName);
//wxWindow* comp = parent->FindWindow (wxcompName);
wxWindow* comp = FindComponentByName (parent, compName);
if (!comp)
{
printf ("Bind: Can't find component '%s'!\n", compName);
return false;
}
return Bind (value, comp);
}
void View::RegisterBinding (Value* value, wxWindow* component, wxEventType eventType,
bool changeEnabled)
{
Binding* b = new Binding ();
b->value = value;
b->component = component;
b->eventType = eventType;
b->changeEnabled = changeEnabled;
if (!changeEnabled)
bindingsByComponent.Put (component, b);
bindingsByValue.Put (value, b);
if (eventType != wxEVT_NULL)
component->Connect (eventType, wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler);
value->AddValueChangeListener (changeListener);
}
bool View::Bind (Value* value, wxChoice* component)
{
switch (value->GetType ())
{
case VALUE_STRING:
case VALUE_LONG:
case VALUE_BOOL:
case VALUE_FLOAT:
case VALUE_NONE: // Supported too in case the type is as of yet unknown.
break;
default:
printf ("Unsupported value type for choice control!\n");
return false;
}
RegisterBinding (value, component, wxEVT_COMMAND_CHOICE_SELECTED);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxTextCtrl* component)
{
switch (value->GetType ())
{
case VALUE_STRING:
case VALUE_LONG:
case VALUE_BOOL:
case VALUE_FLOAT:
case VALUE_NONE: // Supported too in case the type is as of yet unknown.
break;
default:
printf ("Unsupported value type for text control!\n");
return false;
}
RegisterBinding (value, component, wxEVT_COMMAND_TEXT_UPDATED);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxComboBox* component)
{
switch (value->GetType ())
{
case VALUE_STRING:
case VALUE_LONG:
case VALUE_BOOL:
case VALUE_FLOAT:
case VALUE_NONE: // Supported too in case the type is as of yet unknown.
break;
default:
printf ("Unsupported value type for text control!\n");
return false;
}
RegisterBinding (value, component, wxEVT_COMMAND_TEXT_UPDATED);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxCheckBox* component)
{
switch (value->GetType ())
{
case VALUE_STRING:
case VALUE_LONG:
case VALUE_BOOL:
case VALUE_FLOAT:
case VALUE_NONE: // Supported too in case the type is as of yet unknown.
break;
default:
printf ("Unsupported value type for checkbox!\n");
return false;
}
RegisterBinding (value, component, wxEVT_COMMAND_CHECKBOX_CLICKED);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, CustomControl* component)
{
RegisterBinding (value, component, wxEVT_NULL);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxChoicebook* component)
{
switch (value->GetType ())
{
case VALUE_STRING:
case VALUE_LONG:
case VALUE_NONE: // Supported too in case the type is as of yet unknown.
break;
default:
printf ("Unsupported value type for text control!\n");
return false;
}
RegisterBinding (value, component, wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED);
ValueChanged (value);
return true;
}
bool View::BindContainer (Value* value, wxWindow* component)
{
// We also support VALUE_NONE here because that can be useful in situations where we don't
// know the type yet (for example when the value is a ListSelectedValue and nothing has been
// selected).
if (value->GetType () != VALUE_COMPOSITE && value->GetType () != VALUE_NONE)
{
printf ("Unsupported value type for panels! Only VALUE_COMPOSITE is supported.\n");
return false;
}
csString compName = (const char*)component->GetName ().mb_str (wxConvUTF8);
RegisterBinding (value, component, wxEVT_NULL);
csRef<ValueIterator> it = value->GetIterator ();
while (it->HasNext ())
{
csString name;
Value* child = it->NextChild (&name);
wxWindow* childComp = FindComponentByName (component, name);
if (!childComp)
{
printf ("Warning: no component found for child '%s'!\n", name.GetData ());
}
else
{
compName = (const char*)childComp->GetName ().mb_str (wxConvUTF8);
if (!Bind (child, childComp))
return false;
}
}
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxDialog* component)
{
return BindContainer (value, component);
}
bool View::Bind (Value* value, wxPanel* component)
{
return BindContainer (value, component);
}
bool View::Bind (Value* value, wxListCtrl* component)
{
// We also support VALUE_NONE here because that can be useful in situations where we don't
// know the type yet (for example when the value is a ListSelectedValue and nothing has been
// selected).
if (value->GetType () != VALUE_COLLECTION && value->GetType () != VALUE_NONE)
{
printf ("Unsupported value type for lists! Only VALUE_COLLECTION is supported.\n");
return false;
}
RegisterBinding (value, component, wxEVT_NULL);
ValueChanged (value);
return true;
}
bool View::Bind (Value* value, wxTreeCtrl* component)
{
// We also support VALUE_NONE here because that can be useful in situations where we don't
// know the type yet (for example when the value is a ListSelectedValue and nothing has been
// selected).
if (value->GetType () != VALUE_COLLECTION && value->GetType () != VALUE_NONE)
{
printf ("Unsupported value type for trees! Only VALUE_COLLECTION is supported.\n");
return false;
}
RegisterBinding (value, component, wxEVT_NULL);
ValueChanged (value);
return true;
}
static bool ValueToBoolStatic (Value* value)
{
switch (value->GetType ())
{
case VALUE_STRING:
{
const char* v = value->GetStringValue ();
return v && *v == 't';
}
case VALUE_LONG:
return bool (value->GetLongValue ());
case VALUE_BOOL:
return value->GetBoolValue ();
case VALUE_FLOAT:
return fabs (value->GetFloatValue ()) > .000001f;
case VALUE_STRINGARRAY:
return value->GetStringArrayValue () && !value->GetStringArrayValue ()->IsEmpty ();
case VALUE_COLLECTION:
case VALUE_COMPOSITE:
{
csRef<ValueIterator> it = value->GetIterator ();
return it->HasNext ();
}
default:
return false;
}
}
bool View::ValueToBool (Value* value)
{
return ValueToBoolStatic (value);
}
csString View::ValueToString (Value* value)
{
csString val;
switch (value->GetType ())
{
case VALUE_STRING: return csString (value->GetStringValue ());
case VALUE_LONG: val.Format ("%ld", value->GetLongValue ()); return val;
case VALUE_BOOL: return csString (value->GetBoolValue () ? "true" : "false");
case VALUE_FLOAT: val.Format ("%g", value->GetFloatValue ()); return val;
case VALUE_STRINGARRAY: return csString("<stringarray>");
case VALUE_COLLECTION: return csString ("<collection>");
case VALUE_COMPOSITE: return csString ("<composite>");
default: return csString ("<?>");
}
}
void View::LongToValue (long l, Value* value)
{
csString str;
switch (value->GetType ())
{
case VALUE_STRING:
str.Format ("%ld", l);
value->SetStringValue (str);
return;
case VALUE_LONG:
value->SetLongValue (l);
return;
case VALUE_BOOL:
value->SetBoolValue (bool (l));
return;
case VALUE_FLOAT:
value->SetFloatValue (float (l));
return;
case VALUE_STRINGARRAY: return;
case VALUE_COLLECTION: return;
case VALUE_COMPOSITE: return;
default: return;
}
}
void View::BoolToValue (bool in, Value* value)
{
switch (value->GetType ())
{
case VALUE_STRING:
value->SetStringValue (in ? "true" : "false");
return;
case VALUE_LONG:
value->SetLongValue (long (in));
return;
case VALUE_BOOL:
value->SetBoolValue (in);
return;
case VALUE_FLOAT:
value->SetFloatValue (float (in));
return;
case VALUE_STRINGARRAY: return;
case VALUE_COLLECTION: return;
case VALUE_COMPOSITE: return;
default: return;
}
}
void View::StringToValue (const char* str, Value* value)
{
switch (value->GetType ())
{
case VALUE_STRING:
value->SetStringValue (str);
return;
case VALUE_LONG:
{
long l;
csScanStr (str, "%d", &l);
value->SetLongValue (l);
return;
}
case VALUE_BOOL:
{
bool l;
csScanStr (str, "%b", &l);
value->SetBoolValue (l);
return;
}
case VALUE_FLOAT:
{
float l;
csScanStr (str, "%f", &l);
value->SetFloatValue (l);
return;
}
case VALUE_STRINGARRAY: return;
case VALUE_COLLECTION: return;
case VALUE_COMPOSITE: return;
default: return;
}
}
Value* View::FindChild (Value* collection, const char* str)
{
csRef<ValueIterator> it = collection->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (ValueToString (child) == str)
return child;
}
return 0;
}
csRef<CompositeValue> View::CreateComposite (ValueType type, va_list args)
{
csRef<CompositeValue> composite = NEWREF(CompositeValue,new CompositeValue());
composite->AddChildren (type, args);
return composite;
}
csRef<CompositeValue> View::CreateComposite (ValueType type, ...)
{
va_list args;
va_start (args, type);
csRef<CompositeValue> value = CreateComposite (type, args);
va_end (args);
return value;
}
csRef<StringArrayValue> View::CreateStringArray (ValueType type, va_list args)
{
csRef<StringArrayValue> stringarray = NEWREF(StringArrayValue,new StringArrayValue());
csStringArray& array = stringarray->GetArray ();
while (type != VALUE_NONE)
{
switch (type)
{
case VALUE_STRING:
{
const char* value = va_arg (args, char*);
array.Push (value);
break;
}
case VALUE_LONG:
{
long value = va_arg (args, long);
csString fmt;
fmt.Format ("%ld", value);
array.Push (fmt);
break;
}
case VALUE_BOOL:
{
bool value = va_arg (args, int);
csString fmt;
fmt.Format ("%d", int (value));
array.Push (fmt);
break;
}
case VALUE_FLOAT:
{
float value = va_arg (args, double);
csString fmt;
fmt.Format ("%g", value);
array.Push (fmt);
break;
}
default:
array.Push ("<?>");
break;
}
type = (ValueType) va_arg (args, int);
}
return stringarray;
}
csRef<StringArrayValue> View::CreateStringArray (ValueType type, ...)
{
va_list args;
va_start (args, type);
csRef<StringArrayValue> value = CreateStringArray (type, args);
va_end (args);
return value;
}
csStringArray View::ConstructListRow (const ListHeading& lh, Value* value)
{
csStringArray row;
ValueType t = value->GetType ();
if (t == VALUE_STRINGARRAY)
{
const csStringArray* array = value->GetStringArrayValue ();
if (!array) return row;
for (size_t i = 0 ; i < lh.heading.GetSize () ; i++)
{
csString el = array->Get (lh.indices[i]);
row.Push (el);
}
}
else if (t == VALUE_COMPOSITE)
{
for (size_t i = 0 ; i < lh.names.GetSize () ; i++)
{
Value* child = value->GetChildByName (lh.names[i]);
if (child)
row.Push (ValueToString (child));
else
{
printf ("Warning: child '%s' is missing!\n", (const char*)lh.names[i]);
row.Push ("");
}
}
}
else
{
row.Push (ValueToString (value));
}
return row;
}
size_t View::FindRmbContext (wxWindow* component)
{
for (size_t i = 0 ; i < rmbContexts.GetSize () ; i++)
if (rmbContexts[i].component == component)
return i;
return csArrayItemNotFound;
}
void View::OnRMB (wxContextMenuEvent& event)
{
wxWindow* component = wxStaticCast (event.GetEventObject (), wxWindow);
size_t idx = FindRmbContext (component);
if (idx == csArrayItemNotFound)
{
// We also try the parent since when the list is empty we apparently get
// a child of the list instead of the list itself.
component = component->GetParent ();
if (component == 0) return;
idx = FindRmbContext (component);
if (idx == csArrayItemNotFound) return;
}
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
{
wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl);
bool hasItem;
if (!ListCtrlTools::CheckHitList (listCtrl, hasItem, event.GetPosition ()))
return;
}
else if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl);
if (!treeCtrl->IsShownOnScreen ()) return;
int flags = 0;
wxTreeItemId idx = treeCtrl->HitTest (treeCtrl->ScreenToClient (event.GetPosition ()), flags);
if (!idx.IsOk())
{
if (!treeCtrl->GetScreenRect ().Contains (event.GetPosition ()))
return;
}
else treeCtrl->SelectItem (idx);
}
const RmbContext& lc = rmbContexts[idx];
wxMenu contextMenu;
for (size_t j = 0 ; j < lc.actionDefs.GetSize () ; j++)
{
Action* action = lc.actionDefs[j].action;
wxMenuItem* item = contextMenu.Append (lc.actionDefs[j].id,
wxString::FromUTF8 (action->GetName ()));
bool active = action->IsActive (this, component);
item->Enable (active);
}
component->PopupMenu (&contextMenu);
}
void View::OnActionExecuted (wxCommandEvent& event)
{
int id = event.GetId ();
// We have to scan all lists here to find the one that has the right id.
for (size_t i = 0 ; i < rmbContexts.GetSize () ; i++)
{
const RmbContext& lc = rmbContexts[i];
for (size_t j = 0 ; j < lc.actionDefs.GetSize () ; j++)
if (lc.actionDefs[j].id == id)
{
lc.actionDefs[j].action->Do (this, lc.component);
return;
}
}
// Scan all buttons if we didn't find a list.
csHash<csRef<Action>,csPtrKey<wxButton> >::GlobalIterator it = buttonActions.GetIterator ();
while (it.HasNext ())
{
csPtrKey<wxButton> button;
csRef<Action> action = it.Next (button);
if (button == event.GetEventObject ())
{
action->Do (this, button);
return;
}
}
}
void View::OnComponentChanged (wxCommandEvent& event)
{
wxWindow* component = wxStaticCast (event.GetEventObject (), wxWindow);
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding)
{
printf ("OnComponentChanged: Something went wrong! Called without a value!\n");
return;
}
if (binding->processing) return;
binding->processing = true;
#if DO_DEBUG
printf ("View::OnComponentChanged: %s\n", binding->value->Dump ().GetData ());
#endif
if (component->IsKindOf (CLASSINFO (wxTextCtrl)))
{
wxTextCtrl* textCtrl = wxStaticCast (component, wxTextCtrl);
csString text = (const char*)textCtrl->GetValue ().mb_str (wxConvUTF8);
StringToValue (text, binding->value);
}
else if (component->IsKindOf (CLASSINFO (wxChoice)))
{
wxChoice* choiceCtrl = wxStaticCast (component, wxChoice);
csString text = (const char*)choiceCtrl->GetStringSelection ().mb_str (wxConvUTF8);
StringToValue (text, binding->value);
}
else if (component->IsKindOf (CLASSINFO (wxComboBox)))
{
wxComboBox* combo = wxStaticCast (component, wxComboBox);
csString text = (const char*)combo->GetValue ().mb_str (wxConvUTF8);
StringToValue (text, binding->value);
}
else if (component->IsKindOf (CLASSINFO (wxCheckBox)))
{
wxCheckBox* checkBox = wxStaticCast (component, wxCheckBox);
BoolToValue (checkBox->GetValue (), binding->value);
}
else if (component->IsKindOf (CLASSINFO (wxChoicebook)))
{
wxChoicebook* choicebook = wxStaticCast (component, wxChoicebook);
int pageSel = choicebook->GetSelection ();
if (binding->value->GetType () == VALUE_LONG)
LongToValue ((long)pageSel, binding->value);
else
{
csString value;
if (pageSel == wxNOT_FOUND) value = "";
else
{
wxString pageTxt = choicebook->GetPageText (pageSel);
value = (const char*)pageTxt.mb_str (wxConvUTF8);
}
StringToValue (value, binding->value);
}
}
else
{
printf ("OnComponentChanged: this type of component not yet supported!\n");
}
binding->processing = false;
}
void View::BuildTree (wxTreeCtrl* treeCtrl, Value* value, wxTreeItemId& parent)
{
csRef<ValueIterator> it = value->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
wxTreeItemId itemId = treeCtrl->AppendItem (parent, wxString::FromUTF8 (child->GetStringValue ()));
BuildTree (treeCtrl, child, itemId);
}
}
void View::UpdateTree (wxTreeCtrl* treeCtrl, Value* value, wxTreeItemId& parent)
{
csRef<ValueIterator> it = value->GetIterator ();
wxTreeItemIdValue cookie;
wxTreeItemId itemId = treeCtrl->GetFirstChild (parent, cookie);
bool addingnew = false; // Set to true as soon as we're adding new items ourselves.
while (it->HasNext ())
{
Value* child = it->NextChild ();
wxString newLabel = wxString::FromUTF8 (child->GetStringValue ());
if ((!addingnew) && itemId.IsOk ())
{
wxString currentLabel = treeCtrl->GetItemText (itemId);
if (currentLabel != newLabel)
{
treeCtrl->SetItemText (itemId, newLabel);
}
UpdateTree (treeCtrl, child, itemId);
itemId = treeCtrl->GetNextChild (parent, cookie);
}
else
{
itemId = treeCtrl->AppendItem (parent, newLabel);
UpdateTree (treeCtrl, child, itemId);
addingnew = true;
}
}
if (!addingnew)
{
// Might have to remove stuff.
csArray<wxTreeItemId> toRemove;
while (itemId.IsOk ())
{
toRemove.Push (itemId);
itemId = treeCtrl->GetNextChild (parent, cookie);
}
for (size_t i = 0 ; i < toRemove.GetSize () ; i++)
treeCtrl->Delete (toRemove[i]);
}
}
bool View::IsValueBound (Value* value) const
{
ValueToBinding::ConstIterator it = bindingsByValue.GetIterator (value);
return it.HasNext ();
}
bool View::CheckIfParentDisabled (wxWindow* window)
{
window = window->GetParent ();
while (window)
{
if (window == parent) return false;
if (disabledComponents.In (window)) return true;
if (window->IsEnabled () == false) return true;
window = window->GetParent ();
}
return false;
}
void View::EnableBoundComponents (wxWindow* comp, bool state)
{
if (state)
disabledComponents.Delete (comp);
else
disabledComponents.Add (comp);
bool parentDisabled = CheckIfParentDisabled (comp);
if (parentDisabled) state = false;
EnableBoundComponentsInt (comp, state);
}
void View::EnableBoundComponentsInt (wxWindow* comp, bool state)
{
if (comp->IsKindOf (CLASSINFO (wxPanel)) ||
comp->IsKindOf (CLASSINFO (wxDialog)))
{
if (disabledComponents.In (comp))
state = false;
wxWindowList list = comp->GetChildren ();
wxWindowList::iterator iter;
for (iter = list.begin (); iter != list.end () ; ++iter)
{
wxWindow* child = *iter;
EnableBoundComponentsInt (child, state);
}
}
else
{
Binding* binding = bindingsByComponent.Get (comp, 0);
if (binding)
{
if (!state)
comp->Enable (state);
else if (!disabledComponents.In (comp))
comp->Enable (state);
}
}
}
void View::ValueChanged (Value* value)
{
#if DO_DEBUG
printf ("View::ValueChanged: %s\n", value->Dump ().GetData ());
#endif
ValueToBinding::Iterator it = bindingsByValue.GetIterator (value);
if (!it.HasNext ())
{
printf ("ValueChanged: Something went wrong! Called without a valid binding!\n");
CS_ASSERT (false);
return;
}
while (it.HasNext ())
{
Binding* b = it.Next ();
wxWindow* comp = b->component;
if (b->changeEnabled)
{
// Modify disabled/enabled state instead of value.
bool state = ValueToBool (value);
EnableBoundComponents (comp, state);
continue;
}
if (!b->processing)
{
CustomControl* customCtrl;
if (comp->IsKindOf (CLASSINFO (wxTextCtrl)))
{
b->processing = true;
wxTextCtrl* textCtrl = wxStaticCast (comp, wxTextCtrl);
csString text = ValueToString (value);
textCtrl->SetValue (wxString::FromUTF8 (text));
b->processing = false;
}
else if (comp->IsKindOf (CLASSINFO (wxChoice)))
{
b->processing = true;
wxChoice* choiceCtrl = wxStaticCast (comp, wxChoice);
csString text = ValueToString (value);
choiceCtrl->SetStringSelection (wxString::FromUTF8 (text));
b->processing = false;
}
else if (comp->IsKindOf (CLASSINFO (wxComboBox)))
{
b->processing = true;
wxComboBox* combo = wxStaticCast (comp, wxComboBox);
csString text = ValueToString (value);
combo->SetValue (wxString::FromUTF8 (text));
b->processing = false;
}
else if (comp->IsKindOf (CLASSINFO (wxCheckBox)))
{
b->processing = true;
wxCheckBox* checkBox = wxStaticCast (comp, wxCheckBox);
bool in = ValueToBool (value);
checkBox->SetValue (in);
b->processing = false;
}
else if ((customCtrl = dynamic_cast<CustomControl*> (comp)))
{
customCtrl->SyncValue (value);
}
else if (comp->IsKindOf (CLASSINFO (wxPanel)) ||
comp->IsKindOf (CLASSINFO (wxDialog)))
{
// If the value of a composite changes we update the children.
csRef<ValueIterator> it = value->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (IsValueBound (child))
ValueChanged (child);
}
}
else if (comp->IsKindOf (CLASSINFO (wxListCtrl)))
{
//csString compName = (const char*)comp->GetName ().mb_str (wxConvUTF8);
//printf ("ValueChanged for component '%s'\n", compName.GetData ()); fflush (stdout);
wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl);
long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl);
listCtrl->Freeze ();
listCtrl->DeleteAllItems ();
ListHeading lhdef;
const ListHeading& lh = listToHeading.Get (listCtrl, lhdef);
csRef<ValueIterator> it = value->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
ListCtrlTools::AddRow (listCtrl, ConstructListRow (lh, child));
}
if (idx != -1)
ListCtrlTools::SelectRow (listCtrl, idx, true);
listCtrl->Thaw ();
}
else if (comp->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
wxTreeCtrl* treeCtrl = wxStaticCast (comp, wxTreeCtrl);
treeCtrl->Freeze ();
wxTreeItemId rootId = treeCtrl->GetRootItem ();
if (rootId.IsOk ())
{
UpdateTree (treeCtrl, value, rootId);
}
else
{
treeCtrl->DeleteAllItems ();
rootId = treeCtrl->AddRoot (wxString::FromUTF8 (value->GetStringValue ()));
BuildTree (treeCtrl, value, rootId);
}
treeCtrl->Thaw ();
}
else if (comp->IsKindOf (CLASSINFO (wxChoicebook)))
{
wxChoicebook* choicebook = wxStaticCast (comp, wxChoicebook);
if (value->GetType () == VALUE_LONG)
choicebook->ChangeSelection (value->GetLongValue ());
else
{
csString text = ValueToString (value);
wxString wxtext = wxString::FromUTF8 (text);
for (size_t i = 0 ; i < choicebook->GetPageCount () ; i++)
{
wxString wxp = choicebook->GetPageText (i);
if (wxp == wxtext)
{
choicebook->ChangeSelection (i);
return;
}
}
// If we come here we set to the first page.
choicebook->SetSelection (0);
}
}
else
{
printf ("ValueChanged: this type of component not yet supported!\n");
}
}
}
}
bool View::DefineHeading (const char* listName, const char* heading,
const char* names)
{
wxString wxlistName = wxString::FromUTF8 (listName);
wxWindow* comp = parent->FindWindow (wxlistName);
if (!comp)
{
printf ("DefineHeading: Can't find component '%s'!\n", listName);
return false;
}
if (!comp->IsKindOf (CLASSINFO (wxListCtrl)))
{
printf ("DefineHeading: Component '%s' is not a list control!\n", listName);
return false;
}
wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl);
return DefineHeading (listCtrl, heading, names);
}
bool View::DefineHeading (wxListCtrl* listCtrl, const char* heading,
const char* names)
{
ListHeading lh;
lh.heading.SplitString (heading, ",");
lh.names.SplitString (names, ",");
for (size_t i = 0 ; i < lh.heading.GetSize () ; i++)
ListCtrlTools::SetColumn (listCtrl, i, lh.heading[i], 100);
listToHeading.Put (listCtrl, lh);
return true;
}
bool View::DefineHeadingIndexed (const char* listName, const char* heading, ...)
{
wxString wxlistName = wxString::FromUTF8 (listName);
wxWindow* comp = parent->FindWindow (wxlistName);
if (!comp)
{
printf ("DefineHeading: Can't find component '%s'!\n", listName);
return false;
}
if (!comp->IsKindOf (CLASSINFO (wxListCtrl)))
{
printf ("DefineHeading: Component '%s' is not a list control!\n", listName);
return false;
}
wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl);
va_list args;
va_start (args, heading);
bool rc = DefineHeadingIndexed (listCtrl, heading, args);
va_end (args);
return rc;
}
bool View::DefineHeadingIndexed (wxListCtrl* listCtrl, const char* heading, ...)
{
va_list args;
va_start (args, heading);
bool rc = DefineHeadingIndexed (listCtrl, heading, args);
va_end (args);
return rc;
}
bool View::DefineHeadingIndexed (wxListCtrl* listCtrl, const char* heading, va_list args)
{
ListHeading lh;
lh.heading.SplitString (heading, ",");
for (size_t i = 0 ; i < lh.heading.GetSize () ; i++)
{
int index = va_arg (args, int);
lh.indices.Push (index);
ListCtrlTools::SetColumn (listCtrl, i, lh.heading[i], 100);
}
listToHeading.Put (listCtrl, lh);
return true;
}
bool View::AddAction (const char* compName, Action* action)
{
wxString wxcompName = wxString::FromUTF8 (compName);
wxWindow* comp = parent->FindWindow (wxcompName);
if (!comp)
{
printf ("AddAction: Can't find component '%s'!\n", compName);
return false;
}
return AddAction (comp, action);
}
bool View::AddAction (wxWindow* component, Action* action)
{
if (component->IsKindOf (CLASSINFO (wxButton)))
return AddAction (wxStaticCast (component, wxButton), action);
if (component->IsKindOf (CLASSINFO (wxListCtrl)) || component->IsKindOf (CLASSINFO (wxTreeCtrl)))
return AddContextAction (component, action);
printf ("AddAction: Unsupported type for component!\n");
return false;
}
bool View::AddContextAction (wxWindow* component, Action* action)
{
component->Connect (lastContextID, wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler);
size_t idx = FindRmbContext (component);
if (idx == csArrayItemNotFound)
{
RmbContext lc;
lc.component = component;
idx = rmbContexts.Push (lc);
component->Connect (wxEVT_CONTEXT_MENU, wxContextMenuEventHandler (EventHandler :: OnRMB), 0, &eventHandler);
}
RmbContext& lc = rmbContexts[idx];
ActionDef ad;
ad.id = lastContextID;
ad.action = action;
lc.actionDefs.Push (ad);
lastContextID++;
return true;
}
bool View::AddAction (wxButton* button, Action* action)
{
button->Connect (wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler);
buttonActions.Put (button, action);
wxString wxlabel = wxString::FromUTF8 (action->GetName ());
button->SetLabel (wxlabel);
return true;
}
bool View::SetSelectedValue (wxWindow* component, Value* value)
{
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding)
{
printf ("SetSelectedValue: Component is not bound to a value!\n");
return false;
}
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
{
wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl);
csRef<ValueIterator> it = binding->value->GetIterator ();
bool found = false;
size_t idx = 0;
while (it->HasNext ())
{
Value* child = it->NextChild ();
if (child == value) { found = true; break; }
idx++;
}
if (found)
{
ListCtrlTools::SelectRow (listCtrl, idx, true);
return true;
}
return false;
}
if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl);
wxTreeItemId child = TreeFromValue (treeCtrl, treeCtrl->GetRootItem (),
binding->value, value);
if (child.IsOk ())
{
treeCtrl->SelectItem (child);
return true;
}
return false;
}
printf ("SetSelectedValue: Unsupported type for component!\n");
return false;
}
Value* View::GetValue (wxWindow* component)
{
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding) return 0;
return binding->value;
}
Value* View::GetSelectedValue (wxWindow* component)
{
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding)
{
printf ("GetSelectedValue: Component is not bound to a value!\n");
return 0;
}
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
{
wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl);
long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl);
if (idx < 0) return 0;
return binding->value->GetChild (size_t (idx));
}
if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl);
wxTreeItemId selection = treeCtrl->GetSelection ();
if (selection.IsOk ())
return ValueFromTree (treeCtrl, selection, binding->value);
else
return 0;
}
printf ("GetSelectedValue: Unsupported type for component!\n");
return 0;
}
csArray<Value*> View::GetSelectedValues (wxWindow* component)
{
Binding* binding = bindingsByComponent.Get (component, 0);
if (!binding)
{
printf ("GetSelectedValue: Component is not bound to a value!\n");
return 0;
}
csArray<Value*> values;
if (component->IsKindOf (CLASSINFO (wxListCtrl)))
{
wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl);
csArray<long> indices = ListCtrlTools::GetSelectedRowIndices (listCtrl);
for (size_t i = 0 ; i < indices.GetSize () ; i++)
values.Push (binding->value->GetChild (size_t (indices[i])));
return values;
}
if (component->IsKindOf (CLASSINFO (wxTreeCtrl)))
{
wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl);
wxTreeItemId selection = treeCtrl->GetSelection ();
// @@@ Only support first selection for now.
if (selection.IsOk ())
values.Push (ValueFromTree (treeCtrl, selection, binding->value));
return values;
}
printf ("GetSelectedValue: Unsupported type for component!\n");
return 0;
}
class SignalChangeListener : public ValueChangeListener
{
private:
csRef<Value> source;
csRef<Value> dest;
bool dochildren;
public:
SignalChangeListener (Value* source, Value* dest, bool dochildren) :
source (source), dest (dest), dochildren (dochildren) { }
virtual ~SignalChangeListener () { }
virtual void ValueChanged (Value* value)
{
// printf ("SIGNAL: from %s to %s\n", source->Dump ().GetData (), dest->Dump ().GetData ());
dest->FireValueChanged ();
if (dochildren)
{
csRef<ValueIterator> it = dest->GetIterator ();
while (it->HasNext ())
{
Value* child = it->NextChild ();
// printf (" FIRE: to %s\n", child->Dump ().GetData ());
child->FireValueChanged ();
}
}
}
};
void View::Signal (Value* source, Value* dest, bool dochildren)
{
csRef<SignalChangeListener> listener;
listener.AttachNew (new SignalChangeListener (source, dest, dochildren));
source->AddValueChangeListener (listener);
}
class NotValue : public BoolValue
{
private:
csRef<Value> value;
public:
NotValue (Value* value) : value (value) { }
virtual ~NotValue () { }
virtual void SetBoolValue (bool fl) { }
virtual bool GetBoolValue ()
{
return !ValueToBoolStatic (value);
}
};
csRef<Value> View::Not (Value* value)
{
csRef<Value> v;
v.AttachNew (new NotValue (value));
csRef<StandardChangeListener> changeListener;
changeListener.AttachNew (new StandardChangeListener (v));
value->AddValueChangeListener (changeListener);
return v;
}
class AndValue : public BoolValue
{
private:
csRef<Value> value1, value2;
public:
AndValue (Value* value1, Value* value2) : value1 (value1), value2 (value2) { }
virtual ~AndValue () { }
virtual void SetBoolValue (bool fl) { }
virtual bool GetBoolValue ()
{
return ValueToBoolStatic (value1) && ValueToBoolStatic (value2);
}
};
csRef<Value> View::And (Value* value1, Value* value2)
{
csRef<Value> v;
v.AttachNew (new AndValue (value1, value2));
csRef<StandardChangeListener> changeListener;
changeListener.AttachNew (new StandardChangeListener (v));
value1->AddValueChangeListener (changeListener);
value2->AddValueChangeListener (changeListener);
return v;
}
class OrValue : public BoolValue
{
private:
csRef<Value> value1, value2;
public:
OrValue (Value* value1, Value* value2) : value1 (value1), value2 (value2) { }
virtual ~OrValue () { }
virtual void SetBoolValue (bool fl) { }
virtual bool GetBoolValue ()
{
return ValueToBoolStatic (value1) || ValueToBoolStatic (value2);
}
};
csRef<Value> View::Or (Value* value1, Value* value2)
{
csRef<Value> v;
v.AttachNew (new OrValue (value1, value2));
csRef<StandardChangeListener> changeListener;
changeListener.AttachNew (new StandardChangeListener (v));
value1->AddValueChangeListener (changeListener);
value2->AddValueChangeListener (changeListener);
return v;
}
// --------------------------------------------------------------------------
} // namespace Ares
| 28.044307 | 119 | 0.665062 | GarethNelson |
11086346168afae2284634a663b83f4e9fc29531 | 7,930 | cpp | C++ | WDL/plush2/pl_read_3ds.cpp | hor-net/wdl-ol | 4a88575f82c0c577b28fc3b27279456b12b187fe | [
"Zlib"
] | 2 | 2017-12-05T04:18:55.000Z | 2021-03-20T03:04:56.000Z | WDL/plush2/pl_read_3ds.cpp | Metabog/wdl-ol | bfe87d2c4297d003f2475dc22d460440e5e1b4fa | [
"Zlib"
] | null | null | null | WDL/plush2/pl_read_3ds.cpp | Metabog/wdl-ol | bfe87d2c4297d003f2475dc22d460440e5e1b4fa | [
"Zlib"
] | 2 | 2017-04-24T12:45:33.000Z | 2019-12-22T04:31:51.000Z | /******************************************************************************
Plush Version 1.2
read_3ds.c
3DS Object Reader
Copyright (c) 1996-2000, Justin Frankel
******************************************************************************/
#include "plush.h"
typedef struct
{
pl_uInt16 id;
void (*func)(pl_uChar *ptr, pl_uInt32 p);
} _pl_3DSChunk;
static pl_Obj *obj;
static pl_Obj *bobj;
static pl_Obj *lobj;
static pl_sInt16 currentobj;
static pl_Mat *_m;
static pl_Float _pl3DSReadFloat(pl_uChar **ptr);
static pl_uInt32 _pl3DSReadDWord(pl_uChar **ptr);
static pl_uInt16 _pl3DSReadWord(pl_uChar **ptr);
static void _pl3DSChunkReader(pl_uChar *ptr, int len);
static void _pl3DSRGBFReader(pl_uChar *f, pl_uInt32 p);
static void _pl3DSRGBBReader(pl_uChar *f, pl_uInt32 p);
static int _pl3DSASCIIZReader(pl_uChar *ptr, pl_uInt32 p, char *as);
static void _pl3DSObjBlockReader(pl_uChar *ptr, pl_uInt32 p);
static void _pl3DSTriMeshReader(pl_uChar *f, pl_uInt32 p);
static void _pl3DSVertListReader(pl_uChar *f, pl_uInt32 p);
static void _pl3DSFaceListReader(pl_uChar *f, pl_uInt32 p);
static void _pl3DSFaceMatReader(pl_uChar *f, pl_uInt32 p);
static void MapListReader(pl_uChar *f, pl_uInt32 p);
static pl_sInt16 _pl3DSFindChunk(pl_uInt16 id);
static _pl_3DSChunk _pl3DSChunkNames[] = {
{0x4D4D,NULL}, /* Main */
{0x3D3D,NULL}, /* Object Mesh */
{0x4000,_pl3DSObjBlockReader},
{0x4100,_pl3DSTriMeshReader},
{0x4110,_pl3DSVertListReader},
{0x4120,_pl3DSFaceListReader},
{0x4130,_pl3DSFaceMatReader},
{0x4140,MapListReader},
{0xAFFF,NULL}, /* Material */
{0xA010,NULL}, /* Ambient */
{0xA020,NULL}, /* Diff */
{0xA030,NULL}, /* Specular */
{0xA200,NULL}, /* Texture */
{0x0010,_pl3DSRGBFReader},
{0x0011,_pl3DSRGBBReader},
};
pl_Obj *plRead3DSObjFromFile(char *fn, pl_Mat *m)
{
FILE *f = fopen(fn, "rb");
if (!f) return 0;
fseek(f, 0, 2);
pl_uInt32 p = ftell(f);
rewind(f);
WDL_HeapBuf buf;
buf.Resize(p);
int s = fread(buf.Get(), 1, p, f);
fclose(f);
if(!s) return 0;
return plRead3DSObj(buf.Get(), s, m);
}
pl_Obj *plRead3DSObjFromResource(HINSTANCE hInst, int resid, pl_Mat *m)
{
#ifdef _WIN32
HRSRC hResource = FindResource(hInst, MAKEINTRESOURCE(resid), "3DS");
if(!hResource) return NULL;
DWORD imageSize = SizeofResource(hInst, hResource);
if(imageSize < 6) return NULL;
HGLOBAL res = LoadResource(hInst, hResource);
const void* pResourceData = LockResource(res);
if(!pResourceData) return NULL;
unsigned char *data = (unsigned char *)pResourceData;
pl_Obj *o = plRead3DSObj(data, imageSize, m);
DeleteObject(res);
return o;
#else
return 0;
#endif
}
pl_Obj *plRead3DSObj(void *ptr, int size, pl_Mat *m)
{
_m = m;
obj = bobj = lobj = 0;
currentobj = 0;
_pl3DSChunkReader((pl_uChar *)ptr, size);
return bobj;
}
static pl_Float _pl3DSReadFloat(pl_uChar **ptr) {
pl_uInt32 *i;
pl_IEEEFloat32 c;
i = (pl_uInt32 *) &c;
*i = _pl3DSReadDWord(ptr);
return ((pl_Float) c);
}
static pl_uInt32 _pl3DSReadDWord(pl_uChar **ptr)
{
pl_uInt32 r;
pl_uChar *p = *ptr;
r = *p++;
r |= (*p++)<<8;
r |= (*p++)<<16;
r |= (*p++)<<24;
*ptr += 4;
return r;
}
static pl_uInt16 _pl3DSReadWord(pl_uChar **ptr)
{
pl_uInt16 r;
pl_uChar *p = *ptr;
r = *p++;
r |= (*p++)<<8;
*ptr += 2;
return r;
}
static void _pl3DSRGBFReader(pl_uChar *f, pl_uInt32 p)
{
pl_Float c[3];
if(p < 3*4) return;
c[0] = _pl3DSReadFloat(&f);
c[1] = _pl3DSReadFloat(&f);
c[2] = _pl3DSReadFloat(&f);
}
static void _pl3DSRGBBReader(pl_uChar *f, pl_uInt32 p)
{
unsigned char c[3];
if(p < 3) return;
memcpy(c, f, sizeof(c));
}
static int _pl3DSASCIIZReader(pl_uChar *ptr, pl_uInt32 p, char *as)
{
int l = 0;
while (*ptr && p>0)
{
if(as) *as++ = *ptr;
ptr++;
l++;
p--;
}
if(as) *as = 0;
return l+1;
}
static void _pl3DSObjBlockReader(pl_uChar *ptr, pl_uInt32 p)
{
int l = _pl3DSASCIIZReader(ptr, p, 0);
ptr += l;
p -= l;
_pl3DSChunkReader(ptr, p);
}
static void _pl3DSTriMeshReader(pl_uChar *ptr, pl_uInt32 p)
{
pl_uInt32 i;
pl_Face *face;
obj = new pl_Obj;
_pl3DSChunkReader(ptr, p);
i = obj->Faces.GetSize();
face = obj->Faces.Get();
while (i--)
{
pl_Vertex *vp=obj->Vertices.Get();
pl_Vertex *fVertices[3] = {
vp+face->VertexIndices[0],
vp+face->VertexIndices[1],
vp+face->VertexIndices[2],
};
face->MappingU[0][0] = fVertices[0]->xformedx;
face->MappingV[0][0] = fVertices[0]->xformedy;
face->MappingU[0][1] = fVertices[1]->xformedx;
face->MappingV[0][1] = fVertices[1]->xformedy;
face->MappingU[0][2] = fVertices[2]->xformedx;
face->MappingV[0][2] = fVertices[2]->xformedy;
face++;
}
obj->CalculateNormals();
if (currentobj == 0)
{
currentobj = 1;
lobj = bobj = obj;
}
else
{
lobj->Children.Add(obj);
lobj = obj;
}
}
static void _pl3DSVertListReader(pl_uChar *f, pl_uInt32 p)
{
pl_uInt16 nv;
pl_Vertex *v;
int len = (int)p;
nv = _pl3DSReadWord(&f);
len -= 2;
if(len <= 0) return;
obj->Vertices.Resize(nv);
v = obj->Vertices.Get();
while (nv--)
{
memset(v,0,sizeof(pl_Vertex));
v->x = _pl3DSReadFloat(&f);
v->y = _pl3DSReadFloat(&f);
v->z = _pl3DSReadFloat(&f);
len -= 3*4;
if(len < 0) return;
v++;
}
}
static void _pl3DSFaceListReader(pl_uChar *f, pl_uInt32 p)
{
pl_uInt16 nv;
pl_uInt16 c[3];
pl_uInt16 flags;
pl_Face *face;
int len = (int)p;
nv = _pl3DSReadWord(&f);
len -= 2;
if(len <= 0) return;
obj->Faces.Resize(nv);
face = obj->Faces.Get();
while (nv--)
{
memset(face,0,sizeof(pl_Face));
c[0] = _pl3DSReadWord(&f);
c[1] = _pl3DSReadWord(&f);
c[2] = _pl3DSReadWord(&f);
flags = _pl3DSReadWord(&f);
len -= 4*2;
if(len < 0) return;
face->VertexIndices[0] = (c[0]&0x0000FFFF);
face->VertexIndices[1] = (c[1]&0x0000FFFF);
face->VertexIndices[2] = (c[2]&0x0000FFFF);
face->Material = _m;
face++;
}
if(len) _pl3DSChunkReader(f, len);
}
static void _pl3DSFaceMatReader(pl_uChar *ptr, pl_uInt32 p)
{
pl_uInt16 n, nf;
int l = _pl3DSASCIIZReader(ptr, p, 0);
ptr += l;
p -= l;
n = _pl3DSReadWord(&ptr);
while (n--)
{
nf = _pl3DSReadWord(&ptr);
}
}
static void MapListReader(pl_uChar *f, pl_uInt32 p)
{
pl_uInt16 nv;
pl_Float c[2];
pl_Vertex *v;
int len = (int) p;
nv = _pl3DSReadWord(&f);
len -= 2;
v = obj->Vertices.Get();
if (nv == obj->Vertices.GetSize()) while (nv--)
{
c[0] = _pl3DSReadFloat(&f);
c[1] = _pl3DSReadFloat(&f);
len -= 2*4;
if (len < 0) return;
v->xformedx = c[0];
v->xformedy = c[1];
v++;
}
}
static pl_sInt16 _pl3DSFindChunk(pl_uInt16 id)
{
pl_sInt16 i;
for (i = 0; i < sizeof(_pl3DSChunkNames)/sizeof(_pl3DSChunkNames[0]); i++)
if (id == _pl3DSChunkNames[i].id) return i;
return -1;
}
static void _pl3DSChunkReader(pl_uChar *ptr, int len)
{
pl_uInt32 hlen;
pl_uInt16 hid;
pl_sInt16 n;
while (len > 0)
{
hid = _pl3DSReadWord(&ptr);
len -= 2;
if(len <= 0) return;
hlen = _pl3DSReadDWord(&ptr);
len -= 4;
if(len <= 0) return;
if (hlen == 0) return;
hlen -= 6;
n = _pl3DSFindChunk(hid);
if (n < 0)
{
ptr += hlen;
len -= hlen;
}
else
{
pl_uChar *p = ptr;
if (_pl3DSChunkNames[n].func != NULL)
_pl3DSChunkNames[n].func(p, hlen);
else
_pl3DSChunkReader(p, hlen);
ptr += hlen;
len -= hlen;
}
}
}
| 22.787356 | 80 | 0.583102 | hor-net |
1109568803479872ecba62b53e9492f3aae3671b | 38,338 | cpp | C++ | src/common/information_schema.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | null | null | null | src/common/information_schema.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | null | null | null | src/common/information_schema.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "information_schema.h"
#include <boost/algorithm/string/join.hpp>
#include "runtime_state.h"
#include "meta_server_interact.hpp"
#include "schema_factory.h"
#include "network_socket.h"
#include "scalar_fn_call.h"
#include "parser.h"
namespace baikaldb {
int InformationSchema::init() {
init_partition_split_info();
init_region_status();
init_columns();
init_statistics();
init_schemata();
init_tables();
init_virtual_index_influence_info();
init_routines();
init_key_column_usage();
init_referential_constraints();
return 0;
}
int64_t InformationSchema::construct_table(const std::string& table_name, FieldVec& fields) {
auto& table = _tables[table_name];//_tables[table_name]取出的是Schema_info
table.set_table_id(--_max_table_id);
table.set_table_name(table_name);
table.set_database("information_schema");
table.set_database_id(_db_id);
table.set_namespace_name("INTERNAL");
table.set_engine(pb::INFORMATION_SCHEMA);
int id = 0;
for (auto& pair : fields) {
auto* field = table.add_fields();
field->set_field_name(pair.first);
field->set_mysql_type(pair.second);
field->set_field_id(++id);
}
SchemaFactory::get_instance()->update_table(table);
return table.table_id();
}
void InformationSchema::init_partition_split_info() {
// 定义字段信息
FieldVec fields {
{"partition_key", pb::STRING},
{"table_name", pb::STRING},
{"split_info", pb::STRING},
{"split_rows", pb::STRING},
};
int64_t table_id = construct_table("PARTITION_SPLIT_INFO", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
for (auto expr : conditions) {
if (expr->node_type() != pb::FUNCTION_CALL) {
continue;
}
int32_t fn_op = static_cast<ScalarFnCall*>(expr)->fn().fn_op();
if (fn_op != parser::FT_EQ) {
continue;
}
if (!expr->children(0)->is_slot_ref()) {
continue;
}
SlotRef* slot_ref = static_cast<SlotRef*>(expr->children(0));
int32_t field_id = slot_ref->field_id();
if (field_id != 2) {
continue;
}
if (expr->children(1)->is_constant()) {
table_name = expr->children(1)->get_value(nullptr).get_string();
}
}
if (table_name.empty()) {
return records;
}
auto* factory = SchemaFactory::get_instance();
int64_t condition_table_id = 0;
if (factory->get_table_id(namespace_ + "." + table_name, condition_table_id) != 0) {
return records;
}
auto index_ptr = factory->get_index_info_ptr(condition_table_id);
if (index_ptr == nullptr) {
return records;
}
if (index_ptr->fields.size() < 2) {
return records;
}
std::map<std::string, pb::RegionInfo> region_infos;
factory->get_all_region_by_table_id(condition_table_id, ®ion_infos);
std::string last_partition_key;
std::vector<std::string> last_keys;
std::vector<int64_t> last_region_ids;
last_keys.reserve(3);
last_region_ids.reserve(3);
int64_t last_id = 0;
std::string partition_key;
auto type1 = index_ptr->fields[0].type;
auto type2 = index_ptr->fields[1].type;
records.reserve(10000);
std::vector<std::vector<int64_t>> region_ids;
region_ids.reserve(10000);
pb::QueryRequest req;
pb::QueryResponse res;
req.set_op_type(pb::QUERY_REGION);
for (auto& pair : region_infos) {
TableKey start_key(pair.second.start_key());
int pos = 0;
partition_key = start_key.decode_start_key_string(type1, pos);
if (partition_key != last_partition_key) {
if (last_keys.size() > 1) {
for (auto id : last_region_ids) {
req.add_region_ids(id);
}
region_ids.emplace_back(last_region_ids);
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("partition_key"), last_partition_key);
record->set_string(record->get_field_by_name("table_name"), table_name);
record->set_string(record->get_field_by_name("split_info"), boost::join(last_keys, ","));
//record->set_string(record->get_field_by_name("split_rows"), boost::join(rows, ","));
records.emplace_back(record);
}
last_partition_key = partition_key;
last_keys.clear();
last_region_ids.clear();
last_region_ids.emplace_back(last_id);
}
last_keys.emplace_back(start_key.decode_start_key_string(type2, pos));
last_region_ids.emplace_back(pair.second.region_id());
last_id = pair.second.region_id();
}
if (last_keys.size() > 1) {
for (auto id : last_region_ids) {
req.set_op_type(pb::QUERY_REGION);
}
region_ids.emplace_back(last_region_ids);
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("partition_key"), last_partition_key);
record->set_string(record->get_field_by_name("table_name"), table_name);
record->set_string(record->get_field_by_name("split_info"), boost::join(last_keys, ","));
//record->set_string(record->get_field_by_name("split_rows"), boost::join(rows, ","));
records.emplace_back(record);
}
MetaServerInteract::get_instance()->send_request("query", req, res);
std::unordered_map<int64_t, std::string> region_lines;
for (auto& info : res.region_infos()) {
region_lines[info.region_id()] = std::to_string(info.num_table_lines());
}
for (uint32_t i = 0; i < records.size(); i++) {
std::vector<std::string> rows;
rows.reserve(3);
if (i < region_ids.size()) {
for (auto& id : region_ids[i]) {
rows.emplace_back(region_lines[id]);
}
}
records[i]->set_string(records[i]->get_field_by_name("split_rows"), boost::join(rows, ","));
}
return records;
};
}
void InformationSchema::init_region_status() {
// 定义字段信息
FieldVec fields {
{"region_id", pb::INT64},
{"parent", pb::INT64},
{"table_id", pb::INT64},
{"main_table_id", pb::INT64},
{"table_name", pb::STRING},
{"start_key", pb:: STRING},
{"end_key", pb::STRING},
{"create_time", pb::STRING},
{"peers", pb::STRING},
{"leader", pb::STRING},
{"version", pb::INT64},
{"conf_version", pb::INT64},
{"num_table_lines", pb::INT64},
{"used_size", pb::INT64},
};
int64_t table_id = construct_table("REGION_STATUS", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
for (auto expr : conditions) {
if (expr->node_type() != pb::FUNCTION_CALL) {
continue;
}
int32_t fn_op = static_cast<ScalarFnCall*>(expr)->fn().fn_op();
if (fn_op != parser::FT_EQ) {
continue;
}
if (!expr->children(0)->is_slot_ref()) {
continue;
}
SlotRef* slot_ref = static_cast<SlotRef*>(expr->children(0));
int32_t field_id = slot_ref->field_id();
if (field_id != 5) {
continue;
}
if (expr->children(1)->is_constant()) {
table_name = expr->children(1)->get_value(nullptr).get_string();
}
}
if (table_name.empty()) {
return records;
}
auto* factory = SchemaFactory::get_instance();
int64_t condition_table_id = 0;
if (factory->get_table_id(namespace_ + "." + table_name, condition_table_id) != 0) {
return records;
}
auto index_ptr = factory->get_index_info_ptr(condition_table_id);
if (index_ptr == nullptr) {
return records;
}
std::map<std::string, pb::RegionInfo> region_infos;
factory->get_all_region_by_table_id(condition_table_id, ®ion_infos);
records.reserve(region_infos.size());
for (auto& pair : region_infos) {
auto& region = pair.second;
TableKey start_key(region.start_key());
TableKey end_key(region.end_key());
auto record = factory->new_record(table_id);
record->set_int64(record->get_field_by_name("region_id"), region.region_id());
record->set_int64(record->get_field_by_name("parent"), region.parent());
record->set_int64(record->get_field_by_name("table_id"), region.table_id());
record->set_int64(record->get_field_by_name("main_table_id"), region.main_table_id());
record->set_string(record->get_field_by_name("table_name"), table_name);
record->set_int64(record->get_field_by_name("version"), region.version());
record->set_int64(record->get_field_by_name("conf_version"), region.conf_version());
record->set_int64(record->get_field_by_name("num_table_lines"), region.num_table_lines());
record->set_int64(record->get_field_by_name("used_size"), region.used_size());
record->set_string(record->get_field_by_name("leader"), region.leader());
record->set_string(record->get_field_by_name("peers"), boost::join(region.peers(), ","));
time_t t = region.timestamp();
struct tm t_result;
localtime_r(&t, &t_result);
char s[100];
strftime(s, sizeof(s), "%F %T", &t_result);
record->set_string(record->get_field_by_name("create_time"), s);
record->set_string(record->get_field_by_name("start_key"),
start_key.decode_start_key_string(*index_ptr));
record->set_string(record->get_field_by_name("end_key"),
end_key.decode_start_key_string(*index_ptr));
records.emplace_back(record);
}
return records;
};
}
// MYSQL兼容表
void InformationSchema::init_columns() {
// 定义字段信息
FieldVec fields {
{"TABLE_CATALOG", pb::STRING},
{"TABLE_SCHEMA", pb::STRING},
{"TABLE_NAME", pb::STRING},
{"COLUMN_NAME", pb::STRING},
{"ORDINAL_POSITION", pb::INT64},
{"COLUMN_DEFAULT", pb::STRING},
{"IS_NULLABLE", pb::STRING},
{"DATA_TYPE", pb::STRING},
{"CHARACTER_MAXIMUM_LENGTH", pb::INT64},
{"CHARACTER_OCTET_LENGTH", pb::INT64},
{"NUMERIC_PRECISION", pb::INT64},
{"NUMERIC_SCALE", pb::INT64},
{"DATETIME_PRECISION", pb::INT64},
{"CHARACTER_SET_NAME", pb::STRING},
{"COLLATION_NAME", pb::STRING},
{"COLUMN_TYPE", pb::STRING},
{"COLUMN_KEY", pb::STRING},
{"EXTRA", pb::STRING},
{"PRIVILEGES", pb::STRING},
{"COLUMN_COMMENT", pb::STRING},
};
int64_t table_id = construct_table("COLUMNS", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
auto* factory = SchemaFactory::get_instance();
auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get());
records.reserve(tb_vec.size() * 10);
for (auto& table_info : tb_vec) {
int i = 0;
std::vector<std::string> items;
boost::split(items, table_info->name, boost::is_any_of("."));
std::string db = items[0];
std::multimap<int32_t, IndexInfo> field_index;
for (auto& index_id : table_info->indices) {
IndexInfo index_info = factory->get_index_info(index_id);
for (auto& field : index_info.fields) {
field_index.insert(std::make_pair(field.id, index_info));
}
}
for (auto& field : table_info->fields) {
if (field.deleted) {
continue;
}
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def");
record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db);
record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name);
record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name);
record->set_int64(record->get_field_by_name("ORDINAL_POSITION"), ++i);
record->set_string(record->get_field_by_name("COLUMN_DEFAULT"), field.default_value);
record->set_string(record->get_field_by_name("IS_NULLABLE"), field.can_null ? "YES" : "NO");
record->set_string(record->get_field_by_name("DATA_TYPE"), to_mysql_type_string(field.type));
switch (field.type) {
case pb::STRING:
record->set_int64(record->get_field_by_name("CHARACTER_MAXIMUM_LENGTH"), 1048576);
record->set_int64(record->get_field_by_name("CHARACTER_OCTET_LENGTH"), 3145728);
break;
case pb::INT8:
case pb::UINT8:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 3);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0);
break;
case pb::INT16:
case pb::UINT16:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 5);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0);
break;
case pb::INT32:
case pb::UINT32:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 10);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0);
break;
case pb::INT64:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 19);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0);
break;
case pb::UINT64:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 20);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0);
break;
case pb::FLOAT:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 38);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 6);
break;
case pb::DOUBLE:
record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 308);
record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 15);
break;
case pb::DATETIME:
case pb::TIMESTAMP:
case pb::DATE:
record->set_int64(record->get_field_by_name("DATETIME_PRECISION"), 0);
break;
default:
break;
}
record->set_string(record->get_field_by_name("CHARACTER_SET_NAME"), "utf8");
record->set_string(record->get_field_by_name("COLLATION_NAME"), "utf8_general_ci");
record->set_string(record->get_field_by_name("COLUMN_TYPE"), to_mysql_type_full_string(field.type));
std::vector<std::string> extra_vec;
if (field_index.count(field.id) == 0) {
record->set_string(record->get_field_by_name("COLUMN_KEY"), " ");
} else {
std::vector<std::string> index_types;
index_types.reserve(4);
auto range = field_index.equal_range(field.id);
for (auto index_iter = range.first; index_iter != range.second; ++index_iter) {
auto& index_info = index_iter->second;
std::string index = pb::IndexType_Name(index_info.type);
if (index_info.type == pb::I_FULLTEXT) {
index += "(" + pb::SegmentType_Name(index_info.segment_type) + ")";
}
index_types.push_back(index);
extra_vec.push_back(pb::IndexState_Name(index_info.state));
}
record->set_string(record->get_field_by_name("COLUMN_KEY"), boost::algorithm::join(index_types, "|"));
}
if (table_info->auto_inc_field_id == field.id) {
extra_vec.push_back("auto_increment");
} else {
//extra_vec.push_back(" ");
}
record->set_string(record->get_field_by_name("EXTRA"), boost::algorithm::join(extra_vec, "|"));
record->set_string(record->get_field_by_name("PRIVILEGES"), "select,insert,update,references");
record->set_string(record->get_field_by_name("COLUMN_COMMENT"), field.comment);
records.emplace_back(record);
}
}
return records;
};
}
void InformationSchema::init_referential_constraints() {
// 定义字段信息
FieldVec fields {
{"CONSTRAINT_CATALOG", pb::STRING},
{"CONSTRAINT_SCHEMA", pb::STRING},
{"CONSTRAINT_NAME", pb::STRING},
{"UNIQUE_CONSTRAINT_CATALOG", pb::STRING},
{"UNIQUE_CONSTRAINT_SCHEMA", pb::STRING},
{"UNIQUE_CONSTRAINT_NAME", pb::STRING},
{"MATCH_OPTION", pb::STRING},
{"UPDATE_RULE", pb::STRING},
{"DELETE_RULE", pb::STRING},
{"TABLE_NAME", pb::STRING},
{"REFERENCED_TABLE_NAME", pb::STRING}
};
int64_t table_id = construct_table("REFERENTIAL_CONSTRAINTS", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
return records;
};
}
void InformationSchema::init_key_column_usage() {
// 定义字段信息
FieldVec fields {
{"CONSTRAINT_CATALOG", pb::STRING},
{"CONSTRAINT_SCHEMA", pb::STRING},
{"CONSTRAINT_NAME", pb::STRING},
{"TABLE_CATALOG", pb::STRING},
{"TABLE_SCHEMA", pb::STRING},
{"TABLE_NAME", pb::STRING},
{"COLUMN_NAME", pb::STRING},
{"ORDINAL_POSITION", pb::INT64},
{"POSITION_IN_UNIQUE_CONSTRAINT", pb::INT64},
{"REFERENCED_TABLE_SCHEMA", pb::STRING},
{"REFERENCED_TABLE_NAME", pb::STRING},
{"REFERENCED_COLUMN_NAME", pb::STRING}
};
int64_t table_id = construct_table("KEY_COLUMN_USAGE", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
auto* factory = SchemaFactory::get_instance();
auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get());
records.reserve(tb_vec.size() * 10);
for (auto& table_info : tb_vec) {
int i = 0;
std::vector<std::string> items;
boost::split(items, table_info->name, boost::is_any_of("."));
std::string db = items[0];
std::multimap<int32_t, IndexInfo> field_index;
for (auto& index_id : table_info->indices) {
IndexInfo index_info = factory->get_index_info(index_id);
auto index_type = index_info.type;
if (index_type != pb::I_PRIMARY && index_type != pb::I_UNIQ) {
continue;
}
int idx = 0;
for (auto& field : index_info.fields) {
idx ++;
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("CONSTRAINT_CATALOG"), "def");
record->set_string(record->get_field_by_name("CONSTRAINT_SCHEMA"), db);
record->set_string(record->get_field_by_name("CONSTRAINT_NAME"), index_type == pb::I_PRIMARY ? "PRIMARY":"name_key");
record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def");
record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db);
record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name);
record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name);
record->set_int64(record->get_field_by_name("ORDINAL_POSITION"), idx);
records.emplace_back(record);
}
}
}
return records;
};
}
void InformationSchema::init_statistics() {
// 定义字段信息
FieldVec fields {
{"TABLE_CATALOG", pb::STRING},
{"TABLE_SCHEMA", pb::STRING},
{"TABLE_NAME", pb::STRING},
{"NON_UNIQUE", pb::STRING},
{"INDEX_SCHEMA", pb::STRING},
{"INDEX_NAME", pb::STRING},
{"SEQ_IN_INDEX", pb::INT64},
{"COLUMN_NAME", pb::STRING},
{"COLLATION", pb::STRING},
{"CARDINALITY", pb::INT64},
{"SUB_PART", pb::INT64},
{"PACKED", pb::STRING},
{"NULLABLE", pb::STRING},
{"INDEX_TYPE", pb::STRING},
{"COMMENT", pb::STRING},
{"INDEX_COMMENT", pb::STRING},
};
int64_t table_id = construct_table("STATISTICS", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
auto* factory = SchemaFactory::get_instance();
auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get());
records.reserve(tb_vec.size() * 10);
for (auto& table_info : tb_vec) {
std::vector<std::string> items;
boost::split(items, table_info->name, boost::is_any_of("."));
std::string db = items[0];
for (auto& index_id : table_info->indices) {
auto index_ptr = factory->get_index_info_ptr(index_id);
if (index_ptr == nullptr) {
continue;
}
if (index_ptr->index_hint_status != pb::IHS_NORMAL) {
continue;
}
int i = 0;
for (auto& field : index_ptr->fields) {
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def");
record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db);
record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name);
record->set_string(record->get_field_by_name("INDEX_SCHEMA"), db);
std::string index_name = index_ptr->short_name;
std::string index_type = "BTREE";
std::string non_unique = "0";
if (index_ptr->type == pb::I_PRIMARY) {
index_name = "PRIMARY";
} else if (index_ptr->type == pb::I_KEY) {
non_unique = "1";
} else if (index_ptr->type == pb::I_FULLTEXT) {
non_unique = "1";
index_type = "FULLTEXT";
}
record->set_string(record->get_field_by_name("INDEX_NAME"), index_name);
record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name);
record->set_string(record->get_field_by_name("NON_UNIQUE"), non_unique);
record->set_int64(record->get_field_by_name("SEQ_IN_INDEX"), i++);
record->set_string(record->get_field_by_name("NULLABLE"), field.can_null ? "YES" : "");
record->set_string(record->get_field_by_name("COLLATION"), "A");
record->set_string(record->get_field_by_name("INDEX_TYPE"), index_type);
record->set_string(record->get_field_by_name("INDEX_COMMENT"), index_ptr->comments);
std::ostringstream comment;
comment << "'{\"segment_type\":\"";
comment << pb::SegmentType_Name(index_ptr->segment_type) << "\", ";
comment << "\"storage_type\":\"";
comment << pb::StorageType_Name(index_ptr->storage_type) << "\", ";
comment << "\"is_global\":\"" << index_ptr->is_global << "\"}'";
record->set_string(record->get_field_by_name("COMMENT"), comment.str());
records.emplace_back(record);
}
}
}
return records;
};
}
void InformationSchema::init_schemata() {
// 定义字段信息
FieldVec fields {
{"CATALOG_NAME", pb::STRING},
{"SCHEMA_NAME", pb::STRING},
{"DEFAULT_CHARACTER_SET_NAME", pb::STRING},
{"DEFAULT_COLLATION_NAME", pb::STRING},
{"SQL_PATH", pb::INT64},
};
int64_t table_id = construct_table("SCHEMATA", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
auto* factory = SchemaFactory::get_instance();
std::vector<std::string> db_vec = factory->get_db_list(state->client_conn()->user_info->all_database);
records.reserve(db_vec.size());
for (auto& db : db_vec) {
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("CATALOG_NAME"), "def");
record->set_string(record->get_field_by_name("SCHEMA_NAME"), db);
record->set_string(record->get_field_by_name("DEFAULT_CHARACTER_SET_NAME"), "utf8mb4");
record->set_string(record->get_field_by_name("DEFAULT_COLLATION_NAME"), "utf8mb4_bin");
records.emplace_back(record);
}
return records;
};
}
void InformationSchema::init_tables() {
// 定义字段信息
FieldVec fields {
{"TABLE_CATALOG", pb::STRING},
{"TABLE_SCHEMA", pb::STRING},
{"TABLE_NAME", pb::STRING},
{"TABLE_TYPE", pb::STRING},
{"ENGINE", pb::STRING},
{"VERSION", pb::INT64},
{"ROW_FORMAT", pb::STRING},
{"TABLE_ROWS", pb::INT64},
{"AVG_ROW_LENGTH", pb::INT64},
{"DATA_LENGTH", pb::INT64},
{"MAX_DATA_LENGTH", pb::INT64},
{"INDEX_LENGTH", pb::INT64},
{"DATA_FREE", pb::INT64},
{"AUTO_INCREMENT", pb::INT64},
{"CREATE_TIME", pb::DATETIME},
{"UPDATE_TIME", pb::DATETIME},
{"CHECK_TIME", pb::DATETIME},
{"TABLE_COLLATION", pb::STRING},
{"CHECKSUM", pb::INT64},
{"CREATE_OPTIONS", pb::STRING},
{"TABLE_COMMENT", pb::STRING},
{"TABLE_ID", pb::INT64},
};
int64_t table_id = construct_table("TABLES", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
if (state->client_conn() == nullptr) {
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
auto* factory = SchemaFactory::get_instance();
auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get());
records.reserve(tb_vec.size());
for (auto& table_info : tb_vec) {
std::vector<std::string> items;
boost::split(items, table_info->name, boost::is_any_of("."));
std::string db = items[0];
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def");
record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db);
record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name);
record->set_string(record->get_field_by_name("TABLE_TYPE"), "BASE TABLE");
record->set_string(record->get_field_by_name("ENGINE"), "Innodb");
record->set_int64(record->get_field_by_name("VERSION"), table_info->version);
record->set_string(record->get_field_by_name("ROW_FORMAT"), "Compact");
record->set_int64(record->get_field_by_name("TABLE_ROWS"), 0);
record->set_int64(record->get_field_by_name("AVG_ROW_LENGTH"), table_info->byte_size_per_record);
record->set_int64(record->get_field_by_name("DATA_LENGTH"), 0);
record->set_int64(record->get_field_by_name("MAX_DATA_LENGTH"), 0);
record->set_int64(record->get_field_by_name("INDEX_LENGTH"), 0);
record->set_int64(record->get_field_by_name("DATA_FREE"), 0);
record->set_int64(record->get_field_by_name("AUTO_INCREMENT"), 0);
ExprValue ct(pb::TIMESTAMP);
ct._u.uint32_val = table_info->timestamp;
record->set_value(record->get_field_by_name("CREATE_TIME"), ct.cast_to(pb::DATETIME));
record->set_string(record->get_field_by_name("TABLE_COLLATION"), "utf8_bin");
record->set_string(record->get_field_by_name("CREATE_OPTIONS"), "");
record->set_string(record->get_field_by_name("TABLE_COMMENT"), "");
record->set_int64(record->get_field_by_name("TABLE_ID"), table_info->id);
records.emplace_back(record);
}
return records;
};
}
void InformationSchema::init_virtual_index_influence_info() {
//定义字段信息
FieldVec fields {
{"database_name",pb::STRING},
{"table_name",pb::STRING},
{"virtual_index_name",pb::STRING},
{"sign",pb::STRING},
{"sample_sql",pb::STRING},
};
int64_t table_id = construct_table("VIRTUAL_INDEX_AFFECT_SQL", fields);
//定义操作
_calls[table_id] = [table_id](RuntimeState* state,std::vector<ExprNode*>& conditions) ->
std::vector <SmartRecord> {
std::vector <SmartRecord> records;
//更新表中数据前,要交互一次,从TableMem取影响面数据
pb::QueryRequest request;
pb::QueryResponse response;
//1、设定查询请求的操作类型
request.set_op_type(pb::QUERY_SHOW_VIRINDX_INFO_SQL);
//2、发送请求
MetaServerInteract::get_instance()->send_request("query", request, response);
//3.取出response中的影响面信息
auto& virtual_index_info_sqls = response.virtual_index_influence_info();//virtual_index_info and affected_sqls
if(state -> client_conn() == nullptr){
return records;
}
std::string namespace_ = state->client_conn()->user_info->namespace_;
std::string table_name;
auto* factory = SchemaFactory::get_instance();
auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get());
records.reserve(tb_vec.size());
for (auto& it1 : virtual_index_info_sqls) {
std::string key = it1.virtual_index_info();
std::string infuenced_sql = it1.affected_sqls();
std::string sign = it1.affected_sign();
std::vector<std::string> items1;
boost::split(items1, key, boost::is_any_of(","));
auto record = factory->new_record(table_id);
record->set_string(record->get_field_by_name("database_name"), items1[0]);
record->set_string(record->get_field_by_name("table_name"), items1[1]);
record->set_string(record->get_field_by_name("virtual_index_name"),items1[2]);
record->set_string(record->get_field_by_name("sign"), sign);
record->set_string(record->get_field_by_name("sample_sql"), infuenced_sql);
records.emplace_back(record);
}
return records;
};
}
void InformationSchema::init_routines() {
// 定义字段信息
FieldVec fields {
{"SPECIFIC_NAME", pb::STRING},
{"ROUTINE_CATALOG", pb::STRING},
{"ROUTINE_SCHEMA", pb::STRING},
{"ROUTINE_NAME", pb::STRING},
{"ROUTINE_TYPE", pb::STRING},
{"DATA_TYPE", pb::STRING},
{"CHARACTER_MAXIMUM_LENGTH", pb::INT64},
{"CHARACTER_OCTET_LENGTH", pb::INT64},
{"NUMERIC_PRECISION", pb::UINT64},
{"NUMERIC_SCALE", pb::INT64},
{"DATETIME_PRECISION", pb::UINT64},
{"CHARACTER_SET_NAME", pb::STRING},
{"COLLATION_NAME", pb::STRING},
{"DTD_IDENTIFIER", pb::STRING},
{"ROUTINE_BODY", pb::STRING},
{"ROUTINE_DEFINITION" , pb::STRING},
{"EXTERNAL_NAME" , pb::STRING},
{"EXTERNAL_LANGUAGE" , pb::STRING},
{"PARAMETER_STYLE", pb::STRING},
{"IS_DETERMINISTIC", pb::STRING},
{"SQL_DATA_ACCESS", pb::STRING},
{"SQL_PATH", pb::STRING},
{"SECURITY_TYPE", pb::STRING},
{"CREATED", pb::STRING},
{"LAST_ALTERED", pb::DATETIME},
{"SQL_MODE", pb::DATETIME},
{"ROUTINE_COMMENT", pb::STRING},
{"DEFINER", pb::STRING},
{"CHARACTER_SET_CLIENT", pb::STRING},
{"COLLATION_CONNECTION", pb::STRING},
{"DATABASE_COLLATION", pb::STRING},
};
int64_t table_id = construct_table("ROUTINES", fields);
// 定义操作
_calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) ->
std::vector<SmartRecord> {
std::vector<SmartRecord> records;
return records;
};
}
} // namespace baikaldb
| 48.714104 | 141 | 0.547759 | tisuama |
110e0562d099679db9aaebb93c080a3f1cedebc5 | 10,152 | cc | C++ | src/Mapping.cc | MIRTK/VolumetricMapping | 0c7e58204f8c278d887510b46d7ad0b96735f04f | [
"Apache-2.0"
] | 1 | 2017-06-09T14:39:15.000Z | 2017-06-09T14:39:15.000Z | src/Mapping.cc | MIRTK/VolumetricMapping | 0c7e58204f8c278d887510b46d7ad0b96735f04f | [
"Apache-2.0"
] | 1 | 2017-03-23T13:56:33.000Z | 2017-03-23T17:19:22.000Z | src/Mapping.cc | MIRTK/Mapping | 0c7e58204f8c278d887510b46d7ad0b96735f04f | [
"Apache-2.0"
] | 2 | 2017-06-09T14:39:16.000Z | 2019-09-25T09:08:03.000Z | /*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2016 Imperial College London
* Copyright 2013-2016 Andreas Schuh
*
* 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 "mirtk/Mapping.h"
#include "mirtk/Config.h" // WINDOWS
#include "mirtk/Math.h"
#include "mirtk/Memory.h"
#include "mirtk/Cfstream.h"
#include "mirtk/BaseImage.h"
#include "mirtk/VoxelFunction.h"
#include "mirtk/PointSetUtils.h"
#include "vtkSmartPointer.h"
#include "vtkPointSet.h"
#include "vtkPolyData.h"
#include "vtkImageData.h"
#include "mirtk/PiecewiseLinearMap.h"
#include "mirtk/MeshlessHarmonicMap.h"
#include "mirtk/MeshlessBiharmonicMap.h"
namespace mirtk {
// =============================================================================
// Factory method
// =============================================================================
// -----------------------------------------------------------------------------
Mapping *Mapping::New(const char *fname)
{
UniquePtr<Mapping> map;
const size_t max_name_len = 32;
char map_type_name[max_name_len];
Cifstream is(fname);
is.ReadAsChar(map_type_name, max_name_len);
if (strncmp(map_type_name, MeshlessHarmonicMap::NameOfType(), max_name_len) == 0) {
map.reset(new MeshlessHarmonicMap());
} else if (strncmp(map_type_name, MeshlessBiharmonicMap::NameOfType(), max_name_len) == 0) {
map.reset(new MeshlessBiharmonicMap());
} else {
// Note that a picewise linear map is stored using a VTK file format and
// therefore the map file contains no "mirtk::PiecewiseLinearMap" header.
map.reset(new PiecewiseLinearMap());
}
map->Read(fname);
return map.release();
}
// =============================================================================
// Auxiliary functors
// =============================================================================
namespace MappingUtils {
// -----------------------------------------------------------------------------
/// Evaluate map at lattice points
class EvaluateMap : public VoxelFunction
{
const Mapping *_Map;
vtkImageData *_Domain;
const BaseImage *_Output;
const int _NumberOfVoxels;
const int _l1, _l2;
public:
EvaluateMap(const Mapping *map,
vtkImageData *domain,
const BaseImage *output,
int l1, int l2)
:
_Map(map),
_Domain(domain),
_Output(output),
_NumberOfVoxels(output->NumberOfSpatialVoxels()),
_l1(l1), _l2(l2)
{}
template <class T>
void operator ()(int i, int j, int k, int, T *v) const
{
if (!_Domain || _Domain->GetScalarComponentAsFloat(i, j, k, 0) != .0) {
double x = i, y = j, z = k;
_Output->ImageToWorld(x, y, z);
double *f = new double[_Map->NumberOfComponents()];
_Map->Evaluate(f, x, y, z);
for (int l = _l1; l < _l2; ++l, v += _NumberOfVoxels) {
*v = f[l];
}
delete[] f;
} else {
for (int l = _l1; l < _l2; ++l, v += _NumberOfVoxels) {
*v = numeric_limits<T>::quiet_NaN();
}
}
}
};
} // namespace MappingUtils
using namespace MappingUtils;
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
void Mapping::CopyAttributes(const Mapping &other)
{
_OutsideValue = other._OutsideValue;
}
// -----------------------------------------------------------------------------
Mapping::Mapping()
:
_OutsideValue(mirtk::nan)
{
}
// -----------------------------------------------------------------------------
Mapping::Mapping(const Mapping &other)
:
Object(other)
{
CopyAttributes(other);
}
// -----------------------------------------------------------------------------
Mapping &Mapping::operator =(const Mapping &other)
{
if (this != &other) {
Object::operator =(other);
CopyAttributes(other);
}
return *this;
}
// -----------------------------------------------------------------------------
void Mapping::Initialize()
{
}
// -----------------------------------------------------------------------------
Mapping::~Mapping()
{
}
// =============================================================================
// Map domain
// =============================================================================
// -----------------------------------------------------------------------------
ImageAttributes Mapping::Attributes(int nx, int ny, int nz) const
{
if (this->NumberOfArguments() >= 2) {
if (ny <= 0) ny = nx;
} else {
ny = 0;
}
if (this->NumberOfArguments() >= 3) {
if (nz <= 0) nz = nx;
} else {
nz = 0;
}
double x1, y1, z1, x2, y2, z2;
this->BoundingBox(x1, y1, z1, x2, y2, z2);
const double lx = x2 - x1;
const double ly = y2 - y1;
const double lz = z2 - z1;
ImageAttributes lattice;
lattice._xorigin = x1 + .5 * lx;
lattice._yorigin = y1 + .5 * ly;
lattice._zorigin = z1 + .5 * lz;
lattice._x = nx;
lattice._y = ny;
lattice._z = nz;
lattice._dx = (lattice._x == 0 ? .0 : lx / nx);
lattice._dy = (lattice._y == 0 ? .0 : ly / ny);
lattice._dz = (lattice._z == 0 ? .0 : lz / nz);
if (lattice._x == 0) lattice._x = 1;
if (lattice._y == 0) lattice._y = 1;
if (lattice._z == 0) lattice._z = 1;
return lattice;
}
// -----------------------------------------------------------------------------
ImageAttributes Mapping::Attributes(double dx, double dy, double dz) const
{
double x1, y1, z1, x2, y2, z2;
this->BoundingBox(x1, y1, z1, x2, y2, z2);
const double lx = x2 - x1;
const double ly = y2 - y1;
const double lz = z2 - z1;
if (dx <= .0) {
dx = sqrt(lx*lx + ly*ly + lz*lz) / 256;
}
if (this->NumberOfArguments() >= 2) {
if (dy <= .0) dy = dx;
} else {
dy = 0;
}
if (this->NumberOfArguments() >= 3) {
if (dz <= .0) dz = dx;
} else {
dz = 0;
}
ImageAttributes lattice;
lattice._xorigin = x1 + .5 * lx;
lattice._yorigin = y1 + .5 * ly;
lattice._zorigin = z1 + .5 * lz;
lattice._x = iceil(lx / dx);
lattice._y = iceil(ly / dy);
lattice._z = iceil(lz / dz);
lattice._dx = (lattice._x == 0 ? .0 : dx);
lattice._dy = (lattice._y == 0 ? .0 : dy);
lattice._dz = (lattice._z == 0 ? .0 : dz);
if (lattice._x == 0) lattice._x = 1;
if (lattice._y == 0) lattice._y = 1;
if (lattice._z == 0) lattice._z = 1;
return lattice;
}
// =============================================================================
// Evaluation
// =============================================================================
// -----------------------------------------------------------------------------
void Mapping::Evaluate(GenericImage<float> &f, int l, vtkSmartPointer<vtkPointSet> m) const
{
ImageAttributes lattice = f.Attributes();
lattice._dt = .0;
if (l >= NumberOfComponents() || l + lattice._t > NumberOfComponents()) {
cerr << this->NameOfType() << "::Evaluate: Component index out of range" << endl;
exit(1);
}
vtkSmartPointer<vtkImageData> mask;
if (m) {
mask = NewVtkMask(lattice._x, lattice._y, lattice._z);
ImageStencilToMask(ImageStencil(mask, WorldToImage(m, &f)), mask);
}
ParallelForEachVoxel(EvaluateMap(this, mask, &f, l, l + lattice._t), lattice, f);
}
// -----------------------------------------------------------------------------
void Mapping::Evaluate(GenericImage<double> &f, int l, vtkSmartPointer<vtkPointSet> m) const
{
ImageAttributes lattice = f.Attributes();
lattice._dt = .0;
if (l >= NumberOfComponents() || l + lattice._t > NumberOfComponents()) {
cerr << this->NameOfType() << "::Evaluate: Component index out of range" << endl;
exit(1);
}
vtkSmartPointer<vtkImageData> mask;
if (m) {
mask = NewVtkMask(lattice._x, lattice._y, lattice._z);
ImageStencilToMask(ImageStencil(mask, WorldToImage(m, &f)), mask);
}
ParallelForEachVoxel(EvaluateMap(this, mask, &f, l, l + lattice._t), lattice, f);
}
// =============================================================================
// I/O
// =============================================================================
// -----------------------------------------------------------------------------
bool Mapping::Read(const char *fname)
{
Cifstream is(fname);
const size_t max_name_len = 32;
char map_type_name[max_name_len];
is.ReadAsChar(map_type_name, max_name_len);
if (strncmp(map_type_name, this->NameOfClass(), max_name_len) != 0) {
return false;
}
this->ReadMap(is);
this->Initialize();
return true;
}
// -----------------------------------------------------------------------------
bool Mapping::Write(const char *fname) const
{
Cofstream os(fname);
const size_t max_name_len = 32;
char map_type_name[max_name_len] = {0};
#ifdef WINDOWS
strncpy_s(map_type_name, max_name_len, this->NameOfClass(), max_name_len);
#else
strncpy(map_type_name, this->NameOfClass(), max_name_len);
#endif
os.WriteAsChar(map_type_name, max_name_len);
this->WriteMap(os);
return true;
}
// -----------------------------------------------------------------------------
void Mapping::ReadMap(Cifstream &)
{
cerr << this->NameOfClass() << "::ReadMap not implemented" << endl;
exit(1);
}
// -----------------------------------------------------------------------------
void Mapping::WriteMap(Cofstream &) const
{
cerr << this->NameOfClass() << "::WriteMap not implemented" << endl;
exit(1);
}
} // namespace mirtk
| 28.923077 | 94 | 0.495764 | MIRTK |
1113aebdf33f8740412e440635e3da92af2ee58e | 281 | cpp | C++ | allMatuCommit/回文_2020040901027_20210920120011.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/回文_2020040901027_20210920120011.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/回文_2020040901027_20210920120011.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | #include <stdio.h>
#define N 30
int main(void)
{
char a[N];
int i,j,n;
gets(a);
for(i=0;i<N;i++)
{
n=0;
if(a[i]!='\0')
n++;
}
for(j=0;j<n;j++)
{
if(a[j]==a[n-j-1])
printf("true");
else
printf("false");
}return 0;
} | 12.772727 | 24 | 0.405694 | BachWV |
11144c8848f85cbd6d24ce08a8c6ff9ed28ecb5e | 673 | cpp | C++ | Deitel/Chapter02/exercises/2.24/ex_224.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | Deitel/Chapter02/exercises/2.24/ex_224.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | Deitel/Chapter02/exercises/2.24/ex_224.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | /*
* =====================================================================================
*
* Filename:
*
* Description:
*
* Version: 1.0
* Created: Thanks to github you know it
* Revision: none
* Compiler: g++
*
* Author: Mahmut Erdem ÖZGEN [email protected]
*
*
* =====================================================================================
*/
#include <iostream>
int main(int argc, const char *argv[]) {
int num1;
std::cout << "Enter an integer: ";
std::cin >> num1;
std::cout << num1 << " is " << ((num1 % 2 == 0) ? "even" : "odd") << std::endl;
return 0;
}
| 22.433333 | 88 | 0.356612 | SebastianTirado |
11146beceed78a107969a3394a9839683fe5efd9 | 5,303 | cpp | C++ | test/sources/tools/match/test-optimize_mask.cpp | Kartonagnick/tools-match | ec27ca94a031e04f072f8366bde2d567c29134c8 | [
"MIT"
] | null | null | null | test/sources/tools/match/test-optimize_mask.cpp | Kartonagnick/tools-match | ec27ca94a031e04f072f8366bde2d567c29134c8 | [
"MIT"
] | 7 | 2021-02-05T20:45:04.000Z | 2021-03-09T15:12:14.000Z | test/sources/tools/match/test-optimize_mask.cpp | Kartonagnick/tools-match | ec27ca94a031e04f072f8366bde2d567c29134c8 | [
"MIT"
] | null | null | null |
// [2021y-02m-05d] Idrisov Denis R.
#include <mygtest/modern.hpp>
#ifdef TEST_TOOLS_MATCH_OPTIMIZE_MASK
#define dTEST_COMPONENT tools, match
#define dTEST_METHOD optimize_mask
#define dTEST_TAG tdd
#include <tools/match/optimize_mask.hpp>
namespace me = ::tools;
//==============================================================================
namespace
{
template<class ch, class s1, class s2>
void optimization(const s1& src_mask, const s2& expect)
{
typedef std::basic_string<ch>
str_type;
str_type mask = src_mask;
const size_t len = me::optimize_mask(mask);
const str_type result(mask, 0, len);
ASSERT_TRUE(result == expect)
<< "mask = '" << mask << "'\n"
<< "expected = '" << expect << "'\n"
;
}
#define optimize(mask, expect) \
optimization<char>(mask, expect); \
optimization<wchar_t>(L##mask, L##expect)
} // namespace
//==============================================================================
#ifndef NDEBUG
// nullptr (death)
TEST_COMPONENT(000)
{
size_t len = 0;
ASSERT_DEATH_DEBUG(
char* mask = NULL;
len = me::optimize_mask(mask)
);
ASSERT_DEATH_DEBUG(
wchar_t* mask = NULL;
len = me::optimize_mask(mask)
);
(void) len;
}
#endif // !NDEBUG
TEST_COMPONENT(001)
{
std::string mask = "1**?a";
const size_t len = me::optimize_mask(mask);
ASSERT_TRUE(len == 4);
ASSERT_TRUE(mask.size() == 4);
std::string re(mask, 0, len);
ASSERT_TRUE(re == "1*?a");
ASSERT_TRUE(mask == "1*?a");
}
TEST_COMPONENT(002)
{
// 0123456789012345678
char mask[] = "aaa****bbbb";
const std::string etalon = "aaa*bbbb";
const size_t len = me::optimize_mask(mask);
const std::string result(mask, len);
ASSERT_TRUE(len == etalon.length());
ASSERT_TRUE(etalon == result);
}
TEST_COMPONENT(003)
{
// 0123456789012345678
char mask[] = "aaa****bbbb***ccc";
const std::string etalon = "aaa*bbbb*ccc";
const size_t len = me::optimize_mask(mask);
const std::string result(mask, len);
ASSERT_TRUE(len == etalon.length());
ASSERT_TRUE(etalon == result);
}
TEST_COMPONENT(004)
{
char mask[] = "***";
const std::string etalon = "*";
const size_t len = me::optimize_mask(mask);
const std::string result(mask, len);
ASSERT_TRUE(len == etalon.length());
ASSERT_TRUE(etalon == result);
}
TEST_COMPONENT(005)
{
char mask[] = "";
const std::string etalon = "";
const size_t len = me::optimize_mask(mask);
const std::string result(mask, len);
ASSERT_TRUE(len == etalon.length());
ASSERT_TRUE(etalon == result);
}
TEST_COMPONENT(006)
{
char mask[] = "txt";
const std::string etalon = "txt";
const size_t len = me::optimize_mask(mask);
const std::string result(mask, len);
ASSERT_TRUE(len == etalon.length());
ASSERT_TRUE(etalon == result);
}
TEST_COMPONENT(007)
{
std::string mask = "1**?***a*?**";
const size_t len = me::optimize_mask(mask);
ASSERT_TRUE(len == 8);
std::string re(mask, 0, len);
ASSERT_TRUE(re == "1*?*a*?*");
ASSERT_TRUE(mask == "1*?*a*?*");
}
TEST_COMPONENT(008)
{
std::string val = "123???***??456";
const size_t len = me::optimize_mask(val);
ASSERT_TRUE(val == "123???*??456");
ASSERT_TRUE(len == 12);
}
// --- stress
TEST_COMPONENT(009)
{
optimize("*.*" , "*.*" );
optimize("" , "" );
optimize("**?test??.** /" , "*?test??.* /" );
optimize("*?m.?*" , "*?m.?*" );
optimize("*?m.?*/" , "*?m.?*/" );
optimize("*?m.?* /" , "*?m.?* /" );
optimize(" *?m.?* /" , " *?m.?* /" );
optimize("*?m.?" , "*?m.?" );
optimize("*?m.?/" , "*?m.?/" );
optimize("*?m.? /" , "*?m.? /" );
optimize(" *?m.? /" , " *?m.? /" );
optimize(" *?m.? " , " *?m.? " );
optimize("*?m.??" , "*?m.??" );
optimize(" *?m.?? " , " *?m.?? " );
optimize(" *?m.?? /" , " *?m.?? /" );
optimize("*?m.\?\?" , "*?m.\?\?" );
optimize("*?m.\?\? " , "*?m.\?\? " );
optimize("*?m.?*?" , "*?m.?*?" );
optimize(" *?m.?*? " , " *?m.?*? " );
optimize(" *?m.?*?/" , " *?m.?*?/" );
optimize(" *?m.?*? /" , " *?m.?*? /" );
optimize("*?m.?*?/ " , "*?m.?*?/ " );
optimize(" *?m.?*? / " , " *?m.?*? / " );
optimize(" *?m.?*?" , " *?m.?*?" );
optimize(" *?m.?*?/" , " *?m.?*?/" );
optimize(" *?m.?*? /" , " *?m.?*? /" );
optimize(" *?m.?*? / " , " *?m.?*? / " );
optimize(" *?m.?*? //" , " *?m.?*? //" );
optimize(" *?m.?*?/ " , " *?m.?*?/ " );
optimize(" *?m.?*? " , " *?m.?*? " );
optimize(" *?m.?*? /" , " *?m.?*? /" );
optimize(" *?m.?*? / " , " *?m.?*? / " );
optimize(" *?m.?*?/ " , " *?m.?*?/ " );
optimize(" ***?m.?***?/ " , " *?m.?*?/ " );
}
#endif // !TEST_TOOLS_MATCH_OPTIMIZE_MASK
| 29.960452 | 80 | 0.443334 | Kartonagnick |
1115266ea6f1ad6946315dcfd49244e9cfe17af4 | 1,109 | hpp | C++ | controller.hpp | Greentwip/PuyoPuyo | cb76c4b5861e29765050675cde0185d15aa055e6 | [
"MIT"
] | null | null | null | controller.hpp | Greentwip/PuyoPuyo | cb76c4b5861e29765050675cde0185d15aa055e6 | [
"MIT"
] | null | null | null | controller.hpp | Greentwip/PuyoPuyo | cb76c4b5861e29765050675cde0185d15aa055e6 | [
"MIT"
] | null | null | null | #pragma once
#include "sl.h"
#include "defines.hpp"
#include "input.hpp"
class controller {
public:
virtual input get_input() {
return input(direction::horizontal, 0, rotation::none);
}
};
class player_controller : public controller {
virtual input get_input() override {
auto key_left = slGetKey(SL_KEY_LEFT);
auto key_right = slGetKey(SL_KEY_RIGHT);
auto key_down = slGetKey(SL_KEY_DOWN);
auto rotate_left = slGetKey('Z');
auto rotate_right = slGetKey('X');
if (key_left) {
return input(direction::horizontal, -1, rotation::none);
}
if (key_right) {
return input(direction::horizontal, 1, rotation::none);
}
if (key_down) {
return input(direction::vertical, -1, rotation::none);
}
if (rotate_left) {
return input(direction::horizontal, 0, rotation::left);
}
if (rotate_right) {
return input(direction::horizontal, 0, rotation::right);
}
return input(direction::horizontal, 0, rotation::none);
}
};
class ai_controller : public controller {
virtual input get_input() override {
return input(direction::horizontal, 0, rotation::none);
}
};
| 20.924528 | 59 | 0.693417 | Greentwip |
11160972c1639127f27bf491266449eb98ff1944 | 5,937 | cxx | C++ | Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkHiddenLineRemovalPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtk_glew.h"
#include "vtkHiddenLineRemovalPass.h"
#include "vtkActor.h"
#include "vtkMapper.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkProp.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderState.h"
#include <string>
// Define to print debug statements to the OpenGL CS stream (useful for e.g.
// apitrace debugging):
//#define ANNOTATE_STREAM
namespace
{
void annotate(const std::string &str)
{
#ifdef ANNOTATE_STREAM
vtkOpenGLStaticCheckErrorMacro("Error before glDebug.")
glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER,
GL_DEBUG_SEVERITY_NOTIFICATION,
0, str.size(), str.c_str());
vtkOpenGLClearErrorMacro();
#else // ANNOTATE_STREAM
(void)str;
#endif // ANNOTATE_STREAM
}
}
vtkStandardNewMacro(vtkHiddenLineRemovalPass)
//------------------------------------------------------------------------------
void vtkHiddenLineRemovalPass::PrintSelf(std::ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//------------------------------------------------------------------------------
void vtkHiddenLineRemovalPass::Render(const vtkRenderState *s)
{
this->NumberOfRenderedProps = 0;
// Separate the wireframe props from the others:
std::vector<vtkProp*> wireframeProps;
std::vector<vtkProp*> otherProps;
for (int i = 0; i < s->GetPropArrayCount(); ++i)
{
bool isWireframe = false;
vtkProp *prop = s->GetPropArray()[i];
vtkActor *actor = vtkActor::SafeDownCast(prop);
if (actor)
{
vtkProperty *property = actor->GetProperty();
if (property->GetRepresentation() == VTK_WIREFRAME)
{
isWireframe = true;
}
}
if (isWireframe)
{
wireframeProps.push_back(actor);
}
else
{
otherProps.push_back(actor);
}
}
vtkViewport *vp = s->GetRenderer();
// Render the non-wireframe geometry as normal:
annotate("Rendering non-wireframe props.");
this->NumberOfRenderedProps = this->RenderProps(otherProps, vp);
vtkOpenGLStaticCheckErrorMacro("Error after non-wireframe geometry.");
// Store the coincident topology parameters -- we want to force polygon
// offset to keep the drawn lines sharp:
int ctMode = vtkMapper::GetResolveCoincidentTopology();
double ctFactor, ctUnits;
vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(ctFactor,
ctUnits);
vtkMapper::SetResolveCoincidentTopology(VTK_RESOLVE_POLYGON_OFFSET);
vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(2.0, 2.0);
// Draw the wireframe props as surfaces into the depth buffer only:
annotate("Rendering wireframe prop surfaces.");
this->SetRepresentation(wireframeProps, VTK_SURFACE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
this->RenderProps(wireframeProps, vp);
vtkOpenGLStaticCheckErrorMacro("Error after wireframe surface rendering.");
// Now draw the wireframes as normal:
annotate("Rendering wireframes.");
this->SetRepresentation(wireframeProps, VTK_WIREFRAME);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
this->NumberOfRenderedProps = this->RenderProps(wireframeProps, vp);
vtkOpenGLStaticCheckErrorMacro("Error after wireframe rendering.");
// Restore the previous coincident topology parameters:
vtkMapper::SetResolveCoincidentTopology(ctMode);
vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(ctFactor,
ctUnits);
}
//------------------------------------------------------------------------------
bool vtkHiddenLineRemovalPass::WireframePropsExist(vtkProp **propArray,
int nProps)
{
for (int i = 0; i < nProps; ++i)
{
vtkActor *actor = vtkActor::SafeDownCast(propArray[i]);
if (actor)
{
vtkProperty *property = actor->GetProperty();
if (property->GetRepresentation() == VTK_WIREFRAME)
{
return true;
}
}
}
return false;
}
//------------------------------------------------------------------------------
vtkHiddenLineRemovalPass::vtkHiddenLineRemovalPass()
{
}
//------------------------------------------------------------------------------
vtkHiddenLineRemovalPass::~vtkHiddenLineRemovalPass()
{
}
//------------------------------------------------------------------------------
void vtkHiddenLineRemovalPass::SetRepresentation(std::vector<vtkProp *> &props,
int repr)
{
for (std::vector<vtkProp*>::iterator it = props.begin(), itEnd = props.end();
it != itEnd; ++it)
{
vtkActor *actor = vtkActor::SafeDownCast(*it);
if (actor)
{
actor->GetProperty()->SetRepresentation(repr);
}
}
}
//------------------------------------------------------------------------------
int vtkHiddenLineRemovalPass::RenderProps(std::vector<vtkProp *> &props,
vtkViewport *vp)
{
int propsRendered = 0;
for (std::vector<vtkProp*>::iterator it = props.begin(), itEnd = props.end();
it != itEnd; ++it)
{
propsRendered += (*it)->RenderOpaqueGeometry(vp);
}
return propsRendered;
}
| 32.442623 | 80 | 0.595419 | keithroe |
111793c676ad7140d1e988a74ed4cf5ffcc48d82 | 734 | cpp | C++ | libs/proto/example/hello.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 11 | 2015-07-12T13:04:52.000Z | 2021-05-30T23:23:46.000Z | libs/proto/example/hello.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | null | null | null | libs/proto/example/hello.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 3 | 2015-12-23T01:51:57.000Z | 2019-08-25T04:58:32.000Z | //[ HelloWorld
////////////////////////////////////////////////////////////////////
// Copyright 2008 Eric Niebler. 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 <iostream>
#include <boost/proto/core.hpp>
#include <boost/proto/context.hpp>
#include <boost/typeof/std/ostream.hpp>
namespace proto = boost::proto;
proto::terminal< std::ostream & >::type cout_ = {std::cout};
template< typename Expr >
void evaluate( Expr const & expr )
{
proto::default_context ctx;
proto::eval(expr, ctx);
}
int main()
{
evaluate( cout_ << "hello" << ',' << " world" );
return 0;
}
//]
| 26.214286 | 69 | 0.589918 | zyiacas |
111b589bf119bbe67c7855522445a6c0bde32047 | 3,611 | hpp | C++ | src/dag/dag_block_manager.hpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | null | null | null | src/dag/dag_block_manager.hpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | 7 | 2021-06-08T12:40:38.000Z | 2021-06-16T12:11:15.000Z | src/dag/dag_block_manager.hpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | null | null | null | #pragma once
#include "dag_block.hpp"
#include "final_chain/final_chain.hpp"
#include "transaction_manager/transaction.hpp"
#include "transaction_manager/transaction_manager.hpp"
#include "vdf_sortition.hpp"
namespace taraxa {
enum class BlockStatus { invalid, proposed, broadcasted, verified, unseen };
using BlockStatusTable = ExpirationCacheMap<blk_hash_t, BlockStatus>;
// Thread safe
class DagBlockManager {
public:
DagBlockManager(addr_t node_addr, vdf_sortition::VdfConfig const &vdf_config,
optional<state_api::DPOSConfig> dpos_config, unsigned verify_threads, std::shared_ptr<DbStorage> db,
std::shared_ptr<TransactionManager> trx_mgr, std::shared_ptr<FinalChain> final_chain,
std::shared_ptr<PbftChain> pbft_chain, logger::Logger log_time_, uint32_t queue_limit = 0);
~DagBlockManager();
void insertBlock(DagBlock const &blk);
// Only used in initial syncs when blocks are received with full list of transactions
void insertBroadcastedBlockWithTransactions(DagBlock const &blk, std::vector<Transaction> const &transactions);
void pushUnverifiedBlock(DagBlock const &block,
bool critical); // add to unverified queue
void pushUnverifiedBlock(DagBlock const &block, std::vector<Transaction> const &transactions,
bool critical); // add to unverified queue
DagBlock popVerifiedBlock(); // get one verified block and pop
void pushVerifiedBlock(DagBlock const &blk);
std::pair<size_t, size_t> getDagBlockQueueSize() const;
level_t getMaxDagLevelInQueue() const;
void start();
void stop();
bool isBlockKnown(blk_hash_t const &hash);
std::shared_ptr<DagBlock> getDagBlock(blk_hash_t const &hash) const;
void clearBlockStatausTable() { blk_status_.clear(); }
bool pivotAndTipsValid(DagBlock const &blk);
uint64_t getCurrentMaxProposalPeriod() const;
uint64_t getLastProposalPeriod() const;
void setLastProposalPeriod(uint64_t const period);
std::pair<uint64_t, bool> getProposalPeriod(level_t level);
std::shared_ptr<ProposalPeriodDagLevelsMap> newProposePeriodDagLevelsMap(level_t anchor_level);
private:
using uLock = boost::unique_lock<boost::shared_mutex>;
using sharedLock = boost::shared_lock<boost::shared_mutex>;
using upgradableLock = boost::upgrade_lock<boost::shared_mutex>;
using upgradeLock = boost::upgrade_to_unique_lock<boost::shared_mutex>;
void verifyBlock();
std::atomic<bool> stopped_ = true;
size_t num_verifiers_ = 4;
const uint32_t cache_max_size_ = 10000;
const uint32_t cache_delete_step_ = 100;
std::atomic<uint64_t> last_proposal_period_ = 0;
uint64_t current_max_proposal_period_ = 0;
std::shared_ptr<DbStorage> db_;
std::shared_ptr<TransactionManager> trx_mgr_;
std::shared_ptr<FinalChain> final_chain_;
std::shared_ptr<PbftChain> pbft_chain_;
logger::Logger log_time_;
// seen blks
BlockStatusTable blk_status_;
ExpirationCacheMap<blk_hash_t, DagBlock> seen_blocks_;
std::vector<std::thread> verifiers_;
mutable boost::shared_mutex shared_mutex_for_unverified_qu_;
mutable boost::shared_mutex shared_mutex_for_verified_qu_;
boost::condition_variable_any cond_for_unverified_qu_;
boost::condition_variable_any cond_for_verified_qu_;
uint32_t queue_limit_;
std::map<uint64_t, std::deque<std::pair<DagBlock, std::vector<Transaction> > > > unverified_qu_;
std::map<uint64_t, std::deque<DagBlock> > verified_qu_;
vdf_sortition::VdfConfig vdf_config_;
optional<state_api::DPOSConfig> dpos_config_;
LOG_OBJECTS_DEFINE
};
} // namespace taraxa
| 41.505747 | 118 | 0.7635 | agrebin |
111cdeaa469629cd408bfcf3d07afb61a4311821 | 178 | cpp | C++ | Runic/Src/Runic/Scene/SceneManager.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | Runic/Src/Runic/Scene/SceneManager.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | Runic/Src/Runic/Scene/SceneManager.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | #include "runicpch.h"
#include "SceneManager.h"
namespace Runic {
Scope<SceneManager::SceneManagerData> SceneManager::s_Data = CreateScope<SceneManager::SceneManagerData>();
} | 29.666667 | 108 | 0.786517 | Swarmley |
1120fe5c48d0ec4925a967b3fae35d5a8517ae09 | 8,496 | cpp | C++ | modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp | SRai22/mvsim | 0890889353c89ac0f1ad9bd6f700068ca22262f3 | [
"BSD-3-Clause"
] | 11 | 2020-07-18T03:16:25.000Z | 2022-03-29T12:59:34.000Z | modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp | SRai22/mvsim | 0890889353c89ac0f1ad9bd6f700068ca22262f3 | [
"BSD-3-Clause"
] | 1 | 2022-01-21T07:56:43.000Z | 2022-01-21T08:07:30.000Z | modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp | SRai22/mvsim | 0890889353c89ac0f1ad9bd6f700068ca22262f3 | [
"BSD-3-Clause"
] | 6 | 2020-06-17T02:34:28.000Z | 2022-03-13T01:37:01.000Z | /*+-------------------------------------------------------------------------+
| MultiVehicle simulator (libmvsim) |
| |
| Copyright (C) 2014-2020 Jose Luis Blanco Claraco |
| Copyright (C) 2017 Borys Tymchenko (Odessa Polytechnic University) |
| Distributed under 3-clause BSD License |
| See COPYING |
+-------------------------------------------------------------------------+ */
#include <mrpt/opengl/COpenGLScene.h>
#include <mvsim/VehicleDynamics/VehicleAckermann.h>
#include <mvsim/World.h>
#include <cmath>
#include <rapidxml.hpp>
#include "xml_utils.h"
using namespace mvsim;
using namespace std;
// Ctor:
DynamicsAckermann::DynamicsAckermann(World* parent)
: VehicleBase(parent, 4 /*num wheels*/)
{
m_chassis_mass = 500.0;
m_chassis_z_min = 0.20;
m_chassis_z_max = 1.40;
m_chassis_color = mrpt::img::TColor(0xe8, 0x30, 0x00);
// Default shape:
m_chassis_poly.clear();
m_chassis_poly.emplace_back(-0.8, -1.0);
m_chassis_poly.emplace_back(-0.8, 1.0);
m_chassis_poly.emplace_back(1.5, 0.9);
m_chassis_poly.emplace_back(1.8, 0.8);
m_chassis_poly.emplace_back(1.8, -0.8);
m_chassis_poly.emplace_back(1.5, -0.9);
updateMaxRadiusFromPoly();
m_fixture_chassis = nullptr;
for (int i = 0; i < 4; i++) m_fixture_wheels[i] = nullptr;
// Default values:
// rear-left:
m_wheels_info[WHEEL_RL].x = 0;
m_wheels_info[WHEEL_RL].y = 0.9;
// rear-right:
m_wheels_info[WHEEL_RR].x = 0;
m_wheels_info[WHEEL_RR].y = -0.9;
// Front-left:
m_wheels_info[WHEEL_FL].x = 1.3;
m_wheels_info[WHEEL_FL].y = 0.9;
// Front-right:
m_wheels_info[WHEEL_FR].x = 1.3;
m_wheels_info[WHEEL_FR].y = -0.9;
}
/** The derived-class part of load_params_from_xml() */
void DynamicsAckermann::dynamics_load_params_from_xml(
const rapidxml::xml_node<char>* xml_node)
{
const std::map<std::string, std::string> varValues = {{"NAME", m_name}};
// <chassis ...> </chassis>
if (const rapidxml::xml_node<char>* xml_chassis =
xml_node->first_node("chassis");
xml_chassis)
{
// Attribs:
TParameterDefinitions attribs;
attribs["mass"] = TParamEntry("%lf", &this->m_chassis_mass);
attribs["zmin"] = TParamEntry("%lf", &this->m_chassis_z_min);
attribs["zmax"] = TParamEntry("%lf", &this->m_chassis_z_max);
attribs["color"] = TParamEntry("%color", &this->m_chassis_color);
parse_xmlnode_attribs(
*xml_chassis, attribs, {},
"[DynamicsAckermann::dynamics_load_params_from_xml]");
// Shape node (optional, fallback to default shape if none found)
if (const rapidxml::xml_node<char>* xml_shape =
xml_chassis->first_node("shape");
xml_shape)
mvsim::parse_xmlnode_shape(
*xml_shape, m_chassis_poly,
"[DynamicsAckermann::dynamics_load_params_from_xml]");
}
//<rl_wheel pos="0 1" mass="6.0" width="0.30" diameter="0.62" />
//<rr_wheel pos="0 -1" mass="6.0" width="0.30" diameter="0.62" />
//<fl_wheel mass="6.0" width="0.30" diameter="0.62" />
//<fr_wheel mass="6.0" width="0.30" diameter="0.62" />
const char* w_names[4] = {
"rl_wheel", // 0
"rr_wheel", // 1
"fl_wheel", // 2
"fr_wheel" // 3
};
// Load common params:
for (size_t i = 0; i < 4; i++)
{
const rapidxml::xml_node<char>* xml_wheel =
xml_node->first_node(w_names[i]);
if (xml_wheel) m_wheels_info[i].loadFromXML(xml_wheel);
}
//<f_wheels_x>1.3</f_wheels_x>
//<f_wheels_d>2.0</f_wheels_d>
// Load front ackermann wheels and other params:
{
double front_x = 1.3;
double front_d = 2.0;
TParameterDefinitions ack_ps;
// Front wheels:
ack_ps["f_wheels_x"] = TParamEntry("%lf", &front_x);
ack_ps["f_wheels_d"] = TParamEntry("%lf", &front_d);
// other params:
ack_ps["max_steer_ang_deg"] = TParamEntry("%lf_deg", &m_max_steer_ang);
parse_xmlnode_children_as_param(
*xml_node, ack_ps, varValues,
"[DynamicsAckermann::dynamics_load_params_from_xml]");
// Front-left:
m_wheels_info[WHEEL_FL].x = front_x;
m_wheels_info[WHEEL_FL].y = 0.5 * front_d;
// Front-right:
m_wheels_info[WHEEL_FR].x = front_x;
m_wheels_info[WHEEL_FR].y = -0.5 * front_d;
}
// Vehicle controller:
// -------------------------------------------------
{
const rapidxml::xml_node<char>* xml_control =
xml_node->first_node("controller");
if (xml_control)
{
rapidxml::xml_attribute<char>* control_class =
xml_control->first_attribute("class");
if (!control_class || !control_class->value())
throw runtime_error(
"[DynamicsAckermann] Missing 'class' attribute in "
"<controller> XML node");
const std::string sCtrlClass = std::string(control_class->value());
if (sCtrlClass == ControllerRawForces::class_name())
m_controller =
ControllerBasePtr(new ControllerRawForces(*this));
else if (sCtrlClass == ControllerTwistFrontSteerPID::class_name())
m_controller =
ControllerBasePtr(new ControllerTwistFrontSteerPID(*this));
else if (sCtrlClass == ControllerFrontSteerPID::class_name())
m_controller =
ControllerBasePtr(new ControllerFrontSteerPID(*this));
else
throw runtime_error(mrpt::format(
"[DynamicsAckermann] Unknown 'class'='%s' in "
"<controller> XML node",
sCtrlClass.c_str()));
m_controller->load_config(*xml_control);
}
}
// Default controller:
if (!m_controller)
m_controller = ControllerBasePtr(new ControllerRawForces(*this));
}
// See docs in base class:
void DynamicsAckermann::invoke_motor_controllers(
const TSimulContext& context, std::vector<double>& out_torque_per_wheel)
{
// Longitudinal forces at each wheel:
out_torque_per_wheel.assign(4, 0.0);
if (m_controller)
{
// Invoke controller:
TControllerInput ci;
ci.context = context;
TControllerOutput co;
m_controller->control_step(ci, co);
// Take its output:
out_torque_per_wheel[WHEEL_RL] = co.rl_torque;
out_torque_per_wheel[WHEEL_RR] = co.rr_torque;
out_torque_per_wheel[WHEEL_FL] = co.fl_torque;
out_torque_per_wheel[WHEEL_FR] = co.fr_torque;
// Kinematically-driven steering wheels:
// Ackermann formulas for inner&outer weels turning angles wrt the
// equivalent (central) one:
computeFrontWheelAngles(
co.steer_ang, m_wheels_info[WHEEL_FL].yaw,
m_wheels_info[WHEEL_FR].yaw);
}
}
void DynamicsAckermann::computeFrontWheelAngles(
const double desired_equiv_steer_ang, double& out_fl_ang,
double& out_fr_ang) const
{
// EQ1: cot(d)+0.5*w/l = cot(do)
// EQ2: cot(di)=cot(do)-w/l
const double w = m_wheels_info[WHEEL_FL].y - m_wheels_info[WHEEL_FR].y;
const double l = m_wheels_info[WHEEL_FL].x - m_wheels_info[WHEEL_RL].x;
ASSERT_(l > 0);
const double w_l = w / l;
const double delta =
b2Clamp(std::abs(desired_equiv_steer_ang), 0.0, m_max_steer_ang);
const bool delta_neg = (desired_equiv_steer_ang < 0);
ASSERT_LT_(delta, 0.5 * M_PI - 0.01);
const double cot_do = 1.0 / tan(delta) + 0.5 * w_l;
const double cot_di = cot_do - w_l;
// delta>0: do->right, di->left wheel
// delta<0: do->left , di->right wheel
(delta_neg ? out_fr_ang : out_fl_ang) =
atan(1.0 / cot_di) * (delta_neg ? -1.0 : 1.0);
(delta_neg ? out_fl_ang : out_fr_ang) =
atan(1.0 / cot_do) * (delta_neg ? -1.0 : 1.0);
}
// See docs in base class:
mrpt::math::TTwist2D DynamicsAckermann::getVelocityLocalOdoEstimate() const
{
mrpt::math::TTwist2D odo_vel;
// Equations:
// Velocities in local +X at each wheel i={0,1}:
// v_i = vx - w_veh * wheel_{i,y} = w_i * R_i
// Re-arranging:
const double w0 = m_wheels_info[WHEEL_RL].getW();
const double w1 = m_wheels_info[WHEEL_RR].getW();
const double R0 = m_wheels_info[WHEEL_RL].diameter * 0.5;
const double R1 = m_wheels_info[WHEEL_RR].diameter * 0.5;
const double Ay = m_wheels_info[WHEEL_RL].y - m_wheels_info[WHEEL_RR].y;
ASSERTMSG_(
Ay != 0.0,
"The two wheels of a differential vehicle CAN'T by at the same Y "
"coordinate!");
const double w_veh = (w1 * R1 - w0 * R0) / Ay;
const double vx_veh = w0 * R0 + w_veh * m_wheels_info[WHEEL_RL].y;
odo_vel.vx = vx_veh;
odo_vel.vy = 0.0;
odo_vel.omega = w_veh;
#if 0 // Debug
{
mrpt::math::TTwist2D gt_vel = this->getVelocityLocal();
printf("\n gt: vx=%7.03f, vy=%7.03f, w= %7.03fdeg\n", gt_vel.vx, gt_vel.vy, mrpt::RAD2DEG(gt_vel.omega));
printf("odo: vx=%7.03f, vy=%7.03f, w= %7.03fdeg\n", odo_vel.vx, odo_vel.vy, mrpt::RAD2DEG(odo_vel.omega));
}
#endif
return odo_vel;
}
| 32.551724 | 108 | 0.660546 | SRai22 |
11247378ff3ce23ff009136e2cb6c955e16446e2 | 1,126 | hpp | C++ | src/pbrrenderer2.hpp | jpbruyere/vke | cf965d29b9092ea6b56847028dc885b67b1603e0 | [
"MIT"
] | 1 | 2018-10-17T17:28:10.000Z | 2018-10-17T17:28:10.000Z | src/pbrrenderer2.hpp | jpbruyere/vke | cf965d29b9092ea6b56847028dc885b67b1603e0 | [
"MIT"
] | null | null | null | src/pbrrenderer2.hpp | jpbruyere/vke | cf965d29b9092ea6b56847028dc885b67b1603e0 | [
"MIT"
] | 1 | 2021-08-11T14:13:02.000Z | 2021-08-11T14:13:02.000Z | #pragma once
#include "vke.hpp"
#include "vkrenderer.hpp"
#include "texture.hpp"
#include "VulkanglTFModel.hpp"
class pbrRenderer : public vke::vkRenderer
{
void generateBRDFLUT();
void generateCubemaps();
protected:
virtual void configurePipelineLayout();
virtual void loadRessources();
virtual void freeRessources();
virtual void prepareDescriptors();
virtual void preparePipeline();
public:
struct Pipelines {
VkPipeline skybox;
VkPipeline pbr;
VkPipeline pbrAlphaBlend;
} pipelines;
VkDescriptorSet dsScene;
struct Textures {
vke::TextureCubeMap environmentCube;
vke::Texture2D lutBrdf;
vke::TextureCubeMap irradianceCube;
vke::TextureCubeMap prefilteredCube;
} textures;
vkglTF::Model skybox;
std::vector<vkglTF::Model> models;
pbrRenderer ();
virtual ~pbrRenderer();
virtual void destroy();
void renderPrimitive(vkglTF::Primitive &primitive, VkCommandBuffer commandBuffer);
void prepareModels();
virtual void draw(VkCommandBuffer cmdBuff);
};
| 22.078431 | 86 | 0.676732 | jpbruyere |
1128adeb375e43db32f68460c232c4134508ccd6 | 2,817 | hpp | C++ | irohad/ordering/impl/on_demand_os_client_grpc.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | irohad/ordering/impl/on_demand_os_client_grpc.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | irohad/ordering/impl/on_demand_os_client_grpc.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP
#define IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP
#include "ordering/on_demand_os_transport.hpp"
#include "network/impl/async_grpc_client.hpp"
#include "ordering.grpc.pb.h"
namespace iroha {
namespace ordering {
namespace transport {
/**
* gRPC client for on demand ordering service
*/
class OnDemandOsClientGrpc : public OdOsNotification {
public:
using TimepointType = std::chrono::system_clock::time_point;
using TimeoutType = std::chrono::milliseconds;
/**
* Constructor is left public because testing required passing a mock
* stub interface
*/
OnDemandOsClientGrpc(
std::unique_ptr<proto::OnDemandOrdering::StubInterface> stub,
std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>>
async_call,
std::function<TimepointType()> time_provider,
std::chrono::milliseconds proposal_request_timeout);
void onBatches(consensus::Round round, CollectionType batches) override;
boost::optional<ProposalType> onRequestProposal(
consensus::Round round) override;
private:
logger::Logger log_;
std::unique_ptr<proto::OnDemandOrdering::StubInterface> stub_;
std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>>
async_call_;
std::function<TimepointType()> time_provider_;
std::chrono::milliseconds proposal_request_timeout_;
};
class OnDemandOsClientGrpcFactory : public OdOsNotificationFactory {
public:
OnDemandOsClientGrpcFactory(
std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>>
async_call,
std::function<OnDemandOsClientGrpc::TimepointType()> time_provider,
OnDemandOsClientGrpc::TimeoutType proposal_request_timeout);
/**
* Create connection with insecure gRPC channel defined by
* network::createClient method
* @see network/impl/grpc_channel_builder.hpp
* This factory method can be used in production code
*/
std::unique_ptr<OdOsNotification> create(
const shared_model::interface::Peer &to) override;
private:
std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>>
async_call_;
std::function<OnDemandOsClientGrpc::TimepointType()> time_provider_;
std::chrono::milliseconds proposal_request_timeout_;
};
} // namespace transport
} // namespace ordering
} // namespace iroha
#endif // IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP
| 35.2125 | 80 | 0.676251 | coderintherye |
112aff1d4d6f7bbdbb57fe6e5e141556be472d73 | 3,173 | hpp | C++ | include/armadillo_bits/op_sum_meat.hpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 8 | 2017-01-12T14:18:50.000Z | 2021-02-18T14:44:33.000Z | include/armadillo_bits/op_sum_meat.hpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 1 | 2017-07-04T05:40:30.000Z | 2017-07-04T05:43:37.000Z | include/armadillo_bits/op_sum_meat.hpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 6 | 2016-08-21T00:29:08.000Z | 2022-01-09T08:41:33.000Z | // Copyright (C) 2008-2015 Conrad Sanderson
// Copyright (C) 2008-2015 NICTA (www.nicta.com.au)
//
// 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 http://mozilla.org/MPL/2.0/.
//! \addtogroup op_sum
//! @{
template<typename T1>
arma_hot
inline
void
op_sum::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_sum>& in)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
const uword dim = in.aux_uword_a;
arma_debug_check( (dim > 1), "sum(): parameter 'dim' must be 0 or 1" );
const Proxy<T1> P(in.m);
if(P.is_alias(out) == false)
{
op_sum::apply_noalias(out, P, dim);
}
else
{
Mat<eT> tmp;
op_sum::apply_noalias(tmp, P, dim);
out.steal_mem(tmp);
}
}
template<typename T1>
arma_hot
inline
void
op_sum::apply_noalias(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim)
{
arma_extra_debug_sigprint();
if(is_Mat<typename Proxy<T1>::stored_type>::value)
{
op_sum::apply_noalias_unwrap(out, P, dim);
}
else
{
op_sum::apply_noalias_proxy(out, P, dim);
}
}
template<typename T1>
arma_hot
inline
void
op_sum::apply_noalias_unwrap(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
typedef typename Proxy<T1>::stored_type P_stored_type;
const unwrap<P_stored_type> tmp(P.Q);
const typename unwrap<P_stored_type>::stored_type& X = tmp.M;
const uword X_n_rows = X.n_rows;
const uword X_n_cols = X.n_cols;
if(dim == 0)
{
out.set_size(1, X_n_cols);
eT* out_mem = out.memptr();
for(uword col=0; col < X_n_cols; ++col)
{
out_mem[col] = arrayops::accumulate( X.colptr(col), X_n_rows );
}
}
else
{
out.zeros(X_n_rows, 1);
eT* out_mem = out.memptr();
for(uword col=0; col < X_n_cols; ++col)
{
arrayops::inplace_plus( out_mem, X.colptr(col), X_n_rows );
}
}
}
template<typename T1>
arma_hot
inline
void
op_sum::apply_noalias_proxy(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
const uword P_n_rows = P.get_n_rows();
const uword P_n_cols = P.get_n_cols();
if(dim == 0)
{
out.set_size(1, P_n_cols);
eT* out_mem = out.memptr();
for(uword col=0; col < P_n_cols; ++col)
{
eT val1 = eT(0);
eT val2 = eT(0);
uword i,j;
for(i=0, j=1; j < P_n_rows; i+=2, j+=2)
{
val1 += P.at(i,col);
val2 += P.at(j,col);
}
if(i < P_n_rows)
{
val1 += P.at(i,col);
}
out_mem[col] = (val1 + val2);
}
}
else
{
out.zeros(P_n_rows, 1);
eT* out_mem = out.memptr();
for(uword col=0; col < P_n_cols; ++col)
for(uword row=0; row < P_n_rows; ++row)
{
out_mem[row] += P.at(row,col);
}
}
}
//! @}
| 19.114458 | 99 | 0.589663 | ArashMassoudieh |
112c2dc9f8f72e002a965ea65ec48db3c184fd8e | 5,533 | cpp | C++ | clb/src/v20180317/model/LbRsTargets.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | clb/src/v20180317/model/LbRsTargets.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | clb/src/v20180317/model/LbRsTargets.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/clb/v20180317/model/LbRsTargets.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Clb::V20180317::Model;
using namespace std;
LbRsTargets::LbRsTargets() :
m_typeHasBeenSet(false),
m_privateIpHasBeenSet(false),
m_portHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_weightHasBeenSet(false)
{
}
CoreInternalOutcome LbRsTargets::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Type") && !value["Type"].IsNull())
{
if (!value["Type"].IsString())
{
return CoreInternalOutcome(Core::Error("response `LbRsTargets.Type` IsString=false incorrectly").SetRequestId(requestId));
}
m_type = string(value["Type"].GetString());
m_typeHasBeenSet = true;
}
if (value.HasMember("PrivateIp") && !value["PrivateIp"].IsNull())
{
if (!value["PrivateIp"].IsString())
{
return CoreInternalOutcome(Core::Error("response `LbRsTargets.PrivateIp` IsString=false incorrectly").SetRequestId(requestId));
}
m_privateIp = string(value["PrivateIp"].GetString());
m_privateIpHasBeenSet = true;
}
if (value.HasMember("Port") && !value["Port"].IsNull())
{
if (!value["Port"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `LbRsTargets.Port` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_port = value["Port"].GetInt64();
m_portHasBeenSet = true;
}
if (value.HasMember("VpcId") && !value["VpcId"].IsNull())
{
if (!value["VpcId"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `LbRsTargets.VpcId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_vpcId = value["VpcId"].GetInt64();
m_vpcIdHasBeenSet = true;
}
if (value.HasMember("Weight") && !value["Weight"].IsNull())
{
if (!value["Weight"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `LbRsTargets.Weight` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_weight = value["Weight"].GetInt64();
m_weightHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void LbRsTargets::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_typeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Type";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator);
}
if (m_privateIpHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PrivateIp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_privateIp.c_str(), allocator).Move(), allocator);
}
if (m_portHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Port";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_port, allocator);
}
if (m_vpcIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VpcId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_vpcId, allocator);
}
if (m_weightHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Weight";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_weight, allocator);
}
}
string LbRsTargets::GetType() const
{
return m_type;
}
void LbRsTargets::SetType(const string& _type)
{
m_type = _type;
m_typeHasBeenSet = true;
}
bool LbRsTargets::TypeHasBeenSet() const
{
return m_typeHasBeenSet;
}
string LbRsTargets::GetPrivateIp() const
{
return m_privateIp;
}
void LbRsTargets::SetPrivateIp(const string& _privateIp)
{
m_privateIp = _privateIp;
m_privateIpHasBeenSet = true;
}
bool LbRsTargets::PrivateIpHasBeenSet() const
{
return m_privateIpHasBeenSet;
}
int64_t LbRsTargets::GetPort() const
{
return m_port;
}
void LbRsTargets::SetPort(const int64_t& _port)
{
m_port = _port;
m_portHasBeenSet = true;
}
bool LbRsTargets::PortHasBeenSet() const
{
return m_portHasBeenSet;
}
int64_t LbRsTargets::GetVpcId() const
{
return m_vpcId;
}
void LbRsTargets::SetVpcId(const int64_t& _vpcId)
{
m_vpcId = _vpcId;
m_vpcIdHasBeenSet = true;
}
bool LbRsTargets::VpcIdHasBeenSet() const
{
return m_vpcIdHasBeenSet;
}
int64_t LbRsTargets::GetWeight() const
{
return m_weight;
}
void LbRsTargets::SetWeight(const int64_t& _weight)
{
m_weight = _weight;
m_weightHasBeenSet = true;
}
bool LbRsTargets::WeightHasBeenSet() const
{
return m_weightHasBeenSet;
}
| 25.497696 | 139 | 0.663654 | suluner |
112ed45777794d1ae5d574904f83d384da51ed65 | 2,990 | hpp | C++ | AirLib/include/vehicles/plane/UFRudder.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | AirLib/include/vehicles/plane/UFRudder.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | AirLib/include/vehicles/plane/UFRudder.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | #ifndef airsimcore_ufrudder_hpp
#define airsimcore_ufrudder_hpp
#include "UniForce.hpp"
#include "UFRudderParams.hpp"
namespace msr {
namespace airlib {
class UFRudder : public UniForce
{
public:
UFRudder(const Vector3r& position, const Vector3r& normal, UFRudderParams::UniForceDirection turning_direction,
UFRudderParams * params, const Environment* environment, uint id = -1)
: params_(params)
{
initialize(position, normal, turning_direction, environment, id);
setType(UniForceType::Rudder);
setWrench2Zero();
setObjType(UpdatableObject::typeUpdObj::rudder);
//params_->calculateMaxThrust();
}
UFRudderParams * getCurrentParams() const
{
return params_;
}
void reportState(StateReporter& reporter) override
{
reporter.writeValue("Dir", static_cast<int>(getTurningDirection()));
reporter.writeValue("Ctrl-in", getOutput().control_signal_input);
reporter.writeValue("Ctrl-fl", getOutput().control_signal_filtered);
reporter.writeValue("speed", getOutput().speed);
reporter.writeValue("thrust", getOutput().thrust);
reporter.writeValue("torque", getOutput().torque_scaler);
}
uint getActID() const override
{
return params_->getActID();
}
void setControlSignal(real_T control_signal) override
{
real_T ctrl = Utils::clip(control_signal, -1.0f, 1.0f);
UniForce::setControlSignal(ctrl);
}
protected:
void setWrench(Wrench& wrench) override
{
Vector3r normal = getNormal();
wrench.force = normal *( getOutput().thrust + getOutput().resistance )* getAirDensityRatio();
wrench.torque = Vector3r(0,0,0);
}
private:
void setOutput(Output& output, const FirstOrderFilter<real_T>& control_signal_filter) override
{
output.control_signal_input = control_signal_filter.getInput();
output.control_signal_filtered = control_signal_filter.getOutput();
auto ctrl_signal = output.control_signal_filtered - 0.5f;
output.angle = ctrl_signal * params_->getMaxAngle() ;
//resistance drag
Vector3r unit_z(0, 1, 0); //NED frame
Quaternionr angle_plane(AngleAxisr( output.angle, unit_z));
Vector3r force2plane = VectorMath::rotateVector(Vector3r(getAirSpeed().x(), 0, getAirSpeed().z()), angle_plane, true);
const float velocity_input = std::abs(force2plane.z()) * force2plane.z();
output.resistance = velocity_input * params_->getResistance();
//airflow correction
const float velocity_forward = getAirSpeed().x() * getAirSpeed().x();
output.thrust = velocity_forward * ctrl_signal * params_->getMaxThrust() ;
output.torque_scaler = 0.0f;
output.turning_direction = getTurningDirection();
output.vel_input = force2plane;
}
UniForceParams& getParams() const override
{
return (UniForceParams &)params_;
}
real_T getCtrlSigFltTC() const override
{
return params_->control_signal_filter_tc;
}
private:
UFRudderParams * params_;
};
}
}
#endif | 33.595506 | 122 | 0.71204 | artemopolus |
113035645ab7998f7dc2089bb49985b608411cf1 | 463 | cpp | C++ | Codeforces/158A - Next Round.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/158A - Next Round.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/158A - Next Round.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector <int> data;
for (int i = 0; i < n; i++) {
int input;
cin >> input;
data.push_back(input);
}
int kth_value = data.at(k - 1), count = 0;
for (int i = 0; i < data.size(); i++) {
if (data.at(i) >= kth_value && data.at(i) > 0)
count ++;
}
cout << count << endl;
return 0;
} | 17.148148 | 54 | 0.464363 | naimulcsx |
11375d1474b937d09f081169435e7038a8ecf073 | 11,688 | cpp | C++ | moon/core/network/socket.cpp | PM5616/moon | 04fe49c498caa53acb1b6a9ded76839a6c465289 | [
"MIT"
] | null | null | null | moon/core/network/socket.cpp | PM5616/moon | 04fe49c498caa53acb1b6a9ded76839a6c465289 | [
"MIT"
] | null | null | null | moon/core/network/socket.cpp | PM5616/moon | 04fe49c498caa53acb1b6a9ded76839a6c465289 | [
"MIT"
] | 1 | 2019-09-09T21:25:15.000Z | 2019-09-09T21:25:15.000Z | #include "socket.h"
#include "common/log.hpp"
#include "common/string.hpp"
#include "common/hash.hpp"
#include "worker.h"
#include "network/moon_connection.hpp"
#include "network/custom_connection.hpp"
#include "network/ws_connection.hpp"
using namespace moon;
socket::socket(router * r, worker* w, asio::io_context & ioctx)
: router_(r)
, worker_(w)
, ioc_(ioctx)
, timer_(ioctx)
{
response_ = message::create();
timeout();
}
uint32_t socket::listen(const std::string & ip, uint16_t port, uint32_t owner, uint8_t type)
{
try
{
auto ctx = std::make_shared<socket::acceptor_context>(type, owner, ioc_);
asio::ip::tcp::resolver resolver(ioc_);
asio::ip::tcp::resolver::query query(ip, std::to_string(port));
auto iter = resolver.resolve(query);
asio::ip::tcp::endpoint endpoint = *iter;
ctx->acceptor.open(endpoint.protocol());
#if TARGET_PLATFORM != PLATFORM_WINDOWS
ctx->acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true));
#endif
ctx->acceptor.bind(endpoint);
ctx->acceptor.listen(std::numeric_limits<int>::max());
auto id = uuid();
ctx->fd = id;
acceptors_.emplace(id, ctx);
return id;
}
catch (asio::system_error& e)
{
CONSOLE_ERROR(router_->logger(), "%s:%d %s(%d)", ip.data(), port, e.what(), e.code().value());
return 0;
}
}
void socket::accept(int fd, int32_t sessionid, uint32_t owner)
{
MOON_CHECK(owner > 0, "socket::accept : invalid serviceid");
auto iter = acceptors_.find(fd);
if (iter == acceptors_.end())
{
return;
}
auto& ctx = iter->second;
if (!ctx->acceptor.is_open())
{
return;
}
worker* w = router_->get_worker(router_->worker_id(owner));
auto c = w->socket().make_connection(owner, ctx->type);
ctx->acceptor.async_accept(c->socket(), [this, ctx, c, w, sessionid, owner](const asio::error_code& e)
{
if (!e)
{
c->fd(w->socket().uuid());
w->socket().add_connection(c, true);
if (sessionid == 0)
{
accept(ctx->fd, sessionid, owner);
}
else
{
response(ctx->fd, ctx->owner, std::to_string(c->fd()), std::string_view{}, sessionid, PTYPE_TEXT);
}
}
else
{
if (sessionid != 0)
{
response(ctx->fd, ctx->owner, moon::format("socket::accept error %s(%d)", e.message().data(), e.value()), "error"sv, sessionid, PTYPE_ERROR);
}
else
{
if (e != asio::error::operation_aborted)
{
CONSOLE_WARN(router_->logger(), "socket::accept error %s(%d)", e.message().data(), e.value());
}
close(ctx->fd);
}
}
});
}
int socket::connect(const std::string& host, uint16_t port, uint32_t serviceid, uint32_t owner, uint8_t type, int32_t sessionid, int32_t timeout)
{
try
{
asio::ip::tcp::resolver resolver(ioc_);
asio::ip::tcp::resolver::query query(host, std::to_string(port));
asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
worker* w = router_->get_worker(router_->worker_id(owner));
auto c = w->socket().make_connection(owner, type);
if (0 == sessionid)
{
asio::connect(c->socket(), endpoint_iterator);
c->fd(w->socket().uuid());
w->socket().add_connection(c, false);
return c->fd();
}
else
{
if (timeout > 0)
{
std::shared_ptr<asio::steady_timer> connect_timer = std::make_shared<asio::steady_timer>(ioc_);
connect_timer->expires_from_now(std::chrono::milliseconds(timeout));
connect_timer->async_wait([this, c, serviceid, sessionid, host, port, connect_timer](const asio::error_code & e) {
if (e)
{
CONSOLE_ERROR(router_->logger(), "connect %s:%d timer error %s", host.data(), port, e.message().data());
return;
}
if (c->fd() == 0)
{
c->close();
response(0, serviceid, std::string_view{}, moon::format("connect %s:%d timeout", host.data(), port), sessionid, PTYPE_ERROR);
}
});
}
asio::async_connect(c->socket(), endpoint_iterator,
[this, c, w, host, port, serviceid, sessionid](const asio::error_code& e, asio::ip::tcp::resolver::iterator)
{
if (!e)
{
c->fd(w->socket().uuid());
w->socket().add_connection(c, false);
response(0, serviceid, std::to_string(c->fd()), std::string_view{}, sessionid, PTYPE_TEXT);
}
else
{
if (c->socket().is_open())
{
response(0, serviceid, std::string_view{}, moon::format("connect %s:%d failed: %s(%d)", host.data(), port, e.message().data(), e.value()), sessionid, PTYPE_ERROR);
}
}
});
}
}
catch (asio::system_error& e)
{
if (sessionid == 0)
{
CONSOLE_WARN(router_->logger(), "connect %s:%d failed: %s(%d)", host.data(), port, e.code().message().data(), e.code().value());
}
else
{
asio::post(ioc_, [this, host, port, serviceid, sessionid, e]() {
response(0,serviceid, std::string_view{}
, moon::format("connect %s:%d failed: %s(%d)", host.data(), port, e.code().message().data(), e.code().value())
, sessionid, PTYPE_ERROR);
});
}
}
return 0;
}
void socket::read(uint32_t fd, uint32_t owner, size_t n, read_delim delim, int32_t sessionid)
{
do
{
if (auto iter = connections_.find(fd); iter != connections_.end())
{
if (iter->second->read(moon::read_request{ delim, n, sessionid }))
{
return;
}
}
} while (0);
ioc_.post([this, owner, sessionid]() {
response(0, owner, "read an invalid socket", "closed", sessionid, PTYPE_ERROR);
});
}
bool socket::write(uint32_t fd, const buffer_ptr_t & data)
{
auto iter = connections_.find(fd);
if (iter == connections_.end())
{
return false;
}
return iter->second->send(data);
}
bool socket::write_with_flag(uint32_t fd, const buffer_ptr_t & data, int flag)
{
auto iter = connections_.find(fd);
if (iter == connections_.end())
{
return false;
}
MOON_ASSERT(flag > 0 && flag < static_cast<int>(buffer_flag::buffer_flag_max), "socket::write_with_flag flag invalid")
data->set_flag(static_cast<buffer_flag>(flag));
return iter->second->send(data);
}
bool socket::write_message(uint32_t fd, message * m)
{
return write(fd, *m);
}
bool socket::close(uint32_t fd,bool remove)
{
if (auto iter = connections_.find(fd); iter != connections_.end())
{
iter->second->close();
if (remove)
{
connections_.erase(iter);
unlock_fd(fd);
}
return true;
}
if (auto iter = acceptors_.find(fd); iter != acceptors_.end())
{
if (iter->second->acceptor.is_open())
{
iter->second->acceptor.cancel();
iter->second->acceptor.close();
}
if (remove)
{
acceptors_.erase(iter);
unlock_fd(fd);
}
return true;
}
return false;
}
bool socket::settimeout(uint32_t fd, int v)
{
if (auto iter = connections_.find(fd); iter != connections_.end())
{
iter->second->settimeout(v);
return true;
}
return false;
}
bool socket::setnodelay(uint32_t fd)
{
if (auto iter = connections_.find(fd); iter != connections_.end())
{
iter->second->set_no_delay();
return true;
}
return false;
}
bool socket::set_enable_frame(uint32_t fd, std::string flag)
{
moon::lower(flag);
moon::frame_enable_flag v = frame_enable_flag::none;
switch (moon::chash_string(flag))
{
case "none"_csh:
{
v = moon::frame_enable_flag::none;
break;
}
case "r"_csh:
{
v = moon::frame_enable_flag::receive;
break;
}
case "w"_csh:
{
v = moon::frame_enable_flag::send;
break;
}
case "wr"_csh:
case "rw"_csh:
{
v = moon::frame_enable_flag::both;
break;
}
default:
CONSOLE_WARN(router_->logger(), "tcp::set_enable_frame Unsupported enable frame flag %s.Support: 'r' 'w' 'wr' 'rw'.", flag.data());
return false;
}
if (auto iter = connections_.find(fd); iter != connections_.end())
{
auto c = std::dynamic_pointer_cast<moon_connection>(iter->second);
if (c)
{
c->set_frame_flag(v);
return true;
}
}
return false;
}
uint32_t socket::uuid()
{
uint32_t res = 0;
do
{
res = uuid_.fetch_add(1);
res %= max_socket_num;
++res;
res |= (worker_->id() << 16);
} while (!try_lock_fd(res));
return res;
}
connection_ptr_t socket::make_connection(uint32_t serviceid, uint8_t type)
{
connection_ptr_t connection;
switch (type)
{
case PTYPE_SOCKET:
{
connection = std::make_shared<moon_connection>(serviceid, type, this, ioc_);
break;
}
case PTYPE_TEXT:
{
connection = std::make_shared<custom_connection>(serviceid, type, this, ioc_);
break;
}
case PTYPE_SOCKET_WS:
{
connection = std::make_shared<ws_connection>(serviceid, type, this, ioc_);
break;
}
default:
break;
}
connection->logger(router_->logger());
return connection;
}
void socket::response(uint32_t sender, uint32_t receiver, string_view_t data, string_view_t header, int32_t sessionid, uint8_t type)
{
if (0 == sessionid)
return;
response_->set_sender(sender);
response_->set_receiver(0);
response_->get_buffer()->clear();
response_->get_buffer()->write_back(data.data(), 0, data.size());
response_->set_header(header);
response_->set_sessionid(sessionid);
response_->set_type(type);
handle_message(receiver, response_);
}
bool socket::try_lock_fd(uint32_t fd)
{
std::unique_lock lck(lock_);
return fd_watcher_.emplace(fd).second;
}
void socket::unlock_fd(uint32_t fd)
{
std::unique_lock lck(lock_);
size_t count = fd_watcher_.erase(fd);
MOON_CHECK(count == 1, "socket fd erase failed!");
}
void socket::add_connection(const connection_ptr_t & c, bool accepted)
{
asio::dispatch(ioc_, [c, accepted, this]() mutable {
connections_.emplace(c->fd(), c);
c->start(accepted);
});
}
service * socket::find_service(uint32_t serviceid)
{
return worker_->find_service(serviceid);;
}
void socket::timeout()
{
timer_.expires_from_now(std::chrono::seconds(10));
timer_.async_wait([this](const asio::error_code & e) {
if (e)
{
return;
}
auto now = base_connection::now();
for (auto& connection : connections_)
{
connection.second->timeout(now);
}
timeout();
});
}
| 28.231884 | 187 | 0.548939 | PM5616 |
113a22f0880d64de816b0cf42ffa0668639a02b9 | 1,710 | hpp | C++ | src/share/connected_devices/details/descriptions.hpp | egelwan/Karabiner-Elements | 896439dd2130904275553282063dd7fe4852e1a8 | [
"Unlicense"
] | 5,422 | 2019-10-27T17:51:04.000Z | 2022-03-31T15:45:41.000Z | src/share/connected_devices/details/descriptions.hpp | XXXalice/Karabiner-Elements | 52f579cbf60251cf18915bd938eb4431360b763b | [
"Unlicense"
] | 1,310 | 2019-10-28T04:57:24.000Z | 2022-03-31T04:55:37.000Z | src/share/connected_devices/details/descriptions.hpp | XXXalice/Karabiner-Elements | 52f579cbf60251cf18915bd938eb4431360b763b | [
"Unlicense"
] | 282 | 2019-10-28T02:36:04.000Z | 2022-03-19T06:18:54.000Z | #pragma once
#include "device_properties.hpp"
#include <pqrs/json.hpp>
namespace krbn {
namespace connected_devices {
namespace details {
class descriptions {
public:
descriptions(void) : descriptions("", "") {
}
descriptions(const std::string& manufacturer,
const std::string& product) : manufacturer_(manufacturer),
product_(product) {
}
descriptions(const device_properties& device_properties) : descriptions(device_properties.get_manufacturer().value_or(""),
device_properties.get_product().value_or("")) {
}
static descriptions make_from_json(const nlohmann::json& json) {
return descriptions(pqrs::json::find<std::string>(json, "manufacturer").value_or(""),
pqrs::json::find<std::string>(json, "product").value_or(""));
}
nlohmann::json to_json(void) const {
return nlohmann::json({
{"manufacturer", manufacturer_},
{"product", product_},
});
}
const std::string& get_manufacturer(void) const {
return manufacturer_;
}
const std::string& get_product(void) const {
return product_;
}
bool operator==(const descriptions& other) const {
return manufacturer_ == other.manufacturer_ &&
product_ == other.product_;
}
bool operator!=(const descriptions& other) const {
return !(*this == other);
}
private:
std::string manufacturer_;
std::string product_;
};
inline void to_json(nlohmann::json& json, const descriptions& descriptions) {
json = descriptions.to_json();
}
} // namespace details
} // namespace connected_devices
} // namespace krbn
| 27.580645 | 124 | 0.634503 | egelwan |
113f4fd6d216825e4a30be9575443514be07c4cb | 887 | hpp | C++ | include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
namespace RED4ext
{
namespace anim {
struct AnimNode_BlendSpace_InternalsBlendSpacePoint
{
static constexpr const char* NAME = "animAnimNode_BlendSpace_InternalsBlendSpacePoint";
static constexpr const char* ALIAS = NAME;
CName animationName; // 00
bool useFixedCoordinates; // 08
uint8_t unk09[0x10 - 0x9]; // 9
DynArray<float> fixedCoordinates; // 10
bool useStaticPose; // 20
uint8_t unk21[0x24 - 0x21]; // 21
float staticPoseTime; // 24
float staticPoseProgress; // 28
uint8_t unk2C[0x30 - 0x2C]; // 2C
};
RED4EXT_ASSERT_SIZE(AnimNode_BlendSpace_InternalsBlendSpacePoint, 0x30);
} // namespace anim
} // namespace RED4ext
| 27.71875 | 91 | 0.735062 | Cyberpunk-Extended-Development-Team |
114271b5c47275bf0579b389fa1c3a5a0c384cfc | 460 | cpp | C++ | BOJ_CPP/12789.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/12789.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/12789.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int n, board = 1, board[1001], board, t;
int main() {
fastio;
cin >> n;
for (int i = 0; i <= n; ++i) {
if (i < n) {
cin >> board;
board[++t] = board;
}
while (t && board[t] == board) {
--t;
++board;
}
}
cout << (t ? "Sad" : "Nice");
return 0;
} | 20.909091 | 63 | 0.428261 | tnsgh9603 |
1143e3c9a20da3c8c480e28247b909e41e87d942 | 618 | cpp | C++ | src/BucketSort.cpp | MarutTomasz/PAMSI_Projekt_2 | e8a154babd328fb18f48304021af90d6d7a79480 | [
"MIT"
] | null | null | null | src/BucketSort.cpp | MarutTomasz/PAMSI_Projekt_2 | e8a154babd328fb18f48304021af90d6d7a79480 | [
"MIT"
] | null | null | null | src/BucketSort.cpp | MarutTomasz/PAMSI_Projekt_2 | e8a154babd328fb18f48304021af90d6d7a79480 | [
"MIT"
] | null | null | null | #include "BucketSort.hh"
void BucketSort(Element Tablica[], long int pierwszy_element, long int ostatni_element) {
Kubel Wiadro[11]; // stwórz tablice kubłów
long int k = 0; // zmienna pomocnicza do obsługi tablicy
for(long int i = pierwszy_element; i <= ostatni_element; i++) // Powtarzaj dla całej tablicy
Wiadro[Tablica[i].getOcena()].addLast(Tablica[i]); // Wrzuć elementy do odpowiedniego kubła
for(int j = 0; j <= 10; j++) // powtarzaj dla każdego kubła
while(!Wiadro[j].isEmpty()) // Az kubeł nie będzie pusty
Tablica[k++] = Wiadro[j].takeFront(); // Wrzucaj z kubła do tablicy
}
| 44.142857 | 95 | 0.68932 | MarutTomasz |
1143e5133ef4efc20855683f857ea2bfb104721d | 17,704 | cpp | C++ | Source/ResourceAnimator.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 10 | 2019-02-05T07:57:21.000Z | 2021-10-17T13:44:31.000Z | Source/ResourceAnimator.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 178 | 2019-02-26T17:29:08.000Z | 2019-06-05T10:55:42.000Z | Source/ResourceAnimator.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 2 | 2020-02-27T18:57:27.000Z | 2020-05-28T01:19:59.000Z | #include "ResourceAnimator.h"
#include "imgui/imgui.h"
#include "ModuleScene.h"
#include "ModuleFileSystem.h"
#include "Application.h"
#include "Optick/include/optick.h"
#include "ModuleTimeManager.h"
#include "Application.h"
#include "ResourceAvatar.h"
#include "ModuleResourceManager.h"
#include <assert.h>
ResourceAnimator::ResourceAnimator(ResourceTypes type, uint uuid, ResourceData data, ResourceAnimatorData animator_data) : Resource(type, uuid, data), animator_data(animator_data)
{}
ResourceAnimator::~ResourceAnimator()
{
}
bool ResourceAnimator::LoadInMemory()
{
return true;
}
bool ResourceAnimator::UnloadFromMemory()
{
return true;
}
void ResourceAnimator::OnPanelAssets()
{
#ifndef GAMEMODE
ImGuiTreeNodeFlags flags = 0;
flags |= ImGuiTreeNodeFlags_::ImGuiTreeNodeFlags_Leaf;
if (App->scene->selectedObject == this)
flags |= ImGuiTreeNodeFlags_::ImGuiTreeNodeFlags_Selected;
char id[DEFAULT_BUF_SIZE];
sprintf(id, "%s##%d", data.name.data(), uuid);
if (ImGui::TreeNodeEx(id, flags))
ImGui::TreePop();
if (ImGui::IsMouseReleased(0) && ImGui::IsItemHovered() /*&& (mouseDelta.x == 0 && mouseDelta.y == 0)*/)
{
SELECT(this);
}
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
{
ImGui::SetDragDropPayload("ANIMATOR_INSPECTOR_SELECTOR", &uuid, sizeof(uint));
ImGui::EndDragDropSource();
}
#endif // !GAMEMODE
}
bool ResourceAnimator::ImportFile(const char* file, std::string& name, std::string& outputFile)
{
assert(file != nullptr);
// Search for the meta associated to the file
char metaFile[DEFAULT_BUF_SIZE];
strcpy_s(metaFile, strlen(file) + 1, file); // file
strcat_s(metaFile, strlen(metaFile) + strlen(EXTENSION_META) + 1, EXTENSION_META); // extension
if (App->fs->Exists(metaFile))
{
// Read the meta
uint uuid = 0;
int64_t lastModTime = 0;
bool result = ResourceAnimator::ReadMeta(metaFile, lastModTime, uuid, name);
assert(result);
// The uuid of the resource would be the entry
char entry[DEFAULT_BUF_SIZE];
sprintf_s(entry, "%u", uuid);
outputFile = entry;
}
return true;
}
bool ResourceAnimator::ExportFile(ResourceData& resourceData, ResourceAnimatorData& animData, std::string& outputFile, bool overwrite)
{
bool ret = false;
uint nameSize = DEFAULT_BUF_SIZE;
// Name
char animator_name[DEFAULT_BUF_SIZE];
strcpy_s(animator_name, DEFAULT_BUF_SIZE, animData.name.data());
uint animations_size = animData.animations_uuids.size();
uint meshes_size = animData.meshes_uuids.size();
uint size =
sizeof(uint) +
sizeof(uint) +
sizeof(uint) * animations_size +
sizeof(uint) +
sizeof(uint) * meshes_size +
sizeof(uint) + // name size
sizeof(char) * nameSize; // name
char* buffer = new char[size];
char* cursor = buffer;
// 1. Store avatar uuid
uint bytes = sizeof(uint);
memcpy(cursor, &animData.avatar_uuid, bytes);
cursor += bytes;
// 2. Store animations size
bytes = sizeof(uint);
memcpy(cursor, &animations_size, bytes);
cursor += bytes;
// 3. Store animations
for (uint i = 0; i < animations_size; ++i)
{
bytes = sizeof(uint);
memcpy(cursor, &animData.animations_uuids[i], bytes);
cursor += bytes;
}
// 4. Store meshes size
bytes = sizeof(uint);
memcpy(cursor, &meshes_size, bytes);
cursor += bytes;
// 5. Store Meshes
for (uint i = 0; i < meshes_size; ++i)
{
bytes = sizeof(uint);
memcpy(cursor, &animData.meshes_uuids[i], bytes);
cursor += bytes;
}
// 2. Store name size
bytes = sizeof(uint);
memcpy(cursor, &nameSize, bytes);
cursor += bytes;
// 3. Store name
bytes = sizeof(char) * nameSize;
memcpy(cursor, &animator_name, bytes);
//cursor += bytes;
// --------------------------------------------------
// Build the path of the file
if (overwrite)
outputFile = resourceData.file;
else
outputFile = resourceData.name;
// Save the file
ret = App->fs->SaveInGame(buffer, size, FileTypes::AnimatorFile, outputFile, overwrite) > 0;
if (ret)
{
CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved Animator '%s'", outputFile.data());
}
else
CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save Animator '%s'", outputFile.data());
RELEASE_ARRAY(buffer);
return ret;
}
uint ResourceAnimator::CreateMeta(const char* file, uint animatorUuid, std::string& name, std::string& outputMetaFile)
{
assert(file != nullptr);
uint uuidsSize = 1;
uint nameSize = DEFAULT_BUF_SIZE;
// Name
char animator_name[DEFAULT_BUF_SIZE];
strcpy_s(animator_name, DEFAULT_BUF_SIZE, name.data());
// --------------------------------------------------
uint size =
sizeof(int64_t) +
sizeof(uint) +
sizeof(uint) * uuidsSize +
sizeof(uint) + // name size
sizeof(char) * nameSize;
char* data = new char[size];
char* cursor = data;
// 1. Store last modification time
int64_t lastModTime = App->fs->GetLastModificationTime(file);
assert(lastModTime > 0);
uint bytes = sizeof(int64_t);
memcpy(cursor, &lastModTime, bytes);
cursor += bytes;
// 2. Store uuids size
bytes = sizeof(uint);
memcpy(cursor, &uuidsSize, bytes);
cursor += bytes;
// 3. Store animator uuid
bytes = sizeof(uint) * uuidsSize;
memcpy(cursor, &animatorUuid, bytes);
cursor += bytes;
// 4. Store animator name size
bytes = sizeof(uint);
memcpy(cursor, &nameSize, bytes);
cursor += bytes;
// 5. Store animator name
bytes = sizeof(char) * nameSize;
memcpy(cursor, animator_name, bytes);
cursor += bytes;
// --------------------------------------------------
// Build the path of the meta file and save it
outputMetaFile = file;
outputMetaFile.append(EXTENSION_META);
uint resultSize = App->fs->Save(outputMetaFile.data(), data, size);
if (resultSize > 0)
{
CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved meta '%s'", outputMetaFile.data());
}
else
{
CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save meta '%s'", outputMetaFile.data());
return 0;
}
return lastModTime;
}
bool ResourceAnimator::ReadMeta(const char* metaFile, int64_t& lastModTime, uint& animatorUuid, std::string& name)
{
assert(metaFile != nullptr);
char* buffer;
uint size = App->fs->Load(metaFile, &buffer);
if (size > 0)
{
char* cursor = (char*)buffer;
// 1. Load last modification time
uint bytes = sizeof(int64_t);
memcpy(&lastModTime, cursor, bytes);
cursor += bytes;
// 2. Load uuids size
uint uuidsSize = 0;
bytes = sizeof(uint);
memcpy(&uuidsSize, cursor, bytes);
assert(uuidsSize > 0);
cursor += bytes;
// 3. Load animation uuid
bytes = sizeof(uint) * uuidsSize;
memcpy(&animatorUuid, cursor, bytes);
cursor += bytes;
// 4. Load animation name size
uint nameSize = 0;
bytes = sizeof(uint);
memcpy(&nameSize, cursor, bytes);
assert(nameSize > 0);
cursor += bytes;
// 5. Load animation name
name.resize(nameSize);
bytes = sizeof(char) * nameSize;
memcpy(&name[0], cursor, bytes);
CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully loaded meta '%s'", metaFile);
RELEASE_ARRAY(buffer);
}
else
{
CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not load meta '%s'", metaFile);
return false;
}
return true;
}
bool ResourceAnimator::LoadFile(const char* file, ResourceAnimatorData& outputAnimationData)
{
assert(file != nullptr);
bool ret = false;
char* buffer;
uint size = App->fs->Load(file, &buffer);
if (size > 0)
{
char* cursor = (char*)buffer;
// 1. Load avatar uuid
uint bytes = sizeof(uint);
memcpy(&outputAnimationData.avatar_uuid, cursor, bytes);
cursor += bytes;
// 2. Load animations size
uint animations_size = 0u;
bytes = sizeof(uint);
memcpy(&animations_size, cursor, bytes);
cursor += bytes;
// 3. Load animations
outputAnimationData.animations_uuids.reserve(animations_size);
for (uint i = 0; i < animations_size; ++i)
{
bytes = sizeof(uint);
uint anim_uuid = 0u;
memcpy(&anim_uuid, cursor, bytes);
outputAnimationData.animations_uuids.push_back(anim_uuid);
cursor += bytes;
}
outputAnimationData.animations_uuids.shrink_to_fit();
// 2. Load meshes size
uint meshes_size = 0u;
bytes = sizeof(uint);
memcpy(&meshes_size, cursor, bytes);
cursor += bytes;
// 3. Load meshes
outputAnimationData.meshes_uuids.reserve(meshes_size);
for (uint i = 0; i < meshes_size; ++i)
{
bytes = sizeof(uint);
uint mesh_uuid = 0u;
memcpy(&mesh_uuid, cursor, bytes);
outputAnimationData.meshes_uuids.push_back(mesh_uuid);
cursor += bytes;
}
outputAnimationData.meshes_uuids.shrink_to_fit();
// 2. Load name size
bytes = sizeof(uint);
uint nameSize = 0;
memcpy(&nameSize, cursor, bytes);
assert(nameSize > 0);
cursor += bytes;
// 3. Load name
if (nameSize > 0) {
bytes = sizeof(char) * nameSize;
outputAnimationData.name.resize(nameSize);
memcpy(&outputAnimationData.name[0], cursor, bytes);
}
CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully loaded Animator '%s'", file);
RELEASE_ARRAY(buffer);
}
else
CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not load Animator '%s'", file);
return ret;
}
bool ResourceAnimator::GenerateLibraryFiles() const
{
assert(data.file.data() != nullptr);
// Search for the meta associated to the file
char metaFile[DEFAULT_BUF_SIZE];
strcpy_s(metaFile, strlen(data.file.data()) + 1, data.file.data()); // file
strcat_s(metaFile, strlen(metaFile) + strlen(EXTENSION_META) + 1, EXTENSION_META); // extension
// 1. Copy meta
if (App->fs->Exists(metaFile))
{
std::string outputFile;
uint size = App->fs->Copy(metaFile, DIR_LIBRARY_ANIMATORS, outputFile);
if (size > 0)
{
// 2. Copy Animator
outputFile.clear();
uint size = App->fs->Copy(data.file.data(), DIR_LIBRARY_ANIMATORS, outputFile);
if (size > 0)
return true;
}
}
return false;
}
uint ResourceAnimator::SetNameToMeta(const char* metaFile, const std::string& name)
{
assert(metaFile != nullptr);
int64_t lastModTime = 0;
uint materialUuid = 0;
std::string oldName;
ReadMeta(metaFile, lastModTime, materialUuid, oldName);
uint uuidsSize = 1;
uint nameSize = DEFAULT_BUF_SIZE;
// Name
char materialName[DEFAULT_BUF_SIZE];
strcpy_s(materialName, DEFAULT_BUF_SIZE, name.data());
uint size =
sizeof(int64_t) +
sizeof(uint) +
sizeof(uint) * uuidsSize +
sizeof(uint) + // name size
sizeof(char) * nameSize; // name
char* data = new char[size];
char* cursor = data;
// 1. Store last modification time
uint bytes = sizeof(int64_t);
memcpy(cursor, &lastModTime, bytes);
cursor += bytes;
// 2. Store uuids size
bytes = sizeof(uint);
memcpy(cursor, &uuidsSize, bytes);
cursor += bytes;
// 3. Store animator uuid
bytes = sizeof(uint) * uuidsSize;
memcpy(cursor, &materialUuid, bytes);
cursor += bytes;
// 4. Store animator name size
bytes = sizeof(uint);
memcpy(cursor, &nameSize, bytes);
cursor += bytes;
// 5. Store animator name
bytes = sizeof(char) * nameSize;
memcpy(cursor, materialName, bytes);
cursor += bytes;
// --------------------------------------------------
// Build the path of the meta file and save it
uint retSize = App->fs->Save(metaFile, data, size);
if (retSize > 0)
{
CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved meta '%s'", metaFile);
}
else
{
CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save meta '%s'", metaFile);
return 0;
}
return lastModTime;
}
void ResourceAnimator::InitAnimator()
{
if (current_anim) {
current_anim->interpolate = true;
current_anim->loop = true;
}
anim_state = AnimationState::PLAYING;
}
bool ResourceAnimator::Update()
{
#ifndef GAMEMODE
OPTICK_CATEGORY("ResourceAnimator_Update", Optick::Category::Animation);
#endif // GAMEMODE
//if (App->GetEngineState() != engine_states::ENGINE_PLAY)
//return update_status::UPDATE_CONTINUE;
if (stop_all)
return update_status::UPDATE_CONTINUE;
if (current_anim == nullptr)
return update_status::UPDATE_CONTINUE;
float dt = App->timeManager->GetDt();
float predicted_time = dt + current_anim->anim_timer;
if (predicted_time >= current_anim->duration && current_anim->duration > 0.0f)
{
current_anim->finished = true;
if (!current_anim->loop)
anim_state = AnimationState::STOPPED;
else
current_anim->anim_timer = 0.0f;
}
else
{
current_anim->finished = false;
}
switch (anim_state)
{
case AnimationState::PLAYING: {
current_anim->anim_timer += dt * current_anim->anim_speed * animation_speed_mod;
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer);
}
}
break;
case AnimationState::PAUSED:
break;
case AnimationState::STOPPED: {
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer);
}
current_anim->anim_timer = 0.0f;
PauseAnimation();
}
break;
case AnimationState::BLENDING: {
last_anim->anim_timer += dt * last_anim->anim_speed * animation_speed_mod;
current_anim->anim_timer += dt * current_anim->anim_speed * animation_speed_mod;
blend_timer += dt;
float blend_percentage = blend_timer / 1.0f;
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(last_anim->animation_uuid, last_anim->anim_timer, blend_percentage);
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer, blend_percentage);
}
if (blend_percentage >= blend_timelapse)
anim_state = PLAYING;
}
break;
}
return true;
}
void ResourceAnimator::SetAnimationSpeed(float new_speed)
{
animation_speed_mod = new_speed;
}
void ResourceAnimator::SetAnimationBlendTime(float new_blend)
{
blend_timelapse = new_blend;
}
void ResourceAnimator::ClearAnimations() {
for (uint i = 0u; i < animations.size(); i++)
{
Animation* animation = animations[i];
delete animation;
}
animations.clear();
current_anim = nullptr;
}
void ResourceAnimator::AddAnimationFromAnimationResource(ResourceAnimation * res)
{
Animation* animation = new Animation();
animation->name = res->animationData.name;
animation->animation_uuid = res->GetUuid();
animation->duration = res->animationData.duration;
animation->numKeys = res->animationData.numKeys;
animation->boneKeys = res->animationData.boneKeys;
animations.push_back(animation);
current_anim = animations[0];
current_anim->interpolate = true;
current_anim->loop = true;
}
float ResourceAnimator::GetCurrentAnimationTime() const
{
return current_anim->anim_timer;
}
const char * ResourceAnimator::GetAnimationName(int index) const
{
return animations[index]->name.c_str();
}
uint ResourceAnimator::GetAnimationsNumber() const
{
return (uint)animations.size();
}
ResourceAnimator::Animation * ResourceAnimator::GetCurrentAnimation() const
{
return current_anim;
}
void ResourceAnimator::SetCurrentAnimationTime(float time)
{
current_anim->anim_timer = time;
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer);
}
}
bool ResourceAnimator::SetCurrentAnimation(const char * anim_name)
{
for (uint i = 0u; i < animations.size(); i++)
{
Animation* it_anim = animations[i];
if (strcmp(it_anim->name.c_str(), anim_name) == 0) {
anim_state = BLENDING;
blend_timer = 0.0f;
last_anim = current_anim;
current_anim = it_anim;
SetCurrentAnimationTime(0.0f);
current_anim->finished = false;
current_anim->anim_timer = 0.0f;
return true;
}
}
return false;
}
void ResourceAnimator::PlayAnimation()
{
anim_state = AnimationState::PLAYING;
current_anim->anim_timer = 0.0f;
current_anim->finished = false;
ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
ava->SetIsAnimated(true);
}
void ResourceAnimator::PauseAnimation()
{
anim_state = AnimationState::PAUSED;
ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
//ava->SetIsAnimated(false);
}
void ResourceAnimator::StopAnimation()
{
anim_state = AnimationState::STOPPED;
ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
//ava->SetIsAnimated(false);
}
void ResourceAnimator::StepBackwards()
{
if (current_anim->anim_timer > 0.0f)
{
float dt = 0.0f;
dt = App->GetDt();
#ifdef GAMEMODE
dt = App->timeManager->GetDt();
#endif // GAMEMODE
current_anim->anim_timer -= dt * current_anim->anim_speed;
if (current_anim->anim_timer < 0.0f)
current_anim->anim_timer = 0.0f;
else {
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer);
}
}
PauseAnimation();
}
}
void ResourceAnimator::StepForward()
{
if (current_anim->anim_timer < current_anim->duration)
{
float dt = 0.0f;
dt = App->GetDt();
#ifdef GAMEMODE
dt = App->timeManager->GetDt();
#endif // GAMEMODE
current_anim->anim_timer += dt * current_anim->anim_speed;
if (current_anim->anim_timer > current_anim->duration)
current_anim->anim_timer = 0.0f;
else {
ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid);
if (tmp_avatar) {
tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer);
}
}
PauseAnimation();
}
}
| 23.859838 | 179 | 0.702666 | JellyBitStudios |
1146228624a8b8b9ab69bc02861e03c67580ec60 | 200 | hpp | C++ | Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | 1 | 2021-12-31T09:27:00.000Z | 2021-12-31T09:27:00.000Z | Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | null | null | null | Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | 1 | 2021-12-22T03:34:04.000Z | 2021-12-22T03:34:04.000Z | #ifndef ISP_IMP_HPP
#define ISP_IMP_HPP
#include "stm32f4xx.h"
extern "C" void CAN1_RX0_IRQHandler(void);
extern "C" void CAN2_RX0_IRQHandler(void);
extern "C" void USART6_IRQHandler(void);
#endif
| 18.181818 | 42 | 0.78 | PhilosopheAM |
114680078d851d23f4ce09c036e0378d9c0da4e0 | 830 | cpp | C++ | VRDemoHelper/VRDemoHotKeyManager.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | VRDemoHelper/VRDemoHotKeyManager.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | VRDemoHelper/VRDemoHotKeyManager.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "VRDemoHotKeyManager.h"
#include "util\l4util.h"
#include "VRDemoConfigurator.h"
#include "VRDemoTogglesWrapper.h"
const std::string VRDemoHotKeyManager::HOT_KEY_PAUSE = "HotKeyPause";
VRDemoHotKeyManager::VRDemoHotKeyManager()
{
}
VRDemoHotKeyManager::~VRDemoHotKeyManager()
{
}
void VRDemoHotKeyManager::configurate(HWND wnd)
{
// TODO: to make it configuable
/*
const VRDemoConfigurator::KeyValueMap *helperSection = VRDemoConfigurator::getInstance().getHelperSection();
if (helperSection) {
VRDemoConfigurator::KeyValueMap::const_iterator it = helperSection->find(l4util::toUpper(HOT_KEY_PAUSE));
std::string keyPause;
if (it != helperSection->end()) {
keyPause = it->second;
}
}
*/
RegisterHotKey(wnd, 1, 0, VK_F8);
}
| 24.411765 | 113 | 0.701205 | sunzhuoshi |
114847aae9ce44d97ea043bd5ae07da63ae2c1b7 | 2,961 | cpp | C++ | 2/main.cpp | j00st/cpse2 | f541d9097d1db064974d71f816cf49ecae30c6f8 | [
"MIT"
] | null | null | null | 2/main.cpp | j00st/cpse2 | f541d9097d1db064974d71f816cf49ecae30c6f8 | [
"MIT"
] | null | null | null | 2/main.cpp | j00st/cpse2 | f541d9097d1db064974d71f816cf49ecae30c6f8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include <SFML/Graphics.hpp>
#include "ball.hpp"
#include "entity.hpp"
#include "character.hpp"
#include "wall.hpp"
class action {
private:
std::function< bool() > condition;
std::function< void() > work;
public:
action(
std::function< bool() > condition,
std::function< void() > work
) : condition( condition ),
work( work )
{}
action(
sf::Keyboard::Key key,
std::function< void() > work
) :
condition(
[ key ]()->bool { return sf::Keyboard::isKeyPressed( key ); }
),
work(work)
{}
action(
sf::Mouse::Button button,
std::function< void() > work
) :
condition(
[ button ]()->bool { return sf::Mouse::isButtonPressed( button ); }
),
work(work)
{}
action(
entity *thisEntity,
entity *otherEntity,
std::function< void() > work
) :
condition(
[ thisEntity, otherEntity ]()->bool {return thisEntity->getBoundingBox().intersects(otherEntity->getBoundingBox()); }
),
work(work)
{}
void operator()(){
if( condition() ){
work();
}
}
};
int main( int argc, char *argv[] ){
std::cout << "Starting application 2\n";
sf::RenderWindow window{ sf::VideoMode{ 640, 480 }, "2" };
std::vector<entity*> entityList;
entityList.push_back(new character(sf::Vector2f{160.0, 240.0}, sf::Vector2f{40.0,40.0}, sf::Color::Blue));
entityList.push_back(new wall(sf::Vector2f{0.0, 0.0}, sf::Vector2f{640.0, 10.0}, sf::Color::Red));
entityList.push_back(new wall(sf::Vector2f{0.0, 10.0}, sf::Vector2f{10.0, 460.0}, sf::Color::Blue));
entityList.push_back(new wall(sf::Vector2f{630.0, 10.0}, sf::Vector2f{10.0, 460.0}, sf::Color::Red));
entityList.push_back(new wall(sf::Vector2f{0.0, 470.0}, sf::Vector2f{640.0, 10.0}, sf::Color::Blue));
entityList.push_back(new ball(sf::Vector2f{400.0, 300.0}, sf::Vector2f{20.0, 0.0}, sf::Color::Red));
action actions[] = {
action( sf::Keyboard::Left, [&](){ entityList[0]->move( sf::Vector2f( -10.0, 0.0 )); }),
action( sf::Keyboard::Right, [&](){ entityList[0]->move( sf::Vector2f( +10.0, 0.0 )); }),
action( sf::Keyboard::Up, [&](){ entityList[0]->move( sf::Vector2f( 0.0, -10.0 )); }),
action( sf::Keyboard::Down, [&](){ entityList[0]->move( sf::Vector2f( 0.0, +10.0 )); }),
action( sf::Keyboard::Escape, [&](){ window.close(); })
};
while (window.isOpen()) {
window.clear();
for(auto & entity : entityList){
for(auto & otherEntity : entityList){
if(entity != otherEntity){
auto testcollision = action(entity, otherEntity, [&](){ entity->changeColor(); entity->collide(*otherEntity); });
testcollision();
}
}
entity->draw(window);
}
for( auto & action : actions ){
action();
}
window.display();
sf::sleep( sf::milliseconds( 20 ));
sf::Event event;
while( window.pollEvent(event) ){
if( event.type == sf::Event::Closed ){
window.close();
}
}
}
std::cout << "Terminating application\n";
return 0;
}
| 26.918182 | 120 | 0.61128 | j00st |
114a1391f6b8559b98560049e7c9e2fac7147cf0 | 5,737 | hpp | C++ | src/Players/MCTS/MCTS.hpp | ClubieDong/BoardGameAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | 2 | 2021-05-26T07:17:24.000Z | 2021-05-26T07:21:16.000Z | src/Players/MCTS/MCTS.hpp | ClubieDong/ChessAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | null | null | null | src/Players/MCTS/MCTS.hpp | ClubieDong/ChessAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include <cmath>
#include <cassert>
#include <set>
#include <chrono>
#include <random>
#include <ratio>
#include <type_traits>
#include "../RandomPlayer/RandomPlayer.hpp"
template <typename Game, typename ActGen, unsigned int Iterations, typename Ratio = std::ratio<14, 10>,
typename Rollout = RandomPlayer<Game, ActGen>>
class MCTS
{
static_assert(Iterations > 0);
static_assert(std::is_same_v<Game, typename Rollout::GameType>);
public:
inline static constexpr unsigned int PlayerCount = Game::PlayerCount;
using GameType = Game;
using Action = typename Game::Action;
using Result = typename Game::Result;
private:
inline static constexpr double C = static_cast<double>(Ratio::num) / Ratio::den;
static_assert(C >= 0);
class Node
{
friend class MCTS;
private:
Node *_Parent = nullptr;
Action _Action;
std::vector<std::unique_ptr<Node>> _Children;
std::unique_ptr<Game> _Game;
std::unique_ptr<ActGen> _ActGen;
unsigned int _NextPlayer;
std::array<double, PlayerCount> _Value{};
unsigned int _Count = 0;
public:
inline explicit Node(const Game &game, const ActGen &actGen)
: _Game(std::make_unique<Game>(game)),
_ActGen(std::make_unique<ActGen>(actGen)),
_NextPlayer(_Game->GetNextPlayer()) {}
inline explicit Node(std::unique_ptr<Game> game, std::unique_ptr<ActGen> actGen, Action action, Node &parent)
: _Parent(&parent), _Action(action), _Game(std::move(game)),
_ActGen(std::move(actGen)), _NextPlayer(_Game->GetNextPlayer()) {}
};
const Game *_Game;
ActGen _ActGen;
public:
inline explicit MCTS(const Game &game) : _Game(&game), _ActGen(game) {}
inline explicit MCTS(const Game &game, const std::vector<Action> &) : MCTS(game) {}
MCTS(const MCTS &) = delete;
MCTS &operator=(const MCTS &) = delete;
inline MCTS(MCTS &&) = default;
inline MCTS &operator=(MCTS &&) = default;
inline void Notify(Action act) { _ActGen.Notify(act); }
Action operator()()
{
Node root(*_Game, _ActGen);
for (unsigned int iter = 0; iter < Iterations; ++iter)
{
// Selection
Node *p = &root;
// While p is not a leaf node
while (p->_Children.size() != 0)
{
auto player = p->_NextPlayer;
double maxUCB = 0;
unsigned int index = -1;
for (unsigned int i = 0; i < p->_Children.size(); ++i)
{
auto &node = *p->_Children[i];
// Avoid 0 as divider
// When n_i == 0, UCB is infinite
if (node._Count == 0)
{
index = i;
break;
}
double ucb = node._Value[player] / node._Count;
ucb += C * std::sqrt(std::log(p->_Count) / node._Count);
if (ucb > maxUCB)
{
maxUCB = ucb;
index = i;
}
}
assert(index < p->_Children.size());
p = p->_Children[index].get();
}
// Expansion
if (p->_Count != 0 && !p->_Game->GetResult())
{
for (auto act : *p->_ActGen)
{
auto game = std::make_unique<Game>(*p->_Game);
auto actGen = std::make_unique<ActGen>(*p->_ActGen);
actGen->SetGame(*game);
(*game)(act);
actGen->Notify(act);
auto node = std::make_unique<Node>(std::move(game), std::move(actGen), act, *p);
p->_Children.push_back(std::move(node));
}
assert(p->_Children.size() > 0);
p->_Game = nullptr;
p->_ActGen = nullptr;
p = p->_Children[0].get();
}
// Rollout
Game game = *p->_Game;
Rollout roll(game);
auto value = game.GetResult();
while (!value)
{
auto act = roll();
game(act);
roll.Notify(act);
value = game.GetResult();
}
// Back propagation
while (true)
{
++p->_Count;
for (unsigned int i = 0; i < PlayerCount; ++i)
p->_Value[i] += (*value)[i];
if (p == &root)
break;
p = p->_Parent;
}
}
// Choose best move
std::set<unsigned int> bestSet;
double bestWinRate = 0;
for (unsigned int i = 0; i < root._Children.size(); ++i)
{
double rate = root._Children[i]->_Value[_Game->GetNextPlayer()] /
root._Children[i]->_Count;
if (rate == bestWinRate)
bestSet.insert(i);
else if (rate > bestWinRate)
{
bestSet.clear();
bestSet.insert(i);
bestWinRate = rate;
}
}
std::vector<unsigned int> bests(bestSet.cbegin(), bestSet.cend());
static auto seed = std::chrono::system_clock::now().time_since_epoch().count();
static std::default_random_engine e(seed);
std::uniform_int_distribution<unsigned int> random(0, bests.size() - 1);
return root._Children[bests[random(e)]]->_Action;
}
};
| 34.769697 | 117 | 0.495381 | ClubieDong |
11540f3b5fc42fa35160a78cfafa58bc64951b83 | 480 | cpp | C++ | Phi Sieve.cpp | ArniRahman/Number-Theory | 49ca663e8f425c4def53447fd9ad723b7096340a | [
"MIT"
] | null | null | null | Phi Sieve.cpp | ArniRahman/Number-Theory | 49ca663e8f425c4def53447fd9ad723b7096340a | [
"MIT"
] | null | null | null | Phi Sieve.cpp | ArniRahman/Number-Theory | 49ca663e8f425c4def53447fd9ad723b7096340a | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int phi[100000];
void phiSieve(int n)
{
for(int i=1; i<=n;i++)
phi[i] = i;
for(int i=2; i<=n; i++ )
{
if(phi[i]==i)
{
phi[i] = i-1;
for(int j= 2*i;j<=n;j+=i)
{
phi[j] = (phi[j]/i)*(i-1);
}
}
}
}
int main()
{
int n = 10;
phiSieve(n);
for(int i=1;i<=n;i++)
{
cout<<i<<" "<<phi[i]<<endl;
}
}
| 12.307692 | 42 | 0.35625 | ArniRahman |
115d84c1a5bfedf18d8d57a2759c260166164eb3 | 4,375 | cpp | C++ | ui/src/efxpreviewarea.cpp | hawesy/qlcplus | 1702f03144fe210611881f15424a535febae0c6a | [
"ECL-2.0",
"Apache-2.0"
] | 478 | 2015-01-20T14:51:17.000Z | 2022-03-31T06:56:05.000Z | ui/src/efxpreviewarea.cpp | hjtappe/qlcplus | b5537fa11d419d148eca5cb1321ee98d3dc5047b | [
"ECL-2.0",
"Apache-2.0"
] | 711 | 2015-01-05T06:50:06.000Z | 2022-03-06T20:31:07.000Z | ui/src/efxpreviewarea.cpp | hjtappe/qlcplus | b5537fa11d419d148eca5cb1321ee98d3dc5047b | [
"ECL-2.0",
"Apache-2.0"
] | 386 | 2015-01-07T15:36:59.000Z | 2022-03-31T06:56:07.000Z | /*
Q Light Controller
efxpreviewarea.cpp
Copyright (c) Heikki Junnila
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.txt
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 <QPaintEvent>
#include <QPainter>
#include <QDebug>
#include <QPen>
#include "efxpreviewarea.h"
#include "qlcmacros.h"
#include "gradient.h"
EFXPreviewArea::EFXPreviewArea(QWidget* parent)
: QWidget(parent)
, m_timer(this)
, m_iter(0)
, m_gradientBg(false)
, m_bgAlpha(255)
{
QPalette p = palette();
p.setColor(QPalette::Window, p.color(QPalette::Base));
setPalette(p);
connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
}
EFXPreviewArea::~EFXPreviewArea()
{
}
void EFXPreviewArea::setPolygon(const QPolygonF& polygon)
{
m_original = polygon;
m_scaled = scale(m_original, size());
}
int EFXPreviewArea::polygonsCount() const
{
return m_original.size();
}
void EFXPreviewArea::setFixturePolygons(const QVector<QPolygonF> &fixturePoints)
{
m_originalFixturePoints.resize(fixturePoints.size());
m_fixturePoints.resize(fixturePoints.size());
for(int i = 0; i < m_fixturePoints.size(); ++i)
{
m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]);
m_fixturePoints[i] = scale(m_originalFixturePoints[i], size());
}
}
void EFXPreviewArea::draw(int timerInterval)
{
m_timer.stop();
m_iter = 0;
m_timer.start(timerInterval);
}
void EFXPreviewArea::slotTimeout()
{
if (m_iter < m_scaled.size())
m_iter++;
repaint();
}
QPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target)
{
QPolygonF scaled;
for (int i = 0; i < poly.size(); i++)
{
QPointF pt = poly.at(i);
pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width())));
pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height())));
scaled << pt;
}
return scaled;
}
void EFXPreviewArea::resizeEvent(QResizeEvent* e)
{
m_scaled = scale(m_original, e->size());
for (int i = 0; i < m_fixturePoints.size(); ++i)
m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size());
QWidget::resizeEvent(e);
}
void EFXPreviewArea::paintEvent(QPaintEvent* e)
{
QWidget::paintEvent(e);
QPainter painter(this);
QPen pen;
QPointF point;
QColor color = Qt::white;
if (m_gradientBg)
painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256));
else
{
color.setAlpha(m_bgAlpha);
painter.fillRect(rect(), color);
}
/* Crosshairs */
color = palette().color(QPalette::Mid);
painter.setPen(color);
// Do division by two instead with a bitshift to prevent rounding
painter.drawLine(width() >> 1, 0, width() >> 1, height());
painter.drawLine(0, height() >> 1, width(), height() >> 1);
/* Plain points with text color */
color = palette().color(QPalette::Text);
pen.setColor(color);
painter.setPen(pen);
painter.drawPolygon(m_scaled);
// Draw the points from the point array
if (m_iter < m_scaled.size() && m_iter >= 0)
{
painter.setBrush(Qt::white);
pen.setColor(Qt::black);
// drawing fixture positions from the end,
// so that lower numbers are on top
for (int i = m_fixturePoints.size() - 1; i >= 0; --i)
{
point = m_fixturePoints.at(i).at(m_iter);
painter.drawEllipse(point, 8, 8);
painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1));
}
}
else
{
//Change old behaviour from stop to restart
restart();
}
}
void EFXPreviewArea::restart()
{
m_iter = 0;
}
void EFXPreviewArea::showGradientBackground(bool enable)
{
m_gradientBg = enable;
repaint();
}
void EFXPreviewArea::setBackgroundAlpha(int alpha)
{
m_bgAlpha = alpha;
}
| 24.717514 | 100 | 0.648229 | hawesy |
11618e2e68b188bf2607133d4de66fdbe614ed12 | 20,505 | cpp | C++ | src/xercesc/dom/deprecated/AttrImpl.cpp | allianz-pmichel/xerces-c-src_2_8_0 | 7e62f6c653944894a34ee41581e6d7d66e3387dd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/dom/deprecated/AttrImpl.cpp | allianz-pmichel/xerces-c-src_2_8_0 | 7e62f6c653944894a34ee41581e6d7d66e3387dd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/dom/deprecated/AttrImpl.cpp | allianz-pmichel/xerces-c-src_2_8_0 | 7e62f6c653944894a34ee41581e6d7d66e3387dd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* 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.
*/
/*
* $Id: AttrImpl.cpp 568078 2007-08-21 11:43:25Z amassari $
*
* <p><b>WARNING</b>: Some of the code here is partially duplicated in
* ParentNode, be careful to keep these two classes in sync!
*/
#include "AttrImpl.hpp"
#include "DOM_DOMException.hpp"
#include "DocumentImpl.hpp"
#include "TextImpl.hpp"
#include "ElementImpl.hpp"
#include "DStringPool.hpp"
#include "NodeIDMap.hpp"
#include "RangeImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
/*
* The handling of the value field being either the first child node (a
* ChildNode*) or directly the value (a DOMString) is rather tricky. In the
* DOMString case we need to get the field in the right type so that the
* compiler is happy and the appropriate operator gets called. This is
* essential for the reference counts of the DOMStrings involved to be updated
* as due.
* This is consistently achieved by taking the address of the value field and
* changing it into a DOMString*, and then dereferencing it to get a DOMString.
* The typical piece of code is:
* DOMString *x = (DomString *)&value;
* ... use of *x which is the DOMString ...
* This was amended by neilg after memory management was
* introduced. Now a union exists which is either a
* DOMString * or a ChildNode *. This will be less efficient
* (one more dereference per access) but actually works on all the
* compilers we support.
*/
AttrImpl::AttrImpl(DocumentImpl *ownerDoc, const DOMString &aName)
: NodeImpl (ownerDoc)
{
name = aName.clone();
isSpecified(true);
hasStringValue(true);
value.child = null;
};
AttrImpl::AttrImpl(const AttrImpl &other, bool /*deep*/)
: NodeImpl(other)
{
name = other.name.clone();
isSpecified(other.isSpecified());
/* We must initialize the void* value to null in *all* cases. Failing to do
* so would cause, in case of assignment to a DOMString later, its content
* to be derefenced as a DOMString, which would lead the ref count code to
* be called on something that is not actually a DOMString... Really bad
* things would then happen!!!
*/
value.child = null;
hasStringValue(other.hasStringValue());
if (other.isIdAttr())
{
isIdAttr(true);
this->getOwnerDocument()->getNodeIDMap()->add(this);
}
// take care of case where there are kids
if (!hasStringValue()) {
cloneChildren(other);
}
else {
if(other.value.str == null)
{
if(value.str != null)
{
*(value.str) = null;
delete value.str;
value.str = null;
}
}
else
{
// get the address of the value field of this as a DOMString*
DOMString *x = (value.str == null
?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString())
:value.str
);
// and the address of the value field of other as a DOMString*
DOMString *y = other.value.str;
// We can now safely do the cloning and assignement, both operands
// being a DOMString their ref counts will be updated appropriately
*x = y->clone();
}
}
};
AttrImpl::~AttrImpl() {
if (hasStringValue()) {
// if value is a DOMString we must make sure its ref count is updated.
// this is achieved by changing the address of the value field into a
// DOMString* and setting the value field to null
if(value.str != null)
{
*(value.str) = null;
delete value.str;
value.str = null;
}
}
}
// create a real Text node as child if we don't have one yet
void AttrImpl::makeChildNode() {
if (hasStringValue()) {
if (value.child != null) {
// change the address of the value field into a DOMString*
DOMString *x = (value.str == null
?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString())
:value.str
);
// create a Text node passing the DOMString it points to
TextImpl *text =
(TextImpl *) getOwnerDocument()->createTextNode(*x);
// get the DOMString ref count to be updated by setting the value
// field to null
*x = null;
delete x;
// finally reassign the value to the node address
value.child = text;
text->isFirstChild(true);
text->previousSibling = text;
text->ownerNode = this;
text->isOwned(true);
}
hasStringValue(false);
}
}
NodeImpl * AttrImpl::cloneNode(bool deep)
{
return new (getOwnerDocument()->getMemoryManager()) AttrImpl(*this, deep);
};
DOMString AttrImpl::getNodeName() {
return name;
};
short AttrImpl::getNodeType() {
return DOM_Node::ATTRIBUTE_NODE;
};
DOMString AttrImpl::getName()
{
return name;
};
DOMString AttrImpl::getNodeValue()
{
return getValue();
};
bool AttrImpl::getSpecified()
{
return isSpecified();
};
DOMString AttrImpl::getValue()
{
if (value.child == null) {
return 0; // return "";
}
if (hasStringValue()) {
// change value into a DOMString*
DOMString *x = (value.str == null
?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString())
:value.str
);
// return the DOMString it points to
return *x;
}
ChildNode *firstChild = value.child;
ChildNode *node = firstChild->nextSibling;
if (node == null) {
return firstChild->getNodeValue().clone();
}
int length = 0;
for (node = firstChild; node != null; node = node->nextSibling)
length += node->getNodeValue().length();
DOMString retString;
retString.reserve(length);
for (node = firstChild; node != null; node = node->nextSibling)
{
retString.appendData(node->getNodeValue());
};
return retString;
};
bool AttrImpl::isAttrImpl()
{
return true;
};
void AttrImpl::setNodeValue(const DOMString &val)
{
setValue(val);
};
void AttrImpl::setSpecified(bool arg)
{
isSpecified(arg);
};
void AttrImpl::setValue(const DOMString &newvalue)
{
if (isReadOnly())
{
throw DOM_DOMException
(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null
);
}
// If this attribute was of type ID and in the map, take it out,
// then put it back in with the new name. For now, we don't worry
// about what happens if the new name conflicts
//
if (isIdAttr())
this->getOwnerDocument()->getNodeIDMap()->remove(this);
if (!hasStringValue() && value.str != null) {
NodeImpl *kid;
while ((kid = value.child) != null) { // Remove existing kids
removeChild(kid);
if (kid->nodeRefCount == 0)
NodeImpl::deleteIf(kid);
}
}
// directly store the string as the value by changing the value field
// into a DOMString
DOMString *x = (value.str == null
?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString())
:value.str
);
if (newvalue != null) {
*x = newvalue.clone();
}
else {
*x = null;
delete x;
value.str = null;
}
hasStringValue(true);
isSpecified(true);
changed();
if (isIdAttr())
this->getOwnerDocument()->getNodeIDMap()->add(this);
};
DOMString AttrImpl::toString()
{
DOMString retString;
retString.appendData(name);
retString.appendData(DOMString("=\""));
retString.appendData(getValue());
retString.appendData(DOMString("\""));
return retString;
}
//Introduced in DOM Level 2
ElementImpl *AttrImpl::getOwnerElement()
{
// if we have an owner, ownerNode is our ownerElement, otherwise it's
// our ownerDocument and we don't have an ownerElement
return (ElementImpl *) (isOwned() ? ownerNode : null);
}
//internal use by parser only
void AttrImpl::setOwnerElement(ElementImpl *ownerElem)
{
ownerNode = ownerElem;
isOwned(false);
}
// ParentNode stuff
void AttrImpl::cloneChildren(const NodeImpl &other) {
// for (NodeImpl *mykid = other.getFirstChild();
for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild();
mykid != null;
mykid = mykid->getNextSibling()) {
this->appendChild(mykid->cloneNode(true));
}
}
NodeListImpl *AttrImpl::getChildNodes() {
return this;
}
NodeImpl * AttrImpl::getFirstChild() {
makeChildNode();
return value.child;
}
NodeImpl * AttrImpl::getLastChild() {
return lastChild();
}
ChildNode * AttrImpl::lastChild() {
// last child is stored as the previous sibling of first child
makeChildNode();
return value.child != null ? (value.child)->previousSibling : null;
}
void AttrImpl::lastChild(ChildNode *node) {
// store lastChild as previous sibling of first child
if (value.child != null) {
(value.child)->previousSibling = node;
}
}
unsigned int AttrImpl::getLength() {
if (hasStringValue()) {
return 1;
}
ChildNode *node = value.child;
int length = 0;
while (node != null) {
length++;
node = node->nextSibling;
}
return length;
}
bool AttrImpl::hasChildNodes()
{
return value.child != null;
};
NodeImpl *AttrImpl::insertBefore(NodeImpl *newChild, NodeImpl *refChild) {
DocumentImpl *ownerDocument = getOwnerDocument();
bool errorChecking = ownerDocument->getErrorChecking();
if (newChild->isDocumentFragmentImpl()) {
// SLOW BUT SAFE: We could insert the whole subtree without
// juggling so many next/previous pointers. (Wipe out the
// parent's child-list, patch the parent pointers, set the
// ends of the list.) But we know some subclasses have special-
// case behavior they add to insertBefore(), so we don't risk it.
// This approch also takes fewer bytecodes.
// NOTE: If one of the children is not a legal child of this
// node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
// have been transferred. (Alternative behaviors would be to
// reparent up to the first failure point or reparent all those
// which are acceptable to the target node, neither of which is
// as robust. PR-DOM-0818 isn't entirely clear on which it
// recommends?????
// No need to check kids for right-document; if they weren't,
// they wouldn't be kids of that DocFrag.
if (errorChecking) {
for (NodeImpl *kid = newChild->getFirstChild(); // Prescan
kid != null; kid = kid->getNextSibling()) {
if (!DocumentImpl::isKidOK(this, kid)) {
throw DOM_DOMException(
DOM_DOMException::HIERARCHY_REQUEST_ERR,
null);
}
}
}
while (newChild->hasChildNodes()) { // Move
insertBefore(newChild->getFirstChild(), refChild);
}
return newChild;
}
// it's a no-op if refChild is the same as newChild
if (refChild == newChild) {
return newChild;
}
if (errorChecking) {
if (isReadOnly()) {
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
null);
}
if (newChild->getOwnerDocument() != ownerDocument) {
throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
}
if (!DocumentImpl::isKidOK(this, newChild)) {
throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,
null);
}
// refChild must be a child of this node (or null)
if (refChild != null && refChild->getParentNode() != this) {
throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
}
// Prevent cycles in the tree
// newChild cannot be ancestor of this Node,
// and actually cannot be this
bool treeSafe = true;
for (NodeImpl *a = this; treeSafe && a != null; a = a->getParentNode())
{
treeSafe = (newChild != a);
}
if (!treeSafe) {
throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,
null);
}
}
makeChildNode(); // make sure we have a node and not a string
// Convert to internal type, to avoid repeated casting
ChildNode * newInternal = (ChildNode *)newChild;
NodeImpl *oldparent = newInternal->getParentNode();
if (oldparent != null) {
oldparent->removeChild(newInternal);
}
// Convert to internal type, to avoid repeated casting
ChildNode *refInternal = (ChildNode *)refChild;
// Attach up
newInternal->ownerNode = this;
newInternal->isOwned(true);
// Attach before and after
// Note: firstChild.previousSibling == lastChild!!
ChildNode *firstChild = value.child;
if (firstChild == null) {
// this our first and only child
value.child = newInternal; // firstChild = newInternal
newInternal->isFirstChild(true);
newInternal->previousSibling = newInternal;
}
else {
if (refInternal == null) {
// this is an append
ChildNode *lastChild = firstChild->previousSibling;
lastChild->nextSibling = newInternal;
newInternal->previousSibling = lastChild;
firstChild->previousSibling = newInternal;
}
else {
// this is an insert
if (refChild == firstChild) {
// at the head of the list
firstChild->isFirstChild(false);
newInternal->nextSibling = firstChild;
newInternal->previousSibling = firstChild->previousSibling;
firstChild->previousSibling = newInternal;
value.child = newInternal; // firstChild = newInternal;
newInternal->isFirstChild(true);
}
else {
// somewhere in the middle
ChildNode *prev = refInternal->previousSibling;
newInternal->nextSibling = refInternal;
prev->nextSibling = newInternal;
refInternal->previousSibling = newInternal;
newInternal->previousSibling = prev;
}
}
}
changed();
if (this->getOwnerDocument() != null) {
typedef RefVectorOf<RangeImpl> RangeImpls;
RangeImpls* ranges = this->getOwnerDocument()->getRanges();
if ( ranges != null) {
unsigned int sz = ranges->size();
for (unsigned int i =0; i<sz; i++) {
ranges->elementAt(i)->updateRangeForInsertedNode(newInternal);
}
}
}
return newInternal;
}
NodeImpl *AttrImpl::item(unsigned int index) {
if (hasStringValue()) {
if (index != 0 || value.child == null) {
return null;
}
else {
makeChildNode();
return (NodeImpl *) (value.child);
}
}
ChildNode *nodeListNode = value.child;
for (unsigned int nodeListIndex = 0;
nodeListIndex < index && nodeListNode != null;
nodeListIndex++) {
nodeListNode = nodeListNode->nextSibling;
}
return nodeListNode;
}
NodeImpl *AttrImpl::removeChild(NodeImpl *oldChild) {
DocumentImpl *ownerDocument = getOwnerDocument();
if (ownerDocument->getErrorChecking()) {
if (isReadOnly()) {
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
null);
}
if (oldChild == null || oldChild->getParentNode() != this) {
throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
}
}
// fix other ranges for change before deleting the node
if (getOwnerDocument() != null) {
typedef RefVectorOf<RangeImpl> RangeImpls;
RangeImpls* ranges = this->getOwnerDocument()->getRanges();
if (ranges != null) {
unsigned int sz = ranges->size();
if (sz != 0) {
for (unsigned int i =0; i<sz; i++) {
if (ranges->elementAt(i) != null)
ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);
}
}
}
}
ChildNode * oldInternal = (ChildNode *) oldChild;
// Patch linked list around oldChild
// Note: lastChild == firstChild->previousSibling
if (oldInternal == value.child) {
// removing first child
oldInternal->isFirstChild(false);
value.child = oldInternal->nextSibling; // firstChild = oldInternal->nextSibling
ChildNode *firstChild = value.child;
if (firstChild != null) {
firstChild->isFirstChild(true);
firstChild->previousSibling = oldInternal->previousSibling;
}
} else {
ChildNode *prev = oldInternal->previousSibling;
ChildNode *next = oldInternal->nextSibling;
prev->nextSibling = next;
if (next == null) {
// removing last child
ChildNode *firstChild = value.child;
firstChild->previousSibling = prev;
} else {
// removing some other child in the middle
next->previousSibling = prev;
}
}
// Remove oldInternal's references to tree
oldInternal->ownerNode = getOwnerDocument();
oldInternal->isOwned(false);
oldInternal->nextSibling = null;
oldInternal->previousSibling = null;
changed();
return oldInternal;
};
NodeImpl *AttrImpl::replaceChild(NodeImpl *newChild, NodeImpl *oldChild) {
insertBefore(newChild, oldChild);
if (newChild != oldChild) {
removeChild(oldChild);
}
// changed() already done.
return oldChild;
}
void AttrImpl::setReadOnly(bool readOnl, bool deep) {
NodeImpl::setReadOnly(readOnl, deep);
if (deep) {
if (hasStringValue()) {
return;
}
// Recursively set kids
for (ChildNode *mykid = value.child;
mykid != null;
mykid = mykid->nextSibling)
if(! (mykid->isEntityReference()))
mykid->setReadOnly(readOnl,true);
}
}
//Introduced in DOM Level 2
void AttrImpl::normalize()
{
if (hasStringValue()) {
return;
}
ChildNode *kid, *next;
for (kid = value.child; kid != null; kid = next)
{
next = kid->nextSibling;
// If kid and next are both Text nodes (but _not_ CDATASection,
// which is a subclass of Text), they can be merged.
if (next != null &&
kid->isTextImpl() && !(kid->isCDATASectionImpl()) &&
next->isTextImpl() && !(next->isCDATASectionImpl()) )
{
((TextImpl *) kid)->appendData(((TextImpl *) next)->getData());
removeChild(next);
if (next->nodeRefCount == 0)
deleteIf(next);
next = kid; // Don't advance; there might be another.
}
// Otherwise it might be an Element, which is handled recursively
else
if (kid->isElementImpl())
kid->normalize();
};
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
};
XERCES_CPP_NAMESPACE_END
| 29.588745 | 88 | 0.59566 | allianz-pmichel |
1162b0b99d357373a0a203e44e98a5d92306ef6d | 2,356 | cpp | C++ | EU4toV2/Source/EU4World/Leader/EU4Leader.cpp | GregB76/EU4toVic2 | 0a8822101a36a16036fdc315e706d113d9231101 | [
"MIT"
] | 1 | 2020-04-22T03:09:51.000Z | 2020-04-22T03:09:51.000Z | EU4toV2/Source/EU4World/Leader/EU4Leader.cpp | fessi1202/EU4toVic2 | 1f4cce609e495f8b4e00580a12ab4a29b304902f | [
"MIT"
] | null | null | null | EU4toV2/Source/EU4World/Leader/EU4Leader.cpp | fessi1202/EU4toVic2 | 1f4cce609e495f8b4e00580a12ab4a29b304902f | [
"MIT"
] | null | null | null | #include "EU4Leader.h"
#include "../ID.h"
#include "Log.h"
#include "ParserHelpers.h"
EU4::Leader::Leader(std::istream& theStream)
{
registerKeyword("name", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleString nameString(theStream);
name = nameString.getString();
});
registerKeyword("type", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleString typeString(theStream);
leaderType = typeString.getString();
});
registerKeyword("female", [this](const std::string& unused, std::istream& theStream)
{
commonItems::ignoreItem(unused, theStream);
female = true;
});
registerKeyword("manuever", [this](const std::string& unused, std::istream& theStream)
{ // don't fix PDX typo!
const commonItems::singleInt theValue(theStream);
maneuver = theValue.getInt();
});
registerKeyword("fire", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleInt theValue(theStream);
fire = theValue.getInt();
});
registerKeyword("shock", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleInt theValue(theStream);
shock = theValue.getInt();
});
registerKeyword("siege", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleInt theValue(theStream);
siege = theValue.getInt();
});
registerKeyword("country", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleString countryString(theStream);
country = countryString.getString();
});
registerKeyword("activation", [this](const std::string& unused, std::istream& theStream)
{
const commonItems::singleString dateString(theStream);
activationDate = date(dateString.getString());
});
registerKeyword("id", [this](const std::string& idType, std::istream& theStream)
{
const ID theID(theStream);
leaderID = theID.getIDNum();
});
registerRegex("[a-zA-Z0-9_\\.:]+", commonItems::ignoreItem);
parseStream(theStream);
clearRegisteredKeywords();
}
bool EU4::Leader::isLand() const
{
if (leaderType == "general" || leaderType == "conquistador") return true;
if (leaderType == "explorer" || leaderType == "admiral") return false;
LOG(LogLevel::Warning) << "Unknown leader type " << leaderType;
return false;
}
| 32.722222 | 89 | 0.699491 | GregB76 |
1162e73158b027001d8203ff72fcde43dca72208 | 2,885 | cpp | C++ | libcaf_core/src/tracing_data.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/src/tracing_data.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/src/tracing_data.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/tracing_data.hpp"
#include <cstdint>
#include "caf/actor_system.hpp"
#include "caf/deserializer.hpp"
#include "caf/error.hpp"
#include "caf/logger.hpp"
#include "caf/sec.hpp"
#include "caf/serializer.hpp"
#include "caf/tracing_data_factory.hpp"
namespace caf {
tracing_data::~tracing_data() {
// nop
}
namespace {
template <class Serializer>
auto inspect_impl(Serializer& sink, const tracing_data_ptr& x) {
if (x == nullptr) {
uint8_t dummy = 0;
return sink(dummy);
}
uint8_t dummy = 1;
if (auto err = sink(dummy))
return err;
return x->serialize(sink);
}
template <class Deserializer>
typename Deserializer::result_type
inspect_impl(Deserializer& source, tracing_data_ptr& x) {
uint8_t dummy = 0;
if (auto err = source(dummy))
return err;
if (dummy == 0) {
x.reset();
return {};
}
auto ctx = source.context();
if (ctx == nullptr)
return sec::no_context;
auto tc = ctx->system().tracing_context();
if (tc == nullptr)
return sec::no_tracing_context;
return tc->deserialize(source, x);
}
} // namespace
error inspect(serializer& sink, const tracing_data_ptr& x) {
return inspect_impl(sink, x);
}
error_code<sec> inspect(binary_serializer& sink, const tracing_data_ptr& x) {
return inspect_impl(sink, x);
}
error inspect(deserializer& source, tracing_data_ptr& x) {
return inspect_impl(source, x);
}
error_code<sec> inspect(binary_deserializer& source, tracing_data_ptr& x) {
return inspect_impl(source, x);
}
} // namespace caf
| 32.41573 | 80 | 0.49636 | dosuperuser |
116526500659c13d6366b6db5a045c780a51a3a6 | 3,896 | hpp | C++ | samples/sampleslib/window.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | 1 | 2018-03-01T01:05:25.000Z | 2018-03-01T01:05:25.000Z | samples/sampleslib/window.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | samples/sampleslib/window.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | #ifndef SAMPLES_LIB_WINDOW_H
#define SAMPLES_LIB_WINDOW_H
#include <framework/framework.hpp>
namespace sampleslib
{
template<vg::SpaceType type>
struct SpaceObjectInfo
{
using SceneType = void;
using CameraType = void;
};
template<>
struct SpaceObjectInfo<vg::SpaceType::SPACE_2>
{
using SceneType = vg::Scene2;
using CameraType = vg::CameraOP2;
};
template<>
struct SpaceObjectInfo<vg::SpaceType::SPACE_3>
{
using SceneType = vg::Scene3;
using CameraType = vg::Camera3;
};
template <vg::SpaceType SPACE_TYPE>
class Window : public vgf::Window
{
public:
using PointType = typename vg::SpaceTypeInfo<SPACE_TYPE>::PointType;
using RotationType = typename vg::SpaceTypeInfo<SPACE_TYPE>::RotationType;
using RotationDimType = typename vg::SpaceTypeInfo<SPACE_TYPE>::RotationDimType;
using SceneType = typename SpaceObjectInfo<SPACE_TYPE>::SceneType;
using CameraType = typename SpaceObjectInfo<SPACE_TYPE>::CameraType;
using TimePointType = typename std::chrono::time_point<std::chrono::steady_clock>;
Window(uint32_t width
, uint32_t height
, const char* title
);
Window(std::shared_ptr<GLFWwindow> pWindow
, std::shared_ptr<vk::SurfaceKHR> pSurface
);
protected:
float m_rotationSpeed;
TimePointType m_startTimeFrame;
TimePointType m_endTimeFrame;
bool m_isPause;
/**
* Costing time of per frame (s)
*/
float m_frameTimer;
/**
* Passed time since starting application (s)
**/
float m_passedTime;
/**
* The speed of time advaced [0, 1]
**/
float m_timerSpeedFactor;
uint32_t m_fpsTimer;
uint32_t m_frameCounter;
uint32_t m_lastFPS;
uint32_t m_lastDrawCount;
vg::Vector2 m_lastWinPos;
vg::Vector2 m_lastWinSize;
float m_cameraZoom;
float m_cameraZoomSpeed;
float m_cameraAspect;
PointType m_cameraPosition;
RotationDimType m_cameraRotation;
RotationDimType m_worldRotation;
struct {
vgf::Bool32 left = VGF_FALSE;
vgf::Bool32 right = VGF_FALSE;
vgf::Bool32 middle = VGF_FALSE;
} m_mouseButtons;
double m_mousePos[2];
uint32_t m_sceneCount;
std::vector<std::shared_ptr<SceneType>> m_pScenes;
std::shared_ptr<SceneType> m_pScene;
std::shared_ptr<CameraType> m_pCamera;
vg::Bool32 m_preDepthScene;
virtual void _onResize() override;
virtual void _onPreReCreateSwapchain() override;
virtual void _onPostReCreateSwapchain() override;
virtual void _onPreUpdate() override;
virtual void _onUpdate() override;
virtual void _onPostUpdate() override;
virtual void _onPreDraw() override;
virtual void _onDraw() override;
virtual void _onPostDraw() override;
static std::vector<vg::Renderer::SceneInfo> mySceneInfos;
virtual void _onPreRender(vg::Renderer::RenderInfo &info
, vg::Renderer::RenderResultInfo &resultInfo) override;
virtual void _onRender(vg::Renderer::RenderInfo &info
, vg::Renderer::RenderResultInfo &resultInfo) override;
virtual void _onPostRender(vg::Renderer::RenderInfo &info
, vg::Renderer::RenderResultInfo &resultInfo) override;
virtual void _init();
virtual void _initState();
private:
void _createCamera();
void _createScene();
void _initUI();
void _initInputHanders();
void _updateCamera();
};
}
#include "sampleslib/window.inl"
#endif // !SAMPLES_LIB_WINDOW_H
| 29.074627 | 90 | 0.62808 | YiJiangFengYun |
11670232f86b94910304e9683dd1f2d7ebafda9d | 229,759 | cpp | C++ | GBAemu/cpu/arm.cpp | robojan/EmuAll | 0a589136df9fefbfa142e605e1d3a0c94f726bad | [
"Apache-2.0"
] | 1 | 2021-03-04T03:52:39.000Z | 2021-03-04T03:52:39.000Z | GBAemu/cpu/arm.cpp | robojan/EmuAll | 0a589136df9fefbfa142e605e1d3a0c94f726bad | [
"Apache-2.0"
] | null | null | null | GBAemu/cpu/arm.cpp | robojan/EmuAll | 0a589136df9fefbfa142e605e1d3a0c94f726bad | [
"Apache-2.0"
] | null | null | null |
#include <GBAemu/cpu/hostInstructions.h>
#include <GBAemu/cpu/cpu.h>
#include <GBAemu/cpu/armException.h>
#include <GBAemu/gba.h>
#include <GBAemu/util/log.h>
#include <GBAemu/defines.h>
#include <GBAemu/util/preprocessor.h>
// 001xxxxxxxxx
uint32_t Cpu::GetShifterOperandImm(uint32_t instruction)
{
uint32_t operand = instruction & 0xFF;
uint8_t rotateImm = (instruction >> 8) & 0xF;
if (rotateImm == 0) {
return operand;
}
else {
ROR(operand, rotateImm * 2, operand);
}
return operand;
}
uint32_t Cpu::GetShifterOperandLSL(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSL(_registers[rm], shift, operand);
return operand;
}
}
uint32_t Cpu::GetShifterOperandLSLReg(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint32_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSL(_registers[rm], shift, operand);
return operand;
}
}
uint32_t Cpu::GetShifterOperandLSR(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
shift = 32;
}
uint32_t operand;
LSR(_registers[rm], shift, operand);
return operand;
}
uint32_t Cpu::GetShifterOperandLSRReg(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSR(_registers[rm], shift, operand);
return operand;
}
}
uint32_t Cpu::GetShifterOperandASR(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
shift = 32;
}
uint32_t operand;
ASR(_registers[rm], shift, operand);
return operand;
}
uint32_t Cpu::GetShifterOperandASRReg(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
ASR(_registers[rm], shift, operand);
return operand;
}
}
uint32_t Cpu::GetShifterOperandROR(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
uint32_t operand;
if (shift == 0) {
RRX(_registers[rm], 1, operand, _hostFlags);
}
else {
ROR(_registers[rm], shift, operand);
}
return operand;
}
uint32_t Cpu::GetShifterOperandRORReg(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
ROR(_registers[rm], shift, operand);
return operand;
}
}
// 001xxxxxxxxx
uint32_t Cpu::GetShifterOperandImmFlags(uint32_t instruction)
{
uint32_t operand = instruction & 0xFF;
uint8_t rotateImm = (instruction >> 8) & 0xF;
if (rotateImm == 0) {
return operand;
}
else {
ROR_CFLAG(operand, rotateImm * 2, operand, _hostFlags);
}
return operand;
}
uint32_t Cpu::GetShifterOperandLSLFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSL_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
}
uint32_t Cpu::GetShifterOperandLSLRegFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint32_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSL_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
}
uint32_t Cpu::GetShifterOperandLSRFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
shift = 32;
}
uint32_t operand;
LSR_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
uint32_t Cpu::GetShifterOperandLSRRegFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
LSR_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
}
uint32_t Cpu::GetShifterOperandASRFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
if (shift == 0) {
shift = 32;
}
uint32_t operand;
ASR_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
uint32_t Cpu::GetShifterOperandASRRegFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
ASR_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
}
uint32_t Cpu::GetShifterOperandRORFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t shift = (instruction >> 7) & 0x1F;
uint32_t operand;
if (shift == 0) {
RRX_CFLAG(_registers[rm], 1, operand, _hostFlags);
}
else {
ROR_CFLAG(_registers[rm], shift, operand, _hostFlags);
}
return operand;
}
uint32_t Cpu::GetShifterOperandRORRegFlags(uint32_t instruction)
{
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t shift = _registers[rs];
if (shift == 0) {
return _registers[rm];
}
else {
uint32_t operand;
ROR_CFLAG(_registers[rm], shift, operand, _hostFlags);
return operand;
}
}
void Cpu::TickARM(bool step) {
uint32_t instruction = _pipelineInstruction;
_pipelineInstruction = _system._memory.Read32(_registers[REGPC] & 0xFFFFFFFC);
if (step && IsBreakpoint(_registers[REGPC] - 4)) {
instruction = _breakpoints.at(_registers[REGPC] - 4);
}
_registers[REGPC] += 4;
uint8_t cond = instruction >> 28;
if (!IsConditionMet(cond, _hostFlags)) {
return;
}
uint16_t code = ((instruction >> 4) & 0xF) | (((instruction >> 20) & 0xFF) << 4);
switch (code) {
// ADC
case 0x0A8:
case 0x0A0: {// ADC <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0A1: { // ADC <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0AA:
case 0x0A2: { // ADC <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0A3: { // ADC <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0AC:
case 0x0A4: { // ADC <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0A5: { // ADC <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0AE:
case 0x0A6: { // ADC <Rd>, <Rn>, <Rm>, ROR #<imm>
// ADC <Rd>, <Rn>, <Rm>, RRX
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0A7: { // ADC <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0B8:
case 0x0B0: {// ADCS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLFlags(instruction);
if (rd == REGPC) {
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0B1: { // ADCS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0BA:
case 0x0B2: { // ADCS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0B3: { // ADCS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0BC:
case 0x0B4: { // ADCS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0B5: { // ADCS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0BE:
case 0x0B6: { // ADCS <Rd>, <Rn>, <Rm>, ROR #<imm>
// ADCS <Rd>, <Rn>, <Rm>, RRX
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0B7: { // ADCS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x2A0) { // ADC <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x2B0) { // ADC <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
ADC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// ADD
case 0x080:
case 0x088: { // ADD <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x081: { // ADD <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x082:
case 0x08A: { // ADD <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x083: { // ADD <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x084:
case 0x08C: { // ADD <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x085: { // ADD <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x086: // ADD <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x08E: { // ADD <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x087: { // ADD <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x090:
case 0x098: { // ADDS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x091: { // ADDS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x092:
case 0x09A: { // ADDS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x093: { // ADDS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x094:
case 0x09C: { // ADDS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x095: { // ADDS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x096: // ADDS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x09E: { // ADDS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x097: { // ADDS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x280) { // ADD <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
ADD(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x290) { // ADDS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
ADD(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// AND
case 0x000:
case 0x008: { // AND <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x001: { // AND <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x002:
case 0x00A: { // AND <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x003: { // AND <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x004:
case 0x00C: { // AND <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x005: { // AND <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x006: // AND <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x00E: { // AND <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x007: { // AND <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x010:
case 0x018: { // ANDS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
}
break;
}
case 0x011: { // ANDS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x012:
case 0x01A: { // ANDS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x013: { // ANDS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x014:
case 0x01C: { // ANDS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x015: { // ANDS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x016: // ANDS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x01E: { // ANDS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x017: { // ANDS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x200) { // AND <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
AND(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x210) { // ANDS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
AND(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// B
CASE_RANGE256(0xA00) { // B <target_address>
uint32_t address = instruction & 0xFFFFFF;
if ((address & 0x00800000) != 0) address |= 0xFF000000;
address <<= 2;
_registers[REGPC] += address;
_pipelineInstruction = ARM_NOP;
break;
}
// BL
CASE_RANGE256(0xB00) { // BL <target_address>
uint32_t address = instruction & 0xFFFFFF;
if ((address & 0x00800000) != 0) address |= 0xFF000000;
address <<= 2;
_registers[REGLR] = _registers[REGPC] - 4;
_registers[REGPC] += address;
_pipelineInstruction = ARM_NOP;
break;
}
// BIC
case 0x1C0:
case 0x1C8: { // BIC <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C1: { // BIC <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C2:
case 0x1CA: { // BIC <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C3: { // BIC <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C4:
case 0x1CC: { // BIC <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C5: { // BIC <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C6: // BIC <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x1CE: { // BIC <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1C7: { // BIC <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1D0:
case 0x1D8: { // BICS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D1: { // BICS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D2:
case 0x1DA: { // BICS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D3: { // BICS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D4:
case 0x1DC: { // BICS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D5: { // BICS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D6: // BICS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x1DE: { // BICS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1D7: { // BICS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x3C0) { // BIC <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
BIC(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x3D0) { // BICS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
BIC(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// BKPT
case 0x127: { // BKPT <imm_16>
uint16_t imm = instruction & 0xF;
imm |= (instruction >> 4) & 0xFFF0;
throw BreakPointARMException(imm);
break;
}
// BX
case 0x121: { // BX <Rm>
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rm];
SetThumbMode((address & 0x1) != 0);
_registers[REGPC] = address & 0xFFFFFFFE;
_pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE128_OFFSET(0xE00, 1) { // CDP <coproc>, <opcode_1>, <CRd>, <CRn>, <CRm>, <opcode_2>
Log(Warn, "Coprocessor instruction found. Not supported.");
__debugbreak();
break;
}
// CMN
case 0x170:
case 0x178: { // CMN <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x171: { // CMN <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x172:
case 0x17A: { // CMN <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x173: { // CMN <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x174:
case 0x17C: { // CMN <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x175: { // CMN <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x176: // CMN <Rn>, <Rm>, RRX #<imm>
case 0x17E: { // CMN <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
case 0x177: { // CMN <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
CASE_RANGE16(0x370) { // CMN <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandImmFlags(instruction);
CMN(_registers[rn], operand, _hostFlags);
break;
}
// CMP
case 0x150:
case 0x158: { // CMP <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x151: { // CMP <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x152:
case 0x15A: { // CMP <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x153: { // CMP <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x154:
case 0x15C: { // CMP <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x155: { // CMP <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x156: // CMP <Rn>, <Rm>, RRX #<imm>
case 0x15E: { // CMP <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
case 0x157: { // CMP <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
CASE_RANGE16(0x350) { // CMP <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandImmFlags(instruction);
CMP(_registers[rn], operand, _hostFlags);
break;
}
// EOR
case 0x020:
case 0x028: { // EOR <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x021: { // EOR <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x022:
case 0x02A: { // EOR <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x023: { // EOR <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x024:
case 0x02C: { // EOR <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x025: { // EOR <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x026: // EOR <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x02E: { // EOR <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x027: { // EOR <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x030:
case 0x038: { // EORS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x031: { // EORS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x032:
case 0x03A: { // EORS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x033: { // EORS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x034:
case 0x03C: { // EORS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x035: { // EORS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x036: // EORS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x03E: { // EORS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x037: { // EORS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x220) { // EOR <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
EOR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x230) { // EORS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
EOR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// LDM
CASE_RANGE16(0x810) { // LDMDA <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if ((registerList & (1 << 15)) != 0) {
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
break;
}
CASE_RANGE16(0x830) { // LDMDA <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if ((registerList & (1 << 15)) != 0) {
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x890) { // LDMIA <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address += 4;
}
break;
}
CASE_RANGE16(0x8B0) { // LDMIA <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address += 4;
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x910) { // LDMDB <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if ((registerList & (1 << 15)) != 0) {
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
break;
}
CASE_RANGE16(0x930) { // LDMDB <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if ((registerList & (1 << 15)) != 0) {
address -= 4;
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_registers[i] = _system._memory.Read32(address);
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x990) { // LDMIB <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i >= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x9B0) { // LDMIB <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
_registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x850) { // LDMDA <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
address -= 4;
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
}
for (int i = 14; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_registersUser[i - 8] = _system._memory.Read32(address);
}
}
for (int i = 7; i >= 0; i--) {
address -= 4;
_registers[i] = _system._memory.Read32(address);
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_registers[i] = _system._memory.Read32(address);
if (i == REGPC) _pipelineInstruction = ARM_NOP;
}
}
}
break;
}
CASE_RANGE16(0x870) { // LDMDA <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
address -= 4;
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
}
for (int i = 14; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_registersUser[i - 8] = _system._memory.Read32(address);
}
}
for (int i = 7; i >= 0; i--) {
address -= 4;
_registers[i] = _system._memory.Read32(address);
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_registers[i] = _system._memory.Read32(address);
if (i == REGPC) _pipelineInstruction = ARM_NOP;
}
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x8D0) { // LDMIA <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
for (int i = 8; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registersUser[i - 8] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
}
}
else {
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x8F0) { // LDMIA <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
for (int i = 8; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registersUser[i - 8] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
}
}
else {
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_registers[i] = _system._memory.Read32(address);
}
}
if ((registerList & (1 << 15)) != 0) {
address += 4;
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
}
}
break;
}
CASE_RANGE16(0x950) { // LDMDB <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_registersUser[i - 8] = _system._memory.Read32(address);
address -= 4;
}
}
for (int i = 7; i >= 0; i--) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
else {
if ((registerList & (1 << 15)) != 0) {
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
}
break;
}
CASE_RANGE16(0x970) { // LDMDB <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_registersUser[i - 8] = _system._memory.Read32(address);
address -= 4;
}
}
for (int i = 7; i >= 0; i--) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
else {
if ((registerList & (1 << 15)) != 0) {
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address -= 4;
}
for (int i = 14; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address -= 4;
}
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x9D0) { // LDMIB <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
for (int i = 8; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registersUser[i - 8] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
address += 4;
}
}
else {
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address += 4;
}
}
break;
}
CASE_RANGE16(0x9F0) { // LDMIB <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
for (int i = 8; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registersUser[i - 8] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
_cpsr = _spsr;
uint32_t pc = _system._memory.Read32(address);
UpdateMode();
if (IsInThumbMode()) {
_registers[15] = pc & 0xFFFFFFFE;
}
else {
_registers[15] = pc & 0xFFFFFFFC;
}
_pipelineInstruction = ARM_NOP;
address += 4;
}
}
else {
for (int i = 0; i <= 14; i++) {
if ((registerList & (1 << i)) != 0) {
_registers[i] = _system._memory.Read32(address);
address += 4;
}
}
if ((registerList & (1 << 15)) != 0) {
uint32_t pc = _system._memory.Read32(address);
_registers[15] = pc & 0xFFFFFFFC;
_pipelineInstruction = ARM_NOP;
address += 4;
}
}
_registers[rn] = address;
break;
}
// LDR
CASE_RANGE16(0x410) { // LDR <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x490) { // LDR <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x510) { // LDR <Rd>, [<Rn>, #-<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x530) { // LDR <Rd>, [<Rn>, #-<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x590) { // LDR <Rd>, [<Rn>, #+<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x5B0) { // LDR <Rd>, [<Rn>, #+<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x610:
case 0x618:{ // LDR <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x612:
case 0x61A: { // LDR <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x614:
case 0x61C: { // LDR <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x616:
case 0x61E: { // LDR <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x690:
case 0x698: { // LDR <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x692:
case 0x69A: { // LDR <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x694:
case 0x69C: { // LDR <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x696:
case 0x69E: { // LDR <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x710:
case 0x718: { // LDR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x712:
case 0x71A: { // LDR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x714:
case 0x71C: { // LDR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x716:
case 0x71E: { // LDR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x790:
case 0x798: { // LDR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x792:
case 0x79A: { // LDR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x794:
case 0x79C: { // LDR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x796:
case 0x79E: { // LDR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x730:
case 0x738: { // LDR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x732:
case 0x73A: { // LDR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x734:
case 0x73C: { // LDR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x736:
case 0x73E: { // LDR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7B0:
case 0x7B8: { // LDR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7B2:
case 0x7BA: { // LDR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7B4:
case 0x7BC: { // LDR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7B6:
case 0x7BE: { // LDR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read32(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// LDRB
CASE_RANGE16(0x450) { // LDRB <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x4D0) { // LDRB <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x550) { // LDRB <Rd>, [<Rn>, #-<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x570) { // LDRB <Rd>, [<Rn>, #-<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x5D0) { // LDRB <Rd>, [<Rn>, #+<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x5F0) { // LDRB <Rd>, [<Rn>, #+<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x650:
case 0x658: { // LDRB <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x652:
case 0x65A: { // LDRB <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x654:
case 0x65C: { // LDRB <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x656:
case 0x65E: { // LDRB <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x6D0:
case 0x6D8: { // LDRB <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x6D2:
case 0x6DA: { // LDRB <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x6D4:
case 0x6DC: { // LDRB <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x6D6:
case 0x6DE: { // LDRB <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x750:
case 0x758: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x752:
case 0x75A: { // LDRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x754:
case 0x75C: { // LDRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x756:
case 0x75E: { // LDRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7D0:
case 0x7D8: { // LDRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7D2:
case 0x7DA: { // LDRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7D4:
case 0x7DC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7D6:
case 0x7DE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x770:
case 0x778: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x772:
case 0x77A: { // LDRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x774:
case 0x77C: { // LDRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x776:
case 0x77E: { // LDRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7F0:
case 0x7F8: { // LDRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7F2:
case 0x7FA: { // LDRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7F4:
case 0x7FC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x7F6:
case 0x7FE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read8(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
//LDRBT
CASE_RANGE16(0x470) { // LDRBT <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x4F0) { // LDRBT <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd-8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x670:
case 0x678: { // LDRBT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x672:
case 0x67A: { // LDRBT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x674:
case 0x67C: { // LDRBT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x676:
case 0x67E: { // LDRBT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x6F0:
case 0x6F8: { // LDRBT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6F2:
case 0x6FA: { // LDRBT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6F4:
case 0x6FC: { // LDRBT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6F6:
case 0x6FE: { // LDRBT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read8(address);
}
}
else {
_registers[rd] = _system._memory.Read8(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
// LDRH
case 0x01B: { // LDRH <Rd>, [<Rn>], -<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address - _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x09B: { // LDRH <Rd>, [<Rn>], +<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address + _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x05B: { // LDRH <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0DB: { // LDRH <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x11B: { // LDRH <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
_registers[rd] = _system._memory.Read16(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x19B: { // LDRH <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
_registers[rd] = _system._memory.Read16(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x15B: { // LDRH <Rd>, [<Rn>, #-<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read16(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1DB: { // LDRH <Rd>, [<Rn>, #+<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read16(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x13B: { // LDRH <Rd>, [<Rn>, -<Rm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1BB: { // LDRH <Rd>, [<Rn>, +<Rm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x17B: { // LDRH <Rd>, [<Rn>, #-<offset_8>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1FB: { // LDRH <Rd>, [<Rn>, #+<offset_8>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
_registers[rd] = _system._memory.Read16(address);
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// LDRSB
case 0x01D: { // LDRSB <Rd>, [<Rn>], -<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address - _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x09D: { // LDRSB <Rd>, [<Rn>], +<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address + _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x05D: { // LDRSB <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0DD: { // LDRSB <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x11D: { // LDRSB <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x19D: { // LDRSB <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x15D: { // LDRSB <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1DD: { // LDRSB <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x13D: { // LDRSB <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1BD: { // LDRSB <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x17D: { // LDRSB <Rd>, [<Rn>, #-<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1FD: { // LDRSB <Rd>, [<Rn>, #+<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
uint32_t value = _system._memory.Read8(address);
if ((value & 0x80) != 0) value |= 0xFFFFFF00;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// LDRSH
case 0x01F: { // LDRSH <Rd>, [<Rn>], -<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address - _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x09F: { // LDRSH <Rd>, [<Rn>], +<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address + _registers[rm];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x05F: { // LDRSH <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address - offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0DF: { // LDRSH <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address + offset;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x11F: { // LDRSH <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x19F: { // LDRSH <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x15F: { // LDRSH <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1DF: { // LDRSH <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x13F: { // LDRSH <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1BF: { // LDRSH <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x17F: { // LDRSH <Rd>, [<Rn>, #-<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1FF: { // LDRSH <Rd>, [<Rn>, #+<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
uint32_t value = _system._memory.Read16(address);
if ((value & 0x8000) != 0) value |= 0xFFFF0000;
_registers[rd] = value;
_registers[rn] = address;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// LDRT
CASE_RANGE16(0x430) { // LDRT <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x4B0) { // LDRT <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x630:
case 0x638: { // LDRT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x632:
case 0x63A: { // LDRT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x634:
case 0x63C: { // LDRT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x636:
case 0x63E: { // LDRT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address - offset;
break;
}
case 0x6B0:
case 0x6B8: { // LDRT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6B2:
case 0x6BA: { // LDRT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6B4:
case 0x6BC: { // LDRT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
case 0x6B6:
case 0x6BE: { // LDRT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
else {
_registersUser[rd - 8] = _system._memory.Read32(address);
}
}
else {
_registers[rd] = _system._memory.Read32(address);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
_registers[rn] = address + offset;
break;
}
// MLA
case 0x029: { // MLA <Rd>, <Rm>, <Rs>, <Rn>
uint8_t rd = (instruction >> 16) & 0xF;
uint8_t rn = (instruction >> 12) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 0) & 0xF;
MLA(_registers[rm], _registers[rs], _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x039: { // MLAS <Rd>, <Rm>, <Rs>, <Rn>
uint8_t rd = (instruction >> 16) & 0xF;
uint8_t rn = (instruction >> 12) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 0) & 0xF;
MLA_FLAGS(_registers[rm], _registers[rs], _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// MOV
case 0x1A0:
case 0x1A8: { // MOV <Rd>, <Rm>, LSL #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A1: { // MOV <Rd>, <Rm>, LSL <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A2:
case 0x1AA: { // MOV <Rd>, <Rm>, LSR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A3: { // MOV <Rd>, <Rm>, LSR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A4:
case 0x1AC: { // MOV <Rd>, <Rm>, ASR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A5: { // MOV <Rd>, <Rm>, ASR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A6: // MOV <Rd>, <Rm>, RRX #<imm>
case 0x1AE: { // MOV <Rd>, <Rm>, ROR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1A7: { // MOV <Rd>, <Rm>, ROR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1B0:
case 0x1B8: { // MOVS <Rd>, <Rm>, LSL #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B1: { // MOVS <Rd>, <Rm>, LSL <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B2:
case 0x1BA: { // MOVS <Rd>, <Rm>, LSR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B3: { // MOVS <Rd>, <Rm>, LSR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B4:
case 0x1BC: { // MOVS <Rd>, <Rm>, ASR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B5: { // MOVS <Rd>, <Rm>, ASR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B6: // MOVS <Rd>, <Rm>, RRX #<imm>
case 0x1BE: { // MOVS <Rd>, <Rm>, ROR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1B7: { // MOVS <Rd>, <Rm>, ROR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x3A0) { // MOV <Rd>, #<immediate>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x3B0) { // MOVS <Rd>, #<immediate>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
_registers[rd] = operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
MOV_FLAGS(operand, _hostFlags);
_registers[rd] = operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// MRS
case 0x100: { // MRS <Rd>, CPSR
uint8_t rd = (instruction >> 12) & 0xF;
SaveHostFlagsToCPSR();
_registers[rd] = _cpsr;
break;
}
case 0x140: { // MRS <Rd>, SPSR
uint8_t rd = (instruction >> 12) & 0xF;
_registers[rd] = _spsr;
break;
}
// MSR
CASE_RANGE16(0x320) { // MSR CPSR_<fields>, #<immediate>
uint8_t rotImm = (instruction >> 8) & 0xF;
uint8_t imm = instruction & 0xFF;
uint32_t operand;
ROR(imm, rotImm * 2, operand);
uint32_t mask = 0;
SaveHostFlagsToCPSR();
if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF;
}
if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF00;
}
if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF0000;
}
if ((instruction & (1 << 19)) != 0) {
mask |= 0xFF000000;
}
_cpsr = (_cpsr & ~mask) | (operand & mask);
LoadHostFlagsFromCPSR();
UpdateMode();
break;
}
CASE_RANGE16(0x360) { // MSR SPSR_<fields>, #<immediate>
uint8_t rotImm = (instruction >> 8) & 0xF;
uint8_t imm = instruction & 0xFF;
uint32_t operand;
ROR(imm, rotImm * 2, operand);
uint32_t mask = 0;
if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF;
}
if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF00;
}
if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF0000;
}
if ((instruction & (1 << 19)) != 0) {
mask |= 0xFF000000;
}
_spsr = (_spsr & ~mask) | (operand & mask);
break;
}
case 0x120: { // MSR CPSR_<fields>, <Rm>
uint8_t rm = instruction & 0xF;
uint32_t operand = _registers[rm];
uint32_t mask = 0;
SaveHostFlagsToCPSR();
if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF;
}
if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF00;
}
if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF0000;
}
if ((instruction & (1 << 19)) != 0) {
mask |= 0xFF000000;
}
_cpsr = (_cpsr & ~mask) | (operand & mask);
LoadHostFlagsFromCPSR();
UpdateMode();
break;
}
case 0x160: { // MSR SPSR_<fields>, <Rm>
uint8_t rm = instruction & 0xF;
uint32_t operand = _registers[rm];
uint32_t mask = 0;
if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF;
}
if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF00;
}
if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) {
mask |= 0xFF0000;
}
if ((instruction & (1 << 19)) != 0) {
mask |= 0xFF000000;
_hostFlags &= ~((1 << 0) | (1 << 6) | (1 << 7) | (1 << 11));
if ((operand & CPSR_V_MASK) != 0) _hostFlags |= (1 << 11);
if ((operand & CPSR_C_MASK) != 0) _hostFlags |= (1 << 0);
if ((operand & CPSR_Z_MASK) != 0) _hostFlags |= (1 << 6);
if ((operand & CPSR_N_MASK) != 0) _hostFlags |= (1 << 7);
}
_spsr = (_spsr & ~mask) | (operand & mask);
break;
}
// MUL
case 0x009: { // MUL <Rd>, <Rm>, <Rs>
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rd = (instruction >> 16) & 0xF;
_registers[rd] = _registers[rm] * _registers[rs];
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x019: { // MULS <Rd>, <Rm>, <Rs>
uint8_t rm = instruction & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rd = (instruction >> 16) & 0xF;
MUL_FLAGS(_registers[rm], _registers[rs], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// MVN
case 0x1E0:
case 0x1E8: { // MVN <Rd>, <Rm>, LSL #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E1: { // MVN <Rd>, <Rm>, LSL <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E2:
case 0x1EA: { // MVN <Rd>, <Rm>, LSR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E3: { // MVN <Rd>, <Rm>, LSR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E4:
case 0x1EC: { // MVN <Rd>, <Rm>, ASR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E5: { // MVN <Rd>, <Rm>, ASR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E6: // MVN <Rd>, <Rm>, RRX #<imm>
case 0x1EE: { // MVN <Rd>, <Rm>, ROR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1E7: { // MVN <Rd>, <Rm>, ROR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x1F0:
case 0x1F8: { // MVNS <Rd>, <Rm>, LSL #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F1: { // MVNS <Rd>, <Rm>, LSL <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F2:
case 0x1FA: { // MVNS <Rd>, <Rm>, LSR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F3: { // MVNS <Rd>, <Rm>, LSR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
}
break;
}
case 0x1F4:
case 0x1FC: { // MVNS <Rd>, <Rm>, ASR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F5: { // MVNS <Rd>, <Rm>, ASR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F6: // MVNS <Rd>, <Rm>, RRX #<imm>
case 0x1FE: { // MVNS <Rd>, <Rm>, ROR #<imm>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x1F7: { // MVNS <Rd>, <Rm>, ROR <Rs>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x3E0) { // MVN <Rd>, #<immediate>
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x3F0) { // MVNS <Rd>, #<immediate>
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
_registers[rd] = ~operand;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
MVN_FLAGS(operand, _hostFlags);
_registers[rd] = ~operand;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// ORR
case 0x180:
case 0x188: { // ORR <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x181: { // ORR <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x182:
case 0x18A: { // ORR <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x183: { // ORR <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x184:
case 0x18C: { // ORR <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x185: { // ORR <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x186: // ORR <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x18E: { // ORR <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x187: { // ORR <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x190:
case 0x198: { // ORRS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x191: { // ORRS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x192:
case 0x19A: { // ORRS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x193: { // ORRS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x194:
case 0x19C: { // ORRS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x195: { // ORRS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x196: // ORRS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x19E: { // ORRS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x197: { // ORRS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x380) { // ORR <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
ORR(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x390) { // ORRS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
ORR(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// RSB
case 0x060:
case 0x068: { // RSB <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x061: { // RSB <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x062:
case 0x06A: { // RSB <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x063: { // RSB <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x064:
case 0x06C: { // RSB <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x065: { // RSB <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x066: // RSB <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x06E: { // RSB <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x067: { // RSB <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x070:
case 0x078: { // RSBS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x071: { // RSBS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x072:
case 0x07A: { // RSBS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x073: { // RSBS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x074:
case 0x07C: { // RSBS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x075: { // RSBS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x076: // RSBS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x07E: { // RSBS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x077: { // RSBS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x260) { // RSB <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
SUB(operand, _registers[rn], _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x270) { // RSBS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
SUB(operand, _registers[rn], _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// RSC
case 0x0E0:
case 0x0E8: { // RSC <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E1: { // RSC <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E2:
case 0x0EA: { // RSC <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E3: { // RSC <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E4:
case 0x0EC: { // RSC <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E5: { // RSC <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E6: // RSC <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x0EE: { // RSC <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0E7: { // RSC <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0F0:
case 0x0F8: { // RSCS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);;
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F1: { // RSCS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F2:
case 0x0FA: { // RSCS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F3: { // RSCS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F4:
case 0x0FC: { // RSCS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F5: { // RSCS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F6: // RSCS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x0FE: { // RSCS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0F7: { // RSCS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x2E0) { // RSC <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x2F0) { // RSCS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
SBC(operand, _registers[rn], _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// SBC
case 0x0C0:
case 0x0C8: { // SBC <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C1: { // SBC <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C2:
case 0x0CA: { // SBC <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C3: { // SBC <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C4:
case 0x0CC: { // SBC <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C5: { // SBC <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C6: // SBC <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x0CE: { // SBC <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0C7: { // SBC <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0D0:
case 0x0D8: { // SBCS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D1: { // SBCS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D2:
case 0x0DA: { // SBCS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D3: { // SBCS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D4:
case 0x0DC: { // SBCS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D5: { // SBCS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D6: // SBCS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x0DE: { // SBCS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x0D7: { // SBCS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x2C0) { // SBC <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x2D0) { // SBCS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
SBC(_registers[rn], operand, _registers[rd], _hostFlags);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// SMLAL
case 0x0E9: { // SMLAL <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
SMLAL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0F9: { // SMLALS <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
SMLAL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// SMULL
case 0x0C9: { // SMULL <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
SMULL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0D9: { // SMULLS <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
SMULL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// STM
CASE_RANGE16(0x800) { // STMDA <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
break;
}
CASE_RANGE16(0x820) { // STMDA <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x880) { // STMIA <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
break;
}
CASE_RANGE16(0x8A0) { // STMIA <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x900) { // STMDB <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
break;
}
CASE_RANGE16(0x920) { // STMDB <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x980) { // STMIB <Rn>, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i >= 15; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
break;
}
CASE_RANGE16(0x9A0) { // STMIB <Rn>!, <registers>
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x840) { // STMDA <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
_system._memory.Write32(address, _registers[REGPC]);
address -= 4;
}
_system._memory.Write32(address, _registersUser[14-8]);
address -= 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
address -= 4;
if (InABankedUserRegistersMode()) {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registersUser[i - 8]);
address -= 4;
}
}
}
else {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
}
for (int i = 7; i >= 0; i--) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
}
break;
}
CASE_RANGE16(0x860) { // STMDA <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
_system._memory.Write32(address, _registers[REGPC]);
address -= 4;
}
_system._memory.Write32(address, _registersUser[14 - 8]);
address -= 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
address -= 4;
if (InABankedUserRegistersMode()) {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registersUser[i - 8]);
address -= 4;
}
}
}
else {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
}
for (int i = 7; i >= 0; i--) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address -= 4;
}
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x8C0) { // STMIA <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
if (InABankedUserRegistersMode()) {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registersUser[i - 8]);
address += 4;
}
}
}
else {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
}
_system._memory.Write32(address, _registersUser[13 - 8]);
address += 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
address += 4;
if ((registerList & (1 << 15)) != 0) {
_system._memory.Write32(address, _registers[REGPC]);
address += 4;
}
}
else {
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
}
break;
}
CASE_RANGE16(0x8E0) { // STMIA <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
if (InABankedUserRegistersMode()) {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registersUser[i - 8]);
address += 4;
}
}
}
else {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
}
_system._memory.Write32(address, _registersUser[13 - 8]);
address += 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
address += 4;
if ((registerList & (1 << 15)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[REGPC]);
}
}
else {
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
_system._memory.Write32(address, _registers[i]);
address += 4;
}
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x940) { // STMDB <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[REGPC]);
}
address -= 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
address -= 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
if (InABankedUserRegistersMode()) {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registersUser[i - 8]);
}
}
}
else {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
for (int i = 7; i >= 0; i--) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
break;
}
CASE_RANGE16(0x960) { // STMDB <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if ((registerList & (1 << 15)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[REGPC]);
}
address -= 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
address -= 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
if (InABankedUserRegistersMode()) {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registersUser[i - 8]);
}
}
}
else {
for (int i = 12; i >= 8; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
for (int i = 7; i >= 0; i--) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
else {
for (int i = 15; i >= 0; i--) {
if ((registerList & (1 << i)) != 0) {
address -= 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
_registers[rn] = address;
break;
}
CASE_RANGE16(0x9C0) { // STMIB <Rn>, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
if (InABankedUserRegistersMode()) {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registersUser[i - 8]);
}
}
}
else {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
address += 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
address += 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
if ((registerList & (1 << 15)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[REGPC]);
}
}
else {
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
break;
}
CASE_RANGE16(0x9E0) { // STMIB <Rn>!, <registers>^
uint16_t registerList = instruction & 0xFFFF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
for (int i = 0; i <= 7; i++) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
if (InABankedUserRegistersMode()) {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registersUser[i - 8]);
}
}
}
else {
for (int i = 8; i <= 12; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
address += 4;
_system._memory.Write32(address, _registersUser[13 - 8]);
address += 4;
_system._memory.Write32(address, _registersUser[14 - 8]);
if ((registerList & (1 << 15)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[REGPC]);
}
}
else {
for (int i = 0; i <= 15; i++) {
if ((registerList & (1 << i)) != 0) {
address += 4;
_system._memory.Write32(address, _registers[i]);
}
}
}
_registers[rn] = address;
break;
}
// STR
CASE_RANGE16(0x400) { // STR <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x480) { // STR <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
CASE_RANGE16(0x500) { // STR <Rd>, [<Rn>, #-<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
CASE_RANGE16(0x520) { // STR <Rd>, [<Rn>, #-<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
CASE_RANGE16(0x580) { // STR <Rd>, [<Rn>, #+<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
CASE_RANGE16(0x5A0) { // STR <Rd>, [<Rn>, #+<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x600:
case 0x608: { // STR <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x602:
case 0x60A: { // STR <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x604:
case 0x60C: { // STR <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x606:
case 0x60E: { // STR <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x680:
case 0x688: { // STR <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x682:
case 0x68A: { // STR <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x684:
case 0x68C: { // STR <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x686:
case 0x68E: { // STR <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x700:
case 0x708: { // STR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x702:
case 0x70A: { // STR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x704:
case 0x70C: { // STR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x706:
case 0x70E: { // STR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x780:
case 0x788: { // STR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x782:
case 0x78A: { // STR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x784:
case 0x78C: { // STR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x786:
case 0x78E: { // STR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
break;
}
case 0x720:
case 0x728: { // STR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x722:
case 0x72A: { // STR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x724:
case 0x72C: { // STR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x726:
case 0x72E: { // STR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7A0:
case 0x7A8: { // STR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7A2:
case 0x7AA: { // STR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7A4:
case 0x7AC: { // STR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7A6:
case 0x7AE: { // STR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write32(address, _registers[rd]);
_registers[rn] = address;
break;
}
// STRB
CASE_RANGE16(0x440) { // STRB <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x4C0) { // STRB <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
CASE_RANGE16(0x540) { // STRB <Rd>, [<Rn>, #-<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
CASE_RANGE16(0x560) { // STRB <Rd>, [<Rn>, #-<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
CASE_RANGE16(0x5C0) { // STRB <Rd>, [<Rn>, #+<offset_12>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
CASE_RANGE16(0x5E0) { // STRB <Rd>, [<Rn>, #+<offset_12>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x640:
case 0x648: { // STRB <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x642:
case 0x64A: { // STRB <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x644:
case 0x64C: { // STRB <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x646:
case 0x64E: { // STRB <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x6C0:
case 0x6C8: { // STRB <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x6C2:
case 0x6CA: { // STRB <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x6C4:
case 0x6CC: { // STRB <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x6C6:
case 0x6CE: { // STRB <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x740:
case 0x748: { // STRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x742:
case 0x74A: { // STRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x744:
case 0x74C: { // STRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x746:
case 0x74E: { // STRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x7C0:
case 0x7C8: { // STRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x7C2:
case 0x7CA: { // STRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x7C4:
case 0x7CC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x7C6:
case 0x7CE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
break;
}
case 0x760:
case 0x768: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x762:
case 0x76A: { // STRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x764:
case 0x76C: { // STRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x766:
case 0x76E: { // STRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] - offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7E0:
case 0x7E8: { // STRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSL(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7E2:
case 0x7EA: { // STRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandLSR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7E4:
case 0x7EC: { // STRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandASR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x7E6:
case 0x7EE: { // STRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]!
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t offset = GetShifterOperandROR(instruction);
uint32_t address = _registers[rn] + offset;
_system._memory.Write8(address, _registers[rd]);
_registers[rn] = address;
break;
}
//STRBT
CASE_RANGE16(0x460) { // STRBT <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd-8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x4E0) { // STRBT <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd-8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x660:
case 0x668: { // STRBT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd-8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x662:
case 0x66A: { // STRBT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd-8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x664:
case 0x66C: { // STRBT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x666:
case 0x66E: { // STRBT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x6E0:
case 0x6E8: { // STRBT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6E2:
case 0x6EA: { // STRBT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6E4:
case 0x6EC: { // STRBT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6E6:
case 0x6EE: { // STRBT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write8(address, _registers[rd]);
}
else {
_system._memory.Write8(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write8(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
// STRH
case 0x00B: { // STRH <Rd>, [<Rn>], -<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address - _registers[rm];
break;
}
case 0x08B: { // STRH <Rd>, [<Rn>], +<Rm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address + _registers[rm];
break;
}
case 0x04B: { // STRH <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address - offset;
break;
}
case 0x0CB: { // STRH <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address + offset;
break;
}
case 0x10B: { // STRH <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
_system._memory.Write16(address, _registers[rd]);
break;
}
case 0x18B: { // STRH <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
_system._memory.Write16(address, _registers[rd]);
break;
}
case 0x14B: { // STRH <Rd>, [<Rn>], #-<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
_system._memory.Write16(address, _registers[rd]);
break;
}
case 0x1CB: { // STRH <Rd>, [<Rn>], #+<offset_8>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
_system._memory.Write16(address, _registers[rd]);
break;
}
case 0x12B: { // STRH <Rd>, [<Rn>, -<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] - _registers[rm];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x1AB: { // STRH <Rd>, [<Rn>, +<Rm>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rm = instruction & 0xF;
uint32_t address = _registers[rn] + _registers[rm];
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x16B: { // STRH <Rd>, [<Rn>, #-<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] - offset;
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address;
break;
}
case 0x1EB: { // STRH <Rd>, [<Rn>, #+<offset_8>]
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0);
uint32_t address = _registers[rn] + offset;
_system._memory.Write16(address, _registers[rd]);
_registers[rn] = address;
break;
}
// STRT
CASE_RANGE16(0x420) { // STRT <Rd>, [<Rn>], #-<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
CASE_RANGE16(0x4A0) { // STRT <Rd>, [<Rn>], #+<offset_12>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint16_t offset = (instruction & 0xFFF);
uint32_t address = _registers[rn];
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x620:
case 0x628: { // STRT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x622:
case 0x62A: { // STRT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x624:
case 0x62C: { // STRT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x626:
case 0x62E: { // STRT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address - offset;
break;
}
case 0x6A0:
case 0x6A8: { // STRT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSL(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6A2:
case 0x6AA: { // STRT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandLSR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6A4:
case 0x6AC: { // STRT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandASR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
case 0x6A6:
case 0x6AE: { // STRT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t address = _registers[rn];
uint32_t offset = GetShifterOperandROR(instruction);
if (InAPrivilegedMode()) {
if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) {
_system._memory.Write32(address, _registers[rd]);
}
else {
_system._memory.Write32(address, _registersUser[rd - 8]);
}
}
else {
_system._memory.Write32(address, _registers[rd]);
}
_registers[rn] = address + offset;
break;
}
// SUB
case 0x040:
case 0x048: { // SUB <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSL(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x041: { // SUB <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSLReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x042:
case 0x04A: { // SUB <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x043: { // SUB <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandLSRReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x044:
case 0x04C: { // SUB <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x045: { // SUB <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandASRReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x046: // SUB <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x04E: { // SUB <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandROR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x047: { // SUB <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandRORReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x050:
case 0x058: { // SUBS <Rd>, <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSL(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x051: { // SUBS <Rd>, <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSLReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x052:
case 0x05A: { // SUBS <Rd>, <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x053: { // SUBS <Rd>, <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandLSRReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x054:
case 0x05C: { // SUBS <Rd>, <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x055: { // SUBS <Rd>, <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandASRReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x056: // SUBS <Rd>, <Rn>, <Rm>, RRX #<imm>
case 0x05E: { // SUBS <Rd>, <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandROR(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
case 0x057: { // SUBS <Rd>, <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandRORReg(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
CASE_RANGE16(0x240) { // SUB <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint32_t operand = GetShifterOperandImm(instruction);
SUB(_registers[rn], operand, _registers[rd]);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
CASE_RANGE16(0x250) { // SUBS <Rd>, <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
if (rd == REGPC) {
uint32_t operand = GetShifterOperandImm(instruction);
SUB(_registers[rn], operand, _registers[rd]);
_cpsr = _spsr;
UpdateMode();
_pipelineInstruction = ARM_NOP;
}
else {
uint32_t operand = GetShifterOperandImmFlags(instruction);
SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags);
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
}
break;
}
// SWI
CASE_RANGE256(0xF00) { // SWI <immed_24>
uint32_t imm = instruction & 0xFFFFFF;
SoftwareInterrupt(imm);
break;
}
// SWP
case 0x109: { // SWP <Rd>, <Rm>, [<Rn>]
uint8_t rm = (instruction)& 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
uint32_t temp = _system._memory.Read32(address);
ROR(temp, (address & 0x3) * 8, temp);
_system._memory.Write32(address, _registers[rm]);
_registers[rd] = temp;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// SWPB
case 0x149: { // SWPB <Rd>, <Rm>, [<Rn>]
uint8_t rm = (instruction)& 0xF;
uint8_t rd = (instruction >> 12) & 0xF;
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t address = _registers[rn];
uint8_t temp = _system._memory.Read8(address);
_system._memory.Write8(address, _registers[rm]);
_registers[rd] = temp;
if (rd == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// TEQ
case 0x130:
case 0x138: { // TEQ <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x131: { // TEQ <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x132:
case 0x13A: { // TEQ <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x133: { // TEQ <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x134:
case 0x13C: { // TEQ <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x135: { // TEQ <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x136: // TEQ <Rn>, <Rm>, RRX #<imm>
case 0x13E: { // TEQ <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
case 0x137: { // TEQ <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
CASE_RANGE16(0x330) { // TEQ <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandImmFlags(instruction);
TEQ(_registers[rn], operand, _hostFlags);
break;
}
// TST
case 0x110:
case 0x118: { // TST <Rn>, <Rm>, LSL #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x111: { // TST <Rn>, <Rm>, LSL <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSLRegFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x112:
case 0x11A: { // TST <Rn>, <Rm>, LSR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x113: { // TST <Rn>, <Rm>, LSR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandLSRRegFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x114:
case 0x11C: { // TST <Rn>, <Rm>, ASR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x115: { // TST <Rn>, <Rm>, ASR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandASRRegFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x116: // TST <Rn>, <Rm>, RRX #<imm>
case 0x11E: { // TST <Rn>, <Rm>, ROR #<imm>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
case 0x117: { // TST <Rn>, <Rm>, ROR <Rs>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandRORRegFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
CASE_RANGE16(0x310) { // TST <Rn>, #<immediate>
uint8_t rn = (instruction >> 16) & 0xF;
uint32_t operand = GetShifterOperandImmFlags(instruction);
TST(_registers[rn], operand, _hostFlags);
break;
}
// UMLAL
case 0x0A9: { // UMLAL <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
UMLAL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x0B9: { // UMLALS <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
UMLAL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
// UMULL
case 0x089: { // UMULL <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
UMULL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
case 0x099: { // UMULLS <RdLo>, <RdHi>, <Rm>, <Rs>
uint8_t rdLo = (instruction >> 12) & 0xF;
uint8_t rdHi = (instruction >> 16) & 0xF;
uint8_t rs = (instruction >> 8) & 0xF;
uint8_t rm = (instruction >> 8) & 0xF;
UMULL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags);
if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP;
break;
}
default: {
Log(Error, "Unknown ARM instruction found: 0x%08x at PC=0x%08x", instruction, _registers[REGPC] - 8);
throw BreakPointARMException(0);
__debugbreak();
break;
}
}
} | 32.419783 | 103 | 0.640841 | robojan |
1168e453db2ad86a204d3f15c0361243ed0625f7 | 295 | cpp | C++ | src/rendering/records/SlideGpuRecord.cpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | src/rendering/records/SlideGpuRecord.cpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | src/rendering/records/SlideGpuRecord.cpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | #include "rendering/records/SlideGpuRecord.h"
#include "rendering/utility/gl/GLTexture.h"
SlideGpuRecord::SlideGpuRecord( std::shared_ptr<GLTexture> texture )
: m_texture( texture ),
m_activeLevel( 0 )
{
}
std::weak_ptr<GLTexture> SlideGpuRecord::texture()
{
return m_texture;
}
| 21.071429 | 68 | 0.732203 | halfmvsq |
116b40834155c6244b5bad09a34b0915491a81bc | 145,952 | cpp | C++ | src/generator/x86_64/reg_alloc_multi.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | 2 | 2022-03-28T07:43:02.000Z | 2022-03-30T11:53:25.000Z | src/generator/x86_64/reg_alloc_multi.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | null | null | null | src/generator/x86_64/reg_alloc_multi.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | 2 | 2022-03-30T10:39:04.000Z | 2022-03-30T11:53:28.000Z | #include "generator/x86_64/generator.h"
#include <iostream>
#include <sstream>
using namespace generator::x86_64;
namespace {
std::array<std::array<const char *, 4>, REG_COUNT> reg_names = {
std::array<const char *, 4>{"rax", "eax", "ax", "al"},
{"rbx", "ebx", "bx", "bl"},
{"rcx", "ecx", "cx", "cl"},
{"rdx", "edx", "dx", "dl"},
{"rdi", "edi", "di", "dil"},
{"rsi", "esi", "si", "sil"},
{"r8", "r8d", "r8w", "r8b"},
{"r9", "r9d", "r9w", "r9b"},
{"r10", "r10d", "r10w", "r10b"},
{"r11", "r11d", "r11w", "r11b"},
{"r12", "r12d", "r12w", "r12b"},
{"r13", "r13d", "r13w", "r13b"},
{"r14", "r14d", "r14w", "r14b"},
{"r15", "r15d", "r15w", "r15b"},
};
std::array<const char *, FP_REG_COUNT> fp_reg_names = {"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"};
std::array<REGISTER, 6> call_reg = {REG_DI, REG_SI, REG_D, REG_C, REG_8, REG_9};
// only for integers
const char *reg_name(const REGISTER reg, const Type type) {
const auto &arr = reg_names[reg];
switch (type) {
case Type::imm:
case Type::i64:
return arr[0];
case Type::i32:
return arr[1];
case Type::i16:
return arr[2];
case Type::i8:
return arr[3];
default:
assert(0);
exit(1);
}
}
const char *mem_size(const Type type) {
switch (type) {
case Type::imm:
case Type::i64:
return "QWORD PTR";
case Type::i32:
return "DWORD PTR";
case Type::i16:
return "WORD PTR";
case Type::i8:
return "BYTE PTR";
case Type::f32:
case Type::f64:
case Type::mt:
assert(0);
exit(1);
}
assert(0);
exit(1);
}
Type choose_type(SSAVar *typ1, SSAVar *typ2) {
assert(typ1->type == typ2->type || typ1->is_immediate() || typ2->is_immediate());
if (typ1->is_immediate() && typ2->is_immediate()) {
return Type::i64;
} else if (typ1->is_immediate()) {
return typ2->type;
} else {
return typ1->type;
}
}
} // namespace
void RegAlloc::compile_blocks() {
auto compiled_blocks = std::vector<BasicBlock *>{};
for (const auto &bb : gen->ir->basic_blocks) {
if (bb->gen_info.compiled) {
continue;
}
if (!is_block_top_level(bb.get())) {
continue;
}
auto supported = true;
for (auto *input : bb->inputs) {
if (!std::holds_alternative<size_t>(input->info)) {
supported = false;
break;
}
const auto static_idx = std::get<size_t>(input->info);
input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC;
input->gen_info.static_idx = static_idx;
}
if (!supported) {
assert(0);
continue;
}
if (!bb->gen_info.input_map_setup) {
generate_input_map(bb.get());
}
size_t max_stack_frame = 0;
compiled_blocks.clear();
compile_block(bb.get(), true, max_stack_frame, compiled_blocks);
translation_blocks.clear();
asm_buf.clear();
}
// when blocks have a self-contained circular reference chain, they do not get recognized as top-level so
// we compile them here and use the lowest-id-block (which should later be the lowest-address one) as the first
for (const auto &bb : gen->ir->basic_blocks) {
if (bb->gen_info.compiled) {
continue;
}
auto supported = true;
for (auto *input : bb->inputs) {
if (!std::holds_alternative<size_t>(input->info)) {
supported = false;
break;
}
const auto static_idx = std::get<size_t>(input->info);
input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC;
input->gen_info.static_idx = static_idx;
}
if (!supported) {
assert(0);
continue;
}
// only for testing
if (!bb->gen_info.input_map_setup) {
generate_input_map(bb.get());
}
size_t max_stack_frame = 0;
compiled_blocks.clear();
bb->gen_info.manual_top_level = true;
compile_block(bb.get(), true, max_stack_frame, compiled_blocks);
translation_blocks.clear();
asm_buf.clear();
}
}
// compile all bblocks with an id greater than this with the normal generator
constexpr size_t BB_OLD_COMPILE_ID_TIL = static_cast<size_t>(-1);
// only merge bblocks with an id <= BB_MERGE_TIL_ID, otherwise mark them as a top-level block and pass inputs through statics
constexpr size_t BB_MERGE_TIL_ID = static_cast<size_t>(-1);
void RegAlloc::compile_block(BasicBlock *bb, const bool first_block, size_t &max_stack_frame_size, std::vector<BasicBlock *> &compiled_blocks) {
RegMap reg_map = {};
FPRegMap fp_reg_map = {};
StackMap stack_map = {};
cur_bb = bb;
cur_reg_map = ®_map;
cur_fp_reg_map = &fp_reg_map;
cur_stack_map = &stack_map;
// TODO: this hack is needed because syscalls have a continuation mapping so we cant create the input mapping in the previous' block
// cfop
if (!bb->gen_info.input_map_setup) {
for (auto *input : bb->inputs) {
if (!std::holds_alternative<size_t>(input->info)) {
assert(0);
exit(1);
return;
}
const auto static_idx = std::get<size_t>(input->info);
input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC;
input->gen_info.static_idx = static_idx;
BasicBlock::GeneratorInfo::InputInfo info;
info.location = BasicBlock::GeneratorInfo::InputInfo::STATIC;
info.static_idx = static_idx;
bb->gen_info.input_map.push_back(info);
}
bb->gen_info.input_map_setup = true;
}
if (bb->id > BB_OLD_COMPILE_ID_TIL) {
gen->compile_block(bb);
bb->gen_info.compiled = true;
} else {
// fill in reg_map and stack_map from inputs
for (auto *var : bb->inputs) {
if (var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) {
reg_map[var->gen_info.reg_idx].cur_var = var;
reg_map[var->gen_info.reg_idx].alloc_time = 0;
} else if (var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) {
fp_reg_map[var->gen_info.reg_idx].cur_var = var;
fp_reg_map[var->gen_info.reg_idx].alloc_time = 0;
} else if (var->gen_info.location == SSAVar::GeneratorInfoX64::STACK_FRAME) {
const auto stack_slot = var->gen_info.stack_slot;
if (stack_map.size() <= stack_slot) {
stack_map.resize(stack_slot + 1);
}
stack_map[stack_slot].free = false;
stack_map[stack_slot].var = var;
}
}
if (!first_block) {
if (!(gen->optimizations & Generator::OPT_NO_TRANS_BBS) || is_block_jumpable(bb)) {
generate_translation_block(bb);
}
print_asm("b%zu_reg_alloc:\n", bb->id);
print_asm("# MBRA\n"); // multi-block register allocation
print_asm("# Virt Start: %#lx\n# Virt End: %#lx\n", bb->virt_start_addr, bb->virt_end_addr);
}
init_time_of_use(bb);
compile_vars(bb);
prepare_cf_ops(bb);
max_stack_frame_size = std::max(max_stack_frame_size, stack_map.size());
{
auto asm_block = AssembledBlock{};
asm_block.bb = bb;
asm_block.assembly = asm_buf;
asm_buf.clear();
asm_block.reg_map = reg_map;
asm_block.fp_reg_map = fp_reg_map;
asm_block.stack_map = std::move(stack_map);
assembled_blocks.push_back(std::move(asm_block));
}
cur_bb = nullptr;
cur_stack_map = nullptr;
cur_reg_map = nullptr;
cur_fp_reg_map = nullptr;
bb->gen_info.compiled = true;
compiled_blocks.push_back(bb);
// TODO: prioritize jumps so we can omit the jmp bX_reg_alloc
for (const auto &cf_op : bb->control_flow_ops) {
auto *target = cf_op.target();
if (target && !target->gen_info.compiled && target->id <= BB_MERGE_TIL_ID && !is_block_top_level(target) && !target->gen_info.call_cont_block) {
compile_block(target, false, max_stack_frame_size, compiled_blocks);
}
if (cf_op.type == CFCInstruction::call) {
// sometimes there are cases where a block is a call target and continuation block,
// e.g. with noreturn calls the next block will be recognized as a continuation block
auto *cont_block = std::get<CfOp::CallInfo>(cf_op.info).continuation_block;
if (!cont_block->gen_info.compiled && !is_block_top_level(cont_block)) {
compile_block(cont_block, false, max_stack_frame_size, compiled_blocks);
}
} else if (cf_op.type == CFCInstruction::icall) {
auto *cont_block = std::get<CfOp::ICallInfo>(cf_op.info).continuation_block;
if (!cont_block->gen_info.compiled && !is_block_top_level(cont_block)) {
compile_block(cont_block, false, max_stack_frame_size, compiled_blocks);
}
}
}
if (first_block) {
// need to add a bit of space to the stack since the cfops might need to spill to the stack
max_stack_frame_size += gen->ir->statics.size();
// align to 16 bytes
max_stack_frame_size = (((max_stack_frame_size * 8) + 15) & 0xFFFFFFFF'FFFFFFF0);
for (auto *bb : compiled_blocks) {
bb->gen_info.max_stack_size = max_stack_frame_size;
}
fprintf(gen->out_fd, "b%zu:\nsub rsp, %zu\n", bb->id, max_stack_frame_size);
fprintf(gen->out_fd, "# MBRA\n"); // multi-block register allocation
fprintf(gen->out_fd, "# Virt Start: %#lx\n# Virt End: %#lx\n", bb->virt_start_addr, bb->virt_end_addr);
write_assembled_blocks(max_stack_frame_size, compiled_blocks);
fprintf(gen->out_fd, "\n# Translation Blocks\n");
for (const auto &pair : translation_blocks) {
fprintf(gen->out_fd, "b%zu:\nsub rsp, %zu\n", pair.first, max_stack_frame_size);
fprintf(gen->out_fd, "# MBRATB\n"); // multi-block register allocation translation block
fprintf(gen->out_fd, "%s\n", pair.second.c_str());
}
fprintf(gen->out_fd, "\n");
translation_blocks.clear();
assembled_blocks.clear();
}
}
}
void RegAlloc::compile_vars(BasicBlock *bb) {
auto ®_map = *cur_reg_map;
std::ostringstream ir_stream;
for (size_t var_idx = 0; var_idx < bb->variables.size(); ++var_idx) {
auto *var = bb->variables[var_idx].get();
const auto cur_time = var_idx;
// print ir for better readability
// TODO: add flag for this to reduce useless stuff in asm file
// TODO: when we merge ops, we need to print ir before the merged op
ir_stream.str("");
var->print(ir_stream, gen->ir);
print_asm("# %s\n", ir_stream.str().c_str());
if (var->gen_info.already_generated) {
continue;
}
// TODO: this essentially skips input vars but we should have a seperate if for that
// since the location of the input vars is supplied by the previous block
if (var->is_immediate() || std::holds_alternative<size_t>(var->info)) {
// skip immediates and statics, we load them on-demand
continue;
}
if (!std::holds_alternative<std::unique_ptr<Operation>>(var->info)) {
// skip vars that depend on ops of other vars for example
continue;
}
auto *op = std::get<std::unique_ptr<Operation>>(var->info).get();
if (is_float(op->lifter_info.in_op_size) || is_float(var->type)) {
compile_fp_op(var, cur_time);
continue;
}
switch (op->type) {
case Instruction::add:
[[fallthrough]];
case Instruction::sub:
[[fallthrough]];
case Instruction::shl:
[[fallthrough]];
case Instruction::shr:
[[fallthrough]];
case Instruction::sar:
[[fallthrough]];
case Instruction::_or:
[[fallthrough]];
case Instruction::_and:
[[fallthrough]];
case Instruction::_xor:
[[fallthrough]];
case Instruction::umax:
[[fallthrough]];
case Instruction::umin:
[[fallthrough]];
case Instruction::max:
[[fallthrough]];
case Instruction::min:
[[fallthrough]];
case Instruction::mul_l:
[[fallthrough]];
case Instruction::ssmul_h:
[[fallthrough]];
case Instruction::uumul_h:
[[fallthrough]];
case Instruction::div:
[[fallthrough]];
case Instruction::udiv: {
auto *in1 = op->in_vars[0].get();
auto *in2 = op->in_vars[1].get();
auto *dst = op->out_vars[0];
// TODO: the imm-branch and not-imm-branch can probably be merged if we use a string as the second operand
// and just put the imm in there
if (in2->is_immediate() && !std::get<SSAVar::ImmInfo>(in2->info).binary_relative) {
const auto imm_val = std::get<SSAVar::ImmInfo>(in2->info).val;
REGISTER in1_reg;
if (op->type != Instruction::ssmul_h && op->type != Instruction::uumul_h && op->type != Instruction::div && op->type != Instruction::udiv) {
in1_reg = load_val_in_reg(cur_time, in1);
} else {
// need to load into rax and clear rdx
in1_reg = load_val_in_reg(cur_time, in1, REG_A);
// rdx gets clobbered by mul and used by div
if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) {
save_reg(REG_D);
}
clear_reg(cur_time, REG_D);
if (op->type == Instruction::div) {
if (var->type == Type::i32) {
print_asm("cdq\n");
} else {
print_asm("cqo\n");
}
} else if (op->type == Instruction::udiv) {
print_asm("xor edx, edx\n");
}
}
const auto in1_reg_name = reg_name(in1_reg, choose_type(in1, in2));
REGISTER dst_reg = REG_NONE;
if (op->type != Instruction::add || in1->gen_info.last_use_time == cur_time) {
dst_reg = in1_reg;
} else {
// check if there is a free register
for (size_t reg = 0; reg < REG_COUNT; ++reg) {
if (reg_map[reg].cur_var == nullptr) {
dst_reg = static_cast<REGISTER>(reg);
break;
}
auto *var = reg_map[reg].cur_var;
if (var->gen_info.last_use_time < cur_time) {
dst_reg = static_cast<REGISTER>(reg);
break;
}
}
if (dst_reg == REG_NONE) {
size_t in1_next_use = 0;
for (auto use : in1->gen_info.uses) {
if (use > cur_time) {
in1_next_use = use;
break;
}
}
// check if there is a variable thats already saved on the stack and used after the dst
auto check_unsaved_vars = !in1->gen_info.saved_in_stack;
for (size_t reg = 0; reg < REG_COUNT; ++reg) {
auto *var = reg_map[reg].cur_var;
if (!check_unsaved_vars && !var->gen_info.saved_in_stack) {
continue;
}
size_t var_next_use = 0;
for (auto use : var->gen_info.uses) {
if (use > cur_time) {
var_next_use = use;
break;
}
}
if (var_next_use > in1_next_use) {
dst_reg = static_cast<REGISTER>(reg);
break;
}
}
if (dst_reg == REG_NONE) {
dst_reg = in1_reg;
}
}
}
const auto dst_reg_name = reg_name(dst_reg, choose_type(in1, in2));
if (reg_map[dst_reg].cur_var && reg_map[dst_reg].cur_var->gen_info.last_use_time > cur_time) {
save_reg(dst_reg);
}
auto did_merge = false;
if ((gen->optimizations & Generator::OPT_MERGE_OP) && dst && dst->ref_count == 1 && bb->variables.size() > var_idx + 1) {
if (op->type == Instruction::add) {
// check if next instruction is a load
auto *next_var = bb->variables[var_idx + 1].get();
if (std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) {
auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get();
if (!is_float(next_var->type) && !is_float(next_op->lifter_info.in_op_size)) {
if (next_op->type == Instruction::load && next_op->in_vars[0] == dst) {
auto *load_dst = next_op->out_vars[0];
// check for zero/sign-extend
if (load_dst->ref_count == 1 && bb->variables.size() > var_idx + 2) {
auto *nnext_var = bb->variables[var_idx + 2].get();
if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) {
auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get();
if (nnext_op->in_vars[0] == load_dst && nnext_op->type == Instruction::zero_extend) {
auto *ext_dst = nnext_op->out_vars[0];
if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) {
if (load_dst->type == Type::i32) {
print_asm("mov %s, [%s + %ld]\n", reg_names[dst_reg][1], in1_reg_name, imm_val);
} else {
print_asm("movzx %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val);
}
} else {
const auto imm_reg = load_val_in_reg(cur_time, in2);
if (load_dst->type == Type::i32) {
print_asm("mov %s, [%s + %s]\n", reg_names[dst_reg][1], in1_reg_name, reg_names[imm_reg][0]);
} else {
print_asm("movzx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]);
}
}
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, ext_dst, dst_reg);
load_dst->gen_info.already_generated = true;
ext_dst->gen_info.already_generated = true;
did_merge = true;
} else if (nnext_op->in_vars[0] == load_dst && nnext_op->type == Instruction::sign_extend) {
auto *ext_dst = nnext_op->out_vars[0];
if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) {
if (load_dst->type == Type::i32) {
assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64);
print_asm("movsxd %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val);
} else {
print_asm("movsx %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val);
}
} else {
const auto imm_reg = load_val_in_reg(cur_time, in2);
if (load_dst->type == Type::i32) {
assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64);
print_asm("movsxd %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]);
} else {
print_asm("movsx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]);
}
}
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, ext_dst, dst_reg);
load_dst->gen_info.already_generated = true;
ext_dst->gen_info.already_generated = true;
did_merge = true;
}
}
}
if (!did_merge) {
// merge add and load
if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) {
print_asm("mov %s, [%s + %ld]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, imm_val);
} else {
const auto imm_reg = load_val_in_reg(cur_time, in2);
print_asm("mov %s, [%s + %s]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, reg_names[imm_reg][0]);
}
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, load_dst, dst_reg);
load_dst->gen_info.already_generated = true;
did_merge = true;
}
} else if (next_op->type == Instruction::cast) {
// detect add/cast/store sequence
auto *cast_var = next_op->out_vars[0];
if (cast_var->ref_count == 1 && bb->variables.size() > var_idx + 2) {
auto *nnext_var = bb->variables[var_idx + 2].get();
if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) {
auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get();
if (nnext_op->type == Instruction::store && nnext_op->in_vars[0] == dst && nnext_op->in_vars[1] == cast_var) {
auto *store_dst = nnext_op->out_vars[0]; // should be == nnext_var
// load source of cast
const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get());
print_asm("mov [%s + %ld], %s\n", in1_reg_name, imm_val, reg_name(cast_reg, cast_var->type));
cast_var->gen_info.already_generated = true;
store_dst->gen_info.already_generated = true;
did_merge = true;
}
}
}
} else if (next_op->type == Instruction::store && next_op->in_vars[0].get() == dst) {
// merge add/store
auto *store_src = next_op->in_vars[1].get();
if (store_src->is_immediate() && !store_src->get_immediate().binary_relative) {
const auto store_imm_val = store_src->get_immediate().val;
if (store_imm_val != INT64_MIN && std::abs(store_imm_val) < 0x7FFFFFFF) {
print_asm("mov %s [%s + %ld], %ld\n", mem_size(next_op->lifter_info.in_op_size), in1_reg_name, imm_val, store_imm_val);
next_op->out_vars[0]->gen_info.already_generated = true;
did_merge = true;
}
}
if (!did_merge) {
const auto src_reg = load_val_in_reg(cur_time, store_src);
print_asm("mov [%s + %ld], %s\n", in1_reg_name, imm_val, reg_name(src_reg, store_src->type));
next_op->out_vars[0]->gen_info.already_generated = true;
did_merge = true;
}
}
}
}
} else if ((gen->optimizations & Generator::OPT_ARCH_BMI2) && op->type == Instruction::_and && op->in_vars[1]->is_immediate()) {
// v2 <- and v0, 31/63
// (cast i32 v3 <- i64 v1)
// shl/shr/sar v3/v1, v2
if (std::get<SSAVar::ImmInfo>(op->in_vars[1]->info).val == 0x1F && bb->variables.size() > var_idx + 2) {
// check for cast
auto *next_var = bb->variables[var_idx + 1].get();
if (next_var->ref_count == 1 && next_var->type == Type::i32 && std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) {
auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get();
if (next_op->type == Instruction::cast && !is_float(next_var->type) && !is_float(next_op->lifter_info.in_op_size)) {
// check for shift
auto *nnext_var = bb->variables[var_idx + 2].get();
if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) {
auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get();
if ((nnext_op->type == Instruction::shl || nnext_op->type == Instruction::shr || nnext_op->type == Instruction::sar) && nnext_op->in_vars[0] == next_var &&
nnext_op->in_vars[1] == dst) {
// this can be merged into a single shift
const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get());
if (nnext_op->type == Instruction::shl) {
print_asm("shlx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]);
} else if (nnext_op->type == Instruction::shr) {
print_asm("shrx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]);
} else if (nnext_op->type == Instruction::sar) {
print_asm("sarx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]);
}
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, nnext_var, dst_reg);
next_var->gen_info.already_generated = true;
nnext_var->gen_info.already_generated = true;
did_merge = true;
}
}
}
}
} else if (std::get<SSAVar::ImmInfo>(op->in_vars[1]->info).val == 0x3F) {
auto *next_var = bb->variables[var_idx + 1].get();
if (std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) {
auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get();
if ((next_op->type == Instruction::shl || next_op->type == Instruction::shr || next_op->type == Instruction::sar) && !is_float(next_var->type)) {
// check if the shift operand is 64bit and we shift the anded value
if (next_op->in_vars[0]->type == Type::i64 && next_op->in_vars[1] == dst) {
const auto shift_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get());
if (next_op->type == Instruction::shl) {
print_asm("shlx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]);
} else if (next_op->type == Instruction::shr) {
print_asm("shrx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]);
} else if (next_op->type == Instruction::sar) {
print_asm("sarx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]);
}
next_var->gen_info.already_generated = true;
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, next_var, dst_reg);
did_merge = true;
}
}
}
}
}
}
if (did_merge) {
break;
}
const auto op_with_imm32 = [imm_val, this, in1_reg_name, cur_time, in1, in2](const char *op_str) {
// 0x8000'0000'0000'0000 cannot be represented as uint64_t
if (imm_val != INT64_MIN && std::abs(imm_val) <= 0x7FFF'FFFF) {
print_asm("%s %s, 0x%lx\n", op_str, in1_reg_name, imm_val);
} else {
auto imm_reg = alloc_reg(cur_time);
print_asm("mov %s, 0x%lx\n", reg_names[imm_reg][0], imm_val);
print_asm("%s %s, %s\n", op_str, in1_reg_name, reg_name(imm_reg, choose_type(in1, in2)));
}
};
switch (op->type) {
case Instruction::add:
if (dst_reg == in1_reg) {
op_with_imm32("add");
} else {
if (imm_val != INT64_MIN && std::abs(imm_val) <= 0x7FFF'FFFF) {
print_asm("lea %s, [%s + %ld]\n", dst_reg_name, in1_reg_name, imm_val);
} else {
auto imm_reg = alloc_reg(cur_time);
print_asm("mov %s, %ld\n", reg_names[imm_reg][0], imm_val);
print_asm("lea %s, [%s + %s]\n", reg_names[dst_reg][0], reg_names[in1_reg][0], reg_names[imm_reg][0]);
}
}
break;
case Instruction::sub:
op_with_imm32("sub");
break;
case Instruction::shl:
print_asm("shl %s, %ld\n", in1_reg_name, imm_val);
break;
case Instruction::shr:
print_asm("shr %s, %ld\n", in1_reg_name, imm_val);
break;
case Instruction::sar:
print_asm("sar %s, %ld\n", in1_reg_name, imm_val);
break;
case Instruction::_or:
op_with_imm32("or");
break;
case Instruction::_and:
op_with_imm32("and");
break;
case Instruction::_xor:
op_with_imm32("xor");
break;
case Instruction::umax:
op_with_imm32("cmp");
print_asm("jae b%zu_%zu_max\n", bb->id, var_idx);
print_asm("mov %s, %ld\n", in1_reg_name, imm_val);
print_asm("b%zu_%zu_max:\n", bb->id, var_idx);
break;
case Instruction::umin:
op_with_imm32("cmp");
print_asm("jbe b%zu_%zu_min\n", bb->id, var_idx);
print_asm("mov %s, %ld\n", in1_reg_name, imm_val);
print_asm("b%zu_%zu_min:\n", bb->id, var_idx);
break;
case Instruction::max:
op_with_imm32("cmp");
print_asm("jge b%zu_%zu_smax\n", bb->id, var_idx);
print_asm("mov %s, %ld\n", in1_reg_name, imm_val);
print_asm("b%zu_%zu_smax:\n", bb->id, var_idx);
break;
case Instruction::min:
op_with_imm32("cmp");
print_asm("jle b%zu_%zu_smin\n", bb->id, var_idx);
print_asm("mov %s, %ld\n", in1_reg_name, imm_val);
print_asm("b%zu_%zu_smin:\n", bb->id, var_idx);
break;
case Instruction::mul_l:
op_with_imm32("imul");
break;
case Instruction::ssmul_h: {
const auto imm_reg = load_val_in_reg(cur_time, in2);
print_asm("imul %s\n", reg_name(imm_reg, in1->type));
break;
}
case Instruction::uumul_h: {
const auto imm_reg = load_val_in_reg(cur_time, in2);
print_asm("mul %s\n", reg_name(imm_reg, in1->type));
break;
}
case Instruction::div: {
const auto imm_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D);
print_asm("idiv %s\n", reg_name(imm_reg, in1->type));
break;
}
case Instruction::udiv: {
const auto imm_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D);
print_asm("div %s\n", reg_name(imm_reg, in1->type));
break;
}
default:
// should never be hit
assert(0);
exit(1);
}
clear_reg(cur_time, dst_reg);
if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) {
// result is in rdx
set_var_to_reg(cur_time, dst, REG_D);
} else if (op->type == Instruction::div || op->type == Instruction::udiv) {
if (dst) {
set_var_to_reg(cur_time, dst, REG_A);
}
if (op->out_vars[1]) {
set_var_to_reg(cur_time, op->out_vars[1], REG_D);
}
} else {
set_var_to_reg(cur_time, dst, dst_reg);
}
break;
}
// TODO: when in1 == imm & in2 != imm and we have a sub we can neg in2, add in2, in1
REGISTER in1_reg, in2_reg;
if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) {
// TODO: here we could optimise and accept either in1 or in2 in reg a if one of them already is or is already in a register
in1_reg = load_val_in_reg(cur_time, in1, REG_A);
// rdx gets clobbered but it's fine to use it as a source operand
in2_reg = load_val_in_reg(cur_time, in2);
if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) {
save_reg(REG_D);
}
clear_reg(cur_time, REG_D);
} else if (op->type == Instruction::div || op->type == Instruction::udiv) {
in1_reg = load_val_in_reg(cur_time, in1, REG_A);
// div uses rdx so we cannot have a source in it
in2_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D);
if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) {
save_reg(REG_D);
}
clear_reg(cur_time, REG_D);
if (op->type == Instruction::div) {
if (var->type == Type::i32) {
print_asm("cdq\n");
} else {
print_asm("cqo\n");
}
} else {
print_asm("xor edx, edx\n");
}
} else if (op->type == Instruction::shl || op->type == Instruction::shr || op->type == Instruction::sar) {
if (!(gen->optimizations & Generator::OPT_ARCH_BMI2) || (op->in_vars[0]->type != Type::i64 && op->in_vars[0]->type != Type::i32)) {
// when we shift 16/8 bit values we need to use the shl/shr/sar instructions so the shift val needs to be in cl
in2_reg = load_val_in_reg(cur_time, in2, REG_C);
} else {
in2_reg = load_val_in_reg(cur_time, in2);
}
in1_reg = load_val_in_reg(cur_time, in1);
} else {
in1_reg = load_val_in_reg(cur_time, in1);
in2_reg = load_val_in_reg(cur_time, in2);
}
const auto type = choose_type(in1, in2);
const auto in1_reg_name = reg_name(in1_reg, type);
const auto in2_reg_name = reg_name(in2_reg, type);
if (in1->gen_info.last_use_time > cur_time) {
save_reg(in1_reg);
}
if (merge_op_bin(cur_time, var_idx, in1_reg)) {
break;
}
const auto write_shift = [this, in1_reg_name, in2_reg_name, op](const char *instr_name) {
if (!(gen->optimizations & Generator::OPT_ARCH_BMI2) || (op->in_vars[0]->type != Type::i64 && op->in_vars[0]->type != Type::i32)) {
print_asm("%s %s, cl\n", instr_name, in1_reg_name);
} else {
print_asm("%sx %s, %s, %s\n", instr_name, in1_reg_name, in1_reg_name, in2_reg_name);
}
};
switch (op->type) {
case Instruction::add:
print_asm("add %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::sub:
print_asm("sub %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::shl:
write_shift("shl");
break;
case Instruction::shr:
write_shift("shr");
break;
case Instruction::sar:
write_shift("sar");
break;
case Instruction::_or:
print_asm("or %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::_and:
print_asm("and %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::_xor:
print_asm("xor %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::umax:
print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name);
print_asm("cmovb %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::umin:
print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name);
print_asm("cmova %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::max:
print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name);
print_asm("cmovl %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::min:
print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name);
print_asm("cmovg %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::mul_l:
print_asm("imul %s, %s\n", in1_reg_name, in2_reg_name);
break;
case Instruction::ssmul_h:
print_asm("imul %s\n", in2_reg_name);
break;
case Instruction::uumul_h:
print_asm("mul %s\n", in2_reg_name);
break;
case Instruction::div:
print_asm("idiv %s\n", in2_reg_name);
break;
case Instruction::udiv:
print_asm("div %s\n", in2_reg_name);
break;
default:
// should never be hit
assert(0);
exit(1);
}
clear_reg(cur_time, in1_reg);
if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) {
// result is in rdx
set_var_to_reg(cur_time, dst, REG_D);
} else if (op->type == Instruction::div || op->type == Instruction::udiv) {
if (dst) {
set_var_to_reg(cur_time, dst, REG_A);
}
if (op->out_vars[1]) {
set_var_to_reg(cur_time, op->out_vars[1], REG_D);
}
} else {
set_var_to_reg(cur_time, dst, in1_reg);
}
break;
}
case Instruction::load: {
auto *addr = op->in_vars[0].get();
auto *dst = op->out_vars[0];
// TODO: when addr is a (binary-relative) immediate it should be foldable into one instruction
const auto addr_reg = load_val_in_reg(cur_time, addr);
if (addr->gen_info.last_use_time > cur_time) {
save_reg(addr_reg);
}
print_asm("mov %s, [%s]\n", reg_name(addr_reg, dst->type), reg_names[addr_reg][0]);
clear_reg(cur_time, addr_reg);
set_var_to_reg(cur_time, dst, addr_reg);
break;
}
case Instruction::store: {
auto *addr = op->in_vars[0].get();
auto *val = op->in_vars[1].get();
assert(addr->is_immediate() || addr->type == Type::i64);
// TODO: when addr is a (binary-relative) immediate this can be omitted sometimes
const auto addr_reg = load_val_in_reg(cur_time, addr);
if (val->is_immediate() && !val->get_immediate().binary_relative) {
const auto imm_val = val->get_immediate().val;
if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) {
print_asm("mov %s [%s], %ld\n", mem_size(op->lifter_info.in_op_size), reg_names[addr_reg][0], imm_val);
break;
}
}
const auto val_reg = load_val_in_reg(cur_time, val);
print_asm("mov [%s], %s\n", reg_names[addr_reg][0], reg_name(val_reg, op->lifter_info.in_op_size));
break;
}
case Instruction::_not: {
auto *val = op->in_vars[0].get();
auto *dst = op->out_vars[0];
assert(val->type == dst->type || val->is_immediate());
const auto val_reg = load_val_in_reg(cur_time, val);
if (val->gen_info.last_use_time > cur_time) {
save_reg(val_reg);
}
print_asm("not %s\n", reg_name(val_reg, val->is_immediate() ? Type::i64 : val->type));
clear_reg(cur_time, val_reg);
set_var_to_reg(cur_time, dst, val_reg);
break;
}
case Instruction::seq:
[[fallthrough]];
case Instruction::slt:
[[fallthrough]];
case Instruction::sltu: {
auto *cmp1 = op->in_vars[0].get();
auto *cmp2 = op->in_vars[1].get();
auto *val1 = op->in_vars[2].get();
auto *val2 = op->in_vars[3].get();
auto *dst = op->out_vars[0];
const auto cmp1_reg = load_val_in_reg(cur_time, cmp1);
if (cmp1->gen_info.last_use_time > cur_time) {
save_reg(cmp1_reg);
}
if (val1->is_immediate() && val2->is_immediate()) {
const auto &val1_info = std::get<SSAVar::ImmInfo>(val1->info);
const auto &val2_info = std::get<SSAVar::ImmInfo>(val2->info);
if (val1_info.val == 1 && !val1_info.binary_relative && val2_info.val == 0 && !val2_info.binary_relative) {
if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && std::get<SSAVar::ImmInfo>(cmp2->info).val != INT64_MIN &&
std::abs(cmp2->get_immediate().val) < 0x7FFF'FFFF) {
const auto type = cmp1->is_immediate() ? Type::i64 : cmp1->type;
print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val);
} else {
const auto cmp2_reg = load_val_in_reg(cur_time, cmp2);
auto type = choose_type(cmp1, cmp2);
print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type));
}
if (!cmp1->is_immediate() || std::get<SSAVar::ImmInfo>(cmp1->info).binary_relative || static_cast<uint64_t>(std::get<SSAVar::ImmInfo>(cmp1->info).val) > 255) {
// dont need to clear if we know the register holds a value that fits into 1 byte
print_asm("mov %s, 0\n", reg_names[cmp1_reg][0]);
}
if (op->type == Instruction::seq) {
print_asm("sete %s\n", reg_names[cmp1_reg][3]);
} else if (op->type == Instruction::slt) {
print_asm("setl %s\n", reg_names[cmp1_reg][3]);
} else {
print_asm("setb %s\n", reg_names[cmp1_reg][3]);
}
clear_reg(cur_time, cmp1_reg);
set_var_to_reg(cur_time, dst, cmp1_reg);
break;
}
}
const auto val1_reg = load_val_in_reg(cur_time, val1);
const auto val2_reg = load_val_in_reg(cur_time, val2);
if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && std::get<SSAVar::ImmInfo>(cmp2->info).val != INT64_MIN &&
std::abs(std::get<SSAVar::ImmInfo>(cmp2->info).val) <= 0x7FFFFFFF) {
const auto type = cmp1->is_immediate() ? Type::i64 : cmp1->type;
print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val);
} else {
const auto cmp2_reg = load_val_in_reg(cur_time, cmp2);
auto type = choose_type(cmp1, cmp2);
print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type));
}
if (op->type == Instruction::seq) {
print_asm("cmove %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type));
print_asm("cmovne %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type));
} else if (op->type == Instruction::slt) {
print_asm("cmovl %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type));
print_asm("cmovge %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type));
} else {
print_asm("cmovb %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type));
print_asm("cmovae %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type));
}
clear_reg(cur_time, cmp1_reg);
set_var_to_reg(cur_time, dst, cmp1_reg);
break;
}
case Instruction::setup_stack: {
auto *dst = op->out_vars[0];
assert(dst->type == Type::i64);
const auto dst_reg = alloc_reg(cur_time);
print_asm("mov %s, [init_stack_ptr]\n", reg_names[dst_reg][0]);
set_var_to_reg(cur_time, dst, dst_reg);
break;
}
case Instruction::cast:
[[fallthrough]];
case Instruction::sign_extend:
[[fallthrough]];
case Instruction::zero_extend: {
auto *input = op->in_vars[0].get();
auto *output = op->out_vars[0];
if (input->is_immediate() && !std::get<SSAVar::ImmInfo>(input->info).binary_relative) {
// cast,sign_extend and zero_extend are no-ops
auto imm = std::get<SSAVar::ImmInfo>(input->info).val;
switch (output->type) {
case Type::i64:
break;
case Type::i32:
imm = imm & 0xFFFFFFFF;
break;
case Type::i16:
imm = imm & 0xFFFF;
break;
case Type::i8:
imm = imm & 0xFF;
break;
default:
assert(0);
exit(1);
}
const auto dst_reg = alloc_reg(cur_time);
const auto dst_reg_name = reg_name(dst_reg, output->type);
print_asm("mov %s, %ld\n", dst_reg_name, imm);
set_var_to_reg(cur_time, output, dst_reg);
break;
}
const auto dst_reg = load_val_in_reg(cur_time, input);
const auto dst_reg_name = reg_name(dst_reg, input->type);
if (input->gen_info.last_use_time > cur_time) {
save_reg(dst_reg);
}
// TODO: in theory you could simply alias the input var for cast and zero_extend
if (op->type == Instruction::sign_extend) {
print_asm("movsx %s, %s\n", reg_name(dst_reg, output->type), dst_reg_name);
} else if (input->type != output->type) {
// clear upper parts of register
// find smallest type
auto type = input->type;
if (output->type == Type::i8) {
type = Type::i8;
} else if (output->type == Type::i16 && type != Type::i8) {
type = Type::i16;
} else if (output->type == Type::i32 && type != Type::i8 && type != Type::i16) {
type = Type::i32;
}
if (type == Type::i32) {
const auto name = reg_name(dst_reg, type);
print_asm("mov %s, %s\n", name, name);
} else {
if (type == Type::i16) {
print_asm("and %s, 0xFFFF\n", reg_names[dst_reg][0]);
} else if (type == Type::i8) {
print_asm("and %s, 0xFF\n", reg_names[dst_reg][0]);
}
// nothing to do for 64 bit
}
}
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, output, dst_reg);
break;
}
default:
fprintf(stderr, "Encountered unknown instruction in generator\n");
assert(0);
exit(1);
}
}
}
void RegAlloc::compile_fp_op(SSAVar *var, size_t cur_time) {
const auto *op = std::get<std::unique_ptr<Operation>>(var->info).get();
SSAVar *in1 = op->in_vars[0];
// handles binary fp operations
auto bin_op = [this, var, op, in1, cur_time](const char *instruction) {
assert(is_float(var->type) && var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type);
const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, op->in_vars[0]);
const FP_REGISTER in2_reg = load_val_in_fp_reg(cur_time, op->in_vars[1]);
if (in1->gen_info.last_use_time > cur_time) {
save_fp_reg(in1_reg);
}
print_asm("%s%s %s, %s\n", instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg]);
clear_fp_reg(cur_time, in1_reg);
set_var_to_fp_reg(cur_time, var, in1_reg);
};
// handles fused multiply add operations
auto fma_op = [this, var, op, in1, cur_time](const char *fma_instruction, const char *second_instruction, const bool negate_mul_res = false) {
assert(is_float(var->type) && var->type == in1->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, in1);
const FP_REGISTER in2_reg = load_val_in_fp_reg(cur_time, op->in_vars[1]);
const FP_REGISTER in3_reg = load_val_in_fp_reg(cur_time, op->in_vars[2]);
if (in1->gen_info.last_use_time > cur_time) {
save_fp_reg(in1_reg);
}
if (gen->optimizations & Generator::OPT_ARCH_FMA3) {
print_asm("%s%s %s, %s, %s\n", fma_instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg], fp_reg_names[in3_reg]);
} else {
assert(is_float(var->type) && var->type == in1->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
print_asm("muls%s %s, %s\n", Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg]);
if (negate_mul_res) {
const REGISTER tempr_reg = alloc_reg(cur_time);
print_asm("mov %s, %lu\n", reg_name(tempr_reg, Type::i64), (var->type == Type::f32 ? 0x8000'0000 : 0x8000'0000'0000'0000));
print_asm("push %s\n", reg_name(tempr_reg, Type::i64));
print_asm("push QWORD PTR 0\n");
print_asm("pxor %s, [rsp]\n", fp_reg_names[in1_reg]);
print_asm("add rsp, 16\n");
}
print_asm("%s%s %s, %s\n", second_instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in3_reg]);
}
clear_fp_reg(cur_time, in1_reg);
set_var_to_fp_reg(cur_time, var, in1_reg);
};
auto cmp_op = [this, var, op, in1, cur_time](const char *cc) {
SSAVar *cmp2 = op->in_vars[1];
SSAVar *val1 = op->in_vars[2];
SSAVar *val2 = op->in_vars[3];
assert(is_float(in1->type) && in1->type == cmp2->type && val1->type == Type::imm && val2->type == Type::imm);
FP_REGISTER cmp1_reg = load_val_in_fp_reg(cur_time, in1);
FP_REGISTER cmp2_reg = load_val_in_fp_reg(cur_time, cmp2);
REGISTER val1_reg = load_val_in_reg(cur_time, val1);
REGISTER val2_reg = load_val_in_reg(cur_time, val2);
if (val1->gen_info.last_use_time > cur_time) {
save_reg(val1_reg);
}
print_asm("comis%s %s, %s\n", Generator::fp_op_size_from_type(in1->type), fp_reg_names[cmp1_reg], fp_reg_names[cmp2_reg]);
print_asm("cmov%s %s, %s\n", cc, reg_name(val1_reg, var->type), reg_name(val2_reg, var->type));
clear_reg(cur_time, val1_reg);
set_var_to_reg(cur_time, var, val1_reg);
};
switch (op->type) {
case Instruction::min:
bin_op("mins");
break;
case Instruction::max:
bin_op("maxs");
break;
case Instruction::add:
bin_op("adds");
break;
case Instruction::sub:
bin_op("subs");
break;
case Instruction::fmul:
bin_op("muls");
break;
case Instruction::fdiv:
bin_op("divs");
break;
case Instruction::fmadd:
fma_op("vfmadd213s", "adds");
break;
case Instruction::fmsub:
fma_op("vfmsub213s", "subs");
break;
case Instruction::fnmadd:
fma_op("vfnmadd213s", "adds", true);
break;
case Instruction::fnmsub:
fma_op("vfnmsub213s", "subs", true);
break;
case Instruction::fsqrt: {
assert(is_float(var->type) && var->type == in1->type);
const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, in1);
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
print_asm("sqrts%s %s, %s\n", Generator::fp_op_size_from_type(var->type), fp_reg_names[dest_reg], fp_reg_names[in1_reg]);
clear_fp_reg(cur_time, dest_reg);
set_var_to_fp_reg(cur_time, var, dest_reg);
break;
}
case Instruction::slt:
cmp_op("ae");
break;
case Instruction::sle:
cmp_op("a");
break;
case Instruction::seq:
cmp_op("ne");
break;
case Instruction::load: {
assert(in1->type == Type::i64 || in1->type == Type::imm);
const REGISTER addr_reg = load_val_in_reg(cur_time, in1);
if (in1->gen_info.last_use_time > cur_time) {
save_reg(addr_reg);
}
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
print_asm("mov%s %s, [%s]\n", (var->type == Type::f32 ? "d" : "q"), fp_reg_names[dest_reg], reg_names[addr_reg][0]);
set_var_to_fp_reg(cur_time, var, dest_reg);
break;
}
case Instruction::store: {
auto *val = op->in_vars[1].get();
assert(in1->type == Type::imm || in1->type == Type::i64);
assert(is_float(val->type));
const REGISTER addr_reg = load_val_in_reg(cur_time, in1);
const FP_REGISTER val_reg = load_val_in_fp_reg(cur_time, val);
print_asm("mov%s [%s], %s\n", (val->type == Type::f32 ? "d" : "q"), reg_names[addr_reg][0], fp_reg_names[val_reg]);
break;
}
case Instruction::zero_extend:
assert(is_float(var->type) && is_float(in1->type));
[[fallthrough]];
case Instruction::cast: {
assert(is_float(var->type) || is_float(in1->type));
if (is_float(in1->type)) {
if (is_float(var->type)) {
const FP_REGISTER dst_reg = load_val_in_fp_reg(cur_time, in1);
if (in1->gen_info.last_use_time > cur_time) {
save_fp_reg(dst_reg);
}
clear_fp_reg(cur_time, dst_reg);
set_var_to_fp_reg(cur_time, var, dst_reg);
} else {
const FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1);
const REGISTER dest_reg = alloc_reg(cur_time);
print_asm("mov%s %s, %s\n", (in1->type == Type::f32 ? "d" : "q"), reg_name(dest_reg, var->type), fp_reg_names[in_reg]);
set_var_to_reg(cur_time, var, dest_reg);
}
} else {
const REGISTER in_reg = load_val_in_reg(cur_time, in1);
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
print_asm("mov%s %s, %s\n", (var->type == Type::f32 ? "d" : "q"), fp_reg_names[dest_reg], reg_name(in_reg, in1->type));
set_var_to_fp_reg(cur_time, var, dest_reg);
}
break;
}
case Instruction::convert: {
assert(is_float(var->type) || is_float(in1->type));
// evalute convert names
const char *conv_name_1 = Generator::convert_name_from_type(in1->type);
const char *conv_name_2 = Generator::convert_name_from_type(var->type);
if (is_float(in1->type)) {
FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1);
// floating point -> integer
if (is_float(var->type)) {
// floating point -> floating point
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
compile_rounding_mode(cur_time, op, alloc_reg(cur_time));
print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, fp_reg_names[dest_reg], fp_reg_names[in_reg]);
set_var_to_fp_reg(cur_time, var, dest_reg);
break;
} else {
const REGISTER dest_reg = alloc_reg(cur_time);
in_reg = compile_rounding_mode(cur_time, op, dest_reg, true, in_reg);
// compile_rounding_mode(cur_time, op, dest_reg);
print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, reg_name(dest_reg, var->type), fp_reg_names[in_reg]);
set_var_to_reg(cur_time, var, dest_reg);
}
} else {
// integer -> floating point
compile_rounding_mode(cur_time, op, alloc_reg(cur_time));
const REGISTER in_reg = load_val_in_reg(cur_time, in1);
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, fp_reg_names[dest_reg], reg_name(in_reg, in1->type));
set_var_to_fp_reg(cur_time, var, dest_reg);
}
break;
}
case Instruction::uconvert: {
assert(is_float(in1->type) ^ is_float(var->type));
compile_rounding_mode(cur_time, op, alloc_reg(cur_time));
const char *conv_name_1 = Generator::convert_name_from_type(in1->type);
const char *conv_name_2 = Generator::convert_name_from_type(var->type);
if (is_float(in1->type)) {
// floating point -> unsigned integer
assert(var->type == Type::i32 || var->type == Type::i64);
const FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1);
const REGISTER dest_reg = alloc_reg(cur_time);
const bool single_precision = in1->type == Type::f32;
const char *dest_reg_name = reg_name(dest_reg, var->type);
print_asm("cvt%s2si %s, %s\n", conv_name_1, dest_reg_name, fp_reg_names[in_reg]);
print_asm("mov%s %s, %s\n", (single_precision ? "d" : "q"), (single_precision ? "ebp" : "rbp"), fp_reg_names[in_reg]);
print_asm("sar rbp, %d\n", (single_precision ? 31 : 63));
if (var->type == Type::i64 && single_precision) {
print_asm("movsxd rbp, ebp\n");
}
print_asm("not rbp\n");
print_asm("and %s, %s\n", dest_reg_name, (var->type == Type::i32 ? "ebp" : "rbp"));
print_asm("xor rbp, rbp\n");
set_var_to_reg(cur_time, var, dest_reg);
} else {
// unsigned integer -> floating point
assert(in1->type == Type::i32 || in1->type == Type::i64);
const REGISTER in_reg = load_val_in_reg(cur_time, in1);
const FP_REGISTER dest_reg = alloc_fp_reg(cur_time);
const REGISTER help_reg = alloc_reg(cur_time, REG_NONE, in_reg);
if (in1->type == Type::i32) {
// "zero extend" and then convert: use 64bit register
print_asm("mov %s, %s\n", reg_names[in_reg][1], reg_names[in_reg][1]);
print_asm("cvt%s2%s %s, %s\n", Generator::convert_name_from_type(Type::i64), conv_name_2, fp_reg_names[dest_reg], reg_names[in_reg][0]);
} else if (in1->type == Type::i64) {
// method taken from gcc compiler
const char *in_reg_name = reg_names[in_reg][0], *help_reg_name = reg_names[help_reg][0], *dest_reg_name = fp_reg_names[dest_reg];
// test if msb is set: if set, then handle else use normal (signed) convert
print_asm("test %s, %s\n", in_reg_name, in_reg_name);
print_asm("js 0f\n");
print_asm("cvtsi2%s %s, %s\n", conv_name_2, dest_reg_name, in_reg_name);
print_asm("jmp 2f\n");
print_asm("0:\n");
// test for edge case
print_asm("mov %s, -1\n", help_reg_name);
print_asm("cmp %s, %s\n", in_reg_name, help_reg_name);
print_asm("je 1f\n");
// use gcc method to convert unsigned values
print_asm("mov %s, %s\n", help_reg_name, in_reg_name);
print_asm("shr %s, 1\n", help_reg_name);
print_asm("and %s, 1\n", reg_name(in_reg, Type::i32));
print_asm("or %s, %s\n", in_reg_name, help_reg_name);
print_asm("cvtsi2%s %s, %s\n", conv_name_2, dest_reg_name, in_reg_name);
print_asm("adds%s %s, %s\n", Generator::fp_op_size_from_type(var->type), dest_reg_name, dest_reg_name);
print_asm("jmp 2f\n");
print_asm("1:\n");
// handle edge case
if (var->type == Type::f32) {
print_asm("mov %s, 0x5f800000\n", reg_name(help_reg, Type::i32));
print_asm("movd %s, %s\n", dest_reg_name, reg_name(help_reg, Type::i32));
} else {
print_asm("mov %s, 0x43F0000000000000\n", help_reg_name);
print_asm("movq %s, %s\n", dest_reg_name, help_reg_name);
}
print_asm("2:\n");
}
set_var_to_fp_reg(cur_time, var, dest_reg);
}
break;
}
default:
fprintf(stderr, "Encountered a unknown floating point instruction in the generator!\n");
assert(0);
break;
}
}
bool RegAlloc::merge_op_bin(size_t cur_time, size_t var_idx, REGISTER dst_reg) {
// we know the current var has an operation and two inputs which are both in registers
auto *op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx]->info).get();
auto *dst = op->out_vars[0];
auto *in1 = op->in_vars[0].get();
auto *in2 = op->in_vars[1].get();
// check if optimizations are enabled and we can merge anything
if (!(gen->optimizations & Generator::OPT_MERGE_OP) || cur_bb->variables.size() <= var_idx + 1 || !dst || dst->ref_count > 1) {
return false;
}
// add,load or add,(cast),store
if (op->type == Instruction::add) {
const auto try_merge_add = [this, var_idx, dst, dst_reg, in1, in2, cur_time]() -> bool {
auto *next_var = cur_bb->variables[var_idx + 1].get();
if (!std::holds_alternative<std::unique_ptr<Operation>>(next_var->info))
return false;
auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get();
if (is_float(next_var->type) || is_float(next_op->lifter_info.in_op_size)) {
return false;
}
if (next_op->type == Instruction::load) {
if (next_op->in_vars[0] != dst) {
return false;
}
assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate()));
const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0];
const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0];
// check if there is a zero/sign-extend afterwards
auto *load_dst = next_op->out_vars[0];
if (load_dst->ref_count == 1 && cur_bb->variables.size() > var_idx + 2) {
if (std::holds_alternative<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info)) {
auto *ext_op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info).get();
auto *ext_dst = ext_op->out_vars[0];
if (ext_op->in_vars[0] == load_dst) {
if (ext_op->type == Instruction::zero_extend) {
if (load_dst->type == Type::i32) {
print_asm("mov %s, [%s + %s]\n", reg_names[dst_reg][1], in1_reg_name, in2_reg_name);
} else {
print_asm("movzx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, in2_reg_name);
}
} else if (ext_op->type == Instruction::sign_extend) {
if (load_dst->type == Type::i32) {
assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64);
print_asm("movsxd %s, DWORD PTR [%s + %s]\n", reg_name(dst_reg, ext_dst->type), in1_reg_name, in2_reg_name);
} else {
print_asm("movsx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, in2_reg_name);
}
}
if (ext_op->type == Instruction::zero_extend || ext_op->type == Instruction::sign_extend) {
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, ext_dst, dst_reg);
load_dst->gen_info.already_generated = true;
ext_dst->gen_info.already_generated = true;
return true;
}
}
}
}
// no extension
print_asm("mov %s, [%s + %s]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, in2_reg_name);
clear_reg(cur_time, dst_reg);
set_var_to_reg(cur_time, load_dst, dst_reg);
load_dst->gen_info.already_generated = true;
return true;
} else if (next_op->type == Instruction::store) {
// add,store
auto *addr_src = next_op->in_vars[0].get();
auto *val_src = next_op->in_vars[1].get();
if (addr_src != dst) {
return false;
}
assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate()));
const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0];
const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0];
if (val_src->is_immediate() && !val_src->get_immediate().binary_relative) {
const auto store_imm_val = val_src->get_immediate().val;
if (store_imm_val != INT64_MIN && std::abs(store_imm_val) < 0x7FFFFFFF) {
print_asm("mov %s [%s + %s], %ld\n", mem_size(next_op->lifter_info.in_op_size), in1_reg_name, in2_reg_name, store_imm_val);
next_op->out_vars[0]->gen_info.already_generated = true;
return true;
}
}
const auto val_reg = load_val_in_reg(cur_time, val_src);
print_asm("mov [%s + %s], %s\n", in1_reg_name, in2_reg_name, reg_name(val_reg, next_op->lifter_info.in_op_size));
next_op->out_vars[0]->gen_info.already_generated = true;
return true;
} else if (next_op->type == Instruction::cast) {
// add,cast,store
auto *cast_var = next_op->out_vars[0];
if (cast_var->ref_count != 1 || cur_bb->variables.size() <= var_idx + 2) {
return false;
}
if (!std::holds_alternative<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info)) {
return false;
}
auto *store_op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info).get();
if (store_op->type != Instruction::store || store_op->in_vars[0] != dst || store_op->in_vars[1] != cast_var) {
return false;
}
assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate()));
const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0];
const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0];
const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get());
print_asm("mov [%s + %s], %s\n", in1_reg_name, in2_reg_name, reg_name(cast_reg, cast_var->type));
store_op->out_vars[0]->gen_info.already_generated = true;
cast_var->gen_info.already_generated = true;
return true;
}
return false;
};
return try_merge_add();
}
return false;
}
FP_REGISTER RegAlloc::compile_rounding_mode(size_t cur_time, const Operation *op, const REGISTER help_reg, const bool use_rounds, const FP_REGISTER fp_in_reg) {
if (std::holds_alternative<RoundingMode>(op->rounding_info)) {
const RoundingMode rounding_mode = std::get<RoundingMode>(op->rounding_info);
SSAVar *in1 = op->in_vars[0];
if (use_rounds && gen->optimizations & Generator::OPT_ARCH_SSE4) {
const char *x86_64_rounding_mode;
switch (rounding_mode) {
case RoundingMode::NEAREST:
x86_64_rounding_mode = "0b00";
break;
case RoundingMode::DOWN:
x86_64_rounding_mode = "0b01";
break;
case RoundingMode::UP:
x86_64_rounding_mode = "0b10";
break;
case RoundingMode::ZERO:
x86_64_rounding_mode = "0b11";
break;
default:
assert(0);
break;
}
const FP_REGISTER help_fp_reg = alloc_fp_reg(cur_time);
assert(fp_in_reg != FP_REG_NONE);
print_asm("rounds%s %s, %s, %s\n", Generator::fp_op_size_from_type(in1->type), fp_reg_names[help_fp_reg], fp_reg_names[fp_in_reg], x86_64_rounding_mode);
return help_fp_reg;
} else {
uint32_t x86_64_rounding_mode;
switch (std::get<RoundingMode>(op->rounding_info)) {
case RoundingMode::NEAREST:
x86_64_rounding_mode = 0x0000;
break;
case RoundingMode::DOWN:
x86_64_rounding_mode = 0x2000;
break;
case RoundingMode::UP:
x86_64_rounding_mode = 0x4000;
break;
case RoundingMode::ZERO:
x86_64_rounding_mode = 0x6000;
break;
default:
assert(0);
break;
}
// use dest_reg to set mxcsr
const char *round_reg_name = reg_name(help_reg, Type::i32);
print_asm("sub rsp, 4\n");
print_asm("stmxcsr [rsp]\n");
print_asm("mov %s, [rsp]\n", round_reg_name);
print_asm("and %s, 0xFFFF1FFF\n", round_reg_name);
if (x86_64_rounding_mode != 0) {
print_asm("or %s, %d\n", round_reg_name, x86_64_rounding_mode);
}
print_asm("mov [rsp], %s\n", round_reg_name);
print_asm("ldmxcsr [rsp]\n");
print_asm("add rsp, 4\n");
return fp_in_reg;
}
} else if (std::holds_alternative<RefPtr<SSAVar>>(op->rounding_info)) {
// let helper handle dynamic rounding
SSAVar *rm_var = std::get<RefPtr<SSAVar>>(op->rounding_info).get();
const REGISTER reg = load_val_in_reg(cur_time, rm_var, REG_DI);
if (rm_var->gen_info.last_use_time > cur_time) {
save_reg(REG_DI);
}
assert(reg == REG_DI);
clear_reg(cur_time, REG_DI);
// TODO: Stack alignment?
print_asm("push rax\npush rcx\npush rdx\npush rsi\n");
print_asm("call resolve_dynamic_rounding\n");
print_asm("pop rsi\npop rdx\npop rcx\npop rax\n");
return fp_in_reg;
}
return FP_REG_NONE;
}
void RegAlloc::prepare_cf_ops(BasicBlock *bb) {
// just set the input maps when the cf-op targets do not yet have a input mapping
for (auto &cf_op : bb->control_flow_ops) {
auto *target = cf_op.target();
if (!target || target->gen_info.input_map_setup) {
continue;
}
if (target->gen_info.call_cont_block) {
set_bb_inputs_from_static(target);
continue;
}
switch (cf_op.type) {
case CFCInstruction::jump:
set_bb_inputs(target, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs);
break;
case CFCInstruction::cjump:
set_bb_inputs(target, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
break;
case CFCInstruction::syscall:
// TODO: we don't need this, just need to respect the clobbered registers from a syscall
set_bb_inputs_from_static(target);
break;
case CFCInstruction::call: {
set_bb_inputs_from_static(target);
auto *cont_block = std::get<CfOp::CallInfo>(cf_op.info).continuation_block;
if (!cont_block->gen_info.input_map_setup) {
set_bb_inputs_from_static(cont_block);
}
break;
}
default:
break;
}
}
}
void RegAlloc::compile_cf_ops(BasicBlock *bb, RegMap ®_map, FPRegMap &fp_reg_map, StackMap &stack_map, size_t max_stack_frame_size, BasicBlock *next_bb,
std::vector<BasicBlock *> &compiled_blocks) {
// TODO: when there is one cfop and it's a jump we can already omit the jmp bX_reg_alloc if the block isn't compiled yet
// since it will get compiled straight after
auto reg_map_bak = reg_map;
auto fp_reg_map_bak = fp_reg_map;
auto stack_map_bak = stack_map;
std::vector<SSAVar::GeneratorInfoX64> gen_infos;
for (auto &var : bb->variables) {
gen_infos.emplace_back(var->gen_info);
}
for (size_t cf_idx = 0; cf_idx < bb->control_flow_ops.size(); ++cf_idx) {
auto cur_time = bb->variables.size();
// clear allocations from previous cfop since they dont exist here
// clear_after_alloc_time(cur_time);
if (cf_idx != 0) {
reg_map = reg_map_bak;
fp_reg_map = fp_reg_map_bak;
stack_map = stack_map_bak;
for (size_t i = 0; i < bb->variables.size(); ++i) {
bb->variables[i]->gen_info = gen_infos[i];
}
}
const auto &cf_op = bb->control_flow_ops[cf_idx];
print_asm("b%zu_reg_alloc_cf%zu:\n", bb->id, cf_idx);
auto target_top_level = false;
if (auto *target = cf_op.target(); target != nullptr) {
target_top_level = is_block_top_level(target);
}
auto cjump_asm = std::string{};
if (cf_op.type == CFCInstruction::cjump) {
auto *cmp1 = cf_op.in_vars[0].get();
auto *cmp2 = cf_op.in_vars[1].get();
assert(!is_float(cmp1->type));
assert(!is_float(cmp2->type));
const auto cmp1_reg = load_val_in_reg(cur_time, cmp1);
const auto type = choose_type(cmp1, cmp2);
if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && static_cast<uint64_t>(cmp2->get_immediate().val) != 0x80000000'00000000 &&
std::abs(cmp2->get_immediate().val) <= 0x7FFFFFFF) {
// TODO: only 32bit immediates which are safe to sign extend
print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val);
} else {
const auto cmp2_reg = load_val_in_reg(cur_time, cmp2);
print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type));
}
gen_infos.clear();
reg_map_bak = reg_map;
fp_reg_map_bak = fp_reg_map;
stack_map_bak = stack_map;
for (auto &var : bb->variables) {
gen_infos.emplace_back(var->gen_info);
}
/*std::swap(cjump_asm, asm_buf);
write_target_inputs(cf_op.target(), cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
std::swap(cjump_asm, asm_buf);
if (!target_top_level && cjump_asm.empty() && std::find(compiled_blocks.begin(), compiled_blocks.end(), cf_op.target()) != compiled_blocks.end()) {
// generate a direct jump
switch (std::get<CfOp::CJumpInfo>(cf_op.info).type) {
case CfOp::CJumpInfo::CJumpType::eq:
print_asm("je ");
break;
case CfOp::CJumpInfo::CJumpType::neq:
print_asm("jne ");
break;
case CfOp::CJumpInfo::CJumpType::lt:
print_asm("jb ");
break;
case CfOp::CJumpInfo::CJumpType::gt:
print_asm("ja ");
break;
case CfOp::CJumpInfo::CJumpType::slt:
print_asm("jl ");
break;
case CfOp::CJumpInfo::CJumpType::sgt:
print_asm("jg ");
break;
}
print_asm("b%zu_reg_alloc\n", cf_op.target()->id);
continue;
}*/
switch (std::get<CfOp::CJumpInfo>(cf_op.info).type) {
case CfOp::CJumpInfo::CJumpType::eq:
print_asm("jne");
break;
case CfOp::CJumpInfo::CJumpType::neq:
print_asm("je");
break;
case CfOp::CJumpInfo::CJumpType::lt:
print_asm("jae");
break;
case CfOp::CJumpInfo::CJumpType::gt:
print_asm("jbe");
break;
case CfOp::CJumpInfo::CJumpType::slt:
print_asm("jge");
break;
case CfOp::CJumpInfo::CJumpType::sgt:
print_asm("jle");
break;
}
print_asm(" b%zu_reg_alloc_cf%zu\n", bb->id, cf_idx + 1);
}
switch (cf_op.type) {
case CFCInstruction::jump: {
auto *target = std::get<CfOp::JumpInfo>(cf_op.info).target;
const auto out_of_group = std::find(compiled_blocks.begin(), compiled_blocks.end(), target) == compiled_blocks.end();
if (out_of_group && !target_top_level) {
if (!target->gen_info.compiled) {
target->gen_info.needs_trans_bb = true;
// TODO: this can be fixed with the assembler by compiling all cfops at the end and holding trans bbs until the end before throwing out unneeded ones
auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{};
for (size_t i = 0; i < target->inputs.size(); ++i) {
static_mapping.emplace_back(std::get<CfOp::JumpInfo>(cf_op.info).target_inputs[i], std::get<size_t>(target->inputs[i]->info));
}
write_static_mapping(target, cur_time, static_mapping);
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("jmp b%zu\n", target->id);
break;
}
if (target->gen_info.max_stack_size > max_stack_frame_size) {
const size_t delta = target->gen_info.max_stack_size - max_stack_frame_size;
print_asm("sub rsp, %zu\n", delta);
for (auto &var : bb->variables) {
if (var->gen_info.saved_in_stack) {
var->gen_info.stack_slot += delta / 8;
}
}
for (size_t i = 0; i < (delta / 8); ++i) {
stack_map.insert(stack_map.begin(), StackSlot{});
}
write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs);
} else {
const size_t delta = max_stack_frame_size - target->gen_info.max_stack_size;
for (auto &input : target->gen_info.input_map) {
if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) {
input.stack_slot += delta / 8;
}
}
write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs);
for (auto &input : target->gen_info.input_map) {
if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) {
input.stack_slot -= delta / 8;
}
}
print_asm("add rsp, %zu\n", delta);
}
} else {
write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs);
}
if (target_top_level) {
print_asm("# destroy stack space\n");
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("jmp b%zu\n", target->id);
} else {
if (cf_idx != bb->control_flow_ops.size() - 1 || target != next_bb) {
print_asm("jmp b%zu_reg_alloc\n", target->id);
}
}
break;
}
case CFCInstruction::cjump: {
auto *target = std::get<CfOp::CJumpInfo>(cf_op.info).target;
// asm_buf += cjump_asm;
const auto out_of_group = std::find(compiled_blocks.begin(), compiled_blocks.end(), target) == compiled_blocks.end();
if (out_of_group && !target_top_level) {
if (!target->gen_info.compiled) {
target->gen_info.needs_trans_bb = true;
// TODO: this can be fixed with the assembler by compiling all cfops at the end and holding trans bbs until the end before throwing out unneeded ones
auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{};
for (size_t i = 0; i < target->inputs.size(); ++i) {
static_mapping.emplace_back(std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs[i], std::get<size_t>(target->inputs[i]->info));
}
write_static_mapping(target, cur_time, static_mapping);
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("jmp b%zu\n", target->id);
break;
}
if (target->gen_info.max_stack_size > max_stack_frame_size) {
const size_t delta = target->gen_info.max_stack_size - max_stack_frame_size;
print_asm("sub rsp, %zu\n", delta);
for (auto &var : bb->variables) {
if (var->gen_info.saved_in_stack) {
var->gen_info.stack_slot += delta / 8;
}
}
for (size_t i = 0; i < (delta / 8); ++i) {
stack_map.insert(stack_map.begin(), StackSlot{});
}
write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
} else {
const size_t delta = max_stack_frame_size - target->gen_info.max_stack_size;
for (auto &input : target->gen_info.input_map) {
if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) {
input.stack_slot += delta / 8;
}
}
write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
for (auto &input : target->gen_info.input_map) {
if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) {
input.stack_slot -= delta / 8;
}
}
print_asm("add rsp, %zu\n", delta);
}
} else {
write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
}
if (target_top_level) {
print_asm("# destroy stack space\n");
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("jmp b%zu\n", target->id);
} else {
print_asm("jmp b%zu_reg_alloc\n", target->id);
}
break;
}
case CFCInstruction::unreachable: {
gen->err_msgs.emplace_back(Generator::ErrType::unreachable, bb);
print_asm("lea rdi, [rip + err_unreachable_b%zu]\n", bb->id);
print_asm("jmp panic\n");
break;
}
case CFCInstruction::ijump: {
const auto &info = std::get<CfOp::IJumpInfo>(cf_op.info);
write_static_mapping((info.targets.empty() ? nullptr : info.targets[0]), cur_time, info.mapping);
// TODO: we get a problem if the dst is in a static that has already been written out (so overwritten)
auto *dst = cf_op.in_vars[0].get();
load_val_in_reg(cur_time + 1 + info.mapping.size(), dst, REG_B);
assert(dst->type == Type::imm || dst->type == Type::i64);
print_asm("# destroy stack space\n");
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("jmp ijump_lookup\n");
break;
}
case CFCInstruction::syscall: {
// TODO: allocate over inlined syscall or syscall helper call
// TODO: inline syscalls if they are just passthrough
const auto &info = std::get<CfOp::SyscallInfo>(cf_op.info);
write_static_mapping(info.continuation_block, cur_time, info.continuation_mapping);
// cur_time += 1 + info.continuation_mapping.size();
for (size_t i = 0; i < call_reg.size(); ++i) {
auto *var = cf_op.in_vars[i].get();
if (var == nullptr)
break;
if (var->type == Type::mt)
continue;
const auto reg = call_reg[i];
if (reg_map[reg].cur_var && reg_map[reg].cur_var->gen_info.last_use_time >= cur_time) {
save_reg(reg);
}
load_val_in_reg(cur_time, var, call_reg[i]);
}
if (cf_op.in_vars[6] == nullptr) {
print_asm("sub rsp, 16\n");
} else {
// TODO: clear rax before when we have inputs < 64 bit
if (reg_map[REG_A].cur_var && reg_map[REG_A].cur_var->gen_info.last_use_time >= cur_time) {
save_reg(REG_A);
}
load_val_in_reg(cur_time, cf_op.in_vars[6].get(), REG_A);
print_asm("sub rsp, 8\n");
print_asm("push rax\n");
}
print_asm("call syscall_impl\n");
if (info.static_mapping.size() > 0) {
print_asm("mov [s%zu], rax\n", info.static_mapping.at(0));
}
print_asm("# destroy stack space\n");
if (is_block_top_level(info.continuation_block)) {
print_asm("add rsp, %zu\n", max_stack_frame_size + 16);
} else {
print_asm("add rsp, 16\n");
}
// need to jump to translation block
// TODO: technically we don't need to if the block didn't have a input mapping before
// so only do that when the next block does have an input mapping or more than one predecessor?
print_asm("jmp b%zu%s\n", info.continuation_block->id, is_block_top_level(info.continuation_block) ? "" : "_reg_alloc");
break;
}
case CFCInstruction::call: {
auto &info = std::get<CfOp::CallInfo>(cf_op.info);
// write_target_inputs(info.target, cur_time, info.target_inputs);
auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{};
for (size_t i = 0; i < info.target->inputs.size(); ++i) {
static_mapping.emplace_back(std::get<CfOp::CallInfo>(cf_op.info).target_inputs[i], std::get<size_t>(info.target->inputs[i]->info));
}
write_static_mapping(info.target, cur_time, static_mapping);
// prevent overflow
print_asm("mov rax, [init_ret_stack_ptr]\n");
print_asm("lea rax, [rax - %zu]\n", max_stack_frame_size);
print_asm("cmp rsp, stack_space + 524288\n"); // max depth ~65k
print_asm("cmovb rsp, rax\n");
if (info.continuation_block->virt_start_addr <= 0x7FFFFFFF) {
print_asm("push %lu\n", info.continuation_block->virt_start_addr);
} else {
print_asm("mov rax, %lu\n", info.continuation_block->virt_start_addr);
print_asm("push rax\n");
}
print_asm("call b%zu\n", info.target->id);
if (bb->control_flow_ops.size() != 1 || info.continuation_block != next_bb || is_block_top_level(info.continuation_block)) {
if (is_block_top_level(info.continuation_block) || std::find(compiled_blocks.begin(), compiled_blocks.end(), info.continuation_block) == compiled_blocks.end()) {
print_asm("add rsp, %zu\n", max_stack_frame_size + 8);
print_asm("jmp b%zu\n", info.continuation_block->id);
} else {
print_asm("add rsp, 8\n");
print_asm("jmp b%zu_reg_alloc\n", info.continuation_block->id);
}
} else {
print_asm("add rsp, 8\n");
}
break;
}
case CFCInstruction::_return: {
write_static_mapping(nullptr, cur_time, std::get<CfOp::RetInfo>(cf_op.info).mapping);
// TODO: write out ret addr last and keep it in reg
const auto ret_reg = load_val_in_reg(cur_time + std::get<CfOp::RetInfo>(cf_op.info).mapping.size(), cf_op.in_vars[0]);
const auto dst_reg_name = reg_names[ret_reg][0];
print_asm("# destroy stack space\n");
print_asm("add rsp, %zu\n", max_stack_frame_size);
print_asm("cmp [rsp + 8], %s\n", dst_reg_name);
print_asm("jnz 0f\n");
print_asm("ret\n");
print_asm("0:\n");
// reset ret stack
print_asm("mov rsp, [init_ret_stack_ptr]\n");
// do ijump
print_asm("mov rbx, %s\n", dst_reg_name);
print_asm("jmp ijump_lookup\n");
break;
}
case CFCInstruction::icall: {
const auto &info = std::get<CfOp::ICallInfo>(cf_op.info);
write_static_mapping((info.targets.empty() ? nullptr : info.targets[0]), cur_time, info.mapping);
// TODO: we get a problem if the dst is in a static that has already been written out (so overwritten)
auto *dst = cf_op.in_vars[0].get();
const auto dst_reg = load_val_in_reg(cur_time + 1 + info.mapping.size(), dst, REG_B);
assert(dst->type == Type::imm || dst->type == Type::i64);
const auto overflow_reg = alloc_reg(cur_time + 1 + info.mapping.size(), REG_NONE, dst_reg);
const auto of_reg_name = reg_names[overflow_reg][0];
// prevent overflow
print_asm("mov %s, [init_ret_stack_ptr]\n", of_reg_name);
print_asm("lea %s, [%s - %zu]\n", of_reg_name, of_reg_name, max_stack_frame_size);
print_asm("cmp rsp, stack_space + 524288\n"); // max depth ~65k
print_asm("cmovb rsp, %s\n", of_reg_name);
if (info.continuation_block->virt_start_addr <= 0x7FFFFFFF) {
print_asm("push %lu\n", info.continuation_block->virt_start_addr);
} else {
const auto tmp_reg = alloc_reg(cur_time + 1 + info.mapping.size());
print_asm("mov %s, %lu\n", reg_names[tmp_reg][0], info.continuation_block->virt_start_addr);
print_asm("push %s\n", reg_names[tmp_reg][0]);
}
print_asm("call ijump_lookup\n");
if (bb->control_flow_ops.size() != 1 || info.continuation_block != next_bb || is_block_top_level(info.continuation_block)) {
if (is_block_top_level(info.continuation_block) || std::find(compiled_blocks.begin(), compiled_blocks.end(), info.continuation_block) == compiled_blocks.end()) {
print_asm("add rsp, %zu\n", max_stack_frame_size + 8);
print_asm("jmp b%zu\n", info.continuation_block->id);
} else {
print_asm("add rsp, 8\n");
print_asm("jmp b%zu_reg_alloc\n", info.continuation_block->id);
}
} else {
print_asm("add rsp, 8\n");
}
break;
}
default: {
assert(0);
exit(1);
}
}
}
}
void RegAlloc::write_assembled_blocks(size_t max_stack_frame_size, std::vector<BasicBlock *> &compiled_blocks) {
for (size_t i = 0; i < assembled_blocks.size(); ++i) {
auto &block = assembled_blocks[i];
fprintf(gen->out_fd, "%s\n", block.assembly.c_str());
asm_buf.clear();
cur_bb = block.bb;
cur_reg_map = &block.reg_map;
cur_fp_reg_map = &block.fp_reg_map;
cur_stack_map = &block.stack_map;
auto *next_bb = (i + 1 >= assembled_blocks.size()) ? nullptr : assembled_blocks[i + 1].bb;
compile_cf_ops(block.bb, block.reg_map, block.fp_reg_map, block.stack_map, max_stack_frame_size, next_bb, compiled_blocks);
fprintf(gen->out_fd, "%s\n", asm_buf.c_str());
}
cur_bb = nullptr;
cur_reg_map = nullptr;
cur_fp_reg_map = nullptr;
cur_stack_map = nullptr;
}
void RegAlloc::generate_translation_block(BasicBlock *bb) {
std::string tmp_buf = {};
std::swap(tmp_buf, asm_buf);
bool rax_input = false;
size_t rax_static = 0;
for (size_t i = 0; i < bb->inputs.size(); ++i) {
auto *var = bb->inputs[i];
if (var->type == Type::mt) {
continue;
}
const auto &input_info = bb->gen_info.input_map[i];
// only allow static inputs for now
assert(std::holds_alternative<size_t>(var->info));
const auto src_static = std::get<size_t>(var->info);
switch (input_info.location) {
case BasicBlock::GeneratorInfo::InputInfo::REGISTER:
if (input_info.reg_idx == REG_A) {
rax_input = true;
rax_static = src_static;
break;
}
print_asm("mov %s, [s%zu]\n", reg_names[input_info.reg_idx][0], src_static);
break;
case BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER:
print_asm("movq %s, [s%zu]\n", fp_reg_names[input_info.reg_idx], src_static);
break;
case BasicBlock::GeneratorInfo::InputInfo::STACK:
print_asm("mov rax, [s%zu]\n", src_static);
print_asm("mov [rsp + 8 * %zu], rax\n", input_info.stack_slot);
break;
case BasicBlock::GeneratorInfo::InputInfo::STATIC:
if (input_info.static_idx != src_static) {
// TODO: this can break when two statics are swapped
print_asm("mov rax, [s%zu]\n", src_static);
print_asm("mov [s%zu], rax\n", input_info.static_idx);
}
break;
default:
// other cases shouldn't happen
assert(0);
exit(1);
}
}
if (rax_input) {
print_asm("mov rax, [s%zu]\n", rax_static);
}
print_asm("jmp b%zu_reg_alloc\n", bb->id);
std::swap(tmp_buf, asm_buf);
translation_blocks.push_back(std::make_pair(bb->id, std::move(tmp_buf)));
}
void RegAlloc::set_bb_inputs(BasicBlock *target, const std::vector<RefPtr<SSAVar>> &inputs) {
// TODO: when there are multiple blocks that follow only generate an input mapping once
auto ®_map = *cur_reg_map;
auto &fp_reg_map = *cur_fp_reg_map;
const auto cur_time = cur_bb->variables.size();
// fix for immediate inputs
for (size_t i = 0; i < inputs.size(); ++i) {
auto *input_var = inputs[i].get();
if (input_var->type == Type::mt) {
continue;
}
if (input_var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED) {
continue;
}
assert(input_var->is_immediate());
load_val_in_reg<false>(cur_time, input_var);
}
assert(target->inputs.size() == inputs.size());
if (target->id > BB_MERGE_TIL_ID || is_block_top_level(target)) {
// cheap fix to force single block register allocation
set_bb_inputs_from_static(target);
} else {
for (size_t i = 0; i < inputs.size(); ++i) {
auto *input = inputs[i].get();
input->gen_info.allocated_to_input = false;
if (input->is_static() && input->gen_info.location == SSAVar::GeneratorInfoX64::STATIC && input->gen_info.static_idx != target->inputs[i]->get_static()) {
// force into register because translation blocks might generate incorrect code otherwise
load_val_in_reg<false>(cur_time, input);
}
}
bool rax_used = false, xmm0_used = false;
SSAVar *rax_input, *xmm0_input;
// just write input locations, compile the input map and we done
for (size_t i = 0; i < inputs.size(); ++i) {
auto *input_var = inputs[i].get();
auto *target_var = target->inputs[i];
if (input_var->type == Type::mt) {
continue;
}
if (input_var->gen_info.allocated_to_input) {
// this var was already used as an input so we need to create a new location to store it
// since there might be a different predecessor that stores it somewhere else
const auto stack_slot = allocate_stack_slot(input_var);
target_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
target_var->gen_info.saved_in_stack = true;
target_var->gen_info.stack_slot = stack_slot;
// move var to stack slot
if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) {
print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_names[input_var->gen_info.reg_idx][0]);
} else if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) {
print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[input_var->gen_info.reg_idx]);
} else if (is_float(input_var->type)) {
FP_REGISTER reg = FP_REG_NONE;
// find free/unused register
for (size_t i = 0; i < FP_REG_COUNT; ++i) {
if (fp_reg_map[i].cur_var == nullptr || fp_reg_map[i].cur_var->gen_info.last_use_time < cur_time) {
reg = static_cast<FP_REGISTER>(i);
break;
}
}
if (reg == FP_REG_NONE) {
// use xmm0 to transfer
reg = REG_XMM0;
if (xmm0_used) {
save_fp_reg(REG_XMM0);
clear_fp_reg(cur_time, REG_XMM0);
}
load_val_in_fp_reg(cur_time, input_var, REG_XMM0);
}
print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[reg]);
} else {
auto reg = REG_NONE;
// find free/unused register
for (size_t i = 0; i < REG_COUNT; ++i) {
if (reg_map[i].cur_var == nullptr || reg_map[i].cur_var->gen_info.last_use_time < cur_time) {
reg = static_cast<REGISTER>(i);
break;
}
}
if (reg == REG_NONE) {
// use rax to transfer
reg = REG_A;
if (rax_used) {
save_reg(REG_A);
clear_reg(cur_time, REG_A);
}
load_val_in_reg<false>(cur_time, input_var, REG_A);
}
print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_names[reg][0]);
if (!input_var->gen_info.saved_in_stack) {
input_var->gen_info.saved_in_stack = true;
input_var->gen_info.stack_slot = stack_slot;
}
}
continue;
}
assert(input_var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED);
input_var->gen_info.allocated_to_input = true;
target_var->gen_info.location = input_var->gen_info.location;
target_var->gen_info.loc_info = input_var->gen_info.loc_info;
// TODO: make translation blocks/cfops put the values in the registers/statics *and* stack locations
// if applicable
if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::STACK_FRAME) {
target_var->gen_info.saved_in_stack = true;
target_var->gen_info.stack_slot = input_var->gen_info.stack_slot;
}
if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER && input_var->gen_info.reg_idx == REG_A) {
rax_used = true;
rax_input = input_var;
}
if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER && input_var->gen_info.reg_idx == REG_XMM0) {
xmm0_used = true;
xmm0_input = input_var;
}
}
if (rax_used && rax_input->gen_info.location != SSAVar::GeneratorInfoX64::REGISTER) {
assert(reg_map[REG_A].cur_var->gen_info.saved_in_stack || reg_map[REG_A].cur_var->is_immediate());
clear_reg(cur_time, REG_A);
load_val_in_reg(cur_time, rax_input, REG_A);
}
if (xmm0_used && xmm0_input->gen_info.location != SSAVar::GeneratorInfoX64::FP_REGISTER) {
assert(fp_reg_map[REG_XMM0].cur_var->gen_info.saved_in_stack);
clear_fp_reg(cur_time, REG_XMM0);
load_val_in_fp_reg(cur_time, xmm0_input, REG_XMM0);
}
generate_input_map(target);
}
}
void RegAlloc::set_bb_inputs_from_static(BasicBlock *target) {
for (size_t i = 0; i < target->inputs.size(); ++i) {
auto *var = target->inputs[i];
assert(std::holds_alternative<size_t>(var->info));
BasicBlock::GeneratorInfo::InputInfo info;
info.location = BasicBlock::GeneratorInfo::InputInfo::STATIC;
info.static_idx = std::get<size_t>(var->info);
var->gen_info.location = SSAVar::GeneratorInfoX64::STATIC;
var->gen_info.static_idx = info.static_idx;
target->gen_info.input_map.push_back(info);
}
target->gen_info.input_map_setup = true;
}
void RegAlloc::generate_input_map(BasicBlock *bb) {
for (size_t i = 0; i < bb->inputs.size(); ++i) {
// namespaces :D
using InputInfo = BasicBlock::GeneratorInfo::InputInfo;
using GenInfo = SSAVar::GeneratorInfoX64;
auto *var = bb->inputs[i];
if (var->type == Type::mt) {
// we lie a little
InputInfo info;
info.location = InputInfo::STATIC;
info.static_idx = 32;
bb->gen_info.input_map.push_back(info);
continue;
}
InputInfo info;
const auto var_loc = var->gen_info.location;
assert(var_loc == GenInfo::REGISTER || var_loc == GenInfo::FP_REGISTER || var_loc == GenInfo::STACK_FRAME || var_loc == GenInfo::STATIC);
if (var_loc == GenInfo::STATIC) {
info.location = InputInfo::STATIC;
info.static_idx = var->gen_info.static_idx;
} else if (var_loc == GenInfo::REGISTER) {
info.location = InputInfo::REGISTER;
info.reg_idx = var->gen_info.reg_idx;
} else if (var_loc == GenInfo::FP_REGISTER) {
info.location = InputInfo::FP_REGISTER;
info.reg_idx = var->gen_info.reg_idx;
} else if (var_loc == GenInfo::STACK_FRAME) {
info.location = InputInfo::STACK;
info.stack_slot = var->gen_info.stack_slot;
}
bb->gen_info.input_map.push_back(info);
}
bb->gen_info.input_map_setup = true;
}
void RegAlloc::write_static_mapping([[maybe_unused]] BasicBlock *bb, size_t cur_time, const std::vector<std::pair<RefPtr<SSAVar>, size_t>> &mapping) {
// TODO: this is a bit unfaithful to the time calculation since we write out registers first but that should be fine
auto written_out = std::vector<bool>{};
written_out.resize(mapping.size());
// TODO: here we could write out all register that do not overwrite a static that is uses as an input
// but that involves a bit more housekeeping
// load all static inputs into a register so we don't have to worry about that anymore
for (size_t i = 0; i < mapping.size(); ++i) {
const auto &pair = mapping[i];
auto *var = pair.first.get();
if (var->type == Type::mt) {
continue;
}
if (var->gen_info.location != SSAVar::GeneratorInfoX64::STATIC) {
continue;
}
// skip identity-mapped statics
if (var->gen_info.static_idx == pair.second) {
written_out[i] = true;
continue;
}
if (is_float(var->type)) {
load_val_in_fp_reg(cur_time, var);
} else {
load_val_in_reg(cur_time, var);
}
}
// write out all registers
for (size_t i = 0; i < mapping.size(); ++i) {
const auto &pair = mapping[i];
auto *var = pair.first.get();
if (var->type == Type::mt) {
continue;
}
auto location = var->gen_info.location;
if (location != SSAVar::GeneratorInfoX64::REGISTER && location != SSAVar::GeneratorInfoX64::FP_REGISTER) {
continue;
}
if (std::holds_alternative<size_t>(var->info)) {
auto should_skip = false;
for (size_t i = 0; i < cur_bb->inputs.size(); ++i) {
if (cur_bb->inputs[i] == var) {
const auto &info = cur_bb->gen_info.input_map[i];
if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == pair.second) {
should_skip = true;
}
break;
}
}
if (should_skip) {
continue;
}
}
if (location == SSAVar::GeneratorInfoX64::FP_REGISTER) {
print_asm("movq [s%zu], %s\n", pair.second, fp_reg_names[var->gen_info.reg_idx]);
continue;
}
print_asm("mov [s%zu], %s\n", pair.second, reg_names[var->gen_info.reg_idx][0]);
written_out[i] = true;
}
// write out stuff in stack
for (size_t var_idx = 0; var_idx < mapping.size(); ++var_idx) {
auto *var = mapping[var_idx].first.get();
if (var->type == Type::mt) {
continue;
}
const auto static_idx = mapping[var_idx].second;
if (written_out[var_idx]) {
continue;
}
if (std::holds_alternative<size_t>(var->info)) {
auto should_skip = false;
for (size_t i = 0; i < cur_bb->inputs.size(); ++i) {
if (cur_bb->inputs[i] == var) {
const auto &info = cur_bb->gen_info.input_map[i];
if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == static_idx) {
should_skip = true;
}
break;
}
}
if (should_skip) {
continue;
}
}
// TODO: cant do that here since the syscall cfop needs some vars later on
// TODO: really need to fix this time management
if (is_float(var->type)) {
const auto reg = load_val_in_fp_reg(cur_time, var);
print_asm("movq [s%zu], %s\n", static_idx, fp_reg_names[reg]);
} else {
const auto reg = load_val_in_reg(cur_time /*+ var_idx*/, var);
print_asm("mov [s%zu], %s\n", static_idx, reg_names[reg][0]);
}
}
}
void RegAlloc::write_target_inputs(BasicBlock *target, size_t cur_time, const std::vector<RefPtr<SSAVar>> &inputs) {
// Here we have multiple problems:
// - we could need to write to a static that is needed to be somewhere else later
// - we could need to write to a register that is needed somewhere else later
// - we could need to write to a stack-slot that is needed somewhere else later
// the dumbest thing to solve these would be to recognize them, force-allocate new stack-slots and load them from there when needed
// so that's what we do :)
// register conflicts should be resolved by load_from_reg though
assert(target->gen_info.input_map_setup);
assert(target->inputs.size() == target->gen_info.input_map.size());
const auto &input_map = target->gen_info.input_map;
// mark all stack slots used as inputs as non-free
auto &stack_map = *cur_stack_map;
for (size_t i = 0; i < input_map.size(); ++i) {
if (input_map[i].location != BasicBlock::GeneratorInfo::InputInfo::STACK) {
continue;
}
const auto stack_slot = input_map[i].stack_slot;
if (stack_map.size() <= stack_slot) {
stack_map.resize(stack_slot + 1);
}
stack_map[stack_slot].free = false;
}
// fixup time calculation
// TODO: do this at the start
for (auto &input : inputs) {
input->gen_info.last_use_time = 0;
input->gen_info.uses.clear();
}
size_t cur_write_time = cur_time + 1;
const auto set_use_times = [&cur_write_time, &input_map, &inputs](BasicBlock::GeneratorInfo::InputInfo::LOCATION loc) {
for (size_t i = 0; i < inputs.size(); ++i) {
if (input_map[i].location != loc) {
continue;
}
inputs[i]->gen_info.last_use_time = cur_write_time;
inputs[i]->gen_info.uses.emplace_back(cur_write_time);
cur_write_time++;
}
};
// we write out statics first
set_use_times(BasicBlock::GeneratorInfo::InputInfo::STATIC);
// stack second
set_use_times(BasicBlock::GeneratorInfo::InputInfo::STACK);
// registers last
set_use_times(BasicBlock::GeneratorInfo::InputInfo::REGISTER);
set_use_times(BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER);
// figure out static conflicts
for (size_t i = 0; i < inputs.size(); ++i) {
if (inputs[i]->gen_info.location != SSAVar::GeneratorInfoX64::STATIC) {
continue;
}
if (inputs[i]->type == Type::mt) {
continue;
}
// it is a problem when another input needs to be at this static
auto conflict = false;
for (size_t j = 0; j < inputs.size(); ++j) {
if (j == i) {
continue;
}
if (inputs[j]->type != Type::mt && input_map[j].location == BasicBlock::GeneratorInfo::InputInfo::STATIC && input_map[j].static_idx == inputs[i]->gen_info.static_idx) {
conflict = true;
break;
}
}
if (!conflict) {
continue;
}
// just load it in a register
if (is_float(inputs[i].get()->type)) {
load_val_in_fp_reg(cur_time, inputs[i].get());
} else {
load_val_in_reg(cur_time, inputs[i].get());
}
}
// stack conflicts
for (size_t i = 0; i < inputs.size(); ++i) {
auto *var = inputs[i].get();
if (!var->gen_info.saved_in_stack) {
continue;
}
// when two stack slots overlap and they don't correspond to the same stack slot
auto conflict = false;
for (size_t j = 0; j < inputs.size(); ++j) {
if (i == j || input_map[j].location != BasicBlock::GeneratorInfo::InputInfo::STACK) {
continue;
}
if (var->gen_info.stack_slot == input_map[j].stack_slot) {
conflict = true;
break;
}
}
if (!conflict) {
continue;
}
// load in register, delete stack slot and save again
if (is_float(var->type)) {
const auto reg = load_val_in_fp_reg(cur_time, var);
var->gen_info.saved_in_stack = false;
save_fp_reg(reg);
} else {
const auto reg = load_val_in_reg(cur_time, var);
var->gen_info.saved_in_stack = false;
save_reg(reg);
}
}
cur_write_time = cur_time + 1;
// write out statics
for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) {
if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::STATIC) {
continue;
}
if (inputs[var_idx]->type == Type::mt) {
cur_write_time++;
continue;
}
if (inputs[var_idx]->gen_info.location == SSAVar::GeneratorInfoX64::STATIC && inputs[var_idx]->gen_info.static_idx == input_map[var_idx].static_idx) {
cur_write_time++;
continue;
}
auto *var = inputs[var_idx].get();
if (std::holds_alternative<size_t>(var->info)) {
auto should_skip = false;
for (size_t i = 0; i < cur_bb->inputs.size(); ++i) {
if (cur_bb->inputs[i] == var) {
const auto &info = cur_bb->gen_info.input_map[i];
if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == input_map[var_idx].static_idx) {
should_skip = true;
}
break;
}
}
if (should_skip) {
cur_write_time++;
continue;
}
}
if (is_float(var->type)) {
const auto reg = load_val_in_fp_reg(cur_write_time, var);
print_asm("movq [s%zu], %s\n", input_map[var_idx].static_idx, fp_reg_names[reg]);
} else {
const auto reg = load_val_in_reg(cur_write_time, var);
print_asm("mov [s%zu], %s\n", input_map[var_idx].static_idx, reg_names[reg][0]);
}
cur_write_time++;
}
// write out stack
for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) {
auto &info = input_map[var_idx];
if (info.location != BasicBlock::GeneratorInfo::InputInfo::STACK) {
continue;
}
auto *input = inputs[var_idx].get();
if (input->gen_info.saved_in_stack && input->gen_info.stack_slot == info.stack_slot) {
cur_write_time++;
continue;
}
if (is_float(input->type)) {
const auto reg = load_val_in_fp_reg(cur_write_time, input);
print_asm("movq [rsp + 8 * %zu], %s\n", info.stack_slot, fp_reg_names[reg]);
} else {
const auto reg = load_val_in_reg(cur_write_time, input);
print_asm("mov [rsp + 8 * %zu], %s\n", info.stack_slot, reg_names[reg][0]);
}
cur_write_time++;
}
// write out registers
auto ®_map = *cur_reg_map;
for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) {
if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::REGISTER) {
continue;
}
const auto reg = static_cast<REGISTER>(input_map[var_idx].reg_idx);
auto *input = inputs[var_idx].get();
if (input->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) {
if (input->gen_info.reg_idx == reg) {
cur_write_time++;
continue;
}
// just emit a mov and evict the other var
if (reg_map[reg].cur_var && reg_map[reg].cur_var->gen_info.last_use_time > cur_write_time) {
save_reg(reg);
}
clear_reg(cur_write_time, reg);
print_asm("mov %s, %s\n", reg_names[reg][0], reg_names[input->gen_info.reg_idx][0]);
reg_map[reg].cur_var = input;
reg_map[reg].alloc_time = cur_write_time;
} else {
load_val_in_reg(cur_write_time, input, reg);
}
cur_write_time++;
}
// write out fp registers
auto &fp_reg_map = *cur_fp_reg_map;
for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) {
if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER) {
continue;
}
const auto reg = static_cast<FP_REGISTER>(input_map[var_idx].reg_idx);
auto *input = inputs[var_idx].get();
if (input->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) {
if (input->gen_info.reg_idx == reg) {
cur_write_time++;
continue;
}
// just emit a mov and evict the other var
if (fp_reg_map[reg].cur_var && fp_reg_map[reg].cur_var->gen_info.last_use_time > cur_write_time) {
save_fp_reg(reg);
}
clear_fp_reg(cur_write_time, reg);
print_asm("movq %s, %s\n", fp_reg_names[reg], fp_reg_names[input->gen_info.reg_idx]);
fp_reg_map[reg].cur_var = input;
fp_reg_map[reg].alloc_time = cur_write_time;
} else {
load_val_in_fp_reg(cur_write_time, input, reg);
}
cur_write_time++;
}
}
void RegAlloc::init_time_of_use(BasicBlock *bb) {
for (size_t i = 0; i < bb->variables.size(); ++i) {
auto *var = bb->variables[i].get();
if (!std::holds_alternative<std::unique_ptr<Operation>>(var->info)) {
continue;
}
auto *op = std::get<std::unique_ptr<Operation>>(var->info).get();
for (auto &input : op->in_vars) {
if (!input) {
continue;
}
input->gen_info.last_use_time = i; // max(last_use_time, i)?
input->gen_info.uses.push_back(i);
}
if (std::holds_alternative<RefPtr<SSAVar>>(op->rounding_info)) {
SSAVar *rounding_info = std::get<RefPtr<SSAVar>>(op->rounding_info).get();
rounding_info->gen_info.last_use_time = i;
rounding_info->gen_info.uses.push_back(i);
}
}
const auto set_time_cont_mapping = [](const size_t time_off, std::vector<std::pair<RefPtr<SSAVar>, size_t>> &mapping) {
for (size_t i = 0; i < mapping.size(); ++i) {
auto &info = mapping[i].first->gen_info;
info.last_use_time = std::max(info.last_use_time, time_off + i);
info.uses.push_back(time_off + i);
}
};
const auto set_time_inputs = [](const size_t time_off, std::vector<RefPtr<SSAVar>> &mapping) {
for (size_t i = 0; i < mapping.size(); ++i) {
auto &info = mapping[i]->gen_info;
info.last_use_time = std::max(info.last_use_time, time_off + i);
info.uses.push_back(time_off + i);
}
};
for (auto &cf_op : bb->control_flow_ops) {
// we treat cf_ops as running in parallel
auto time_off = bb->variables.size();
for (auto &input : cf_op.in_vars) {
if (!input) {
continue;
}
input->gen_info.last_use_time = std::max(input->gen_info.last_use_time, time_off);
input->gen_info.uses.push_back(time_off);
}
time_off++;
switch (cf_op.type) {
case CFCInstruction::jump:
set_time_inputs(time_off, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs);
break;
case CFCInstruction::ijump:
set_time_cont_mapping(time_off, std::get<CfOp::IJumpInfo>(cf_op.info).mapping);
break;
case CFCInstruction::cjump:
set_time_inputs(time_off, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs);
break;
case CFCInstruction::call: {
auto &info = std::get<CfOp::CallInfo>(cf_op.info);
set_time_inputs(time_off, info.target_inputs);
time_off += info.target_inputs.size();
break;
}
case CFCInstruction::icall: {
auto &info = std::get<CfOp::ICallInfo>(cf_op.info);
set_time_cont_mapping(time_off, info.mapping);
time_off += info.mapping.size();
break;
}
case CFCInstruction::_return:
set_time_cont_mapping(time_off, std::get<CfOp::RetInfo>(cf_op.info).mapping);
break;
case CFCInstruction::unreachable:
break;
case CFCInstruction::syscall:
set_time_cont_mapping(time_off, std::get<CfOp::SyscallInfo>(cf_op.info).continuation_mapping);
break;
}
}
}
template <bool evict_imms, typename... Args> REGISTER RegAlloc::alloc_reg(size_t cur_time, REGISTER only_this_reg, Args... clear_regs) {
static_assert((std::is_same_v<Args, REGISTER> && ...));
auto ®_map = *cur_reg_map;
if (only_this_reg != REG_NONE) {
auto &cur_var = reg_map[only_this_reg].cur_var;
if (cur_var != nullptr) {
save_reg(only_this_reg, !evict_imms);
cur_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
cur_var = nullptr;
}
return only_this_reg;
}
REGISTER reg = REG_NONE;
// try to find free register
for (size_t i = 0; i < REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality)
continue;
}
if (reg_map[i].cur_var == nullptr) {
reg = static_cast<REGISTER>(i);
break;
}
}
if (reg == REG_NONE) {
// try to find reg with unused var
for (size_t i = 0; i < REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality)
continue;
}
if (reg_map[i].cur_var->gen_info.last_use_time < cur_time) {
reg = static_cast<REGISTER>(i);
break;
}
}
if (reg == REG_NONE) {
// find var that's the farthest from being used again
// TODO: prefer variables that are used less often so that the stack ptr for example stays in a register
size_t farthest_use_time = 0;
REGISTER farthest_use_reg = REG_NONE;
for (size_t i = 0; i < REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality)
continue;
}
size_t next_use = 0;
for (const auto use_time : reg_map[i].cur_var->gen_info.uses) {
if (use_time == cur_time) {
// var is used in this step so don't reuse it
next_use = 0;
break;
}
if (use_time > cur_time) {
next_use = use_time;
break;
}
}
if (next_use == 0) {
// var is needed in this step
continue;
}
if (farthest_use_time < next_use) {
farthest_use_time = next_use;
farthest_use_reg = static_cast<REGISTER>(i);
}
}
assert(farthest_use_reg != REG_NONE);
reg = farthest_use_reg;
// in cfops imms need to be saved to stack cause there's not other means to pass them
save_reg(farthest_use_reg, !evict_imms);
}
}
clear_reg(cur_time, reg, !evict_imms);
reg_map[reg].cur_var = nullptr;
reg_map[reg].alloc_time = cur_time;
return reg;
}
template <typename... Args> FP_REGISTER RegAlloc::alloc_fp_reg(size_t cur_time, FP_REGISTER only_this_reg, Args... clear_regs) {
static_assert((std::is_same_v<Args, FP_REGISTER> && ...));
auto ®_map = *cur_fp_reg_map;
if (only_this_reg != FP_REG_NONE) {
auto &cur_var = reg_map[only_this_reg].cur_var;
if (cur_var != nullptr) {
save_fp_reg(only_this_reg);
cur_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
cur_var = nullptr;
}
return only_this_reg;
}
FP_REGISTER reg = FP_REG_NONE;
// try to find free register
for (size_t i = 0; i < FP_REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) {
continue;
}
if (reg_map[i].cur_var == nullptr) {
reg = static_cast<FP_REGISTER>(i);
break;
}
}
if (reg == FP_REG_NONE) {
// try to find reg with unused var
for (size_t i = 0; i < FP_REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) {
continue;
}
if (reg_map[i].cur_var->gen_info.last_use_time < cur_time) {
reg = static_cast<FP_REGISTER>(i);
break;
}
}
if (reg == FP_REG_NONE) {
// find var that's the farthest from being used again
// TODO: prefer variables that are used less often so that the stack ptr for example stays in a register
size_t farthest_use_time = 0;
FP_REGISTER farthest_use_reg = FP_REG_NONE;
for (size_t i = 0; i < FP_REG_COUNT; ++i) {
if (((i == clear_regs) || ...)) {
continue;
}
size_t next_use = 0;
for (const auto use_time : reg_map[i].cur_var->gen_info.uses) {
if (use_time == cur_time) {
// var is used in this step so don't reuse it
next_use = 0;
break;
}
if (use_time > cur_time) {
next_use = use_time;
break;
}
}
if (next_use == 0) {
// var is needed in this step
continue;
}
if (farthest_use_time < next_use) {
farthest_use_time = next_use;
farthest_use_reg = static_cast<FP_REGISTER>(i);
}
}
assert(farthest_use_reg != FP_REG_NONE);
reg = farthest_use_reg;
// in cfops imms need to be saved to stack cause there's not other means to pass them
save_fp_reg(farthest_use_reg);
}
}
clear_fp_reg(cur_time, reg);
reg_map[reg].cur_var = nullptr;
reg_map[reg].alloc_time = cur_time;
return reg;
}
template <bool evict_imms, typename... Args> REGISTER RegAlloc::load_val_in_reg(size_t cur_time, SSAVar *var, REGISTER only_this_reg, Args... clear_regs) {
static_assert((std::is_same_v<Args, REGISTER> && ...));
auto ®_map = *cur_reg_map;
if (var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) {
if (only_this_reg == REG_NONE || var->gen_info.reg_idx == only_this_reg) {
if (((var->gen_info.reg_idx == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality)
// clear_regs take precedent over only_this_reg though it should never happen
assert(((only_this_reg != clear_regs) && ...));
const auto new_reg = alloc_reg(cur_time, REG_NONE, clear_regs...);
print_asm("mov %s, %s\n", reg_names[new_reg][0], reg_names[var->gen_info.reg_idx][0]);
reg_map[var->gen_info.reg_idx].cur_var = nullptr;
reg_map[new_reg].cur_var = var;
reg_map[new_reg].alloc_time = cur_time;
var->gen_info.reg_idx = new_reg;
return new_reg;
}
return static_cast<REGISTER>(var->gen_info.reg_idx);
}
// TODO: add a thing in the regmap that tells the allocater that the var may only be in this register
// TODO: this will bug out when you alloc a reg and then alloc one if only_this_reg and they end up in the same register
if (auto *other_var = reg_map[only_this_reg].cur_var; other_var && other_var->gen_info.last_use_time >= cur_time) {
// TODO: disabled this as it doesn't cope well when a var needs to be in two registers at the same time,
// e.g. in cfops
/*print_asm("xchg %s, %s\n", reg_names[only_this_reg][0], reg_names[var->gen_info.reg_idx][0]);
std::swap(reg_map[only_this_reg], reg_map[var->gen_info.reg_idx]);
std::swap(var->gen_info.reg_idx, other_var->gen_info.reg_idx);
return only_this_reg;*/
save_reg(only_this_reg);
}
clear_reg(cur_time, only_this_reg);
print_asm("mov %s, %s\n", reg_names[only_this_reg][0], reg_names[var->gen_info.reg_idx][0]);
reg_map[var->gen_info.reg_idx].cur_var = nullptr;
reg_map[only_this_reg].cur_var = var;
var->gen_info.reg_idx = only_this_reg;
return only_this_reg;
}
const auto reg = alloc_reg<evict_imms>(cur_time, only_this_reg, clear_regs...);
if (var->is_immediate()) {
auto &info = std::get<SSAVar::ImmInfo>(var->info);
if (info.binary_relative) {
print_asm("lea %s, [binary + %ld]\n", reg_names[reg][0], info.val);
} else {
print_asm("mov %s, %ld\n", reg_names[reg][0], info.val);
}
} else {
// non-immediates should have been calculated before
assert(var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED);
if (var->gen_info.location == SSAVar::GeneratorInfoX64::STATIC) {
print_asm("mov %s, [s%zu]\n", reg_name(reg, var->type), var->gen_info.static_idx);
} else {
print_asm("mov %s, [rsp + 8 * %zu]\n", reg_name(reg, var->type), var->gen_info.stack_slot);
}
}
reg_map[reg].cur_var = var;
var->gen_info.location = SSAVar::GeneratorInfoX64::REGISTER;
var->gen_info.reg_idx = reg;
return reg;
}
template <typename... Args> FP_REGISTER RegAlloc::load_val_in_fp_reg(size_t cur_time, SSAVar *var, FP_REGISTER only_this_reg, Args... clear_regs) {
static_assert((std::is_same_v<Args, FP_REGISTER> && ...));
auto ®_map = *cur_fp_reg_map;
assert(var->gen_info.location != SSAVar::GeneratorInfoX64::REGISTER);
if (var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) {
if (only_this_reg == FP_REG_NONE || var->gen_info.reg_idx == only_this_reg) {
if (((var->gen_info.reg_idx == clear_regs) || ...)) {
// clear_regs take precedent over only_this_reg though it should never happen
assert(((only_this_reg != clear_regs) && ...));
const auto new_reg = alloc_fp_reg(cur_time, FP_REG_NONE, clear_regs...);
print_asm("movq %s, %s\n", fp_reg_names[new_reg], fp_reg_names[var->gen_info.reg_idx]);
reg_map[var->gen_info.reg_idx].cur_var = nullptr;
reg_map[new_reg].cur_var = var;
reg_map[new_reg].alloc_time = cur_time;
var->gen_info.reg_idx = new_reg;
return new_reg;
}
return static_cast<FP_REGISTER>(var->gen_info.reg_idx);
}
// TODO: add a thing in the regmap that tells the allocater that the var may only be in this register
// TODO: this will bug out when you alloc a reg and then alloc one if only_this_reg and they end up in the same register
if (auto *other_var = reg_map[only_this_reg].cur_var; other_var && other_var->gen_info.last_use_time >= cur_time) {
// swap register contents
/*print_asm("pxor %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]);
print_asm("pxor %s, %s\n", fp_reg_names[var->gen_info.reg_idx], fp_reg_names[only_this_reg]);
print_asm("pxor %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]);
std::swap(reg_map[only_this_reg], reg_map[var->gen_info.reg_idx]);
std::swap(var->gen_info.reg_idx, other_var->gen_info.reg_idx);
return only_this_reg; */
save_fp_reg(only_this_reg);
}
clear_fp_reg(cur_time, only_this_reg);
print_asm("movq %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]);
reg_map[var->gen_info.reg_idx].cur_var = nullptr;
reg_map[only_this_reg].cur_var = var;
var->gen_info.reg_idx = only_this_reg;
return only_this_reg;
}
const auto reg = alloc_fp_reg(cur_time, only_this_reg, clear_regs...);
// non-immediates should have been calculated before
assert(var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED);
if (var->gen_info.location == SSAVar::GeneratorInfoX64::STATIC) {
print_asm("movq %s, [s%zu]\n", fp_reg_names[reg], var->gen_info.static_idx);
} else {
print_asm("movq %s, [rsp + 8 * %zu]\n", fp_reg_names[reg], var->gen_info.stack_slot);
}
reg_map[reg].cur_var = var;
var->gen_info.location = SSAVar::GeneratorInfoX64::FP_REGISTER;
var->gen_info.reg_idx = reg;
return reg;
}
void RegAlloc::clear_reg(size_t cur_time, REGISTER reg, bool imm_to_stack) {
auto ®_map = *cur_reg_map;
auto *var = reg_map[reg].cur_var;
if (!var) {
return;
}
if (var->is_immediate() && !imm_to_stack) {
// we simply calculate the value on demand
var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED;
} else if (var->gen_info.saved_in_stack) {
var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
} else {
// var that was never saved on stack and is not needed anymore
// TODO: <?
assert(var->gen_info.last_use_time <= cur_time);
var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED;
}
reg_map[reg].cur_var = nullptr;
}
void RegAlloc::clear_fp_reg(size_t cur_time, FP_REGISTER reg) {
auto ®_map = *cur_fp_reg_map;
auto *var = reg_map[reg].cur_var;
if (!var) {
return;
}
if (var->gen_info.saved_in_stack) {
var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
} else {
// var that was never saved on stack and is not needed anymore
assert(var->gen_info.last_use_time <= cur_time);
var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED;
}
reg_map[reg].cur_var = nullptr;
}
size_t RegAlloc::allocate_stack_slot(SSAVar *var) {
auto &stack_map = *cur_stack_map;
// find slot for var
size_t stack_slot = 0;
{
auto stack_slot_found = false;
for (size_t i = 0; i < stack_map.size(); ++i) {
if (stack_map[i].free) {
stack_slot_found = true;
stack_slot = i;
break;
}
}
if (!stack_slot_found) {
stack_slot = stack_map.size();
stack_map.emplace_back();
}
}
stack_map[stack_slot].free = false;
stack_map[stack_slot].var = var;
return stack_slot;
}
void RegAlloc::save_reg(REGISTER reg, bool imm_to_stack) {
auto ®_map = *cur_reg_map;
auto *var = reg_map[reg].cur_var;
if (!var) {
return;
}
if (var->gen_info.saved_in_stack) {
// var was already saved, no need to save it again
return;
}
if (var->is_immediate() && !imm_to_stack) {
// no need to save immediates i think
return;
}
// find slot for var
size_t stack_slot = allocate_stack_slot(var);
print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_name(reg, var->type));
var->gen_info.saved_in_stack = true;
var->gen_info.stack_slot = stack_slot;
}
void RegAlloc::save_fp_reg(FP_REGISTER reg) {
auto ®_map = *cur_fp_reg_map;
auto *var = reg_map[reg].cur_var;
if (!var) {
return;
}
if (var->gen_info.saved_in_stack) {
// var was already saved, no need to save it again
return;
}
// find slot for var
size_t stack_slot = allocate_stack_slot(var);
print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[reg]);
var->gen_info.saved_in_stack = true;
var->gen_info.stack_slot = stack_slot;
}
void RegAlloc::clear_after_alloc_time(size_t alloc_time) {
// TODO: doesnt work
auto ®_map = *cur_reg_map;
for (size_t i = 0; i < REG_COUNT; ++i) {
if (reg_map[i].alloc_time < alloc_time) {
continue;
}
auto *var = reg_map[i].cur_var;
if (!var) {
return;
}
if (var->is_immediate()) {
// we simply calculate the value on demand
var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED;
} else if (var->gen_info.saved_in_stack) {
var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME;
} else {
var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED;
}
reg_map[i].cur_var = nullptr;
}
}
bool RegAlloc::is_block_top_level(BasicBlock *bb) {
if (bb->id > BB_OLD_COMPILE_ID_TIL || bb->id > BB_MERGE_TIL_ID || bb->gen_info.manual_top_level || bb->gen_info.call_target) {
return true;
}
for (auto *pred : bb->predecessors) {
if (pred != bb) {
return false;
}
}
return true;
}
| 46.128951 | 195 | 0.521274 | ERAP-SBT |
116c13a620794960c5b365297a95697cef1ac28a | 5,905 | cpp | C++ | 3dparty/taglib/tests/test_aiff.cpp | olanser/uteg | c8c79a8e8e5d185253b415e67f7b6d9e37114da3 | [
"MIT"
] | 3,066 | 2016-06-10T09:23:40.000Z | 2022-03-31T11:01:01.000Z | 3dparty/taglib/tests/test_aiff.cpp | olanser/uteg | c8c79a8e8e5d185253b415e67f7b6d9e37114da3 | [
"MIT"
] | 414 | 2016-09-20T20:26:05.000Z | 2022-03-29T00:43:13.000Z | 3dparty/taglib/tests/test_aiff.cpp | olanser/uteg | c8c79a8e8e5d185253b415e67f7b6d9e37114da3 | [
"MIT"
] | 310 | 2016-06-13T21:53:04.000Z | 2022-03-18T14:36:38.000Z | /***************************************************************************
copyright : (C) 2009 by Lukas Lalinsky
email : [email protected]
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <string>
#include <stdio.h>
#include <tag.h>
#include <tbytevectorlist.h>
#include <aifffile.h>
#include <cppunit/extensions/HelperMacros.h>
#include "utils.h"
using namespace std;
using namespace TagLib;
class TestAIFF : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestAIFF);
CPPUNIT_TEST(testAiffProperties);
CPPUNIT_TEST(testAiffCProperties);
CPPUNIT_TEST(testSaveID3v2);
CPPUNIT_TEST(testSaveID3v23);
CPPUNIT_TEST(testDuplicateID3v2);
CPPUNIT_TEST(testFuzzedFile1);
CPPUNIT_TEST(testFuzzedFile2);
CPPUNIT_TEST_SUITE_END();
public:
void testAiffProperties()
{
RIFF::AIFF::File f(TEST_FILE_PATH_C("empty.aiff"));
CPPUNIT_ASSERT(f.audioProperties());
CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds());
CPPUNIT_ASSERT_EQUAL(67, f.audioProperties()->lengthInMilliseconds());
CPPUNIT_ASSERT_EQUAL(706, f.audioProperties()->bitrate());
CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate());
CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->channels());
CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample());
CPPUNIT_ASSERT_EQUAL(2941U, f.audioProperties()->sampleFrames());
CPPUNIT_ASSERT_EQUAL(false, f.audioProperties()->isAiffC());
}
void testAiffCProperties()
{
RIFF::AIFF::File f(TEST_FILE_PATH_C("alaw.aifc"));
CPPUNIT_ASSERT(f.audioProperties());
CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds());
CPPUNIT_ASSERT_EQUAL(37, f.audioProperties()->lengthInMilliseconds());
CPPUNIT_ASSERT_EQUAL(355, f.audioProperties()->bitrate());
CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate());
CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->channels());
CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample());
CPPUNIT_ASSERT_EQUAL(1622U, f.audioProperties()->sampleFrames());
CPPUNIT_ASSERT_EQUAL(true, f.audioProperties()->isAiffC());
CPPUNIT_ASSERT_EQUAL(ByteVector("ALAW"), f.audioProperties()->compressionType());
CPPUNIT_ASSERT_EQUAL(String("SGI CCITT G.711 A-law"), f.audioProperties()->compressionName());
}
void testSaveID3v2()
{
ScopedFileCopy copy("empty", ".aiff");
string newname = copy.fileName();
{
RIFF::AIFF::File f(newname.c_str());
CPPUNIT_ASSERT(!f.hasID3v2Tag());
f.tag()->setTitle(L"TitleXXX");
f.save();
CPPUNIT_ASSERT(f.hasID3v2Tag());
}
{
RIFF::AIFF::File f(newname.c_str());
CPPUNIT_ASSERT(f.hasID3v2Tag());
CPPUNIT_ASSERT_EQUAL(String(L"TitleXXX"), f.tag()->title());
f.tag()->setTitle("");
f.save();
CPPUNIT_ASSERT(!f.hasID3v2Tag());
}
{
RIFF::AIFF::File f(newname.c_str());
CPPUNIT_ASSERT(!f.hasID3v2Tag());
}
}
void testSaveID3v23()
{
ScopedFileCopy copy("empty", ".aiff");
string newname = copy.fileName();
String xxx = ByteVector(254, 'X');
{
RIFF::AIFF::File f(newname.c_str());
CPPUNIT_ASSERT_EQUAL(false, f.hasID3v2Tag());
f.tag()->setTitle(xxx);
f.tag()->setArtist("Artist A");
f.save(ID3v2::v3);
CPPUNIT_ASSERT_EQUAL(true, f.hasID3v2Tag());
}
{
RIFF::AIFF::File f2(newname.c_str());
CPPUNIT_ASSERT_EQUAL((unsigned int)3, f2.tag()->header()->majorVersion());
CPPUNIT_ASSERT_EQUAL(String("Artist A"), f2.tag()->artist());
CPPUNIT_ASSERT_EQUAL(xxx, f2.tag()->title());
}
}
void testDuplicateID3v2()
{
ScopedFileCopy copy("duplicate_id3v2", ".aiff");
// duplicate_id3v2.aiff has duplicate ID3v2 tag chunks.
// title() returns "Title2" if can't skip the second tag.
RIFF::AIFF::File f(copy.fileName().c_str());
CPPUNIT_ASSERT(f.hasID3v2Tag());
CPPUNIT_ASSERT_EQUAL(String("Title1"), f.tag()->title());
f.save();
CPPUNIT_ASSERT_EQUAL(7030L, f.length());
CPPUNIT_ASSERT_EQUAL(-1L, f.find("Title2"));
}
void testFuzzedFile1()
{
RIFF::AIFF::File f(TEST_FILE_PATH_C("segfault.aif"));
CPPUNIT_ASSERT(!f.isValid());
}
void testFuzzedFile2()
{
RIFF::AIFF::File f(TEST_FILE_PATH_C("excessive_alloc.aif"));
CPPUNIT_ASSERT(!f.isValid());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAIFF);
| 36.226994 | 98 | 0.598476 | olanser |
116f0d43144b6d728b73d8568444fff9379e5988 | 15,563 | cpp | C++ | library/bubble/bubble_border.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 39 | 2019-06-22T12:25:54.000Z | 2022-03-14T05:42:44.000Z | library/bubble/bubble_border.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 5 | 2019-06-29T10:58:43.000Z | 2020-09-04T08:44:09.000Z | library/bubble/bubble_border.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 10 | 2019-08-07T06:08:23.000Z | 2022-03-14T05:42:47.000Z |
#include "bubble_border.h"
#include "base/logging.h"
#include "SkBitmap.h"
#include "ui_gfx/canvas_skia.h"
#include "ui_gfx/path.h"
#include "ui_gfx/rect.h"
#include "ui_base/resource/resource_bundle.h"
#include "view/view.h"
#include "../../resource/resource.h"
// static
SkBitmap* BubbleBorder::left_ = NULL;
SkBitmap* BubbleBorder::top_left_ = NULL;
SkBitmap* BubbleBorder::top_ = NULL;
SkBitmap* BubbleBorder::top_right_ = NULL;
SkBitmap* BubbleBorder::right_ = NULL;
SkBitmap* BubbleBorder::bottom_right_ = NULL;
SkBitmap* BubbleBorder::bottom_ = NULL;
SkBitmap* BubbleBorder::bottom_left_ = NULL;
SkBitmap* BubbleBorder::top_arrow_ = NULL;
SkBitmap* BubbleBorder::bottom_arrow_ = NULL;
SkBitmap* BubbleBorder::left_arrow_ = NULL;
SkBitmap* BubbleBorder::right_arrow_ = NULL;
// static
int BubbleBorder::arrow_offset_;
// The height inside the arrow image, in pixels.
static const int kArrowInteriorHeight = 7;
gfx::Rect BubbleBorder::GetBounds(const gfx::Rect& position_relative_to,
const gfx::Size& contents_size) const
{
// Desired size is size of contents enlarged by the size of the border images.
gfx::Size border_size(contents_size);
gfx::Insets insets;
GetInsets(&insets);
border_size.Enlarge(insets.left() + insets.right(),
insets.top() + insets.bottom());
// Screen position depends on the arrow location.
// The arrow should overlap the target by some amount since there is space
// for shadow between arrow tip and bitmap bounds.
const int kArrowOverlap = 3;
int x = position_relative_to.x();
int y = position_relative_to.y();
int w = position_relative_to.width();
int h = position_relative_to.height();
int arrow_offset = override_arrow_offset_ ? override_arrow_offset_ :
arrow_offset_;
// Calculate bubble x coordinate.
switch(arrow_location_)
{
case TOP_LEFT:
case BOTTOM_LEFT:
x += w / 2 - arrow_offset;
break;
case TOP_RIGHT:
case BOTTOM_RIGHT:
x += w / 2 + arrow_offset - border_size.width() + 1;
break;
case LEFT_TOP:
case LEFT_BOTTOM:
x += w - kArrowOverlap;
break;
case RIGHT_TOP:
case RIGHT_BOTTOM:
x += kArrowOverlap - border_size.width();
break;
case NONE:
case FLOAT:
x += w / 2 - border_size.width() / 2;
break;
}
// Calculate bubble y coordinate.
switch(arrow_location_)
{
case TOP_LEFT:
case TOP_RIGHT:
y += h - kArrowOverlap;
break;
case BOTTOM_LEFT:
case BOTTOM_RIGHT:
y += kArrowOverlap - border_size.height();
break;
case LEFT_TOP:
case RIGHT_TOP:
y += h / 2 - arrow_offset;
break;
case LEFT_BOTTOM:
case RIGHT_BOTTOM:
y += h / 2 + arrow_offset - border_size.height() + 1;
break;
case NONE:
y += h;
break;
case FLOAT:
y += h / 2 - border_size.height() / 2;
break;
}
return gfx::Rect(x, y, border_size.width(), border_size.height());
}
void BubbleBorder::GetInsets(gfx::Insets* insets) const
{
int top = top_->height();
int bottom = bottom_->height();
int left = left_->width();
int right = right_->width();
switch(arrow_location_)
{
case TOP_LEFT:
case TOP_RIGHT:
top = std::max(top, top_arrow_->height());
break;
case BOTTOM_LEFT:
case BOTTOM_RIGHT:
bottom = std::max(bottom, bottom_arrow_->height());
break;
case LEFT_TOP:
case LEFT_BOTTOM:
left = std::max(left, left_arrow_->width());
break;
case RIGHT_TOP:
case RIGHT_BOTTOM:
right = std::max(right, right_arrow_->width());
break;
case NONE:
case FLOAT:
// Nothing to do.
break;
}
insets->Set(top, left, bottom, right);
}
int BubbleBorder::SetArrowOffset(int offset, const gfx::Size& contents_size)
{
gfx::Size border_size(contents_size);
gfx::Insets insets;
GetInsets(&insets);
border_size.Enlarge(insets.left() + insets.right(),
insets.top() + insets.bottom());
offset = std::max(arrow_offset_,
std::min(offset, (is_arrow_on_horizontal(arrow_location_) ?
border_size.width() : border_size.height()) - arrow_offset_));
override_arrow_offset_ = offset;
return override_arrow_offset_;
}
// static
void BubbleBorder::InitClass()
{
static bool initialized = false;
if(!initialized)
{
// Load images.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
left_ = rb.GetBitmapNamed(IDR_BUBBLE_L);
top_left_ = rb.GetBitmapNamed(IDR_BUBBLE_TL);
top_ = rb.GetBitmapNamed(IDR_BUBBLE_T);
top_right_ = rb.GetBitmapNamed(IDR_BUBBLE_TR);
right_ = rb.GetBitmapNamed(IDR_BUBBLE_R);
bottom_right_ = rb.GetBitmapNamed(IDR_BUBBLE_BR);
bottom_ = rb.GetBitmapNamed(IDR_BUBBLE_B);
bottom_left_ = rb.GetBitmapNamed(IDR_BUBBLE_BL);
left_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_L_ARROW);
top_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_T_ARROW);
right_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_R_ARROW);
bottom_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_B_ARROW);
// Calculate horizontal and vertical insets for arrow by ensuring that
// the widest arrow and corner images will have enough room to avoid overlap
int offset_x = (std::max(top_arrow_->width(), bottom_arrow_->width()) / 2) +
std::max(std::max(top_left_->width(), top_right_->width()),
std::max(bottom_left_->width(), bottom_right_->width()));
int offset_y = (std::max(left_arrow_->height(), right_arrow_->height()) / 2) +
std::max(std::max(top_left_->height(), top_right_->height()),
std::max(bottom_left_->height(), bottom_right_->height()));
arrow_offset_ = std::max(offset_x, offset_y);
initialized = true;
}
}
void BubbleBorder::Paint(const view::View& view, gfx::Canvas* canvas) const
{
// Convenience shorthand variables.
const int tl_width = top_left_->width();
const int tl_height = top_left_->height();
const int t_height = top_->height();
const int tr_width = top_right_->width();
const int tr_height = top_right_->height();
const int l_width = left_->width();
const int r_width = right_->width();
const int br_width = bottom_right_->width();
const int br_height = bottom_right_->height();
const int b_height = bottom_->height();
const int bl_width = bottom_left_->width();
const int bl_height = bottom_left_->height();
gfx::Insets insets;
GetInsets(&insets);
const int top = insets.top() - t_height;
const int bottom = view.height() - insets.bottom() + b_height;
const int left = insets.left() - l_width;
const int right = view.width() - insets.right() + r_width;
const int height = bottom - top;
const int width = right - left;
// |arrow_offset| is offset of arrow from the begining of the edge.
int arrow_offset = arrow_offset_;
if(override_arrow_offset_)
{
arrow_offset = override_arrow_offset_;
}
else if(is_arrow_on_horizontal(arrow_location_) &&
!is_arrow_on_left(arrow_location_))
{
arrow_offset = view.width() - arrow_offset - 1;
}
else if(!is_arrow_on_horizontal(arrow_location_) &&
!is_arrow_on_top(arrow_location_))
{
arrow_offset = view.height() - arrow_offset - 1;
}
// Left edge.
if(arrow_location_==LEFT_TOP || arrow_location_==LEFT_BOTTOM)
{
int start_y = top + tl_height;
int before_arrow = arrow_offset - start_y - left_arrow_->height() / 2;
int after_arrow =
height - tl_height - bl_height - left_arrow_->height() - before_arrow;
DrawArrowInterior(canvas,
false,
left_arrow_->width() - kArrowInteriorHeight,
start_y + before_arrow + left_arrow_->height() / 2,
kArrowInteriorHeight,
left_arrow_->height() / 2 - 1);
DrawEdgeWithArrow(canvas,
false,
left_,
left_arrow_,
left,
start_y,
before_arrow,
after_arrow,
left_->width() - left_arrow_->width());
}
else
{
canvas->TileImageInt(*left_, left, top + tl_height, l_width,
height - tl_height - bl_height);
}
// Top left corner.
canvas->DrawBitmapInt(*top_left_, left, top);
// Top edge.
if(arrow_location_==TOP_LEFT || arrow_location_==TOP_RIGHT)
{
int start_x = left + tl_width;
int before_arrow = arrow_offset - start_x - top_arrow_->width() / 2;
int after_arrow =
width - tl_width - tr_width - top_arrow_->width() - before_arrow;
DrawArrowInterior(canvas,
true,
start_x + before_arrow + top_arrow_->width() / 2,
top_arrow_->height() - kArrowInteriorHeight,
1 - top_arrow_->width() / 2,
kArrowInteriorHeight);
DrawEdgeWithArrow(canvas,
true,
top_,
top_arrow_,
start_x,
top,
before_arrow,
after_arrow,
top_->height() - top_arrow_->height());
}
else
{
canvas->TileImageInt(*top_, left + tl_width, top,
width - tl_width - tr_width, t_height);
}
// Top right corner.
canvas->DrawBitmapInt(*top_right_, right - tr_width, top);
// Right edge.
if(arrow_location_==RIGHT_TOP || arrow_location_==RIGHT_BOTTOM)
{
int start_y = top + tr_height;
int before_arrow = arrow_offset - start_y - right_arrow_->height() / 2;
int after_arrow = height - tl_height - bl_height -
right_arrow_->height() - before_arrow;
DrawArrowInterior(canvas,
false,
right - r_width + kArrowInteriorHeight,
start_y + before_arrow + right_arrow_->height() / 2,
-kArrowInteriorHeight,
right_arrow_->height() / 2 - 1);
DrawEdgeWithArrow(canvas,
false,
right_,
right_arrow_,
right - r_width,
start_y,
before_arrow,
after_arrow,
0);
}
else
{
canvas->TileImageInt(*right_, right - r_width, top + tr_height, r_width,
height - tr_height - br_height);
}
// Bottom right corner.
canvas->DrawBitmapInt(*bottom_right_, right - br_width, bottom - br_height);
// Bottom edge.
if(arrow_location_==BOTTOM_LEFT || arrow_location_==BOTTOM_RIGHT)
{
int start_x = left + bl_width;
int before_arrow = arrow_offset - start_x - bottom_arrow_->width() / 2;
int after_arrow =
width - bl_width - br_width - bottom_arrow_->width() - before_arrow;
DrawArrowInterior(canvas,
true,
start_x + before_arrow + bottom_arrow_->width() / 2,
bottom - b_height + kArrowInteriorHeight,
1 - bottom_arrow_->width() / 2,
-kArrowInteriorHeight);
DrawEdgeWithArrow(canvas,
true,
bottom_,
bottom_arrow_,
start_x,
bottom - b_height,
before_arrow,
after_arrow,
0);
}
else
{
canvas->TileImageInt(*bottom_, left + bl_width, bottom - b_height,
width - bl_width - br_width, b_height);
}
// Bottom left corner.
canvas->DrawBitmapInt(*bottom_left_, left, bottom - bl_height);
}
void BubbleBorder::DrawEdgeWithArrow(gfx::Canvas* canvas,
bool is_horizontal,
SkBitmap* edge,
SkBitmap* arrow,
int start_x,
int start_y,
int before_arrow,
int after_arrow,
int offset) const
{
/* Here's what the parameters mean:
* start_x
* .
* . ┌───┐ ┬ offset
* start_y..........┌────┬────────┤ ▲ ├────────┬────┐
* │ / │--------│∙ ∙│--------│ \ │
* │ / ├────────┴───┴────────┤ \ │
* ├───┬┘ └┬───┤
* └───┬────┘ └───┬────┘
* before_arrow ─┘ └─ after_arrow
*/
if(before_arrow)
{
canvas->TileImageInt(*edge, start_x, start_y,
is_horizontal ? before_arrow : edge->width(),
is_horizontal ? edge->height() : before_arrow);
}
canvas->DrawBitmapInt(*arrow,
start_x + (is_horizontal ? before_arrow : offset),
start_y + (is_horizontal ? offset : before_arrow));
if(after_arrow)
{
start_x += (is_horizontal ? before_arrow + arrow->width() : 0);
start_y += (is_horizontal ? 0 : before_arrow + arrow->height());
canvas->TileImageInt(*edge, start_x, start_y,
is_horizontal ? after_arrow : edge->width(),
is_horizontal ? edge->height() : after_arrow);
}
}
void BubbleBorder::DrawArrowInterior(gfx::Canvas* canvas,
bool is_horizontal,
int tip_x,
int tip_y,
int shift_x,
int shift_y) const
{
/* This function fills the interior of the arrow with background color.
* It draws isosceles triangle under semitransparent arrow tip.
*
* Here's what the parameters mean:
*
* ┌──────── |tip_x|
* ┌─────┐
* │ ▲ │ ──── |tip y|
* │∙∙∙∙∙│ ┐
* └─────┘ └─── |shift_x| (offset from tip to vertexes of isosceles triangle)
* └────────── |shift_y|
*/
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(background_color_);
gfx::Path path;
path.incReserve(4);
path.moveTo(SkIntToScalar(tip_x), SkIntToScalar(tip_y));
path.lineTo(SkIntToScalar(tip_x + shift_x),
SkIntToScalar(tip_y + shift_y));
if(is_horizontal)
{
path.lineTo(SkIntToScalar(tip_x - shift_x), SkIntToScalar(tip_y + shift_y));
}
else
{
path.lineTo(SkIntToScalar(tip_x + shift_x), SkIntToScalar(tip_y - shift_y));
}
path.close();
canvas->AsCanvasSkia()->drawPath(path, paint);
}
void BubbleBackground::Paint(gfx::Canvas* canvas, view::View* view) const
{
// The border of this view creates an anti-aliased round-rect region for the
// contents, which we need to fill with the background color.
// NOTE: This doesn't handle an arrow location of "NONE", which has square top
// corners.
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(border_->background_color());
gfx::Path path;
gfx::Rect bounds(view->GetContentsBounds());
SkRect rect;
rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()),
SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom()));
SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius());
path.addRoundRect(rect, radius, radius);
canvas->AsCanvasSkia()->drawPath(path, paint);
} | 32.558577 | 86 | 0.586841 | topillar |
116f9457a86da21a7f2fab19654a4b143e44117b | 2,654 | cpp | C++ | src/formats/pdb.cpp | danny305/ChargeFW2 | c68fd06b9af244e5d8ed9172de17748e587bf46e | [
"MIT"
] | 7 | 2020-05-19T15:14:15.000Z | 2022-03-03T06:38:09.000Z | src/formats/pdb.cpp | danny305/ChargeFW2 | c68fd06b9af244e5d8ed9172de17748e587bf46e | [
"MIT"
] | 10 | 2021-03-04T21:38:49.000Z | 2022-02-11T07:11:19.000Z | src/formats/pdb.cpp | danny305/ChargeFW2 | c68fd06b9af244e5d8ed9172de17748e587bf46e | [
"MIT"
] | 5 | 2021-03-05T00:42:41.000Z | 2021-07-01T05:47:39.000Z | //
// Created by krab1k on 24.1.19.
//
#include <vector>
#include <fmt/format.h>
#include <gemmi/pdb.hpp>
#include "chargefw2.h"
#include "../config.h"
#include "pdb.h"
#include "common.h"
#include "bonds.h"
#include "../periodic_table.h"
MoleculeSet PDB::read_file(const std::string &filename) {
gemmi::Structure structure;
try {
structure = gemmi::read_pdb_file(filename);
}
catch (std::exception &) {
fmt::print(stderr, "Cannot load structure from file: {}\n", filename);
exit(EXIT_FILE_ERROR);
}
auto molecules = std::make_unique<std::vector<Molecule>>();
auto atoms = std::make_unique<std::vector<Atom>>();
/* Read first model only */
auto model = structure.models[0];
size_t idx = 0;
for (const auto &chain: model.chains) {
for (const auto &residue: chain.residues) {
bool hetatm = residue.het_flag == 'H';
for (const auto &atom: residue.atoms) {
double x = atom.pos.x;
double y = atom.pos.y;
double z = atom.pos.z;
int residue_id = residue.seqid.num.value;
const Element *element;
try {
element = PeriodicTable::pte().get_element_by_symbol(get_element_symbol(atom.element.name()));
} catch (std::exception &e) {
fmt::print(stderr, "Error when reading {}: {}\n", structure.name, e.what());
/* Return empty set */
return MoleculeSet(std::move(molecules));
}
if (not atom.has_altloc() or atom.altloc == 'A') {
if ((not hetatm) or
(config::read_hetatm and residue.name != "HOH") or
(config::read_hetatm and not config::ignore_water)) {
atoms->emplace_back(idx, element, x, y, z, atom.name, residue_id, residue.name, chain.name, hetatm);
atoms->back()._set_formal_charge(atom.charge);
idx++;
}
}
}
}
}
if (atoms->empty()) {
fmt::print(stderr, "Error when reading {}: No atoms were loaded\n", structure.name);
} else {
auto bonds = get_bonds(atoms);
std::string name = structure.name;
auto it = structure.info.find("_entry.id");
if (it != structure.info.end()) {
name = it->second;
}
molecules->emplace_back(sanitize_name(name), std::move(atoms), std::move(bonds));
}
return MoleculeSet(std::move(molecules));
}
PDB::PDB() = default;
| 33.175 | 124 | 0.536549 | danny305 |
117344447aed3b85948f68d21f921c79c258bb8a | 470 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /*
Copyright 2015 NumScale SAS
Copyright 2015 LRI UMR 8623 CNRS/University Paris Sud XI
Copyright 2015 Glen Joseph Fernandes
([email protected])
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_ALIGN_DETAIL_ASSUME_ALIGNED_GCC_HPP
#define BOOST_ALIGN_DETAIL_ASSUME_ALIGNED_GCC_HPP
#define BOOST_ALIGN_ASSUME_ALIGNED(p, n) \
(p) = static_cast<__typeof__(p)>(__builtin_assume_aligned((p), (n)))
#endif
| 26.111111 | 68 | 0.804255 | Harshitha91 |
1176a84637af5773c0babc8ec2b6f993371e3b41 | 15,820 | cpp | C++ | frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp | bigw00d/TrapChecker | 9b36f7fef86928d196637ca958fadcacadb6cf50 | [
"Apache-2.0"
] | null | null | null | frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp | bigw00d/TrapChecker | 9b36f7fef86928d196637ca958fadcacadb6cf50 | [
"Apache-2.0"
] | null | null | null | frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp | bigw00d/TrapChecker | 9b36f7fef86928d196637ca958fadcacadb6cf50 | [
"Apache-2.0"
] | null | null | null | #include "mbed.h"
#define MYDEBUG
#define COMPLETE 1
#define INCOMPLETE 0
#define END_OF_PACKET '\n'
#define SIZE_OF_SEND_PACKET 16
#define CHECK_CHUTTER_US 500000
#define ALERT_CYCLE_SEC 1
#define ARERT_MAX_CNT 60
#define CHECK_CONNECT_SEC 2
#define BUZZER_ON 1
#define BUZZER_OFF 0
#define SW_LED_ON 1
#define SW_LED_OFF 0
#define ALERT_START 1
#define ALERT_STOP 0
// alert "bit" definition
#define ALERT_1 1
#define ALERT_2 2
#define ALERT_3 4
#define ALERT_NON 0
// connect "bit" definition
#define CONNECT_1 1
#define CONNECT_2 2
#define CONNECT_3 4
#define CONNECT_NON 0
#define ON_SIGNAL_1 1
#define ON_SIGNAL_2 2
#define ON_SIGNAL_3 4
#define ON_SIGNAL_NON 0
DigitalOut myled(LED1);
#ifdef MYDEBUG
Serial pc(USBTX, USBRX);
#endif
Serial uart(PTE0, PTE1); // tx, rx
DigitalOut buz(PTA13);
InterruptIn sw1(PTD1);
DigitalOut sw_led1(PTB0);
InterruptIn sw2(PTD5);
DigitalOut sw_led2(PTD0);
InterruptIn sw3(PTD3);
DigitalOut sw_led3(PTD2);
void offBuzzer();
void onBuzzer();
void toggleBuzzer();
void stopAlert1();
void stopAlert2();
void stopAlert3();
void startAlert1();
void startAlert2();
void startAlert3();
void offCheckSignal1();
void offCheckSignal2();
void offCheckSignal3();
uint8_t receiveSize=0;
uint8_t sendSize=0;
uint8_t receiveComplete = INCOMPLETE;
uint8_t sendComplete = INCOMPLETE;
uint8_t rBuffIndex=0;
uint8_t sBuffIndex=0;
char receiveBuff[50];
char sendBuff[50];
Ticker chatTimer;
Ticker AlertTimer;
Ticker CheckConnectTimer;
uint8_t intCnt;
uint8_t intCnt2;
uint8_t intCnt3;
uint8_t buzzer_state=BUZZER_OFF;
uint8_t alert=ALERT_STOP;
uint8_t alert_number=ALERT_NON;
uint8_t alert_cnt=0;
uint8_t check_connect=CONNECT_NON;
uint8_t on_signal=ON_SIGNAL_NON;
void checkConnectCallback() // if go into this func, check connect is failed
{
if((check_connect & CONNECT_1) != 0) {
check_connect &= ~(CONNECT_1);
startAlert1();
}
if((check_connect & CONNECT_2) != 0) {
check_connect &= ~(CONNECT_2);
startAlert2();
}
if((check_connect & CONNECT_3) != 0) {
check_connect &= ~(CONNECT_3);
startAlert3();
}
}
void periodicCallback1() {
chatTimer.detach();
intCnt = 0;
}
void push1() {
if(intCnt == 0) {
if((on_signal & ON_SIGNAL_1) != 0) {
on_signal &= ~(ON_SIGNAL_1);
offCheckSignal1();
}
else if(alert_number == ALERT_NON) {
check_connect &= ~(CONNECT_1);
uart.putc('t'); //check connection message to device 0001
uart.putc('x');
uart.putc('d');
uart.putc('t');
uart.putc(' ');
uart.putc('0');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('0');
uart.putc('2');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('1');
uart.putc('\r');
uart.putc('\n');
CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC);
}
else {
stopAlert1();
}
chatTimer.attach_us(periodicCallback1, CHECK_CHUTTER_US); //start detecting chattering
}
intCnt++;
}
void periodicCallback2() {
chatTimer.detach();
intCnt2 = 0;
}
void push2() {
if(intCnt2 == 0) {
if((on_signal & ON_SIGNAL_2) != 0) {
on_signal &= ~(ON_SIGNAL_2);
offCheckSignal2();
}
else if(alert_number == ALERT_NON) {
check_connect &= ~(CONNECT_2);
uart.putc('t'); //check connection message to device 0002
uart.putc('x');
uart.putc('d');
uart.putc('t');
uart.putc(' ');
uart.putc('0');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('0');
uart.putc('2');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('2');
uart.putc('\r');
uart.putc('\n');
CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC);
}
else {
stopAlert2();
}
chatTimer.attach_us(periodicCallback2, CHECK_CHUTTER_US); //start detecting chattering
}
intCnt2++;
}
void periodicCallback3() {
chatTimer.detach();
intCnt3 = 0;
}
void push3() {
if(intCnt3 == 0) {
if((on_signal & ON_SIGNAL_3) != 0) {
on_signal &= ~(ON_SIGNAL_3);
offCheckSignal3();
}
else if(alert_number == ALERT_NON) {
check_connect &= ~(CONNECT_3);
uart.putc('t'); //check connection message to device 0003
uart.putc('x');
uart.putc('d');
uart.putc('t');
uart.putc(' ');
uart.putc('0');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('0');
uart.putc('2');
uart.putc('0');
uart.putc('1');
uart.putc('0');
uart.putc('3');
uart.putc('\r');
uart.putc('\n');
CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC);
}
else {
stopAlert3();
}
chatTimer.attach_us(periodicCallback3, CHECK_CHUTTER_US); //start detecting chattering
}
intCnt3++;
}
void uartCB(void)
{
char ch;
while(uart.readable())
{
ch = uart.getc();
if(receiveComplete == INCOMPLETE) {
receiveBuff[receiveSize] = ch;
receiveSize++;
if(ch == END_OF_PACKET) {
receiveComplete = COMPLETE;
}
}
}
}
#ifdef MYDEBUG
void pcCB(void)
{
char ch;
while(pc.readable())
{
ch = pc.getc();
pc.putc('['); // 送信
pc.putc(ch); // 送信
sendBuff[sendSize] = ch;
sendSize++;
if(ch == END_OF_PACKET) {
sendComplete = COMPLETE;
}
}
}
#endif
void offBuzzer()
{
buzzer_state = BUZZER_OFF;
buz = BUZZER_OFF;
}
void onBuzzer()
{
buzzer_state = BUZZER_ON;
buz = BUZZER_ON;
}
void toggleBuzzer()
{
if(buzzer_state == BUZZER_OFF) {
onBuzzer();
}
else {
offBuzzer();
}
}
void alertCallback()
{
if(alert_cnt >= ARERT_MAX_CNT) {
offBuzzer();
}
else {
toggleBuzzer();
alert_cnt++;
}
if((alert_number & ALERT_1) != 0) {
sw_led1 = !sw_led1;
}
if((alert_number & ALERT_2) != 0) {
sw_led2 = !sw_led2;
}
if((alert_number & ALERT_3) != 0) {
sw_led3 = !sw_led3;
}
}
void onCheckSignal1()
{
on_signal|=ON_SIGNAL_1;
onBuzzer();
sw_led1 = SW_LED_ON;
}
void onCheckSignal2()
{
on_signal|=ON_SIGNAL_2;
onBuzzer();
sw_led2 = SW_LED_ON;
}
void onCheckSignal3()
{
on_signal|=ON_SIGNAL_3;
onBuzzer();
sw_led3 = SW_LED_ON;
}
void offCheckSignal1()
{
on_signal &= ~(ON_SIGNAL_1);
offBuzzer();
sw_led1 = SW_LED_OFF;
}
void offCheckSignal2()
{
on_signal &= ~(ON_SIGNAL_2);
offBuzzer();
sw_led1 = SW_LED_OFF;
}
void offCheckSignal3()
{
on_signal &= ~(ON_SIGNAL_3);
offBuzzer();
sw_led1 = SW_LED_OFF;
}
void startAlert1()
{
alert_cnt=0;
offBuzzer();
alert_number |= ALERT_1;
sw_led1 = SW_LED_OFF;
sw_led2 = SW_LED_OFF;
sw_led3 = SW_LED_OFF;
if(alert_number == ALERT_1) {
AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC);
}
}
void stopAlert1()
{
sw_led1 = SW_LED_OFF;
alert_number &= ~(ALERT_1);
if(alert_number == ALERT_NON) {
offBuzzer();
AlertTimer.detach();
}
}
void startAlert2()
{
alert_cnt=0;
offBuzzer();
alert_number |= ALERT_2;
sw_led1 = SW_LED_OFF;
sw_led2 = SW_LED_OFF;
sw_led3 = SW_LED_OFF;
if(alert_number == ALERT_2) {
AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC);
}
}
void stopAlert2()
{
sw_led2 = SW_LED_OFF;
alert_number &= ~(ALERT_2);
if(alert_number == ALERT_NON) {
offBuzzer();
AlertTimer.detach();
}
}
void startAlert3()
{
alert_cnt=0;
offBuzzer();
alert_number |= ALERT_3;
sw_led1 = SW_LED_OFF;
sw_led2 = SW_LED_OFF;
sw_led3 = SW_LED_OFF;
if(alert_number == ALERT_3) {
AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC);
}
}
void stopAlert3()
{
sw_led3 = SW_LED_OFF;
alert_number &= ~(ALERT_3);
if(alert_number == ALERT_NON) {
offBuzzer();
AlertTimer.detach();
}
}
int main()
{
receiveSize=0;
sendSize=0;
receiveComplete = INCOMPLETE;
sendComplete = INCOMPLETE;
rBuffIndex=0;
sBuffIndex=0;
myled = 1;
sw_led1 = SW_LED_OFF;
sw_led2 = SW_LED_OFF;
offBuzzer();
alert_number=ALERT_NON;
alert_cnt=0;
check_connect=CONNECT_NON;
on_signal=ON_SIGNAL_NON;
intCnt = 0;
intCnt2 = 0;
intCnt3 = 0;
sw1.mode(PullUp);
sw1.fall(&push1);
sw2.mode(PullUp);
sw2.fall(&push2);
uart.baud (19200);
#ifdef MYDEBUG
pc.baud (9600);
#endif
uart.attach(uartCB , Serial::RxIrq);
#ifdef MYDEBUG
pc.attach(pcCB , Serial::RxIrq);
#endif
while (true) {
sleep(); //wait for interrupt
if(alert == ALERT_START) {
alert = ALERT_STOP;
toggleBuzzer();
if((alert_number & ALERT_1) != 0) {
sw_led1 = !sw_led1;
}
if((alert_number & ALERT_2) != 0) {
sw_led2 = !sw_led2;
}
}
if(receiveComplete == COMPLETE) {
#ifdef MYDEBUG
pc.putc('R');
pc.putc('V');
pc.putc(':');
for(rBuffIndex=0; rBuffIndex<receiveSize; ++rBuffIndex) {
pc.putc(receiveBuff[rBuffIndex]); // 送信
}
#endif
if(receiveSize > 7) {
if(
(receiveBuff[3] == '5') &&
(receiveBuff[4] == '1') &&
(receiveBuff[5] == '7') &&
(receiveBuff[6] == '4')
) {
startAlert1();
}
else if(
(receiveBuff[11] == '0') && // data:0001010010 :normal alert
(receiveBuff[12] == '0') &&
(receiveBuff[14] == '0') &&
(receiveBuff[15] == '1') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '1') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '0') &&
(receiveBuff[23] == '1') &&
(receiveBuff[24] == '0')
) {
startAlert1();
}
else if(
(receiveBuff[11] == '0') && // data:0101010010 :check connection success
(receiveBuff[12] == '1') &&
(receiveBuff[14] == '0') &&
(receiveBuff[15] == '1') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '2') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '0') &&
(receiveBuff[23] == '1') &&
(receiveBuff[24] == '0')
) {
check_connect &= ~(CONNECT_1);
CheckConnectTimer.detach();
onCheckSignal1();
}
else if(
(receiveBuff[11] == '0') && // data:0102010010 :check connection success
(receiveBuff[12] == '1') &&
(receiveBuff[14] == '0') &&
(receiveBuff[15] == '2') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '2') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '0') &&
(receiveBuff[23] == '1') &&
(receiveBuff[24] == '0')
) {
check_connect &= ~(CONNECT_2);
CheckConnectTimer.detach();
onCheckSignal2();
}
else if(
(receiveBuff[11] == '0') && // data:0103010010 :check connection success
(receiveBuff[12] == '1') &&
(receiveBuff[14] == '0') &&
(receiveBuff[15] == '3') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '2') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '0') &&
(receiveBuff[23] == '1') &&
(receiveBuff[24] == '0')
) {
check_connect &= ~(CONNECT_3);
CheckConnectTimer.detach();
onCheckSignal3();
}
else if(
(receiveBuff[11] == '0') && // data:0010030101
(receiveBuff[12] == '0') &&
(receiveBuff[14] == '1') &&
(receiveBuff[15] == '0') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '3') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '1') &&
(receiveBuff[23] == '0') &&
(receiveBuff[24] == '1')
) {
check_connect|=CONNECT_1;
}
else if(
(receiveBuff[11] == '0') && // data:0010030102
(receiveBuff[12] == '0') &&
(receiveBuff[14] == '1') &&
(receiveBuff[15] == '0') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '3') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '1') &&
(receiveBuff[23] == '0') &&
(receiveBuff[24] == '2')
) {
check_connect|=CONNECT_2;
}
else if(
(receiveBuff[11] == '0') && // data:0010030103
(receiveBuff[12] == '0') &&
(receiveBuff[14] == '1') &&
(receiveBuff[15] == '0') &&
(receiveBuff[17] == '0') &&
(receiveBuff[18] == '3') &&
(receiveBuff[20] == '0') &&
(receiveBuff[21] == '1') &&
(receiveBuff[23] == '0') &&
(receiveBuff[24] == '3')
) {
check_connect|=CONNECT_3;
}
}
receiveComplete = INCOMPLETE;
receiveSize = 0;
}
#ifdef MYDEBUG
if(sendComplete == COMPLETE) {
pc.putc('s');
pc.putc('d');
pc.putc(':');
for(sBuffIndex=0; sBuffIndex<sendSize; ++sBuffIndex) {
pc.putc(sendBuff[sBuffIndex]); // 送信
}
for(sBuffIndex=0; sBuffIndex<sendSize; ++sBuffIndex) {
uart.putc(sendBuff[sBuffIndex]); // 送信
}
sendComplete = INCOMPLETE;
sendSize = 0;
}
#endif
}
}
| 26.27907 | 96 | 0.467826 | bigw00d |
1176b2596f2b6d1527e009db7ea27ca5cd96cc89 | 5,877 | cc | C++ | packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | null | null | null | packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | 5 | 2020-07-23T01:09:07.000Z | 2020-09-09T05:32:29.000Z | packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Light Source Software, LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
#include <lse/TextSceneNode.h>
#include <lse/Scene.h>
#include <lse/yoga-ext.h>
#include <lse/Style.h>
#include <lse/CompositeContext.h>
#include <lse/Log.h>
#include <lse/Timer.h>
#include <lse/Renderer.h>
#include <lse/PixelConversion.h>
namespace lse {
TextSceneNode::TextSceneNode(Scene* scene) : SceneNode(scene) {
YGNodeSetMeasureFunc(this->ygNode, SceneNode::YogaMeasureCallback);
YGNodeSetNodeType(this->ygNode, YGNodeTypeText);
}
void TextSceneNode::OnStylePropertyChanged(StyleProperty property) {
switch (property) {
case StyleProperty::fontFamily:
case StyleProperty::fontSize:
case StyleProperty::fontStyle:
case StyleProperty::fontWeight:
case StyleProperty::lineHeight:
case StyleProperty::maxLines:
case StyleProperty::textOverflow:
case StyleProperty::textTransform:
this->MarkComputeStyleDirty();
break;
case StyleProperty::textAlign:
case StyleProperty::borderColor: // TODO: borderColor?
case StyleProperty::color:
case StyleProperty::filter:
this->MarkCompositeDirty();
break;
default:
SceneNode::OnStylePropertyChanged(property);
break;
}
}
void TextSceneNode::OnFlexBoxLayoutChanged() {
this->MarkCompositeDirty();
}
void TextSceneNode::OnComputeStyle() {
if (this->SetFont(this->style)) {
this->block.Invalidate();
YGNodeMarkDirty(this->ygNode);
}
}
YGSize TextSceneNode::OnMeasure(float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) {
if (widthMode == YGMeasureModeUndefined) {
width = this->scene->GetWidth();
}
if (heightMode == YGMeasureModeUndefined) {
height = this->scene->GetHeight();
}
this->block.Shape(this->text, this->fontFace, this->style, this->GetStyleContext(), width, height);
return { this->block.WidthF(), this->block.HeightF() };
}
void TextSceneNode::OnComposite(CompositeContext* ctx) {
this->DrawBackground(ctx, StyleBackgroundClipBorderBox);
this->DrawText(ctx);
this->DrawBorder(ctx);
}
const std::string& TextSceneNode::GetText() const {
return this->text;
}
void TextSceneNode::SetText(std::string&& text) {
if (this->text != text) {
this->text = std::move(text);
this->block.Invalidate();
YGNodeMarkDirty(this->ygNode);
}
}
bool TextSceneNode::SetFont(Style* style) {
auto dirty{ false };
if (!style) {
if (this->fontFace) {
dirty = true;
}
this->ClearFontFaceResource();
return dirty;
}
auto findFontResult = this->scene->GetFontManager()->FindFont(
style->GetString(StyleProperty::fontFamily),
style->GetEnum<StyleFontStyle>(StyleProperty::fontStyle),
style->GetEnum<StyleFontWeight>(StyleProperty::fontWeight));
if (this->fontFace == findFontResult) {
return false;
}
// TODO: ResetFont() ?
this->ClearFontFaceResource();
this->fontFace = findFontResult;
if (!this->fontFace) {
return true;
}
switch (this->fontFace->GetFontStatus()) {
case FontStatusReady:
dirty = true;
break;
case FontStatusLoading:
this->fontFace->AddListener(this, [](Font* font, void* listener, FontStatus status) {
auto self{static_cast<TextSceneNode*>(listener)};
if (status == FontStatusReady) {
self->block.Invalidate();
YGNodeMarkDirty(self->ygNode);
font->RemoveListener(listener);
} else {
self->ClearFontFaceResource();
}
});
break;
default:
// TODO: clear?
this->ClearFontFaceResource();
dirty = true;
break;
}
return dirty;
}
void TextSceneNode::DrawText(CompositeContext* ctx) {
auto box{YGNodeGetPaddingBox(this->ygNode)};
auto textStyle{Style::Or(this->style)};
if (this->block.IsEmpty()) {
// if style width and height are set, measure is not used. if this is the situation, shape the text before paint.
this->block.Shape(this->text, this->fontFace, textStyle, this->GetStyleContext(), box.width, box.height);
}
this->block.Paint(ctx->renderer);
if (!this->block.IsReady()) {
return;
}
Rect pos{
box.x + ctx->CurrentMatrix().GetTranslateX(),
box.y + ctx->CurrentMatrix().GetTranslateY(),
this->block.WidthF(),
this->block.HeightF()
};
switch (textStyle->GetEnum(StyleProperty::textAlign)) {
case StyleTextAlignCenter:
pos.x += ((box.width - pos.width) / 2.f);
break;
case StyleTextAlignRight:
pos.x += (box.width - pos.width);
break;
default:
break;
}
// TODO: clip
auto textColor{ textStyle->GetColor(StyleProperty::color).value_or(ColorBlack) };
ctx->renderer->DrawImage(
pos,
this->block.GetTextureSourceRect(),
this->block.GetTexture(),
this->GetStyleContext()->ComputeFilter(textStyle, textColor, ctx->CurrentOpacity()));
}
void TextSceneNode::ClearFontFaceResource() {
if (this->fontFace) {
this->fontFace->RemoveListener(this);
this->fontFace = nullptr;
}
}
void TextSceneNode::OnDestroy() {
this->ClearFontFaceResource();
this->block.Destroy();
}
// TODO: temporary hack due to scene and renderer shutdown conflicts
void TextSceneNode::OnDetach() {
this->ClearFontFaceResource();
this->block.Destroy();
}
} // namespace lse
| 26.958716 | 118 | 0.68181 | lightsourceengine |
117eb1c55dd42e32b61a599b60b3a8c9c239adc5 | 2,850 | cpp | C++ | trunk/libs/angsys/source/value/boolean.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/angsys/source/value/boolean.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/angsys/source/value/boolean.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include <angsys.h>
using namespace ang;
#define MY_TYPE ang::variable<bool>
#include "ang/inline/object_wrapper_specialization.inl"
#undef MY_TYPE
static collections::pair<castr_t, bool> s_boolean_parsing_map[] =
{
{ "FALSE"_sv, false },
{ "False"_sv, false },
{ "HIGH"_sv, true },
{ "High"_sv, true },
{ "LOW"_sv, false },
{ "Low"_sv, false },
{ "NO"_sv, false },
{ "No"_sv, false },
{ "TRUE"_sv, true },
{ "True"_sv, true },
{ "YES"_sv, true },
{ "Yes"_sv, true },
{ "false"_sv, false },
{ "high"_sv, true },
{ "low"_sv, false },
{ "no"_sv, false },
{ "true"_sv, true },
{ "yes"_sv, true },
};
value<bool> variable<bool>::parse(cstr_t cstr)
{
auto idx = algorithms::binary_search(cstr, collections::to_array(s_boolean_parsing_map));
if (idx >= algorithms::array_size(s_boolean_parsing_map))
return false;
else
return s_boolean_parsing_map[idx].value;
}
string variable<bool>::to_string(value<bool> val, text::text_format_t f_)
{
text::text_format_flags_t f;
f.value = f_.format_flags();
switch (f.target)
{
case text::text_format::bool_:
switch (f.case_)
{
case 2:
switch (f.type)
{
case 1: return val.get() ? "YES"_r : "NO"_r;
case 2: return val.get() ? "HIGH"_r : "LOW"_r;
default: return val.get() ? "TRUE"_r : "FALSE"_r;
}
case 3:
switch (f.type)
{
case 1: return val.get() ? "Yes"_r : "No"_r;
case 2: return val.get() ? "High"_r : "Low"_r;
default: return val.get() ? "True"_r : "False"_r;
}
default:
switch (f.type)
{
case 1: return val.get() ? "yes"_r : "no"_r;
case 2: return val.get() ? "high"_r : "low"_r;
default: return val.get() ? "true"_r : "false"_r;
}
}
case text::text_format::signed_:
return variable<int>::to_string(val.get() ? 1 : 0, f_);
case text::text_format::unsigned_:
return variable<uint>::to_string(val.get() ? 1 : 0, f_);
case text::text_format::float_:
return variable<float>::to_string(val.get() ? 1.0f : 0.0f, f_);
default: return val.get() ? "true"_r : "false"_r;
}
}
variable<bool>::variable()
{
set(false);
}
variable<bool>::variable(bool const& val)
{
set(val);
}
variable<bool>::variable(value<bool> const& val)
{
set(val);
}
variable<bool>::variable(variable const* val)
{
set(val ? val->get() : false);
}
variable<bool>::~variable()
{
}
string variable<bool>::to_string()const
{
return get() ? "true"_r : "false"_r;
}
string variable<bool>::to_string(text::text_format_t f)const
{
return ang::move(to_string(*this, f));
}
rtti_t const& variable<bool>::value_type()const
{
return type_of<bool>();
}
bool variable<bool>::set_value(rtti_t const& id, unknown_t val)
{
return false;
}
bool variable<bool>::get_value(rtti_t const& id, unknown_t val)const
{
return false;
}
variant variable<bool>::clone()const
{
return (ivariable*)new variable<bool>(get());
}
| 20.80292 | 90 | 0.641754 | ChuyX3 |
11802b5c8fb08dfd814d4deb2a3d48d258bcdb8c | 3,986 | cpp | C++ | src/CheckBox.cpp | MStr3am/sfui | 64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4 | [
"BSD-3-Clause"
] | null | null | null | src/CheckBox.cpp | MStr3am/sfui | 64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4 | [
"BSD-3-Clause"
] | null | null | null | src/CheckBox.cpp | MStr3am/sfui | 64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009, Robin RUAUX
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <SFML/Graphics/RenderTarget.hpp>
#include <SFUI/CheckBox.hpp>
namespace sf
{
namespace ui
{
CheckBox::CheckBox(const Unicode::Text& caption)
: Widget(),
mChecked(false),
mDecorator(),
mCaption(caption),
mCheckIcon()
{
SetDefaultStyle("BI_CheckBox");
LoadStyle(GetDefaultStyle());
Add(&mDecorator);
Add(&mCaption);
Add(&mCheckIcon);
//mCheckIcon.AddMouseListener(this);
AddMouseListener(this);
}
void CheckBox::SetChecked(bool checked)
{
mChecked = checked;
LoadStyle((checked) ? GetDefaultStyle() + "_Checked" : GetDefaultStyle());
}
bool CheckBox::IsChecked() const
{
return mChecked;
}
void CheckBox::OnMouseReleased(const Event::MouseButtonEvent& mouse)
{
if (mouse.Button == Mouse::Left)
{
if (mChecked)
{
mChecked = false;
LoadStyle(GetDefaultStyle());
}
else
{
mChecked = true;
LoadStyle(GetDefaultStyle() + "_Checked");
}
}
}
void CheckBox::LoadStyle(const std::string& nameStyle)
{
Widget::LoadStyle(nameStyle);
mDecorator.LoadStyle(nameStyle + "->Background");
mCheckIcon.LoadStyle(nameStyle + "->Icon");
mCaption.LoadStyle(nameStyle + "->Label");
}
void CheckBox::SetText(const Unicode::Text& text)
{
mCaption.SetText(text);
}
const Unicode::Text& CheckBox::GetText() const
{
return mCaption.GetText();
}
void CheckBox::SetFont(const Font& font)
{
mCaption.SetFont(font);
}
const Font& CheckBox::GetFont() const
{
return mCaption.GetFont();
}
void CheckBox::SetTextColor(const Color& color)
{
mCaption.SetColor(color);
}
const Color& CheckBox::GetTextColor() const
{
return mCaption.GetColor();
}
}
}
| 32.145161 | 87 | 0.585549 | MStr3am |
1182aae321619cac6684da397f96b049b85f163c | 1,953 | cpp | C++ | aslam_splines_python/src/QuadraticIntegralError.cpp | Curium-sg/aslam_splines | d2c8c69d28d2f742b1d96a6a4e43a5c5112497af | [
"BSD-3-Clause"
] | null | null | null | aslam_splines_python/src/QuadraticIntegralError.cpp | Curium-sg/aslam_splines | d2c8c69d28d2f742b1d96a6a4e43a5c5112497af | [
"BSD-3-Clause"
] | null | null | null | aslam_splines_python/src/QuadraticIntegralError.cpp | Curium-sg/aslam_splines | d2c8c69d28d2f742b1d96a6a4e43a5c5112497af | [
"BSD-3-Clause"
] | null | null | null | /*
* QuadraticIntegralErrorTerm.cpp
*
* Created on: Dec 4, 2013
* Author: hannes
*/
#include <sstream>
#include <boost/python.hpp>
#include <numpy_eigen/boost_python_headers.hpp>
#include <Eigen/Core>
#include <aslam/backend/QuadraticIntegralError.hpp>
using namespace boost::python;
template <int dim, typename Expression = aslam::backend::VectorExpression<dim>>
inline void addQuadraticIntegralExpressionErrorTerms(aslam::backend::OptimizationProblem & problem, double a, double b, int numberOfPoints, const object & expressionFactory, const Eigen::Matrix<double, dim, dim> & sqrtInvR){
using namespace aslam::backend::integration;
struct ExpressionFactoryAdapter {
ExpressionFactoryAdapter(const object & o) : o(o){}
Expression operator()(double time) const {
return extract<Expression>(o(time));
}
private:
const object & o;
};
addQuadraticIntegralExpressionErrorTerms(problem, a, b, numberOfPoints, ExpressionFactoryAdapter(expressionFactory), sqrtInvR);
}
const char * BaseName = "addQuadraticIntegralExpressionErrorTermsToProblem";
template <int dimMax>
void defAddQuadraticIntegralExpressionErrorTerms(){
std::stringstream s;
s << BaseName << dimMax;
boost::python::def(
s.str().c_str(),
&addQuadraticIntegralExpressionErrorTerms<dimMax>,
boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR")
);
defAddQuadraticIntegralExpressionErrorTerms<dimMax -1>();
}
template <>
void defAddQuadraticIntegralExpressionErrorTerms<0>(){
}
void exportAddQuadraticIntegralExpressionErrorTerms(){
defAddQuadraticIntegralExpressionErrorTerms<3>();
boost::python::def(
"addQuadraticIntegralEuclideanExpressionErrorTermsToProblem",
&addQuadraticIntegralExpressionErrorTerms<3, aslam::backend::EuclideanExpression>,
boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR")
);
}
| 31.5 | 224 | 0.760881 | Curium-sg |
118c65525d22b302d8badb189bc39e171ea277d6 | 4,784 | cpp | C++ | world.cpp | rob05c/cppmud | 2fc4cda4373d273fab49dd23975e278fa39ca28d | [
"MIT"
] | null | null | null | world.cpp | rob05c/cppmud | 2fc4cda4373d273fab49dd23975e278fa39ca28d | [
"MIT"
] | null | null | null | world.cpp | rob05c/cppmud | 2fc4cda4373d273fab49dd23975e278fa39ca28d | [
"MIT"
] | null | null | null | #include <atomic>
#include <algorithm>
#include <thread>
#include <chrono>
#include "world.hpp"
#include "util.hpp"
#include "player.hpp"
#include "dir.hpp"
#include "room.hpp"
#include "object.hpp"
World::World() {
this->self = std::shared_ptr<World>(this);
this->startActorThread();
}
World::~World() {
this->destructing = true;
this->actorThread.join();
this->nextID = 1; // start at 1, so any default-initialized ids are never valid.
}
ID World::NextID() {
return this->nextID.fetch_add(1, std::memory_order_relaxed); // TODO verify order
}
void World::AddRoom(std::shared_ptr<Room> r) {
this->rooms[r->ID] = r;
this->room_links[r->ID] = std::map<Direction, RoomID>();
}
void World::AddPlayer(std::shared_ptr<Player> player, RoomID room_id) {
this->players[player->ID] = player;
this->name_players[player->Name] = player->ID;
this->SetPlayerRoom(player->ID, room_id);
}
void World::AddObject(std::shared_ptr<Object> obj, PlayerID player_id) {
this->objects[obj->ID] = obj;
// TODO handle player not existing. Handle errors everywhere. Go has ruined me.
std::shared_ptr<Player> player = this->GetPlayer(player_id);
player->Objects[obj->ID] = obj;
obj->LocationID.Player = player_id;
obj->LocationType = ObjectLocationPlayer;
}
// LinkRooms links the two rooms in both direction, where the Direction is from room0 to room1.
// TODO add a special function for one-way paths.
void World::LinkRooms(RoomID room0, RoomID room1, Direction dir) {
this->room_links[room0][dir] = room1;
this->room_links[room1][reverse_direction(dir)] = room0;
}
void World::SetPlayerRoom(PlayerID playerID, RoomID newRoomID) {
const auto oldPlayerRoomID = this->player_rooms.find(playerID);
if(oldPlayerRoomID != this->player_rooms.end()) {
auto playerSet = this->room_players.find(oldPlayerRoomID->second);
playerSet->second.erase(playerID); // TODO check and error if world.room_players[room] doesn't exist (should never happen)
}
this->player_rooms[playerID] = newRoomID;
this->room_players[newRoomID].insert(playerID);
}
void World::SetObjectRoom(ObjectID object_id, RoomID new_room_id) {
std::shared_ptr<Object> obj = this->objects[object_id];
switch(obj->LocationType) {
case ObjectLocationRoom: {
RoomID old_room_id = obj->LocationID.Room;
std::shared_ptr<Room> old_room(this->rooms[old_room_id]);
old_room->Objects.erase(object_id);
break;
}
case ObjectLocationPlayer: {
PlayerID player_id = obj->LocationID.Player;
std::shared_ptr<Player> player = this->players[player_id];
player->Objects.erase(object_id);
break;
}
default: {
// TODO handle error; should never happen
return;
}
}
std::shared_ptr<Room> room = this->rooms[new_room_id];
room->Objects[object_id] = obj;
obj->LocationType = ObjectLocationRoom;
obj->LocationID.Room = new_room_id;
// TODO print the move to players in previous and new room
}
void World::startActorThread() {
// TODO change to something lighter weight than an OS thread
// TBB? Microthread? Poll? Something else?
this->actorThread = std::thread([=]() {
for(;;) {
if(this->destructing) {
return;
}
for(auto it = this->objects.begin(), end = this->objects.end(); it != end; ++it) {
std::shared_ptr<Object> obj = it->second;
if(obj->Actor_ == nullptr) {
continue;
}
obj->Actor_->Do(this->GetShared(), obj->ID);
}
std::this_thread::sleep_for(std::chrono::milliseconds(this->ActorThreadIntervalMS));
}
});
}
// GetPlayer returns the player with the given ID.
// If the ID doesn't exist, returns NULL.
std::shared_ptr<Player> World::GetPlayer(PlayerID v) {
return this->players[v];
}
// GetRoom returns the room with the given ID.
// If the ID doesn't exist, returns NULL.
std::shared_ptr<Room> World::GetRoom(RoomID v) {
return this->rooms[v];
}
// GetObject returns the object with the given ID.
// If the ID doesn't exist, returns NULL.
std::shared_ptr<Object> World::GetObject(ObjectID v) {
return this->objects[v];
}
// Returns the room the given player is in.
RoomID World::GetPlayerRoom(PlayerID v) {
// TODO change to return a bool? If a room didn't exist, it would be a subtle bug bug
// But, players should always be in a room, right?
return this->player_rooms[v];
}
std::map<Direction, RoomID> World::GetRoomLinks(RoomID v) {
// TODO change to return a bool? If a room didn't exist, it would be a very subtle bug
return this->room_links[v];
}
PlayerID World::GetPlayerByName(std::string name) {
// TODO change to return a bool? If a player didn't exist, it would be a very subtle bug
return this->name_players[name];
}
std::shared_ptr<World> World::GetShared() {
return self;
}
LockedWorld::LockedWorld(LockableWorld w) {
w.m->lock();
this->w = w.w;
this->l = w;
}
LockedWorld::~LockedWorld() {
l.m->unlock();
}
| 29.170732 | 124 | 0.709448 | rob05c |
1192580c35b8ba8a70cae37da2a7adeb26e3a1d5 | 510 | hpp | C++ | include/mppic/optimization/MotionModel.hpp | SteveMacenski/mppic | 539d78a41777afba0d9a2195b6076a9167ed27a2 | [
"MIT"
] | null | null | null | include/mppic/optimization/MotionModel.hpp | SteveMacenski/mppic | 539d78a41777afba0d9a2195b6076a9167ed27a2 | [
"MIT"
] | null | null | null | include/mppic/optimization/MotionModel.hpp | SteveMacenski/mppic | 539d78a41777afba0d9a2195b6076a9167ed27a2 | [
"MIT"
] | 1 | 2022-03-27T01:44:43.000Z | 2022-03-27T01:44:43.000Z | #pragma once
#include <cstdint>
#include <string>
#include <unordered_map>
namespace mppi::optimization {
enum class MotionModel : uint8_t { Omni, DiffDrive, Carlike };
inline bool isHolonomic(MotionModel motion_model)
{
return (motion_model == MotionModel::Omni) ? true : false;
}
const inline std::unordered_map<std::string, MotionModel> MOTION_MODEL_NAMES_MAP = {
{"diff", MotionModel::DiffDrive}, {"carlike", MotionModel::Carlike}, {"omni", MotionModel::Omni}};
} // namespace mppi::optimization
| 25.5 | 100 | 0.739216 | SteveMacenski |
119a8990fd825c7102acd6c0e0c1397ebc5bd533 | 4,118 | cpp | C++ | import/tests/gamma_by_eye.cpp | HosokawaKenchi/PsychlopsJS | 3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb | [
"MIT"
] | null | null | null | import/tests/gamma_by_eye.cpp | HosokawaKenchi/PsychlopsJS | 3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb | [
"MIT"
] | 3 | 2020-06-06T04:16:06.000Z | 2020-07-24T07:36:06.000Z | import/tests/gamma_by_eye.cpp | psychlopsdev/PsychlopsJS | 3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb | [
"MIT"
] | 1 | 2018-12-17T04:59:11.000Z | 2018-12-17T04:59:11.000Z | #include <psychlops.h>
using namespace Psychlops;
double estimated_gamma = 0;
double gamma_step = 8.0;
var estimate_gamma = function(colorlevel) {
estimated_gamma = 0;
gamma_step = 8.0;
while (0.0001<gamma_step) {
while (0<pow(colorlevel, estimated_gamma) - 0.5) {
estimated_gamma += gamma_step;
}
estimated_gamma -= gamma_step;
gamma_step /= 2.0;
}
estimated_gamma += gamma_step;
return estimated_gamma;
};
void psychlops_main()
{
//// 1 Declaration
// declare default window and variables for its parameters
double CANVAS_FRAMENUM;
int CANVAS_REFRESHRATE;
Canvas cnvs(Canvas::fullscreen);
Widgets::Theme::setLightTheme();
Interval rng;
double Gr, Gb, Gg;
double measured_r = 0.5, measured_g = 0.5, measured_b = 0.5;
Widgets::Dial dial_r, dial_g, dial_b;
dial_r.set(200, 60).centering().shift(-300, 200);
dial_g.set(200, 60).centering().shift(0, 200);
dial_b.set(200, 60).centering().shift(300, 200);
dial_r.link(measured_r, "Red", 0 <= rng < 0.99, 1.0 / 8, 0.5);
dial_g.link(measured_g, "Green", 0 <= rng < 0.99, 1.0 / 8, 0.5);
dial_b.link(measured_b, "Blue", 0 <= rng < 0.99, 1.0 / 8, 0.5);
Widgets::Button endbutton, switchbutton;
endbutton.set(L"キャンセル", 48);
endbutton.centering().shift(cnvs.getWidth()*0.4, cnvs.getHeight()*0.4);
switchbutton.set(L" 次へ ", 48);
switchbutton.centering(cnvs.getHcenter(), dial_g.getBottom() + 200);
//// 2 Initialization
// Set initial values for local variables
CANVAS_REFRESHRATE = cnvs.getRefreshRate();
CANVAS_FRAMENUM = 0;
//// 3 Drawing
Psychlops::Rectangle center_rect(100, 100);
Image grads[3];
Color grads_color[3];
grads_color[0] = Color(1, 0, 0);
grads_color[1] = Color(0, 1, 0);
grads_color[2] = Color(0, 0, 1);
for (int i = 0; i < 3; i++) {
grads[i].set(200, 200);
for (int y = 0; y < 200; y++) {
for (int x = 0; x < 200; x++) {
grads[i].pix(x, y, y % 2 == 0 ? grads_color[i] : Color::black);
}
}
grads[i].cache();
grads[i].centering().shift(-300 + i * 300, 0);
}
int endflag = 0;
Mouse::show();
Psychlops::Letters instruction1(L"それぞれの図形の下のスライダーを調整し、");
Psychlops::Letters instruction2(L"中心の四角とその周りの明るさをできるだけ近づけてください。");
instruction1.centering().shift(0, -300);
instruction2.centering().shift(0, -300 + Psychlops.Font.default_font.size * 1.1);
Figures::ShaderGabor gbr;
gbr.setSigma(200);
gbr.centering();
bool calibrating = true;
int frames = 0;
Psychlops::Color::setGammaValue(1.0, 1.0, 1.0);
// [begin loop]
while (endflag < 1) {
frames++;
if (calibrating) {
cnvs.clear();
dial_r.draw();
dial_g.draw();
dial_b.draw();
if (dial_r.changed()) { Gr = estimate_gamma(measured_r); }
if (dial_g.changed()) { Gg = estimate_gamma(measured_g); }
if (dial_b.changed()) { Gb = estimate_gamma(measured_b); }
if (endflag == 0) {
for (int i = 0; i < 3; i++) { grads[i].shift(0, (frames % 2) * 2 - 1).draw(); }
} else if (endflag == 1) {
for (int i = 0; i < 3; i++) { grads[i].draw(); }
}
center_rect.centering().shift(-300 + 0 * 300, 0);
center_rect.draw(Color(measured_r, 0.0, 0.0));
center_rect.centering().shift(-300 + 1 * 300, 0);
center_rect.draw(Color(0.0, measured_g, 0.0));
center_rect.centering().shift(-300 + 2 * 300, 0);
center_rect.draw(Color(0.0, 0.0, measured_b));
instruction1.draw(Color::white);
instruction2.draw(Color::white);
endbutton.draw();
if (endbutton.pushed()) { endflag = 4; }
switchbutton.draw();
if (switchbutton.pushed()) {
endflag += 1; calibrating = false; frames = 0;
measured_r = 0.5; measured_g = 0.5; measured_b = 0.5;
}
} else {
cnvs.clear();
if (frames > 30) {
calibrating = true;
frames = 0;
}
}
cnvs.flip();
CANVAS_FRAMENUM++;
}
// [end loop]
AppInfo::localSettings["GammaR"] = Gr;
AppInfo::localSettings["GammaG"] = Gg;
AppInfo::localSettings["GammaB"] = Gb;
AppInfo::saveLocalSettings();
//alert("Estimated Gamma:\r\nR: "+Gr+"\r\nG: "+Gg+"\r\nB:"+Gb);
}
| 27.453333 | 84 | 0.616076 | HosokawaKenchi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.