hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a7639aa9219011d216e1f621411328d10d3cf144
5,922
cpp
C++
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
2
2018-03-26T10:49:16.000Z
2019-07-25T12:08:32.000Z
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
null
null
null
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
1
2020-01-30T07:25:25.000Z
2020-01-30T07:25:25.000Z
// Copyright(c) 2019, NVIDIA CORPORATION. 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. // // VulkanHpp Samples : Events // Use basic events #include "../utils/utils.hpp" #include "vulkan/vulkan.hpp" #include <iostream> static char const * AppName = "Events"; static char const * EngineName = "Vulkan.hpp"; int main( int /*argc*/, char ** /*argv*/ ) { try { vk::Instance instance = vk::su::createInstance( AppName, EngineName, {}, vk::su::getInstanceExtensions() ); #if !defined( NDEBUG ) vk::DebugUtilsMessengerEXT debugUtilsMessenger = instance.createDebugUtilsMessengerEXT( vk::su::makeDebugUtilsMessengerCreateInfoEXT() ); #endif vk::PhysicalDevice physicalDevice = instance.enumeratePhysicalDevices().front(); uint32_t graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex( physicalDevice.getQueueFamilyProperties() ); vk::Device device = vk::su::createDevice( physicalDevice, graphicsQueueFamilyIndex ); vk::CommandPool commandPool = vk::su::createCommandPool( device, graphicsQueueFamilyIndex ); vk::CommandBuffer commandBuffer = device.allocateCommandBuffers( vk::CommandBufferAllocateInfo( commandPool, vk::CommandBufferLevel::ePrimary, 1 ) ) .front(); vk::Queue graphicsQueue = device.getQueue( graphicsQueueFamilyIndex, 0 ); /* VULKAN_KEY_START */ // Start with a trivial command buffer and make sure fence wait doesn't time out commandBuffer.begin( vk::CommandBufferBeginInfo( vk::CommandBufferUsageFlags() ) ); commandBuffer.setViewport( 0, vk::Viewport( 0.0f, 0.0f, 10.0f, 10.0f, 0.0f, 1.0f ) ); commandBuffer.end(); vk::Fence fence = device.createFence( vk::FenceCreateInfo() ); vk::SubmitInfo submitInfo( {}, {}, commandBuffer ); graphicsQueue.submit( submitInfo, fence ); // Make sure timeout is long enough for a simple command buffer without waiting for an event vk::Result result; int timeouts = -1; do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); timeouts++; } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); if ( timeouts != 0 ) { std::cout << "Unsuitable timeout value, exiting\n"; exit( -1 ); } // Now create an event and wait for it on the GPU vk::Event event = device.createEvent( vk::EventCreateInfo( vk::EventCreateFlags() ) ); commandBuffer.reset( vk::CommandBufferResetFlags() ); commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.waitEvents( event, vk::PipelineStageFlagBits::eHost, vk::PipelineStageFlagBits::eBottomOfPipe, nullptr, nullptr, nullptr ); commandBuffer.end(); device.resetFences( fence ); // Note that stepping through this code in the debugger is a bad idea because the GPU can TDR waiting for the event. // Execute the code from vk::Queue::submit() through vk::Device::setEvent() without breakpoints graphicsQueue.submit( submitInfo, fence ); // We should timeout waiting for the fence because the GPU should be waiting on the event result = device.waitForFences( fence, true, vk::su::FenceTimeout ); if ( result != vk::Result::eTimeout ) { std::cout << "Didn't get expected timeout in vk::Device::waitForFences, exiting\n"; exit( -1 ); } // Set the event from the CPU and wait for the fence. // This should succeed since we set the event device.setEvent( event ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); commandBuffer.reset( {} ); device.resetFences( fence ); device.resetEvent( event ); // Now set the event from the GPU and wait on the CPU commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.setEvent( event, vk::PipelineStageFlagBits::eBottomOfPipe ); commandBuffer.end(); // Look for the event on the CPU. It should be vk::Result::eEventReset since we haven't sent the command buffer yet. result = device.getEventStatus( event ); assert( result == vk::Result::eEventReset ); // Send the command buffer and loop waiting for the event graphicsQueue.submit( submitInfo, fence ); int polls = 0; do { result = device.getEventStatus( event ); polls++; } while ( result != vk::Result::eEventSet ); printf( "%d polls to find the event set\n", polls ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); device.destroyEvent( event ); device.destroyFence( fence ); /* VULKAN_KEY_END */ device.freeCommandBuffers( commandPool, commandBuffer ); device.destroyCommandPool( commandPool ); device.destroy(); #if !defined( NDEBUG ) instance.destroyDebugUtilsMessengerEXT( debugUtilsMessenger ); #endif instance.destroy(); } catch ( vk::SystemError & err ) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit( -1 ); } catch ( std::exception & err ) { std::cout << "std::exception: " << err.what() << std::endl; exit( -1 ); } catch ( ... ) { std::cout << "unknown error\n"; exit( -1 ); } return 0; }
35.461078
120
0.670719
amaiorano
a7671f70f4843dc4e7cc6c6e9f7638ecc9ec8d1a
800
cpp
C++
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
3
2021-06-05T11:43:44.000Z
2022-03-19T04:03:58.000Z
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
null
null
null
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
2
2020-07-20T06:04:45.000Z
2022-03-19T04:03:57.000Z
#include "pch.h" // enable for visual studio version >= 2019 // #include "stdafx.h" // enable for visual studio version < 2019 #include "GetLastErrorToString.h" GetLastErrorToString::operator CString() { CreateMsg(); return m_msg; } GetLastErrorToString::operator LPCTSTR() { CreateMsg(); return (LPCTSTR)m_msg; } void GetLastErrorToString::CreateMsg() { LPTSTR *buff; m_ID = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, m_ID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, 10, NULL); m_msg.Format(_T("%s"), (TCHAR*)buff); LocalFree(buff); #ifdef UNICODE _RPTW2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #else _RPT2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #endif }
26.666667
188
0.73
nibasya
a767b58cea305262300f3e21ce74318c33292bc1
446
cpp
C++
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
23
2017-01-06T15:31:13.000Z
2021-11-21T13:58:19.000Z
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
3
2021-09-08T09:37:48.000Z
2022-01-19T13:53:20.000Z
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
3
2018-01-16T23:57:51.000Z
2019-11-02T07:44:09.000Z
#include "qak_plugin.h" #include "maskedmousearea.h" #include "propertytoggle.h" #include "resource.h" #include "store.h" #include <qqml.h> void QakPlugin::registerTypes(const char *uri) { // @uri Qak qmlRegisterType<MaskedMouseArea>(uri, 1, 0, "MaskedMouseArea"); qmlRegisterType<Resource>(uri, 1, 0, "Resource"); qmlRegisterType<Store>(uri, 1, 0, "Store"); qmlRegisterType<PropertyToggle>(uri, 1, 0, "PropertyToggle"); }
24.777778
67
0.699552
Larpon
a76921d32cde3d80c4a94502831a99a2d2ba5c9b
9,980
cpp
C++
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(XALAN_BUILD_DEPRECATED_DOM_BRIDGE) // Class header file. #include "FormatterToDeprecatedXercesDOM.hpp" #include <cassert> #include <xercesc/sax/AttributeList.hpp> #if XERCES_VERSION_MAJOR >= 2 #include <xercesc/dom/deprecated/DOM_CDATASection.hpp> #include <xercesc/dom/deprecated/DOM_Comment.hpp> #include <xercesc/dom/deprecated/DOM_EntityReference.hpp> #include <xercesc/dom/deprecated/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/deprecated/DOM_Text.hpp> #else #include <xercesc/dom/DOM_CDATASection.hpp> #include <xercesc/dom/DOM_Comment.hpp> #include <xercesc/dom/DOM_EntityReference.hpp> #include <xercesc/dom/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/DOM_Text.hpp> #endif #include <xalanc/XalanDOM/XalanDOMString.hpp> #include <xalanc/PlatformSupport/DOMStringHelper.hpp> #include <xalanc/PlatformSupport/PrefixResolver.hpp> #include <xalanc/DOMSupport/DOMServices.hpp> #include <xalanc/XercesParserLiaison/XercesDOMException.hpp> namespace XALAN_CPP_NAMESPACE { const XalanDOMString FormatterToDeprecatedXercesDOM::s_emptyString; FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_DocumentFragmentType& docFrag, DOM_ElementType& currentElement) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(docFrag), m_currentElem(currentElement), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0 && m_docFrag != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_ElementType& elem) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(elem), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::~FormatterToDeprecatedXercesDOM() { } void FormatterToDeprecatedXercesDOM::setDocumentLocator(const Locator* const /* locator */) { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::endDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startElement( const XMLCh* const name, AttributeListType& attrs) { try { processAccumulatedText(); DOM_ElementType elem = createElement(name, attrs); append(elem); m_elemStack.push_back(m_currentElem); m_currentElem = elem; } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::endElement(const XMLCh* const /* name */) { try { processAccumulatedText(); if(m_elemStack.empty() == false) { m_currentElem = m_elemStack.back(); m_elemStack.pop_back(); } else { m_currentElem = 0; } } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::characters( const XMLCh* const chars, const unsigned int length) { m_textBuffer.append(chars, length); } void FormatterToDeprecatedXercesDOM::charactersRaw( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); cdata(chars, length); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::entityReference(const XMLCh* const name) { try { processAccumulatedText(); DOM_EntityReferenceType theXercesNode = m_doc.createEntityReference(name); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::ignorableWhitespace( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, chars, length); DOM_TextType theXercesNode = m_doc.createTextNode(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::processingInstruction( const XMLCh* const target, const XMLCh* const data) { try { processAccumulatedText(); DOM_ProcessingInstructionType theXercesNode = m_doc.createProcessingInstruction(target, data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::resetDocument() { } void FormatterToDeprecatedXercesDOM::comment(const XMLCh* const data) { try { processAccumulatedText(); DOM_CommentType theXercesNode = m_doc.createComment(data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::cdata( const XMLCh* const ch, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, ch, length); DOM_CDATASectionType theXercesNode = m_doc.createCDATASection(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::append(DOM_NodeType &newNode) { assert(newNode != 0); if(m_currentElem.isNull() == false) { m_currentElem.appendChild(newNode); } else if(m_docFrag.isNull() == false) { m_docFrag.appendChild(newNode); } else { m_doc.appendChild(newNode); } } DOM_ElementType FormatterToDeprecatedXercesDOM::createElement( const XalanDOMChar* theElementName, AttributeListType& attrs) { DOM_ElementType theElement; if (m_prefixResolver == 0) { theElement = m_doc.createElement(theElementName); addAttributes(theElement, attrs); } else { // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theElementName, *m_prefixResolver, false , m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement = m_doc.createElement(theElementName); } else { theElement = m_doc.createElementNS(theNamespace->c_str(), theElementName); } addAttributes(theElement, attrs); } return theElement; } void FormatterToDeprecatedXercesDOM::addAttributes( DOM_ElementType& theElement, AttributeListType& attrs) { const unsigned int nAtts = attrs.getLength(); if (m_prefixResolver == 0) { for(unsigned int i = 0; i < nAtts; i++) { theElement.setAttribute(attrs.getName(i), attrs.getValue(i)); } } else { for(unsigned int i = 0; i < nAtts; i++) { const XalanDOMChar* const theName = attrs.getName(i); assert(theName != 0); // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theName, *m_prefixResolver, true, m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement.setAttribute(theName, attrs.getValue(i)); } else { theElement.setAttributeNS(theNamespace->c_str(), theName, attrs.getValue(i)); } } } } void FormatterToDeprecatedXercesDOM::processAccumulatedText() { if (m_textBuffer.empty() == false) { DOM_TextType theXercesNode = m_doc.createTextNode(m_textBuffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); clear(m_textBuffer); } } } #endif //XALAN_BUILD_DEPRECATED_DOM_BRIDGE
20.835073
104
0.647295
ulisesten
a76b080776c0582331328d0da8f40a9423bd8258
11,142
cpp
C++
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
/** @file ImmutableListTests.cpp * * Unit tests for pistis::util::ImmutableList */ #include <pistis/util/ImmutableList.hpp> #include <pistis/exceptions/OutOfRangeError.hpp> #include <pistis/testing/Allocator.hpp> #include <gtest/gtest.h> #include <sstream> #include <stdint.h> using namespace pistis::exceptions; using namespace pistis::util; namespace pt = pistis::testing; namespace { typedef ::pt::Allocator<uint32_t> TestAllocator; typedef ImmutableList<uint32_t, TestAllocator> UInt32List; typedef std::vector<uint32_t> TrueList; inline std::string toStr(bool v) { return v ? "true" : "false"; } template <typename T> inline std::unique_ptr<T> make_result(const T& result) { return std::unique_ptr<T>(new T(result)); } template <typename Item, typename Allocator> std::unique_ptr<::testing::AssertionResult> verifyListAccessors( std::unique_ptr<::testing::AssertionResult> prior, const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { if (!*prior) { return std::move(prior); } if (truth.empty() != list.empty()) { return make_result( ::testing::AssertionFailure() << "truth.empty() != list.empty() [ " << toStr(truth.empty()) << " != " << toStr(list.empty()) << " ]" ); } if (truth.size() != list.size()) { return make_result( ::testing::AssertionFailure() << "truth.size() != list.size() [ " << truth.size() << " != " << list.size() << " ]" ); } // list.size() == truth.size() by prior assertion if (!list.size()) { // Don't check front() and back() } else if (truth.front() != list.front()) { return make_result( ::testing::AssertionFailure() << "truth.front() != list.front() [ " << truth.front() << " != " << list.front() << " ]" ); } else if (truth.back() != list.back()) { return make_result( ::testing::AssertionFailure() << "truth.back() != list.back() [ " << truth.back() << " != " << list.back() << " ]" ); } return make_result(::testing::AssertionSuccess()); } template <typename ListIterator, typename TruthIterator> std::unique_ptr<::testing::AssertionResult> verifyRange( std::unique_ptr<::testing::AssertionResult> prior, TruthIterator truthBegin, ListIterator listBegin, ListIterator listEnd) { if (!*prior) { return std::move(prior); } auto i = truthBegin; uint32_t ndx = 0; for (auto j = listBegin; j != listEnd; ++i, ++j, ++ndx) { if (*i != *j) { return make_result( ::testing::AssertionFailure() << "truth[" << ndx << "] (which is " << *i << " ) != list[" << ndx << "] (which is " << *j << ")" ); } } return make_result(::testing::AssertionSuccess()); } template <typename Item, typename Allocator> ::testing::AssertionResult verifyList( const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { std::unique_ptr<::testing::AssertionResult> result = make_result(::testing::AssertionSuccess()); result = verifyListAccessors(std::move(result), truth, list); result = verifyRange(std::move(result), truth.begin(), list.begin(), list.end()); result = verifyRange(std::move(result), truth.cbegin(), list.cbegin(), list.cend()); return *result; } } TEST(ImmutableListTests, CreateEmpty) { const TestAllocator allocator("TEST_1"); UInt32List list(allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(TrueList(), list)); } TEST(ImmutableListTests, CreateFromSingleItem) { const TestAllocator allocator("TEST_1"); UInt32List list(3, 16, allocator); TrueList truth{ 16, 16, 16 }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromLengthAndIterator) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.size(), DATA.begin(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromRange) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.begin(), DATA.end(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromInitializerList) { const TestAllocator allocator("TEST_1"); TrueList truth{ 7, 4, 9, 22, 27 }; UInt32List list{ { 7, 4, 9, 22, 27 }, allocator }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromCopy) { const TestAllocator allocator("TEST_1"); const TestAllocator otherAllocator("TEST_2"); const std::vector<uint32_t> DATA{ 4, 12, 9 }; const TrueList truth(DATA); UInt32List list( DATA.begin(), DATA.end(), allocator); ASSERT_EQ(allocator.name(), list.allocator().name()); ASSERT_TRUE(verifyList(truth, list)); UInt32List copy(list); EXPECT_EQ(allocator.name(), copy.allocator().name()); EXPECT_TRUE(verifyList(truth, copy)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); UInt32List copyWithNewAllocator(list, otherAllocator); EXPECT_EQ(otherAllocator.name(), copyWithNewAllocator.allocator().name()); EXPECT_TRUE(verifyList(truth, copyWithNewAllocator)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, Back) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); EXPECT_EQ(4, list.back()); EXPECT_EQ(4, list.back(0)); EXPECT_EQ(1, list.back(1)); EXPECT_EQ(2, list.back(2)); EXPECT_EQ(3, list.back(3)); } TEST(ImmutableListTests, At) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i != DATA.size(); ++i) { EXPECT_EQ(DATA[i], list.at(i)); } EXPECT_THROW(list.at(list.size()), std::range_error); } TEST(ImmutableListTests, Sublist) { const TestAllocator allocator("TEST_1"); const TrueList truth{3, 4, 5, 6}; UInt32List list{ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, allocator }; UInt32List sublist(list.sublist(3, 7)); EXPECT_EQ(allocator.name(), sublist.allocator().name()); EXPECT_TRUE(verifyList(truth, sublist)); EXPECT_TRUE(verifyList(TrueList(), list.sublist(3, 3))); EXPECT_TRUE(verifyList(TrueList(), list.sublist(10, 10))); EXPECT_THROW(list.sublist(11, 15), OutOfRangeError); EXPECT_THROW(list.sublist(10, 11), OutOfRangeError); EXPECT_THROW(list.sublist( 7, 3), IllegalValueError); } TEST(ImmutableListTests, Concat) { const TestAllocator allocator("TEST_1"); const TrueList trueConcatenated{ 5, 4, 2, 7, 1, 9, 4 }; UInt32List list1{ { 5, 4, 2, 7 }, allocator }; UInt32List list2{ { 1, 9, 4 }, allocator }; UInt32List empty{ allocator }; UInt32List concatenated = list1.concat(list2); EXPECT_EQ(allocator.name(), concatenated.allocator().name()); EXPECT_TRUE(verifyList(trueConcatenated, concatenated)); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, list1.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, empty.concat(list1))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, list2.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, empty.concat(list2))); } TEST(ImmutableListTests, Add) { const TestAllocator allocator("TEST_1"); const TrueList trueOriginal{ 5, 4, 2, 7 }; const TrueList trueAddedToEnd{ 5, 4, 2, 7, 3 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedToEnd, list.add(3))); EXPECT_TRUE(verifyList(trueOriginal, list)); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.add(10))); } TEST(ImmutableListTests, Insert) { const TestAllocator allocator("TEST_1"); const TrueList trueAddedAtStart{ 6, 5, 4, 2, 7 }; const TrueList trueAddedInMiddle{ 5, 4, 1, 2, 7 }; const TrueList trueAddedAtEnd{ 5, 4, 2, 7, 9 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedAtStart, list.insert(0, 6))); EXPECT_TRUE(verifyList(trueAddedInMiddle, list.insert(2, 1))); EXPECT_TRUE(verifyList(trueAddedAtEnd, list.insert(4, 9))); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.insert(0, 10))); } TEST(ImmutableListTests, Remove) { const TestAllocator allocator("TEST_1"); const TrueList trueRemovedAtStart{ 4, 2, 7 }; const TrueList trueRemovedInMiddle{ 5, 4, 7 }; const TrueList trueRemovedAtEnd{ 5, 4, 2 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List oneItem{ { 10 }, allocator }; EXPECT_TRUE(verifyList(trueRemovedAtStart, list.remove(0))); EXPECT_TRUE(verifyList(trueRemovedInMiddle, list.remove(2))); EXPECT_TRUE(verifyList(trueRemovedAtEnd, list.remove(4))); EXPECT_TRUE(verifyList(TrueList{ }, oneItem.remove(0))); } TEST(ImmutableListTests, Replace) { const TestAllocator allocator("TEST_1"); const TrueList trueReplacedAtStart{ 6, 4, 2, 7 }; const TrueList trueReplacedInMiddle{ 5, 4, 9, 7 }; const TrueList trueReplacedAtEnd{ 5, 4, 2, 1 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; EXPECT_TRUE(verifyList(trueReplacedAtStart, list.replace((size_t)0, 6))); EXPECT_TRUE(verifyList(trueReplacedInMiddle, list.replace(2, 9))); EXPECT_TRUE(verifyList(trueReplacedAtEnd, list.replace(3, 1))); } TEST(ImmutableListTests, Map) { const TestAllocator allocator("TEST_1"); const std::vector<std::string> truth{ "5", "2", "7", "13" }; UInt32List list{ { 5, 2, 7, 13 }, allocator }; ImmutableList< std::string, pt::Allocator<std::string> > mapped( list.map([](uint32_t x) { std::ostringstream tmp; tmp << x; return tmp.str(); }) ); EXPECT_EQ(allocator.name(), mapped.allocator().name()); EXPECT_TRUE(verifyList(truth, mapped)); } TEST(ImmutableListTest, Reduce) { UInt32List list{ 5, 2, 7, 13 }; UInt32List emptyList; auto concat = [](const std::string& s, uint32_t x) { std::ostringstream tmp; tmp << s << ", " << x; return tmp.str(); }; auto mix = [](uint32_t x, uint32_t y) { return x * 100 + y; }; EXPECT_EQ("**, 5, 2, 7, 13", list.reduce(concat, "**")); EXPECT_EQ("**", emptyList.reduce(concat, "**")); EXPECT_EQ(5020713, list.reduce(mix)); EXPECT_THROW(emptyList.reduce(mix), IllegalStateError); } TEST(ImmutableListTests, ListEquality) { UInt32List list{ 3, 2, 5, 10, 7 }; UInt32List same{ 3, 2, 5, 10, 7 }; UInt32List different{ 3, 2, 9, 10, 7 }; EXPECT_TRUE(list == same); EXPECT_FALSE(list == different); EXPECT_TRUE(list != different); EXPECT_FALSE(list != same); } TEST(ImmutableListTests, RandomAccess) { const std::vector<uint32_t> DATA{ 3, 2, 5, 10, 7 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i < DATA.size(); ++i) { EXPECT_EQ(DATA[i], list[i]); } }
32.770588
76
0.662179
tomault
a76fb6bb8c0cbb05e44c24489d39382f2cd13ca2
9,138
cpp
C++
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
#include "main.h" #include <natus/application/global.h> #include <natus/application/app.h> #include <natus/tool/imgui/sprite_editor.h> #include <natus/device/global.h> #include <natus/gfx/camera/pinhole_camera.h> #include <natus/graphics/shader/nsl_bridge.hpp> #include <natus/graphics/variable/variable_set.hpp> #include <natus/profile/macros.h> #include <natus/format/global.h> #include <natus/format/nsl/nsl_module.h> #include <natus/geometry/mesh/polygon_mesh.h> #include <natus/geometry/mesh/tri_mesh.h> #include <natus/geometry/mesh/flat_tri_mesh.h> #include <natus/geometry/3d/cube.h> #include <natus/geometry/3d/tetra.h> #include <natus/math/vector/vector3.hpp> #include <natus/math/vector/vector4.hpp> #include <natus/math/matrix/matrix4.hpp> #include <natus/math/utility/angle.hpp> #include <natus/math/utility/3d/transformation.hpp> #include <thread> namespace this_file { using namespace natus::core::types ; class test_app : public natus::application::app { natus_this_typedefs( test_app ) ; private: natus::graphics::async_views_t _graphics ; app::window_async_t _wid_async ; app::window_async_t _wid_async2 ; natus::graphics::state_object_res_t _root_render_states ; natus::gfx::pinhole_camera_t _camera_0 ; natus::io::database_res_t _db ; natus::device::three_device_res_t _dev_mouse ; natus::device::ascii_device_res_t _dev_ascii ; bool_t _do_tool = true ; natus::tool::sprite_editor_res_t _se ; public: test_app( void_t ) { natus::application::app::window_info_t wi ; #if 0 _wid_async = this_t::create_window( "A Render Window", wi, { natus::graphics::backend_type::gl3, natus::graphics::backend_type::d3d11} ) ; _wid_async2 = this_t::create_window( "A Render Window", wi) ; _wid_async.window().position( 50, 50 ) ; _wid_async.window().resize( 800, 800 ) ; _wid_async2.window().position( 50 + 800, 50 ) ; _wid_async2.window().resize( 800, 800 ) ; _graphics = natus::graphics::async_views_t( { _wid_async.async(), _wid_async2.async() } ) ; #else _wid_async = this_t::create_window( "A Render Window", wi ) ; _wid_async.window().resize( 1000, 1000 ) ; #endif _db = natus::io::database_t( natus::io::path_t( DATAPATH ), "./working", "data" ) ; _se = natus::tool::sprite_editor_res_t( natus::tool::sprite_editor_t( _db ) ) ; } test_app( this_cref_t ) = delete ; test_app( this_rref_t rhv ) : app( ::std::move( rhv ) ) { _wid_async = std::move( rhv._wid_async ) ; _wid_async2 = std::move( rhv._wid_async2 ) ; _camera_0 = std::move( rhv._camera_0 ) ; _db = std::move( rhv._db ) ; _graphics = std::move( rhv._graphics ) ; _se = std::move( rhv._se ) ; } virtual ~test_app( void_t ) {} virtual natus::application::result on_event( window_id_t const, this_t::window_event_info_in_t wei ) noexcept { _camera_0.perspective_fov( natus::math::angle<float_t>::degree_to_radian( 90.0f ), float_t(wei.w) / float_t(wei.h), 1.0f, 1000.0f ) ; return natus::application::result::ok ; } private: virtual natus::application::result on_init( void_t ) noexcept { natus::device::global_t::system()->search( [&] ( natus::device::idevice_res_t dev_in ) { if( natus::device::three_device_res_t::castable( dev_in ) ) { _dev_mouse = dev_in ; } else if( natus::device::ascii_device_res_t::castable( dev_in ) ) { _dev_ascii = dev_in ; } } ) ; if( !_dev_mouse.is_valid() ) natus::log::global_t::status( "no three mouse found" ) ; if( !_dev_ascii.is_valid() ) natus::log::global_t::status( "no ascii keyboard found" ) ; { _camera_0.look_at( natus::math::vec3f_t( 0.0f, 60.0f, -50.0f ), natus::math::vec3f_t( 0.0f, 1.0f, 0.0f ), natus::math::vec3f_t( 0.0f, 0.0f, 0.0f )) ; } // root render states { natus::graphics::state_object_t so = natus::graphics::state_object_t( "root_render_states" ) ; { natus::graphics::render_state_sets_t rss ; rss.depth_s.do_change = true ; rss.depth_s.ss.do_activate = false ; rss.depth_s.ss.do_depth_write = false ; rss.polygon_s.do_change = true ; rss.polygon_s.ss.do_activate = true ; rss.polygon_s.ss.ff = natus::graphics::front_face::clock_wise ; rss.polygon_s.ss.cm = natus::graphics::cull_mode::back ; rss.polygon_s.ss.fm = natus::graphics::fill_mode::fill ; so.add_render_state_set( rss ) ; } _root_render_states = std::move( so ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( _root_render_states ) ; } ) ; } { //_se->add_sprite_sheet( "industrial", natus::io::location_t( "images.industrial.industrial.v2.png" ) ) ; //_se->add_sprite_sheet( "enemies", natus::io::location_t( "images.Paper-Pixels-8x8.Enemies.png" ) ) ; //_se->add_sprite_sheet( "player", natus::io::location_t( "images.Player.png" ) ) ; //_se->add_sprite_sheet( "tiles", natus::io::location_t( "images.Tiles.png" ) ) ; _se->add_sprite_sheet( "sprite_sheets", natus::io::location_t( "sprite_sheets.natus" ) ) ; } return natus::application::result::ok ; } float value = 0.0f ; virtual natus::application::result on_update( natus::application::app_t::update_data_in_t ) noexcept { NATUS_PROFILING_COUNTER_HERE( "Update Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_device( natus::application::app_t::device_data_in_t ) noexcept { { natus::device::layouts::ascii_keyboard_t ascii( _dev_ascii ) ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f8 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f9 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f2 ) == natus::device::components::key_state::released ) { _do_tool = !_do_tool ; } } NATUS_PROFILING_COUNTER_HERE( "Device Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_graphics( natus::application::app_t::render_data_in_t ) noexcept { // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.push( _root_render_states ) ; } ) ; } // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.pop( natus::graphics::backend::pop_type::render_state ); } ) ; } NATUS_PROFILING_COUNTER_HERE( "Render Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_tool( natus::tool::imgui_view_t imgui ) noexcept { if( !_do_tool ) return natus::application::result::no_imgui ; { bool_t show_demo = true ; ImGui::ShowDemoWindow( &show_demo ) ; } _se->do_tool( imgui ) ; return natus::application::result::ok ; } virtual natus::application::result on_shutdown( void_t ) noexcept { return natus::application::result::ok ; } }; natus_res_typedef( test_app ) ; } int main( int argc, char ** argv ) { return natus::application::global_t::create_application( this_file::test_app_res_t( this_file::test_app_t() ) )->exec() ; }
36.552
121
0.552637
aconstlink
a770b77f699c26e5194a4be7cadaf389a2a99c75
7,019
cc
C++
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
1
2017-03-13T15:51:22.000Z
2017-03-13T15:51:22.000Z
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
null
null
null
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
null
null
null
// // Copyright (C) 2004 Andras Varga // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/transportlayer/tcp_common/TCPSegment.h" namespace inet { namespace tcp { Register_Class(Sack); bool Sack::empty() const { return start_var == 0 && end_var == 0; } bool Sack::contains(const Sack& other) const { return seqLE(start_var, other.start_var) && seqLE(other.end_var, end_var); } void Sack::clear() { start_var = end_var = 0; } void Sack::setSegment(unsigned int start_par, unsigned int end_par) { setStart(start_par); setEnd(end_par); } std::string Sack::str() const { std::stringstream out; out << "[" << start_var << ".." << end_var << ")"; return out.str(); } Register_Class(TCPSegment); uint32_t TCPSegment::getSegLen() { return payloadLength_var + (finBit_var ? 1 : 0) + (synBit_var ? 1 : 0); } void TCPSegment::truncateSegment(uint32 firstSeqNo, uint32 endSeqNo) { ASSERT(payloadLength_var > 0); // must have common part: #ifndef NDEBUG if (!(seqLess(sequenceNo_var, endSeqNo) && seqLess(firstSeqNo, sequenceNo_var + payloadLength_var))) { throw cRuntimeError(this, "truncateSegment(%u,%u) called on [%u, %u) segment\n", firstSeqNo, endSeqNo, sequenceNo_var, sequenceNo_var + payloadLength_var); } #endif // ifndef NDEBUG unsigned int truncleft = 0; unsigned int truncright = 0; if (seqLess(sequenceNo_var, firstSeqNo)) { truncleft = firstSeqNo - sequenceNo_var; } if (seqGreater(sequenceNo_var + payloadLength_var, endSeqNo)) { truncright = sequenceNo_var + payloadLength_var - endSeqNo; } truncateData(truncleft, truncright); } unsigned short TCPSegment::getHeaderOptionArrayLength() { unsigned short usedLength = 0; for (uint i = 0; i < getHeaderOptionArraySize(); i++) usedLength += getHeaderOption(i)->getLength(); return usedLength; } TCPSegment& TCPSegment::operator=(const TCPSegment& other) { if (this == &other) return *this; clean(); TCPSegment_Base::operator=(other); copy(other); return *this; } void TCPSegment::copy(const TCPSegment& other) { for (const auto & elem : other.payloadList) addPayloadMessage(elem.msg->dup(), elem.endSequenceNo); for (const auto opt: other.headerOptionList) addHeaderOption(opt->dup()); } TCPSegment::~TCPSegment() { clean(); } void TCPSegment::clean() { dropHeaderOptions(); while (!payloadList.empty()) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } } void TCPSegment::truncateData(unsigned int truncleft, unsigned int truncright) { ASSERT(payloadLength_var >= truncleft + truncright); if (0 != byteArray_var.getDataArraySize()) byteArray_var.truncateData(truncleft, truncright); while (!payloadList.empty() && (payloadList.front().endSequenceNo - sequenceNo_var) <= truncleft) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } sequenceNo_var += truncleft; payloadLength_var -= truncleft + truncright; // truncate payload data correctly while (!payloadList.empty() && (payloadList.back().endSequenceNo - sequenceNo_var) > payloadLength_var) { cPacket *msg = payloadList.back().msg; payloadList.pop_back(); dropAndDelete(msg); } } void TCPSegment::parsimPack(cCommBuffer *b) PARSIMPACK_CONST { TCPSegment_Base::parsimPack(b); b->pack((int)headerOptionList.size()); for (const auto opt: headerOptionList) { b->packObject(opt); } b->pack((int)payloadList.size()); for (PayloadList::const_iterator it = payloadList.begin(); it != payloadList.end(); it++) { b->pack(it->endSequenceNo); b->packObject(it->msg); } } void TCPSegment::parsimUnpack(cCommBuffer *b) { TCPSegment_Base::parsimUnpack(b); int i, n; b->unpack(n); for (i = 0; i < n; i++) { TCPOption *opt = check_and_cast<TCPOption*>(b->unpackObject()); headerOptionList.push_back(opt); } b->unpack(n); for (i = 0; i < n; i++) { TCPPayloadMessage payload; b->unpack(payload.endSequenceNo); payload.msg = check_and_cast<cPacket*>(b->unpackObject()); payloadList.push_back(payload); } } void TCPSegment::setPayloadArraySize(unsigned int size) { throw cRuntimeError(this, "setPayloadArraySize() not supported, use addPayloadMessage()"); } unsigned int TCPSegment::getPayloadArraySize() const { return payloadList.size(); } TCPPayloadMessage& TCPSegment::getPayload(unsigned int k) { auto i = payloadList.begin(); while (k > 0 && i != payloadList.end()) (++i, --k); if (i == payloadList.end()) throw cRuntimeError("Model error at getPayload(): index out of range"); return *i; } void TCPSegment::setPayload(unsigned int k, const TCPPayloadMessage& payload_var) { throw cRuntimeError(this, "setPayload() not supported, use addPayloadMessage()"); } void TCPSegment::addPayloadMessage(cPacket *msg, uint32 endSequenceNo) { take(msg); TCPPayloadMessage payload; payload.endSequenceNo = endSequenceNo; payload.msg = msg; payloadList.push_back(payload); } cPacket *TCPSegment::removeFirstPayloadMessage(uint32& endSequenceNo) { if (payloadList.empty()) return nullptr; cPacket *msg = payloadList.front().msg; endSequenceNo = payloadList.front().endSequenceNo; payloadList.pop_front(); drop(msg); return msg; } void TCPSegment::addHeaderOption(TCPOption *option) { headerOptionList.push_back(option); } void TCPSegment::setHeaderOptionArraySize(unsigned int size) { throw cRuntimeError(this, "setHeaderOptionArraySize() not supported, use addHeaderOption()"); } unsigned int TCPSegment::getHeaderOptionArraySize() const { return headerOptionList.size(); } TCPOptionPtr& TCPSegment::getHeaderOption(unsigned int k) { return headerOptionList.at(k); } void TCPSegment::setHeaderOption(unsigned int k, const TCPOptionPtr& headerOption) { throw cRuntimeError(this, "setHeaderOption() not supported, use addHeaderOption()"); } void TCPSegment::dropHeaderOptions() { for (auto opt : headerOptionList) delete opt; headerOptionList.clear(); } } // namespace tcp } // namespace inet
25.805147
109
0.682576
StarStuffSteve
a77174a760f57f32c171183044d4196695837821
505
cpp
C++
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
null
null
null
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
2
2016-01-07T00:03:00.000Z
2016-01-25T21:08:00.000Z
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
2
2015-11-29T06:02:19.000Z
2021-03-29T06:00:22.000Z
#include "gtest/gtest.h" #include <string> #include "csimsbw.h" #include "csim/error_codes.h" // generated with test resource locations #include "test_resources.h" TEST(SBW, model_string) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); EXPECT_NE(std::string(modelString), ""); }
22.954545
71
0.659406
OpenCMISS-Dependencies
a777ace1664fd926477699b879b9b96a9a4f2e1d
1,822
cpp
C++
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
2
2020-11-16T08:06:30.000Z
2021-06-18T03:21:44.000Z
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
// Copyright © 2017-2020 Khaos Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Signer.h" #include "Address.h" #include "../PublicKey.h" using namespace TW; using namespace TW::Algorand; const Data TRANSACTION_TAG = {84, 88}; const std::string TRANSACTION_PAY = "pay"; Proto::SigningOutput Signer::sign(const Proto::SigningInput &input) noexcept { auto protoOutput = Proto::SigningOutput(); auto key = PrivateKey(Data(input.private_key().begin(), input.private_key().end())); auto pubkey = key.getPublicKey(TWPublicKeyTypeED25519); auto from = Address(pubkey); auto note = Data(input.note().begin(), input.note().end()); auto genesisId = input.genesis_id(); auto genesisHash = Data(input.genesis_hash().begin(), input.genesis_hash().end()); if (input.has_transaction_pay()) { auto message = input.transaction_pay(); auto to = Address(message.to_address()); auto transaction = Transaction(from, to, message.fee(), message.amount(), message.first_round(), message.last_round(), note, TRANSACTION_PAY, genesisId, genesisHash); auto signature = sign(key, transaction); auto serialized = transaction.serialize(signature); protoOutput.set_encoded(serialized.data(), serialized.size()); } return protoOutput; } Data Signer::sign(const PrivateKey &privateKey, Transaction &transaction) noexcept { Data data; append(data, TRANSACTION_TAG); append(data, transaction.serialize()); auto signature = privateKey.sign(data, TWCurveED25519); return Data(signature.begin(), signature.end()); }
38.765957
104
0.694841
Khaos-Labs
a77823a4d029474d69084e3fa30e4490328e92a6
748
cpp
C++
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
/* Given an integer array of size n, find all elements that appear more than ? n/3 ? times. Note: The algorithm should run in linear time and in O(1) space. Runtime: 16 ms, faster than 87.33% of C++ online submissions for Majority Element II. Memory Usage: 10.7 MB, less than 50.89% of C++ online submissions for Majority Element II. */ class Solution { public: vector<int> majorityElement(vector<int>& nums) { vector<int> result; if (nums.size() == 0) return result; int min_bound = nums.size() / 3; //use hash unordered_map<int, int> mymap; for (const int& x : nums) { ++mymap[x]; } for (auto p : mymap) { if (p.second > min_bound) result.push_back(p.first); } sort(result.begin(), result.end()); return result; } };
27.703704
90
0.673797
Hussein-A
a778c2ff335d175f25a2d199f1367bda500ad831
2,934
cc
C++
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
#include "PCU.h" #include "parma_dcpart.h" #include "parma_commons.h" #include "parma_convert.h" #include <maximalIndependentSet/mis.h> #include <pcu_util.h> typedef std::map<unsigned, unsigned> muu; namespace { bool isInMis(muu& mt) { unsigned seed = TO_UINT(PCU_Comm_Self()+1); mis_init(seed); misLuby::partInfo part; part.id = PCU_Comm_Self(); std::set<int> targets; APF_ITERATE(muu, mt, mtItr) { int peer = TO_INT(mtItr->second); if( !targets.count(peer) ) { part.adjPartIds.push_back(peer); part.net.push_back(peer); targets.insert(peer); } } part.net.push_back(part.id); return mis(part,false,true); } } class dcPartFixer::PartFixer : public dcPart { public: PartFixer(apf::Mesh* mesh, unsigned verbose=0) : dcPart(mesh,verbose), m(mesh), vb(verbose) { fix(); } private: apf::Mesh* m; unsigned vb; int totNumDc() { int ndc = TO_INT(numDisconnectedComps()); return PCU_Add_Int(ndc); } void setupPlan(muu& dcCompTgts, apf::Migration* plan) { apf::MeshEntity* e; apf::MeshIterator* itr = m->begin(m->getDimension()); while( (e = m->iterate(itr)) ) { if( isIsolated(e) ) continue; unsigned id = compId(e); if ( dcCompTgts.count(id) ) plan->send(e, TO_INT(dcCompTgts[id])); } m->end(itr); } /** * @brief remove the disconnected set(s) of elements from the part * @remark migrate the disconnected set(s) of elements into the adjacent part * that shares the most faces with the disconnected set of elements * requires that the sets of elements forming disconnected components * are tagged */ void fix() { double t1 = PCU_Time(); int loop = 0; int ndc = 0; while( (ndc = totNumDc()) && loop++ < 50 ) { double t2 = PCU_Time(); muu dcCompTgts; unsigned maxSz = 0; for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) > maxSz ) maxSz = getCompSize(i); for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) != maxSz ) dcCompTgts[i] = getCompPeer(i); PCU_ALWAYS_ASSERT( dcCompTgts.size() == getNumComps()-1 ); apf::Migration* plan = new apf::Migration(m); if ( isInMis(dcCompTgts) ) setupPlan(dcCompTgts, plan); reset(); double t3 = PCU_Time(); m->migrate(plan); if( ! PCU_Comm_Self() && vb) parmaCommons::status( "loop %d components %d seconds <fix migrate> %.3f %.3f\n", loop, ndc, t3-t2, PCU_Time()-t3); } parmaCommons::printElapsedTime(__func__, PCU_Time() - t1); } }; dcPartFixer::dcPartFixer(apf::Mesh* mesh, unsigned verbose) : pf( new PartFixer(mesh,verbose) ) {} dcPartFixer::~dcPartFixer() { delete pf; }
27.942857
81
0.582481
Thomas-Ulrich
a77959f0e89a7b99097f2af7afbdd048e8b7d490
2,457
cc
C++
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
24
2015-07-22T05:07:51.000Z
2019-02-28T04:52:33.000Z
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T05:43:02.000Z
2021-07-17T17:14:45.000Z
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T01:07:30.000Z
2021-01-05T09:49:30.000Z
/* * * Copyright (C) 1997-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: ofstd * * Author: Andreas Barth * * Purpose: test programm for class OFStack * * Last Update: $Author: joergr $ * Update Date: $Date: 2010-10-14 13:15:16 $ * CVS/RCS Revision: $Revision: 1.11 $ * Status: $State: Exp $ * * CVS/RCS Log at end of file * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/ofstd/ofstream.h" #include "dcmtk/ofstd/ofstack.h" #include "dcmtk/ofstd/ofconsol.h" int main() { OFStack<int> st; st.push(1); st.push(2); st.push(3); OFStack<int> nst(st); COUT << "Output of number of Elements in st: " << st.size() << OFendl; COUT << "Output and deletion of st: "; while(!st.empty()) { COUT << st.top() << " "; st.pop(); } COUT << OFendl; COUT << "Output of number of Elements in copy from st: " << nst.size() << OFendl; COUT << "Output and deletion of copy from st: "; while(!nst.empty()) { COUT << nst.top() << " "; nst.pop(); } COUT << OFendl; } /* ** ** CVS/RCS Log: ** $Log: tststack.cc,v $ ** Revision 1.11 2010-10-14 13:15:16 joergr ** Updated copyright header. Added reference to COPYRIGHT file. ** ** Revision 1.10 2006/08/14 16:42:48 meichel ** Updated all code in module ofstd to correctly compile if the standard ** namespace has not included into the global one with a "using" directive. ** ** Revision 1.9 2005/12/08 15:49:11 meichel ** Changed include path schema for all DCMTK header files ** ** Revision 1.8 2004/01/16 10:37:23 joergr ** Removed acknowledgements with e-mail addresses from CVS log. ** ** Revision 1.7 2002/04/16 13:37:01 joergr ** Added configurable support for C++ ANSI standard includes (e.g. streams). ** ** Revision 1.6 2001/06/01 15:51:41 meichel ** Updated copyright header ** ** Revision 1.5 2000/03/08 16:36:08 meichel ** Updated copyright header. ** ** Revision 1.4 2000/03/03 14:02:53 meichel ** Implemented library support for redirecting error messages into memory ** instead of printing them to stdout/stderr for GUI applications. ** ** Revision 1.3 1998/11/27 12:42:11 joergr ** Added copyright message to source files and changed CVS header. ** ** ** */
24.57
85
0.638991
chrisvana
a779e73de1486642d329cc195c088afd6bc82c0c
9,172
cpp
C++
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file gpuinterpolationitem.cpp * @author Lars Debor <lars.debor@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date October, 2017 * * @section LICENSE * * Copyright (C) 2017, Lars Debor and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief GpuInterpolationItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "gpuinterpolationitem.h" #include "../../materials/gpuinterpolationmaterial.h" #include "../../3dhelpers/custommesh.h" #include <mne/mne_bem_surface.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <Qt3DCore/QEntity> #include <Qt3DCore/QTransform> #include <Qt3DRender/QComputeCommand> #include <Qt3DRender/QAttribute> #include <Qt3DRender/QGeometryRenderer> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace Qt3DRender; using namespace Qt3DCore; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= GpuInterpolationItem::GpuInterpolationItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : Abstract3DTreeItem(p3DEntityParent, iType, text) , m_bIsDataInit(false) , m_pMaterial(new GpuInterpolationMaterial) { initItem(); } //************************************************************************************************************* void GpuInterpolationItem::initData(const MNELIB::MNEBemSurface &tMneBemSurface, QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == true) { qDebug("GpuInterpolationItem::initData data already initialized"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); //Create draw entity if needed if(!m_pMeshDrawEntity) { m_pMeshDrawEntity = new QEntity(this); m_pCustomMesh = new CustomMesh; //Interpolated signal attribute QAttribute *pInterpolatedSignalAttrib = new QAttribute; pInterpolatedSignalAttrib->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); pInterpolatedSignalAttrib->setDataType(Qt3DRender::QAttribute::Float); pInterpolatedSignalAttrib->setVertexSize(4); pInterpolatedSignalAttrib->setByteOffset(0); pInterpolatedSignalAttrib->setByteStride(4 * sizeof(float)); pInterpolatedSignalAttrib->setName(QStringLiteral("OutputColor")); pInterpolatedSignalAttrib->setBuffer(m_pMaterial->getOutputColorBuffer()); //add interpolated signal Attribute m_pCustomMesh->addAttribute(pInterpolatedSignalAttrib); m_pMeshDrawEntity->addComponent(m_pCustomMesh); m_pMeshDrawEntity->addComponent(m_pMaterial); } //Create compute entity if needed if(!m_pComputeEntity) { m_pComputeEntity = new QEntity(this); m_pComputeCommand = new QComputeCommand; m_pComputeEntity->addComponent(m_pComputeCommand); m_pComputeEntity->addComponent(m_pMaterial); } const uint iWeightMatRows = tMneBemSurface.rr.rows(); //Set work group size const uint iWorkGroupsSize = static_cast<uint>(std::ceil(std::sqrt(iWeightMatRows))); m_pComputeCommand->setWorkGroupX(iWorkGroupsSize); m_pComputeCommand->setWorkGroupY(iWorkGroupsSize); m_pComputeCommand->setWorkGroupZ(1); //Set custom mesh data //generate mesh base color QColor baseColor = QColor(80, 80, 80, 255); MatrixX3f matVertColor(tMneBemSurface.rr.rows(),3); for(int i = 0; i < matVertColor.rows(); ++i) { matVertColor(i,0) = baseColor.redF(); matVertColor(i,1) = baseColor.greenF(); matVertColor(i,2) = baseColor.blueF(); } //Set renderable 3D entity mesh and color data m_pCustomMesh->setMeshData(tMneBemSurface.rr, tMneBemSurface.nn, tMneBemSurface.tris, matVertColor, Qt3DRender::QGeometryRenderer::Triangles); m_bIsDataInit = true; } //************************************************************************************************************* void GpuInterpolationItem::setWeightMatrix(QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == false) { qDebug("GpuInterpolationItem::setWeightMatrix item data is not initialized!"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); } //************************************************************************************************************* void GpuInterpolationItem::addNewRtData(const VectorXf &tSignalVec) { if(m_pMaterial && m_bIsDataInit) { m_pMaterial->addSignalData(tSignalVec); } } //************************************************************************************************************* void GpuInterpolationItem::setNormalization(const QVector3D &tVecThresholds) { m_pMaterial->setNormalization(tVecThresholds); } //************************************************************************************************************* void GpuInterpolationItem::setColormapType(const QString &tColormapType) { m_pMaterial->setColormapType(tColormapType); } //************************************************************************************************************* void GpuInterpolationItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip(this->text()); } //*************************************************************************************************************
39.878261
116
0.490188
ChunmingGu
a77b539c8e18e780822445d43a7e28e2c127b9e6
25,800
inl
C++
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
/// @file /// /// Copyright Matus Chochlik. /// 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 <eagine/app/context.hpp> #include <eagine/extract.hpp> #include <eagine/integer_range.hpp> #include <eagine/logging/type/yes_no_maybe.hpp> #include <eagine/maybe_unused.hpp> #include <eagine/oglplus/config/basic.hpp> #include <eagine/valid_if/decl.hpp> #include <eagine/eglplus/egl.hpp> #include <eagine/eglplus/egl_api.hpp> namespace eagine::app { //------------------------------------------------------------------------------ // surface //------------------------------------------------------------------------------ class eglplus_opengl_surface : public main_ctx_object , public video_provider { public: eglplus_opengl_surface(main_ctx_parent parent, eglplus::egl_api& egl) : main_ctx_object{EAGINE_ID(EGLPbuffer), parent} , _egl_api{egl} {} auto get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options&) const -> std::vector<eglplus::egl_types::int_type>; auto initialize( execution_context&, const eglplus::display_handle, const eglplus::egl_types::config_type, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const eglplus::display_handle, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const identifier instance, const launch_options&, const video_options&) -> bool; void clean_up(); auto video_kind() const noexcept -> video_context_kind final; auto instance_id() const noexcept -> identifier final; auto is_offscreen() noexcept -> tribool final; auto has_framebuffer() noexcept -> tribool final; auto surface_size() noexcept -> std::tuple<int, int> final; auto surface_aspect() noexcept -> float final; void parent_context_changed(const video_context&) final; void video_begin(execution_context&) final; void video_end(execution_context&) final; void video_commit(execution_context&) final; private: eglplus::egl_api& _egl_api; identifier _instance_id; eglplus::display_handle _display{}; eglplus::surface_handle _surface{}; eglplus::context_handle _context{}; int _width{1}; int _height{1}; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options& video_opts) const -> std::vector<eglplus::egl_types::int_type> { const auto& EGL = _egl_api.constants(); const auto add_major_version = [&](auto attribs) { return attribs + (EGL.context_major_version | (video_opts.gl_version_major() / 3)); }; const auto add_minor_version = [&](auto attribs) { eglplus::context_attrib_traits::value_type fallback = 0; if(gl_otherwise_gles) { if(!video_opts.gl_compatibility_context()) { fallback = 3; } } return attribs + (EGL.context_minor_version | (video_opts.gl_version_minor() / fallback)); }; const auto add_profile_mask = [&](auto attribs) { const auto compat = video_opts.gl_compatibility_context(); if(compat) { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_compatibility_profile_bit); } else { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_core_profile_bit); } }; const auto add_debugging = [&](auto attribs) { return attribs + (EGL.context_opengl_debug | video_opts.gl_debug_context()); }; const auto add_robustness = [&](auto attribs) { return attribs + (EGL.context_opengl_robust_access | video_opts.gl_robust_access()); }; return add_robustness( add_debugging(add_profile_mask(add_minor_version( add_major_version(eglplus::context_attribute_base()))))) .copy(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const eglplus::egl_types::config_type config, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; const auto apis{egl.get_client_api_bits(display)}; const bool has_gl = apis.has(EGL.opengl_bit); const bool has_gles = apis.has(EGL.opengl_es_bit); if(!has_gl && !has_gles) { log_info("display does not support any OpenAPI APIs;skipping"); return false; } log_info("display device supports GL APIs") .arg(EAGINE_ID(OpenGL), yes_no_maybe(has_gl)) .arg(EAGINE_ID(OpenGL_ES), yes_no_maybe(has_gles)) .arg(EAGINE_ID(PreferES), yes_no_maybe(video_opts.prefer_gles())); const bool gl_otherwise_gles = has_gl && !video_opts.prefer_gles(); _width = video_opts.surface_width() / 1; _height = video_opts.surface_height() / 1; const auto surface_attribs = (EGL.width | _width) + (EGL.height | _height); if(ok surface{ egl.create_pbuffer_surface(display, config, surface_attribs)}) { _surface = surface; const auto gl_api = gl_otherwise_gles ? eglplus::client_api(EGL.opengl_api) : eglplus::client_api(EGL.opengl_es_api); if(ok bound{egl.bind_api(gl_api)}) { const auto context_attribs = get_context_attribs( exec_ctx, gl_otherwise_gles, opts, video_opts); if(ok ctxt{egl.create_context( display, config, eglplus::context_handle{}, view(context_attribs))}) { _context = ctxt; return true; } else { log_error("failed to create context") .arg(EAGINE_ID(message), (!ctxt).message()); } } else { log_error("failed to bind OpenGL API") .arg(EAGINE_ID(message), (!bound).message()); } } else { log_error("failed to create pbuffer ${width}x${height}") .arg(EAGINE_ID(width), _width) .arg(EAGINE_ID(height), _height) .arg(EAGINE_ID(message), (!surface).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; if(device_idx) { log_info("trying EGL device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { exec_ctx.log_info("trying default EGL display device"); } if(ok initialized{egl.initialize(display)}) { if(auto conf_driver_name{video_opts.driver_name()}) { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { if(are_equal( extract(video_opts.driver_name()), extract(driver_name))) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } else { log_info( "${current} does not match the configured " "${config} display driver; skipping") .arg( EAGINE_ID(current), EAGINE_ID(Identifier), extract(driver_name)) .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { log_error("failed to get EGL display driver name"); return false; } } else { log_info( "cannot determine current display driver to match " "with configured ${config} driver; skipping") .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } } } _display = display; const auto config_attribs = (EGL.red_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.green_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.blue_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.alpha_size | (video_opts.alpha_bits() / EGL.dont_care)) + (EGL.depth_size | (video_opts.depth_bits() / EGL.dont_care)) + (EGL.stencil_size | (video_opts.stencil_bits() / EGL.dont_care)) + (EGL.color_buffer_type | EGL.rgb_buffer) + (EGL.surface_type | EGL.pbuffer_bit) + (EGL.renderable_type | (EGL.opengl_bit | EGL.opengl_es3_bit)); if(ok count{egl.choose_config.count(_display, config_attribs)}) { log_info("found ${count} suitable framebuffer configurations") .arg(EAGINE_ID(count), extract(count)); if(ok config{egl.choose_config(_display, config_attribs)}) { return initialize(exec_ctx, _display, config, opts, video_opts); } else { const string_view dont_care{"-"}; log_error("no matching framebuffer configuration found") .arg( EAGINE_ID(color), EAGINE_ID(integer), video_opts.color_bits(), dont_care) .arg( EAGINE_ID(alpha), EAGINE_ID(integer), video_opts.alpha_bits(), dont_care) .arg( EAGINE_ID(depth), EAGINE_ID(integer), video_opts.depth_bits(), dont_care) .arg( EAGINE_ID(stencil), EAGINE_ID(integer), video_opts.stencil_bits(), dont_care) .arg(EAGINE_ID(message), (!config).message()); } } else { log_error("failed to query framebuffer configurations") .arg(EAGINE_ID(message), (!count).message()); } } else { exec_ctx.log_error("failed to initialize EGL display") .arg(EAGINE_ID(message), (!initialized).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const identifier id, const launch_options& opts, const video_options& video_opts) -> bool { _instance_id = id; const auto& [egl, EGL] = _egl_api; const auto device_kind = video_opts.device_kind(); const auto device_path = video_opts.device_path(); const auto device_idx = video_opts.device_index(); const bool select_device = device_kind.is_valid() || device_path.is_valid() || device_idx.is_valid() || video_opts.driver_name().is_valid(); if(select_device && egl.EXT_device_enumeration) { if(ok dev_count{egl.query_devices.count()}) { const auto n = std_size(extract(dev_count)); std::vector<eglplus::egl_types::device_type> devices; devices.resize(n); if(egl.query_devices(cover(devices))) { for(const auto cur_dev_idx : integer_range(n)) { bool matching_device = true; auto device = eglplus::device_handle(devices[cur_dev_idx]); if(device_idx) { if(std_size(extract(device_idx)) == cur_dev_idx) { log_info("explicitly selected device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { matching_device = false; log_info( "current device index is ${current} but, " "device ${config} requested; skipping") .arg(EAGINE_ID(current), cur_dev_idx) .arg(EAGINE_ID(config), extract(device_idx)); } } if(device_kind) { if(extract(device_kind) == video_device_kind::hardware) { if(!egl.MESA_device_software(device)) { log_info( "device ${index} seems to be hardware as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is software but, " "hardware device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } else if( extract(device_kind) == video_device_kind::software) { if(!egl.EXT_device_drm(device)) { log_info( "device ${index} seems to be software as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is hardware but, " "software device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } } if(device_path) { if(egl.EXT_device_drm(device)) { if(ok path{egl.query_device_string( device, EGL.drm_device_file)}) { if(are_equal( extract(device_path), extract(path))) { log_info( "using DRM device ${path} as " "explicitly specified by configuration") .arg( EAGINE_ID(path), EAGINE_ID(FsPath), extract(path)); } else { matching_device = false; log_info( "device file is ${current}, but " "${config} was requested; skipping") .arg( EAGINE_ID(current), EAGINE_ID(FsPath), extract(path)) .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } } else { log_warning( "${config} requested by config, but cannot " "determine current device file path") .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } if(matching_device) { if(ok display{egl.get_platform_display(device)}) { if(initialize( exec_ctx, display, signedness_cast(cur_dev_idx), opts, video_opts)) { return true; } else { _egl_api.terminate(display); } } } } } } } else { if(ok display{egl.get_display()}) { return initialize(exec_ctx, display, -1, opts, video_opts); } else { exec_ctx.log_error("failed to get EGL display") .arg(EAGINE_ID(message), (!display).message()); } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::clean_up() { if(_display) { if(_context) { _egl_api.destroy_context(_display, _context); } if(_surface) { _egl_api.destroy_surface(_display, _surface); } _egl_api.terminate(_display); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::video_kind() const noexcept -> video_context_kind { return video_context_kind::opengl; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::instance_id() const noexcept -> identifier { return _instance_id; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::is_offscreen() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::has_framebuffer() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_size() noexcept -> std::tuple<int, int> { return {_width, _height}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_aspect() noexcept -> float { return float(_width) / float(_height); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::parent_context_changed(const video_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_begin(execution_context&) { _egl_api.make_current(_display, _surface, _context); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_end(execution_context&) { _egl_api.make_current.none(_display); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_commit(execution_context&) { _egl_api.swap_buffers(_display, _surface); } //------------------------------------------------------------------------------ // provider //------------------------------------------------------------------------------ class eglplus_opengl_provider : public main_ctx_object , public hmi_provider { public: eglplus_opengl_provider(main_ctx_parent parent) : main_ctx_object{EAGINE_ID(EGLPPrvdr), parent} {} auto is_implemented() const noexcept -> bool final; auto implementation_name() const noexcept -> string_view final; auto is_initialized() -> bool final; auto should_initialize(execution_context&) -> bool final; auto initialize(execution_context&) -> bool final; void update(execution_context&) final; void clean_up(execution_context&) final; void input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) final; void video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)>) final; void audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) final; private: eglplus::egl_api _egl_api; std::map<identifier, std::shared_ptr<eglplus_opengl_surface>> _surfaces; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_implemented() const noexcept -> bool { return _egl_api.get_display && _egl_api.initialize && _egl_api.terminate && _egl_api.get_configs && _egl_api.choose_config && _egl_api.get_config_attrib && _egl_api.query_string && _egl_api.swap_buffers; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::implementation_name() const noexcept -> string_view { return {"eglplus"}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_initialized() -> bool { return !_surfaces.empty(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::should_initialize(execution_context& exec_ctx) -> bool { for(auto& [inst, video_opts] : exec_ctx.options().video_requirements()) { EAGINE_MAYBE_UNUSED(inst); if(video_opts.has_provider(implementation_name())) { return true; } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::initialize(execution_context& exec_ctx) -> bool { if(_egl_api.get_display) { auto& options = exec_ctx.options(); for(auto& [inst, video_opts] : options.video_requirements()) { const bool should_create_surface = video_opts.has_provider(implementation_name()) && (video_opts.video_kind() == video_context_kind::opengl); if(should_create_surface) { if(auto surface{std::make_shared<eglplus_opengl_surface>( *this, _egl_api)}) { if(extract(surface).initialize( exec_ctx, inst, options, video_opts)) { _surfaces[inst] = std::move(surface); } else { extract(surface).clean_up(); } } } } return true; } exec_ctx.log_error("EGL is context is not supported"); return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::update(execution_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::clean_up(execution_context&) { for(auto& entry : _surfaces) { entry.second->clean_up(); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)> handler) { for(auto& p : _surfaces) { handler(p.second); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) {} //------------------------------------------------------------------------------ auto make_eglplus_opengl_provider(main_ctx_parent parent) -> std::shared_ptr<hmi_provider> { return {std::make_shared<eglplus_opengl_provider>(parent)}; } //------------------------------------------------------------------------------ } // namespace eagine::app
40
81
0.496783
matus-chochlik
a77d5d08599b35023ed74a3c445c214264380b15
9,544
cpp
C++
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-03-24T13:33:52.000Z
2020-03-24T13:33:52.000Z
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2021-09-02T14:21:33.000Z
2021-09-02T14:21:33.000Z
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-07-15T05:55:55.000Z
2020-07-15T05:55:55.000Z
/** * \date 2014-08-04 * \brief Implementation of OpenGeoSys simulation application * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <tclap/CmdLine.h> #include <chrono> #ifndef _WIN32 #ifdef __APPLE__ #include <xmmintrin.h> #else #include <cfenv> #endif // __APPLE__ #endif // _WIN32 #ifdef USE_PETSC #include <vtkMPIController.h> #include <vtkSmartPointer.h> #endif // BaseLib #include "BaseLib/ConfigTreeUtil.h" #include "BaseLib/DateTools.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" #include "BaseLib/TemplateLogogFormatterSuppressedGCC.h" #include "Applications/ApplicationsLib/LinearSolverLibrarySetup.h" #include "Applications/ApplicationsLib/LogogSetup.h" #include "Applications/ApplicationsLib/ProjectData.h" #include "Applications/ApplicationsLib/TestDefinition.h" #include "Applications/InSituLib/Adaptor.h" #include "InfoLib/CMakeInfo.h" #include "InfoLib/GitInfo.h" #include "ProcessLib/TimeLoop.h" #include "NumLib/NumericsConfig.h" #ifdef OGS_USE_PYTHON #include "ogs_embedded_python.h" #endif int main(int argc, char* argv[]) { // Parse CLI arguments. TCLAP::CmdLine cmd( "OpenGeoSys-6 software.\n" "Copyright (c) 2012-2020, OpenGeoSys Community " "(http://www.opengeosys.org) " "Distributed under a Modified BSD License. " "See accompanying file LICENSE.txt or " "http://www.opengeosys.org/project/license\n" "version: " + GitInfoLib::GitInfo::ogs_version + "\n" + "CMake arguments: " + CMakeInfoLib::CMakeInfo::cmake_args, ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::ValueArg<std::string> reference_path_arg( "r", "reference", "Run output result comparison after successful simulation comparing to " "all files in the given path.", false, "", "PATH"); cmd.add(reference_path_arg); TCLAP::UnlabeledValueArg<std::string> project_arg( "project-file", "Path to the ogs6 project file.", true, "", "PROJECT_FILE"); cmd.add(project_arg); TCLAP::ValueArg<std::string> outdir_arg("o", "output-directory", "the output directory to write to", false, "", "PATH"); cmd.add(outdir_arg); TCLAP::ValueArg<std::string> log_level_arg("l", "log-level", "the verbosity of logging " "messages: none, error, warn, " "info, debug, all", false, #ifdef NDEBUG "info", #else "all", #endif "LOG_LEVEL"); cmd.add(log_level_arg); TCLAP::SwitchArg nonfatal_arg("", "config-warnings-nonfatal", "warnings from parsing the configuration " "file will not trigger program abortion"); cmd.add(nonfatal_arg); TCLAP::SwitchArg unbuffered_cout_arg("", "unbuffered-std-out", "use unbuffered standard output"); cmd.add(unbuffered_cout_arg); #ifndef _WIN32 // TODO: On windows floating point exceptions are not handled // currently TCLAP::SwitchArg enable_fpe_arg("", "enable-fpe", "enables floating point exceptions"); cmd.add(enable_fpe_arg); #endif // _WIN32 cmd.parse(argc, argv); // deactivate buffer for standard output if specified if (unbuffered_cout_arg.isSet()) { std::cout.setf(std::ios::unitbuf); } ApplicationsLib::LogogSetup logog_setup; logog_setup.setLevel(log_level_arg.getValue()); INFO("This is OpenGeoSys-6 version %s.", GitInfoLib::GitInfo::ogs_version.c_str()); #ifndef _WIN32 // On windows this command line option is not present. // Enable floating point exceptions if (enable_fpe_arg.isSet()) { #ifdef __APPLE__ _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); #else feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif // __APPLE__ } #endif // _WIN32 #ifdef OGS_USE_PYTHON pybind11::scoped_interpreter guard = ApplicationsLib::setupEmbeddedPython(); (void)guard; #endif BaseLib::RunTime run_time; { auto const start_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(start_time); INFO("OGS started on %s.", time_str.c_str()); } std::unique_ptr<ApplicationsLib::TestDefinition> test_definition; auto ogs_status = EXIT_SUCCESS; try { bool solver_succeeded = false; { ApplicationsLib::LinearSolverLibrarySetup linear_solver_library_setup(argc, argv); #if defined(USE_PETSC) vtkSmartPointer<vtkMPIController> controller = vtkSmartPointer<vtkMPIController>::New(); controller->Initialize(&argc, &argv, 1); vtkMPIController::SetGlobalController(controller); logog_setup.setFormatter( std::make_unique<BaseLib::TemplateLogogFormatterSuppressedGCC< TOPIC_LEVEL_FLAG | TOPIC_FILE_NAME_FLAG | TOPIC_LINE_NUMBER_FLAG>>()); #endif run_time.start(); auto project_config = BaseLib::makeConfigTree( project_arg.getValue(), !nonfatal_arg.getValue(), "OpenGeoSysProject"); BaseLib::setProjectDirectory( BaseLib::extractPath(project_arg.getValue())); ProjectData project(*project_config, BaseLib::getProjectDirectory(), outdir_arg.getValue()); if (!reference_path_arg.isSet()) { // Ignore the test_definition section. project_config->ignoreConfigParameter("test_definition"); } else { test_definition = std::make_unique<ApplicationsLib::TestDefinition>( //! \ogs_file_param{prj__test_definition} project_config->getConfigSubtree("test_definition"), reference_path_arg.getValue(), outdir_arg.getValue()); INFO("Cleanup possible output files before running ogs."); BaseLib::removeFiles(test_definition->getOutputFiles()); } #ifdef USE_INSITU auto isInsituConfigured = false; //! \ogs_file_param{prj__insitu} if (auto t = project_config->getConfigSubtreeOptional("insitu")) { InSituLib::Initialize( //! \ogs_file_param{prj__insitu__scripts} t->getConfigSubtree("scripts"), BaseLib::extractPath(project_arg.getValue())); isInsituConfigured = true; } #else project_config->ignoreConfigParameter("insitu"); #endif INFO("Initialize processes."); for (auto& p : project.getProcesses()) { p->initialize(); } // Check intermediately that config parsing went fine. project_config.checkAndInvalidate(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); INFO("Solve processes."); auto& time_loop = project.getTimeLoop(); time_loop.initialize(); solver_succeeded = time_loop.loop(); #ifdef USE_INSITU if (isInsituConfigured) InSituLib::Finalize(); #endif INFO("[time] Execution took %g s.", run_time.elapsed()); #if defined(USE_PETSC) controller->Finalize(1); #endif } // This nested scope ensures that everything that could possibly // possess a ConfigTree is destructed before the final check below is // done. BaseLib::ConfigTree::assertNoSwallowedErrors(); ogs_status = solver_succeeded ? EXIT_SUCCESS : EXIT_FAILURE; } catch (std::exception& e) { ERR(e.what()); ogs_status = EXIT_FAILURE; } { auto const end_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(end_time); INFO("OGS terminated on %s.", time_str.c_str()); } if (ogs_status == EXIT_FAILURE) { ERR("OGS terminated with error."); return EXIT_FAILURE; } if (test_definition == nullptr) { // There are no tests, so just exit; return ogs_status; } INFO(""); INFO("##########################################"); INFO("# Running tests #"); INFO("##########################################"); INFO(""); if (!test_definition->runTests()) { ERR("One of the tests failed."); return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.462585
80
0.576907
OlafKolditz
a77df707c2889771045e50b016329560b5f64f4d
2,289
cpp
C++
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
362
2017-09-30T09:35:01.000Z
2022-02-24T14:45:48.000Z
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
170
2017-09-18T16:11:23.000Z
2022-03-31T21:36:21.000Z
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
54
2017-09-20T08:30:21.000Z
2022-03-29T02:55:24.000Z
/* Dwarf Therapist Copyright (c) 2018 Clement Vuchener 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 "defaultroleweight.h" #include "standardpaths.h" DefaultRoleWeight DefaultRoleWeight::attributes("attributes", 0.25); DefaultRoleWeight DefaultRoleWeight::skills("skills", 1.0); DefaultRoleWeight DefaultRoleWeight::facets("traits", 0.20); DefaultRoleWeight DefaultRoleWeight::beliefs("beliefs", 0.20); DefaultRoleWeight DefaultRoleWeight::goals("goals", 0.10); DefaultRoleWeight DefaultRoleWeight::needs("needs", 0.10); DefaultRoleWeight DefaultRoleWeight::preferences("prefs", 0.15); DefaultRoleWeight::DefaultRoleWeight(const char *key, float default_value) : m_value_key(QString("options/default_%1_weight").arg(key)) , m_overwrite_key(QString("options/overwrite_default_%1_weight").arg(key)) , m_default_value(default_value) , m_value(default_value) { } void DefaultRoleWeight::update() { auto s = StandardPaths::settings(); m_overwrite = s->value(m_overwrite_key, s->contains(m_value_key)).toBool(); m_value = s->value(m_value_key, m_default_value).toFloat(); } void DefaultRoleWeight::update_all() { attributes.update(); skills.update(); facets.update(); beliefs.update(); goals.update(); needs.update(); preferences.update(); }
36.919355
79
0.771953
Alatun-Rom
a7809b99d206bc39ac2a402fd7f708d07dd1c1e0
4,989
cpp
C++
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
1
2022-01-06T17:44:07.000Z
2022-01-06T17:44:07.000Z
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
32
2021-09-24T23:50:09.000Z
2022-03-29T09:37:26.000Z
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
null
null
null
#include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/types/chunk_collection.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/execution/executor.hpp" #include "duckdb/parallel/event.hpp" namespace duckdb { PhysicalRecursiveCTE::PhysicalRecursiveCTE(vector<LogicalType> types, bool union_all, unique_ptr<PhysicalOperator> top, unique_ptr<PhysicalOperator> bottom, idx_t estimated_cardinality) : PhysicalOperator(PhysicalOperatorType::RECURSIVE_CTE, move(types), estimated_cardinality), union_all(union_all) { children.push_back(move(top)); children.push_back(move(bottom)); } PhysicalRecursiveCTE::~PhysicalRecursiveCTE() { } //===--------------------------------------------------------------------===// // Sink //===--------------------------------------------------------------------===// class RecursiveCTEState : public GlobalSinkState { public: explicit RecursiveCTEState(ClientContext &context, const PhysicalRecursiveCTE &op) : new_groups(STANDARD_VECTOR_SIZE) { ht = make_unique<GroupedAggregateHashTable>(BufferManager::GetBufferManager(context), op.types, vector<LogicalType>(), vector<BoundAggregateExpression *>()); } unique_ptr<GroupedAggregateHashTable> ht; bool intermediate_empty = true; ChunkCollection intermediate_table; idx_t chunk_idx = 0; SelectionVector new_groups; }; unique_ptr<GlobalSinkState> PhysicalRecursiveCTE::GetGlobalSinkState(ClientContext &context) const { return make_unique<RecursiveCTEState>(context, *this); } idx_t PhysicalRecursiveCTE::ProbeHT(DataChunk &chunk, RecursiveCTEState &state) const { Vector dummy_addresses(LogicalType::POINTER); // Use the HT to eliminate duplicate rows idx_t new_group_count = state.ht->FindOrCreateGroups(chunk, dummy_addresses, state.new_groups); // we only return entries we have not seen before (i.e. new groups) chunk.Slice(state.new_groups, new_group_count); return new_group_count; } SinkResultType PhysicalRecursiveCTE::Sink(ExecutionContext &context, GlobalSinkState &state, LocalSinkState &lstate, DataChunk &input) const { auto &gstate = (RecursiveCTEState &)state; if (!union_all) { idx_t match_count = ProbeHT(input, gstate); if (match_count > 0) { gstate.intermediate_table.Append(input); } } else { gstate.intermediate_table.Append(input); } return SinkResultType::NEED_MORE_INPUT; } //===--------------------------------------------------------------------===// // Source //===--------------------------------------------------------------------===// void PhysicalRecursiveCTE::GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate_p, LocalSourceState &lstate) const { auto &gstate = (RecursiveCTEState &)*sink_state; while (chunk.size() == 0) { if (gstate.chunk_idx < gstate.intermediate_table.ChunkCount()) { // scan any chunks we have collected so far chunk.Reference(gstate.intermediate_table.GetChunk(gstate.chunk_idx)); gstate.chunk_idx++; break; } else { // we have run out of chunks // now we need to recurse // we set up the working table as the data we gathered in this iteration of the recursion working_table->Reset(); working_table->Merge(gstate.intermediate_table); // and we clear the intermediate table gstate.intermediate_table.Reset(); gstate.chunk_idx = 0; // now we need to re-execute all of the pipelines that depend on the recursion ExecuteRecursivePipelines(context); // check if we obtained any results // if not, we are done if (gstate.intermediate_table.Count() == 0) { break; } } } } void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) const { if (pipelines.empty()) { throw InternalException("Missing pipelines for recursive CTE"); } for (auto &pipeline : pipelines) { auto sink = pipeline->GetSink(); if (sink != this) { // reset the sink state for any intermediate sinks sink->sink_state = sink->GetGlobalSinkState(context.client); } for (auto &op : pipeline->GetOperators()) { if (op) { op->op_state = op->GetGlobalOperatorState(context.client); } } pipeline->Reset(); } auto &executor = pipelines[0]->executor; vector<shared_ptr<Event>> events; executor.ReschedulePipelines(pipelines, events); while (true) { executor.WorkOnTasks(); if (executor.HasError()) { executor.ThrowException(); } bool finished = true; for (auto &event : events) { if (!event->IsFinished()) { finished = false; break; } } if (finished) { // all pipelines finished: done! break; } } } } // namespace duckdb
33.26
119
0.676889
kimmolinna
a782c7e4694aa5e8f9c94f0a891038ca5f6f0422
13,904
hpp
C++
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2016-08-29T09:23:49.000Z
2019-06-13T20:29:28.000Z
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
class MedicalLarge { name = $STR_ZECCUP_MedicalLarge; // EAST class Hospital_CUP_O_TK { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_O_TK; // Credit: 2600K icon = "\ca\data\flag_rus_co.paa"; side = 8; class Object0 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {0.195923,-5.93896,0}; dir = 210;}; class Object1 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {-11.6127,-2.72363,0}; dir = 90;}; class Object2 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,-8.50635,0}; dir = 270;}; class Object3 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-6.59546,-8.46338,0}; dir = 270;}; class Object4 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-15.5317,-9.78564,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-9.46423,-11.7817,0}; dir = 270;}; class Object7 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.75,-3.375,0}; dir = 30;}; class Object8 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {-4.96875,-8.81641,0}; dir = 112.818;}; class Object9 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.4955,-3.6665,0}; dir = 240;}; class Object10 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.75452,-4.38281,0}; dir = 315;}; class Object11 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.93164,-2.69141,0}; dir = 15;}; class Object12 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00452,-3.0835,0}; dir = 45;}; class Object13 {side = 8; vehicle = "Body"; rank = ""; position[] = {-0.707642,-3.521,0}; dir = 315;}; // Z: 0.0999999 class Object14 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.25,-8.625,0}; dir = 0;}; class Object15 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.9216,-7.93555,0}; dir = 0;}; class Object16 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-14.0197,-8.65381,0}; dir = 105;}; class Object17 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,0.368652,0}; dir = 270;}; class Object18 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-2.52954,8.83838,0}; dir = 90;}; class Object19 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-13.3904,6.23584,0}; dir = 0;}; class Object20 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-5.14038,6.36084,0}; dir = 0;}; class Object21 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-7.11633,6.49658,0}; dir = 0;}; class Object22 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-3.11633,6.37158,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.3663,6.37158,0}; dir = 0;}; class Object24 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-15.2413,6.12158,0}; dir = 0;}; class Object25 {side = 8; vehicle = "Land_FieldToilet_F"; rank = ""; position[] = {-3.375,4.25,0}; dir = 345.002;}; class Object26 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-13.8955,1.35156,0}; dir = 90;}; class Object27 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.29749,2.15967,0}; dir = 120;}; class Object28 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.3053,2.16406,0}; dir = 45;}; class Object29 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00635,1.41406,0}; dir = 135;}; class Object30 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.58862,2.90527,0}; dir = 330;}; class Object31 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-8.61414,2.34131,0}; dir = 105;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-3.75,2.375,0}; dir = 105;}; class Object33 {side = 8; vehicle = "Land_Pallets_F"; rank = ""; position[] = {-4.00256,14.0288,0}; dir = 90;}; class Object34 {side = 8; vehicle = "Land_Pallet_F"; rank = ""; position[] = {-2.61108,15.373,0}; dir = 192.542;}; class Object35 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {8.69763,-11.3872,0}; dir = 300;}; class Object36 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.96472,-9.39063,0}; dir = 330;}; class Object37 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.22583,-9.4541,0}; dir = 330;}; class Object38 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.5,-10.125,0}; dir = 75;}; class Object39 {side = 8; vehicle = "Land_fort_artillery_nest_EP1"; rank = ""; position[] = {18.4866,6.375,0}; dir = 90;}; class Object40 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {4.73523,6.29248,0}; dir = 180;}; class Object41 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {14.1373,6.52637,0}; dir = 90;}; class Object42 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {6.125,12.6494,0}; dir = 180;}; class Object43 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {13.9001,11.2822,0}; dir = 300;}; class Object44 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {13.8027,7.09961,0}; dir = 330;}; class Object45 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {16.8672,3.83154,0}; dir = 123.359;}; class Object46 {side = 8; vehicle = "Body"; rank = ""; position[] = {15.1174,2.87842,0}; dir = 150;}; class Object47 {side = 8; vehicle = "Body"; rank = ""; position[] = {12.2452,1.75684,0}; dir = 180;}; class Object48 {side = 8; vehicle = "Body"; rank = ""; position[] = {13.6187,2.13037,0}; dir = 165;}; class Object49 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.6823,6.30811,0}; dir = 180;}; class Object50 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {14.6732,6.5918,0}; dir = 255;}; class Object51 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.9232,7.89111,0}; dir = 345;}; class Object52 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.1201,7.28418,0}; dir = 315;}; class Object53 {side = 8; vehicle = "AmmoCrate_NoInteractive_"; rank = ""; position[] = {14.7791,11.0151,0}; dir = 300;}; class Object54 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {17.2242,5.30664,0}; dir = 196.374;}; }; // WEST class Hospital_CUP_B_USMC { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_B_USMC; // Credit: 2600K icon = "\ca\data\flag_usa_co.paa"; side = 8; class Object0 {side = 8; vehicle = "Land_CamoNetVar_NATO_EP1"; rank = ""; position[] = {-7.36267,-7.84863,0}; dir = 90;}; class Object1 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-1.0127,-13.3354,0}; dir = 0;}; class Object2 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-9.2627,-13.5854,0}; dir = 0;}; class Object3 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-12.6608,-10.0933,0}; dir = 90;}; class Object4 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {-8.70935,-11.6304,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.2512,-2.49072,0}; dir = 240;}; class Object6 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-2.61743,-2.36914,0}; dir = 300;}; class Object7 {side = 8; vehicle = "Land_BagFence_Round_F"; rank = ""; position[] = {-12.2045,-3.12598,0}; dir = 135;}; class Object8 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7654,-8.62891,0}; dir = 270;}; class Object9 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7655,-5.75391,0}; dir = 270;}; class Object10 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.875,-4.125,0}; dir = 315.002;}; class Object11 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.12183,-8.74609,0}; dir = 59.392;}; class Object12 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.30188,-4.69873,0}; dir = 134.559;}; class Object13 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.82617,-9.15381,0}; dir = 240.001;}; class Object14 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.58191,-4.03955,0}; dir = 329.971;}; class Object15 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.34473,-5.36133,0}; dir = 119.98;}; class Object16 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.0918,-9.81445,0}; dir = 254.978;}; class Object17 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.49463,-8.96143,0}; dir = 44.9741;}; class Object18 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.50916,-8.9707,0}; dir = 239.966;}; class Object19 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.77698,-7.9707,0}; dir = 89.9435;}; class Object20 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.46082,-4.83203,0}; dir = 164.938;}; class Object21 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.875,-3.41797,0}; dir = 314.957;}; class Object22 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-4.35156,-11.6455,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-5.5,-11.875,0}; dir = 285.016;}; class Object24 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-7.62488,-11.75,0}; dir = 194.982;}; class Object25 {side = 8; vehicle = "B_Slingload_01_Medevac_F"; rank = ""; position[] = {-6,8.25,0}; dir = 300;}; class Object27 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {1.7594,11.376,0}; dir = 330;}; class Object28 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {2.00574,12.7427,0}; dir = 30;}; class Object29 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-1.36926,13.2573,0}; dir = 285;}; class Object30 {side = 8; vehicle = "Land_PaperBox_open_empty_F"; rank = ""; position[] = {-7.87537,6.875,0}; dir = 300;}; class Object31 {side = 8; vehicle = "Land_PaperBox_closed_F"; rank = ""; position[] = {-6.49158,5.36523,0}; dir = 150;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-1.5,0.5,0}; dir = 315;}; class Object33 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-8.02747,5.28076,0}; dir = 240;}; class Object34 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {-6.125,11.125,0}; dir = 194.999;}; class Object35 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {4.11865,-13.0493,0}; dir = 6.83019e-006;}; class Object36 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.4506,-8.49365,0}; dir = 90;}; class Object37 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {14.2563,-12.9507,0}; dir = 180;}; class Object38 {side = 8; vehicle = "Body"; rank = ""; position[] = {6.8501,-7.96289,0}; dir = 90;}; // Z: 0.0908942 class Object39 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.375,-11.75,0}; dir = 285.016;}; class Object40 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.5001,-11.75,0}; dir = 194.982;}; class Object41 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {14.5,-14.125,0}; dir = 285.016;}; class Object42 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {13.6251,-14.125,0}; dir = 194.982;}; class Object43 {side = 8; vehicle = "US_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {8.77747,-0.0498047,0}; dir = 0;}; class Object44 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {6.7373,12.0396,0}; dir = 0;}; class Object45 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,7.75635,0}; dir = 90;}; class Object46 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {11.3687,12.3257,0}; dir = 6.83019e-006;}; class Object47 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,2.13135,0}; dir = 90;}; class Object48 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {15.7142,11.0317,0}; dir = 90;}; class Object49 {side = 8; vehicle = "Land_ToiletBox_F"; rank = ""; position[] = {7.12146,9.70947,0}; dir = 30.0776;}; class Object50 {side = 8; vehicle = "Land_WaterTank_F"; rank = ""; position[] = {5.12585,10.2192,0}; dir = 0.0586366;}; class Object51 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.25,11.125,0}; dir = 195;}; class Object52 {side = 8; vehicle = "Body"; rank = ""; position[] = {9.41858,4.82324,0}; dir = 90.0001;}; // Z: 0.0926261 class Object53 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.86951,0.118652,0}; dir = 75;}; class Object54 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.61707,1.49707,0}; dir = 105;}; class Object55 {side = 8; vehicle = "Land_MetalBarrel_empty_F"; rank = ""; position[] = {11.1964,10.918,0}; dir = 255;}; class Object56 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.3746,10.7339,0}; dir = 134.965;}; class Object57 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.0023,10.1938,0}; dir = 105.016;}; class Object58 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.5,9.75,0}; dir = 270;}; }; }; class MedicalMedium { name = $STR_ZECCUP_MedicalMedium; }; class MedicalSmall { name = $STR_ZECCUP_MedicalSmall; };
101.489051
135
0.610256
LISTINGS09
a78408805c9ef2a4fb93d43a039d7c3ce3294dfe
2,170
cpp
C++
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
1
2019-03-28T20:45:32.000Z
2019-03-28T20:45:32.000Z
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
#include <mud/core.h> #include <19_multi_viewport/19_multi_viewport.h> #include <03_materials/03_materials.h> using namespace mud; size_t viewport_mode(Widget& parent) { std::vector<size_t> num_viewer_vals = { 1, 2, 4 }; ui::label(parent, "num viewports : "); static uint32_t choice = 1; ui::radio_switch(parent, carray<cstring, 3>{ "1", "2", "4" }, choice); return num_viewer_vals[choice]; } void ex_19_multi_viewport(Shell& app, Widget& parent, Dockbar& dockbar) { static float time = 0.f; time += 0.01f; bool multiple_scene = false; static size_t num_viewers = 2; if(Widget* dock = ui::dockitem(dockbar, "Game", carray<uint16_t, 1>{ 1U })) num_viewers = viewport_mode(*dock); Widget& layout = ui::layout(parent); Widget& first_split = ui::board(layout); Widget* second_split = num_viewers > 2 ? &ui::board(layout) : nullptr; std::vector<Viewer*> viewers = {}; if(!multiple_scene) { static Scene scene = { app.m_gfx_system }; for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::viewer(i >= 2 ? *second_split : first_split, scene)); } else { for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::scene_viewer(i >= 2 ? *second_split : first_split)); } for(Viewer* viewer : viewers) { ui::orbit_controller(*viewer); Gnode& scene = viewer->m_scene->begin(); for(size_t x = 0; x < 11; ++x) for(size_t y = 0; y < 11; ++y) { vec3 angles = { time + x * 0.21f, 0.f, time + y * 0.37f }; vec3 pos = { -15.f + x * 3.f, 0, -15.f + y * 3.f }; float r = ncosf(time + float(x) * 0.21f); float b = nsinf(time + float(y) * 0.37f); float g = ncosf(time); Colour color = { r, g, b }; Gnode& gnode = gfx::node(scene, {}, pos, quat(angles), vec3(1)); gfx::shape(gnode, Cube(), Symbol(color, Colour::None)); } } } #ifdef _19_MULTI_VIEWPORT_EXE void pump(Shell& app) { shell_context(app.m_ui->begin(), app.m_editor); ex_19_multi_viewport(app, *app.m_editor.m_screen, *app.m_editor.m_dockbar); } int main(int argc, char *argv[]) { Shell app(MUD_RESOURCE_PATH, exec_path(argc, argv).c_str()); app.m_gfx_system.init_pipeline(pipeline_minimal); app.run(pump); } #endif
25.529412
79
0.64977
alecnunn
a78490ca22772fbbe23e1b65bd705acf34432e8a
5,922
hpp
C++
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. /// \file /// Defines function for taking the determinant of a rank-2 tensor #pragma once #include "DataStructures/Tensor/Tensor.hpp" #include "Utilities/Gsl.hpp" namespace detail { template <typename Symm, typename Index, typename = std::nullptr_t> struct DeterminantImpl; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 1>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { return get<0, 0>(tensor); } }; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 2>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); return t00 * t11 - t01 * t10; } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t21) - t01 * (t10 * t22 - t12 * t20) + t02 * (t10 * t21 - t11 * t20); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t12) - t01 * (t01 * t22 - t12 * t02) + t02 * (t01 * t12 - t11 * t02); } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t30 = get<3, 0>(tensor); const auto& t31 = get<3, 1>(tensor); const auto& t32 = get<3, 2>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t32; const auto minor2 = t21 * t33 - t23 * t31; const auto minor3 = t20 * t33 - t23 * t30; const auto minor4 = t21 * t32 - t22 * t31; const auto minor5 = t20 * t32 - t22 * t30; const auto minor6 = t20 * t31 - t21 * t30; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t10 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t10 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t10 * minor4 - t11 * minor5 + t12 * minor6); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t23; const auto minor2 = t12 * t33 - t23 * t13; const auto minor3 = t02 * t33 - t23 * t03; const auto minor4 = t12 * t23 - t22 * t13; const auto minor5 = t02 * t23 - t22 * t03; const auto minor6 = t02 * t13 - t12 * t03; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t01 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t01 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t01 * minor4 - t11 * minor5 + t12 * minor6); } }; } // namespace detail /// @{ /*! * \ingroup TensorGroup * \brief Computes the determinant of a rank-2 Tensor `tensor`. * * \requires That `tensor` be a rank-2 Tensor, with both indices sharing the * same dimension and type. */ template <typename T, typename Symm, typename Index0, typename Index1> void determinant( const gsl::not_null<Scalar<T>*> det_tensor, const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { static_assert(Index0::dim == Index1::dim, "Cannot take the determinant of a Tensor whose Indices are not " "of the same dimensionality."); static_assert(Index0::index_type == Index1::index_type, "Taking the determinant of a mixed Spatial and Spacetime index " "Tensor is not allowed since it's not clear what that means."); get(*det_tensor) = detail::DeterminantImpl<Symm, Index0>::apply(tensor); } template <typename T, typename Symm, typename Index0, typename Index1> Scalar<T> determinant( const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { Scalar<T> result{}; determinant(make_not_null(&result), tensor); return result; } /// @}
37.245283
80
0.614826
macedo22
a784bc499e303988d8a73b3303a9d4355e58e35f
1,861
cc
C++
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
1
2020-06-24T07:34:55.000Z
2020-06-24T07:34:55.000Z
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
null
null
null
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include "gtest/gtest.h" #include "sequential-search.h" #include "binary-search-tree.h" #include "red-black-tree.h" TEST (SEQUENTIAL, TEST_CASE_001) { BaseSearch *search = new SequentialSearch(); EXPECT_EQ(0, 0); } TEST (BINARY_SEARCH_TREE, TEST_CASE_001) { int search_target = 8; std::string tree_elements = ""; BinarySearchTree *bst_tree = new BinarySearchTree(); BSTNode *head = bst_tree->create_node(1); BSTNode *node1 = bst_tree->create_node(2); BSTNode *node2 = bst_tree->create_node(3); BSTNode *node3 = bst_tree->create_node(4); BSTNode *node4 = bst_tree->create_node(5); BSTNode *node5 = bst_tree->create_node(6); BSTNode *node6 = bst_tree->create_node(7); BSTNode *node7 = bst_tree->create_node(8); bst_tree->insert_node(head, node1); bst_tree->insert_node(head, node2); bst_tree->insert_node(head, node3); bst_tree->insert_node(head, node4); bst_tree->insert_node(head, node5); bst_tree->insert_node(head, node6); bst_tree->insert_node(head, node7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 2 3 4 5 6 7 8 ", tree_elements.c_str()); tree_elements = ""; bst_tree->remove_node(head, 2); bst_tree->remove_node(head, 4); bst_tree->remove_node(head, 7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 3 5 6 8 ", tree_elements.c_str()); // test search BSTNode *test_search = bst_tree->search_node(head, search_target); EXPECT_EQ(search_target, test_search->data); } TEST (REDBLACKTREE, TEST_CASE_001) { RedBlackTree *red_black_tree = new RedBlackTree(); red_black_tree->version_info(); EXPECT_EQ(0, 0); } int main (int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.630769
70
0.68619
BONITA-KWKim
a786202d692a972fd9b5663ff265857d3848244c
8,040
cpp
C++
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
5
2019-09-14T14:08:46.000Z
2021-04-27T11:21:43.000Z
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
null
null
null
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
1
2019-10-19T04:19:46.000Z
2019-10-19T04:19:46.000Z
#include "ws.h" #include "WL_DEF.H" ws_GBuffer ws_gbuffer; std::vector<ws_PointLight> ws_active_lights; GLuint ws_create_sphere() { GLuint handle; glGenBuffers(1, &handle); glBindBuffer(GL_ARRAY_BUFFER, handle); ws_Vector3 *pVertices = new ws_Vector3[WS_SPHERE_VERT_COUNT]; int hseg = 8; int vseg = 8; auto pVerts = pVertices; { auto cos_h = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h = sinf(1.0f / (float)hseg * (float)M_PI); for (int j = 1; j < hseg - 1; ++j) { auto cos_h_next = cosf((float)(j + 1) / (float)hseg * (float)M_PI); auto sin_h_next = sinf((float)(j + 1) / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h; pVerts->y = sin_v_next * sin_h; pVerts->z = cos_h; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } cos_h = cos_h_next; sin_h = sin_h_next; } } // Caps { auto cos_h_next = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h_next = sinf(1.0f / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = 1.0f; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = -1.0f; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } } glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * WS_SPHERE_VERT_COUNT, pVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (float *)(uintptr_t)(0)); delete[] pVertices; return handle; } ws_GBuffer ws_create_gbuffer(int w, int h) { ws_GBuffer gbuffer; glGenFramebuffers(1, &gbuffer.frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); // Albeo { glGenTextures(1, &gbuffer.albeoHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gbuffer.albeoHandle, 0); } // Normal { glGenTextures(1, &gbuffer.normalHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gbuffer.normalHandle, 0); } // Depth { glGenTextures(1, &gbuffer.depthHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gbuffer.depthHandle, 0); } // Attach the main depth buffer { glBindRenderbuffer(GL_RENDERBUFFER, ws_resources.mainRT.depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, ws_resources.mainRT.depth); } assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); return gbuffer; } void ws_resize_gbuffer(ws_GBuffer &gbuffer, int w, int h) { glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } void ws_draw_pointlight(const ws_PointLight& pointLight) { // Update uniforms static auto LightPosition_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightPosition"); static auto LightRadius_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightRadius"); static auto LightIntensity_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightIntensity"); static auto LightColor_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightColor"); ws_Vector3 lpos = {pointLight.position.x, pointLight.position.y, pointLight.position.z}; glUniform3fv(LightPosition_uniform, 1, &lpos.x); glUniform1f(LightRadius_uniform, pointLight.radius); glUniform1f(LightIntensity_uniform, pointLight.intensity); glUniform4fv(LightColor_uniform, 1, &pointLight.color.r); glDrawArrays(GL_TRIANGLES, 0, WS_SPHERE_VERT_COUNT); }
36.545455
124
0.606468
Daivuk
a7875e99e239cd4ad711fd5d736f2f8b94b57109
23,026
cpp
C++
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
1
2018-06-15T00:27:24.000Z
2018-06-15T00:27:24.000Z
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
null
null
null
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
null
null
null
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: proto_model.cpp Abstract: <abstract> Author: Leonardo de Moura (leonardo) 2007-03-08. Revision History: --*/ #include"proto_model.h" #include"model_params.hpp" #include"ast_pp.h" #include"ast_ll_pp.h" #include"var_subst.h" #include"array_decl_plugin.h" #include"well_sorted.h" #include"used_symbols.h" #include"model_v2_pp.h" proto_model::proto_model(ast_manager & m, params_ref const & p): model_core(m), m_afid(m.mk_family_id(symbol("array"))), m_eval(*this), m_rewrite(m) { register_factory(alloc(basic_factory, m)); m_user_sort_factory = alloc(user_sort_factory, m); register_factory(m_user_sort_factory); m_model_partial = model_params(p).partial(); } void proto_model::register_aux_decl(func_decl * d, func_interp * fi) { model_core::register_decl(d, fi); m_aux_decls.insert(d); } /** \brief Set new_fi as the new interpretation for f. If f_aux != 0, then assign the old interpretation of f to f_aux. If f_aux == 0, then delete the old interpretation of f. f_aux is marked as a auxiliary declaration. */ void proto_model::reregister_decl(func_decl * f, func_interp * new_fi, func_decl * f_aux) { func_interp * fi = get_func_interp(f); if (fi == 0) { register_decl(f, new_fi); } else { if (f_aux != 0) { register_decl(f_aux, fi); m_aux_decls.insert(f_aux); } else { dealloc(fi); } m_finterp.insert(f, new_fi); } } expr * proto_model::mk_some_interp_for(func_decl * d) { SASSERT(!has_interpretation(d)); expr * r = get_some_value(d->get_range()); // if t is a function, then it will be the constant function. if (d->get_arity() == 0) { register_decl(d, r); } else { func_interp * new_fi = alloc(func_interp, m_manager, d->get_arity()); new_fi->set_else(r); register_decl(d, new_fi); } return r; } bool proto_model::is_select_of_model_value(expr* e) const { return is_app_of(e, m_afid, OP_SELECT) && is_as_array(to_app(e)->get_arg(0)) && has_interpretation(array_util(m_manager).get_as_array_func_decl(to_app(to_app(e)->get_arg(0)))); } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { m_eval.set_model_completion(model_completion); try { m_eval(e, result); #if 0 std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; #endif return true; } catch (model_evaluator_exception & ex) { (void)ex; TRACE("model_evaluator", tout << ex.msg() << "\n";); return false; } } /** \brief Evaluate the expression e in the current model, and store the result in \c result. It returns \c true if succeeded, and false otherwise. If the evaluation fails, then r contains a term that is simplified as much as possible using the interpretations available in the model. When model_completion == true, if the model does not assign an interpretation to a declaration it will build one for it. Moreover, partial functions will also be completed. So, if model_completion == true, the evaluator never fails if it doesn't contain quantifiers. */ /** \brief Replace uninterpreted constants occurring in fi->get_else() by their interpretations. */ void proto_model::cleanup_func_interp(func_interp * fi, func_decl_set & found_aux_fs) { if (fi->is_partial()) return; expr * fi_else = fi->get_else(); TRACE("model_bug", tout << "cleaning up:\n" << mk_pp(fi_else, m_manager) << "\n";); obj_map<expr, expr*> cache; expr_ref_vector trail(m_manager); ptr_buffer<expr, 128> todo; ptr_buffer<expr> args; todo.push_back(fi_else); expr * a; while (!todo.empty()) { a = todo.back(); if (is_uninterp_const(a)) { todo.pop_back(); func_decl * a_decl = to_app(a)->get_decl(); expr * ai = get_const_interp(a_decl); if (ai == 0) { ai = get_some_value(a_decl->get_range()); register_decl(a_decl, ai); } cache.insert(a, ai); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(t->get_arg(i)); } else { args.push_back(arg); } } if (!visited) { continue; } func_decl * f = t->get_decl(); if (m_aux_decls.contains(f)) found_aux_fs.insert(f); expr_ref new_t(m_manager); new_t = m_rewrite.mk_app(f, num_args, args.c_ptr()); if (t != new_t.get()) trail.push_back(new_t); todo.pop_back(); cache.insert(t, new_t); break; } default: SASSERT(a != 0); cache.insert(a, a); todo.pop_back(); break; } } } if (!cache.find(fi_else, a)) { UNREACHABLE(); } fi->set_else(a); } void proto_model::remove_aux_decls_not_in_set(ptr_vector<func_decl> & decls, func_decl_set const & s) { unsigned sz = decls.size(); unsigned i = 0; unsigned j = 0; for (; i < sz; i++) { func_decl * f = decls[i]; if (!m_aux_decls.contains(f) || s.contains(f)) { decls[j] = f; j++; } } decls.shrink(j); } /** \brief Replace uninterpreted constants occurring in the func_interp's get_else() by their interpretations. */ void proto_model::cleanup() { func_decl_set found_aux_fs; decl2finterp::iterator it = m_finterp.begin(); decl2finterp::iterator end = m_finterp.end(); for (; it != end; ++it) { func_interp * fi = (*it).m_value; cleanup_func_interp(fi, found_aux_fs); } // remove auxiliary declarations that are not used. if (found_aux_fs.size() != m_aux_decls.size()) { remove_aux_decls_not_in_set(m_decls, found_aux_fs); remove_aux_decls_not_in_set(m_func_decls, found_aux_fs); func_decl_set::iterator it2 = m_aux_decls.begin(); func_decl_set::iterator end2 = m_aux_decls.end(); for (; it2 != end2; ++it2) { func_decl * faux = *it2; if (!found_aux_fs.contains(faux)) { TRACE("cleanup_bug", tout << "eliminating " << faux->get_name() << "\n";); func_interp * fi = 0; m_finterp.find(faux, fi); SASSERT(fi != 0); m_finterp.erase(faux); m_manager.dec_ref(faux); dealloc(fi); } } m_aux_decls.swap(found_aux_fs); } } value_factory * proto_model::get_factory(family_id fid) { return m_factories.get_plugin(fid); } void proto_model::freeze_universe(sort * s) { SASSERT(m_manager.is_uninterp(s)); m_user_sort_factory->freeze_universe(s); } /** \brief Return the known universe of an uninterpreted sort. */ obj_hashtable<expr> const & proto_model::get_known_universe(sort * s) const { return m_user_sort_factory->get_known_universe(s); } ptr_vector<expr> const & proto_model::get_universe(sort * s) const { ptr_vector<expr> & tmp = const_cast<proto_model*>(this)->m_tmp; tmp.reset(); obj_hashtable<expr> const & u = get_known_universe(s); obj_hashtable<expr>::iterator it = u.begin(); obj_hashtable<expr>::iterator end = u.end(); for (; it != end; ++it) tmp.push_back(*it); return tmp; } unsigned proto_model::get_num_uninterpreted_sorts() const { return m_user_sort_factory->get_num_sorts(); } sort * proto_model::get_uninterpreted_sort(unsigned idx) const { SASSERT(idx < get_num_uninterpreted_sorts()); return m_user_sort_factory->get_sort(idx); } /** \brief Return true if the given sort is uninterpreted and has a finite interpretation in the model. */ bool proto_model::is_finite(sort * s) const { return m_manager.is_uninterp(s) && m_user_sort_factory->is_finite(s); } expr * proto_model::get_some_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_value(s); // there is no factory for the family id, then assume s is uninterpreted. return m_user_sort_factory->get_some_value(s); } } bool proto_model::get_some_values(sort * s, expr_ref & v1, expr_ref & v2) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_values(s, v1, v2); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_values(s, v1, v2); else return false; } } expr * proto_model::get_fresh_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_fresh_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_fresh_value(s); else // Use user_sort_factory if the theory has no support for model construnction. // This is needed when dummy theories are used for arithmetic or arrays. return m_user_sort_factory->get_fresh_value(s); } } void proto_model::register_value(expr * n) { sort * s = m_manager.get_sort(n); if (m_manager.is_uninterp(s)) { m_user_sort_factory->register_value(n); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) f->register_value(n); } } bool proto_model::is_as_array(expr * v) const { return is_app_of(v, m_afid, OP_AS_ARRAY); } void proto_model::compress() { ptr_vector<func_decl>::iterator it = m_func_decls.begin(); ptr_vector<func_decl>::iterator end = m_func_decls.end(); for (; it != end; ++it) { func_decl * f = *it; func_interp * fi = get_func_interp(f); SASSERT(fi != 0); fi->compress(); } } /** \brief Complete the interpretation fi of f if it is partial. If f does not have an interpretation in the given model, then this is a noop. */ void proto_model::complete_partial_func(func_decl * f) { func_interp * fi = get_func_interp(f); if (fi && fi->is_partial()) { expr * else_value = 0; #if 0 // For UFBV benchmarks, setting the "else" to false is not a good idea. // TODO: find a permanent solution. A possibility is to add another option. if (m_manager.is_bool(f->get_range())) { else_value = m_manager.mk_false(); } else { else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); } #else else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); #endif fi->set_else(else_value); } } /** \brief Set the (else) field of function interpretations... */ void proto_model::complete_partial_funcs() { if (m_model_partial) return; // m_func_decls may be "expanded" when we invoke get_some_value. // So, we must not use iterators to traverse it. for (unsigned i = 0; i < m_func_decls.size(); i++) { complete_partial_func(m_func_decls[i]); } } model * proto_model::mk_model() { TRACE("proto_model", tout << "mk_model\n"; model_v2_pp(tout, *this);); model * m = alloc(model, m_manager); decl2expr::iterator it1 = m_interp.begin(); decl2expr::iterator end1 = m_interp.end(); for (; it1 != end1; ++it1) { m->register_decl(it1->m_key, it1->m_value); } decl2finterp::iterator it2 = m_finterp.begin(); decl2finterp::iterator end2 = m_finterp.end(); for (; it2 != end2; ++it2) { m->register_decl(it2->m_key, it2->m_value); m_manager.dec_ref(it2->m_key); } m_finterp.reset(); // m took the ownership of the func_interp's unsigned sz = get_num_uninterpreted_sorts(); for (unsigned i = 0; i < sz; i++) { sort * s = get_uninterpreted_sort(i); TRACE("proto_model", tout << "copying uninterpreted sorts...\n" << mk_pp(s, m_manager) << "\n";); ptr_vector<expr> const& buf = get_universe(s); m->register_usort(s, buf.size(), buf.c_ptr()); } return m; } #if 0 #include"simplifier.h" #include"basic_simplifier_plugin.h" // Auxiliary function for computing fi(args[0], ..., args[fi.get_arity() - 1]). // The result is stored in result. // Return true if succeeded, and false otherwise. // It uses the simplifier s during the computation. bool eval(func_interp & fi, simplifier & s, expr * const * args, expr_ref & result) { bool actuals_are_values = true; if (fi.num_entries() != 0) { for (unsigned i = 0; actuals_are_values && i < fi.get_arity(); i++) { actuals_are_values = fi.m().is_value(args[i]); } } func_entry * entry = fi.get_entry(args); if (entry != 0) { result = entry->get_result(); return true; } TRACE("func_interp", tout << "failed to find entry for: "; for(unsigned i = 0; i < fi.get_arity(); i++) tout << mk_pp(args[i], fi.m()) << " "; tout << "\nis partial: " << fi.is_partial() << "\n";); if (!fi.eval_else(args, result)) { return false; } if (actuals_are_values && fi.args_are_values()) { // cheap case... we are done return true; } // build symbolic result... the actuals may be equal to the args of one of the entries. basic_simplifier_plugin * bs = static_cast<basic_simplifier_plugin*>(s.get_plugin(fi.m().get_basic_family_id())); for (unsigned k = 0; k < fi.num_entries(); k++) { func_entry const * curr = fi.get_entry(k); SASSERT(!curr->eq_args(fi.m(), fi.get_arity(), args)); if (!actuals_are_values || !curr->args_are_values()) { expr_ref_buffer eqs(fi.m()); unsigned i = fi.get_arity(); while (i > 0) { --i; expr_ref new_eq(fi.m()); bs->mk_eq(curr->get_arg(i), args[i], new_eq); eqs.push_back(new_eq); } SASSERT(eqs.size() == fi.get_arity()); expr_ref new_cond(fi.m()); bs->mk_and(eqs.size(), eqs.c_ptr(), new_cond); bs->mk_ite(new_cond, curr->get_result(), result, result); } } return true; } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { bool is_ok = true; SASSERT(is_well_sorted(m_manager, e)); TRACE("model_eval", tout << mk_pp(e, m_manager) << "\n"; tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n";); obj_map<expr, expr*> eval_cache; expr_ref_vector trail(m_manager); sbuffer<std::pair<expr*, expr*>, 128> todo; ptr_buffer<expr> args; expr * null = static_cast<expr*>(0); todo.push_back(std::make_pair(e, null)); simplifier m_simplifier(m_manager); expr * a; expr * expanded_a; while (!todo.empty()) { std::pair<expr *, expr *> & p = todo.back(); a = p.first; expanded_a = p.second; if (expanded_a != 0) { expr * r = 0; eval_cache.find(expanded_a, r); SASSERT(r != 0); todo.pop_back(); eval_cache.insert(a, r); TRACE("model_eval", tout << "orig:\n" << mk_pp(a, m_manager) << "\n"; tout << "after beta reduction:\n" << mk_pp(expanded_a, m_manager) << "\n"; tout << "new:\n" << mk_pp(r, m_manager) << "\n";); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!eval_cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(std::make_pair(t->get_arg(i), null)); } else { args.push_back(arg); } } if (!visited) { continue; } SASSERT(args.size() == t->get_num_args()); expr_ref new_t(m_manager); func_decl * f = t->get_decl(); if (!has_interpretation(f)) { // the model does not assign an interpretation to f. SASSERT(new_t.get() == 0); if (f->get_family_id() == null_family_id) { if (model_completion) { // create an interpretation for f. new_t = mk_some_interp_for(f); } else { TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } if (new_t.get() == 0) { // t is interpreted or model completion is disabled. m_simplifier.mk_app(f, num_args, args.c_ptr(), new_t); TRACE("model_eval", tout << mk_pp(t, m_manager) << " -> " << new_t << "\n";); trail.push_back(new_t); if (!is_app(new_t) || to_app(new_t)->get_decl() != f || is_select_of_model_value(new_t)) { // if the result is not of the form (f ...), then assume we must simplify it. expr * new_new_t = 0; if (!eval_cache.find(new_t.get(), new_new_t)) { todo.back().second = new_t; todo.push_back(std::make_pair(new_t, null)); continue; } else { new_t = new_new_t; } } } } else { // the model has an interpretaion for f. if (num_args == 0) { // t is a constant new_t = get_const_interp(f); } else { // t is a function application SASSERT(new_t.get() == 0); // try to use function graph first func_interp * fi = get_func_interp(f); SASSERT(fi->get_arity() == num_args); expr_ref r1(m_manager); // fi may be partial... if (!::eval(*fi, m_simplifier, args.c_ptr(), r1)) { SASSERT(fi->is_partial()); // fi->eval only fails when fi is partial. if (model_completion) { expr * r = get_some_value(f->get_range()); fi->set_else(r); SASSERT(!fi->is_partial()); new_t = r; } else { // f is an uninterpreted function, there is no need to use m_simplifier.mk_app new_t = m_manager.mk_app(f, num_args, args.c_ptr()); trail.push_back(new_t); TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } else { SASSERT(r1); trail.push_back(r1); TRACE("model_eval", tout << mk_pp(a, m_manager) << "\nevaluates to: " << r1 << "\n";); expr * r2 = 0; if (!eval_cache.find(r1.get(), r2)) { todo.back().second = r1; todo.push_back(std::make_pair(r1, null)); continue; } else { new_t = r2; } } } } TRACE("model_eval", tout << "orig:\n" << mk_pp(t, m_manager) << "\n"; tout << "new:\n" << mk_pp(new_t, m_manager) << "\n";); todo.pop_back(); SASSERT(new_t.get() != 0); eval_cache.insert(t, new_t); break; } case AST_VAR: SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; case AST_QUANTIFIER: TRACE("model_eval", tout << "found quantifier\n" << mk_pp(a, m_manager) << "\n";); is_ok = false; // evaluator does not handle quantifiers. SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; default: UNREACHABLE(); break; } } } if (!eval_cache.find(e, a)) { TRACE("model_eval", tout << "FAILED e: " << mk_bounded_pp(e, m_manager) << "\n";); UNREACHABLE(); } result = a; std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; TRACE("model_eval", ast_ll_pp(tout << "original: ", m_manager, e); ast_ll_pp(tout << "evaluated: ", m_manager, a); ast_ll_pp(tout << "reduced: ", m_manager, result.get()); tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n"; ); SASSERT(is_well_sorted(m_manager, result.get())); return is_ok; } #endif
33.812041
117
0.5228
flowingcloudbackup
a78e291fec91811edf30eb4e01b9dd7d602b798f
681
cpp
C++
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
// file: send_message.cpp // // LCM example program. // // compile with: // $ g++ -o send_message send_message.cpp -llcm // // On a system with pkg-config, you can also use: // $ g++ -o send_message send_message.cpp `pkg-config --cflags --libs lcm` #include <ctime> #include <lcm/lcm-cpp.hpp> #include <unistd.h> #include <iostream> #include "moos_double_t.hpp" int main(int argc, char ** argv) { lcm::LCM lcm; if(!lcm.good()) return 1; std::time_t result = std::time(NULL); moos_lcm_bridge_types::moos_double_t msg; msg.timestamp = (long) result; //msg_time; msg.value = 17; lcm.publish("NAV_HEADING", &msg); return 0; }
21.28125
75
0.631424
aspears1935
a78ec63364b2bcdc87c1a7ed8458d904f4065cc0
5,491
cpp
C++
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "VectorMatrixAssembler.h" #include <cassert> #include "NumLib/DOF/DOFTableUtil.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "LocalAssemblerInterface.h" #include "CoupledSolutionsForStaggeredScheme.h" #include "Process.h" namespace ProcessLib { VectorMatrixAssembler::VectorMatrixAssembler( std::unique_ptr<AbstractJacobianAssembler>&& jacobian_assembler) : _jacobian_assembler(std::move(jacobian_assembler)) { } void VectorMatrixAssembler::preAssemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_x = x.get(indices); local_assembler.preAssemble(t, local_x); } void VectorMatrixAssembler::assemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); local_assembler.assemble(t, local_x, _local_M_data, _local_K_data, _local_b_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); local_assembler.assembleWithCoupledTerm(t, _local_M_data, _local_K_data, _local_b_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } } void VectorMatrixAssembler::assembleWithJacobian( std::size_t const mesh_item_id, LocalAssemblerInterface& local_assembler, NumLib::LocalToGlobalIndexMap const& dof_table, const double t, GlobalVector const& x, GlobalVector const& xdot, const double dxdot_dx, const double dx_dx, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, GlobalMatrix& Jac, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_xdot = xdot.get(indices); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); _local_Jac_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); _jacobian_assembler->assembleWithJacobian( local_assembler, t, local_x, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); _jacobian_assembler->assembleWithJacobianAndCoupling( local_assembler, t, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } if (!_local_Jac_data.empty()) { auto const local_Jac = MathLib::toMatrix(_local_Jac_data, num_r_c, num_r_c); Jac.add(r_c_indices, local_Jac); } else { OGS_FATAL( "No Jacobian has been assembled! This might be due to programming " "errors in the local assembler of the current process."); } } } // namespace ProcessLib
33.481707
80
0.675651
yingtaohu
a78ffce8e4ff64c892ee4e8be84ed153b4e98f48
2,091
cpp
C++
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
yemaedahrav/cgal
ef771049b173007f2c566375bbd85a691adcee17
[ "CC0-1.0" ]
1
2019-04-08T23:06:26.000Z
2019-04-08T23:06:26.000Z
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
yemaedahrav/cgal
ef771049b173007f2c566375bbd85a691adcee17
[ "CC0-1.0" ]
1
2021-03-12T14:38:20.000Z
2021-03-12T14:38:20.000Z
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
szobov/cgal
e7b91b92b8c6949e3b62023bdd1e9f3ad8472626
[ "CC0-1.0" ]
1
2022-03-05T04:18:59.000Z
2022-03-05T04:18:59.000Z
#include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Curves_on_surface_topology.h> #include <CGAL/Path_on_surface.h> #include <CGAL/squared_distance_3.h> #include <CGAL/draw_face_graph_with_paths.h> #include <fstream> using Mesh = CGAL::Surface_mesh<CGAL::Simple_cartesian<double>::Point_3>; using Path_on_surface = CGAL::Surface_mesh_topology::Path_on_surface<Mesh>; double cycle_length(const Mesh& mesh, const Path_on_surface& cycle) { // Compute the length of the given cycle. double res=0; for (std::size_t i=0; i<cycle.length(); ++i) { res+=std::sqrt (CGAL::squared_distance(mesh.point(mesh.vertex(mesh.edge(cycle[i]), 0)), mesh.point(mesh.vertex(mesh.edge(cycle[i]), 1)))); } return res; } void display_cycle_info(const Mesh& mesh, const Path_on_surface& cycle) { // Display information about the given cycle. if (cycle.is_empty()) { std::cout<<"Empty."<<std::endl; return; } std::cout<<"Root: "<<mesh.point(mesh.vertex(mesh.edge(cycle[0]), 0))<<"; " <<"Number of edges: "<<cycle.length()<<"; " <<"Length: "<<cycle_length(mesh, cycle)<<std::endl; } int main(int argc, char* argv[]) { std::string filename(argc==1?"data/3torus.off":argv[1]); bool draw=(argc<3?false:(std::string(argv[2])=="-draw")); Mesh sm; if(!CGAL::read_polygon_mesh(filename, sm)) { std::cout<<"Cannot read file '"<<filename<<"'. Exiting program"<<std::endl; return EXIT_FAILURE; } std::cout<<"File '"<<filename<<"' loaded. Finding edge-width of the mesh..."<<std::endl; CGAL::Surface_mesh_topology::Curves_on_surface_topology<Mesh> cst(sm, true); Path_on_surface cycle1=cst.compute_edge_width(true); CGAL::Surface_mesh_topology::Euclidean_length_weight_functor<Mesh> wf(sm); Path_on_surface cycle2=cst.compute_shortest_non_contractible_cycle(wf, true); std::cout<<"Cycle 1 (pink): "; display_cycle_info(sm, cycle1); std::cout<<"Cycle 2 (green): "; display_cycle_info(sm, cycle2); if (draw) { CGAL::draw(sm, {cycle1, cycle2}); } return EXIT_SUCCESS; }
36.051724
90
0.683405
yemaedahrav
a790c61c43f1fa8b82035b8605f11a51d41f37b1
9,253
cpp
C++
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
#include "PrimitiveMesh.h" #include "Geometry.h" namespace Havana::Tools { namespace { using namespace Math; using namespace DirectX; using primitive_mesh_creator = void(*)(Scene&, const PrimitiveInitInfo& info); void CreatePlane(Scene& scene, const PrimitiveInitInfo& info); void CreateCube(Scene& scene, const PrimitiveInitInfo& info); void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info); void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info); primitive_mesh_creator creators[] { CreatePlane, CreateCube, CreateUVSphere, CreateICOSphere, CreateCylinder, CreateCapsule }; static_assert(_countof(creators) == PrimitiveMeshType::Count); struct Axis { enum: u32 { x = 0, y = 1, z = 2 }; }; Mesh CreatePlane(const PrimitiveInitInfo& info, u32 horizontalIndex = Axis::x, u32 verticalIndex = Axis::z, bool flipWinding = false, Vec3 offset = { -0.5f, 0.0f, -0.5f }, Vec2 uRange = { 0.0f, 1.0f }, Vec2 vRange = { 0.0f, 1.0f }) { assert(horizontalIndex < 3 && verticalIndex < 3); assert(horizontalIndex != verticalIndex); const u32 horizontalCount{ clamp(info.segments[horizontalIndex], 1u, 10u) }; const u32 verticalCount{ clamp(info.segments[verticalIndex], 1u, 10u) }; const f32 horizontalStep{ 1.0f / horizontalCount }; const f32 verticalStep{ 1.0f / verticalCount }; const f32 uStep{ (uRange.y - uRange.x) / horizontalCount }; const f32 vStep{ (vRange.y - vRange.x) / verticalCount }; Mesh m{}; Utils::vector<Vec2> uvs; for (u32 j{ 0 }; j <= verticalCount; j++) { for (u32 i{ 0 }; i <= horizontalCount; i++) { Vec3 position{ offset }; f32* const as_array{ &position.x }; as_array[horizontalIndex] += i * horizontalStep; as_array[verticalIndex] += j * verticalStep; m.positions.emplace_back(position.x * info.size.x, position.y * info.size.y, position.z * info.size.z); Vec2 uv{ uRange.x, 1.0f - vRange.x }; uv.x += i * uStep; uv.y -= j * vStep; uvs.emplace_back(uv); } } assert(m.positions.size() == (((u64)horizontalCount + 1)*((u64)verticalCount + 1))); const u32 rowLength{ horizontalCount + 1 }; // number of vertices in a row for (u32 j{ 0 }; j < verticalCount; j++) { u32 k{ 0 }; for (u32 i{ k }; i < horizontalCount; i++) { const u32 index[4] { i + j * rowLength, i + (j + 1) * rowLength, (i + 1) + j * rowLength, (i + 1) + (j + 1) * rowLength, }; // Triangle 1 m.rawIndices.emplace_back(index[0]); m.rawIndices.emplace_back(index[flipWinding ? 2 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 2]); // Triangle 2 m.rawIndices.emplace_back(index[2]); m.rawIndices.emplace_back(index[flipWinding ? 3 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 3]); } ++k; } const u32 numIndices{ 3 * 2 * horizontalCount * verticalCount }; assert(m.rawIndices.size() == numIndices); m.uvSets.resize(1); for (u32 i{ 0 }; i < numIndices; i++) { m.uvSets[0].emplace_back(uvs[m.rawIndices[i]]); } return m; } Mesh CreateUVSphere(const PrimitiveInitInfo& info) { const u32 phiCount{ clamp(info.segments[Axis::x], 3u, 64u) }; const u32 thetaCount{ clamp(info.segments[Axis::y], 2u, 64u) }; const f32 thetaStep{ pi / thetaCount }; const f32 phiStep{ twoPi / phiCount }; const u32 numVertices{ 2 + phiCount * (thetaCount - 1) }; const u32 numIndices{ 2 * 3 * phiCount + 2 * 3 * phiCount * (thetaCount - 2) }; Mesh m{}; m.name = "uvSphere"; m.positions.resize(numVertices); // Add top vertex u32 c{ 0 }; m.positions[c++] = { 0.0f, info.size.y, 0.0f }; // Add the body of the vertices for (u32 j{ 1 }; j < thetaCount; j++) { const f32 theta{ j * thetaStep }; for (u32 i{ 0 }; i < phiCount; i++) { const f32 phi{ i * phiStep }; m.positions[c++] = { info.size.x * XMScalarSin(theta) * XMScalarCos(phi), info.size.y * XMScalarCos(theta), -info.size.z * XMScalarSin(theta) * XMScalarSin(phi) }; } } // Add bottom vertex m.positions[c++] = { 0.0f, -info.size.y, 0.0f }; assert(numVertices == c); c = 0; m.rawIndices.resize(numIndices); Utils::vector<Vec2> uvs(numIndices); const f32 inverseThetaCount{ 1.0f / thetaCount }; const f32 inversePhiCount{ 1.0f / phiCount }; // Indices for top cap, connecting the north pole to the first ring // UV Coords at the same time for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { i * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 1; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 2; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { 1.0f - inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = phiCount; uvs[c] = { 1.0f, 1.0f - inverseThetaCount }; m.rawIndices[c++] = 1; // Indices for the section between the top and bottom rings // UV Coords at the same time for (u32 j{ 0 }; j < (thetaCount - 2); j++) { for (u32 i{ 0 }; i < (phiCount - 1); i++) { const u32 index[4] { 1 + i + j * phiCount, 1 + i + (j + 1) * phiCount, 1 + (i + 1) + (j + 1) * phiCount, 1 + (i + 1) + j * phiCount }; // Triangle 1 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { i * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } const u32 index[4] { phiCount + j * phiCount, phiCount + (j + 1) * phiCount, 1 + (j + 1) * phiCount, 1 + j * phiCount }; // Triangle 1 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { 1.0f, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } // Indices for bottom cap, connecting the south pole to the last ring // UV Coords at the same time const u32 southPoleIndex{ (u32)m.positions.size() - 1 }; for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { (i + 1) * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i + 1; uvs[c] = { i * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { 1.0f, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount; uvs[c] = { 1.0f - inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - 1; assert(c == numIndices); m.uvSets.emplace_back(uvs); return m; } void CreatePlane(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "plane"; lod.meshes.emplace_back(CreatePlane(info)); scene.lodGroups.emplace_back(lod); } void CreateCube(Scene& scene, const PrimitiveInitInfo& info) {} void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "uvSphere"; lod.meshes.emplace_back(CreateUVSphere(info)); scene.lodGroups.emplace_back(lod); } void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info) {} } // anonymous namespace EDITOR_INTERFACE void CreatePrimitiveMesh(SceneData* data, PrimitiveInitInfo* info) { assert(data && info); assert(info->type < PrimitiveMeshType::Count); Scene scene{}; creators[info->type](scene, *info); // TODO: process scene and pack to be sent to the Editor data->settings.calculateNormals = 1; ProcessScene(scene, data->settings); PackData(scene, *data); } }
30.238562
108
0.602832
ZackShrout
0427bd33aa17e82efd3c0f572e58865a8f46b5c5
16,935
cpp
C++
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** XML Configuration File Handling. Load Settings. Load & Save Hi-Scores. Copyright Chris White. See license.txt for more details. ***************************************************************************/ // see: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_propertytree/tutorial.html #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <iostream> #include "main.hpp" #include "config.hpp" #include "globals.hpp" #include "setup.hpp" #include "../utils.hpp" #include "engine/ohiscore.hpp" #include "engine/audio/osoundint.hpp" // api change in boost 1.56 #include <boost/version.hpp> #if (BOOST_VERSION >= 105600) typedef boost::property_tree::xml_writer_settings<std::string> xml_writer_settings; #else typedef boost::property_tree::xml_writer_settings<char> xml_writer_settings; #endif Config config; Config::Config(void) { } Config::~Config(void) { } void Config::init() { } using boost::property_tree::ptree; ptree pt_config; void Config::load(const std::string &filename) { // Load XML file and put its contents in property tree. // No namespace qualification is needed, because of Koenig // lookup on the second argument. If reading fails, exception // is thrown. try { read_xml(filename, pt_config, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { std::cout << "Error: " << e.what() << "\n"; } // ------------------------------------------------------------------------ // Menu Settings // ------------------------------------------------------------------------ menu.enabled = pt_config.get("menu.enabled", 1); menu.road_scroll_speed = pt_config.get("menu.roadspeed", 50); // ------------------------------------------------------------------------ // Video Settings // ------------------------------------------------------------------------ video.mode = pt_config.get("video.mode", 0); // Video Mode: Default is Windowed video.scale = pt_config.get("video.window.scale", 2); // Video Scale: Default is 2x video.scanlines = pt_config.get("video.scanlines", 0); // Scanlines video.fps = pt_config.get("video.fps", 2); // Default is 60 fps video.fps_count = pt_config.get("video.fps_counter", 0); // FPS Counter video.widescreen = pt_config.get("video.widescreen", 1); // Enable Widescreen Mode video.hires = pt_config.get("video.hires", 0); // Hi-Resolution Mode video.filtering = pt_config.get("video.filtering", 0); // Open GL Filtering Mode set_fps(video.fps); // ------------------------------------------------------------------------ // Sound Settings // ------------------------------------------------------------------------ sound.enabled = pt_config.get("sound.enable", 1); sound.advertise = pt_config.get("sound.advertise", 1); sound.preview = pt_config.get("sound.preview", 1); sound.fix_samples = pt_config.get("sound.fix_samples", 1); // Custom Music for (int i = 0; i < 4; i++) { std::string xmltag = "sound.custom_music.track"; xmltag += Utils::to_string(i+1); sound.custom_music[i].enabled = pt_config.get(xmltag + ".<xmlattr>.enabled", 0); sound.custom_music[i].title = pt_config.get(xmltag + ".title", "TRACK " +Utils::to_string(i+1)); sound.custom_music[i].filename= pt_config.get(xmltag + ".filename", "track"+Utils::to_string(i+1)+".wav"); } // ------------------------------------------------------------------------ // CannonBoard Settings // ------------------------------------------------------------------------ cannonboard.enabled = pt_config.get("cannonboard.<xmlattr>.enabled", 0); cannonboard.port = pt_config.get("cannonboard.port", "COM6"); cannonboard.baud = pt_config.get("cannonboard.baud", 57600); cannonboard.debug = pt_config.get("cannonboard.debug", 0); cannonboard.cabinet = pt_config.get("cannonboard.cabinet", 0); // ------------------------------------------------------------------------ // Controls // ------------------------------------------------------------------------ controls.gear = pt_config.get("controls.gear", 0); controls.steer_speed = pt_config.get("controls.steerspeed", 3); controls.pedal_speed = pt_config.get("controls.pedalspeed", 4); controls.keyconfig[0] = pt_config.get("controls.keyconfig.up", 273); controls.keyconfig[1] = pt_config.get("controls.keyconfig.down", 274); controls.keyconfig[2] = pt_config.get("controls.keyconfig.left", 276); controls.keyconfig[3] = pt_config.get("controls.keyconfig.right", 275); controls.keyconfig[4] = pt_config.get("controls.keyconfig.acc", 122); controls.keyconfig[5] = pt_config.get("controls.keyconfig.brake", 120); controls.keyconfig[6] = pt_config.get("controls.keyconfig.gear1", 32); controls.keyconfig[7] = pt_config.get("controls.keyconfig.gear2", 32); controls.keyconfig[8] = pt_config.get("controls.keyconfig.start", 49); controls.keyconfig[9] = pt_config.get("controls.keyconfig.coin", 53); controls.keyconfig[10] = pt_config.get("controls.keyconfig.menu", 286); controls.keyconfig[11] = pt_config.get("controls.keyconfig.view", 304); controls.padconfig[0] = pt_config.get("controls.padconfig.acc", 0); controls.padconfig[1] = pt_config.get("controls.padconfig.brake", 1); controls.padconfig[2] = pt_config.get("controls.padconfig.gear1", 2); controls.padconfig[3] = pt_config.get("controls.padconfig.gear2", 2); controls.padconfig[4] = pt_config.get("controls.padconfig.start", 3); controls.padconfig[5] = pt_config.get("controls.padconfig.coin", 4); controls.padconfig[6] = pt_config.get("controls.padconfig.menu", 5); controls.padconfig[7] = pt_config.get("controls.padconfig.view", 6); controls.analog = pt_config.get("controls.analog.<xmlattr>.enabled", 0); controls.pad_id = pt_config.get("controls.pad_id", 0); controls.axis[0] = pt_config.get("controls.analog.axis.wheel", 0); controls.axis[1] = pt_config.get("controls.analog.axis.accel", 2); controls.axis[2] = pt_config.get("controls.analog.axis.brake", 3); controls.asettings[0] = pt_config.get("controls.analog.wheel.zone", 75); controls.asettings[1] = pt_config.get("controls.analog.wheel.dead", 0); controls.asettings[2] = pt_config.get("controls.analog.pedals.dead", 0); controls.haptic = pt_config.get("controls.analog.haptic.<xmlattr>.enabled", 0); controls.max_force = pt_config.get("controls.analog.haptic.max_force", 9000); controls.min_force = pt_config.get("controls.analog.haptic.min_force", 8500); controls.force_duration= pt_config.get("controls.analog.haptic.force_duration", 20); // ------------------------------------------------------------------------ // Engine Settings // ------------------------------------------------------------------------ engine.dip_time = pt_config.get("engine.time", 0); engine.dip_traffic = pt_config.get("engine.traffic", 1); engine.freeze_timer = engine.dip_time == 4; engine.disable_traffic = engine.dip_traffic == 4; engine.dip_time &= 3; engine.dip_traffic &= 3; engine.freeplay = pt_config.get("engine.freeplay", 0) != 0; engine.jap = pt_config.get("engine.japanese_tracks", 0); engine.prototype = pt_config.get("engine.prototype", 0); // Additional Level Objects engine.level_objects = pt_config.get("engine.levelobjects", 1); engine.randomgen = pt_config.get("engine.randomgen", 1); engine.fix_bugs_backup = engine.fix_bugs = pt_config.get("engine.fix_bugs", 1) != 0; engine.fix_timer = pt_config.get("engine.fix_timer", 0) != 0; engine.layout_debug = pt_config.get("engine.layout_debug", 0) != 0; engine.new_attract = pt_config.get("engine.new_attract", 1) != 0; // ------------------------------------------------------------------------ // Time Trial Mode // ------------------------------------------------------------------------ ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); } bool Config::save(const std::string &filename) { // Save stuff pt_config.put("video.mode", video.mode); pt_config.put("video.window.scale", video.scale); pt_config.put("video.scanlines", video.scanlines); pt_config.put("video.fps", video.fps); pt_config.put("video.widescreen", video.widescreen); pt_config.put("video.hires", video.hires); pt_config.put("sound.enable", sound.enabled); pt_config.put("sound.advertise", sound.advertise); pt_config.put("sound.preview", sound.preview); pt_config.put("sound.fix_samples", sound.fix_samples); pt_config.put("controls.gear", controls.gear); pt_config.put("controls.steerspeed", controls.steer_speed); pt_config.put("controls.pedalspeed", controls.pedal_speed); pt_config.put("controls.keyconfig.up", controls.keyconfig[0]); pt_config.put("controls.keyconfig.down", controls.keyconfig[1]); pt_config.put("controls.keyconfig.left", controls.keyconfig[2]); pt_config.put("controls.keyconfig.right", controls.keyconfig[3]); pt_config.put("controls.keyconfig.acc", controls.keyconfig[4]); pt_config.put("controls.keyconfig.brake", controls.keyconfig[5]); pt_config.put("controls.keyconfig.gear1", controls.keyconfig[6]); pt_config.put("controls.keyconfig.gear2", controls.keyconfig[7]); pt_config.put("controls.keyconfig.start", controls.keyconfig[8]); pt_config.put("controls.keyconfig.coin", controls.keyconfig[9]); pt_config.put("controls.keyconfig.menu", controls.keyconfig[10]); pt_config.put("controls.keyconfig.view", controls.keyconfig[11]); pt_config.put("controls.padconfig.acc", controls.padconfig[0]); pt_config.put("controls.padconfig.brake", controls.padconfig[1]); pt_config.put("controls.padconfig.gear1", controls.padconfig[2]); pt_config.put("controls.padconfig.gear2", controls.padconfig[3]); pt_config.put("controls.padconfig.start", controls.padconfig[4]); pt_config.put("controls.padconfig.coin", controls.padconfig[5]); pt_config.put("controls.padconfig.menu", controls.padconfig[6]); pt_config.put("controls.padconfig.view", controls.padconfig[7]); pt_config.put("controls.analog.<xmlattr>.enabled", controls.analog); pt_config.put("engine.time", engine.freeze_timer ? 4 : engine.dip_time); pt_config.put("engine.traffic", engine.disable_traffic ? 4 : engine.dip_traffic); pt_config.put("engine.japanese_tracks", engine.jap); pt_config.put("engine.prototype", engine.prototype); pt_config.put("engine.levelobjects", engine.level_objects); pt_config.put("engine.new_attract", engine.new_attract); pt_config.put("time_trial.laps", ttrial.laps); pt_config.put("time_trial.traffic", ttrial.traffic); pt_config.put("continuous.traffic", cont_traffic), ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); try { write_xml(filename, pt_config, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving config: " << e.what() << "\n"; return false; } return true; } void Config::load_scores(const std::string &filename) { // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { e.what(); return; } // Game Scores for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); e->score = Utils::from_hex_string(pt.get<std::string>(xmltag + ".score", "0")); e->initial1 = pt.get(xmltag + ".initial1", ".")[0]; e->initial2 = pt.get(xmltag + ".initial2", ".")[0]; e->initial3 = pt.get(xmltag + ".initial3", ".")[0]; e->maptiles = Utils::from_hex_string(pt.get<std::string>(xmltag + ".maptiles", "20202020")); e->time = Utils::from_hex_string(pt.get<std::string>(xmltag + ".time" , "0")); if (e->initial1 == '.') e->initial1 = 0x20; if (e->initial2 == '.') e->initial2 = 0x20; if (e->initial3 == '.') e->initial3 = 0x20; } } void Config::save_scores(const std::string &filename) { // Create empty property tree object ptree pt; for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); pt.put(xmltag + ".score", Utils::to_hex_string(e->score)); pt.put(xmltag + ".initial1", e->initial1 == 0x20 ? "." : Utils::to_string((char) e->initial1)); // use . to represent space pt.put(xmltag + ".initial2", e->initial2 == 0x20 ? "." : Utils::to_string((char) e->initial2)); pt.put(xmltag + ".initial3", e->initial3 == 0x20 ? "." : Utils::to_string((char) e->initial3)); pt.put(xmltag + ".maptiles", Utils::to_hex_string(e->maptiles)); pt.put(xmltag + ".time", Utils::to_hex_string(e->time)); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } void Config::load_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Counter value that represents 1m 15s 0ms static const uint16_t COUNTER_1M_15 = 0x11D0; // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { for (int i = 0; i < 15; i++) ttrial.best_times[i] = COUNTER_1M_15; e.what(); return; } // Time Trial Scores for (int i = 0; i < 15; i++) { ttrial.best_times[i] = pt.get("time_trial.score" + Utils::to_string(i), COUNTER_1M_15); } } void Config::save_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Create empty property tree object ptree pt; // Time Trial Scores for (int i = 0; i < 15; i++) { pt.put("time_trial.score" + Utils::to_string(i), ttrial.best_times[i]); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } bool Config::clear_scores() { // Init Default Hiscores ohiscore.init_def_scores(); int clear = 0; // Remove XML files if they exist clear += remove(std::string(FILENAME_SCORES).append(".xml").c_str()); clear += remove(std::string(FILENAME_SCORES).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append(".xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_CONT).append(".xml").c_str()); clear += remove(std::string(FILENAME_CONT).append("_jap.xml").c_str()); // remove returns 0 on success return clear == 6; } void Config::set_fps(int fps) { video.fps = fps; // Set core FPS to 30fps or 60fps this->fps = video.fps == 0 ? 30 : 60; // Original game ticks sprites at 30fps but background scroll at 60fps tick_fps = video.fps < 2 ? 30 : 60; cannonball::frame_ms = 1000.0 / this->fps; #ifdef COMPILE_SOUND_CODE if (config.sound.enabled) cannonball::audio.stop_audio(); osoundint.init(); if (config.sound.enabled) cannonball::audio.start_audio(); #endif }
40.611511
138
0.58943
pdpdds
042c8582ce7be8f2c9d239da2727d8384847d5b2
22,847
cpp
C++
src/protocol/Connection.cpp
garrettr/ricochet
a22c729b3e912794a8af65879ed1b38573385657
[ "OpenSSL" ]
3,461
2015-01-01T09:44:50.000Z
2022-03-26T06:24:41.000Z
src/protocol/Connection.cpp
infocoms/Ricochet-DarkMode
0d3513965aac61f0af10369d05fc3a8cfa6f6d1c
[ "BSD-3-Clause" ]
498
2015-01-02T07:32:06.000Z
2022-01-22T16:44:07.000Z
src/protocol/Connection.cpp
infocoms/Ricochet-DarkMode
0d3513965aac61f0af10369d05fc3a8cfa6f6d1c
[ "BSD-3-Clause" ]
447
2015-01-08T01:19:39.000Z
2022-01-27T19:07:39.000Z
/* Ricochet - https://ricochet.im/ * Copyright (C) 2014, John Brooks <john.brooks@dereferenced.net> * * 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 names of the copyright owners 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 "Connection_p.h" #include "ControlChannel.h" #include "utils/Useful.h" #include <QTcpSocket> #include <QTimer> #include <QtEndian> #include <QDebug> using namespace Protocol; Connection::Connection(QTcpSocket *socket, Direction direction) : QObject() , d(new ConnectionPrivate(this)) { d->setSocket(socket, direction); } ConnectionPrivate::ConnectionPrivate(Connection *qq) : QObject(qq) , q(qq) , socket(0) , direction(Connection::ClientSide) , purpose(Connection::Purpose::Unknown) , wasClosed(false) , handshakeDone(false) , nextOutboundChannelId(-1) { ageTimer.start(); QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); timeout->setInterval(UnknownPurposeTimeout * 1000); connect(timeout, &QTimer::timeout, this, [this,timeout]() { if (purpose == Connection::Purpose::Unknown) { qDebug() << "Closing connection" << q << "with unknown purpose after timeout"; q->close(); } timeout->deleteLater(); } ); timeout->start(); } Connection::~Connection() { qDebug() << this << "Destroying connection"; // When we call closeImmediately, the list of channels will be cleared. // In the normal case, they will all use deleteLater to be freed at the // next event loop. Since the connection is being destructed immediately, // and we want to be certain that channels don't outlive it, copy the // list before it's cleared and delete them immediately afterwards. auto channels = d->channels; d->closeImmediately(); // These would be deleted by QObject ownership as well, but we want to // give them a chance to destruct before the connection d pointer is reset. foreach (Channel *c, channels) delete c; // Reset d pointer, so we'll crash nicely if anything tries to call // into Connection after this. d = 0; } ConnectionPrivate::~ConnectionPrivate() { // Reset q pointer, for the same reason as above q = 0; } Connection::Direction Connection::direction() const { return d->direction; } bool Connection::isConnected() const { bool re = d->socket && d->socket->state() == QAbstractSocket::ConnectedState; if (d->wasClosed) { Q_ASSERT(!re); } return re; } QString Connection::serverHostname() const { QString hostname; if (direction() == ClientSide) hostname = d->socket->peerName(); else if (direction() == ServerSide) hostname = d->socket->property("localHostname").toString(); if (!hostname.endsWith(QStringLiteral(".onion"))) { BUG() << "Connection does not have a valid server hostname:" << hostname; return QString(); } return hostname; } int Connection::age() const { return qRound(d->ageTimer.elapsed() / 1000.0); } void ConnectionPrivate::setSocket(QTcpSocket *s, Connection::Direction d) { if (socket) { BUG() << "Connection already has a socket"; return; } socket = s; direction = d; connect(socket, &QAbstractSocket::disconnected, this, &ConnectionPrivate::socketDisconnected); connect(socket, &QIODevice::readyRead, this, &ConnectionPrivate::socketReadable); socket->setParent(q); if (socket->state() != QAbstractSocket::ConnectedState) { BUG() << "Connection created with socket in a non-connected state" << socket->state(); } Channel *control = new ControlChannel(direction == Connection::ClientSide ? Channel::Outbound : Channel::Inbound, q); // Closing the control channel must also close the connection connect(control, &Channel::invalidated, q, &Connection::close); insertChannel(control); if (!control->isOpened() || control->identifier() != 0 || q->channel(0) != control) { BUG() << "Control channel on new connection is not set up properly"; q->close(); return; } if (direction == Connection::ClientSide) { // The server side is implicitly authenticated (by the transport) as the correct service, so grant that QString serverName = q->serverHostname(); if (serverName.isEmpty()) { BUG() << "Server side of connection doesn't have an authenticated name, aborting"; q->close(); return; } q->grantAuthentication(Connection::HiddenServiceAuth, serverName); // Send the introduction version handshake message char intro[] = { 0x49, 0x4D, 0x02, ProtocolVersion, 0 }; if (socket->write(intro, sizeof(intro)) < (int)sizeof(intro)) { qDebug() << "Failed writing introduction message to socket"; q->close(); return; } } } void Connection::close() { if (isConnected()) { Q_ASSERT(!d->wasClosed); qDebug() << "Disconnecting socket for connection" << this; d->socket->disconnectFromHost(); // If not fully closed in 5 seconds, abort QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); connect(timeout, &QTimer::timeout, d, &ConnectionPrivate::closeImmediately); timeout->start(5000); } } void ConnectionPrivate::closeImmediately() { if (socket) socket->abort(); if (!wasClosed) { BUG() << "Socket was forcefully closed but never emitted closed signal"; wasClosed = true; emit q->closed(); } if (!channels.isEmpty()) { foreach (Channel *c, channels) qDebug() << "Open channel:" << c << c->type() << c->connection(); BUG() << "Channels remain open after forcefully closing connection socket"; } } void ConnectionPrivate::socketDisconnected() { qDebug() << "Connection" << this << "disconnected"; closeAllChannels(); if (!wasClosed) { wasClosed = true; emit q->closed(); } } void ConnectionPrivate::socketReadable() { if (!handshakeDone) { qint64 available = socket->bytesAvailable(); if (direction == Connection::ClientSide && available >= 1) { // Expecting a single byte in response with the chosen version uchar version = ProtocolVersionFailed; if (socket->read(reinterpret_cast<char*>(&version), 1) < 1) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (version == 0) { qDebug() << "Server in outbound connection is using the version 1.0 protocol"; emit q->oldVersionNegotiated(socket); q->close(); return; } else if (version != ProtocolVersion) { qDebug() << "Version negotiation failed on outbound connection"; emit q->versionNegotiationFailed(); socket->abort(); return; } else emit q->ready(); } else if (direction == Connection::ServerSide && available >= 3) { // Expecting at least 3 bytes uchar intro[3] = { 0 }; qint64 re = socket->peek(reinterpret_cast<char*>(intro), sizeof(intro)); if (re < (int)sizeof(intro)) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 nVersions = intro[2]; if (intro[0] != 0x49 || intro[1] != 0x4D || nVersions == 0) { qDebug() << "Invalid introduction sequence on inbound connection"; socket->abort(); return; } if (available < (qint64)sizeof(intro) + nVersions) return; // Discard intro header re = socket->read(reinterpret_cast<char*>(intro), sizeof(intro)); QByteArray versions(nVersions, 0); re = socket->read(versions.data(), versions.size()); if (re != versions.size()) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 selectedVersion = ProtocolVersionFailed; foreach (quint8 v, versions) { if (v == ProtocolVersion) { selectedVersion = v; break; } } re = socket->write(reinterpret_cast<char*>(&selectedVersion), 1); if (re != 1) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (selectedVersion != ProtocolVersion) { qDebug() << "Version negotiation failed on inbound connection"; emit q->versionNegotiationFailed(); // Close gracefully to allow the response to write q->close(); return; } else emit q->ready(); } else { return; } } qint64 available; while ((available = socket->bytesAvailable()) >= PacketHeaderSize) { uchar header[PacketHeaderSize]; // Peek at the header first, to read the size of the packet and make sure // the entire thing is available within the buffer. qint64 re = socket->peek(reinterpret_cast<char*>(header), PacketHeaderSize); if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } else if (re < PacketHeaderSize) { BUG() << "Socket had" << available << "bytes available but peek only returned" << re; return; } Q_STATIC_ASSERT(PacketHeaderSize == 4); quint16 packetSize = qFromBigEndian<quint16>(header); quint16 channelId = qFromBigEndian<quint16>(&header[2]); if (packetSize < PacketHeaderSize) { qWarning() << "Corrupted data from connection (packet size is too small); disconnecting"; socket->abort(); return; } if (packetSize > available) break; // Read header out of the buffer and discard re = socket->read(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // Because of QTcpSocket buffering, we can expect that up to 'available' bytes // will read. Treat anything less as an error condition. BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } // Read data QByteArray data(packetSize - PacketHeaderSize, 0); re = (data.size() == 0) ? 0 : socket->read(data.data(), data.size()); if (re != data.size()) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // As above BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } Channel *channel = q->channel(channelId); if (!channel) { // XXX We should sanity-check and rate limit these responses better if (data.isEmpty()) { qDebug() << "Ignoring channel close message for non-existent channel" << channelId; } else { qDebug() << "Ignoring" << data.size() << "byte packet for non-existent channel" << channelId; // Send channel close message writePacket(channelId, QByteArray()); } continue; } if (channel->connection() != q) { // If this fails, something is extremely broken. It may be dangerous to continue // processing any data at all. Crash gracefully. BUG() << "Channel" << channelId << "found on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while handling packet"); return; } if (data.isEmpty()) { channel->closeChannel(); } else { channel->receivePacket(data); } } } bool ConnectionPrivate::writePacket(Channel *channel, const QByteArray &data) { if (channel->connection() != q) { // As above, dangerously broken, crash the process to avoid damage BUG() << "Writing packet for channel" << channel->identifier() << "on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while writing packet"); return false; } return writePacket(channel->identifier(), data); } bool ConnectionPrivate::writePacket(int channelId, const QByteArray &data) { if (channelId < 0 || channelId > UINT16_MAX) { BUG() << "Cannot write packet for channel with invalid identifier" << channelId; return false; } if (data.size() > PacketMaxDataSize) { BUG() << "Cannot write oversized packet of" << data.size() << "bytes to channel" << channelId; return false; } if (!q->isConnected()) { qDebug() << "Cannot write packet to closed connection"; return false; } Q_STATIC_ASSERT(PacketHeaderSize + PacketMaxDataSize <= UINT16_MAX); Q_STATIC_ASSERT(PacketHeaderSize == 4); uchar header[PacketHeaderSize] = { 0 }; qToBigEndian(static_cast<quint16>(PacketHeaderSize + data.size()), header); qToBigEndian(static_cast<quint16>(channelId), &header[2]); qint64 re = socket->write(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } re = socket->write(data); if (re != data.size()) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } return true; } int ConnectionPrivate::availableOutboundChannelId() { // Server opens even-nubmered channels, client opens odd-numbered bool evenNumbered = (direction == Connection::ServerSide); const int minId = evenNumbered ? 2 : 1; const int maxId = evenNumbered ? (UINT16_MAX-1) : UINT16_MAX; if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) nextOutboundChannelId = minId; // Find an unused id, trying a maximum of 100 times, using a random step to avoid collision for (int i = 0; i < 100 && channels.contains(nextOutboundChannelId); i++) { nextOutboundChannelId += 1 + (qrand() % 200); if (evenNumbered) nextOutboundChannelId += nextOutboundChannelId % 2; if (nextOutboundChannelId > maxId) nextOutboundChannelId = minId; } if (channels.contains(nextOutboundChannelId)) { // Abort the connection if we still couldn't find an id, because it's probably a nasty bug BUG() << "Can't find an available outbound channel ID for connection; aborting connection"; socket->abort(); return -1; } if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) { BUG() << "Selected a channel id that isn't within range"; return -1; } if (evenNumbered == bool(nextOutboundChannelId % 2)) { BUG() << "Selected a channel id that isn't valid for this side of the connection"; return -1; } int re = nextOutboundChannelId; nextOutboundChannelId += 2; return re; } bool ConnectionPrivate::isValidAvailableChannelId(int id, Connection::Direction side) { if (id < 1 || id > UINT16_MAX) return false; bool evenNumbered = bool(id % 2); if (evenNumbered == (side == Connection::ServerSide)) return false; if (channels.contains(id)) return false; return true; } bool ConnectionPrivate::insertChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to insert a channel assigned to a different connection"; return false; } if (channel->identifier() < 0) { BUG() << "Connection tried to insert a channel without a valid identifier"; return false; } if (channels.contains(channel->identifier())) { BUG() << "Connection tried to insert a channel with a duplicate id" << channel->identifier() << "- we have" << channels.value(channel->identifier()) << "and inserted" << channel; return false; } if (channel->parent() != q) { BUG() << "Connection inserted a channel without expected parent object. Fixing."; channel->setParent(q); } channels.insert(channel->identifier(), channel); return true; } void ConnectionPrivate::removeChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to remove a channel assigned to a different connection"; return; } // Out of caution, find the channel by pointer instead of identifier. This will make sure // it's always removed from the list, even if the identifier was somehow reset or lost. for (auto it = channels.begin(); it != channels.end(); ) { if (*it == channel) it = channels.erase(it); else it++; } } void ConnectionPrivate::closeAllChannels() { // Takes a copy, won't be broken by removeChannel calls foreach (Channel *channel, channels) channel->closeChannel(); if (!channels.isEmpty()) BUG() << "Channels remain open on connection after calling closeAllChannels"; } QHash<int,Channel*> Connection::channels() { return d->channels; } Channel *Connection::channel(int identifier) { return d->channels.value(identifier); } Connection::Purpose Connection::purpose() const { return d->purpose; } bool Connection::setPurpose(Purpose value) { if (d->purpose == value) return true; switch (value) { case Purpose::Unknown: BUG() << "A connection can't reset to unknown purpose"; return false; case Purpose::KnownContact: if (!hasAuthenticated(HiddenServiceAuth)) { BUG() << "Connection purpose cannot be KnownContact without authenticating a service"; return false; } break; case Purpose::OutboundRequest: if (d->direction != ClientSide) { BUG() << "Connection purpose cannot be OutboundRequest on an inbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to OutboundRequest"; return false; } break; case Purpose::InboundRequest: if (d->direction != ServerSide) { BUG() << "Connection purpose cannot be InboundRequest on an outbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to InboundRequest"; return false; } break; default: BUG() << "Purpose type" << int(value) << "is not defined"; return false; } Purpose old = d->purpose; d->purpose = value; emit purposeChanged(d->purpose, old); return true; } bool Connection::hasAuthenticated(AuthenticationType type) const { return d->authentication.contains(type); } bool Connection::hasAuthenticatedAs(AuthenticationType type, const QString &identity) const { auto it = d->authentication.find(type); if (!identity.isEmpty() && it != d->authentication.end()) return *it == identity; return false; } QString Connection::authenticatedIdentity(AuthenticationType type) const { return d->authentication.value(type); } void Connection::grantAuthentication(AuthenticationType type, const QString &identity) { if (hasAuthenticated(type)) { BUG() << "Tried to redundantly grant" << type << "authentication to connection"; return; } qDebug() << "Granting" << type << "authentication as" << identity << "to connection"; d->authentication.insert(type, identity); emit authenticated(type, identity); }
34.616667
130
0.600823
garrettr
042c9dc2cd0d2405799a6e5b0ca994ce53a07029
1,136
hpp
C++
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
//! @file Font.hpp #pragma once #include "../main.hpp" class Font { private: Font() = default; Font(const char* _name); Font(const Font&) = delete; Font(Font&&) = delete; virtual ~Font(); Font& operator=(const Font&) = delete; Font& operator=(Font&&) = delete; public: //! built-in font static const char* defaultFont; const char* getName() const { return name.c_str(); } TTF_Font* getTTF() { return font; } //! get the size of the given text string in pixels //! @param str the utf-8 string to get the size of //! @param out_w the integer to hold the width //! @param out_h the integer to hold the height //! @return 0 on success, non-zero on error int sizeText(const char* str, int* out_w, int* out_h) const; //! get the height of the font //! @return the font height in pixels int height() const; //! get a Font object from the engine //! @param name The Font name //! @return the Font or nullptr if it could not be retrieved static Font* get(const char* name); //! dump engine's font cache static void dumpCache(); private: std::string name; TTF_Font* font = nullptr; int pointSize = 16; };
23.666667
61
0.672535
PegasusEpsilon
042cf49955f381c33af736b13f3712813964bf1c
876
cc
C++
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
// Copyright (c) 2020 [Your Name]. All rights reserved. #include <sudoku/sudoku_parser.h> #include <iostream> #include <fstream> void HandleFile(std::string puzzle); int main(int argc, char** argv) { // There is always at least 1 argument -- the name of the program which we // don't care about if (argc == 1) { std::cout << "Please input a file " << std::endl; std::string file; std::cin >> file; HandleFile(file); } else { for (int i = 1; i < argc; i++) { HandleFile(argv[i]); } } } void HandleFile(std::string puzzle) { std::ifstream puzzle_stream(puzzle); if (puzzle_stream.fail()) { std::cout << "\nInvalid file" << std::endl; } else { sudoku_parser parser; std::istream& input_stream = puzzle_stream; std::ostream& output_stream = std::cout; input_stream >> parser; output_stream << parser; } }
25.028571
76
0.627854
CS126SP20
042f62b522d5c4e94a3a91d40ff19f6170803aee
329
cpp
C++
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int foo_1_6_11z() { double a, b, c, d, e, f, x, y; cin >> a; cin >> b; cin >> c; cin >> d; cin >> e; cin >> f; x = (e*d - b*f) / (d*a - b*c); y = (a*f - e*c) / (d*a - b*c); cout << x << " " << y << endl; }
14.954545
34
0.419453
Kaermor
042f890043cf1be0dcd3612270f70377536110a1
53,038
cpp
C++
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
#include <imgui/imgui.h> #include "terrain_editor.h" #include "editor/asset_browser.h" #include "editor/asset_compiler.h" #include "editor/entity_folders.h" #include "editor/prefab_system.h" #include "editor/studio_app.h" #include "editor/utils.h" #include "engine/crc32.h" #include "engine/crt.h" #include "engine/engine.h" #include "engine/geometry.h" #include "engine/log.h" #include "engine/os.h" #include "engine/path.h" #include "engine/prefab.h" #include "engine/profiler.h" #include "engine/resource_manager.h" #include "engine/universe.h" #include "physics/physics_scene.h" #include "renderer/culling_system.h" #include "renderer/editor/composite_texture.h" #include "renderer/material.h" #include "renderer/model.h" #include "renderer/render_scene.h" #include "renderer/renderer.h" #include "renderer/terrain.h" #include "renderer/texture.h" #include "stb/stb_image.h" namespace Lumix { static const ComponentType MODEL_INSTANCE_TYPE = reflection::getComponentType("model_instance"); static const ComponentType TERRAIN_TYPE = reflection::getComponentType("terrain"); static const ComponentType HEIGHTFIELD_TYPE = reflection::getComponentType("physical_heightfield"); static const char* HEIGHTMAP_SLOT_NAME = "Heightmap"; static const char* SPLATMAP_SLOT_NAME = "Splatmap"; static const char* DETAIL_ALBEDO_SLOT_NAME = "Detail albedo"; static const char* DETAIL_NORMAL_SLOT_NAME = "Detail normal"; static const float MIN_BRUSH_SIZE = 0.5f; struct PaintTerrainCommand final : IEditorCommand { struct Rectangle { int from_x; int from_y; int to_x; int to_y; }; PaintTerrainCommand(WorldEditor& editor, TerrainEditor::ActionType action_type, u16 grass_mask, u64 textures_mask, const DVec3& hit_pos, const Array<bool>& mask, float radius, float rel_amount, u16 flat_height, Vec3 color, EntityRef terrain, u32 layers_mask, Vec2 fixed_value, bool can_be_merged) : m_world_editor(editor) , m_terrain(terrain) , m_can_be_merged(can_be_merged) , m_new_data(editor.getAllocator()) , m_old_data(editor.getAllocator()) , m_items(editor.getAllocator()) , m_action_type(action_type) , m_textures_mask(textures_mask) , m_grass_mask(grass_mask) , m_mask(editor.getAllocator()) , m_flat_height(flat_height) , m_layers_masks(layers_mask) , m_fixed_value(fixed_value) { m_mask.resize(mask.size()); for (int i = 0; i < mask.size(); ++i) { m_mask[i] = mask[i]; } m_width = m_height = m_x = m_y = -1; Universe& universe = *editor.getUniverse(); const Transform entity_transform = universe.getTransform(terrain).inverted(); RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 local_pos = entity_transform.transform(hit_pos); float terrain_size = scene->getTerrainSize(terrain).x; local_pos = local_pos / terrain_size; local_pos.y = -1; Item& item = m_items.emplace(); item.m_local_pos = Vec3(local_pos); item.m_radius = radius / terrain_size; item.m_amount = rel_amount; item.m_color = color; } bool execute() override { if (m_new_data.empty()) { saveOldData(); generateNewData(); } applyData(m_new_data); return true; } void undo() override { applyData(m_old_data); } const char* getType() override { return "paint_terrain"; } bool merge(IEditorCommand& command) override { if (!m_can_be_merged) { return false; } PaintTerrainCommand& my_command = static_cast<PaintTerrainCommand&>(command); if (m_terrain == my_command.m_terrain && m_action_type == my_command.m_action_type && m_textures_mask == my_command.m_textures_mask && m_layers_masks == my_command.m_layers_masks) { my_command.m_items.push(m_items.back()); my_command.resizeData(); my_command.rasterItem(getDestinationTexture(), my_command.m_new_data, m_items.back()); return true; } return false; } private: struct Item { Rectangle getBoundingRectangle(int texture_size) const { Rectangle r; r.from_x = maximum(0, int(texture_size * (m_local_pos.x - m_radius) - 0.5f)); r.from_y = maximum(0, int(texture_size * (m_local_pos.z - m_radius) - 0.5f)); r.to_x = minimum(texture_size, int(texture_size * (m_local_pos.x + m_radius) + 0.5f)); r.to_y = minimum(texture_size, int(texture_size * (m_local_pos.z + m_radius) + 0.5f)); return r; } float m_radius; float m_amount; Vec3 m_local_pos; Vec3 m_color; }; private: Texture* getDestinationTexture() { const char* uniform_name; switch (m_action_type) { case TerrainEditor::REMOVE_GRASS: case TerrainEditor::LAYER: uniform_name = SPLATMAP_SLOT_NAME; break; default: uniform_name = HEIGHTMAP_SLOT_NAME; break; } RenderScene* scene = (RenderScene*)m_world_editor.getUniverse()->getScene(TERRAIN_TYPE); return scene->getTerrainMaterial(m_terrain)->getTextureByName(uniform_name); } u16 computeAverage16(const Texture* texture, int from_x, int to_x, int from_y, int to_y) { ASSERT(texture->format == gpu::TextureFormat::R16); u32 sum = 0; int texture_width = texture->width; for (int i = from_x, end = to_x; i < end; ++i) { for (int j = from_y, end2 = to_y; j < end2; ++j) { sum += ((u16*)texture->getData())[(i + j * texture_width)]; } } return u16(sum / (to_x - from_x) / (to_y - from_y)); } float getAttenuation(Item& item, int i, int j, int texture_size) const { float dist = ((texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); dist = powf(dist, 4); float max_dist = powf(texture_size * item.m_radius, 8); return 1.0f - minimum(dist / max_dist, 1.0f); } bool isMasked(float x, float y) { if (m_mask.size() == 0) return true; int s = int(sqrtf((float)m_mask.size())); int ix = int(x * s); int iy = int(y * s); return m_mask[int(ix + x * iy)]; } void rasterLayerItem(Texture* texture, Array<u8>& data, Item& item) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); u8 tex[64]; u32 tex_count = 0; for (u8 i = 0; i < 64; ++i) { if (m_textures_mask & ((u64)1 << i)) { tex[tex_count] = i; ++tex_count; } } if (tex_count == 0) return; for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (!isMasked(fx, fy)) continue; const int offset = 4 * (i - m_x + (j - m_y) * m_width); for (u32 layer = 0; layer < 2; ++layer) { if ((m_layers_masks & (1 << layer)) == 0) continue; const float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add <= 0) continue; if (((u64)1 << data[offset]) & m_textures_mask) { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] += minimum(255 - data[offset + 1], add); } } } else { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] = add; } } data[offset] = tex[rand() % tex_count]; } } } } } void rasterGrassItem(Texture* texture, Array<u8>& data, Item& item, bool remove) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (isMasked(fx, fy)) { int offset = 4 * (i - m_x + (j - m_y) * m_width) + 2; float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add > 0) { u16* tmp = ((u16*)&data[offset]); if (remove) { *tmp &= ~m_grass_mask; } else { *tmp |= m_grass_mask; } } } } } } void rasterSmoothHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); float avg = computeAverage16(texture, rect.from_x, rect.to_x, rect.from_y, rect.to_y); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += u16((avg - x) * item.m_amount * attenuation); ((u16*)&data[0])[offset] = x; } } } void rasterFlatHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { int offset = i - m_x + (j - m_y) * m_width; float dist = sqrtf( (texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); float t = (dist - texture_size * item.m_radius * item.m_amount) / (texture_size * item.m_radius * (1 - item.m_amount)); t = clamp(1 - t, 0.0f, 1.0f); u16 old_value = ((u16*)&data[0])[offset]; ((u16*)&data[0])[offset] = (u16)(m_flat_height * t + old_value * (1-t)); } } } void rasterItem(Texture* texture, Array<u8>& data, Item& item) { if (m_action_type == TerrainEditor::LAYER || m_action_type == TerrainEditor::REMOVE_GRASS) { if (m_textures_mask) { rasterLayerItem(texture, data, item); } if (m_grass_mask) { rasterGrassItem(texture, data, item, m_action_type == TerrainEditor::REMOVE_GRASS); } return; } else if (m_action_type == TerrainEditor::SMOOTH_HEIGHT) { rasterSmoothHeightItem(texture, data, item); return; } else if (m_action_type == TerrainEditor::FLAT_HEIGHT) { rasterFlatHeightItem(texture, data, item); return; } ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); const float STRENGTH_MULTIPLICATOR = 256.0f; float amount = maximum(item.m_amount * item.m_amount * STRENGTH_MULTIPLICATOR, 1.0f); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; int add = int(attenuation * amount); u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += m_action_type == TerrainEditor::RAISE_HEIGHT ? minimum(add, 0xFFFF - x) : maximum(-add, -x); ((u16*)&data[0])[offset] = x; } } } void generateNewData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_new_data.resize(bpp * maximum(1, (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y))); if(m_old_data.size() > 0) { memcpy(&m_new_data[0], &m_old_data[0], m_new_data.size()); } for (int item_index = 0; item_index < m_items.size(); ++item_index) { Item& item = m_items[item_index]; rasterItem(texture, m_new_data, item); } } void saveOldData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_x = rect.from_x; m_y = rect.from_y; m_width = rect.to_x - rect.from_x; m_height = rect.to_y - rect.from_y; m_old_data.resize(bpp * (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y)); int index = 0; for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (u32 k = 0; k < bpp; ++k) { m_old_data[index] = texture->getData()[(i + j * texture->width) * bpp + k]; ++index; } } } } void applyData(Array<u8>& data) { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); for (int j = m_y; j < m_y + m_height; ++j) { for (int i = m_x; i < m_x + m_width; ++i) { int index = bpp * (i + j * texture->width); for (u32 k = 0; k < bpp; ++k) { texture->getData()[index + k] = data[bpp * (i - m_x + (j - m_y) * m_width) + k]; } } } texture->onDataUpdated(m_x, m_y, m_width, m_height); if (m_action_type != TerrainEditor::LAYER && m_action_type != TerrainEditor::REMOVE_GRASS) { IScene* scene = m_world_editor.getUniverse()->getScene(crc32("physics")); if (!scene) return; auto* phy_scene = static_cast<PhysicsScene*>(scene); if (!scene->getUniverse().hasComponent(m_terrain, HEIGHTFIELD_TYPE)) return; phy_scene->updateHeighfieldData(m_terrain, m_x, m_y, m_width, m_height, &data[0], bpp); } } void resizeData() { Array<u8> new_data(m_world_editor.getAllocator()); Array<u8> old_data(m_world_editor.getAllocator()); auto texture = getDestinationTexture(); Rectangle rect; getBoundingRectangle(texture, rect); int new_w = rect.to_x - rect.from_x; const u32 bpp = gpu::getBytesPerPixel(texture->format); new_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); old_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); // original for (int row = rect.from_y; row < rect.to_y; ++row) { memcpy(&new_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); memcpy(&old_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); } // new for (int row = 0; row < m_height; ++row) { memcpy(&new_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_new_data[row * bpp * m_width], bpp * m_width); memcpy(&old_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_old_data[row * bpp * m_width], bpp * m_width); } m_x = rect.from_x; m_y = rect.from_y; m_height = rect.to_y - rect.from_y; m_width = rect.to_x - rect.from_x; m_new_data.swap(new_data); m_old_data.swap(old_data); } void getBoundingRectangle(Texture* texture, Rectangle& rect) { int s = texture->width; Item& item = m_items[0]; rect.from_x = maximum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), 0); rect.from_y = maximum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), 0); rect.to_x = minimum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), texture->width); rect.to_y = minimum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), texture->height); for (int i = 1; i < m_items.size(); ++i) { Item& item = m_items[i]; rect.from_x = minimum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), rect.from_x); rect.to_x = maximum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), rect.to_x); rect.from_y = minimum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), rect.from_y); rect.to_y = maximum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), rect.to_y); } rect.from_x = maximum(rect.from_x, 0); rect.to_x = minimum(rect.to_x, texture->width); rect.from_y = maximum(rect.from_y, 0); rect.to_y = minimum(rect.to_y, texture->height); } private: WorldEditor& m_world_editor; Array<u8> m_new_data; Array<u8> m_old_data; u64 m_textures_mask; u16 m_grass_mask; int m_width; int m_height; int m_x; int m_y; TerrainEditor::ActionType m_action_type; Array<Item> m_items; EntityRef m_terrain; Array<bool> m_mask; u16 m_flat_height; u32 m_layers_masks; Vec2 m_fixed_value; bool m_can_be_merged; }; TerrainEditor::~TerrainEditor() { m_app.removeAction(&m_smooth_terrain_action); m_app.removeAction(&m_lower_terrain_action); m_app.removeAction(&m_remove_grass_action); m_app.removeAction(&m_remove_entity_action); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } m_app.removePlugin(*this); } TerrainEditor::TerrainEditor(StudioApp& app) : m_app(app) , m_color(1, 1, 1) , m_current_brush(0) , m_selected_prefabs(app.getAllocator()) , m_brush_mask(app.getAllocator()) , m_brush_texture(nullptr) , m_flat_height(0) , m_is_enabled(false) , m_size_spread(1, 1) , m_y_spread(0, 0) , m_albedo_composite(app.getAllocator()) { m_smooth_terrain_action.init("Smooth terrain", "Terrain editor - smooth", "smoothTerrain", "", false); m_lower_terrain_action.init("Lower terrain", "Terrain editor - lower", "lowerTerrain", "", false); m_remove_grass_action.init("Remove grass from terrain", "Terrain editor - remove grass", "removeGrassFromTerrain", "", false); m_remove_entity_action.init("Remove entities from terrain", "Terrain editor - remove entities", "removeEntitiesFromTerrain", "", false); app.addAction(&m_smooth_terrain_action); app.addAction(&m_lower_terrain_action); app.addAction(&m_remove_grass_action); app.addAction(&m_remove_entity_action); app.addPlugin(*this); m_terrain_brush_size = 10; m_terrain_brush_strength = 0.1f; m_textures_mask = 0b1; m_layers_mask = 0b1; m_grass_mask = 1; m_is_align_with_normal = false; m_is_rotate_x = false; m_is_rotate_y = false; m_is_rotate_z = false; m_rotate_x_spread = m_rotate_y_spread = m_rotate_z_spread = Vec2(0, PI * 2); } void TerrainEditor::increaseBrushSize() { if (m_terrain_brush_size < 10) { ++m_terrain_brush_size; return; } m_terrain_brush_size = minimum(100.0f, m_terrain_brush_size + 10); } void TerrainEditor::decreaseBrushSize() { if (m_terrain_brush_size < 10) { m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 1.0f); return; } m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 10.0f); } void TerrainEditor::drawCursor(RenderScene& scene, EntityRef entity, const DVec3& center) const { PROFILE_FUNCTION(); Terrain* terrain = scene.getTerrain(entity); constexpr int SLICE_COUNT = 30; constexpr float angle_step = PI * 2 / SLICE_COUNT; if (m_mode == Mode::HEIGHT && m_is_flat_height && ImGui::GetIO().KeyCtrl) { scene.addDebugCross(center, 1.0f, 0xff0000ff); return; } float brush_size = m_terrain_brush_size; const Vec3 local_center = Vec3(getRelativePosition(center, entity, scene.getUniverse())); const Transform terrain_transform = scene.getUniverse().getTransform(entity); for (int i = 0; i < SLICE_COUNT + 1; ++i) { const float angle = i * angle_step; const float next_angle = i * angle_step + angle_step; Vec3 local_from = local_center + Vec3(cosf(angle), 0, sinf(angle)) * brush_size; local_from.y = terrain->getHeight(local_from.x, local_from.z); local_from.y += 0.25f; Vec3 local_to = local_center + Vec3(cosf(next_angle), 0, sinf(next_angle)) * brush_size; local_to.y = terrain->getHeight(local_to.x, local_to.z); local_to.y += 0.25f; const DVec3 from = terrain_transform.transform(local_from); const DVec3 to = terrain_transform.transform(local_to); scene.addDebugLine(from, to, 0xffff0000); } const Vec3 rel_pos = Vec3(terrain_transform.inverted().transform(center)); const i32 w = terrain->getWidth(); const i32 h = terrain->getHeight(); const float scale = terrain->getXZScale(); const IVec3 p = IVec3(rel_pos / scale); const i32 half_extents = i32(1 + brush_size / scale); for (i32 j = p.z - half_extents; j <= p.z + half_extents; ++j) { for (i32 i = p.x - half_extents; i <= p.x + half_extents; ++i) { DVec3 p00(i * scale, 0, j * scale); DVec3 p10((i + 1) * scale, 0, j * scale); DVec3 p11((i + 1) * scale, 0, (j + 1) * scale); DVec3 p01(i * scale, 0, (j + 1) * scale); p00.y = terrain->getHeight(i, j); p10.y = terrain->getHeight(i + 1, j); p11.y = terrain->getHeight(i + 1, j + 1); p01.y = terrain->getHeight(i, j + 1); p00 = terrain_transform.transform(p00); p10 = terrain_transform.transform(p10); p01 = terrain_transform.transform(p01); p11 = terrain_transform.transform(p11); scene.addDebugLine(p10, p01, 0xff800000); scene.addDebugLine(p10, p11, 0xff800000); scene.addDebugLine(p00, p10, 0xff800000); scene.addDebugLine(p01, p11, 0xff800000); scene.addDebugLine(p00, p01, 0xff800000); } } } DVec3 TerrainEditor::getRelativePosition(const DVec3& world_pos, EntityRef terrain, Universe& universe) const { const Transform transform = universe.getTransform(terrain); const Transform inv_transform = transform.inverted(); return inv_transform.transform(world_pos); } u16 TerrainEditor::getHeight(const DVec3& world_pos, RenderScene* scene, EntityRef terrain) const { const DVec3 rel_pos = getRelativePosition(world_pos, terrain, scene->getUniverse()); ComponentUID cmp; cmp.entity = terrain; cmp.scene = scene; cmp.type = TERRAIN_TYPE; Texture* heightmap = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); if (!heightmap) return 0; u16* data = (u16*)heightmap->getData(); float scale = scene->getTerrainXZScale(terrain); return data[int(rel_pos.x / scale) + int(rel_pos.z / scale) * heightmap->width]; } bool TerrainEditor::onMouseDown(UniverseView& view, int x, int y) { if (!m_is_enabled) return false; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return false; Universe& universe = *editor.getUniverse(); bool is_terrain = universe.hasComponent(selected_entities[0], TERRAIN_TYPE); if (!is_terrain) return false; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(selected_entities[0], origin, dir); if (!hit.is_hit) return false; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, selected_entities[0]); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, selected_entities[0]); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, false, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, false, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, false, selected_entities[0], editor); break; } return true; } static void getProjections(const Vec3& axis, const Vec3 vertices[8], float& min, float& max) { max = dot(vertices[0], axis); min = max; for(int i = 1; i < 8; ++i) { float d = dot(vertices[i], axis); min = minimum(d, min); max = maximum(d, max); } } static bool overlaps(float min1, float max1, float min2, float max2) { return (min1 <= min2 && min2 <= max1) || (min2 <= min1 && min1 <= max2); } static bool testOBBCollision(const AABB& a, const Matrix& mtx_b, const AABB& b) { Vec3 box_a_points[8]; Vec3 box_b_points[8]; a.getCorners(Matrix::IDENTITY, box_a_points); b.getCorners(mtx_b, box_b_points); const Vec3 normals[] = {Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals[i], box_a_points, box_a_min, box_a_max); getProjections(normals[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } Vec3 normals_b[] = { normalize(mtx_b.getXVector()), normalize(mtx_b.getYVector()), normalize(mtx_b.getZVector())}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals_b[i], box_a_points, box_a_min, box_a_max); getProjections(normals_b[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } return true; } void TerrainEditor::removeEntities(const DVec3& hit_pos, WorldEditor& editor) const { if (m_selected_prefabs.empty()) return; PrefabSystem& prefab_system = editor.getPrefabSystem(); PROFILE_FUNCTION(); Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); const AABB brush_aabb(Vec3(-m_terrain_brush_size), Vec3(m_terrain_brush_size)); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); } if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); } if(!meshes) return; editor.beginCommandGroup("remove_entities"); if (m_selected_prefabs.empty()) { meshes->forEach([&](EntityRef entity){ if (prefab_system.getPrefab(entity) == 0) return; const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); }); } else { meshes->forEach([&](EntityRef entity){ for (auto* res : m_selected_prefabs) { if ((prefab_system.getPrefab(entity) & 0xffffFFFF) == res->getPath().getHash()) { const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); } } }); } editor.endCommandGroup(); meshes->free(scene->getEngine().getPageAllocator()); } static bool isOBBCollision(RenderScene& scene, const CullResult* meshes, const Transform& model_tr, Model* model, bool ignore_not_in_folder, const EntityFolders& folders, EntityFolders::FolderID folder) { float radius_a_squared = model->getOriginBoundingRadius() * model_tr.scale; radius_a_squared = radius_a_squared * radius_a_squared; Universe& universe = scene.getUniverse(); Span<const ModelInstance> model_instances = scene.getModelInstances(); const Transform* transforms = universe.getTransforms(); while(meshes) { const EntityRef* entities = meshes->entities; for (u32 i = 0, c = meshes->header.count; i < c; ++i) { const EntityRef mesh = entities[i]; // we resolve collisions when painting by removing recently added mesh, but we do not refresh `meshes` // so it can contain invalid entities if (!universe.hasEntity(mesh)) continue; const ModelInstance& model_instance = model_instances[mesh.index]; const Transform& tr_b = transforms[mesh.index]; const float radius_b = model_instance.model->getOriginBoundingRadius() * tr_b.scale; const float radius_squared = radius_a_squared + radius_b * radius_b; if (squaredLength(model_tr.pos - tr_b.pos) < radius_squared) { const Transform rel_tr = model_tr.inverted() * tr_b; Matrix mtx = rel_tr.rot.toMatrix(); mtx.multiply3x3(rel_tr.scale); mtx.setTranslation(Vec3(rel_tr.pos)); if (testOBBCollision(model->getAABB(), mtx, model_instance.model->getAABB())) { if (ignore_not_in_folder && folders.getFolder(EntityRef{mesh.index}) != folder) { continue; } return true; } } } meshes = meshes->header.next; } return false; } static bool areAllReady(Span<PrefabResource*> prefabs) { for (PrefabResource* p : prefabs) if (!p->isReady()) return false; return true; } void TerrainEditor::paintEntities(const DVec3& hit_pos, WorldEditor& editor, EntityRef terrain) const { PROFILE_FUNCTION(); if (m_selected_prefabs.empty()) return; if (!areAllReady(m_selected_prefabs)) return; auto& prefab_system = editor.getPrefabSystem(); editor.beginCommandGroup("paint_entities"); { Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); const Transform terrain_tr = universe.getTransform(terrain); const Transform inv_terrain_tr = terrain_tr.inverted(); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); const EntityFolders& folders = editor.getEntityFolders(); const EntityFolders::FolderID folder = folders.getSelectedFolder(); Vec2 size = scene->getTerrainSize(terrain); float scale = 1.0f - maximum(0.01f, m_terrain_brush_strength); for (int i = 0; i <= m_terrain_brush_size * m_terrain_brush_size / 100.0f * m_terrain_brush_strength; ++i) { const float angle = randFloat(0, PI * 2); const float dist = randFloat(0, 1.0f) * m_terrain_brush_size; const float y = randFloat(m_y_spread.x, m_y_spread.y); DVec3 pos(hit_pos.x + cosf(angle) * dist, 0, hit_pos.z + sinf(angle) * dist); const Vec3 terrain_pos = Vec3(inv_terrain_tr.transform(pos)); if (terrain_pos.x >= 0 && terrain_pos.z >= 0 && terrain_pos.x <= size.x && terrain_pos.z <= size.y) { pos.y = scene->getTerrainHeightAt(terrain, terrain_pos.x, terrain_pos.z) + y; pos.y += terrain_tr.pos.y; Quat rot(0, 0, 0, 1); if(m_is_align_with_normal) { Vec3 normal = scene->getTerrainNormalAt(terrain, terrain_pos.x, terrain_pos.z); Vec3 dir = normalize(cross(normal, Vec3(1, 0, 0))); Matrix mtx = Matrix::IDENTITY; mtx.setXVector(cross(normal, dir)); mtx.setYVector(normal); mtx.setXVector(dir); rot = mtx.getRotation(); } else { if (m_is_rotate_x) { float angle = randFloat(m_rotate_x_spread.x, m_rotate_x_spread.y); Quat q(Vec3(1, 0, 0), angle); rot = q * rot; } if (m_is_rotate_y) { float angle = randFloat(m_rotate_y_spread.x, m_rotate_y_spread.y); Quat q(Vec3(0, 1, 0), angle); rot = q * rot; } if (m_is_rotate_z) { float angle = randFloat(m_rotate_z_spread.x, m_rotate_z_spread.y); Quat q(rot.rotate(Vec3(0, 0, 1)), angle); rot = q * rot; } } float size = randFloat(m_size_spread.x, m_size_spread.y); int random_idx = rand(0, m_selected_prefabs.size() - 1); if (!m_selected_prefabs[random_idx]) continue; const EntityPtr entity = prefab_system.instantiatePrefab(*m_selected_prefabs[random_idx], pos, rot, size); if (entity.isValid()) { if (universe.hasComponent((EntityRef)entity, MODEL_INSTANCE_TYPE)) { Model* model = scene->getModelInstanceModel((EntityRef)entity); const Transform tr = { pos, rot, size * scale }; if (isOBBCollision(*scene, meshes, tr, model, m_ignore_entities_not_in_folder, folders, folder)) { editor.undo(); } } } } } meshes->free(m_app.getEngine().getPageAllocator()); } editor.endCommandGroup(); } void TerrainEditor::onMouseMove(UniverseView& view, int x, int y, int, int) { if (!m_is_enabled) return; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return; const EntityRef entity = selected_entities[0]; Universe& universe = *editor.getUniverse(); if (!universe.hasComponent(entity, TERRAIN_TYPE)) return; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if (!hit.is_hit) return; if (hit.entity != entity) return; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, entity); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, entity); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, true, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, true, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, true, selected_entities[0], editor); break; } } Material* TerrainEditor::getMaterial(ComponentUID cmp) const { if (!cmp.isValid()) return nullptr; auto* scene = static_cast<RenderScene*>(cmp.scene); return scene->getTerrainMaterial((EntityRef)cmp.entity); } static Array<u8> getFileContent(const char* path, IAllocator& allocator) { Array<u8> res(allocator); os::InputFile file; if (!file.open(path)) return res; res.resize((u32)file.size()); if (!file.read(res.begin(), res.byte_size())) res.clear(); file.close(); return res; } void TerrainEditor::layerGUI(ComponentUID cmp) { m_mode = Mode::LAYER; RenderScene* scene = static_cast<RenderScene*>(cmp.scene); Material* material = scene->getTerrainMaterial((EntityRef)cmp.entity); if (!material) return; if (material->getTextureByName(SPLATMAP_SLOT_NAME) && ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(SPLATMAP_SLOT_NAME)->save(); } if (m_brush_texture) { ImGui::Image(m_brush_texture->handle, ImVec2(100, 100)); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_TIMES, ImGui::GetStyle().Colors[ImGuiCol_Text], "Clear brush mask")) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); m_brush_mask.clear(); m_brush_texture = nullptr; } ImGui::SameLine(); } ImGui::SameLine(); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_MASK, ImGui::GetStyle().Colors[ImGuiCol_Text], "Select brush mask")) { char filename[LUMIX_MAX_PATH]; if (os::getOpenFilename(Span(filename), "All\0*.*\0", nullptr)) { int image_width; int image_height; int image_comp; Array<u8> tmp = getFileContent(filename, m_app.getAllocator()); auto* data = stbi_load_from_memory(tmp.begin(), tmp.byte_size(), &image_width, &image_height, &image_comp, 4); if (data) { m_brush_mask.resize(image_width * image_height); for (int j = 0; j < image_width; ++j) { for (int i = 0; i < image_width; ++i) { m_brush_mask[i + j * image_width] = data[image_comp * (i + j * image_width)] > 128; } } Engine& engine = m_app.getEngine(); ResourceManagerHub& rm = engine.getResourceManager(); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } Lumix::IPlugin* plugin = engine.getPluginManager().getPlugin("renderer"); Renderer& renderer = *static_cast<Renderer*>(plugin); m_brush_texture = LUMIX_NEW(m_app.getAllocator(), Texture)( Path("brush_texture"), *rm.get(Texture::TYPE), renderer, m_app.getAllocator()); m_brush_texture->create(image_width, image_height, gpu::TextureFormat::RGBA8, data, image_width * image_height * 4); stbi_image_free(data); } } } char grass_mode_shortcut[64]; if (m_remove_entity_action.shortcutText(Span(grass_mode_shortcut))) { ImGuiEx::Label(StaticString<64>("Grass mode (", grass_mode_shortcut, ")")); ImGui::TextUnformatted(m_remove_entity_action.isActive() ? "Remove" : "Add"); } int type_count = scene->getGrassCount((EntityRef)cmp.entity); for (int i = 0; i < type_count; ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = (m_grass_mask & (1 << i)) != 0; m_app.getAssetBrowser().tile(scene->getGrassPath((EntityRef)cmp.entity, i), b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_grass_mask = 0; if (b) { m_grass_mask &= ~(1 << i); } else { m_grass_mask |= 1 << i; } } } Texture* albedo = material->getTextureByName(DETAIL_ALBEDO_SLOT_NAME); Texture* normal = material->getTextureByName(DETAIL_NORMAL_SLOT_NAME); if (!albedo) { ImGui::Text("No detail albedo in material %s", material->getPath().c_str()); return; } if (albedo->isFailure()) { ImGui::Text("%s failed to load", albedo->getPath().c_str()); return; } if (!albedo->isReady()) { ImGui::Text("Loading %s...", albedo->getPath().c_str()); return; } if (!normal) { ImGui::Text("No detail normal in material %s", material->getPath().c_str()); return; } if (normal->isFailure()) { ImGui::Text("%s failed to load", normal->getPath().c_str()); return; } if (!normal->isReady()) { ImGui::Text("Loading %s...", normal->getPath().c_str()); return; } if (albedo->depth != normal->depth) { ImGui::TextWrapped(ICON_FA_EXCLAMATION_TRIANGLE " albedo texture %s has different number of layers than normal texture %s" , albedo->getPath().c_str() , normal->getPath().c_str()); } bool primary = m_layers_mask & 0b1; bool secondary = m_layers_mask & 0b10; // TODO shader does not handle secondary surfaces now, so pretend they don't exist // uncomment once shader is ready m_layers_mask = 0xb11; /*ImGuiEx::Label("Primary surface"); ImGui::Checkbox("##prim", &primary); ImGuiEx::Label("Secondary surface"); ImGui::Checkbox("##sec", &secondary); if (secondary) { bool use = m_fixed_value.x >= 0; ImGuiEx::Label("Use fixed value"); if (ImGui::Checkbox("##fxd", &use)) { m_fixed_value.x = use ? 0.f : -1.f; } if (m_fixed_value.x >= 0) { ImGuiEx::Label("Min/max"); ImGui::DragFloatRange2("##minmax", &m_fixed_value.x, &m_fixed_value.y, 0.01f, 0, 1); } }*/ FileSystem& fs = m_app.getEngine().getFileSystem(); if (albedo->getPath() != m_albedo_composite_path) { m_albedo_composite.loadSync(fs, albedo->getPath()); m_albedo_composite_path = albedo->getPath(); } m_layers_mask = (primary ? 1 : 0) | (secondary ? 0b10 : 0); for (i32 i = 0; i < m_albedo_composite.layers.size(); ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = m_textures_mask & ((u64)1 << i); m_app.getAssetBrowser().tile(m_albedo_composite.layers[i].red.path, b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_textures_mask = 0; if (b) m_textures_mask &= ~((u64)1 << i); else m_textures_mask |= (u64)1 << i; } if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) { ImGui::OpenPopup(StaticString<8>("ctx", i)); } if (ImGui::BeginPopup(StaticString<8>("ctx", i))) { if (ImGui::Selectable("Remove surface")) { compositeTextureRemoveLayer(albedo->getPath(), i); compositeTextureRemoveLayer(normal->getPath(), i); m_albedo_composite_path = ""; } ImGui::EndPopup(); } } if (albedo->depth < 255) { if (ImGui::Button(ICON_FA_PLUS "Add surface")) ImGui::OpenPopup("Add surface"); } ImGui::SetNextWindowSizeConstraints(ImVec2(200, 100), ImVec2(FLT_MAX, FLT_MAX)); if (ImGui::BeginPopupModal("Add surface")) { ImGuiEx::Label("Albedo"); m_app.getAssetBrowser().resourceInput("albedo", Span(m_add_layer_popup.albedo), Texture::TYPE); ImGuiEx::Label("Normal"); m_app.getAssetBrowser().resourceInput("normal", Span(m_add_layer_popup.normal), Texture::TYPE); if (ImGui::Button(ICON_FA_PLUS "Add")) { saveCompositeTexture(albedo->getPath(), m_add_layer_popup.albedo); saveCompositeTexture(normal->getPath(), m_add_layer_popup.normal); m_albedo_composite_path = ""; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_TIMES "Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } void TerrainEditor::compositeTextureRemoveLayer(const Path& path, i32 layer) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { texture.layers.erase(layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::saveCompositeTexture(const Path& path, const char* channel) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { CompositeTexture::Layer new_layer; new_layer.red.path = channel; new_layer.red.src_channel = 0; new_layer.green.path = channel; new_layer.green.src_channel = 1; new_layer.blue.path = channel; new_layer.blue.src_channel = 2; new_layer.alpha.path = channel; new_layer.alpha.src_channel = 3; texture.layers.push(new_layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::entityGUI() { m_mode = Mode::ENTITY; ImGuiEx::Label("Ignore other folders (?)"); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("When placing entities, ignore collisions with " "entities in other folders than the currently selected folder " "in hierarchy view"); } ImGui::Checkbox("##ignore_filter", &m_ignore_entities_not_in_folder); static char filter[100] = {0}; const float w = ImGui::CalcTextSize(ICON_FA_TIMES).x + ImGui::GetStyle().ItemSpacing.x * 2; ImGui::SetNextItemWidth(-w); ImGui::InputTextWithHint("##filter", "Filter", filter, sizeof(filter)); ImGui::SameLine(); if (ImGuiEx::IconButton(ICON_FA_TIMES, "Clear filter")) { filter[0] = '\0'; } static ImVec2 size(-1, 200); if (ImGui::ListBoxHeader("##prefabs", size)) { auto& resources = m_app.getAssetCompiler().lockResources(); u32 count = 0; for (const AssetCompiler::ResourceItem& res : resources) { if (res.type != PrefabResource::TYPE) continue; ++count; if (filter[0] != 0 && stristr(res.path.c_str(), filter) == nullptr) continue; int selected_idx = m_selected_prefabs.find([&](PrefabResource* r) -> bool { return r && r->getPath() == res.path; }); bool selected = selected_idx >= 0; const char* loading_str = selected_idx >= 0 && m_selected_prefabs[selected_idx]->isEmpty() ? " - loading..." : ""; StaticString<LUMIX_MAX_PATH + 15> label(res.path.c_str(), loading_str); if (ImGui::Selectable(label, &selected)) { if (selected) { ResourceManagerHub& manager = m_app.getEngine().getResourceManager(); PrefabResource* prefab = manager.load<PrefabResource>(res.path); if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } m_selected_prefabs.push(prefab); } else { PrefabResource* prefab = m_selected_prefabs[selected_idx]; if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } else { m_selected_prefabs.swapAndPop(selected_idx); prefab->decRefCount(); } } } } if (count == 0) ImGui::TextUnformatted("No prefabs"); m_app.getAssetCompiler().unlockResources(); ImGui::ListBoxFooter(); } ImGuiEx::HSplitter("after_prefab", &size); if(ImGui::Checkbox("Align with normal", &m_is_align_with_normal)) { if(m_is_align_with_normal) m_is_rotate_x = m_is_rotate_y = m_is_rotate_z = false; } if (ImGui::Checkbox("Rotate around X", &m_is_rotate_x)) { if (m_is_rotate_x) m_is_align_with_normal = false; } if (m_is_rotate_x) { Vec2 tmp = m_rotate_x_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate X spread", &tmp.x, &tmp.y)) { m_rotate_x_spread.x = degreesToRadians(tmp.x); m_rotate_x_spread.y = degreesToRadians(tmp.y); } } if (ImGui::Checkbox("Rotate around Y", &m_is_rotate_y)) { if (m_is_rotate_y) m_is_align_with_normal = false; } if (m_is_rotate_y) { Vec2 tmp = m_rotate_y_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Y spread", &tmp.x, &tmp.y)) { m_rotate_y_spread.x = degreesToRadians(tmp.x); m_rotate_y_spread.y = degreesToRadians(tmp.y); } } if(ImGui::Checkbox("Rotate around Z", &m_is_rotate_z)) { if(m_is_rotate_z) m_is_align_with_normal = false; } if (m_is_rotate_z) { Vec2 tmp = m_rotate_z_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Z spread", &tmp.x, &tmp.y)) { m_rotate_z_spread.x = degreesToRadians(tmp.x); m_rotate_z_spread.y = degreesToRadians(tmp.y); } } ImGui::DragFloatRange2("Size spread", &m_size_spread.x, &m_size_spread.y, 0.01f); m_size_spread.x = minimum(m_size_spread.x, m_size_spread.y); ImGui::DragFloatRange2("Y spread", &m_y_spread.x, &m_y_spread.y, 0.01f); m_y_spread.x = minimum(m_y_spread.x, m_y_spread.y); } void TerrainEditor::exportToOBJ(ComponentUID cmp) const { char filename[LUMIX_MAX_PATH]; if (!os::getSaveFilename(Span(filename), "Wavefront obj\0*.obj", "obj")) return; os::OutputFile file; if (!file.open(filename)) { logError("Failed to open ", filename); return; } char basename[LUMIX_MAX_PATH]; copyString(Span(basename), Path::getBasename(filename)); auto* scene = static_cast<RenderScene*>(cmp.scene); const EntityRef e = (EntityRef)cmp.entity; const Texture* hm = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); OutputMemoryStream blob(m_app.getAllocator()); blob.reserve(8 * 1024 * 1024); blob << "mtllib " << basename << ".mtl\n"; blob << "o Terrain\n"; const float xz_scale = scene->getTerrainXZScale(e); const float y_scale = scene->getTerrainYScale(e); ASSERT(hm->format == gpu::TextureFormat::R16); const u16* hm_data = (const u16*)hm->getData(); for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { const float height = hm_data[i + j * hm->width] / float(0xffff) * y_scale; blob << "v " << i * xz_scale << " " << height << " " << j * xz_scale << "\n"; } } for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { blob << "vt " << i / float(hm->width - 1) << " " << j / float(hm->height - 1) << "\n"; } } blob << "usemtl Material\n"; auto write_face_vertex = [&](u32 idx){ blob << idx << "/" << idx; }; for (u32 j = 0; j < hm->height - 1; ++j) { for (u32 i = 0; i < hm->width - 1; ++i) { const u32 idx = i + j * hm->width + 1; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << "\n"; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << " "; write_face_vertex(idx + hm->width); blob << "\n"; } } if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", filename); } file.close(); char dir[LUMIX_MAX_PATH]; copyString(Span(dir), Path::getDir(filename)); StaticString<LUMIX_MAX_PATH> mtl_filename(dir, basename, ".mtl"); if (!file.open(mtl_filename)) { logError("Failed to open ", mtl_filename); return; } blob.clear(); blob << "newmtl Material"; if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", mtl_filename); } file.close(); } void TerrainEditor::onGUI(ComponentUID cmp, WorldEditor& editor) { ASSERT(cmp.type == TERRAIN_TYPE); auto* scene = static_cast<RenderScene*>(cmp.scene); ImGui::Unindent(); if (!ImGui::CollapsingHeader("Terrain editor")) { ImGui::Indent(); return; } ImGui::Indent(); ImGuiEx::Label("Enable"); ImGui::Checkbox("##ed_enabled", &m_is_enabled); if (!m_is_enabled) return; Material* material = getMaterial(cmp); if (!material) { ImGui::Text("No material"); return; } if (!material->getTextureByName(HEIGHTMAP_SLOT_NAME)) { ImGui::Text("No heightmap"); return; } if (ImGui::Button(ICON_FA_FILE_EXPORT)) exportToOBJ(cmp); ImGuiEx::Label("Brush size"); ImGui::DragFloat("##br_size", &m_terrain_brush_size, 1, MIN_BRUSH_SIZE, FLT_MAX); ImGuiEx::Label("Brush strength"); ImGui::SliderFloat("##br_str", &m_terrain_brush_strength, 0, 1.0f); if (ImGui::BeginTabBar("brush_type")) { if (ImGui::BeginTabItem("Height")) { m_mode = Mode::HEIGHT; if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(HEIGHTMAP_SLOT_NAME)->save(); } ImGuiEx::Label("Mode"); if (m_is_flat_height) { ImGui::TextUnformatted("flat"); } else if (m_smooth_terrain_action.isActive()) { char shortcut[64]; if (m_smooth_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("smooth (%s)", shortcut); } else { ImGui::TextUnformatted("smooth"); } } else if (m_lower_terrain_action.isActive()) { char shortcut[64]; if (m_lower_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("lower (%s)", shortcut); } else { ImGui::TextUnformatted("lower"); } } else { ImGui::TextUnformatted("raise"); } ImGui::Checkbox("Flat", &m_is_flat_height); if (m_is_flat_height) { ImGui::SameLine(); ImGui::Text("- Press Ctrl to pick height"); } ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Surface and grass")) { layerGUI(cmp); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Entity")) { entityGUI(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } if (!cmp.isValid() || !m_is_enabled) { return; } const Vec2 mp = editor.getView().getMousePos(); Universe& universe = *editor.getUniverse(); for(auto entity : editor.getSelectedEntities()) { if (!universe.hasComponent(entity, TERRAIN_TYPE)) continue; RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); DVec3 origin; Vec3 dir; editor.getView().getViewport().getRay(mp, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if(hit.is_hit) { DVec3 center = hit.origin + hit.dir * hit.t; drawCursor(*scene, entity, center); return; } } } void TerrainEditor::paint(const DVec3& hit_pos, ActionType action_type, bool old_stroke, EntityRef terrain, WorldEditor& editor) const { UniquePtr<PaintTerrainCommand> command = UniquePtr<PaintTerrainCommand>::create(editor.getAllocator(), editor, action_type, m_grass_mask, (u64)m_textures_mask, hit_pos, m_brush_mask, m_terrain_brush_size, m_terrain_brush_strength, m_flat_height, m_color, terrain, m_layers_mask, m_fixed_value, old_stroke); editor.executeCommand(command.move()); } } // namespace Lumix
30.359473
165
0.678419
santaclose
04326480283816f6e982b697093aab4f31b36529
21,971
hpp
C++
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.Networking.UnityWebRequest #include "UnityEngine/Networking/UnityWebRequest.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: UnityEngine.Networking namespace UnityEngine::Networking { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError // [TokenAttribute] Offset: FFFFFFFF struct UnityWebRequest::UnityWebRequestError/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: UnityWebRequestError constexpr UnityWebRequestError(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static constexpr const int OK = 0; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OK(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static void _set_OK(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static constexpr const int Unknown = 1; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Unknown(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static void _set_Unknown(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static constexpr const int SDKError = 2; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SDKError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static void _set_SDKError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static constexpr const int UnsupportedProtocol = 3; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnsupportedProtocol(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static void _set_UnsupportedProtocol(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static constexpr const int MalformattedUrl = 4; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_MalformattedUrl(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static void _set_MalformattedUrl(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static constexpr const int CannotResolveProxy = 5; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveProxy(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static void _set_CannotResolveProxy(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static constexpr const int CannotResolveHost = 6; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static void _set_CannotResolveHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static constexpr const int CannotConnectToHost = 7; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotConnectToHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static void _set_CannotConnectToHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static constexpr const int AccessDenied = 8; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_AccessDenied(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static void _set_AccessDenied(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static constexpr const int GenericHttpError = 9; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_GenericHttpError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static void _set_GenericHttpError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static constexpr const int WriteError = 10; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_WriteError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static void _set_WriteError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static constexpr const int ReadError = 11; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReadError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static void _set_ReadError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static constexpr const int OutOfMemory = 12; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OutOfMemory(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static void _set_OutOfMemory(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static constexpr const int Timeout = 13; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Timeout(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static void _set_Timeout(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static constexpr const int HTTPPostError = 14; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_HTTPPostError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static void _set_HTTPPostError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static constexpr const int SSLCannotConnect = 15; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCannotConnect(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static void _set_SSLCannotConnect(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static constexpr const int Aborted = 16; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Aborted(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static void _set_Aborted(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static constexpr const int TooManyRedirects = 17; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_TooManyRedirects(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static void _set_TooManyRedirects(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static constexpr const int ReceivedNoData = 18; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReceivedNoData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static void _set_ReceivedNoData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static constexpr const int SSLNotSupported = 19; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLNotSupported(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static void _set_SSLNotSupported(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static constexpr const int FailedToSendData = 20; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToSendData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static void _set_FailedToSendData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static constexpr const int FailedToReceiveData = 21; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToReceiveData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static void _set_FailedToReceiveData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static constexpr const int SSLCertificateError = 22; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCertificateError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static void _set_SSLCertificateError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static constexpr const int SSLCipherNotAvailable = 23; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCipherNotAvailable(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static void _set_SSLCipherNotAvailable(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static constexpr const int SSLCACertError = 24; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCACertError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static void _set_SSLCACertError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static constexpr const int UnrecognizedContentEncoding = 25; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnrecognizedContentEncoding(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static void _set_UnrecognizedContentEncoding(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static constexpr const int LoginFailed = 26; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_LoginFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static void _set_LoginFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static constexpr const int SSLShutdownFailed = 27; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLShutdownFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static void _set_SSLShutdownFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static constexpr const int NoInternetConnection = 28; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_NoInternetConnection(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static void _set_NoInternetConnection(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError #pragma pack(pop) static check_size<sizeof(UnityWebRequest::UnityWebRequestError), 0 + sizeof(int)> __UnityEngine_Networking_UnityWebRequest_UnityWebRequestErrorSizeCheck; static_assert(sizeof(UnityWebRequest::UnityWebRequestError) == 0x4); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError, "UnityEngine.Networking", "UnityWebRequest/UnityWebRequestError"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
99.41629
158
0.823449
Fernthedev
04375a304f2cd29a9b0c5eb3ce8b357124ad381c
11,956
hh
C++
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
//////////////////////////////////////////////////////////////////////////////// // TensionFieldTheory.hh //////////////////////////////////////////////////////////////////////////////// /*! @file // Implements a field theory relaxed energy density for a fully generic, // potentially anisotropic, 2D "C-based" energy density. Here "C-based" means // the energy density is expressed in terms of the Cauchy-Green deformation // tensor. // Our implementation is based on the applied math paper // [Pipkin1994:"Relaxed energy densities for large deformations of membranes"] // whose optimality criterion for the wrinkling strain we use to obtain a // slightly less expensive optimization formulation. // // We implement the second derivatives needed for a Newton-based equilibrium // solver; these are nontrivial since they must account for the dependence of // the wrinkling strain on C. */ // Author: Julian Panetta (jpanetta), julian.panetta@gmail.com // Created: 06/28/2020 19:01:21 //////////////////////////////////////////////////////////////////////////////// #ifndef TENSIONFIELDTHEORY_HH #define TENSIONFIELDTHEORY_HH #include <Eigen/Dense> #include <MeshFEM/Types.hh> #include <stdexcept> #include <iostream> #include <MeshFEM/newton_optimizer/dense_newton.hh> template<class _Psi> struct IsotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Eigen::Matrix<Real, 1, 1>; using HessType = Eigen::Matrix<Real, 1, 1>; using M2d = Mat2_T<Real>; IsotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const Vec2_T<Real> &n) : m_psi(psi), m_C(C), m_nn(n * n.transpose()) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 1; } void setVars(const VarType &vars) { m_a = vars; m_psi.setC(m_C + m_a[0] * m_nn); } const VarType &getVars() const { return m_a; } Real energy() const { return m_psi.energy(); } VarType gradient() const { return VarType(0.5 * doubleContract(m_nn, m_psi.PK2Stress()) ); } HessType hessian() const { return HessType(0.5 * doubleContract(m_psi.delta_PK2Stress(m_nn), m_nn)); } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: VarType m_a = VarType::Zero(); Psi &m_psi; M2d m_C, m_nn; }; template<class _Psi> struct AnisotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Vec2_T<Real>; using HessType = Mat2_T<Real>; using M2d = Mat2_T<Real>; AnisotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const VarType &n) : m_psi(psi), m_C(C), m_ntilde(n) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 2; } void setVars(const VarType &vars) { m_ntilde = vars; m_psi.setC(m_C + m_ntilde * m_ntilde.transpose()); } const VarType &getVars() const { return m_ntilde; } Real energy() const { return m_psi.energy(); } // S : (0.5 * (n delta_n^T + delta_n n^T)) // = S : n delta_n^T = (S n) . delta_n VarType gradient() const { return m_psi.PK2Stress() * m_ntilde; } // psi(n * n^T) // dpsi = n^T psi'(n * n^T) . dn // d2psi = dn_a^T psi'(n * n^T) . dn_b + n^T (psi'' : (n * dn_a^T)) . dn_b // = psi' : (dn_a dn_b^T) + ... HessType hessian() const { HessType h = m_psi.PK2Stress(); // psi' : (dn_a dn_b^T) M2d dnn(M2d::Zero()); dnn.col(0) = m_ntilde; h.row(0) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); dnn.col(0).setZero(); dnn.col(1) = m_ntilde; h.row(1) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); if (h.array().isNaN().any()) throw std::runtime_error("NaN Hessian"); if (std::abs(h(0, 1) - h(1, 0)) > 1e-10 * std::abs(h(1, 0)) + 1e-10) throw std::runtime_error("Asymmetric Hessian"); return h; } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: Psi &m_psi; M2d m_C; VarType m_ntilde = VarType::Zero(); }; // Define a relaxed 2D C-based energy based on a given 2D C-based energy `Psi_C` template<class Psi_C> struct RelaxedEnergyDensity { static_assert(Psi_C::EDType == EDensityType::CBased, "Tension field theory only works on C-based energy densities"); static constexpr size_t N = Psi_C::N; static constexpr size_t Dimension = N; static constexpr EDensityType EDType = EDensityType::CBased; using Matrix = typename Psi_C::Matrix; using Real = typename Psi_C::Real; using ES = Eigen::SelfAdjointEigenSolver<Matrix>; using V2d = Vec2_T<Real>; static_assert(N == 2, "Tension field theory relaxation only defined for 2D energies"); static std::string name() { return std::string("Relaxed") + Psi_C::name(); } // Forward all constructor arguments to m_psi template<class... Args> RelaxedEnergyDensity(Args&&... args) : m_psi(std::forward<Args>(args)...), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { } // We need a custom copy constructor since m_anisoProb contains a // reference to this->m_psi RelaxedEnergyDensity(const RelaxedEnergyDensity &b) : m_psi(b.m_psi), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } // Note: UninitializedDeformationTag argument must be a rvalue reference so it exactly // matches the type passed by the constructor call // RelaxedEnergyDensity(b, UninitializedDeformationTag()); otherwise the // perfect forwarding constructor above will be preferred for this call, // incorrectly forwarding b to Psi's constructor. RelaxedEnergyDensity(const RelaxedEnergyDensity &b, UninitializedDeformationTag &&) : m_psi(b.m_psi, UninitializedDeformationTag()), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } void setC(const Matrix &C) { m_C = C; if (!relaxationEnabled()) { m_psi.setC(C); return; } // Note: Eigen guarantees eigenvalues are sorted in ascending order. ES C_eigs(C); // std::cout << "C eigenvalues: " << C_eigs.eigenvalues().transpose() << std::endl; // Detect full compression if (C_eigs.eigenvalues()[1] < 1) { m_tensionState = 0; m_wrinkleStrain = -C; return; } m_psi.setC(C); ES S_eigs(m_psi.PK2Stress()); // Detect full tension // std::cout << "S eigenvalues: " << S_eigs.eigenvalues().transpose() << std::endl; if (S_eigs.eigenvalues()[0] >= -1e-12) { m_tensionState = 2; m_wrinkleStrain.setZero(); return; } // Handle partial tension m_tensionState = 1; // In the isotropic case, principal stress and strain directions // coincide, and the wrinkling strain must be in the form // a n n^T, where n is the eigenvector corresponding to the smallest // stress eigenvalue and a > 0 is an unknown. // This simplifies the determination of wrinkling strain to a convex // 1D optimization problem that we solve with Newton's method. V2d n = S_eigs.eigenvectors().col(0); using IWSP = IsotropicWrinkleStrainProblem<Psi_C>; IWSP isoProb(m_psi, C, n); // std::cout << "Solving isotropic wrinkle strain problem" << std::endl; isoProb.setVars(typename IWSP::VarType{0.0}); isoProb.solve(); Real a = isoProb.getVars()[0]; if (a < 0) throw std::runtime_error("Invalid wrinkle strain"); // We use this isotropic assumption to obtain initial guess for the // anisotropic case, where the wrinkling strain is in the form // n_tilde n_tilde^T // with a 2D vector n_tilde as the unknown. m_anisoProb.setC(C); // std::cout << "Solving anisotropic wrinkle strain problem" << std::endl; m_anisoProb.setVars(std::sqrt(a) * n); m_anisoProb.solve(); auto ntilde = m_anisoProb.getVars(); m_wrinkleStrain = -ntilde * ntilde.transpose(); // { // ES S_eigs_new(m_psi.PK2Stress()); // std::cout << "new S eigenvalues: " << S_eigs_new.eigenvalues().transpose() << std::endl; // } } Real energy() const { if (relaxationEnabled() && fullCompression()) return 0.0; return m_psi.energy(); } Matrix PK2Stress() const { if (relaxationEnabled() && fullCompression()) return Matrix::Zero(); // By envelope theorem, the wrinkling strain's perturbation can be // neglected, and the stress is simply the stress of the underlying // material model evaluated on the "elastic strain". return m_psi.PK2Stress(); } template<class Mat_> Matrix delta_PK2Stress(const Mat_ &dC) const { if (!relaxationEnabled() || fullTension()) return m_psi.delta_PK2Stress(dC); if (fullCompression()) return Matrix::Zero(); // n solves m_anisoProb: // (psi') n = 0 // delta_n solves: // (psi'' : dC + n delta n) n + (psi') delta_n = 0 // (psi'' : n delta_n) n + (psi') delta_n = -(psi'' : dC) n // H delta_n = -(psi'' : dC) n auto ntilde = m_anisoProb.getVars(); V2d delta_n = -m_anisoProb.hessian().inverse() * (m_psi.delta_PK2Stress(dC.matrix()) * ntilde); // In the partial tension case, we need to account for the wrinkling // strain perturbation. return m_psi.delta_PK2Stress(dC.matrix() + ntilde * delta_n.transpose() + delta_n * ntilde.transpose()); } template<class Mat_, class Mat2_> Matrix delta2_PK2Stress(const Mat_ &/* dF_a */, const Mat2_ &/* dF_b */) const { throw std::runtime_error("Unimplemented"); } V2d principalBiotStrains() const { ES es(m_C); return es.eigenvalues().array().sqrt() - 1.0; } const Matrix &wrinkleStrain() const { return m_wrinkleStrain; } bool fullCompression() const { return m_tensionState == 0; } bool partialTension() const { return m_tensionState == 1; } bool fullTension() const { return m_tensionState == 2; } int tensionState() const { return m_tensionState; } // Copying is super dangerous since we m_anisoProb uses a reference to m_psi... RelaxedEnergyDensity &operator=(const RelaxedEnergyDensity &) = delete; // Direct access to the energy density for debugging or // to change the material properties Psi_C &psi() { return m_psi; } const Psi_C &psi() const { return m_psi; } // Turn on or off the tension field theory approximation void setRelaxationEnabled(bool enable) { m_relaxationEnabled = enable; setC(m_C); } bool relaxationEnabled() const { return m_relaxationEnabled; } void copyMaterialProperties(const RelaxedEnergyDensity &other) { psi().copyMaterialProperties(other.psi()); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: // Tension state: // 0: compression in all directions // 1: partial tension // 2: tension in all directions int m_tensionState = 2; Psi_C m_psi; Matrix m_wrinkleStrain = Matrix::Zero(), m_C = Matrix::Identity(); // full Cauchy-Green deformation tensor. AnisotropicWrinkleStrainProblem<Psi_C> m_anisoProb; bool m_relaxationEnabled = true; }; #endif /* end of include guard: TENSIONFIELDTHEORY_HH */
39.328947
113
0.613499
MeshFEM
04380da30516f9931c814f7e57999f699f2103d4
7,764
cpp
C++
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Dathrohan_Balnazzar SD%Complete: 95 SDComment: Possibly need to fix/improve summons after death SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" enum eEnums { //Dathrohan spells SPELL_CRUSADERSHAMMER = 17286, //AOE stun SPELL_CRUSADERSTRIKE = 17281, SPELL_HOLYSTRIKE = 17284, //weapon dmg +3 //Transform SPELL_BALNAZZARTRANSFORM = 17288, //restore full HP/mana, trigger spell Balnazzar Transform Stun //Balnazzar spells SPELL_SHADOWSHOCK = 17399, SPELL_MINDBLAST = 17287, SPELL_PSYCHICSCREAM = 13704, SPELL_SLEEP = 12098, SPELL_MINDCONTROL = 15690, NPC_DATHROHAN = 10812, NPC_BALNAZZAR = 10813, NPC_ZOMBIE = 10698 //probably incorrect }; struct SummonDef { float m_fX, m_fY, m_fZ, m_fOrient; }; SummonDef m_aSummonPoint[]= { {3444.156f, -3090.626f, 135.002f, 2.240f}, //G1 front, left {3449.123f, -3087.009f, 135.002f, 2.240f}, //G1 front, right {3446.246f, -3093.466f, 135.002f, 2.240f}, //G1 back left {3451.160f, -3089.904f, 135.002f, 2.240f}, //G1 back, right {3457.995f, -3080.916f, 135.002f, 3.784f}, //G2 front, left {3454.302f, -3076.330f, 135.002f, 3.784f}, //G2 front, right {3460.975f, -3078.901f, 135.002f, 3.784f}, //G2 back left {3457.338f, -3073.979f, 135.002f, 3.784f} //G2 back, right }; class boss_dathrohan_balnazzar : public CreatureScript { public: boss_dathrohan_balnazzar() : CreatureScript("boss_dathrohan_balnazzar") { } CreatureAI* GetAI(Creature* creature) const { return new boss_dathrohan_balnazzarAI (creature); } struct boss_dathrohan_balnazzarAI : public ScriptedAI { boss_dathrohan_balnazzarAI(Creature* creature) : ScriptedAI(creature) {} uint32 m_uiCrusadersHammer_Timer; uint32 m_uiCrusaderStrike_Timer; uint32 m_uiMindBlast_Timer; uint32 m_uiHolyStrike_Timer; uint32 m_uiShadowShock_Timer; uint32 m_uiPsychicScream_Timer; uint32 m_uiDeepSleep_Timer; uint32 m_uiMindControl_Timer; bool m_bTransformed; void Reset() { m_uiCrusadersHammer_Timer = 8000; m_uiCrusaderStrike_Timer = 12000; m_uiMindBlast_Timer = 6000; m_uiHolyStrike_Timer = 18000; m_uiShadowShock_Timer = 4000; m_uiPsychicScream_Timer = 16000; m_uiDeepSleep_Timer = 20000; m_uiMindControl_Timer = 10000; m_bTransformed = false; if (me->GetEntry() == NPC_BALNAZZAR) me->UpdateEntry(NPC_DATHROHAN); } void JustDied(Unit* /*killer*/) { static uint32 uiCount = sizeof(m_aSummonPoint)/sizeof(SummonDef); for (uint8 i=0; i<uiCount; ++i) me->SummonCreature(NPC_ZOMBIE, m_aSummonPoint[i].m_fX, m_aSummonPoint[i].m_fY, m_aSummonPoint[i].m_fZ, m_aSummonPoint[i].m_fOrient, TEMPSUMMON_TIMED_DESPAWN, HOUR*IN_MILLISECONDS); } void EnterCombat(Unit* /*who*/) { } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //START NOT TRANSFORMED if (!m_bTransformed) { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //CrusadersHammer if (m_uiCrusadersHammer_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSHAMMER); m_uiCrusadersHammer_Timer = 12000; } else m_uiCrusadersHammer_Timer -= uiDiff; //CrusaderStrike if (m_uiCrusaderStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSTRIKE); m_uiCrusaderStrike_Timer = 15000; } else m_uiCrusaderStrike_Timer -= uiDiff; //HolyStrike if (m_uiHolyStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_HOLYSTRIKE); m_uiHolyStrike_Timer = 15000; } else m_uiHolyStrike_Timer -= uiDiff; //BalnazzarTransform if (HealthBelowPct(40)) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); //restore hp, mana and stun DoCast(me, SPELL_BALNAZZARTRANSFORM); me->UpdateEntry(NPC_BALNAZZAR); m_bTransformed = true; } } else { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //ShadowShock if (m_uiShadowShock_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_SHADOWSHOCK); m_uiShadowShock_Timer = 11000; } else m_uiShadowShock_Timer -= uiDiff; //PsychicScream if (m_uiPsychicScream_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_PSYCHICSCREAM); m_uiPsychicScream_Timer = 20000; } else m_uiPsychicScream_Timer -= uiDiff; //DeepSleep if (m_uiDeepSleep_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_SLEEP); m_uiDeepSleep_Timer = 15000; } else m_uiDeepSleep_Timer -= uiDiff; //MindControl if (m_uiMindControl_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDCONTROL); m_uiMindControl_Timer = 15000; } else m_uiMindControl_Timer -= uiDiff; } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_dathrohan_balnazzar() { new boss_dathrohan_balnazzar(); }
34.816143
122
0.551391
499453466
0438c5e47926dbfe5ee9f60971e30e206204d7fa
3,624
cpp
C++
league_skin_changer/game_classes.cpp
slowptr/LeagueSkinChanger
c37d505c4062b1acc1a7012650d6a33d5d8a3bce
[ "MIT" ]
1
2020-11-24T14:51:20.000Z
2020-11-24T14:51:20.000Z
league_skin_changer/game_classes.cpp
devzhai/LeagueSkinChanger
aaad169c8b74756c0ceb668fa003577aedc62965
[ "MIT" ]
null
null
null
league_skin_changer/game_classes.cpp
devzhai/LeagueSkinChanger
aaad169c8b74756c0ceb668fa003577aedc62965
[ "MIT" ]
null
null
null
/* This file is part of LeagueSkinChanger by b3akers, licensed under the MIT license: * * MIT License * * Copyright (c) b3akers 2020 * * 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 "game_classes.hpp" #include "encryption.hpp" #include "fnv_hash.hpp" #include <Windows.h> void character_data_stack::push( const char* model, int32_t skin ) { static const auto Push = reinterpret_cast<int( __thiscall* )( void*, const char* model, int32_t skinid, int32_t, bool update_spells, bool dont_update_hud, bool, bool change_particle, bool, char, const char*, int32_t, const char*, int32_t )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Push ); Push( this, model, skin, 0, false, false, false, true, false, -1, "\x00", 0, "\x00", 0 ); } void character_data_stack::update( bool change ) { static const auto Update = reinterpret_cast<void( __thiscall* )( void*, bool )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Update ); Update( this, change ); } void obj_ai_base::change_skin( const char* model, int32_t skin ) { //Update skinid in object class to appear name in scoreboard and fix for some things // reinterpret_cast<xor_value<int32_t>*>( std::uintptr_t( this ) + offsets::ai_base::SkinId )->encrypt( skin ); this->get_character_data_stack( )->base_skin.skin = skin; //Lux has same skinid but diff model we have to handle it, game receives packets and calls Push function to change skin we do same but don't pushing new class but modify existing // if ( fnv::hash_runtime( this->get_character_data_stack( )->base_skin.model.str ) == FNV( "Lux" ) ) { if ( skin == 7 ) { if ( this->get_character_data_stack( )->stack.empty( ) ) { this->get_character_data_stack( )->push( model, skin ); return; } auto& last = this->get_character_data_stack( )->stack.back( ); last.skin = skin; last.model.str = model; last.model.length = strlen( model ); last.model.capacity = last.model.length + 1; } else { //Make sure that stack for lux is cleared // this->get_character_data_stack( )->stack.clear( ); } } this->get_character_data_stack( )->update( true ); } obj_ai_base* obj_ai_minion::get_owner( ) { static const auto GetOwnerObject = reinterpret_cast<obj_ai_base * ( __thiscall* )( void* )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::GetOwnerObject ); return GetOwnerObject( this ); } bool obj_ai_minion::is_lane_minion( ) { return reinterpret_cast<xor_value<bool>*>( std::uintptr_t( this ) + offsets::ai_minion::IsLaneMinion )->decrypt( ); }
45.873418
337
0.73234
slowptr
043ac0b5c34ad8ecec530d8db83cb7eba171b072
2,298
cpp
C++
lib/spdk/BdevStats.cpp
janlt/daqdb
04ff602fe0a6c199a782b877203b8b8b9d3fec66
[ "Apache-2.0" ]
22
2019-02-08T17:23:12.000Z
2021-10-12T06:35:37.000Z
lib/spdk/BdevStats.cpp
janlt/daqdb
04ff602fe0a6c199a782b877203b8b8b9d3fec66
[ "Apache-2.0" ]
8
2019-02-11T06:30:47.000Z
2020-04-22T09:49:44.000Z
lib/spdk/BdevStats.cpp
daq-db/daqdb
e30afe8a9a4727e60d0c1122d28679a4ce326844
[ "Apache-2.0" ]
10
2019-02-11T10:26:52.000Z
2019-09-16T20:49:25.000Z
/** * Copyright (c) 2019 Intel Corporation * * 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 <stdio.h> #include <time.h> #include <iostream> #include <sstream> #include <string> #include "BdevStats.h" namespace DaqDB { /* * BdevStats */ std::ostringstream &BdevStats::formatWriteBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] write_compl_cnt[" << write_compl_cnt << "] write_err_cnt[" << write_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } std::ostringstream &BdevStats::formatReadBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] read_compl_cnt[" << read_compl_cnt << "] read_err_cnt[" << read_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } void BdevStats::printWritePer(std::ostream &os, const char *bdev_addr) { if (!(write_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatWriteBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } void BdevStats::printReadPer(std::ostream &os, const char *bdev_addr) { if (!(read_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatReadBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } } // namespace DaqDB
31.916667
79
0.60705
janlt
043cb4f04d9e8e2afacf1f781cc1f86786d7a247
551
hpp
C++
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "LolLootPlayerLoot.hpp" namespace lol { struct LolLootPlayerLootMap { int64_t version; std::map<std::string, LolLootPlayerLoot> playerLoot; }; inline void to_json(json& j, const LolLootPlayerLootMap& v) { j["version"] = v.version; j["playerLoot"] = v.playerLoot; } inline void from_json(const json& j, LolLootPlayerLootMap& v) { v.version = j.at("version").get<int64_t>(); v.playerLoot = j.at("playerLoot").get<std::map<std::string, LolLootPlayerLoot>>(); } }
32.411765
87
0.675136
Maufeat
04429fd235d6659428bd0141cf64515cf9d012af
3,328
hpp
C++
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
1
2021-06-18T05:00:10.000Z
2021-06-18T05:00:10.000Z
// Copyright 2014 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 <bsoncxx/document/view.hpp> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/write_concern.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { /// /// Class representing the optional arguments to a MongoDB insert operation /// class MONGOCXX_API insert { public: /// /// Sets the bypass_document_validation option. /// If true, allows the write to opt-out of document level validation. /// /// @note /// On servers >= 3.2, the server applies validation by default. On servers < 3.2, this option /// is ignored. /// /// @param bypass_document_validation /// Whether or not to bypass document validation /// insert& bypass_document_validation(bool bypass_document_validation); /// /// Gets the current value of the bypass_document_validation option. /// /// @return The optional value of the bypass_document_validation option. /// const stdx::optional<bool>& bypass_document_validation() const; /// /// Sets the write_concern for this operation. /// /// @param wc /// The new write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// insert& write_concern(class write_concern wc); /// /// The current write_concern for this operation. /// /// @return The current write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// const stdx::optional<class write_concern>& write_concern() const; /// /// @note: This applies only to insert_many and is ignored for insert_one. /// /// If true, when an insert fails, return without performing the remaining /// writes. If false, when a write fails, continue with the remaining /// writes, if any. Inserts can be performed in any order if this is false. /// Defaults to true. /// /// @param ordered /// Whether or not the insert_many will be ordered. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// insert& ordered(bool ordered); /// /// The current ordered value for this operation. /// /// @return The current ordered value. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// const stdx::optional<bool>& ordered() const; private: stdx::optional<class write_concern> _write_concern; stdx::optional<bool> _ordered; stdx::optional<bool> _bypass_document_validation; }; } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp>
31.102804
100
0.682091
VincentPT
04458d4bd362c54a9a27195322e1ad616d5d4a14
2,320
cpp
C++
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <eigenml/decision_tree/decision_tree_traits.hpp> #include <eigenml/decision_tree/splitting/find_thresholds.hpp> #include <eigenml/decision_tree/splitting/criteria.hpp> using namespace eigenml; using namespace eigenml::decision_tree; typedef tree_traits<ModelType::kSupervisedClassifier, Matrix, Matrix> classification_tree_traits; TEST(ThresholdFinding, Entropy) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = entropy(hist); ASSERT_DOUBLE_EQ(v.first, 1); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, Gini) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = gini(hist); ASSERT_DOUBLE_EQ(v.first, 0.5); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, SimplethresholdEntropy) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(entropy<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(2, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); } TEST(ThresholdFinding, SimplethresholdGini) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(gini<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(1, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); }
30.12987
97
0.731466
guillempalou
044d0c1fd78751ffbea415337b6b2fc0c75051ec
29,450
cc
C++
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "icing/index/main/posting-list-used.h" #include <fcntl.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <deque> #include <iterator> #include <memory> #include <random> #include <string> #include <vector> #include "icing/text_classifier/lib3/utils/base/status.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "icing/index/main/posting-list-utils.h" #include "icing/legacy/index/icing-bit-util.h" #include "icing/schema/section.h" #include "icing/store/document-id.h" #include "icing/testing/common-matchers.h" #include "icing/testing/hit-test-utils.h" using std::reverse; using std::vector; using testing::ElementsAre; using testing::ElementsAreArray; using testing::Eq; using testing::IsEmpty; using testing::Le; using testing::Lt; namespace icing { namespace lib { struct HitElt { HitElt() = default; explicit HitElt(const Hit &hit_in) : hit(hit_in) {} static Hit get_hit(const HitElt &hit_elt) { return hit_elt.hit; } Hit hit; }; TEST(PostingListTest, PostingListUsedPrependHitNotFull) { static const int kNumHits = 2551; static const size_t kHitsSize = kNumHits * sizeof(Hit); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Make used. Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/56); pl_used.PrependHit(hit0); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); Hit hit1(/*section_id=*/0, 1, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit1); // Size = sizeof(uncompressed hit1) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); Hit hit2(/*section_id=*/0, 2, /*term_frequency=*/56); pl_used.PrependHit(hit2); // Size = sizeof(uncompressed hit2) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); Hit hit3(/*section_id=*/0, 3, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit3); // Size = sizeof(uncompressed hit3) // + sizeof(hit2-hit3) + sizeof(hit2::term_frequency) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); } TEST(PostingListTest, PostingListUsedPrependHitAlmostFull) { constexpr int kHitsSize = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Fill up the compressed region. // Transitions: // Adding hit0: EMPTY -> NOT_FULL // Adding hit1: NOT_FULL -> NOT_FULL // Adding hit2: NOT_FULL -> NOT_FULL Hit hit0(/*section_id=*/0, 0, Hit::kDefaultTermFrequency); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); ICING_EXPECT_OK(pl_used.PrependHit(hit2)); // Size used will be 2+2+4=8 bytes int expected_size = sizeof(Hit::Value) + 2 + 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); // Add one more hit to transition NOT_FULL -> ALMOST_FULL Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/3); ICING_EXPECT_OK(pl_used.PrependHit(hit3)); // Compressed region would be 2+2+3+4=11 bytes, but the compressed region is // only 10 bytes. So instead, the posting list will transition to ALMOST_FULL. // The in-use compressed region will actually shrink from 8 bytes to 7 bytes // because the uncompressed version of hit2 will be overwritten with the // compressed delta of hit2. hit3 will be written to one of the special hits. // Because we're in ALMOST_FULL, the expected size is the size of the pl minus // the one hit used to mark the posting list as ALMOST_FULL. expected_size = kHitsSize - sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> ALMOST_FULL Hit hit4 = CreateHit(hit3, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit4)); // There are currently 7 bytes in use in the compressed region. hit3 will have // a 2-byte delta. That delta will fit in the compressed region (which will // now have 9 bytes in use), hit4 will be placed in one of the special hits // and the posting list will remain in ALMOST_FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit4, hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> FULL Hit hit5 = CreateHit(hit4, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit5)); // There are currently 9 bytes in use in the compressed region. hit4 will have // a 2-byte delta which will not fit in the compressed region. So hit4 will // remain in one of the special hits and hit5 will occupy the other, making // the posting list FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(kHitsSize)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit5, hit4, hit3, hit2, hit1, hit0))); // The posting list is FULL. Adding another hit should fail. Hit hit6 = CreateHit(hit5, /*desired_byte_length=*/1); EXPECT_THAT(pl_used.PrependHit(hit6), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, PostingListUsedMinSize) { std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PL State: EMPTY EXPECT_THAT(pl_used.BytesUsed(), Eq(0)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); // Add a hit, PL should shift to ALMOST_FULL state Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/true); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); // Add the smallest hit possible - no term_frequency and a delta of 1. PL // should shift to FULL state. Hit hit1(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/true, /*is_prefix_hit=*/false); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); // Size = sizeof(uncompressed hit1) + sizeof(uncompressed hit0) expected_size += sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); // Try to add the smallest hit possible. Should fail Hit hit2(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/false); EXPECT_THAT(pl_used.PrependHit(hit2), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); } TEST(PostingListTest, PostingListPrependHitArrayMinSizePostingList) { constexpr int kFinalSize = 1025; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kFinalSize); // Min Size = 10 int size = posting_list_utils::min_posting_list_size(); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // Add five hits. The PL is in the empty state and an empty min size PL can // only fit two hits. So PrependHitArray should fail. uint32_t num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_can_prepend, Eq(2)); int can_fit_hits = num_can_prepend; // The PL has room for 2 hits. We should be able to add them without any // problem, transitioning the PL from EMPTY -> ALMOST_FULL -> FULL const HitElt *hits_in_ptr = hits_in.data() + (hits_in.size() - 2); num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( hits_in_ptr, can_fit_hits, false); EXPECT_THAT(num_can_prepend, Eq(can_fit_hits)); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend() - hits_in.size() + can_fit_hits, std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayPostingList) { // Size = 30 int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // The last hit is uncompressed and the four before it should only take one // byte. Total use = 8 bytes. // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25-22 Hit #5 // 21-10 <unused> // 9-5 kSpecialHit // 4-0 Offset=22 // ---------------------- int byte_size = sizeof(Hit::Value) + hits_in.size() - 1; // Add five hits. The PL is in the empty state and should be able to fit all // five hits without issue, transitioning the PL from EMPTY -> NOT_FULL. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); Hit first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/3)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // Size increased by the deltas of these hits (1+2+1+2+3+2) = 11 bytes // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-11 Hit #11 // 10 <unused> // 9-5 kSpecialHit // 4-0 Offset=11 // ---------------------- byte_size += 11; // Add these 6 hits. The PL is currently in the NOT_FULL state and should // remain in the NOT_FULL state. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/3); hits_in.clear(); hits_in.emplace_back(first_hit); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11-10 <unused> // 9-5 Hit #12 // 4-0 kSpecialHit // ---------------------- byte_size = 25; // Add this 1 hit. The PL is currently in the NOT_FULL state and should // transition to the ALMOST_FULL state - even though there is still some // unused space. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11 delta(Hit #12) // 10 <unused> // 9-5 Hit #13 // 4-0 Hit #14 // ---------------------- // Add these 2 hits. The PL is currently in the ALMOST_FULL state. Adding the // first hit should keep the PL in ALMOST_FULL because the delta between Hit // #12 and Hit #13 (1 byte) can fit in the unused area (2 bytes). Adding the // second hit should tranisition to the FULL state because the delta between // Hit #13 and Hit #14 (2 bytes) is larger than the remaining unused area // (1 byte). num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayTooManyHits) { static constexpr int kNumHits = 128; static constexpr int kDeltaSize = 1; static constexpr int kTermFrequencySize = 1; static constexpr size_t kHitsSize = ((kNumHits * (kDeltaSize + kTermFrequencySize)) / 5) * 5; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); // Create an array with one too many hits vector<Hit> hits_in_too_many = CreateHits(kNumHits + 1, /*desired_byte_length=*/1); vector<HitElt> hit_elts_in_too_many; for (const Hit &hit : hits_in_too_many) { hit_elts_in_too_many.emplace_back(hit); } ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PrependHitArray should fail because hit_elts_in_too_many is far too large // for the minimum size pl. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); ICING_ASSERT_OK_AND_ASSIGN( pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // PrependHitArray should fail because hit_elts_in_too_many is one hit too // large for this pl. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, PostingListStatusJumpFromNotFullToFullAndBack) { const uint32_t pl_size = 3 * sizeof(Hit); char hits_buf[pl_size]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, pl_size)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue - 1, 0))); uint32_t bytes_used = pl.BytesUsed(); // Status not full. ASSERT_THAT(bytes_used, Le(pl_size - posting_list_utils::kSpecialHitsSize)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue >> 2, 0))); // Status should jump to full directly. ASSERT_THAT(pl.BytesUsed(), Eq(pl_size)); pl.PopFrontHits(1); // Status should return to not full as before. ASSERT_THAT(pl.BytesUsed(), Eq(bytes_used)); } TEST(PostingListTest, DeltaOverflow) { char hits_buf[1000]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, 4 * sizeof(Hit))); static const Hit::Value kOverflow[4] = { Hit::kInvalidValue >> 2, (Hit::kInvalidValue >> 2) * 2, (Hit::kInvalidValue >> 2) * 3, Hit::kInvalidValue - 1, }; // Fit at least 4 ordinary values. for (Hit::Value v = 0; v < 4; v++) { ICING_EXPECT_OK(pl.PrependHit(Hit(4 - v))); } // Cannot fit 4 overflow values. ICING_ASSERT_OK_AND_ASSIGN(pl, PostingListUsed::CreateFromUnitializedRegion( hits_buf, 4 * sizeof(Hit))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[3]))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[2]))); // Can fit only one more. ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[1]))); EXPECT_THAT(pl.PrependHit(Hit(kOverflow[0])), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, MoveFrom) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } ICING_ASSERT_OK(pl_used2.MoveFrom(&pl_used1)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, MoveFromNullArgumentReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } EXPECT_THAT(pl_used1.MoveFrom(/*other=*/nullptr), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits.rbegin(), hits.rend()))); } TEST(PostingListTest, MoveFromInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used1 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf1.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, MoveToInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used2 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf2.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); } TEST(PostingListTest, MoveToPostingListTooSmall) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), posting_list_utils::min_posting_list_size())); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/1, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, PopHitsWithScores) { int size = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); // This posting list is 20-bytes. Create four hits that will have deltas of // two bytes each and all of whom will have a non-default score. This posting // list will be almost_full. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13 score(Hit #2) // 12-11 delta(Hit #2) // 10 <unused> // 9-5 Hit #3 // 4-0 kInvalidHitVal // ---------------------- Hit hit0(/*section_id=*/0, /*document_id=*/0, /*score=*/5); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/2); ICING_ASSERT_OK(pl_used.PrependHit(hit0)); ICING_ASSERT_OK(pl_used.PrependHit(hit1)); ICING_ASSERT_OK(pl_used.PrependHit(hit2)); ICING_ASSERT_OK(pl_used.PrependHit(hit3)); ICING_ASSERT_OK_AND_ASSIGN(std::vector<Hit> hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit3, hit2, hit1, hit0)); // Now, pop the last hit. The posting list should contain the first three // hits. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13-10 <unused> // 9-5 Hit #2 // 4-0 kInvalidHitVal // ---------------------- ICING_ASSERT_OK(pl_used.PopFrontHits(1)); ICING_ASSERT_OK_AND_ASSIGN(hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit2, hit1, hit0)); } } // namespace lib } // namespace icing
41.304348
80
0.67399
PixelPlusUI-SnowCone
0452941871a83af5ba88c83fbedd86ff43b8d988
25,244
cpp
C++
modules/core/src/split.cpp
liqingshan/opencv
5e68f35500a859838ab8688bd3487cf9edece3f7
[ "BSD-3-Clause" ]
17
2016-03-16T08:48:30.000Z
2022-02-21T12:09:28.000Z
modules/core/src/split.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
5
2017-10-15T15:44:47.000Z
2022-02-17T11:31:32.000Z
modules/core/src/split.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
25
2018-09-26T08:51:13.000Z
2022-02-24T13:43:58.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { namespace hal { #if CV_NEON template<typename T> struct VSplit2; template<typename T> struct VSplit3; template<typename T> struct VSplit4; #define SPLIT2_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, \ data_type* dst1) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ } \ } #define SPLIT3_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ } \ } #define SPLIT4_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2, data_type* dst3) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ store_func(dst3, r.val[3]); \ } \ } SPLIT2_KERNEL_TEMPLATE(VSplit2, uchar , uint8x16x2_t, vld2q_u8 , vst1q_u8 ); SPLIT2_KERNEL_TEMPLATE(VSplit2, ushort, uint16x8x2_t, vld2q_u16, vst1q_u16); SPLIT2_KERNEL_TEMPLATE(VSplit2, int , int32x4x2_t, vld2q_s32, vst1q_s32); SPLIT2_KERNEL_TEMPLATE(VSplit2, int64 , int64x1x2_t, vld2_s64 , vst1_s64 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, uchar , uint8x16x3_t, vld3q_u8 , vst1q_u8 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, ushort, uint16x8x3_t, vld3q_u16, vst1q_u16); SPLIT3_KERNEL_TEMPLATE(VSplit3, int , int32x4x3_t, vld3q_s32, vst1q_s32); SPLIT3_KERNEL_TEMPLATE(VSplit3, int64 , int64x1x3_t, vld3_s64 , vst1_s64 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, uchar , uint8x16x4_t, vld4q_u8 , vst1q_u8 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, ushort, uint16x8x4_t, vld4q_u16, vst1q_u16); SPLIT4_KERNEL_TEMPLATE(VSplit4, int , int32x4x4_t, vld4q_s32, vst1q_s32); SPLIT4_KERNEL_TEMPLATE(VSplit4, int64 , int64x1x4_t, vld4_s64 , vst1_s64 ); #elif CV_SSE2 template <typename T> struct VSplit2 { VSplit2() : support(false) { } void operator()(const T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit3 { VSplit3() : support(false) { } void operator()(const T *, T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit4 { VSplit4() : support(false) { } void operator()(const T *, T *, T *, T *, T *) const { } bool support; }; #define SPLIT2_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit2<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit2() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ } \ \ bool support; \ } #define SPLIT3_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit3<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit3() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1, data_type * dst2) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, \ v_src3, v_src4, v_src5); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ } \ \ bool support; \ } #define SPLIT4_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit4<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit4() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, data_type * dst0, data_type * dst1, \ data_type * dst2, data_type * dst3) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ reg_type v_src6 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 6)); \ reg_type v_src7 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 7)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3, \ v_src4, v_src5, v_src6, v_src7); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ _mm_storeu_##flavor((cast_type *)(dst3), v_src6); \ _mm_storeu_##flavor((cast_type *)(dst3 + ELEMS_IN_VEC), v_src7); \ } \ \ bool support; \ } SPLIT2_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT2_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT2_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT3_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT3_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT3_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT4_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT4_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT4_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); #endif template<typename T> static void split_( const T* src, T** dst, int len, int cn ) { int k = cn % 4 ? cn % 4 : 4; int i, j; if( k == 1 ) { T* dst0 = dst[0]; if(cn == 1) { memcpy(dst0, src, len * sizeof(T)); } else { for( i = 0, j = 0 ; i < len; i++, j += cn ) dst0[i] = src[j]; } } else if( k == 2 ) { T *dst0 = dst[0], *dst1 = dst[1]; i = j = 0; #if CV_NEON if(cn == 2) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; for( ; i < len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } #elif CV_SSE2 if (cn == 2) { int inc_i = 32/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; } } else if( k == 3 ) { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2]; i = j = 0; #if CV_NEON if(cn == 3) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } #elif CV_SSE2 if (cn == 3) { int inc_i = 32/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; } } else { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2], *dst3 = dst[3]; i = j = 0; #if CV_NEON if(cn == 4) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } #elif CV_SSE2 if (cn == 4) { int inc_i = 32/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } for( ; k < cn; k += 4 ) { T *dst0 = dst[k], *dst1 = dst[k+1], *dst2 = dst[k+2], *dst3 = dst[k+3]; for( i = 0, j = k; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } } void split8u(const uchar* src, uchar** dst, int len, int cn ) { CALL_HAL(split8u, cv_hal_split8u, src,dst, len, cn) split_(src, dst, len, cn); } void split16u(const ushort* src, ushort** dst, int len, int cn ) { CALL_HAL(split16u, cv_hal_split16u, src,dst, len, cn) split_(src, dst, len, cn); } void split32s(const int* src, int** dst, int len, int cn ) { CALL_HAL(split32s, cv_hal_split32s, src,dst, len, cn) split_(src, dst, len, cn); } void split64s(const int64* src, int64** dst, int len, int cn ) { CALL_HAL(split64s, cv_hal_split64s, src,dst, len, cn) split_(src, dst, len, cn); } }} // cv::hal:: /****************************************************************************************\ * split & merge * \****************************************************************************************/ typedef void (*SplitFunc)(const uchar* src, uchar** dst, int len, int cn); static SplitFunc getSplitFunc(int depth) { static SplitFunc splitTab[] = { (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split64s), 0 }; return splitTab[depth]; } #ifdef HAVE_IPP namespace cv { static bool ipp_split(const Mat& src, Mat* mv, int channels) { #ifdef HAVE_IPP_IW CV_INSTRUMENT_REGION_IPP() if(channels != 3 && channels != 4) return false; if(src.dims <= 2) { IppiSize size = ippiSize(src.size()); void *dstPtrs[4] = {NULL}; size_t dstStep = mv[0].step; for(int i = 0; i < channels; i++) { dstPtrs[i] = mv[i].ptr(); if(dstStep != mv[i].step) return false; } return CV_INSTRUMENT_FUN_IPP(llwiCopySplit, src.ptr(), (int)src.step, dstPtrs, (int)dstStep, size, (int)src.elemSize1(), channels, 0) >= 0; } else { const Mat *arrays[5] = {NULL}; uchar *ptrs[5] = {NULL}; arrays[0] = &src; for(int i = 1; i < channels; i++) { arrays[i] = &mv[i-1]; } NAryMatIterator it(arrays, ptrs); IppiSize size = { (int)it.size, 1 }; for( size_t i = 0; i < it.nplanes; i++, ++it ) { if(CV_INSTRUMENT_FUN_IPP(llwiCopySplit, ptrs[0], 0, (void**)&ptrs[1], 0, size, (int)src.elemSize1(), channels, 0) < 0) return false; } return true; } #else CV_UNUSED(src); CV_UNUSED(mv); CV_UNUSED(channels); return false; #endif } } #endif void cv::split(const Mat& src, Mat* mv) { CV_INSTRUMENT_REGION() int k, depth = src.depth(), cn = src.channels(); if( cn == 1 ) { src.copyTo(mv[0]); return; } for( k = 0; k < cn; k++ ) { mv[k].create(src.dims, src.size, depth); } CV_IPP_RUN_FAST(ipp_split(src, mv, cn)); SplitFunc func = getSplitFunc(depth); CV_Assert( func != 0 ); size_t esz = src.elemSize(), esz1 = src.elemSize1(); size_t blocksize0 = (BLOCK_SIZE + esz-1)/esz; AutoBuffer<uchar> _buf((cn+1)*(sizeof(Mat*) + sizeof(uchar*)) + 16); const Mat** arrays = (const Mat**)(uchar*)_buf; uchar** ptrs = (uchar**)alignPtr(arrays + cn + 1, 16); arrays[0] = &src; for( k = 0; k < cn; k++ ) { arrays[k+1] = &mv[k]; } NAryMatIterator it(arrays, ptrs, cn+1); size_t total = it.size; size_t blocksize = std::min((size_t)CV_SPLIT_MERGE_MAX_BLOCK_SIZE(cn), cn <= 4 ? total : std::min(total, blocksize0)); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( size_t j = 0; j < total; j += blocksize ) { size_t bsz = std::min(total - j, blocksize); func( ptrs[0], &ptrs[1], (int)bsz, cn ); if( j + blocksize < total ) { ptrs[0] += bsz*esz; for( k = 0; k < cn; k++ ) ptrs[k+1] += bsz*esz1; } } } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_split( InputArray _m, OutputArrayOfArrays _mv ) { int type = _m.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; String dstargs, processelem, indexdecl; for (int i = 0; i < cn; ++i) { dstargs += format("DECLARE_DST_PARAM(%d)", i); indexdecl += format("DECLARE_INDEX(%d)", i); processelem += format("PROCESS_ELEM(%d)", i); } ocl::Kernel k("split", ocl::core::split_merge_oclsrc, format("-D T=%s -D OP_SPLIT -D cn=%d -D DECLARE_DST_PARAMS=%s" " -D PROCESS_ELEMS_N=%s -D DECLARE_INDEX_N=%s", ocl::memopTypeToStr(depth), cn, dstargs.c_str(), processelem.c_str(), indexdecl.c_str())); if (k.empty()) return false; Size size = _m.size(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(size, depth, i); std::vector<UMat> dst; _mv.getUMatVector(dst); int argidx = k.set(0, ocl::KernelArg::ReadOnly(_m.getUMat())); for (int i = 0; i < cn; ++i) argidx = k.set(argidx, ocl::KernelArg::WriteOnlyNoSize(dst[i])); k.set(argidx, rowsPerWI); size_t globalsize[2] = { (size_t)size.width, ((size_t)size.height + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif void cv::split(InputArray _m, OutputArrayOfArrays _mv) { CV_INSTRUMENT_REGION() CV_OCL_RUN(_m.dims() <= 2 && _mv.isUMatVector(), ocl_split(_m, _mv)) Mat m = _m.getMat(); if( m.empty() ) { _mv.release(); return; } CV_Assert( !_mv.fixedType() || _mv.empty() || _mv.type() == m.depth() ); int depth = m.depth(), cn = m.channels(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(m.dims, m.size.p, depth, i); std::vector<Mat> dst; _mv.getMatVector(dst); split(m, &dst[0]); }
42.786441
185
0.393797
liqingshan
0452ae4a768900c322fe1193c624b23be4479254
1,464
hpp
C++
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
31
2016-11-08T05:13:02.000Z
2022-02-23T19:13:01.000Z
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
6
2017-01-17T20:21:55.000Z
2021-09-02T07:36:18.000Z
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
5
2017-07-11T11:10:55.000Z
2022-02-14T01:55:16.000Z
#ifndef acommon_filter_char_hh #define acommon_filter_char_hh // This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. namespace acommon { struct FilterChar { unsigned int chr; unsigned int width; // width must always be < 256 typedef unsigned int Chr; typedef unsigned int Width; explicit FilterChar(Chr c = 0, Width w = 1) : chr(c), width(w) {} FilterChar(Chr c, FilterChar o) : chr(c), width(o.width) {} static Width sum(const FilterChar * o, const FilterChar * stop) { Width total = 0; for (; o != stop; ++o) total += o->width; return total; } static Width sum(const FilterChar * o, unsigned int size) { return sum(o, o+size); } FilterChar(Chr c, const FilterChar * o, unsigned int size) : chr(c), width(sum(o,size)) {} FilterChar(Chr c, const FilterChar * o, const FilterChar * stop) : chr(c), width(sum(o,stop)) {} operator Chr () const {return chr;} FilterChar & operator= (Chr c) {chr = c; return *this;} }; static inline bool operator==(FilterChar lhs, FilterChar rhs) { return lhs.chr == rhs.chr; } static inline bool operator!=(FilterChar lhs, FilterChar rhs) { return lhs.chr != rhs.chr; } } #endif
28.705882
69
0.638661
reydajp
0455e1b953175e5fa7f25afc9b03beefbaadcd2b
3,559
inl
C++
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
4
2017-01-24T09:32:23.000Z
2021-08-20T03:29:54.000Z
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
null
null
null
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
1
2021-08-20T03:29:55.000Z
2021-08-20T03:29:55.000Z
/* * Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project 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 */ /* * Stack.cpp * * Implementation file * * Author: Elad Raz <e@eladraz.com> */ #include "xStl/types.h" #include "data/exceptions.h" #include "runnable/Stack.h" template <class T, class Itr> void StackInfrastructor<T, Itr>::pop2null(uint amount) { if (amount == 0) return; if (isEmpty()) XSTL_THROW(ClrStackError); for (uint i = 0; i < amount; i++) { Itr b(m_stack.begin()); m_stack.remove(b); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::push(const T& var) { m_stack.insert(var); } template <class T, class Itr> const T& StackInfrastructor<T, Itr>::peek() const { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> T& StackInfrastructor<T, Itr>::getArg(uint index) { Itr j = m_stack.begin(); while (index > 0) { if (j == m_stack.end()) XSTL_THROW(ClrStackError); ++j; --index; } return *j; } template <class T, class Itr> T& StackInfrastructor<T, Itr>::tos() { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> bool StackInfrastructor<T, Itr>::isEmpty() const { return m_stack.begin() == m_stack.end(); } template <class T, class Itr> uint StackInfrastructor<T, Itr>::getStackCount() const { return m_stack.length(); } template <class T, class Itr> cList<T>& StackInfrastructor<T, Itr>::getList() { return m_stack; } template <class T, class Itr> const Itr StackInfrastructor<T, Itr>::getTosPosition() { return m_stack.begin(); } template <class T, class Itr> void StackInfrastructor<T, Itr>::revertStack(const Itr& pos) { while (m_stack.begin() != pos) { if (isEmpty()) { // Error with stack reverting CHECK_FAIL(); } m_stack.remove(m_stack.begin()); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::clear() { m_stack.removeAll(); }
25.421429
78
0.692329
eladraz
0455f1414c402e8cfef678358dc0fa8b56e2ad54
2,229
cpp
C++
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
// Copyright (c), Firelight Technologies Pty, Ltd. 2012-2019. #include "FMODEvent.h" #include "FMODStudioModule.h" #include "fmod_studio.hpp" UFMODEvent::UFMODEvent(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { } /** Get tags to show in content view */ void UFMODEvent::GetAssetRegistryTags(TArray<FAssetRegistryTag> &OutTags) const { Super::GetAssetRegistryTags(OutTags); if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Max); bool bOneshot = false; bool bStream = false; bool b3D = false; if (EventDesc) { EventDesc->isOneshot(&bOneshot); EventDesc->isStream(&bStream); EventDesc->is3D(&b3D); } OutTags.Add(UObject::FAssetRegistryTag("Oneshot", bOneshot ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("Streaming", bStream ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("3D", b3D ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); } } FString UFMODEvent::GetDesc() { return FString::Printf(TEXT("Event %s"), *AssetGuid.ToString(EGuidFormats::DigitsWithHyphensInBraces)); } void UFMODEvent::GetParameterDescriptions(TArray<FMOD_STUDIO_PARAMETER_DESCRIPTION> &Parameters) const { if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Auditioning); if (EventDesc) { int ParameterCount; EventDesc->getParameterDescriptionCount(&ParameterCount); Parameters.SetNumUninitialized(ParameterCount); for (int ParameterIndex = 0; ParameterIndex < ParameterCount; ++ParameterIndex) { EventDesc->getParameterDescriptionByIndex(ParameterIndex, &Parameters[ParameterIndex]); } } } }
37.779661
147
0.665321
alessandrofama
0459c857420fa66ea62ffc1905429b1cee9363d5
1,379
cpp
C++
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
28
2017-03-01T04:09:18.000Z
2022-02-01T13:33:50.000Z
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
3
2017-03-09T05:22:49.000Z
2017-08-02T18:38:05.000Z
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
17
2017-03-01T14:00:01.000Z
2022-02-08T06:36:54.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Daniele Panozzo <daniele.panozzo@gmail.com> // // 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/. #include "readPNG.h" #include <stb_image.h> IGL_INLINE bool igl::png::readPNG( const std::string png_file, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A ) { int cols,rows,n; unsigned char *data = stbi_load(png_file.c_str(), &cols, &rows, &n, 4); if(data == NULL) { return false; } R.resize(cols,rows); G.resize(cols,rows); B.resize(cols,rows); A.resize(cols,rows); for (unsigned i=0; i<rows; ++i) { for (unsigned j=0; j<cols; ++j) { R(j,rows-1-i) = data[4*(j + cols * i) + 0]; G(j,rows-1-i) = data[4*(j + cols * i) + 1]; B(j,rows-1-i) = data[4*(j + cols * i) + 2]; A(j,rows-1-i) = data[4*(j + cols * i) + 3]; } } stbi_image_free(data); return true; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh #endif
28.729167
78
0.647571
rushmash
045c0ec66c0e55f83e66ae30b656194e5ba64852
2,841
cpp
C++
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
2
2021-01-12T12:04:09.000Z
2022-03-21T10:09:54.000Z
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
70
2017-02-25T16:37:48.000Z
2018-01-28T22:15:42.000Z
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
null
null
null
// $flisboac 2018-01-14 #include "adl_catch.hpp" #include "adl/oct/cpu/closure_oper.hpp" #include "adl/oct/cpu/add_cons_close_oper.hpp" #include "adl/oct/cons.hpp" #include "adl/oct/system.hpp" #include "adl/oct/cpu/dense_dbm.hpp" #include "adl/oct/cpu/seq_context.hpp" using namespace adl::oct; using namespace adl::oct::cpu; using namespace adl::literals; using namespace adl::operators; using namespace adl::dsl; template <typename DbmType, typename OperType> static void add_cons(char const* type_name, DbmType& dbm, OperType&& oper) { using limits = typename DbmType::constant_limits; using constant_type = typename DbmType::constant_type; auto cons_close_sat = oper.get(); INFO("type_name = " << type_name << ", dbm = " << dbm.to_string()); REQUIRE((cons_close_sat)); for (auto k = dbm.first_var(); k <= dbm.last_var(); k++) { INFO(limits::raw_value(dbm.at(k, k))); REQUIRE( (dbm.at(k, k) == 0) ); // closure INFO(limits::raw_value(dbm.at(k, -k))); REQUIRE( (limits::is_even(dbm.at(k, -k))) ); // tight closure (unary constraints, all even) for (auto i = dbm.first_var(); i <= dbm.last_var(); i++) { INFO("dbm.at(k, i) = " << limits::raw_value(dbm.at(k, i))); INFO("dbm.at(k, -k) = " << limits::raw_value(dbm.at(k, -k))); INFO("dbm.at(-i, i) = " << limits::raw_value(dbm.at(-i, i))); REQUIRE( (dbm.at(k, i) <= (dbm.at(k, -k) / 2) + (dbm.at(-i, i) / 2)) ); // strong closure for (auto j = dbm.first_var(); j <= dbm.last_var(); j++) { REQUIRE( (dbm.at(i, j) <= dbm.at(i, k) + dbm.at(k, j)) ); // closure } } } }; template <typename FloatType> static void do_test(char const* type_name) { using limits = constant_limits<FloatType>; auto xi = 1_ov; auto xj = 2_ov; auto xdi = xi.to_counterpart(); auto xdj = xj.to_counterpart(); auto context = cpu::seq_context::make(); auto dbm = context.make_dbm<cpu::dense_dbm, FloatType>(xj); dbm.assign({ xi <= FloatType(3.0), xj <= FloatType(2.0), xi + xj <= FloatType(6.0) }); auto queue = context.make_queue(); auto closure = queue.make_oper<cpu::closure_oper>(dbm); REQUIRE( (closure.get()) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi <= FloatType(3.0)) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi - xj <= FloatType(5.0)) ); } TEST_CASE("unit:adl/oct/cpu/add_cons_close_oper.hpp", "[unit][oper][adl][adl/oct][adl/oct/cpu]") { //do_test<int>("int"); // TBD do_test<float>("float"); do_test<double>("double"); do_test<long double>("long double"); do_test<float_int>("float_int"); do_test<double_int>("double_int"); do_test<ldouble_int>("ldouble_int"); }
35.074074
139
0.613868
flisboac
045c1f5e1a51ba243bb541b7645cabb7237e545e
2,032
cpp
C++
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/color_base_type.hpp> #include <sge/opengl/color_order.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/internal_color_format.hpp> #include <sge/opengl/texture/binding_fwd.hpp> #include <sge/opengl/texture/buffer_type.hpp> #include <sge/opengl/texture/surface_config_fwd.hpp> #include <sge/opengl/texture/funcs/set_2d.hpp> #include <sge/renderer/const_raw_pointer.hpp> #include <sge/renderer/dim2.hpp> #include <sge/renderer/texture/creation_failed.hpp> #include <sge/renderer/texture/mipmap/level.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/cast/to_void_ptr.hpp> #include <fcppt/math/dim/output.hpp> void sge::opengl::texture::funcs::set_2d( sge::opengl::texture::binding const &, sge::opengl::texture::surface_config const &, sge::opengl::texture::buffer_type const _buffer_type, sge::opengl::color_order const _format, sge::opengl::color_base_type const _format_type, sge::opengl::internal_color_format const _internal_format, sge::renderer::texture::mipmap::level const _level, sge::renderer::dim2 const &_dim, sge::renderer::const_raw_pointer const _src) { sge::opengl::call( ::glTexImage2D, _buffer_type.get(), fcppt::cast::to_signed(_level.get()), _internal_format.get(), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.w())), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.h())), 0, _format.get(), _format_type.get(), fcppt::cast::to_void_ptr(_src)); SGE_OPENGL_CHECK_STATE( (fcppt::format(FCPPT_TEXT("Creation of texture with size %1% failed!")) % _dim).str(), sge::renderer::texture::creation_failed) }
38.339623
92
0.718012
cpreh
045c670d8919bd4d658a5b55e884390a99fe6a0a
4,818
cpp
C++
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "droplabel.h" #include "processdialog.h" #include "preferencesdialog.h" #include "aboutdialog.h" #include "processmodemodel.h" #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_settings(new Waifu2xConverterQtSettings), m_procmode(new ProcessModeModel) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { delete ui; } ProcessModeModel* MainWindow::processModeModel(){ return m_procmode; } void MainWindow::browseImage() { QFileDialog dialog(this, tr("Select image"), m_settings->lastUsedDir()); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setMimeTypeFilters({"image/jpeg", "image/png", "application/octet-stream"}); if (dialog.exec() == QFileDialog::Accepted){ QString filePath = dialog.selectedFiles().first(); m_settings->setLastUsedDir(QDir(filePath).absolutePath()); processImage(filePath); } } void MainWindow::processImage(const QString &imageFileName) { QString outputFileName; if (m_settings->isUseCustomFileName()) { outputFileName = browseSaveLocation(imageFileName); if (outputFileName.isEmpty()) return; } ProcessDialog dialog(imageFileName, ui->threadsBox->value(), ui->scaleRatioBox->value(), ui->noiseReductionLevel->value(), ui->imageProcessingModeBox->currentData().toString(), outputFileName, m_settings->modelDirectory(), this); dialog.exec(); } QString MainWindow::browseSaveLocation(const QString &inputImageFileName) { QDir dir(inputImageFileName); QString fileExtension; QFileDialog dialog(this, tr("Save")); dir.cdUp(); if (inputImageFileName.contains(".")) fileExtension = inputImageFileName.split(".").last(); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setDirectory(dir.absolutePath()); dialog.selectFile(inputImageFileName); dialog.exec(); return dialog.selectedFiles().isEmpty() ? QString() : dialog.selectedFiles().first(); } void MainWindow::closeEvent(QCloseEvent *) { save(); } void MainWindow::save() { m_settings->setThreadsCount(ui->threadsBox->value()); m_settings->setScaleRatio(ui->scaleRatioBox->value()); m_settings->setNoiseReductionLevel(ui->noiseReductionLevel->value()); m_settings->setImageProcessingMode(ui->imageProcessingModeBox->currentData().toString()); } void MainWindow::toggleOptions(int boxIndex){ QString currentData = ui->imageProcessingModeBox->itemData(boxIndex).toString(); ui->noiseReductionLevel->setEnabled(currentData.contains("noise")); ui->scaleRatioBox->setEnabled(currentData.contains("scale")); } void MainWindow::init() { qApp->setApplicationDisplayName(tr("Waifu2x Converter Qt")); setWindowTitle(QApplication::applicationDisplayName()); auto* dropLabel = new DropLabel(this); ui->imageProcessingModeBox->setModel(m_procmode); connect(ui->action_Preferences, &QAction::triggered, [&]() { PreferencesDialog dialog; dialog.exec(); }); connect(ui->imageProcessingModeBox, SIGNAL(currentIndexChanged(int)),SLOT(toggleOptions(int))); connect(dropLabel, SIGNAL(fileDropped(QString)), this, SLOT(processImage(QString))); connect(ui->browseButton, SIGNAL(clicked(bool)), this, SLOT(browseImage())); connect(ui->action_Open_image, &QAction::triggered, this, &MainWindow::browseImage); connect(ui->action_About_waifu2x_converter_qt, &QAction::triggered, [&]() { AboutDialog dialog; dialog.exec(); }); connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->actionE_xit, &QAction::triggered, qApp, &QApplication::quit); ui->browseButton->setIcon(style()->standardIcon((QStyle::SP_DirOpenIcon))); ui->action_Open_image->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon)); ui->actionE_xit->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton)); ui->action_About_waifu2x_converter_qt->setIcon(style()->standardIcon(QStyle::SP_DialogHelpButton)); ui->dropLayout->insertWidget(0, dropLabel, 10); ui->threadsBox->setValue(m_settings->threadsCount()); ui->scaleRatioBox->setValue(m_settings->scaleRatio()); ui->noiseReductionLevel->setValue(m_settings->noiseReductionLevel()); int currDataIndex = ui->imageProcessingModeBox->findData(m_settings->imageProcessingMode()); ui->imageProcessingModeBox->setCurrentIndex(currDataIndex); }
34.170213
103
0.679743
rossomah
045d4d63848b049e7e86e47f4a829b066701d3df
454
cpp
C++
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
3
2020-03-27T15:25:19.000Z
2022-01-18T14:12:25.000Z
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
#include "pch.h" #include "DependencyDestructor.h" DependencyDestructor::DependencyDestructor(UniqueFunction<void(Object&, void*)> aDestroyFunc) noexcept : myDestroyFunc(std::move(aDestroyFunc)) {} void DependencyDestructor::Destroy(Object& aObject, SComponent& aComponent) { myDestroyFunc(aObject, &aComponent); } void DependencyDestructor::Destroy(Object& aObject, _BaseFunctionality& aFunctionality) { myDestroyFunc(aObject, &aFunctionality); }
26.705882
102
0.799559
nicolasgustafsson
0460535ea80b720c029d52957f7462d8f1437044
1,991
hpp
C++
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #ifndef CYNG_ASYNC_TASK_BUILDER_HPP #define CYNG_ASYNC_TASK_BUILDER_HPP #include <cyng/async/task/task.hpp> #include <cyng/async/mux.h> #include <chrono> namespace cyng { namespace async { /** * Create a new task class */ template < typename T, typename ...Args > auto make_task(mux& m, Args &&... args) -> std::shared_ptr<task < T >> { typedef task < T > task_type; return std::make_shared< task_type >(m, std::forward<Args>(args)...); } /** * There are three options to start a task: * (1) sync - insert task into task list and call run() method * in the same thread. * * (2) async - insert task into task list and call run() method * in another thread. * * (3) delayed - insert task into task list and call run() method * from a timer callback. */ template < typename T, typename ...Args > std::pair<std::size_t, bool> start_task_sync(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return std::make_pair(tp->get_id(), m.insert(tp, sync())); } template < typename T, typename ...Args > std::size_t start_task_detached(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return (m.insert(tp, detach())) ? tp->get_id() : NO_TASK ; } template < typename T, typename R, typename P, typename ...Args > std::pair<std::size_t, bool> start_task_delayed(mux& m, std::chrono::duration<R, P> d, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); if (m.insert(tp, none())) { tp->suspend(d); return std::make_pair(tp->get_id(), true); } return std::make_pair(tp->get_id(), false); } inline std::pair<std::size_t, bool> start_task_sync(mux& m, shared_task tp) { return std::make_pair(tp->get_id(), m.insert(tp, sync())); } } // async } #endif // CYNG_ASYNC_TASK_BUILDER_HPP
23.987952
105
0.618282
solosTec
04618b56167c2afb23b07fc7a8c03d94ac5d020e
4,753
cpp
C++
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include <stdlib.h> #include <time.h> #include <ctime> #include "spaceship.hpp" MySpaceShip::MySpaceShip() { //Setup Quadric Object pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); posx = 0.0f; posy = 10.0f; posz = 2.0f; roty = 0.0f; //initial velocity (in unit per second) velx = 0.0f; vely = 3.0f; velz = 0.0f; //velroty = 10.0f; } MySpaceShip::~MySpaceShip() { gluDeleteQuadric(pObj); } void MySpaceShip::draw() { glTranslatef(posx, posy, posz); glRotatef(timetick, 0.0f, 1.0f, 0.0f); srand(time(NULL)); glDisable(GL_CULL_FACE); //front glPushMatrix(); glTranslatef(0.0f, 10.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 5.0f, 0.0f, 10, 26, 5); glPopMatrix(); //body glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(rand()%45*0.1, rand()%45*0.1,rand()%45 * 0.01 ); gluCylinder(pObj, 5.0f, 5.0f, 15, 26, 5); glPopMatrix(); //back glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(1.0f, 1.0f, 1.0f); gluDisk(pObj, 0.0f, 5.0f, 26, 5); glPopMatrix(); //top mirror glPushMatrix(); glTranslatef(0.0f, 14.0f, -8.0f); glColor3f(0.0f, 1.0f, 1.0f); gluSphere(pObj,4.0f, 20, 20); glPopMatrix(); //left wing alpha glPushMatrix(); glTranslatef(10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //left wing beta glPushMatrix(); glTranslatef(10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing alpha glPushMatrix(); glTranslatef(-10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing beta glPushMatrix(); glTranslatef(-10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //exhaust pipe glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 4.0f, 2.0f, 6, 26, 5); glPopMatrix(); //EP back glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(1.0f, 0.0f, 0.0f); gluDisk(pObj, 0.0f, 4.0f, 26, 5); glPopMatrix(); glEnable(GL_CULL_FACE); } void MySpaceShip::Movespaceship() { glPushMatrix(); glTranslatef(0.0f , tickMove , 0.0f ); //glRotatef(roty, 0.0f, 1.0f, 0.0f); draw(); glPopMatrix(); } void MySpaceShip::drawfence() { glDisable(GL_CULL_FACE); glPushMatrix(); glColor3f(1.0f, 1.0f, 0.0f); glTranslatef(0.0f, 0.0f, 0.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); gluCylinder(pObj, 25.0f, 25.0f, 7, 26, 5); glPopMatrix(); } //elapsetime in milisec void MySpaceShip::tickTime(long int elapseTime) { ticktick++; if(ticktick == 30){ if(tickMove < 51.0 && moveUp == 1){ ticktick =0; tickMove+= 5.0; if(tickMove >= 51.0) moveUp = 0; }else if(moveUp == 0){ ticktick=0; tickMove-= 5.0; if(tickMove < 0.0){ moveUp = 1; } } } }
24.626943
62
0.553124
shaungoh01
0461d4b23fd08dadbc6ccba03f980035da92353d
2,006
hpp
C++
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
45
2018-12-13T21:11:23.000Z
2022-03-28T09:21:44.000Z
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
279
2018-12-18T08:52:43.000Z
2022-03-24T19:03:29.000Z
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
25
2018-12-13T20:38:51.000Z
2022-03-25T09:45:58.000Z
#pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/sidechain_defs.hpp> #include <fc/safe.hpp> namespace graphene { namespace chain { struct son_wallet_withdraw_create_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_id_type son_id; fc::time_point_sec timestamp; uint32_t block_num; sidechain_type sidechain; std::string peerplays_uid; std::string peerplays_transaction_id; chain::account_id_type peerplays_from; chain::asset peerplays_asset; sidechain_type withdraw_sidechain; std::string withdraw_address; std::string withdraw_currency; safe<int64_t> withdraw_amount; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; struct son_wallet_withdraw_process_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_wallet_withdraw_id_type son_wallet_withdraw_id; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; } } // namespace graphene::chain FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation, (fee)(payer) (son_id) (timestamp) (block_num) (sidechain) (peerplays_uid) (peerplays_transaction_id) (peerplays_from) (peerplays_asset) (withdraw_sidechain) (withdraw_address) (withdraw_currency) (withdraw_amount) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation, (fee)(payer) (son_wallet_withdraw_id) )
35.192982
95
0.720339
vampik33
046339ccd708b23e61fa5cc526dd7bf97a3512d7
2,633
cc
C++
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-08-21T05:54:42.000Z
2019-08-21T05:54:42.000Z
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
null
null
null
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-10-11T09:34:49.000Z
2019-10-11T09:34:49.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/arm/math/im2sequence.h" #include <arm_neon.h> #include "lite/utils/cp_logging.h" namespace paddle { namespace lite { namespace arm { namespace math { void im2sequence(const float* input, const int input_c, const int input_h, const int input_w, const int kernel_h, const int kernel_w, const int pad_top, const int pad_bottom, const int pad_left, const int pad_right, const int stride_h, const int stride_w, const int out_h, const int out_w, float* out, Context<TARGET(kARM)>* ctx) { int window_size = kernel_h * kernel_w; int out_rows = out_h * out_w; int out_cols = input_c * window_size; int H_pad = input_h + pad_top + pad_bottom; int W_pad = input_w + pad_left + pad_right; for (int h_id = 0; h_id < out_h; h_id++) { for (int w_id = 0; w_id < out_w; w_id++) { // consider dilation. int start_h = h_id * stride_h - pad_top; int start_w = w_id * stride_w - pad_left; for (int c_id = 0; c_id < input_c; c_id++) { for (int k_h_id = 0; k_h_id < kernel_h; k_h_id++) { int in_h_id = start_h + k_h_id; bool exceed_flag = (in_h_id < 0) || (in_h_id >= H_pad); int out_start_id = (h_id * out_w + w_id) * out_cols + c_id * window_size; for (int k_w_id = 0; k_w_id < kernel_w; k_w_id++) { int in_w_id = start_w + k_w_id; exceed_flag = exceed_flag || (in_w_id < 0) || (in_w_id >= W_pad); int input_id = (c_id * input_h + in_h_id) * input_w + in_w_id; int out_id = out_start_id + k_h_id * kernel_w + k_w_id; out[out_id] = exceed_flag ? 0.f : input[input_id]; } } } } } } } // namespace math } // namespace arm } // namespace lite } // namespace paddle
36.068493
77
0.590961
banbishan
0463ff21ce8758867f178b840135651d22ddf08f
1,305
cpp
C++
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
/* Idea: - Dynamic Programming - If you reach the base case in the recursion, then you have an answer, so print it. - This method work if the dynamic programming answer is true or false. */ #include <bits/stdc++.h> using namespace std; int const N = 1e5 + 1; int n, a[N], dp[N][6]; vector<int> sol; int rec(int idx, int prv) { if(idx == n) { for(int i = 0; i < sol.size(); ++i) printf("%s%d", i == 0 ? "" : " ", sol[i]); puts(""); exit(0); } int &ret = dp[idx][prv]; if(ret != -1) return ret; ret = 0; if(a[idx] == a[idx - 1]) { for(int i = 1; i <= 5; ++i) if(i != prv) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] > a[idx - 1]) { for(int i = prv + 1; i <= 5; ++i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] < a[idx - 1]) { for(int i = prv - 1; i >= 1; --i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } return ret; } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); memset(dp, -1, sizeof dp); for(int i = 1; i <= 5; ++i) { sol.push_back(i); if(rec(1, i)) return 0; sol.pop_back(); } puts("-1"); return 0; }
17.4
56
0.45977
khaled-farouk
04652172919828de08f918ebb22c9ccef7308f03
555
cpp
C++
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
#include "../../include/gui/PlayingScreen.h" /* Derived-screen-specific additional frame processing for display*/ void PlayingScreen::processFrame(Mat& frame, const TrackingInfo& tracker) const { drawTrackingMarker ( frame, tracker.current() ); } void PlayingScreen::drawTrackingMarker(Mat& frame, const Point& center) const { /* "FREQUENCY POINTER" */ circle ( frame, center, dynconf.trackingMarkerRadius*0.25, StaticConfiguration::trackingMarkerColor, 10, CV_AA ); }
25.227273
81
0.652252
ballcue
046afc267fd2a398fe420ba1b20c4d957d9ecb61
2,075
cpp
C++
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
1
2022-02-13T15:34:33.000Z
2022-02-13T15:34:33.000Z
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
null
null
null
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "fft.h" /************************************************************ ************************************************************/ /****************************** ******************************/ FFT::FFT() { } /****************************** ******************************/ FFT::~FFT() { } /****************************** ******************************/ void FFT::threadedFunction() { while(isThreadRunning()) { lock(); unlock(); sleep(THREAD_SLEEP_MS); } } /****************************** ******************************/ void FFT::setup(int AUDIO_BUF_SIZE) { /******************** ■std::vectorのresizeとassignの違い (C++) https://minus9d.hatenablog.com/entry/2021/02/07/175159 ********************/ vol_l.assign(AUDIO_BUF_SIZE, 0.0); vol_r.assign(AUDIO_BUF_SIZE, 0.0); } /****************************** ******************************/ void FFT::update() { } /****************************** ******************************/ void FFT::draw() { } /****************************** ******************************/ void FFT::SetVol(ofSoundBuffer & buffer) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ vol_l[i] = buffer[i*2 + 0]; vol_r[i] = buffer[i*2 + 1]; } } unlock(); } /****************************** ******************************/ void FFT::GetVol(ofSoundBuffer & buffer, bool b_EnableAudioOut) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ if(b_EnableAudioOut){ buffer[i*2 + 0] = vol_l[i]; buffer[i*2 + 1] = vol_r[i]; }else{ buffer[i*2 + 0] = 0; buffer[i*2 + 1] = 0; } } } unlock(); }
20.75
89
0.360482
SJ-magic-youtube-VisualProgrammer
046b065236406a07667a6ee6c8e615215e77a1ec
1,132
cpp
C++
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Example 3: Input: s = "bb" Output: 2 Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only. */ // all even chars can be used to construct the string, but only one odd char can be added at last class Solution { public: int longestPalindrome(string s) { unordered_map<char,int> ch2freq; int res = 0; bool remainder = false; for ( auto c : s ) ch2freq[c]++; for ( auto it : ch2freq ) { if ( it.second % 2 ) { remainder = true; } res += (it.second / 2) * 2; } if ( remainder ) res++; return res; } };
21.358491
148
0.590989
ComputerProgrammerStorager
046bd4036f74b99487b2080e76d1afa8bbe8fdb2
1,385
cpp
C++
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
1
2016-05-22T07:51:02.000Z
2016-05-22T07:51:02.000Z
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
/* GammaTable.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.00 // // Tag: Desktop // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2016 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/video/GammaTable.h> #include <math.h> namespace CCore { namespace Video { /* class GammaTable */ template <UIntType UInt> void GammaTable::Fill(PtrLen<UInt> table,double order) { double M=table.len-1; double V=MaxUInt<UInt>; for(ulen i=0; i<table.len ;i++) { double x=i/M; double y=pow(x,order); table[i]=UInt( round(V*y) ); } } GammaTable::GammaTable() noexcept { } GammaTable::~GammaTable() { } void GammaTable::fill(double order) { static const ulen DirectLen = ulen(1)<<8 ; static const ulen InverseLen = ulen(1)<<16 ; if( !direct.getLen() ) { SimpleArray<uint16> direct_(DirectLen); SimpleArray<uint8> inverse_(InverseLen); direct=std::move(direct_); inverse=std::move(inverse_); } Fill(Range(direct),order); Fill(Range(inverse),1/order); this->order=order; } } // namespace Video } // namespace CCore
19.507042
90
0.555235
SergeyStrukov
0475e337dbdad96a692616f58bd13ae0ef379153
5,797
cpp
C++
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: GenProtoS_CallResponse.cpp // // AUTHOR: Dean Roddey // // CREATED: 11/24/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements a simple class that represents a call/response // exchange with the target device. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "GenProtoS_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TGenProtoCallRep,TObject) // --------------------------------------------------------------------------- // CLASS: TGenProtoCallRep // PREFIX: clrp // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TGenProtoCallRep: Constructors and Destructor // --------------------------------------------------------------------------- TGenProtoCallRep::TGenProtoCallRep() : m_c4MillisPeriod(0) , m_c4MillisToWait(0) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(nullptr) , m_prepToExpect(nullptr) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) : m_c4MillisPeriod(0) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait , const tCIDLib::TCard4 c4MillisPeriod) : m_c4MillisPeriod(c4MillisPeriod) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep::TGenProtoCallRep(const TGenProtoCallRep& clrpToCopy) : m_c4MillisPeriod(clrpToCopy.m_c4MillisPeriod) , m_c4MillisToWait(clrpToCopy.m_c4MillisToWait) , m_c4NextPoll(clrpToCopy.m_c4NextPoll) , m_pqryToSend(clrpToCopy.m_pqryToSend) , m_prepToExpect(clrpToCopy.m_prepToExpect) { } TGenProtoCallRep::~TGenProtoCallRep() { // We don't own the query/reply pointers, so do nothing } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public operators // --------------------------------------------------------------------------- TGenProtoCallRep& TGenProtoCallRep::operator=(const TGenProtoCallRep& clrpToAssign) { if (this != &clrpToAssign) { // We don't own the query and reply pointers, so we can shallow copy m_c4MillisPeriod = clrpToAssign.m_c4MillisPeriod; m_c4MillisToWait = clrpToAssign.m_c4MillisToWait; m_c4NextPoll = clrpToAssign.m_c4NextPoll; m_pqryToSend = clrpToAssign.m_pqryToSend; m_prepToExpect = clrpToAssign.m_prepToExpect; } return *this; } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TGenProtoCallRep::bExpectsReply() const { return (m_prepToExpect != nullptr); } tCIDLib::TCard4 TGenProtoCallRep::c4MillisPeriod() const { return m_c4MillisPeriod; } tCIDLib::TCard4 TGenProtoCallRep::c4MillisToWait() const { return m_c4MillisToWait; } tCIDLib::TCard4 TGenProtoCallRep::c4NextPollTime() const { return m_c4NextPoll; } const TGenProtoQuery& TGenProtoCallRep::qryToSend() const { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } TGenProtoQuery& TGenProtoCallRep::qryToSend() { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } const TGenProtoReply& TGenProtoCallRep::repToExpect() const { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } TGenProtoReply& TGenProtoCallRep::repToExpect() { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } tCIDLib::TVoid TGenProtoCallRep::ResetPollTime() { m_c4NextPoll = TTime::c4Millis() + m_c4MillisPeriod; } tCIDLib::TVoid TGenProtoCallRep::Set( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) { // We don't own the pointers, so no cleanup of old code is required m_c4MillisToWait = c4MillisToWait; m_pqryToSend = pqryToSend; m_prepToExpect = prepToExpect; }
26.962791
78
0.558737
MarkStega
04779e597994f9724d6ccdd8b42e5a4fb6b7c904
8,607
cpp
C++
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
#include "ltr559.hpp" #include <algorithm> namespace pimoroni { lookup::lookup(std::initializer_list<uint16_t> values) : lut(values) { } uint8_t lookup::index(uint16_t value) { auto it = find(lut.begin(), lut.end(), value); if(it == lut.end()) return 0; return it - lut.begin(); } uint16_t lookup::value(uint8_t index) { return lut[index]; } pimoroni::lookup LTR559::lookup_led_current({5, 10, 20, 50, 100}); pimoroni::lookup LTR559::lookup_led_duty_cycle({25, 50, 75, 100}); pimoroni::lookup LTR559::lookup_led_pulse_freq({30, 40, 50, 60, 70, 80, 90, 100}); pimoroni::lookup LTR559::lookup_proximity_meas_rate({10, 50, 70, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_integration_time({100, 50, 200, 400, 150, 250, 300, 350}); pimoroni::lookup LTR559::lookup_light_repeat_rate({50, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_gain({1, 2, 4, 8, 0, 0, 48, 96}); bool LTR559::init() { i2c_init(i2c, 400000); gpio_set_function(sda, GPIO_FUNC_I2C); gpio_pull_up(sda); gpio_set_function(scl, GPIO_FUNC_I2C); gpio_pull_up(scl); if(interrupt != PIN_UNUSED) { gpio_set_function(interrupt, GPIO_FUNC_SIO); gpio_set_dir(interrupt, GPIO_IN); gpio_pull_up(interrupt); } reset(); interrupts(true, true); // 50mA, 1.0 duty cycle, 30Hz, 1 pulse proximity_led(50, 1.0, 30, 1); // enabled, gain 4x light_control(true, 4); // enabled, saturation indicator enabled proximity_control(true, true); // 100ms measurement rate proximity_measurement_rate(100); // 50ms integration time and repeat rate light_measurement_rate(50, 50); light_threshold(0xFFFF, 0x0000); proximity_threshold(0x7FFF, 0x7FFF); proximity_offset(0); return true; } void LTR559::reset() { set_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT); while(get_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT)) { sleep_ms(100); } } i2c_inst_t* LTR559::get_i2c() const { return i2c; } int LTR559::get_sda() const { return sda; } int LTR559::get_scl() const { return scl; } int LTR559::get_int() const { return interrupt; } uint8_t LTR559::part_id() { uint8_t part_id; read_bytes(LTR559_PART_ID, &part_id, 1); return (part_id >> LTR559_PART_ID_PART_NUMBER_SHIFT) & LTR559_PART_ID_PART_NUMBER_MASK; } uint8_t LTR559::revision_id() { uint8_t revision_id; read_bytes(LTR559_PART_ID, &revision_id, 1); return revision_id & LTR559_PART_ID_REVISION_MASK; } uint8_t LTR559::manufacturer_id() { uint8_t manufacturer; read_bytes(LTR559_MANUFACTURER_ID, &manufacturer, 1); return manufacturer; } bool LTR559::get_reading() { bool has_updated = false; uint8_t status; this->read_bytes(LTR559_ALS_PS_STATUS, &status, 1); bool als_int = (status >> LTR559_ALS_PS_STATUS_ALS_INTERRUPT_BIT) & 0b1; bool ps_int = (status >> LTR559_ALS_PS_STATUS_PS_INTERRUPT_BIT) & 0b1; bool als_data = (status >> LTR559_ALS_PS_STATUS_ALS_DATA_BIT) & 0b1; bool ps_data = (status >> LTR559_ALS_PS_STATUS_PS_DATA_BIT) & 0b1; if(ps_int || ps_data) { has_updated = true; uint16_t ps0; read_bytes(LTR559_PS_DATA, (uint8_t *)&ps0, 2); ps0 &= LTR559_PS_DATA_MASK; data.proximity = ps0; } if(als_int || als_data) { has_updated = true; uint16_t als[2]; read_bytes(LTR559_ALS_DATA_CH1, (uint8_t *)&als, 4); data.als0 = als[1]; data.als1 = als[0]; data.gain = this->lookup_light_gain.value((status >> LTR559_ALS_PS_STATUS_ALS_GAIN_SHIFT) & LTR559_ALS_PS_STATUS_ALS_GAIN_MASK); data.ratio = 101.0f; if((uint32_t)data.als0 + data.als1 > 0) { data.ratio = (float)data.als1 * 100.0f / ((float)data.als1 + data.als0); } uint8_t ch_idx = 3; if(this->data.ratio < 45) ch_idx = 0; else if(data.ratio < 64) ch_idx = 1; else if (data.ratio < 85) ch_idx = 2; float lux = ((int32_t)data.als0 * ch0_c[ch_idx]) - ((int32_t)data.als1 * ch1_c[ch_idx]); lux /= (float)this->data.integration_time / 100.0f; lux /= (float)this->data.gain; data.lux = (uint16_t)(lux / 10000.0f); } return has_updated; } void LTR559::interrupts(bool light, bool proximity) { uint8_t buf = 0; buf |= 0b1 << LTR559_INTERRUPT_POLARITY_BIT; buf |= (uint8_t)light << LTR559_INTERRUPT_ALS_BIT; buf |= (uint8_t)proximity << LTR559_INTERRUPT_PS_BIT; write_bytes(LTR559_INTERRUPT, &buf, 1); } void LTR559::proximity_led(uint8_t current, uint8_t duty_cycle, uint8_t pulse_freq, uint8_t num_pulses) { current = lookup_led_current.index(current); duty_cycle = lookup_led_duty_cycle.index(duty_cycle); duty_cycle <<= LTR559_PS_LED_DUTY_CYCLE_SHIFT; pulse_freq = lookup_led_pulse_freq.index(pulse_freq); pulse_freq <<= LTR559_PS_LED_PULSE_FREQ_SHIFT; uint8_t buf = current | duty_cycle | pulse_freq; write_bytes(LTR559_PS_LED, &buf, 1); buf = num_pulses & LTR559_PS_N_PULSES_MASK; write_bytes(LTR559_PS_N_PULSES, &buf, 1); } void LTR559::light_control(bool active, uint8_t gain) { uint8_t buf = 0; gain = lookup_light_gain.index(gain); buf |= gain << LTR559_ALS_CONTROL_GAIN_SHIFT; if(active) buf |= (0b1 << LTR559_ALS_CONTROL_MODE_BIT); else buf &= ~(0b1 << LTR559_ALS_CONTROL_MODE_BIT); write_bytes(LTR559_ALS_CONTROL, &buf, 1); } void LTR559::proximity_control(bool active, bool saturation_indicator) { uint8_t buf = 0; read_bytes(LTR559_PS_CONTROL, &buf, 1); if(active) buf |= LTR559_PS_CONTROL_ACTIVE_MASK; else buf &= ~LTR559_PS_CONTROL_ACTIVE_MASK; if(saturation_indicator) buf |= 0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT; else buf &= ~(0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT); write_bytes(LTR559_PS_CONTROL, &buf, 1); } void LTR559::light_threshold(uint16_t lower, uint16_t upper) { lower = __builtin_bswap16(lower); upper = __builtin_bswap16(upper); write_bytes(LTR559_ALS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_ALS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::proximity_threshold(uint16_t lower, uint16_t upper) { lower = uint16_to_bit12(lower); upper = uint16_to_bit12(upper); write_bytes(LTR559_PS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_PS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::light_measurement_rate(uint16_t integration_time, uint16_t rate) { data.integration_time = integration_time; integration_time = lookup_light_integration_time.index(integration_time); rate = lookup_light_repeat_rate.index(rate); uint8_t buf = 0; buf |= rate; buf |= integration_time << LTR559_ALS_MEAS_RATE_INTEGRATION_TIME_SHIFT; write_bytes(LTR559_ALS_MEAS_RATE, &buf, 1); } void LTR559::proximity_measurement_rate(uint16_t rate) { uint8_t buf = lookup_proximity_meas_rate.index(rate); write_bytes(LTR559_PS_MEAS_RATE, &buf, 1); } void LTR559::proximity_offset(uint16_t offset) { offset &= LTR559_PS_OFFSET_MASK; write_bytes(LTR559_PS_OFFSET, (uint8_t *)&offset, 1); } uint16_t LTR559::bit12_to_uint16(uint16_t value) { return ((value & 0xFF00) >> 8) | ((value & 0x000F) << 8); } uint16_t LTR559::uint16_to_bit12(uint16_t value) { return ((value & 0xFF) << 8) | ((value & 0xF00) >> 8); } // i2c functions int LTR559::write_bytes(uint8_t reg, uint8_t *buf, int len) { uint8_t buffer[len + 1]; buffer[0] = reg; for(int x = 0; x < len; x++) { buffer[x + 1] = buf[x]; } return i2c_write_blocking(i2c, address, buffer, len + 1, false); }; int LTR559::read_bytes(uint8_t reg, uint8_t *buf, int len) { i2c_write_blocking(i2c, address, &reg, 1, true); i2c_read_blocking(i2c, address, buf, len, false); return len; }; uint8_t LTR559::get_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); return value & (mask << shift); } void LTR559::set_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value |= mask << shift; write_bytes(reg, &value, 1); } void LTR559::clear_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value &= ~(mask << shift); write_bytes(reg, &value, 1); } }
29.782007
134
0.6748
graeme-winter
04793ebe7db7522cc1ddf61cec31cbe68b55cba3
916
cpp
C++
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
#include "widget.h" Widget::Widget(QWidget *parent): QWidget(parent) { QVBoxLayout *l = new QVBoxLayout(this); le = new QLineEdit(this); label = new QLabel("Placeholder",this); labelTime = new QLabel(this); le->setValidator(new QIntValidator(0,100000,this)); l->addWidget(le); l->addWidget(labelTime); l->addWidget(label); w = new WindowHandler("osu.exe"); connect(le,SIGNAL(returnPressed()),this,SLOT(setPid())); QTimer *t = new QTimer(this); t->setInterval(50); connect(t,SIGNAL(timeout()),this,SLOT(refreshScreen())); t->start(); } Widget::~Widget() { } void Widget::setPid() { w->setPid(le->text().toLong()); } void Widget::refreshScreen() { QTime t; t.start(); QPixmap p = w->getProcessScreen(); labelTime->setText(QString::number(t.elapsed()) + QString("ms")); label->setPixmap(p.scaled(600,600,Qt::KeepAspectRatio)); }
20.818182
69
0.635371
FuSoftware
047abf09bdf3505d2fa2557e82e6bf7802596554
4,918
cpp
C++
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
// // Created by theppsh on 17-4-13. // #include <iostream> #include <iomanip> #include "src/aes.hpp" #include "src/triple_des.hpp" int main(int argc,char ** args){ /**aes 加密*/ /// 128位全0的秘钥 u_char key_block[]={0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 }; u_char plain_block[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18, }; u_char cipher_block[16]; AES aes_test(key_block); std::cout<<"********** aes 加密测试 **********"<<std::endl; std::memcpy(cipher_block,plain_block,16); aes_test.Cipher(cipher_block); auto cout_default_flags = std::cout.flags(); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(cipher_block[i])<<" "; } std::cout.setf(cout_default_flags); std::cout<<std::endl; std::cout<<std::endl; std::cout<<"********** aes 解密测试 **********"<<std::endl; std::memcpy(plain_block,cipher_block,16); aes_test.InvCipher(plain_block); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(plain_block[i])<<" "; } std::cout<<std::endl; std::cout.setf(cout_default_flags); /// ***aes加密文件测试 *** std::cout<<std::endl; std::cout<<"******** aes 加密文件测试 ********"<<std::endl; std::string plain_txt= "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/plain.txt"; std::string cipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/cipher.txt"; std::string decipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/decipher.txt"; aes_test.CipherFile(plain_txt,cipher_txt); std::cout<<std::endl; std::cout<<"******** 解密文件测试 ********"<<std::endl; aes_test.InvCipherFile(cipher_txt,decipher_txt); [](const std::string & file_path1,const std::string file_path2){ std::fstream f1,f2; f1.open(file_path1); f2.open(file_path2); assert(f1.is_open()); assert(f2.is_open()); f1.seekg(0,std::ios::end); f2.seekg(0,std::ios::end); int f1_size = static_cast<int>(f1.tellg()); int f2_size = static_cast<int>(f2.tellg()); std::shared_ptr<char> f1_file_buffer(new char[f1_size+1]); std::shared_ptr<char> f2_file_buffer(new char[f2_size+1]); f1.seekg(0,std::ios::beg); f2.seekg(0,std::ios::beg); f1.read(f1_file_buffer.get(),f1_size); f2.read(f2_file_buffer.get(),f2_size); f1_file_buffer.get()[f1_size]='\0'; f2_file_buffer.get()[f2_size]='\0'; if(std::strcmp(f1_file_buffer.get(),f2_file_buffer.get())!=0){ std::cout<<"文件加密解密后的文件与原来的文件不一致"<<std::endl; exit(0); }else{ std::cout<<"文件加密解密通过!"<<std::endl; } }(plain_txt,decipher_txt); /// aes 与 des 的加密解密的速度的测试 均加密128位即16个byete的数据 std::cout<<std::endl; std::cout<<"******** ase & 3des ecb加密解密的速度的测试****** "<< std::endl; int enc_times =100000; //加密而次数s // 先测试 des { u_char des_bit_keys[64]; u_char des_sub_keys[16][48]; auto t1= std::chrono::system_clock::now(); for (int _time =0 ; _time < enc_times; _time++){ des::Char8ToBit64(key_block,des_bit_keys); des::DES_MakeSubKeys(des_bit_keys,des_sub_keys); _3_des::_3_DES_EncryptBlock(plain_block,key_block,key_block,key_block,cipher_block); _3_des::_3_DES_EncryptBlock(plain_block+8,key_block,key_block,key_block,cipher_block+8); //des的块是8个字节也就是64位的。。。 _3_des::_3_DES_DecryptBlock(cipher_block,key_block,key_block,key_block,plain_block); _3_des::_3_DES_DecryptBlock(cipher_block+8,key_block,key_block,key_block,plain_block+8); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } // 再测试aes { auto t1 =std::chrono::system_clock::now(); for(int _time = 0; _time<enc_times;_time++){ aes_test.Cipher(plain_block); memcpy(cipher_block,plain_block,16); aes_test.InvCipher(cipher_block); memcpy(plain_block,cipher_block,16); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } return 0; }
33.917241
123
0.603904
cxrasdfg
047fb2c64eae3736eec741f519400de9348f1f1f
960
cpp
C++
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; TreeNode* lastVisited(NULL); while (!st.empty() || root) { if (root) { st.push(root); root = root->left; } else { auto peek = st.top(); if (peek->right && lastVisited != peek->right) root = peek->right; else { res.push_back(peek->val); lastVisited = peek; st.pop(); } } } return res; } };
23.414634
82
0.402083
zszyellow
0481fc084fe09bf1a197622a2abe5288d0e392f8
1,659
hpp
C++
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #define KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #include "common/buffer.hpp" #include "storage/face/write_batch.hpp" #include "storage/trie/impl/polkadot_trie_db.hpp" namespace kagome::storage::trie { class PolkadotTrieBatch : public face::WriteBatch<common::Buffer, common::Buffer> { enum class Action { PUT, REMOVE }; struct Command { Action action; common::Buffer key{}; // value is unnecessary when action is REMOVE common::Buffer value{}; }; public: explicit PolkadotTrieBatch(PolkadotTrieDb &trie); ~PolkadotTrieBatch() override = default; // value will be copied outcome::result<void> put(const common::Buffer &key, const common::Buffer &value) override; outcome::result<void> put(const common::Buffer &key, common::Buffer &&value) override; outcome::result<void> remove(const common::Buffer &key) override; outcome::result<void> commit() override; void clear() override; bool is_empty() const; private: outcome::result<PolkadotTrieDb::NodePtr> applyPut(PolkadotTrie &trie, const common::Buffer &key, common::Buffer &&value); outcome::result<PolkadotTrieDb::NodePtr> applyRemove(PolkadotTrie &trie, const common::Buffer &key); PolkadotTrieDb &storage_; std::list<Command> commands_; }; } // namespace kagome::storage::trie #endif // KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP
30.163636
104
0.694394
Lederstrumpf
0483595ad4e4751bb81fe67379e81b88004ac9d7
17,761
cpp
C++
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
// Copyright (c) Glyn Matthews 2012, 2013, 2014. // Copyright 2012 Google, Inc. // 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 <gtest/gtest.h> #include <network/uri.hpp> #include "string_utility.hpp" TEST(builder_test, empty_uri_doesnt_throw) { network::uri_builder builder; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, empty_uri) { network::uri_builder builder; network::uri instance(builder); ASSERT_TRUE(instance.empty()); } TEST(builder_test, simple_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_uri) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, simple_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, simple_uri_has_no_user_info) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().user_info()); } TEST(builder_test, simple_uri_has_host) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, simple_uri_host_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, simple_uri_has_no_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().port()); } TEST(builder_test, simple_uri_has_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, simple_uri_path_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, simple_uri_has_no_query) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().query()); } TEST(builder_test, simple_uri_has_no_fragment) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().fragment()); } TEST(builder_test, simple_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_opaque_uri) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto:john.doe@example.com", builder.uri()); } TEST(builder_test, simple_opaque_uri_has_scheme) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_opaque_uri_scheme_value) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto", *builder.uri().scheme()); } TEST(builder_test, relative_hierarchical_uri_doesnt_throw) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_hierarchical_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_opaque_uri) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_EQ("john.doe@example.com", builder.uri()); } TEST(builder_test, full_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, full_uri) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http://user:password@www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, full_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, full_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, full_uri_has_user_info) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().user_info()); } TEST(builder_test, full_uri_user_info_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("user:password", *builder.uri().user_info()); } TEST(builder_test, full_uri_has_host) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, full_uri_host_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, full_uri_has_port) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().port()); } TEST(builder_test, full_uri_has_path) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, full_uri_path_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("/path", *builder.uri().path()); } TEST(builder_test, full_uri_has_query) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().query()); } TEST(builder_test, full_uri_query_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("query", *builder.uri().query()); } TEST(builder_test, full_uri_has_fragment) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().fragment()); } TEST(builder_test, full_uri_fragment_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, relative_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_uri_scheme) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().scheme()); } TEST(builder_test, authority) { network::uri_builder builder; builder .scheme("http") .authority("www.example.com:8080") .path("/") ; ASSERT_EQ("http://www.example.com:8080/", builder.uri()); ASSERT_EQ("www.example.com", *builder.uri().host()); ASSERT_EQ("8080", *builder.uri().port()); } TEST(builder_test, relative_uri_has_host) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, relative_uri_host_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, relative_uri_has_path) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, relative_uri_path_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, build_relative_uri_with_path_query_and_fragment) { network::uri_builder builder; builder .path("/path/") .query("key", "value") .fragment("fragment") ; ASSERT_EQ("/path/", *builder.uri().path()); ASSERT_EQ("key=value", *builder.uri().query()); ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, build_uri_with_capital_scheme) { network::uri_builder builder; builder .scheme("HTTP") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_capital_host) { network::uri_builder builder; builder .scheme("http") .host("WWW.EXAMPLE.COM") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_unencoded_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A path with spaces") ; ASSERT_EQ("http://www.example.com/A%20path%20with%20spaces", builder.uri()); } TEST(builder_test, DISABLED_builder_uri_and_remove_dot_segments_from_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A/./path/") ; ASSERT_EQ("http://www.example.com/A/path/", builder.uri()); } TEST(builder_test, build_uri_with_qmark_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/?/") ; ASSERT_EQ("http://www.example.com/%3F/", builder.uri()); } TEST(builder_test, build_uri_with_hash_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/#/") ; ASSERT_EQ("http://www.example.com/%23/", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("file:///path/to/a/file.html", builder.uri()); } TEST(builder_test, build_http_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("http://www.example.com/path/to/a/file.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path_with_encoded_chars) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file with spaces.html")) ; ASSERT_EQ("file:///path/to/a/file%20with%20spaces.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_with_encoded_unreserved_characters) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/%7Eglynos/") ; ASSERT_EQ("http://www.example.com/~glynos/", builder.uri()); } TEST(builder_test, simple_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .port(8000) .path("/") ; ASSERT_EQ("http://www.example.com:8000/", builder.uri()); } // This seems to work, but I don't want to add the Boost.System // dependency just for this. TEST(builder_test, build_uri_with_ipv4_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v4::loopback()) .path("/") ; ASSERT_EQ("http://127.0.0.1/", builder.uri()); } TEST(builder_test, build_uri_with_ipv6_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v6::loopback()) .path("/") ; ASSERT_EQ("http://[::1]/", builder.uri()); } TEST(builder_test, build_uri_with_query_item) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1", builder.uri()); } TEST(builder_test, build_uri_with_multiple_query_items) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .query("b", "2") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); } //TEST(builder_test, build_uri_with_multiple_query_items_with_int_values) { // network::uri_builder builder; // builder // .scheme("http") // .host("www.example.com") // .query("a", 1) // .query("b", 2) // .path("/") // ; // ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); //} TEST(builder_test, construct_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); builder.query("a", "1").query("b", "2").fragment("fragment"); ASSERT_EQ("http://www.example.com/?a=1&b=2#fragment", builder.uri()); } TEST(builder_test, authority_port_test) { network::uri_builder builder; builder .scheme("https") .authority("www.example.com") ; ASSERT_EQ("www.example.com", *builder.uri().authority()); } TEST(builder_test, clear_user_info_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_user_info(); ASSERT_EQ("http://www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, clear_port_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_port(); ASSERT_EQ("http://user:password@www.example.com/path?query#fragment", builder.uri()); } TEST(builder_test, clear_path_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_path(); ASSERT_EQ("http://user:password@www.example.com:80?query#fragment", builder.uri()); } TEST(builder_test, clear_query_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_query(); ASSERT_EQ("http://user:password@www.example.com:80/path#fragment", builder.uri()); } TEST(builder_test, clear_fragment_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_fragment(); ASSERT_EQ("http://user:password@www.example.com:80/path?query", builder.uri()); } TEST(builder_test, empty_username) { std::string user_info(":"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").user_info(user_info); ASSERT_EQ("ftp://:@127.0.0.1", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash) { std::string path("relative"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").path(path); ASSERT_EQ("ftp://127.0.0.1/relative", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash_2) { network::uri_builder builder; builder .scheme("ftp").host("127.0.0.1").path("noleadingslash/foo.txt"); ASSERT_EQ("/noleadingslash/foo.txt", *builder.uri().path()); }
23.776439
90
0.659422
chfast
04839dfd4e02508c8895013f0fcaf725a3d87a91
200
cpp
C++
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
5
2020-02-25T07:38:08.000Z
2021-06-22T16:15:03.000Z
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
null
null
null
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
2
2020-02-25T07:38:10.000Z
2020-04-26T06:02:14.000Z
#include <Rcpp.h> using namespace Rcpp; RcppExport SEXP rnorm_manual(SEXP n) { NumericVector out( as<int>(n) ); RNGScope rngScope; out = rnorm(as<int>(n), 0.0, 1.0); return out; }
15.384615
38
0.63
mfasiolo
04848621f09ec43b5e6fd5bfa67a27a3096fd2b9
2,807
hpp
C++
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
// Only for matrix with dimension 2, 4, 8, 16... #ifndef SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #define SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #include <utility> namespace CLRS { template <typename T, std::size_t n> void divide_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) b[i][j] = a[i][j]; for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = n / 2; j != n; ++j) c[i][j - n/2] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = 0; j != n / 2; ++j) d[i - n/2][j] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = n / 2; j != n; ++j) e[i - n/2][j - n/2] = a[i][j]; } template <typename T, std::size_t n> void combine_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) { a[i][j] = b[i][j]; a[i][j + n/2] = c[i][j]; a[i + n/2][j] = d[i][j]; a[i + n/2][j + n/2] = e[i][j]; } } template <typename T, std::size_t n> void add_matrix(T (&c)[n][n], T (&a)[n][n], T (&b)[n][n]) { for(std::size_t i = 0; i != n; ++i) for(std::size_t j = 0; j != n; ++j) c[i][j] = a[i][j] + b[i][j]; } template <typename T> void square_matrix_multiply_recursive(T (&a)[1][1], T (&b)[1][1], T (&c)[1][1]) // more specific function template for recursive base case when n equals 1. { c[0][0] = a[0][0] * b[0][0]; } template <typename T, std::size_t n> void square_matrix_multiply_recursive(T (&a)[n][n], T (&b)[n][n], T (&c)[n][n]) { T a00[n/2][n/2]; T a01[n/2][n/2]; T a10[n/2][n/2]; T a11[n/2][n/2]; divide_matrix_4(a, a00, a01, a10, a11); T b00[n/2][n/2]; T b01[n/2][n/2]; T b10[n/2][n/2]; T b11[n/2][n/2]; divide_matrix_4(b, b00, b01, b10, b11); T temp1[n/2][n/2]; T temp2[n/2][n/2]; square_matrix_multiply_recursive(a00, b00, temp1); square_matrix_multiply_recursive(a01, b10, temp2); T c00[n/2][n/2]; add_matrix(c00, temp1, temp2); square_matrix_multiply_recursive(a00, b01, temp1); square_matrix_multiply_recursive(a01, b11, temp2); T c01[n/2][n/2]; add_matrix(c01, temp1, temp2); square_matrix_multiply_recursive(a10, b00, temp1); square_matrix_multiply_recursive(a11, b10, temp2); T c10[n/2][n/2]; add_matrix(c10, temp1, temp2); square_matrix_multiply_recursive(a10, b01, temp1); square_matrix_multiply_recursive(a11, b11, temp2); T c11[n/2][n/2]; add_matrix(c11, temp1, temp2); combine_matrix_4(c, c00, c01, c10, c11); } } #endif
28.07
82
0.526541
zero4drift
0486ad6de881a87ab53291a8a8d2f8c110f20b2e
3,996
hpp
C++
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
1
2021-11-29T21:41:10.000Z
2021-11-29T21:41:10.000Z
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
#ifndef TOOLS_HPP # define TOOLS_HPP # include <string> # include <vector> # include "client.hpp" # include <list> # include "ircserv.hpp" typedef std::vector<std::string> t_strvect; typedef std::list<Client>::iterator t_citer; /****************************************************/ /* additional tools helping the server (tools.cpp) */ /****************************************************/ t_citer ft_findclientfd(t_citer const &begin, t_citer const &end, int fd); t_citer ft_findnick(t_citer const &begin, t_citer const &end, std::string const &nick); t_server *find_server_by_fd(int fd, IRCserv *serv); Client *find_client_by_nick(std::string const &nick, IRCserv *serv); Client *find_client_by_fd(int fd, IRCserv *serv); Channel *find_channel_by_name(const std::string &name, IRCserv *serv); t_server *find_server_by_mask(std::string const &mask, IRCserv *serv); t_server *find_server_by_name(std::string const &name, IRCserv *serv); Client *find_client_by_user_or_nick_and_host(std::string const &str, IRCserv *serv); Client *find_client_by_info(std::string const &info, IRCserv *serv); t_server *find_server_by_token(std::string const &token, IRCserv *serv); t_service *find_service_by_name(std::string const &name, IRCserv *serv); t_service *find_service_by_fd(int fd, IRCserv *serv); std::string get_servername_by_mask(std::string const &mask, IRCserv *serv); std::string get_servername_by_token(std::string const &token, IRCserv *serv); std::string get_hopcount_by_token(std::string const &token, IRCserv *serv); std::string ft_buildmsg(std::string const &from, std::string const &msgcode, std::string const &to, std::string const &cmd, std::string const &msg); void addtonickhistory(IRCserv *serv, t_citer const client); int nick_forward(IRCserv *serv, Client *client); bool remove_channel(Channel *channel, IRCserv *serv); bool remove_client_by_ptr(Client *ptr, IRCserv *serv); bool remove_client_by_nick(std::string const &nick, IRCserv *serv); void remove_server_by_name(std::string const &servername, IRCserv *serv); void self_cmd_squit(int fd, t_fd &fdref, IRCserv *serv); void self_cmd_quit(int fd, t_fd &fdref, IRCserv *serv, std::string const &reason); void self_service_quit(int fd, t_fd &fdref, IRCserv *serv); /****************************************************/ /* string manipulation functions (stringtools.cpp) */ /****************************************************/ t_strvect ft_splitstring(std::string msg, std::string const &delim); t_strvect ft_splitstring(std::string str, char delim); t_strvect ft_splitstringbyany(std::string msg, std::string const &delim); /** * ft_splitcmdbyspace * splits until the second occurance of ':' symbol * (special for irc msg format) */ t_strvect ft_splitcmdbyspace(std::string msg); std::string strvect_to_string(const t_strvect &split, char delim = ' ', size_t pos = 0, size_t len = std::string::npos); bool match(const char *s1, const char *s2); bool match(std::string const &s1, std::string const &s2); std::string ft_strtoupper(std::string const &str); std::string ft_strtolower(std::string const &str); std::string get_nick_from_info(std::string const &info); std::string get_mask_reply(Channel *channel, Client *client, std::string mode, IRCserv *serv); bool is_valid_mask(std::string mask); bool is_valid_serv_host_mask(std::string mask); // ft_tostring std::string ft_tostring(int val); std::string ft_tostring(long val); std::string ft_tostring(uint val); std::string ft_tostring(ulong val); // ft_sto* int ft_stoi(std::string const &str); long ft_stol(std::string const &str); uint ft_stou(std::string const &str); ulong ft_stoul(std::string const &str); /****************************************************/ /* time related functions (timetools.cpp) */ /****************************************************/ time_t ft_getcompiletime(void); time_t ft_getcurrenttime(void); std::string ft_timetostring(time_t rawtime); #endif
44.4
94
0.689189
Antip003
0496310fb225f7616890d7c45f263ff8ff9a1313
2,205
cpp
C++
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
// Yule Zhang #include <iostream> #include <fstream> using namespace std; #include "queue_eda.h" template <typename T> class listaPlus : public queue<T> { using Nodo = typename queue<T>::Nodo; public: void mezclar(listaPlus<T> & l1, listaPlus<T> & l2) { if (l1.nelems == 0) {//Si l1 es vacia this->prim = l2.prim; this->ult = l2.ult; } else if (l2.nelems == 0) {//Si l2 es vacia this->prim = l1.prim; this->ult = l1.ult; } else {//Si ni l1 ni l2 son vacias Nodo* nodo1 = l1.prim; Nodo* nodo2 = l2.prim; if (nodo1->elem <= nodo2->elem) { this->prim = nodo1; nodo1 = nodo1->sig; } else { this->prim = nodo2; nodo2 = nodo2->sig; } Nodo* nodo = this->prim; while (nodo1 != nullptr && nodo2 != nullptr) { if (nodo1->elem <= nodo2->elem) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } else { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } while (nodo1 != nullptr) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } while (nodo2 != nullptr) { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } this->nelems = l1.nelems + l2.nelems; l1.prim = l1.ult = nullptr; l2.prim = l2.ult = nullptr; l1.nelems = l2.nelems = 0; } void print() const { Nodo* aux = this->prim; while (aux != nullptr) { cout << aux->elem << ' '; aux = aux->sig; } cout << endl; } }; void resuelveCaso() { int n; cin >> n;//Leer datos de entrada listaPlus<int> l1;//Primera lista listaPlus<int> l2;//Segunda lista while (n != 0) { l1.push(n); cin >> n; } int m; cin >> m; while (m != 0) { l2.push(m); cin >> m; } listaPlus<int> l;//Lista final l.mezclar(l1, l2); l.print(); } int main() { // ajustes para que cin extraiga directamente de un fichero #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // para dejar todo como estaba al principio #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
18.22314
61
0.569161
Yule1223
0496a3661681dbbbe22c4edf4d044121fb63df10
4,217
hpp
C++
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
9
2020-07-27T12:03:38.000Z
2021-11-01T09:26:31.000Z
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
null
null
null
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
8
2020-08-20T02:56:56.000Z
2022-03-06T12:09:35.000Z
#ifndef RAYTRACING_MATERIAL_H #define RAYTRACING_MATERIAL_H #include "Vector.hpp" enum class MaterialType { DIFFUSE }; class Material { private: // Compute reflection direction Vector3f reflect(const Vector3f &I, const Vector3f &N) const { return I - 2 * I.dot(N) * N; } // Compute refraction direction using Snell's law // // We need to handle with care the two possible situations: // // - When the ray is inside the object // // - When the ray is outside. // // If the ray is outside, you need to make cosi positive cosi = -N.I // // If the ray is inside, you need to invert the refractive indices and negate the normal N Vector3f refract(const Vector3f &I, const Vector3f &N, const float &ior) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; Vector3f n = N; if (cosi < 0) { cosi = -cosi; } else { std::swap(etai, etat); n = -N; } float eta = etai / etat; float k = 1 - eta * eta * (1 - cosi * cosi); return k < 0 ? 0 : eta * I + (eta * cosi - sqrt(k)) * n; } // Compute Fresnel equation // // \param I is the incident view direction // // \param N is the normal at the intersection point // // \param ior is the material refractive index // // \param[out] kr is the amount of light reflected void fresnel(const Vector3f &I, const Vector3f &N, const float &ior, float &kr) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; if (cosi > 0) { std::swap(etai, etat); } // Compute sini using Snell's law float sint = etai / etat * sqrtf(std::max(0.f, 1 - cosi * cosi)); // Total internal reflection if (sint >= 1) { kr = 1; } else { float cost = sqrtf(std::max(0.f, 1 - sint * sint)); cosi = fabsf(cosi); float Rs = ((etat * cosi) - (etai * cost)) / ((etat * cosi) + (etai * cost)); float Rp = ((etai * cosi) - (etat * cost)) / ((etai * cosi) + (etat * cost)); kr = (Rs * Rs + Rp * Rp) / 2; } // As a consequence of the conservation of energy, transmittance is given by: // kt = 1 - kr; } Vector3f toWorld(const Vector3f &a, const Vector3f &N) { Vector3f B, C; if (std::fabs(N.x) > std::fabs(N.y)) { float invLen = 1.0f / std::sqrt(N.x * N.x + N.z * N.z); C = Vector3f(N.z * invLen, 0.0f, -N.x * invLen); } else { float invLen = 1.0f / std::sqrt(N.y * N.y + N.z * N.z); C = Vector3f(0.0f, N.z * invLen, -N.y * invLen); } B = C.cross(N); return a.x * B + a.y * C + a.z * N; } public: MaterialType m_type; Vector3f emit; float ior; Vector3f Kd, Ks; float specularExponent; //Texture tex; Material(MaterialType t = MaterialType::DIFFUSE, Vector3f e = Vector3f(0, 0, 0)) { m_type = t; emit = e; } inline bool hasEmit() { return emit.length() > EPSILON ? true : false; } // sample a ray by Material properties inline Vector3f sample(const Vector3f &wi, const Vector3f &N); // given a ray, calculate the PdF of this ray inline float pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); // given a ray, calculate the contribution of this ray inline Vector3f eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); }; Vector3f Material::sample(const Vector3f &wi, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample on the hemisphere float x_1 = get_random_float(), x_2 = get_random_float(); float z = std::fabs(1.0f - 2.0f * x_1); float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2; Vector3f localRay(r * std::cos(phi), r * std::sin(phi), z); return toWorld(localRay, N); break; } } } float Material::pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample probability 1 / (2 * PI) if (wo.dot(N) > 0.0f) return 0.5f / M_PI; else return 0.0f; break; } } } Vector3f Material::eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // calculate the contribution of diffuse model float cosalpha = wo.dot(N); if (cosalpha > 0.0f) { Vector3f diffuse = Kd / M_PI; return diffuse; } else return Vector3f(0.0f); break; } } } #endif //RAYTRACING_MATERIAL_H
24.805882
91
0.626749
fuzhanzhan
0496d38d5ca036a3d9eb921750231320620b7f96
1,726
hpp
C++
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2022-02-15T02:58:58.000Z
2022-02-15T02:58:58.000Z
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
null
null
null
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2021-12-19T13:25:43.000Z
2021-12-19T13:25:43.000Z
/// \file /// \brief Internal header file that contains implementation of the position /// class. /// \author Lyberta /// \copyright BSLv1. #pragma once namespace std::io { constexpr position::position(streamoff off) noexcept : m_position{off} { } constexpr position::position(offset off) noexcept : m_position{off.value()} { } constexpr streamoff position::value() const noexcept { return m_position; } constexpr position& position::operator++() noexcept { ++m_position; return *this; } constexpr position position::operator++(int) noexcept { position temp{*this}; ++(*this); return temp; } constexpr position& position::operator--() noexcept { --m_position; return *this; } constexpr position position::operator--(int) noexcept { position temp{*this}; --(*this); return temp; } constexpr position& position::operator+=(offset rhs) noexcept { m_position += rhs.value(); return *this; } constexpr position& position::operator-=(offset rhs) noexcept { m_position -= rhs.value(); return *this; } constexpr position position::max() noexcept { return position{numeric_limits<streamoff>::max()}; } constexpr bool operator==(position lhs, position rhs) noexcept { return lhs.value() == rhs.value(); } constexpr strong_ordering operator<=>(position lhs, position rhs) noexcept { return lhs.value() <=> rhs.value(); } constexpr position operator+(position lhs, offset rhs) noexcept { return lhs += rhs; } constexpr position operator+(offset lhs, position rhs) noexcept { return rhs += lhs; } constexpr position operator-(position lhs, offset rhs) noexcept { return lhs -= rhs; } constexpr offset operator-(position lhs, position rhs) noexcept { return offset{lhs.value() - rhs.value()}; } }
17.089109
76
0.715527
YarikTH
0496d52dffcf4e9d830b241efcac8cc3b80f8d64
3,271
hh
C++
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/inst/null_collection_type_manager.hh" Template class for instance_collection's type manager. $Id: null_collection_type_manager.hh,v 1.12 2007/04/15 05:52:19 fang Exp $ */ #ifndef __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #define __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #include <iosfwd> #include "Object/type/canonical_type_fwd.hh" // just for conditional #include "util/persistent_fwd.hh" #include "util/boolean_types.hh" #include "util/memory/pointer_classes_fwd.hh" namespace HAC { namespace entity { class const_param_expr_list; using std::istream; using std::ostream; using util::good_bool; using util::bad_bool; using util::persistent_object_manager; using util::memory::count_ptr; class footprint; template <class> struct class_traits; //============================================================================= /** Appropriate for built-in types with no template parameters. Pretty much only useful to bool. TODO: write a quick raw-type comparison without having to construct canonical type. */ template <class Tag> class null_collection_type_manager { private: typedef null_collection_type_manager<Tag> this_type; typedef class_traits<Tag> traits_type; protected: typedef typename traits_type::instance_collection_generic_type instance_collection_generic_type; typedef typename traits_type::instance_collection_parameter_type instance_collection_parameter_type; typedef typename traits_type::type_ref_ptr_type type_ref_ptr_type; typedef typename traits_type::resolved_type_ref_type resolved_type_ref_type; // has no type parameter struct dumper; void collect_transient_info_base(persistent_object_manager&) const { } void write_object_base(const persistent_object_manager&, ostream&) const { } void load_object_base(const persistent_object_manager&, istream&) { } public: // distinguish internal type from canonical_type /** Only used internally with collections. */ instance_collection_parameter_type __get_raw_type(void) const { return instance_collection_parameter_type(); } resolved_type_ref_type get_resolved_canonical_type(void) const; good_bool complete_type_definition_footprint( const count_ptr<const const_param_expr_list>&) const { return good_bool(true); } bool is_complete_type(void) const { return true; } bool is_relaxed_type(void) const { return false; } // bool doesn't have a footprint static good_bool create_definition_footprint( const instance_collection_parameter_type&, const footprint& /* top */) { return good_bool(true); } protected: bool must_be_collectibly_type_equivalent(const this_type&) const { return true; } bad_bool check_type(const instance_collection_parameter_type&) const { return bad_bool(false); } /** \param t type must be resolved constant. \pre first time called for the collection. */ good_bool commit_type_first_time( const instance_collection_parameter_type&) const { return good_bool(true); } }; // end struct null_collection_type_manager //============================================================================= } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__
25.960317
79
0.751758
broken-wheel
0498d8a8dc6e8deff8fcd2f26aff14da0ddabebe
1,447
cc
C++
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
/** * Copyright 2017 M. Shulhan (ms@kilabit.info). All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "DNSRecordType.hh" namespace vos { const char* DNSRecordType::__cname = "DNSRecordType"; const int DNSRecordType::SIZE = 22; const char* DNSRecordType::NAMES[DNSRecordType::SIZE] = { "A" ,"NS" ,"MD" ,"MF", "CNAME" , "SOA" ,"MB" ,"MG" ,"MR", "NULL" , "WKS" ,"PTR" ,"HINFO","MINFO","MX" , "TXT" ,"AAAA" ,"SRV" ,"AXFR" ,"MAILB" , "MAILA" ,"*" }; const int DNSRecordType::VALUES[DNSRecordType::SIZE] = { 1 ,2 ,3 ,4 ,5 , 6 ,7 ,8 ,9 ,10 , 11 ,12 ,13 ,14 ,15 , 16 ,28 ,33 ,252 ,253 , 254 ,255 }; DNSRecordType::DNSRecordType() : Object() {} DNSRecordType::~DNSRecordType() {} /** * `GET_NAME()` will search list of record type with value is `type` and * return their NAME representation. * * It will return NULL if no match found. */ const char* DNSRecordType::GET_NAME(const int type) { int x = 0; for (; x < SIZE; x++) { if (VALUES[x] == type) { return NAMES[x]; } } return NULL; } /** * `GET_VALUE()` will search list of record type that match with `name` and * return their TYPE representation. * * It will return -1 if no match found. */ int DNSRecordType::GET_VALUE(const char* name) { int x = 0; for (; x < SIZE; x++) { if (strcasecmp(NAMES[x], name) == 0) { return VALUES[x]; } } return -1; } }
19.039474
75
0.615757
shuLhan
049949e220d8f31825a76a600514a0de3d2b3cdd
10,584
cpp
C++
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
2
2021-07-17T13:34:20.000Z
2022-01-09T00:55:51.000Z
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
null
null
null
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
1
2018-11-18T08:32:40.000Z
2018-11-18T08:32:40.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "nsal.h" #include "xtitle_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN template<typename T> void add_endpoint_helper( _In_ std::vector<T>& endpoints, _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { // First check if there's already a match nsal_endpoint_info newInfo(relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_same(protocol, hostName, port)) { nsal_endpoint_info existingInfo; if (endpoint->get_info_for_exact_path(path, existingInfo)) { // The endpoint already exists, make sure all the info about it matches if (existingInfo == newInfo) { return; } else { throw std::runtime_error("endpoints conflict"); } } else { // The specific path does not exist so add it endpoint->add_info(path, newInfo); return; } } } // No matching endpoints so we create a new one. endpoints.emplace_back(protocol, hostName, hostNameType, port); endpoints.back().add_info(path, newInfo); } void nsal::add_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { switch (hostNameType) { case nsal_host_name_type::fqdn: add_endpoint_helper<fqdn_nsal_endpoint>( m_fqdnEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::wildcard: add_endpoint_helper<wildcard_nsal_endpoint>( m_wildcardEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::ip: add_endpoint_helper<ip_nsal_endpoint>( m_ipEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::cidr: add_endpoint_helper<cidr_nsal_endpoint>( m_cidrEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; default: throw std::runtime_error("unsupported host name type"); } } template<typename TEndpoint, typename THostName> bool get_helper( _In_ const std::vector<TEndpoint>& endpoints, _In_ nsal_protocol protocol, _In_ const THostName& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) { for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_match(protocol, hostName, port)) { return endpoint->get_info(path, info); } } return false; } bool nsal::get_endpoint( _In_ web::http::uri& uri, _Out_ nsal_endpoint_info& info) const { nsal_protocol protocol = nsal::deserialize_protocol(uri.scheme()); int port = nsal::get_port(protocol, uri.port()); return get_endpoint(protocol, uri.host(), port, uri.path(), info); } bool nsal::get_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) const { string_t hostNameWithoutEnv = hostName; string_t dnet = _T(".dnet"); size_t f = hostNameWithoutEnv.find(dnet); if ( f != string_t::npos ) { hostNameWithoutEnv.replace(f, dnet.length(), _T("")); } ip_address ipAddr; if (ip_address::try_parse(hostNameWithoutEnv, ipAddr)) { if (get_helper(m_ipEndpoints, protocol, ipAddr, port, path, info)) { return true; } if (get_helper(m_cidrEndpoints, protocol, ipAddr, port, path, info)) { return true; } } else { if (get_helper(m_fqdnEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } if (get_helper(m_wildcardEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } } return false; } void nsal::add_signature_policy(_In_ const signature_policy& signaturePolicy) { m_signaturePolicies.push_back(signaturePolicy); } const signature_policy& nsal::get_signature_policy(_In_ int index) const { return m_signaturePolicies[index]; } nsal_protocol nsal::deserialize_protocol(_In_ const utility::string_t& str) { if (_T("https") == str) return nsal_protocol::https; if (_T("http") == str) return nsal_protocol::http; if (_T("tcp") == str) return nsal_protocol::tcp; if (_T("udp") == str) return nsal_protocol::udp; if (_T("wss") == str) return nsal_protocol::wss; throw web::json::json_exception(_T("Invalid protocol for NSAL endpoint")); } nsal_host_name_type nsal::deserialize_host_name_type(_In_ const utility::string_t& str) { if (_T("fqdn") == str) return nsal_host_name_type::fqdn; if (_T("wildcard") == str) return nsal_host_name_type::wildcard; if (_T("ip") == str) return nsal_host_name_type::ip; if (_T("cidr") == str) return nsal_host_name_type::cidr; throw web::json::json_exception(_T("Invalid NSAL host name type")); } int nsal::deserialize_port(_In_ nsal_protocol protocol, _In_ const web::json::value& json) { int port = utils::extract_json_int(json, _T("Port"), false, 0); return nsal::get_port(protocol, port); } int nsal::get_port( _In_ nsal_protocol protocol, _In_ int port ) { if (port == 0) { switch (protocol) { case nsal_protocol::https: return 443; case nsal_protocol::http: case nsal_protocol::wss: return 80; default: throw web::json::json_exception(_T("Must specify port when protocol is not http or https")); } } return port; } void nsal::deserialize_endpoint( _In_ nsal& nsal, _In_ const web::json::value& endpoint) { utility::string_t relyingParty(utils::extract_json_string(endpoint, _T("RelyingParty"))); if (relyingParty.empty()) { // If there's no RP, we don't care since there's no token to attach return; } utility::string_t subRelyingParty(utils::extract_json_string(endpoint, _T("SubRelyingParty"))); nsal_protocol protocol(nsal::deserialize_protocol(utils::extract_json_string(endpoint, _T("Protocol"), true))); nsal_host_name_type hostNameType(deserialize_host_name_type(utils::extract_json_string(endpoint, _T("HostType"), true))); int port = deserialize_port(protocol, endpoint); nsal.add_endpoint( protocol, utils::extract_json_string(endpoint, _T("Host"), true), hostNameType, port, utils::extract_json_string(endpoint, _T("Path")), relyingParty, subRelyingParty, utils::extract_json_string(endpoint, _T("TokenType"), true), utils::extract_json_int(endpoint, _T("SignaturePolicyIndex"), false, -1)); } void nsal::deserialize_signature_policy(_In_ nsal& nsal, _In_ const web::json::value& json) { std::error_code errc = xbox_live_error_code::no_error; int version = utils::extract_json_int(json, _T("Version"), true); int maxBodyBytes = utils::extract_json_int(json, _T("MaxBodyBytes"), true); std::vector<string_t> extraHeaders( utils::extract_json_vector<string_t>(utils::json_string_extractor, json, _T("ExtraHeaders"), errc, false)); nsal.add_signature_policy(signature_policy(version, maxBodyBytes, extraHeaders)); } nsal nsal::deserialize(_In_ const web::json::value& json) { nsal nsal; auto& jsonObj(json.as_object()); auto it = jsonObj.find(_T("SignaturePolicies")); if (it != jsonObj.end()) { web::json::array signaturePolicies(it->second.as_array()); for (auto it2 = signaturePolicies.begin(); it2 != signaturePolicies.end(); ++it2) { deserialize_signature_policy(nsal, *it2); } } it = jsonObj.find(_T("EndPoints")); if (it != jsonObj.end()) { web::json::array endpoints(it->second.as_array()); for (auto it2 = endpoints.begin(); it2 != endpoints.end(); ++it2) { deserialize_endpoint(nsal, *it2); } } nsal.add_endpoint( nsal_protocol::wss, _T("*.xboxlive.com"), nsal_host_name_type::wildcard, 80, string_t(), _T("http://xboxlive.com"), string_t(), _T("JWT"), 0 ); nsal._Sort_wildcard_endpoints(); return nsal; } void nsal::_Sort_wildcard_endpoints() { std::sort( m_wildcardEndpoints.begin(), m_wildcardEndpoints.end(), [](_In_ const wildcard_nsal_endpoint& lhs, _In_ const wildcard_nsal_endpoint& rhs) -> bool { return lhs.length() > rhs.length(); }); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END
29.157025
125
0.616875
blgrossMS
049c7c6bf5fa81b209230f55f8236cdcf3fd46e6
13,043
cpp
C++
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
28
2015-04-09T04:17:29.000Z
2019-05-28T11:59:22.000Z
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
2
2017-03-23T11:44:57.000Z
2017-12-09T04:02:54.000Z
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
17
2015-01-20T08:37:00.000Z
2019-02-04T02:55:30.000Z
/* -*-C-*- ******************************************************************************** * * File: seam.c (Formerly seam.c) * Description: * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri May 17 16:30:13 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "seam.h" #include "callcpp.h" #include "structures.h" #include "makechop.h" #ifdef __UNIX__ #include <assert.h> #endif /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ #define NUM_STARTING_SEAMS 20 #define SEAMBLOCK 100 /* Cells per block */ makestructure (newseam, free_seam, printseam, SEAM, freeseam, SEAMBLOCK, "SEAM", seamcount); /*---------------------------------------------------------------------- Public Function Code ----------------------------------------------------------------------*/ /** * @name point_in_split * * Check to see if either of these points are present in the current * split. * @returns TRUE if one of them is split. */ bool point_in_split(SPLIT *split, EDGEPT *point1, EDGEPT *point2) { return ((split) ? ((exact_point (split->point1, point1) || exact_point (split->point1, point2) || exact_point (split->point2, point1) || exact_point (split->point2, point2)) ? TRUE : FALSE) : FALSE); } /** * @name point_in_seam * * Check to see if either of these points are present in the current * seam. * @returns TRUE if one of them is. */ bool point_in_seam(SEAM *seam, SPLIT *split) { return (point_in_split (seam->split1, split->point1, split->point2) || point_in_split (seam->split2, split->point1, split->point2) || point_in_split (seam->split3, split->point1, split->point2)); } /** * @name add_seam * * Add another seam to a collection of seams. */ SEAMS add_seam(SEAMS seam_list, SEAM *seam) { return (array_push (seam_list, seam)); } /** * @name combine_seam * * Combine two seam records into a single seam. Move the split * references from the second seam to the first one. The argument * convention is patterned after strcpy. */ void combine_seams(SEAM *dest_seam, SEAM *source_seam) { dest_seam->priority += source_seam->priority; dest_seam->location += source_seam->location; dest_seam->location /= 2; if (source_seam->split1) { if (!dest_seam->split1) dest_seam->split1 = source_seam->split1; else if (!dest_seam->split2) dest_seam->split2 = source_seam->split1; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split1; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split2) { if (!dest_seam->split2) dest_seam->split2 = source_seam->split2; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split2; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split3) { if (!dest_seam->split3) dest_seam->split3 = source_seam->split3; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } free_seam(source_seam); } /** * @name delete_seam * * Free this seam record and the splits that are attached to it. */ void delete_seam(void *arg) { //SEAM *seam) SEAM *seam = (SEAM *) arg; if (seam) { if (seam->split1) delete_split (seam->split1); if (seam->split2) delete_split (seam->split2); if (seam->split3) delete_split (seam->split3); free_seam(seam); } } /** * @name free_seam_list * * Free all the seams that have been allocated in this list. Reclaim * the memory for each of the splits as well. */ void free_seam_list(SEAMS seam_list) { int x; array_loop (seam_list, x) delete_seam (array_value (seam_list, x)); array_free(seam_list); } /** * @name test_insert_seam * * @returns true if insert_seam will succeed. */ bool test_insert_seam(SEAMS seam_list, int index, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp < index && test_seam->widthp + test_index == index - 1 && account_splits_right(test_seam, blob) < 0) return false; } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn >= index && test_index - test_seam->widthn == index && account_splits_left(test_seam, first_blob, blob) < 0) return false; } return true; } /** * @name insert_seam * * Add another seam to a collection of seams at a particular location * in the seam array. */ SEAMS insert_seam(SEAMS seam_list, int index, SEAM *seam, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp >= index) { test_seam->widthp++; /*got in the way */ } else if (test_seam->widthp + test_index == index - 1) { test_seam->widthp = account_splits_right(test_seam, blob); if (test_seam->widthp < 0) { cprintf ("Failed to find any right blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn < index) { test_seam->widthn++; /*got in the way */ } else if (test_index - test_seam->widthn == index) { test_seam->widthn = account_splits_left(test_seam, first_blob, blob); if (test_seam->widthn < 0) { cprintf ("Failed to find any left blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } return (array_insert (seam_list, index, seam)); } /** * @name account_splits_right * * Account for all the splits by looking to the right. * in the blob list. */ int account_splits_right(SEAM *seam, TBLOB *blob) { inT8 found_em[3]; inT8 width; found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; if (found_em[0] && found_em[1] && found_em[2]) return 0; width = 0; do { if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (found_em[0] && found_em[1] && found_em[2]) { return width; } width++; blob = blob->next; } while (blob != NULL); return -1; } /** * @name account_splits_left * * Account for all the splits by looking to the left. * in the blob list. */ int account_splits_left(SEAM *seam, TBLOB *blob, TBLOB *end_blob) { static inT32 depth = 0; static inT8 width; static inT8 found_em[3]; if (blob != end_blob) { depth++; account_splits_left (seam, blob->next, end_blob); depth--; } else { found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; width = 0; } if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (!found_em[0] || !found_em[1] || !found_em[2]) { width++; if (depth == 0) { width = -1; } } return width; } /** * @name find_split_in_blob * * @returns TRUE if the split is somewhere in this blob. */ bool find_split_in_blob(SPLIT *split, TBLOB *blob) { TESSLINE *outline; #if 0 for (outline = blob->outlines; outline != NULL; outline = outline->next) if (is_split_outline (outline, split)) return TRUE; return FALSE; #endif for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point1, outline)) break; if (outline == NULL) return FALSE; for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point2, outline)) return TRUE; return FALSE; } /** * @name join_two_seams * * Merge these two seams into a new seam. Duplicate the split records * in both of the input seams. Return the resultant seam. */ SEAM *join_two_seams(SEAM *seam1, SEAM *seam2) { SEAM *result = NULL; SEAM *temp; assert(seam1 &&seam2); if (((seam1->split3 == NULL && seam2->split2 == NULL) || (seam1->split2 == NULL && seam2->split3 == NULL) || seam1->split1 == NULL || seam2->split1 == NULL) && (!shared_split_points (seam1, seam2))) { clone_seam(result, seam1); clone_seam(temp, seam2); combine_seams(result, temp); } return (result); } /** * @name new_seam * * Create a structure for a "seam" between two blobs. This data * structure may actually hold up to three different splits. * Initailization of this record is done by this routine. */ SEAM *new_seam(PRIORITY priority, int x_location, SPLIT *split1, SPLIT *split2, SPLIT *split3) { SEAM *seam; seam = newseam (); seam->priority = priority; seam->location = x_location; seam->widthp = 0; seam->widthn = 0; seam->split1 = split1; seam->split2 = split2; seam->split3 = split3; return (seam); } /** * @name new_seam_list * * Create a collection of seam records in an array. */ SEAMS new_seam_list() { return (array_new (NUM_STARTING_SEAMS)); } /** * @name print_seam * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seam(const char *label, SEAM *seam) { if (seam) { cprintf(label); cprintf (" %6.2f @ %5d, p=%d, n=%d ", seam->priority, seam->location, seam->widthp, seam->widthn); print_split (seam->split1); if (seam->split2) { cprintf (", "); print_split (seam->split2); if (seam->split3) { cprintf (", "); print_split (seam->split3); } } cprintf ("\n"); } } /** * @name print_seams * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seams(const char *label, SEAMS seams) { int x; char number[CHARS_PER_LINE]; if (seams) { cprintf ("%s\n", label); array_loop(seams, x) { sprintf (number, "%2d: ", x); print_seam (number, (SEAM *) array_value (seams, x)); } cprintf ("\n"); } } /** * @name shared_split_points * * Check these two seams to make sure that neither of them have two * points in common. Return TRUE if any of the same points are present * in any of the splits of both seams. */ int shared_split_points(SEAM *seam1, SEAM *seam2) { if (seam1 == NULL || seam2 == NULL) return (FALSE); if (seam2->split1 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split1)) return (TRUE); if (seam2->split2 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split2)) return (TRUE); if (seam2->split3 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split3)) return (TRUE); return (FALSE); }
26.892784
83
0.602162
danauclair
04a2bea699c47c2db9a3cd4905a84798ec55ef08
9,011
hh
C++
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
1
2021-02-07T01:57:32.000Z
2021-02-07T01:57:32.000Z
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-01-25 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <mutex> #include <string> #include <unordered_map> #include <maxscale/config_common.hh> #include <maxscale/ssl.hh> #include <maxscale/target.hh> /** * Server configuration parameters names */ extern const char CN_MONITORPW[]; extern const char CN_MONITORUSER[]; extern const char CN_PERSISTMAXTIME[]; extern const char CN_PERSISTPOOLMAX[]; extern const char CN_PROXY_PROTOCOL[]; /** * The SERVER structure defines a backend server. Each server has a name * or IP address for the server, a port that the server listens on and * the name of a protocol module that is loaded to implement the protocol * between the gateway and the server. */ class SERVER : public mxs::Target { public: /** * Stores server version info. Encodes/decodes to/from the version number received from the server. * Also stores the version string and parses information from it. Assumed to rarely change, so reads * are not synchronized. */ class VersionInfo { public: enum class Type { UNKNOWN, /**< Not connected yet */ MYSQL, /**< MySQL 5.5 or later. */ MARIADB, /**< MariaDB 5.5 or later */ XPAND, /**< Xpand node */ BLR /**< Binlog router */ }; struct Version { uint64_t total {0}; /**< Total version number received from server */ uint32_t major {0}; /**< Major version */ uint32_t minor {0}; /**< Minor version */ uint32_t patch {0}; /**< Patch version */ }; /** * Reads in version data. Deduces server type from version string. * * @param version_num Version number from server * @param version_string Version string from server */ void set(uint64_t version_num, const std::string& version_string); /** * Return true if the server is a real database and can process queries. Returns false if server * type is unknown or if the server is a binlogrouter. * * @return True if server is a real database */ bool is_database() const; Type type() const; const Version& version_num() const; const char* version_string() const; private: static const int MAX_VERSION_LEN = 256; mutable std::mutex m_lock; /**< Protects against concurrent writing */ Version m_version_num; /**< Numeric version */ Type m_type {Type::UNKNOWN}; /**< Server type */ char m_version_str[MAX_VERSION_LEN + 1] {'\0'}; /**< Server version string */ }; struct PoolStats { int n_persistent = 0; /**< Current persistent pool */ uint64_t n_new_conn = 0; /**< Times the current pool was empty */ uint64_t n_from_pool = 0; /**< Times when a connection was available from the pool */ int persistmax = 0; /**< Maximum pool size actually achieved since startup */ }; /** * Find a server with the specified name. * * @param name Name of the server * @return The server or NULL if not found */ static SERVER* find_by_unique_name(const std::string& name); /** * Find several servers with the names specified in an array. The returned array is equal in size * to the server_names-array. If any server name was not found, then the corresponding element * will be NULL. * * @param server_names An array of server names * @return Array of servers */ static std::vector<SERVER*> server_find_by_unique_names(const std::vector<std::string>& server_names); virtual ~SERVER() = default; /** * Get server address */ virtual const char* address() const = 0; /** * Get server port */ virtual int port() const = 0; /** * Get server extra port */ virtual int extra_port() const = 0; /** * Is proxy protocol in use? */ virtual bool proxy_protocol() const = 0; /** * Set proxy protocol * * @param proxy_protocol Whether proxy protocol is used */ virtual void set_proxy_protocol(bool proxy_protocol) = 0; /** * Get server character set * * @return The numeric character set or 0 if no character set has been read */ virtual uint8_t charset() const = 0; /** * Set server character set * * @param charset Character set to set */ virtual void set_charset(uint8_t charset) = 0; /** * Connection pool statistics * * @return A reference to the pool statistics object */ virtual PoolStats& pool_stats() = 0; /** * Check if server has disk space threshold settings. * * @return True if limits exist */ virtual bool have_disk_space_limits() const = 0; /** * Get a copy of disk space limit settings. * * @return A copy of settings */ virtual DiskSpaceLimits get_disk_space_limits() const = 0; /** * Is persistent connection pool enabled. * * @return True if enabled */ virtual bool persistent_conns_enabled() const = 0; /** * Update server version. * * @param version_num New numeric version * @param version_str New version string */ virtual void set_version(uint64_t version_num, const std::string& version_str) = 0; /** * Get version information. The contents of the referenced object may change at any time, * although in practice this is rare. * * @return Version information */ virtual const VersionInfo& info() const = 0; /** * Update server address. * * @param address The new address */ virtual bool set_address(const std::string& address) = 0; /** * Update the server port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_port(int new_port) = 0; /** * Update the server extra port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_extra_port(int new_port) = 0; /** * @brief Check if a server points to a local MaxScale service * * @return True if the server points to a local MaxScale service */ virtual bool is_mxs_service() const = 0; /** * Set current ping * * @param ping Ping in milliseconds */ virtual void set_ping(int64_t ping) = 0; /** * Set replication lag * * @param lag The current replication lag in seconds */ virtual void set_replication_lag(int64_t lag) = 0; // TODO: Don't expose this to the modules and instead destroy the server // via ServerManager (currently needed by xpandmon) virtual void deactivate() = 0; /** * Set a status bit in the server without locking * * @param bit The bit to set for the server */ virtual void set_status(uint64_t bit) = 0; /** * Clear a status bit in the server without locking * * @param bit The bit to clear for the server */ virtual void clear_status(uint64_t bit) = 0; /** * Assign server status * * @param status Status to assign */ virtual void assign_status(uint64_t status) = 0; /** * Get SSL provider */ virtual const mxs::SSLProvider& ssl() const = 0; virtual mxs::SSLProvider& ssl() = 0; /** * Set server variables * * @param variables Variables and their values to set */ virtual void set_variables(std::unordered_map<std::string, std::string>&& variables) = 0; /** * Get server variable * * @param key Variable name to get * * @return Variable value or empty string if it was not found */ virtual std::string get_variable(const std::string& key) const = 0; /** * Set GTID positions * * @param positions List of pairs for the domain and the GTID position for it */ virtual void set_gtid_list(const std::vector<std::pair<uint32_t, uint64_t>>& positions) = 0; /** * Remove all stored GTID positions */ virtual void clear_gtid_list() = 0; /** * Get current server priority * * This should be used to decide which server is chosen as a master. Currently only galeramon uses it. */ virtual int64_t priority() const = 0; };
28.247649
106
0.610032
crspecter
04a5b3d2a1ab865d6ffc452ef13cb12de16bfc01
2,144
cpp
C++
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
/* * Created on: Sept 15, 2012 * Author: guille */ #include "date-delegate.h" #include <utils.h> #include <QDateEdit> DateDelegate::DateDelegate() : QStyledItemDelegate() { } void DateDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int epoch = index.model()->index(index.row(), index.column()).data().toInt(); QDateTime dateTime = utils::toDateTime(epoch); if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); painter->save(); painter->setPen(option.palette.highlightedText().color()); } painter->drawText(QRect(option.rect.topLeft(), option.rect.bottomRight()), Qt::AlignCenter, dateTime.date().toString("dd/MM/yyyy")); if (option.state & QStyle::State_Selected) painter->restore(); } QWidget *DateDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex & /*index*/) const { QDateEdit *editor = new QDateEdit(parent); editor->setFrame(false); editor->setDisplayFormat("dd/MM/yyyy"); editor->setCalendarPopup(true); return editor; } void DateDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QDate value = utils::toDate(index.model()->data(index, Qt::EditRole).toInt()); QDateEdit *edit = static_cast<QDateEdit*>(editor); edit->setDate(value); } void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QDateEdit *edit = static_cast<QDateEdit*>(editor); int value = utils::toDateStamp(edit->date()); model->setData(index, value, Qt::EditRole); } void DateDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } DateDelegate::~DateDelegate() { }
28.586667
94
0.623134
lgsilva3087
04a827c85eee25d051ca1e13b0d6f68c263a4f04
642
cc
C++
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // physicsbody.cc // (C) 2012-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/physicsbody.h" namespace Physics { #if (__USE_BULLET__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Bullet::BulletBody); #elif(__USE_PHYSX__) __ImplementClass(Physics::PhysicsBody, 'PHBO', PhysX::PhysXBody); #elif(__USE_HAVOK__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Havok::HavokBody); #else #error "Physics::PhysicsBody not implemented" #endif }
33.789474
80
0.573209
gscept
04aa6d5d23d6a0cd6eeaf4f8339101ab1adf2c54
6,105
cc
C++
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
1
2019-04-27T15:24:13.000Z
2019-04-27T15:24:13.000Z
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
null
null
null
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
null
null
null
#include "uv_secnet.hh" #include <iostream> #include <functional> #include <string> #include <sstream> #include <uv.h> #include <memory.h> #include <memory> #include <http_parser.h> typedef struct { int counter = 0; std::shared_ptr<uv_secnet::IConnection> conn = 0; uv_timer_t* timer = nullptr; uv_tcp_t* tcpHandle = nullptr; sockaddr_in* addr = nullptr; uv_secnet::IConnectionObserver* obs = nullptr; } secnet_ctx_s; typedef secnet_ctx_s secnet_ctx_t; void freeHandle(uv_handle_t* handle) { free(handle); } void initCtx (secnet_ctx_t* ctx) { ctx->counter = 0; ctx->conn = nullptr; ctx->timer = (uv_timer_t*)malloc(sizeof(uv_timer_t)); ctx->tcpHandle = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); ctx->addr = (sockaddr_in*)malloc(sizeof(sockaddr_in)); ctx->obs = new uv_secnet::IConnectionObserver(); uv_timer_init(uv_default_loop(), ctx->timer); uv_tcp_init(uv_default_loop(), ctx->tcpHandle); ctx->timer->data = ctx; ctx->tcpHandle->data = ctx; } void freeCtx(secnet_ctx_t* ctx) { free(ctx->timer); uv_close((uv_handle_t*) ctx->tcpHandle, freeHandle); ctx->conn = nullptr; free(ctx->addr); delete ctx->obs; free(ctx); } void timerTick(uv_timer_t* handle) { auto ctx = (secnet_ctx_t*) handle->data; if(++ctx->counter == 20) { std::cout << "Reached final tick, stopping counter" << std::endl; uv_timer_stop(handle); ctx->conn->close(); } else { std::cout << "Processing tick #" << ctx->counter << std::endl; std::stringstream ss; ss << "Hello from C++ tick #" << ctx->counter << std::endl; auto sd = ss.str(); int sl = sd.length(); char* data = (char*)malloc(sl + 1); strcpy(data, sd.c_str()); ctx->conn->write(uv_secnet::Buffer::makeShared(data, sl+1)); } } void connectCb(uv_connect_t* req, int status) { if(status != 0) { std::cout << "Connection Error: " << uv_err_name(status) << std::endl; } else { auto ctx = (secnet_ctx_t*) req->data; auto ssl_ctx = uv_secnet::TLSContext::getDefault(); // ctx->conn = ssl_ctx->secureClientConnection(uv_secnet::TCPConnection::create((uv_stream_t*)req->handle), "google.com"); ctx->conn = uv_secnet::TCPConnection::create((uv_stream_t*)req->handle); ctx->conn->initialize(ctx->obs); uv_secnet::HTTPObject obj("http://locahost:9999/post"); obj.setHeader("Connection", "Upgrade") ->setHeader("Upgrade", "websocket") ->setHeader("Sec-WebSocket-Key", "2BMqVIxuwA32Yuh1ydRutw==") ->setHeader("Sec-WebSocket-Version", "13"); ctx->conn->write(obj.toBuffer()); ctx->conn->close(); } free(req); } void runLoop() { uv_loop_t* loop = uv_default_loop(); secnet_ctx_t* ctx = (secnet_ctx_t*)malloc(sizeof(secnet_ctx_t)); initCtx(ctx); uv_ip4_addr("127.0.0.1", 9999, ctx->addr); // uv_ip4_addr("216.58.201.110", 443, ctx->addr); uv_connect_t* cReq = (uv_connect_t*)malloc(sizeof(uv_connect_t)); cReq->data = ctx; uv_tcp_connect(cReq, ctx->tcpHandle, (sockaddr*)ctx->addr, connectCb); uv_run(loop, UV_RUN_DEFAULT); freeCtx(ctx); } void testUri(std::string url) { auto uri = uv_secnet::Url::parse(url); return; } void on_addr_info(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { auto i4 = AF_INET; auto i6 = AF_INET6; if (status != 0) { char e[1024]; uv_err_name_r(status, e, 1024); std::cout << e << std::endl; return; } if (res->ai_family == AF_INET) { std::cout << inet_ntoa(((sockaddr_in*)res->ai_addr)->sin_addr) << ":" << ((sockaddr_in*)res->ai_addr)->sin_port << std::endl; } std::cout << "DONE!" << std::endl; } class LogObserver : public uv_secnet::IClientObserver { public: uv_secnet::HTTPObject* o; uv_secnet::TCPClient* c; LogObserver() : o(nullptr), c(nullptr) {}; virtual void onClientStatusChanged(uv_secnet::IClient::STATUS status) { std::cout << "Client status changed" << std::endl; }; // <0 - do not reconnect, 0 - reconnect now, >0 - reconnect delay virtual int onClientError(uv_secnet::IClient::ERR, std::string err) { std::cout << "Error: " << err << std::endl; } virtual void onClientData(uv_secnet::buffer_ptr_t data) { // std::cout << "Got data::" << std::endl << std::string(data->base, data->len) << std::endl; } virtual void onClientConnectionStatusChanged(uv_secnet::IClient::CONNECTION_STATUS status) { if (status == uv_secnet::IClient::CONNECTION_STATUS::OPEN) { std::cout << "Connected" << std::endl; c->send(o->toBuffer()); c->close(); } std::cout << "Connection status changed" << std::endl; } }; int main () { // std::string s("https://admin:fickmich@localhost:443/something?query=string"); // runLoop(); // auto buf = uv_secnet::safe_alloc<char>(16); // uv_secnet::randomBytes(buf, 16); // auto data = uv_secnet::vendor::base64_encode((unsigned char*)buf, 16); // std::string body("Text payload, yeah baby!"); // auto buf = uv_secnet::Buffer::makeShared(const_cast<char*>(body.c_str()), body.length()); // uv_secnet::HTTPObject obj(s); // obj.createBody("text/plain", buf) // ->setHeader("X-Auth-Token", "trlalala") // ->setHeader("User-Agent", "fucking_C++_baby!"); // auto b = obj.toBuffer(); // // std::cout << std::string(d, one.length() + two.length()); // std::cout << std::string(b->base, b->len); // std::cout << data << std::endl; uv_loop_t* loop = uv_default_loop(); // uv_secnet::TLSTransform::debug = true; std::string host("https://google.com:443/"); LogObserver o; uv_secnet::TCPClient client(loop, host, &o); auto httpO = uv_secnet::HTTPObject(host); httpO.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36"); httpO.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); o.o = &httpO; o.c = &client; client.enableTLS(); client.connect(); uv_run(loop, UV_RUN_DEFAULT); return 0; }
27.5
169
0.642588
michaelkuk
04abc62efa52d9dcd6d838c93265f6fc16bea6d9
5,461
cpp
C++
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
/** * \file OSGB.cpp * \brief Implementation for geographic_lib::OSGB class * * Copyright (c) Charles Karney (2010-2017) <charles@karney.com> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include <geographic_lib/OSGB.hpp> #include <geographic_lib/Utility.hpp> namespace geographic_lib { using namespace std; const char* const OSGB::letters_ = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; const char* const OSGB::digits_ = "0123456789"; const TransverseMercator& OSGB::OSGBTM() { static const TransverseMercator osgbtm(MajorRadius(), Flattening(), CentralScale()); return osgbtm; } Math::real OSGB::computenorthoffset() { real x, y; static const real northoffset = ( OSGBTM().Forward(real(0), OriginLatitude(), real(0), x, y), FalseNorthing() - y ); return northoffset; } void OSGB::GridReference(real x, real y, int prec, std::string& gridref) { CheckCoords(x, y); if (!(prec >= 0 && prec <= maxprec_)) throw GeographicErr("OSGB precision " + Utility::str(prec) + " not in [0, " + Utility::str(int(maxprec_)) + "]"); if (Math::isnan(x) || Math::isnan(y)) { gridref = "INVALID"; return; } char grid[2 + 2 * maxprec_]; int xh = int(floor(x / tile_)), yh = int(floor(y / tile_)); real xf = x - tile_ * xh, yf = y - tile_ * yh; xh += tileoffx_; yh += tileoffy_; int z = 0; grid[z++] = letters_[(tilegrid_ - (yh / tilegrid_) - 1) * tilegrid_ + (xh / tilegrid_)]; grid[z++] = letters_[(tilegrid_ - (yh % tilegrid_) - 1) * tilegrid_ + (xh % tilegrid_)]; // Need extra real because, since C++11, pow(float, int) returns double real mult = real(pow(real(base_), max(tilelevel_ - prec, 0))); int ix = int(floor(xf / mult)), iy = int(floor(yf / mult)); for (int c = min(prec, int(tilelevel_)); c--;) { grid[z + c] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + prec] = digits_[ iy % base_ ]; iy /= base_; } if (prec > tilelevel_) { xf -= floor(xf / mult); yf -= floor(yf / mult); mult = real(pow(real(base_), prec - tilelevel_)); ix = int(floor(xf * mult)); iy = int(floor(yf * mult)); for (int c = prec - tilelevel_; c--;) { grid[z + c + tilelevel_] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + tilelevel_ + prec] = digits_[ iy % base_ ]; iy /= base_; } } int mlen = z + 2 * prec; gridref.resize(mlen); copy(grid, grid + mlen, gridref.begin()); } void OSGB::GridReference(const std::string& gridref, real& x, real& y, int& prec, bool centerp) { int len = int(gridref.size()), p = 0; if (len >= 2 && toupper(gridref[0]) == 'I' && toupper(gridref[1]) == 'N') { x = y = Math::NaN(); prec = -2; // For compatibility with MGRS::Reverse. return; } char grid[2 + 2 * maxprec_]; for (int i = 0; i < len; ++i) { if (!isspace(gridref[i])) { if (p >= 2 + 2 * maxprec_) throw GeographicErr("OSGB string " + gridref + " too long"); grid[p++] = gridref[i]; } } len = p; p = 0; if (len < 2) throw GeographicErr("OSGB string " + gridref + " too short"); if (len % 2) throw GeographicErr("OSGB string " + gridref + " has odd number of characters"); int xh = 0, yh = 0; while (p < 2) { int i = Utility::lookup(letters_, grid[p++]); if (i < 0) throw GeographicErr("Illegal prefix character " + gridref); yh = yh * tilegrid_ + tilegrid_ - (i / tilegrid_) - 1; xh = xh * tilegrid_ + (i % tilegrid_); } xh -= tileoffx_; yh -= tileoffy_; int prec1 = (len - p)/2; real unit = tile_, x1 = unit * xh, y1 = unit * yh; for (int i = 0; i < prec1; ++i) { unit /= base_; int ix = Utility::lookup(digits_, grid[p + i]), iy = Utility::lookup(digits_, grid[p + i + prec1]); if (ix < 0 || iy < 0) throw GeographicErr("Encountered a non-digit in " + gridref); x1 += unit * ix; y1 += unit * iy; } if (centerp) { x1 += unit/2; y1 += unit/2; } x = x1; y = y1; prec = prec1; } void OSGB::CheckCoords(real x, real y) { // Limits are all multiples of 100km and are all closed on the lower end // and open on the upper end -- and this is reflected in the error // messages. NaNs are let through. if (x < minx_ || x >= maxx_) throw GeographicErr("Easting " + Utility::str(int(floor(x/1000))) + "km not in OSGB range [" + Utility::str(minx_/1000) + "km, " + Utility::str(maxx_/1000) + "km)"); if (y < miny_ || y >= maxy_) throw GeographicErr("Northing " + Utility::str(int(floor(y/1000))) + "km not in OSGB range [" + Utility::str(miny_/1000) + "km, " + Utility::str(maxy_/1000) + "km)"); } } // namespace geographic_lib
32.313609
77
0.505951
embarktrucks
04ae3908f29be5c0b731c7f52f54c893af83da0e
16,195
cpp
C++
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
7
2018-08-11T15:46:14.000Z
2022-01-28T18:39:19.000Z
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
null
null
null
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
1
2019-01-18T20:38:53.000Z
2019-01-18T20:38:53.000Z
/******************************************************************************** Copyright 2017 Frank Imeson and Stephen L. Smith 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 "formula.hpp" using namespace formula; #define DEBUG /******************************************************************************** * * Functions * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, const Lit &b) { Formula* formula = new Formula(F_OR); a->negate(); formula->add(a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(a->negate()); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::get_solution (const Solver &solver, vec<Lit> &lits, Var max_var) { if (max_var < 0) max_var = solver.model.size()-1; for (unsigned int i=0; i<=max_var; i++) lits.push( mkLit(i, solver.model[i] == l_False) ); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_iff (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); Formula* f0 = new Formula(F_AND); Formula* f1 = new Formula(F_AND); f0->add(a); f0->add(b); f1->add(~a); f1->add(~b); formula->add(f0); formula->add(f1); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_least_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) formula->add(mkLit(var_list[i], false)); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_most_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } Formula* f0 = new Formula(F_AND); for (int i=0; i<var_list.size(); i++) { f0->add(mkLit(var_list[i], true)); } formula->add(f0); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::negate_solution (const vec<Lit> &lits, Solver &solver) { vec<Lit> nlits; for (unsigned int i=0; i<lits.size(); i++) nlits.push( ~lits[i] ); solver.addClause(nlits); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Lit formula::translate (const int &lit) { return mkLit(abs(lit)-1, (lit<0)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::translate (const Lit &lit) { return sign(lit) ? -var(lit)-1:var(lit)+1; } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Con &connective) { switch (connective) { case F_AND: return "^"; case F_OR: return "v"; default: return " "; } } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Lit &lit) { stringstream out; if (sign(lit)) out << "-"; else out << " "; out << (var(lit)+1); return out.str(); } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const vec<Lit> &lits) { string result; for (unsigned int i=0; i<lits.size(); i++) result += str(lits[i]) + " "; return result; } /************************************************************//** * @brief * @return negated connective, -1 on error * @version v0.01b ****************************************************************/ Con formula::negate (const Con &connective) { switch (connective) { case F_AND: return F_OR; case F_OR: return F_AND; default: return -1; } } /************************************************************//** * @brief * @return negated litteral * @version v0.01b ****************************************************************/ Lit formula::negate (const Lit &lit) { return ~lit; } /******************************************************************************** * * Formula Class * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::~Formula () { clear(); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula () : connective(F_AND) , max_var(0) {} /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula (Con _connective) : connective(_connective) , max_var(0) {} /************************************************************//** * @brief Clear all contents of Formula recursively * @version v0.01b ****************************************************************/ int Formula::clear () { try { for (unsigned int i=0; i<formuli.size(); i++) { if (formuli[i] != NULL) { delete formuli[i]; formuli[i] = NULL; } } formuli.clear(); } catch(...) { perror("error Formula::clear(): "); exit(1); } return 0; } /************************************************************//** * @brief Negate entire formula * @return 0 on succession, < 0 on error * @version v0.01b ****************************************************************/ int Formula::negate () { connective = ::negate(connective); if (connective < 0) return connective; for (unsigned int i=0; i<lits.size(); i++) lits[i] = ::negate(lits[i]); for (unsigned int i=0; i<formuli.size(); i++) { int rtn = formuli[i]->negate(); if (rtn < 0) return rtn; } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ void Formula::track_max (const Var &var) { if (var > max_var) max_var = var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const Lit &lit) { track_max(var(lit)); lits.push(lit); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const int &lit) { return add(translate(lit)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const vec<Lit> &lits) { for (unsigned int i=0; i<lits.size(); i++) add(lits[i]); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (Formula *formula) { track_max(formula->maxVar()); if (formula != NULL) formuli.push(formula); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::newVar () { max_var++; return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::maxVar () { return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::export_cnf (Lit &out, Formula *formula, Solver *solver) { if ( (formula == NULL && solver == NULL) || (formula != NULL && solver != NULL) ) return -1; // setup vars in solver // translation requires a new var to replace nested phrases if (solver != NULL) { while (solver->nVars() < max_var+1) solver->newVar(); out = mkLit( solver->newVar(), false ); } else { while (formula->maxVar() < max_var) formula->newVar(); out = mkLit( formula->newVar(), false ); } vec<Lit> big_clause; switch (connective) { case F_OR: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(lits[i]); if (solver != NULL) { solver->addClause(~lits[i], out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~lits[i]); phrase->add(out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(cnf_out); if (solver != NULL) { solver->addClause(~cnf_out, out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~cnf_out); phrase->add(out); formula->add(phrase); } } big_clause.push(~out); break; case F_AND: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(~lits[i]); if (solver != NULL) { solver->addClause(lits[i], ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(lits[i]); phrase->add(~out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(~cnf_out); if (solver != NULL) { solver->addClause(cnf_out, ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(cnf_out); phrase->add(~out); formula->add(phrase); } } big_clause.push(out); break; default: break; } if (solver != NULL) { solver->addClause(big_clause); } else { Formula *phrase = new Formula(F_OR); phrase->add(big_clause); formula->add(phrase); } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str () { return str(string("")); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str (string prefix) { string result = prefix; if (formuli.size() == 0) { // result += "( "; for (unsigned int i=0; i<lits.size(); i++) result += ::str(lits[i]) + " " + ::str(connective) + " "; result.resize(result.size()-2); // result += ")\n"; result += "\n"; } else { result += prefix + ::str(connective) + '\n'; for (unsigned int i=0; i<lits.size(); i++) result += prefix + " " + ::str(lits[i]) + '\n'; for (unsigned int i=0; i<formuli.size(); i++) result += formuli[i]->str(prefix+" "); } return result; }
26.946755
91
0.367768
fcimeson
04ae6528676f31336a1509fc10ce4187a0f93f18
4,486
hpp
C++
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
/* * Copyright 2016-2017 Nikolay Aleksiev. All rights reserved. * License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE */ // Copyright Epic Games, Inc. All Rights Reserved. // Modifications for Unreal Engine #pragma once #include "declare.hpp" #include "imp_DepthStencil.hpp" #include "ns.hpp" #include "device.hpp" MTLPP_BEGIN namespace ue4 { template<> struct ITable<id<MTLDepthStencilState>, void> : public IMPTable<id<MTLDepthStencilState>, void>, public ITableCacheRef { ITable() { } ITable(Class C) : IMPTable<id<MTLDepthStencilState>, void>(C) { } }; template<> inline ITable<MTLStencilDescriptor*, void>* CreateIMPTable(MTLStencilDescriptor* handle) { static ITable<MTLStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } template<> inline ITable<MTLDepthStencilDescriptor*, void>* CreateIMPTable(MTLDepthStencilDescriptor* handle) { static ITable<MTLDepthStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } } namespace mtlpp { enum class CompareFunction { Never = 0, Less = 1, Equal = 2, LessEqual = 3, Greater = 4, NotEqual = 5, GreaterEqual = 6, Always = 7, } MTLPP_AVAILABLE(10_11, 8_0); enum class StencilOperation { Keep = 0, Zero = 1, Replace = 2, IncrementClamp = 3, DecrementClamp = 4, Invert = 5, IncrementWrap = 6, DecrementWrap = 7, } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT StencilDescriptor : public ns::Object<MTLStencilDescriptor*> { public: StencilDescriptor(); StencilDescriptor(ns::Ownership const retain) : ns::Object<MTLStencilDescriptor*>(retain) {} StencilDescriptor(MTLStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLStencilDescriptor*>(handle, retain) { } CompareFunction GetStencilCompareFunction() const; StencilOperation GetStencilFailureOperation() const; StencilOperation GetDepthFailureOperation() const; StencilOperation GetDepthStencilPassOperation() const; uint32_t GetReadMask() const; uint32_t GetWriteMask() const; void SetStencilCompareFunction(CompareFunction stencilCompareFunction); void SetStencilFailureOperation(StencilOperation stencilFailureOperation); void SetDepthFailureOperation(StencilOperation depthFailureOperation); void SetDepthStencilPassOperation(StencilOperation depthStencilPassOperation); void SetReadMask(uint32_t readMask); void SetWriteMask(uint32_t writeMask); } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilDescriptor : public ns::Object<MTLDepthStencilDescriptor*> { public: DepthStencilDescriptor(); DepthStencilDescriptor(MTLDepthStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLDepthStencilDescriptor*>(handle, retain) { } CompareFunction GetDepthCompareFunction() const; bool IsDepthWriteEnabled() const; ns::AutoReleased<StencilDescriptor> GetFrontFaceStencil() const; ns::AutoReleased<StencilDescriptor> GetBackFaceStencil() const; ns::AutoReleased<ns::String> GetLabel() const; void SetDepthCompareFunction(CompareFunction depthCompareFunction) const; void SetDepthWriteEnabled(bool depthWriteEnabled) const; void SetFrontFaceStencil(const StencilDescriptor& frontFaceStencil) const; void SetBackFaceStencil(const StencilDescriptor& backFaceStencil) const; void SetLabel(const ns::String& label) const; } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilState : public ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type> { public: DepthStencilState() { } DepthStencilState(ns::Protocol<id<MTLDepthStencilState>>::type handle, ue4::ITableCache* cache = nullptr, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type>(handle, retain, ue4::ITableCacheRef(cache).GetDepthStencilState(handle)) { } ns::AutoReleased<ns::String> GetLabel() const; ns::AutoReleased<Device> GetDevice() const; } MTLPP_AVAILABLE(10_11, 8_0); } MTLPP_END
34.244275
295
0.689924
dtonna
04b24bfd53799b832594a74becbe2d41bc106104
3,097
cpp
C++
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
null
null
null
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
2
2019-07-30T15:36:06.000Z
2021-09-28T15:45:27.000Z
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
2
2019-07-30T14:06:52.000Z
2019-09-26T15:25:05.000Z
#include "config.h" #include "utils.hpp" #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/elog.hpp> #include <phosphor-logging/log.hpp> #include <xyz/openbmc_project/Common/error.hpp> #if OPENSSL_VERSION_NUMBER < 0x10100000L #include <string.h> static void* OPENSSL_zalloc(size_t num) { void* ret = OPENSSL_malloc(num); if (ret != NULL) { memset(ret, 0, num); } return ret; } EVP_MD_CTX* EVP_MD_CTX_new(void) { return (EVP_MD_CTX*)OPENSSL_zalloc(sizeof(EVP_MD_CTX)); } void EVP_MD_CTX_free(EVP_MD_CTX* ctx) { EVP_MD_CTX_cleanup(ctx); OPENSSL_free(ctx); } #endif // OPENSSL_VERSION_NUMBER < 0x10100000L namespace utils { using sdbusplus::exception::SdBusError; using namespace phosphor::logging; constexpr auto HIOMAPD_PATH = "/xyz/openbmc_project/Hiomapd"; constexpr auto HIOMAPD_INTERFACE = "xyz.openbmc_project.Hiomapd.Control"; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::string getService(sdbusplus::bus::bus& bus, const std::string& path, const std::string& intf) { auto mapper = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH, MAPPER_INTERFACE, "GetObject"); mapper.append(path, std::vector<std::string>({intf})); try { auto mapperResponseMsg = bus.call(mapper); std::vector<std::pair<std::string, std::vector<std::string>>> mapperResponse; mapperResponseMsg.read(mapperResponse); if (mapperResponse.empty()) { log<level::ERR>("Error reading mapper response"); throw std::runtime_error("Error reading mapper response"); } return mapperResponse[0].first; } catch (const sdbusplus::exception::SdBusError& ex) { log<level::ERR>("Mapper call failed", entry("METHOD=%d", "GetObject"), entry("PATH=%s", path.c_str()), entry("INTERFACE=%s", intf.c_str())); throw std::runtime_error("Mapper call failed"); } } void hiomapdSuspend(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Suspend"); try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } void hiomapdResume(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Resume"); method.append(true); // Indicate PNOR is modified try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } } // namespace utils
26.470085
78
0.621569
jaypadath
04b35c8cf7b9118dee19bc892bcd69cf302380cd
5,463
cpp
C++
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/text/DateFormat_Field.hpp> extern void unimplemented_(const char16_t* name); java::text::DateFormat_Field::DateFormat_Field(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::text::DateFormat_Field::DateFormat_Field(::java::lang::String* name, int32_t calendarField) : DateFormat_Field(*static_cast< ::default_init_tag* >(0)) { ctor(name, calendarField); } java::text::DateFormat_Field*& java::text::DateFormat_Field::AM_PM() { clinit(); return AM_PM_; } java::text::DateFormat_Field* java::text::DateFormat_Field::AM_PM_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_MONTH() { clinit(); return DAY_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK() { clinit(); return DAY_OF_WEEK_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH() { clinit(); return DAY_OF_WEEK_IN_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_YEAR() { clinit(); return DAY_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::ERA() { clinit(); return ERA_; } java::text::DateFormat_Field* java::text::DateFormat_Field::ERA_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR0() { clinit(); return HOUR0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR1() { clinit(); return HOUR1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY0() { clinit(); return HOUR_OF_DAY0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY1() { clinit(); return HOUR_OF_DAY1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MILLISECOND() { clinit(); return MILLISECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MILLISECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MINUTE() { clinit(); return MINUTE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MINUTE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MONTH() { clinit(); return MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::SECOND() { clinit(); return SECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::SECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::TIME_ZONE() { clinit(); return TIME_ZONE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::TIME_ZONE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_MONTH() { clinit(); return WEEK_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_YEAR() { clinit(); return WEEK_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::YEAR() { clinit(); return YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::YEAR_; java::text::DateFormat_FieldArray*& java::text::DateFormat_Field::calendarToFieldMapping() { clinit(); return calendarToFieldMapping_; } java::text::DateFormat_FieldArray* java::text::DateFormat_Field::calendarToFieldMapping_; java::util::Map*& java::text::DateFormat_Field::instanceMap() { clinit(); return instanceMap_; } java::util::Map* java::text::DateFormat_Field::instanceMap_; constexpr int64_t java::text::DateFormat_Field::serialVersionUID; void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField)"); } int32_t java::text::DateFormat_Field::getCalendarField() { /* stub */ return calendarField ; /* getter */ } java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField) { /* stub */ clinit(); unimplemented_(u"java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField)"); return 0; } java::lang::Object* java::text::DateFormat_Field::readResolve() { /* stub */ unimplemented_(u"java::lang::Object* java::text::DateFormat_Field::readResolve()"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::text::DateFormat_Field::class_() { static ::java::lang::Class* c = ::class_(u"java.text.DateFormat.Field", 26); return c; } java::lang::Class* java::text::DateFormat_Field::getClass0() { return class_(); }
31.039773
122
0.730551
pebble2015
04b682e2bee638e6058c378a04e2f6ce49c9266e
6,969
cpp
C++
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
2,270
2020-04-15T15:14:37.000Z
2022-03-31T19:13:53.000Z
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
471
2017-04-25T07:57:02.000Z
2020-04-08T21:06:47.000Z
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
633
2020-04-15T16:45:55.000Z
2022-03-31T13:32:29.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== #if ! JUCE_ANDROID && ! JUCE_IOS && ! JUCE_MAC bool PushNotifications::Notification::isValid() const noexcept { return true; } #endif PushNotifications::Notification::Notification (const Notification& other) : identifier (other.identifier), title (other.title), body (other.body), subtitle (other.subtitle), groupId (other.groupId), badgeNumber (other.badgeNumber), soundToPlay (other.soundToPlay), properties (other.properties), category (other.category), triggerIntervalSec (other.triggerIntervalSec), repeat (other.repeat), icon (other.icon), channelId (other.channelId), largeIcon (other.largeIcon), tickerText (other.tickerText), actions (other.actions), progress (other.progress), person (other.person), type (other.type), priority (other.priority), lockScreenAppearance (other.lockScreenAppearance), publicVersion (other.publicVersion.get() != nullptr ? new Notification (*other.publicVersion) : nullptr), groupSortKey (other.groupSortKey), groupSummary (other.groupSummary), accentColour (other.accentColour), ledColour (other.ledColour), ledBlinkPattern (other.ledBlinkPattern), vibrationPattern (other.vibrationPattern), shouldAutoCancel (other.shouldAutoCancel), localOnly (other.localOnly), ongoing (other.ongoing), alertOnlyOnce (other.alertOnlyOnce), timestampVisibility (other.timestampVisibility), badgeIconType (other.badgeIconType), groupAlertBehaviour (other.groupAlertBehaviour), timeoutAfterMs (other.timeoutAfterMs) { } //============================================================================== JUCE_IMPLEMENT_SINGLETON (PushNotifications) PushNotifications::PushNotifications() #if JUCE_PUSH_NOTIFICATIONS : pimpl (new Pimpl (*this)) #endif { } PushNotifications::~PushNotifications() { clearSingletonInstance(); } void PushNotifications::addListener (Listener* l) { listeners.add (l); } void PushNotifications::removeListener (Listener* l) { listeners.remove (l); } void PushNotifications::requestPermissionsWithSettings (const PushNotifications::Settings& settings) { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestPermissionsWithSettings (settings); #else ignoreUnused (settings); listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } void PushNotifications::requestSettingsUsed() { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestSettingsUsed(); #else listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } bool PushNotifications::areNotificationsEnabled() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->areNotificationsEnabled(); #else return false; #endif } void PushNotifications::getDeliveredNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getDeliveredNotifications(); #endif } void PushNotifications::removeAllDeliveredNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllDeliveredNotifications(); #endif } String PushNotifications::getDeviceToken() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->getDeviceToken(); #else return {}; #endif } void PushNotifications::setupChannels (const Array<ChannelGroup>& groups, const Array<Channel>& channels) { #if JUCE_PUSH_NOTIFICATIONS pimpl->setupChannels (groups, channels); #else ignoreUnused (groups, channels); #endif } void PushNotifications::getPendingLocalNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getPendingLocalNotifications(); #endif } void PushNotifications::removeAllPendingLocalNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllPendingLocalNotifications(); #endif } void PushNotifications::subscribeToTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->subscribeToTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::unsubscribeFromTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->unsubscribeFromTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::sendLocalNotification (const Notification& n) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendLocalNotification (n); #else ignoreUnused (n); #endif } void PushNotifications::removeDeliveredNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeDeliveredNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::removePendingLocalNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removePendingLocalNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::sendUpstreamMessage (const String& serverSenderId, const String& collapseKey, const String& messageId, const String& messageType, int timeToLive, const StringPairArray& additionalData) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendUpstreamMessage (serverSenderId, collapseKey, messageId, messageType, timeToLive, additionalData); #else ignoreUnused (serverSenderId, collapseKey, messageId, messageType); ignoreUnused (timeToLive, additionalData); #endif } } // namespace juce
30.3
112
0.638686
studiobee
04b7bba6077c701cfe3ba87b19eb7a5b761f9e5a
1,018
cpp
C++
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
#include "ExplosionEvent.h" Go::ExplosionEvent::ExplosionEvent(ModuleLibrary *module) : IEvent(module) { } void Go::ExplosionEvent::Call(const alt::CEvent *ev) { static auto call = GET_FUNC(Library, "altExplosionEvent", bool (*)(alt::IPlayer* source, Entity target, Position position, short explosionType, unsigned int explosionFX)); if (call == nullptr) { alt::ICore::Instance().LogError("Couldn't not call ExplosionEvent."); return; } auto event = dynamic_cast<const alt::CExplosionEvent *>(ev); auto target = event->GetTarget(); auto source = event->GetSource().Get(); auto pos = event->GetPosition(); auto expFX = event->GetExplosionFX(); auto expType = event->GetExplosionType(); Entity e = Go::Runtime::GetInstance()->GetEntity(target); Position cPos; cPos.x = pos.x; cPos.y = pos.y; cPos.z = pos.z; auto cancel = call(source, e, cPos, static_cast<short>(expType), expFX); if(!cancel) { event->Cancel(); } }
29.085714
175
0.649312
Timo972
04b8560c82b0f92dd8c621ce7934ca440540a3be
59,762
cpp
C++
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
1
2021-06-05T00:22:08.000Z
2021-06-05T00:22:08.000Z
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
null
null
null
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * Xidi * DirectInput interface for XInput controllers. ***************************************************************************** * Authored by Samuel Grossman * Copyright (c) 2016-2021 *************************************************************************//** * @file VirtualDirectInputDevice.cpp * Implementation of an IDirectInputDevice interface wrapper around virtual * controllers. *****************************************************************************/ #include "ApiDirectInput.h" #include "ApiGUID.h" #include "ControllerIdentification.h" #include "ControllerTypes.h" #include "DataFormat.h" #include "Message.h" #include "Strings.h" #include "VirtualController.h" #include "VirtualDirectInputDevice.h" #include <atomic> #include <cstdio> #include <cstring> #include <memory> #include <optional> // -------- MACROS --------------------------------------------------------- // /// Logs a DirectInput interface method invocation and returns. #define LOG_INVOCATION_AND_RETURN(result, severity) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked %s on Xidi virtual controller %u, result = 0x%08x.", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method invocation and returns. #define LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, propvalfmt, ...) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked function %s on Xidi virtual controller %u, result = 0x%08x, property = %s" propvalfmt L".", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult, PropertyGuidString(rguidprop), ##__VA_ARGS__); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method without a value and returns. #define LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(result, severity, rguidprop) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L"") /// Logs a DirectInput property-related method where the value is provided in a DIPROPDWORD structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { dwData = %u }", ((LPDIPROPDWORD)ppropval)->dwData) /// Logs a DirectInput property-related method where the value is provided in a DIPROPRANGE structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { lMin = %ld, lMax = %ld }", ((LPDIPROPRANGE)ppropval)->lMin, ((LPDIPROPRANGE)ppropval)->lMax) /// Produces and returns a human-readable string from a given DirectInput property GUID. #define DI_PROPERTY_STRING(rguid, diprop) if (&diprop == &rguid) return _CRT_WIDE(#diprop); namespace Xidi { // -------- INTERNAL FUNCTIONS ----------------------------------------- // /// Converts from axis type enumerator to axis type GUID. /// @param [in] axis Axis type enumerator to convert. /// @return Read-only reference to the corresponding GUID object. static const GUID& AxisTypeGuid(Controller::EAxis axis) { switch (axis) { case Controller::EAxis::X: return GUID_XAxis; case Controller::EAxis::Y: return GUID_YAxis; case Controller::EAxis::Z: return GUID_ZAxis; case Controller::EAxis::RotX: return GUID_RxAxis; case Controller::EAxis::RotY: return GUID_RyAxis; case Controller::EAxis::RotZ: return GUID_RzAxis; default: return GUID_Unknown; } } /// Returns a string representation of the way in which a controller element is identified. /// @param [in] dwHow Value to check. /// @return String representation of the identification method. static const wchar_t* IdentificationMethodString(DWORD dwHow) { switch (dwHow) { case DIPH_DEVICE: return L"DIPH_DEVICE"; case DIPH_BYOFFSET: return L"DIPH_BYOFFSET"; case DIPH_BYUSAGE: return L"DIPH_BYUSAGE"; case DIPH_BYID: return L"DIPH_BYID"; default: return L"(unknown)"; } } /// Returns a human-readable string that represents the specified property GUID. /// @param [in] pguid GUID to check. /// @return String representation of the GUID's semantics. static const wchar_t* PropertyGuidString(REFGUID rguidProp) { switch ((size_t)&rguidProp) { #if DIRECTINPUT_VERSION >= 0x0800 case ((size_t)&DIPROP_KEYNAME): return L"DIPROP_KEYNAME"; case ((size_t)&DIPROP_CPOINTS): return L"DIPROP_CPOINTS"; case ((size_t)&DIPROP_APPDATA): return L"DIPROP_APPDATA"; case ((size_t)&DIPROP_SCANCODE): return L"DIPROP_SCANCODE"; case ((size_t)&DIPROP_VIDPID): return L"DIPROP_VIDPID"; case ((size_t)&DIPROP_USERNAME): return L"DIPROP_USERNAME"; case ((size_t)&DIPROP_TYPENAME): return L"DIPROP_TYPENAME"; #endif case ((size_t)&DIPROP_BUFFERSIZE): return L"DIPROP_BUFFERSIZE"; case ((size_t)&DIPROP_AXISMODE): return L"DIPROP_AXISMODE"; case ((size_t)&DIPROP_GRANULARITY): return L"DIPROP_GRANULARITY"; case ((size_t)&DIPROP_RANGE): return L"DIPROP_RANGE"; case ((size_t)&DIPROP_DEADZONE): return L"DIPROP_DEADZONE"; case ((size_t)&DIPROP_SATURATION): return L"DIPROP_SATURATION"; case ((size_t)&DIPROP_FFGAIN): return L"DIPROP_FFGAIN"; case ((size_t)&DIPROP_FFLOAD): return L"DIPROP_FFLOAD"; case ((size_t)&DIPROP_AUTOCENTER): return L"DIPROP_AUTOCENTER"; case ((size_t)&DIPROP_CALIBRATIONMODE): return L"DIPROP_CALIBRATIONMODE"; case ((size_t)&DIPROP_CALIBRATION): return L"DIPROP_CALIBRATION"; case ((size_t)&DIPROP_GUIDANDPATH): return L"DIPROP_GUIDANDPATH"; case ((size_t)&DIPROP_INSTANCENAME): return L"DIPROP_INSTANCENAME"; case ((size_t)&DIPROP_PRODUCTNAME): return L"DIPROP_PRODUCTNAME"; case ((size_t)&DIPROP_JOYSTICKID): return L"DIPROP_JOYSTICKID"; case ((size_t)&DIPROP_GETPORTDISPLAYNAME): return L"DIPROP_GETPORTDISPLAYNAME"; case ((size_t)&DIPROP_PHYSICALRANGE): return L"DIPROP_PHYSICALRANGE"; case ((size_t)&DIPROP_LOGICALRANGE): return L"DIPROP_LOGICALRANGE"; default: return L"(unknown)"; } } /// Performs property-specific validation of the supplied property header. /// Ensures the header exists and all sizes are correct. /// @param [in] rguidProp GUID of the property for which the header is being validated. /// @param [in] pdiph Pointer to the property header structure to validate. /// @return `true` if the header is valid, `false` otherwise. static bool IsPropertyHeaderValid(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { if (nullptr == pdiph) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected null property header for %s.", PropertyGuidString(rguidProp)); return false; } else if ((sizeof(DIPROPHEADER) != pdiph->dwHeaderSize)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPHEADER (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPHEADER), (unsigned int)pdiph->dwHeaderSize); return false; } else if ((DIPH_DEVICE == pdiph->dwHow) && (0 != pdiph->dwObj)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification value used with DIPH_DEVICE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)0, (unsigned int)pdiph->dwObj); return false; } // Look for reasons why the property header might be invalid and reject it if any are found. switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): case ((size_t)&DIPROP_DEADZONE): case ((size_t)&DIPROP_GRANULARITY): case ((size_t)&DIPROP_SATURATION): // Axis mode, deadzone, granularity, and saturation all use DIPROPDWORD. if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_BUFFERSIZE): case ((size_t)&DIPROP_FFGAIN): case ((size_t)&DIPROP_JOYSTICKID): // Buffer size, force feedback gain, and joystick ID all use DIPROPDWORD and are exclusively device-wide properties. if (DIPH_DEVICE != pdiph->dwHow) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification method for this property (expected %s, got %s).", PropertyGuidString(rguidProp), IdentificationMethodString(DIPH_DEVICE), IdentificationMethodString(pdiph->dwHow)); return false; } else if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_RANGE): case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): // Range-related properties use DIPROPRANGE. if (sizeof(DIPROPRANGE) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPRANGE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPRANGE), (unsigned int)pdiph->dwSize); return false; } break; default: // Any property not listed here is not supported by Xidi and therefore not validated by it. Message::OutputFormatted(Message::ESeverity::Warning, L"Skipped property header validation because the property %s is not supported.", PropertyGuidString(rguidProp)); return true; } Message::OutputFormatted(Message::ESeverity::Info, L"Accepted valid property header for %s.", PropertyGuidString(rguidProp)); return true; } /// Dumps the top-level components of a property request. /// @param [in] rguidProp GUID of the property. /// @param [in] pdiph Pointer to the property header. /// @param [in] requestTypeIsSet `true` if the request type is SetProperty, `false` if it is GetProperty. static void DumpPropertyRequest(REFGUID rguidProp, LPCDIPROPHEADER pdiph, bool requestTypeIsSet) { constexpr Message::ESeverity kDumpSeverity = Message::ESeverity::Debug; if (Message::WillOutputMessageOfSeverity(kDumpSeverity)) { Message::Output(kDumpSeverity, L"Begin dump of property request."); Message::Output(kDumpSeverity, L" Metadata:"); Message::OutputFormatted(kDumpSeverity, L" operation = %sProperty", ((true == requestTypeIsSet) ? L"Set" : L"Get")); Message::OutputFormatted(kDumpSeverity, L" rguidProp = %s", PropertyGuidString(rguidProp)); Message::Output(kDumpSeverity, L" Header:"); if (nullptr == pdiph) { Message::Output(kDumpSeverity, L" (missing)"); } else { Message::OutputFormatted(kDumpSeverity, L" dwSize = %u", pdiph->dwSize); Message::OutputFormatted(kDumpSeverity, L" dwHeaderSize = %u", pdiph->dwHeaderSize); Message::OutputFormatted(kDumpSeverity, L" dwObj = %u (0x%08x)", pdiph->dwObj, pdiph->dwObj); Message::OutputFormatted(kDumpSeverity, L" dwHow = %u (%s)", pdiph->dwHow, IdentificationMethodString(pdiph->dwHow)); } Message::Output(kDumpSeverity, L"End dump of property request."); } } /// Fills the specified buffer with a friendly string representation of the specified controller element. /// Default version does nothing. /// @tparam CharType String character type, either `char` or `wchar_t`. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <typename CharType> static void ElementToString(Controller::SElementIdentifier element, CharType* buf, int bufcount) { // Nothing to do here. } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<char>(Controller::SElementIdentifier element, char* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_X, _countof(XIDI_AXIS_NAME_X)); break; case Controller::EAxis::Y: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Y, _countof(XIDI_AXIS_NAME_Y)); break; case Controller::EAxis::Z: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Z, _countof(XIDI_AXIS_NAME_Z)); break; case Controller::EAxis::RotX: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RX, _countof(XIDI_AXIS_NAME_RX)); break; case Controller::EAxis::RotY: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RY, _countof(XIDI_AXIS_NAME_RY)); break; case Controller::EAxis::RotZ: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RZ, _countof(XIDI_AXIS_NAME_RZ)); break; default: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_UNKNOWN, _countof(XIDI_AXIS_NAME_UNKNOWN)); break; } break; case Controller::EElementType::Button: sprintf_s(buf, bufcount, XIDI_BUTTON_NAME_FORMAT, (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: strncpy_s(buf, bufcount, XIDI_POV_NAME, _countof(XIDI_POV_NAME)); break; case Controller::EElementType::WholeController: strncpy_s(buf, bufcount, XIDI_WHOLE_CONTROLLER_NAME, _countof(XIDI_WHOLE_CONTROLLER_NAME)); break; } } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<wchar_t>(Controller::SElementIdentifier element, wchar_t* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_X), _countof(_CRT_WIDE(XIDI_AXIS_NAME_X))); break; case Controller::EAxis::Y: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Y), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Y))); break; case Controller::EAxis::Z: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Z), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Z))); break; case Controller::EAxis::RotX: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RX), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RX))); break; case Controller::EAxis::RotY: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RY), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RY))); break; case Controller::EAxis::RotZ: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RZ), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RZ))); break; default: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN), _countof(_CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN))); break; } break; case Controller::EElementType::Button: swprintf_s(buf, bufcount, _CRT_WIDE(XIDI_BUTTON_NAME_FORMAT), (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_POV_NAME), _countof(_CRT_WIDE(XIDI_POV_NAME))); break; case Controller::EElementType::WholeController: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME), _countof(_CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME))); break; } } /// Computes the offset in a virtual controller's "native" data packet. /// For application information only. Cannot be used to identify objects. /// Application is presented with the image of a native data packet that stores axes first, then buttons (one byte per button), then POV. /// @param [in] controllerElement Virtual controller element for which a native offset is desired. /// @return Native offset value for providing to applications. static TOffset NativeOffsetForElement(Controller::SElementIdentifier controllerElement) { switch (controllerElement.type) { case Controller::EElementType::Axis: return offsetof(Controller::SState, axis[(int)controllerElement.axis]); case Controller::EElementType::Button: return offsetof(Controller::SState, button) + (TOffset)controllerElement.button; case Controller::EElementType::Pov: return offsetof(Controller::SState, button) + (TOffset)Controller::EButton::Count; default: // This should never happen. return DataFormat::kInvalidOffsetValue; } } /// Fills the specified object instance information structure with information about the specified controller element. /// Size member must already be initialized because multiple versions of the structure exist, so it is used to determine which members to fill in. /// @tparam charMode Selects between ASCII ("A" suffix) and Unicode ("W") suffix versions of types and interfaces. /// @param [in] controllerCapabilities Capabilities that describe the layout of the virtual controller. /// @param [in] controllerElement Virtual controller element about which to fill information. /// @param [in] offset Offset to place into the object instance information structure. /// @param objectInfo [out] Structure to be filled with instance information. template <ECharMode charMode> static void FillObjectInstanceInfo(const Controller::SCapabilities controllerCapabilities, Controller::SElementIdentifier controllerElement, TOffset offset, typename DirectInputDeviceType<charMode>::DeviceObjectInstanceType* objectInfo) { objectInfo->dwOfs = offset; ElementToString(controllerElement, objectInfo->tszName, _countof(objectInfo->tszName)); switch (controllerElement.type) { case Controller::EElementType::Axis: objectInfo->guidType = AxisTypeGuid(controllerElement.axis); objectInfo->dwType = DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE((int)controllerCapabilities.FindAxis(controllerElement.axis)); objectInfo->dwFlags = DIDOI_POLLED | DIDOI_ASPECTPOSITION; break; case Controller::EElementType::Button: objectInfo->guidType = GUID_Button; objectInfo->dwType = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE((int)controllerElement.button); objectInfo->dwFlags = DIDOI_POLLED; break; case Controller::EElementType::Pov: objectInfo->guidType = GUID_POV; objectInfo->dwType = DIDFT_POV | DIDFT_MAKEINSTANCE(0); objectInfo->dwFlags = DIDOI_POLLED; break; } // DirectInput versions 5 and higher include extra members in this structure, and this is indicated on input using the size member of the structure. if (objectInfo->dwSize > sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)) { // These fields are zeroed out because Xidi does not currently offer any of the functionality they represent. objectInfo->dwFFMaxForce = 0; objectInfo->dwFFForceResolution = 0; objectInfo->wCollectionNumber = 0; objectInfo->wDesignatorIndex = 0; objectInfo->wUsagePage = 0; objectInfo->wUsage = 0; objectInfo->dwDimension = 0; objectInfo->wExponent = 0; objectInfo->wReportId = 0; } } /// Signals the specified event if its handle is valid. /// @param [in] eventHandle Handle that can be used to identify the desired event object. static inline void SignalEventIfEnabled(HANDLE eventHandle) { if ((NULL != eventHandle) && (INVALID_HANDLE_VALUE != eventHandle)) SetEvent(eventHandle); } // -------- CONSTRUCTION AND DESTRUCTION ------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> VirtualDirectInputDevice<charMode>::VirtualDirectInputDevice(std::unique_ptr<Controller::VirtualController>&& controller) : controller(std::move(controller)), dataFormat(), refCount(1), stateChangeEventHandle(NULL) { // Nothing to do here. } // -------- INSTANCE METHODS ------------------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> std::optional<Controller::SElementIdentifier> VirtualDirectInputDevice<charMode>::IdentifyElement(DWORD dwObj, DWORD dwHow) const { switch (dwHow) { case DIPH_DEVICE: // Whole device is referenced. // Per DirectInput documentation, the object identifier must be 0. if (0 == dwObj) return Controller::SElementIdentifier({.type = Controller::EElementType::WholeController}); break; case DIPH_BYOFFSET: // Controller element is being identified by offset. // Object identifier is an offset into the application's data format. if (true == IsApplicationDataFormatSet()) return dataFormat->GetElementForOffset(dwObj); break; case DIPH_BYID: // Controller element is being identified by instance identifier. // Object identifier contains type and index, and the latter refers to the controller's reported capabilities. if ((unsigned int)DIDFT_GETINSTANCE(dwObj) >= 0) { const unsigned int kType = (unsigned int)DIDFT_GETTYPE(dwObj); const unsigned int kIndex = (unsigned int)DIDFT_GETINSTANCE(dwObj); switch (kType) { case DIDFT_ABSAXIS: if ((kIndex < (unsigned int)Controller::EAxis::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numAxes)) return Controller::SElementIdentifier({.type = Controller::EElementType::Axis, .axis = controller->GetCapabilities().axisType[kIndex]}); break; case DIDFT_PSHBUTTON: if ((kIndex < (unsigned int)Controller::EButton::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numButtons)) return Controller::SElementIdentifier({.type = Controller::EElementType::Button, .button = (Controller::EButton)kIndex}); break; case DIDFT_POV: if (kIndex == 0) return Controller::SElementIdentifier({.type = Controller::EElementType::Pov}); break; } } break; } return std::nullopt; } // -------- METHODS: IUnknown ------------------------------------------ // // See IUnknown documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::QueryInterface(REFIID riid, LPVOID* ppvObj) { if (nullptr == ppvObj) return E_POINTER; bool validInterfaceRequested = false; if (ECharMode::W == charMode) { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8W)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7W) || IsEqualIID(riid, IID_IDirectInputDevice2W) || IsEqualIID(riid, IID_IDirectInputDeviceW)) #endif validInterfaceRequested = true; } else { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8A)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7A) || IsEqualIID(riid, IID_IDirectInputDevice2A) || IsEqualIID(riid, IID_IDirectInputDeviceA)) #endif validInterfaceRequested = true; } if (true == validInterfaceRequested) { AddRef(); *ppvObj = this; return S_OK; } return E_NOINTERFACE; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::AddRef(void) { return ++refCount; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::Release(void) { const unsigned long numRemainingRefs = --refCount; if (0 == numRemainingRefs) delete this; return (ULONG)numRemainingRefs; } // -------- METHODS: IDirectInputDevice COMMON ------------------------- // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Acquire(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; // Controller acquisition is a no-op for Xidi virtual controllers. // However, DirectInput documentation requires that the application data format already be set. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::CreateEffect(REFGUID rguid, LPCDIEFFECT lpeff, LPDIRECTINPUTEFFECT* ppdeff, LPUNKNOWN punkOuter) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumCreatedEffectObjects(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback, LPVOID pvRef, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffects(DirectInputDeviceType<charMode>::EnumEffectsCallbackType lpCallback, LPVOID pvRef, DWORD dwEffType) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffectsInFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, LPDIENUMEFFECTSINFILECALLBACK pec, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumObjects(DirectInputDeviceType<charMode>::EnumObjectsCallbackType lpCallback, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; const bool willEnumerateAxes = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_ABSAXIS))); const bool willEnumerateButtons = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_PSHBUTTON))); const bool willEnumeratePov = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_POV))); if (nullptr == lpCallback) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if ((true == willEnumerateAxes) || (true == willEnumerateButtons) || (true == willEnumeratePov)) { std::unique_ptr<DirectInputDeviceType<charMode>::DeviceObjectInstanceType> objectDescriptor = std::make_unique<DirectInputDeviceType<charMode>::DeviceObjectInstanceType>(); const Controller::SCapabilities controllerCapabilities = controller->GetCapabilities(); if (true == willEnumerateAxes) { for (int i = 0; i < controllerCapabilities.numAxes; ++i) { const Controller::EAxis kAxis = controllerCapabilities.axisType[i]; const Controller::SElementIdentifier kAxisIdentifier = {.type = Controller::EElementType::Axis, .axis = kAxis}; const TOffset kAxisOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kAxisIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kAxisIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kAxisIdentifier, kAxisOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumerateButtons) { for (int i = 0; i < controllerCapabilities.numButtons; ++i) { const Controller::EButton kButton = (Controller::EButton)i; const Controller::SElementIdentifier kButtonIdentifier = {.type = Controller::EElementType::Button, .button = kButton}; const TOffset kButtonOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kButtonIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kButtonIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kButtonIdentifier, kButtonOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumeratePov) { if (true == controllerCapabilities.hasPov) { const Controller::SElementIdentifier kPovIdentifier = {.type = Controller::EElementType::Pov}; const TOffset kPovOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kPovIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kPovIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kPovIdentifier, kPovOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Escape(LPDIEFFESCAPE pesc) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetCapabilities(LPDIDEVCAPS lpDIDevCaps) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpDIDevCaps) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (lpDIDevCaps->dwSize) { case (sizeof(DIDEVCAPS)): // Force feedback information, only present in the latest version of the structure. lpDIDevCaps->dwFFSamplePeriod = 0; lpDIDevCaps->dwFFMinTimeResolution = 0; lpDIDevCaps->dwFirmwareRevision = 0; lpDIDevCaps->dwHardwareRevision = 0; lpDIDevCaps->dwFFDriverVersion = 0; case (sizeof(DIDEVCAPS_DX3)): // Top-level controller information is common to all virtual controllers. lpDIDevCaps->dwFlags = DIDC_ATTACHED | DIDC_EMULATED | DIDC_POLLEDDEVICE | DIDC_POLLEDDATAFORMAT; lpDIDevCaps->dwDevType = DINPUT_DEVTYPE_XINPUT_GAMEPAD; // Information about controller layout comes from controller capabilities. lpDIDevCaps->dwAxes = controller->GetCapabilities().numAxes; lpDIDevCaps->dwButtons = controller->GetCapabilities().numButtons; lpDIDevCaps->dwPOVs = ((true == controller->GetCapabilities().hasPov) ? 1 : 0); break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceData(DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; // DIDEVICEOBJECTDATA and DIDEVICEOBJECTDATA_DX3 are defined identically for all DirectInput versions below 8. // There is therefore no need to differentiate, as the distinction between "dinput" and "dinput8" takes care of it. if ((false == IsApplicationDataFormatSet()) || (nullptr == pdwInOut) || (sizeof(DIDEVICEOBJECTDATA) != cbObjectData)) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); switch (dwFlags) { case 0: case DIGDD_PEEK: break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); } if (false == controller->IsEventBufferEnabled()) LOG_INVOCATION_AND_RETURN(DIERR_NOTBUFFERED, kMethodSeverityForError); auto lock = controller->Lock(); const DWORD kNumEventsAffected = std::min(*pdwInOut, (DWORD)controller->GetEventBufferCount()); const bool kEventBufferOverflowed = controller->IsEventBufferOverflowed(); const bool kShouldPopEvents = (0 == (dwFlags & DIGDD_PEEK)); if (nullptr != rgdod) { for (DWORD i = 0; i < kNumEventsAffected; ++i) { const Controller::StateChangeEventBuffer::SEvent& event = controller->GetEventBufferEvent(i); ZeroMemory(&rgdod[i], sizeof(rgdod[i])); rgdod[i].dwOfs = dataFormat->GetOffsetForElement(event.data.element).value(); // A value should always be present. rgdod[i].dwTimeStamp = event.timestamp; rgdod[i].dwSequence = event.sequence; switch (event.data.element.type) { case Controller::EElementType::Axis: rgdod[i].dwData = (DWORD)DataFormat::DirectInputAxisValue(event.data.value.axis); break; case Controller::EElementType::Button: rgdod[i].dwData = (DWORD)DataFormat::DirectInputButtonValue(event.data.value.button); break; case Controller::EElementType::Pov: rgdod[i].dwData = (DWORD)DataFormat::DirectInputPovValue(event.data.value.povDirection); break; default: LOG_INVOCATION_AND_RETURN(DIERR_GENERIC, kMethodSeverityForError); // This should never happen. break; } } } if (true == kShouldPopEvents) controller->PopEventBufferOldestEvents(kNumEventsAffected); *pdwInOut = kNumEventsAffected; LOG_INVOCATION_AND_RETURN(((true == kEventBufferOverflowed) ? DI_BUFFEROVERFLOW : DI_OK), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceInfo(DirectInputDeviceType<charMode>::DeviceInstanceType* pdidi) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } FillVirtualControllerInfo(*pdidi, controller->GetIdentifier()); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceState(DWORD cbData, LPVOID lpvData) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; if ((nullptr == lpvData) || (false == IsApplicationDataFormatSet()) || (cbData < dataFormat->GetPacketSizeBytes())) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); bool writeDataPacketResult = false; do { auto lock = controller->Lock(); writeDataPacketResult = dataFormat->WriteDataPacket(lpvData, cbData, controller->GetStateRef()); } while (false); LOG_INVOCATION_AND_RETURN(((true == writeDataPacketResult) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetEffectInfo(DirectInputDeviceType<charMode>::EffectInfoType* pdei, REFGUID rguid) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetForceFeedbackState(LPDWORD pdwOut) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetObjectInfo(DirectInputDeviceType<charMode>::DeviceObjectInstanceType* pdidoi, DWORD dwObj, DWORD dwHow) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidoi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidoi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(dwObj, dwHow); if (false == maybeElement.has_value()) LOG_INVOCATION_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity); const Controller::SElementIdentifier element = maybeElement.value(); if (Controller::EElementType::WholeController == element.type) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); FillObjectInstanceInfo<charMode>(controller->GetCapabilities(), element, ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(element).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(element)), pdidoi); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetProperty(REFGUID rguidProp, LPDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, false); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (Controller::EElementType::WholeController != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = DIPROPAXISMODE_ABS; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetEventBufferCapacity(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisDeadzone(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_FFGAIN): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetForceFeedbackGain(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_GRANULARITY): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPDWORD)pdiph)->dwData = 1; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_JOYSTICKID): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetIdentifier(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPRANGE)pdiph)->lMin = Controller::kAnalogValueMin; ((LPDIPROPRANGE)pdiph)->lMax = Controller::kAnalogValueMax; LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): do { if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::pair kRange = controller->GetAxisRange(element.axis); ((LPDIPROPRANGE)pdiph)->lMin = kRange.first; ((LPDIPROPRANGE)pdiph)->lMax = kRange.second; } while (false); LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_SATURATION): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisSaturation(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Initialize(HINSTANCE hinst, DWORD dwVersion, REFGUID rguid) { // Not required for Xidi virtual controllers as they are implemented now. // However, this method is needed for creating IDirectInputDevice objects via COM. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Poll(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; // DirectInput documentation requires that the application data format already be set before a device can be polled. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if (true == controller->RefreshState()) SignalEventIfEnabled(stateChangeEventHandle); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::RunControlPanel(HWND hwndOwner, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendDeviceData(DWORD cbObjectData, LPCDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendForceFeedbackCommand(DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetCooperativeLevel(HWND hwnd, DWORD dwFlags) { // Presently this is a no-op. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetDataFormat(LPCDIDATAFORMAT lpdf) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpdf) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // If this operation fails, then the current data format and event filter remain unaltered. std::unique_ptr<DataFormat> newDataFormat = DataFormat::CreateFromApplicationFormatSpec(*lpdf, controller->GetCapabilities()); if (nullptr == newDataFormat) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // Use the event filter to prevent the controller from buffering any events that correspond to elements with no offsets. auto lock = controller->Lock(); controller->EventFilterAddAllElements(); for (int i = 0; i < (int)Controller::EAxis::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Axis, .axis = (Controller::EAxis)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } for (int i = 0; i < (int)Controller::EButton::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Button, .button = (Controller::EButton)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } do { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Pov}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } while (false); dataFormat = std::move(newDataFormat); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetEventNotification(HANDLE hEvent) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; stateChangeEventHandle = hEvent; LOG_INVOCATION_AND_RETURN(DI_POLLEDDEVICE, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetProperty(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, true); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (DIPROPAXISMODE_ABS == ((LPDIPROPDWORD)pdiph)->dwData) LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_PROPNOEFFECT, kMethodSeverity, rguidProp, pdiph); else LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetEventBufferCapacity(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisDeadzone(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisDeadzone(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_FFGAIN): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetForceFeedbackGain(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAxisRange(element.axis, ((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAllAxisRange(((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_SATURATION): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisSaturation(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisSaturation(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Unacquire(void) { // Controller acquisition is a no-op for Xidi virtual controllers. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::WriteEffectToFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, DWORD dwEntries, LPDIFILEEFFECT rgDiFileEft, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #if DIRECTINPUT_VERSION >= 0x0800 // -------- METHODS: IDirectInputDevice8 ONLY ------------------------------ // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::BuildActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiaf, DirectInputDeviceType<charMode>::ConstStringType lpszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetImageInfo(DirectInputDeviceType<charMode>::DeviceImageInfoHeaderType* lpdiDevImageInfoHeader) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiActionFormat, DirectInputDeviceType<charMode>::ConstStringType lptszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #endif // -------- EXPLICIT TEMPLATE INSTANTIATION ---------------------------- // // Instantiates both the ASCII and Unicode versions of this class. template class VirtualDirectInputDevice<ECharMode::A>; template class VirtualDirectInputDevice<ECharMode::W>; }
47.354992
309
0.652555
hamzahamidi
04bc038e7a46f22a3c8533cca80fe11a4e90bb20
25,705
hpp
C++
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
pixowl/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
2
2019-12-05T20:43:33.000Z
2020-12-01T02:57:44.000Z
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
null
null
null
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
2
2020-05-10T08:41:12.000Z
2020-05-24T18:58:47.000Z
#ifndef ENTT_ENTITY_SNAPSHOT_HPP #define ENTT_ENTITY_SNAPSHOT_HPP #include "../../TinySTL/array.h" #include <cstddef> #include <utility> #include <cassert> #include <iterator> #include <type_traits> #include "../../TinySTL/unordered_map.h" #include "../config/config.h" #include "entt_traits.hpp" #include "utility.hpp" namespace entt { /** * @brief Forward declaration of the registry class. */ template<typename> class Registry; /** * @brief Utility class to create snapshots from a registry. * * A _snapshot_ can be either a dump of the entire registry or a narrower * selection of components and tags of interest.<br/> * This type can be used in both cases if provided with a correctly configured * output archive. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class Snapshot final { /*! @brief A registry is allowed to create snapshots. */ friend class Registry<Entity>; using follow_fn_type = Entity(const Registry<Entity> &, const Entity); Snapshot(const Registry<Entity> &registry, Entity seed, follow_fn_type *follow) ENTT_NOEXCEPT : registry{registry}, seed{seed}, follow{follow} {} template<typename Component, typename Archive, typename It> void get(Archive &archive, size_t sz, It first, It last) const { archive(static_cast<Entity>(sz)); while(first != last) { const auto entity = *(first++); if(registry.template has<Component>(entity)) { archive(entity, registry.template get<Component>(entity)); } } } template<typename... Component, typename Archive, typename It, size_t... Indexes> void component(Archive &archive, It first, It last, std::index_sequence<Indexes...>) const { tinystl::array<size_t, sizeof...(Indexes)> size{}; auto begin = first; while(begin != last) { const auto entity = *(begin++); using accumulator_type = size_t[]; accumulator_type accumulator = { (registry.template has<Component>(entity) ? ++size[Indexes] : size[Indexes])... }; (void)accumulator; } using accumulator_type = int[]; accumulator_type accumulator = { (get<Component>(archive, size[Indexes], first, last), 0)... }; (void)accumulator; } public: /*! @brief Copying a snapshot isn't allowed. */ Snapshot(const Snapshot &) = delete; /*! @brief Default move constructor. */ Snapshot(Snapshot &&) = default; /*! @brief Copying a snapshot isn't allowed. @return This snapshot. */ Snapshot & operator=(const Snapshot &) = delete; /*! @brief Default move assignment operator. @return This snapshot. */ Snapshot & operator=(Snapshot &&) = default; /** * @brief Puts aside all the entities that are still in use. * * Entities are serialized along with their versions. Destroyed entities are * not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & entities(Archive &archive) const { archive(static_cast<Entity>(registry.alive())); registry.each([&archive](const auto entity) { archive(entity); }); return *this; } /** * @brief Puts aside destroyed entities. * * Entities are serialized along with their versions. Entities that are * still in use are not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & destroyed(Archive &archive) const { auto size = registry.size() - registry.alive(); archive(static_cast<Entity>(size)); if(size) { auto curr = seed; archive(curr); for(--size; size; --size) { curr = follow(registry, curr); archive(curr); } } return *this; } /** * @brief Puts aside the given component. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Type of component to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Component, typename Archive> const Snapshot & component(Archive &archive) const { const auto sz = registry.template size<Component>(); const auto *entities = registry.template data<Component>(); archive(static_cast<Entity>(sz)); for(std::remove_const_t<decltype(sz)> i{}; i < sz; ++i) { const auto entity = entities[i]; archive(entity, registry.template get<Component>(entity)); }; return *this; } /** * @brief Puts aside the given components. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive> std::enable_if_t<(sizeof...(Component) > 1), const Snapshot &> component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (component<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Puts aside the given components for the entities in a range. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @tparam It Type of input iterator. * @param archive A valid reference to an output archive. * @param first An iterator to the first element of the range to serialize. * @param last An iterator past the last element of the range to serialize. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive, typename It> const Snapshot & component(Archive &archive, It first, It last) const { component<Component...>(archive, first, last, std::make_index_sequence<sizeof...(Component)>{}); return *this; } /** * @brief Puts aside the given tag. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Type of tag to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Tag, typename Archive> const Snapshot & tag(Archive &archive) const { const bool has = registry.template has<Tag>(); // numerical length is forced for tags to facilitate loading archive(has ? Entity(1): Entity{}); if(has) { archive(registry.template attachee<Tag>(), registry.template get<Tag>()); } return *this; } /** * @brief Puts aside the given tags. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Types of tags to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Tag, typename Archive> std::enable_if_t<(sizeof...(Tag) > 1), const Snapshot &> tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (tag<Tag>(archive), 0)... }; (void)accumulator; return *this; } private: const Registry<Entity> &registry; const Entity seed; follow_fn_type *follow; }; /** * @brief Utility class to restore a snapshot as a whole. * * A snapshot loader requires that the destination registry be empty and loads * all the data at once while keeping intact the identifiers that the entities * originally had.<br/> * An example of use is the implementation of a save/restore utility. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class SnapshotLoader final { /*! @brief A registry is allowed to create snapshot loaders. */ friend class Registry<Entity>; using assure_fn_type = void(Registry<Entity> &, const Entity, const bool); SnapshotLoader(Registry<Entity> &registry, assure_fn_type *assure_fn) ENTT_NOEXCEPT : registry{registry}, assure_fn{assure_fn} { // restore a snapshot as a whole requires a clean registry assert(!registry.capacity()); } template<typename Archive> void assure(Archive &archive, bool destroyed) const { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); assure_fn(registry, entity, destroyed); } } template<typename Type, typename Archive, typename... Args> void assign(Archive &archive, Args... args) const { Entity length{}; archive(length); while(length--) { Entity entity{}; Type instance{}; archive(entity, instance); static constexpr auto destroyed = false; assure_fn(registry, entity, destroyed); registry.template assign<Type>(args..., entity, static_cast<const Type &>(instance)); } } public: /*! @brief Copying a snapshot loader isn't allowed. */ SnapshotLoader(const SnapshotLoader &) = delete; /*! @brief Default move constructor. */ SnapshotLoader(SnapshotLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ SnapshotLoader & operator=(const SnapshotLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ SnapshotLoader & operator=(SnapshotLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & entities(Archive &archive) const { static constexpr auto destroyed = false; assure(archive, destroyed); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & destroyed(Archive &archive) const { static constexpr auto destroyed = true; assure(archive, destroyed); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create it with * the version it originally had. * * @tparam Component Types of components to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Component, typename Archive> const SnapshotLoader & component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create it with the * version it originally had. * * @tparam Tag Types of tags to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Tag, typename Archive> const SnapshotLoader & tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Tag>(archive, tag_t{}), 0)... }; (void)accumulator; return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A valid loader to continue restoring data. */ const SnapshotLoader & orphans() const { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } private: Registry<Entity> &registry; assure_fn_type *assure_fn; }; /** * @brief Utility class for _continuous loading_. * * A _continuous loader_ is designed to load data from a source registry to a * (possibly) non-empty destination. The loader can accomodate in a registry * more than one snapshot in a sort of _continuous loading_ that updates the * destination one step at a time.<br/> * Identifiers that entities originally had are not transferred to the target. * Instead, the loader maps remote identifiers to local ones while restoring a * snapshot.<br/> * An example of use is the implementation of a client-server applications with * the requirement of transferring somehow parts of the representation side to * side. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class ContinuousLoader final { using traits_type = entt_traits<Entity>; void destroy(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); registry.destroy(local); } } void restore(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); } else { remloc[entity].first = registry.valid(remloc[entity].first) ? remloc[entity].first : registry.create(); // set the dirty flag remloc[entity].second = true; } } template<typename Type, typename Member> std::enable_if_t<std::is_same<Member, Entity>::value> update(Type &instance, Member Type:: *member) { instance.*member = map(instance.*member); } template<typename Type, typename Member> std::enable_if_t<std::is_same<typename std::iterator_traits<typename Member::iterator>::value_type, Entity>::value> update(Type &instance, Member Type:: *member) { for(auto &entity: instance.*member) { entity = map(entity); } } template<typename Other, typename Type, typename Member> std::enable_if_t<!std::is_same<Other, Type>::value> update(Other &, Member Type:: *) {} template<typename Archive> void assure(Archive &archive, void(ContinuousLoader:: *member)(Entity)) { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); (this->*member)(entity); } } template<typename Component> void reset() { for(auto &&ref: remloc) { const auto local = ref.second.first; if(registry.valid(local)) { registry.template reset<Component>(local); } } } template<typename Other, typename Archive, typename Func, typename... Type, typename... Member> void assign(Archive &archive, Func func, Member Type:: *... member) { Entity length{}; archive(length); while(length--) { Entity entity{}; Other instance{}; archive(entity, instance); restore(entity); using accumulator_type = int[]; accumulator_type accumulator = { 0, (update(instance, member), 0)... }; (void)accumulator; func(map(entity), instance); } } public: /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Constructs a loader that is bound to a given registry. * @param registry A valid reference to a registry. */ ContinuousLoader(Registry<entity_type> &registry) ENTT_NOEXCEPT : registry{registry} {} /*! @brief Copying a snapshot loader isn't allowed. */ ContinuousLoader(const ContinuousLoader &) = delete; /*! @brief Default move constructor. */ ContinuousLoader(ContinuousLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ ContinuousLoader & operator=(const ContinuousLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ ContinuousLoader & operator=(ContinuousLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & entities(Archive &archive) { assure(archive, &ContinuousLoader::restore); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & destroyed(Archive &archive) { assure(archive, &ContinuousLoader::destroy); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Component Type of component to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Component, typename Archive, typename... Type, typename... Member> ContinuousLoader & component(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &component) { registry.template accommodate<std::decay_t<decltype(component)>>(entity, component); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (reset<Component>(), assign<Component>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Tag Type of tag to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Tag, typename Archive, typename... Type, typename... Member> ContinuousLoader & tag(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &tag) { registry.template assign<std::decay_t<decltype(tag)>>(tag_t{}, entity, tag); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (registry.template remove<Tag>(), assign<Tag>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Helps to purge entities that no longer have a conterpart. * * Users should invoke this member function after restoring each snapshot, * unless they know exactly what they are doing. * * @return A non-const reference to this loader. */ ContinuousLoader & shrink() { auto it = remloc.begin(); while(it != remloc.cend()) { const auto local = it->second.first; bool &dirty = it->second.second; if(dirty) { dirty = false; ++it; } else { if(registry.valid(local)) { registry.destroy(local); } it = remloc.erase(it); } } return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A non-const reference to this loader. */ ContinuousLoader & orphans() { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } /** * @brief Tests if a loader knows about a given entity. * @param entity An entity identifier. * @return True if `entity` is managed by the loader, false otherwise. */ bool has(entity_type entity) const ENTT_NOEXCEPT { return (remloc.find(entity) != remloc.cend()); } /** * @brief Returns the identifier to which an entity refers. * * @warning * Attempting to use an entity that isn't managed by the loader results in * undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * loader doesn't knows about the entity. * * @param entity An entity identifier. * @return The identifier to which `entity` refers in the target registry. */ entity_type map(entity_type entity) const ENTT_NOEXCEPT { assert(has(entity)); return remloc.find(entity)->second.first; } private: tinystl::unordered_map<Entity, tinystl::pair<Entity, bool>> remloc; Registry<Entity> &registry; }; } #endif // ENTT_ENTITY_SNAPSHOT_HPP
35.455172
127
0.642482
pixowl
04bc831052d4cdf3976f4c818e371795872dbb1e
21,081
hpp
C++
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
13
2022-01-17T12:01:48.000Z
2022-03-16T10:03:14.000Z
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
163
2022-01-17T17:36:45.000Z
2022-03-31T17:42:57.000Z
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
4
2022-01-19T08:44:22.000Z
2022-01-31T23:16:21.000Z
// Copyright (c) 2007-2021 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <pika/config.hpp> #include <pika/allocator_support/internal_allocator.hpp> #include <pika/async_base/dataflow.hpp> #include <pika/async_base/launch_policy.hpp> #include <pika/async_base/traits/is_launch_policy.hpp> #include <pika/coroutines/detail/get_stack_pointer.hpp> #include <pika/datastructures/tuple.hpp> #include <pika/errors/try_catch_exception_ptr.hpp> #include <pika/execution/executors/execution.hpp> #include <pika/execution_base/traits/is_executor.hpp> #include <pika/executors/parallel_executor.hpp> #include <pika/functional/deferred_call.hpp> #include <pika/functional/invoke_fused.hpp> #include <pika/functional/traits/get_function_annotation.hpp> #include <pika/functional/traits/is_action.hpp> #include <pika/futures/detail/future_transforms.hpp> #include <pika/futures/future.hpp> #include <pika/futures/traits/acquire_future.hpp> #include <pika/futures/traits/future_access.hpp> #include <pika/futures/traits/is_future.hpp> #include <pika/modules/memory.hpp> #include <pika/pack_traversal/pack_traversal_async.hpp> #include <pika/threading_base/annotated_function.hpp> #include <pika/threading_base/thread_num_tss.hpp> #include <cstddef> #include <exception> #include <functional> #include <memory> #include <type_traits> #include <utility> /////////////////////////////////////////////////////////////////////////////// // forward declare the type we will get function annotations from namespace pika::detail { template <typename Frame> struct dataflow_finalization; } // namespace pika::lcos::detail namespace pika { namespace traits { #if defined(PIKA_HAVE_THREAD_DESCRIPTION) /////////////////////////////////////////////////////////////////////////// // traits specialization to get annotation from dataflow_finalization template <typename Frame> struct get_function_annotation<pika::detail::dataflow_finalization<Frame>> { using function_type = typename Frame::function_type; // static constexpr char const* call( pika::detail::dataflow_finalization<Frame> const& f) noexcept { char const* annotation = pika::traits::get_function_annotation< typename std::decay<function_type>::type>::call(f.this_->func_); return annotation; } }; #endif }} // namespace pika::traits /////////////////////////////////////////////////////////////////////////////// namespace pika::detail { template <typename Frame> struct dataflow_finalization { // explicit dataflow_finalization(Frame* df) : this_(df) { } using is_void = typename Frame::is_void; // template <typename Futures> void operator()(Futures&& futures) const { return this_->execute(is_void{}, PIKA_FORWARD(Futures, futures)); } // keep the dataflow frame alive with this pointer reference pika::intrusive_ptr<Frame> this_; }; template <typename F, typename Args> struct dataflow_not_callable { static auto error(F f, Args args) { pika::util::invoke_fused(PIKA_MOVE(f), PIKA_MOVE(args)); } using type = decltype(error(std::declval<F>(), std::declval<Args>())); }; /////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename F, typename Args, typename Enable = void> struct dataflow_return_impl { using type = typename dataflow_not_callable<F, Args>::type; }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { using type = pika::future< typename util::detail::invoke_fused_result<F, Args>::type>; }; template <typename Executor, typename F, typename Args> struct dataflow_return_impl_executor; template <typename Executor, typename F, typename... Ts> struct dataflow_return_impl_executor<Executor, F, pika::tuple<Ts...>> { using type = decltype(pika::parallel::execution::async_execute( std::declval<Executor&&>(), std::declval<F>(), std::declval<Ts>()...)); }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if<traits::is_one_way_executor<Policy>::value || traits::is_two_way_executor<Policy>::value>::type> : dataflow_return_impl_executor<Policy, F, Args> { }; template <typename Policy, typename F, typename Args> struct dataflow_return : detail::dataflow_return_impl<traits::is_action<F>::value, Policy, F, Args> { }; template <typename Executor, typename Frame, typename Func, typename Futures, typename Enable = void> struct has_dataflow_finalize : std::false_type { }; template <typename Executor, typename Frame, typename Func, typename Futures> struct has_dataflow_finalize<Executor, Frame, Func, Futures, std::void_t<decltype(std::declval<Executor>().dataflow_finalize( std::declval<Frame>(), std::declval<Func>(), std::declval<Futures>()))>> : std::true_type { }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename Futures> struct dataflow_frame //-V690 : pika::lcos::detail::future_data<typename pika::traits::future_traits< typename detail::dataflow_return<Policy, Func, Futures>::type>::type> { using type = typename detail::dataflow_return<Policy, Func, Futures>::type; using result_type = typename pika::traits::future_traits<type>::type; using base_type = pika::lcos::detail::future_data<result_type>; using is_void = std::is_void<result_type>; using function_type = Func; using dataflow_type = dataflow_frame<Policy, Func, Futures>; friend struct dataflow_finalization<dataflow_type>; friend struct traits::get_function_annotation< dataflow_finalization<dataflow_type>>; private: // workaround gcc regression wrongly instantiating constructors dataflow_frame(); dataflow_frame(dataflow_frame const&); public: using init_no_addref = typename base_type::init_no_addref; /// A struct to construct the dataflow_frame in-place struct construction_data { Policy policy_; Func func_; }; /// Construct the dataflow_frame from the given policy /// and callable object. static construction_data construct_from(Policy policy, Func func) { return construction_data{PIKA_MOVE(policy), PIKA_MOVE(func)}; } explicit dataflow_frame(construction_data data) : base_type(init_no_addref{}) , policy_(PIKA_MOVE(data.policy_)) , func_(PIKA_MOVE(data.func_)) { } private: /////////////////////////////////////////////////////////////////////// /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::false_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { this->set_data(util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures))); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::true_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); this->set_data(util::unused_type()); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /////////////////////////////////////////////////////////////////////// template <typename Futures_> void finalize(pika::detail::async_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::async_policy> exec{policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> void finalize(pika::detail::fork_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::fork_policy> exec{ policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> PIKA_FORCEINLINE void finalize( pika::detail::sync_policy, Futures_&& futures) { // We need to run the completion on a new thread if we are on a // non pika thread. bool recurse_asynchronously = pika::threads::get_self_ptr() == nullptr; #if defined(PIKA_HAVE_THREADS_GET_STACK_POINTER) recurse_asynchronously = !this_thread::has_sufficient_stack_space(); #else struct handle_continuation_recursion_count { handle_continuation_recursion_count() : count_(threads::get_continuation_recursion_count()) { ++count_; } ~handle_continuation_recursion_count() { --count_; } std::size_t& count_; } cnt; recurse_asynchronously = recurse_asynchronously || cnt.count_ > PIKA_CONTINUATION_MAX_RECURSION_DEPTH; #endif if (!recurse_asynchronously) { pika::scoped_annotation annotate(func_); execute(is_void{}, PIKA_FORWARD(Futures_, futures)); } else { finalize(pika::launch::async, PIKA_FORWARD(Futures_, futures)); } } template <typename Futures_> void finalize(launch policy, Futures_&& futures) { if (policy == launch::sync) { finalize(launch::sync, PIKA_FORWARD(Futures_, futures)); } else if (policy == launch::fork) { finalize(launch::fork, PIKA_FORWARD(Futures_, futures)); } else { finalize(launch::async, PIKA_FORWARD(Futures_, futures)); } } // The overload for pika::dataflow taking an executor simply forwards // to the corresponding executor customization point. template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && !has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::parallel::execution::post(PIKA_FORWARD(Executor, exec), PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { #if defined(PIKA_CUDA_VERSION) std::forward<Executor>(exec) #else PIKA_FORWARD(Executor, exec) #endif .dataflow_finalize( this, PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); } public: /// Check whether the current future is ready template <typename T> auto operator()(util::async_traverse_visit_tag, T&& current) -> decltype(async_visit_future(PIKA_FORWARD(T, current))) { return async_visit_future(PIKA_FORWARD(T, current)); } /// Detach the current execution context and continue when the /// current future was set to be ready. template <typename T, typename N> auto operator()(util::async_traverse_detach_tag, T&& current, N&& next) -> decltype(async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next))) { return async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next)); } /// Finish the dataflow when the traversal has finished template <typename Futures_> PIKA_FORCEINLINE void operator()( util::async_traverse_complete_tag, Futures_&& futures) { finalize(policy_, PIKA_FORWARD(Futures_, futures)); } private: Policy policy_; Func func_; }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow( Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async( util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <typename Allocator, typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow_alloc( Allocator const& alloc, Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async_allocator( alloc, util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename Enable = void> struct dataflow_dispatch_impl; // launch template <typename Policy> struct dataflow_dispatch_impl<false, Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename Policy_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Policy_&& policy, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Policy_, policy), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; template <typename Policy> struct dataflow_dispatch<Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } template <typename Allocator, typename P, typename F, typename Id, typename... Ts> PIKA_FORCEINLINE static auto call(Allocator const& alloc, P&& p, F&& f, typename std::enable_if< traits::is_action<typename std::decay<F>::type>::value, Id>::type const& id, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...); } }; // executors template <typename Executor> struct dataflow_dispatch<Executor, typename std::enable_if<traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value>::type> { template <typename Allocator, typename Executor_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Executor_&& exec, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Executor_, exec), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; // any action, plain function, or function object template <typename FD> struct dataflow_dispatch_impl<false, FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts, typename Enable = typename std::enable_if< !traits::is_action<typename std::decay<F>::type>::value>::type> PIKA_FORCEINLINE static auto call(Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; template <typename FD> struct dataflow_dispatch<FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; } // namespace pika::detail
38.468978
80
0.590342
pika-org
04c38aa757ac89e639ef2dc40de352a9681f2ef4
1,509
cpp
C++
Sources/Kore/Display.cpp
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
203
2019-05-30T22:40:19.000Z
2022-03-16T22:01:09.000Z
Sources/Kore/Display.cpp
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
136
2019-06-01T04:39:33.000Z
2022-03-14T12:38:03.000Z
Sources/Kore/Display.cpp
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
211
2019-06-05T12:22:57.000Z
2022-03-24T08:44:18.000Z
#include "Display.h" #include <kinc/display.h> using namespace Kore; namespace { const int MAXIMUM_DISPLAYS = 16; Display displays[MAXIMUM_DISPLAYS]; } void Display::init() { kinc_display_init(); } Display *Display::primary() { displays[kinc_primary_display()]._index = kinc_primary_display(); return &displays[kinc_primary_display()]; } Display *Display::get(int index) { displays[index]._index = index; return &displays[index]; } int Display::count() { return kinc_count_displays(); } bool Display::available() { return kinc_display_available(_index); } const char *Display::name() { return kinc_display_name(_index); } int Display::x() { return kinc_display_current_mode(_index).x; } int Display::y() { return kinc_display_current_mode(_index).y; } int Display::width() { return kinc_display_current_mode(_index).width; } int Display::height() { return kinc_display_current_mode(_index).height; } int Display::frequency() { return kinc_display_current_mode(_index).frequency; } int Display::pixelsPerInch() { return kinc_display_current_mode(_index).pixels_per_inch; } DisplayMode Display::availableMode(int index) { DisplayMode mode; kinc_display_mode_t kMode = kinc_display_available_mode(_index, index); mode.width = kMode.width; mode.height = kMode.height; mode.frequency = kMode.frequency; mode.bitsPerPixel = kMode.bits_per_pixel; return mode; } int Display::countAvailableModes() { return kinc_display_count_available_modes(_index); } Display::Display() {}
19.597403
72
0.75613
foundry2D
04c6e26e243767d876a118491c35ca4de1595f39
32,524
cpp
C++
miniapps/meshing/mesh-explorer.cpp
liruipeng/mfem
bf3f1f1327f064baae40693256c9559feae1a99a
[ "BSD-3-Clause" ]
null
null
null
miniapps/meshing/mesh-explorer.cpp
liruipeng/mfem
bf3f1f1327f064baae40693256c9559feae1a99a
[ "BSD-3-Clause" ]
1
2020-04-21T00:30:35.000Z
2020-04-21T00:32:28.000Z
miniapps/meshing/mesh-explorer.cpp
liruipeng/mfem
bf3f1f1327f064baae40693256c9559feae1a99a
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // // ----------------------------------------------------- // Mesh Explorer Miniapp: Explore and manipulate meshes // ----------------------------------------------------- // // This miniapp is a handy tool to examine, visualize and manipulate a given // mesh. Some of its features are: // // - visualizing of mesh materials and individual mesh elements // - mesh scaling, randomization, and general transformation // - manipulation of the mesh curvature // - the ability to simulate parallel partitioning // - quantitative and visual reports of mesh quality // // Compile with: make mesh-explorer // // Sample runs: mesh-explorer // mesh-explorer -m ../../data/beam-tri.mesh // mesh-explorer -m ../../data/star-q2.mesh // mesh-explorer -m ../../data/disc-nurbs.mesh // mesh-explorer -m ../../data/escher-p3.mesh // mesh-explorer -m ../../data/mobius-strip.mesh #include "mfem.hpp" #include <fstream> #include <limits> #include <cstdlib> using namespace mfem; using namespace std; // This transformation can be applied to a mesh with the 't' menu option. void transformation(const Vector &p, Vector &v) { // simple shear transformation double s = 0.1; if (p.Size() == 3) { v(0) = p(0) + s*p(1) + s*p(2); v(1) = p(1) + s*p(2) + s*p(0); v(2) = p(2); } else if (p.Size() == 2) { v(0) = p(0) + s*p(1); v(1) = p(1) + s*p(0); } else { v = p; } } // This function is used with the 'r' menu option, sub-option 'l' to refine a // mesh locally in a region, defined by return values <= region_eps. double region_eps = 1e-8; double region(const Vector &p) { const double x = p(0), y = p(1); // here we describe the region: (x <= 1/4) && (y >= 0) && (y <= 1) return std::max(std::max(x - 0.25, -y), y - 1.0); } // The projection of this function can be plotted with the 'l' menu option double f(const Vector &p) { double x = p(0); double y = p.Size() > 1 ? p(1) : 0.0; double z = p.Size() > 2 ? p(2) : 0.0; if (1) { // torus in the xy-plane const double r_big = 2.0; const double r_small = 1.0; return hypot(r_big - hypot(x, y), z) - r_small; } if (0) { // sphere at the origin: const double r = 1.0; return hypot(hypot(x, y), z) - r; } } Mesh *read_par_mesh(int np, const char *mesh_prefix) { Mesh *mesh; Array<Mesh *> mesh_array; mesh_array.SetSize(np); for (int p = 0; p < np; p++) { ostringstream fname; fname << mesh_prefix << '.' << setfill('0') << setw(6) << p; ifgzstream meshin(fname.str().c_str()); if (!meshin) { cerr << "Can not open mesh file: " << fname.str().c_str() << '!' << endl; for (p--; p >= 0; p--) { delete mesh_array[p]; } return NULL; } mesh_array[p] = new Mesh(meshin, 1, 0); // set element and boundary attributes to be the processor number + 1 if (1) { for (int i = 0; i < mesh_array[p]->GetNE(); i++) { mesh_array[p]->GetElement(i)->SetAttribute(p+1); } for (int i = 0; i < mesh_array[p]->GetNBE(); i++) { mesh_array[p]->GetBdrElement(i)->SetAttribute(p+1); } } } mesh = new Mesh(mesh_array, np); for (int p = 0; p < np; p++) { delete mesh_array[np-1-p]; } mesh_array.DeleteAll(); return mesh; } // Given a 3D mesh, produce a 2D mesh consisting of its boundary elements. Mesh *skin_mesh(Mesh *mesh) { // Determine mapping from vertex to boundary vertex Array<int> v2v(mesh->GetNV()); v2v = -1; for (int i = 0; i < mesh->GetNBE(); i++) { Element *el = mesh->GetBdrElement(i); int *v = el->GetVertices(); int nv = el->GetNVertices(); for (int j = 0; j < nv; j++) { v2v[v[j]] = 0; } } int nbvt = 0; for (int i = 0; i < v2v.Size(); i++) { if (v2v[i] == 0) { v2v[i] = nbvt++; } } // Create a new mesh for the boundary Mesh * bmesh = new Mesh(mesh->Dimension() - 1, nbvt, mesh->GetNBE(), 0, mesh->SpaceDimension()); // Copy vertices to the boundary mesh nbvt = 0; for (int i = 0; i < v2v.Size(); i++) { if (v2v[i] >= 0) { double *c = mesh->GetVertex(i); bmesh->AddVertex(c); nbvt++; } } // Copy elements to the boundary mesh int bv[4]; for (int i = 0; i < mesh->GetNBE(); i++) { Element *el = mesh->GetBdrElement(i); int *v = el->GetVertices(); int nv = el->GetNVertices(); for (int j = 0; j < nv; j++) { bv[j] = v2v[v[j]]; } switch (el->GetGeometryType()) { case Geometry::SEGMENT: bmesh->AddSegment(bv, el->GetAttribute()); break; case Geometry::TRIANGLE: bmesh->AddTriangle(bv, el->GetAttribute()); break; case Geometry::SQUARE: bmesh->AddQuad(bv, el->GetAttribute()); break; default: break; /// This should not happen } } bmesh->FinalizeTopology(); // Copy GridFunction describing nodes if present if (mesh->GetNodes()) { FiniteElementSpace *fes = mesh->GetNodes()->FESpace(); const FiniteElementCollection *fec = fes->FEColl(); if (dynamic_cast<const H1_FECollection*>(fec)) { FiniteElementCollection *fec_copy = FiniteElementCollection::New(fec->Name()); FiniteElementSpace *fes_copy = new FiniteElementSpace(*fes, bmesh, fec_copy); GridFunction *bdr_nodes = new GridFunction(fes_copy); bdr_nodes->MakeOwner(fec_copy); bmesh->NewNodes(*bdr_nodes, true); Array<int> vdofs; Array<int> bvdofs; Vector v; for (int i=0; i<mesh->GetNBE(); i++) { fes->GetBdrElementVDofs(i, vdofs); mesh->GetNodes()->GetSubVector(vdofs, v); fes_copy->GetElementVDofs(i, bvdofs); bdr_nodes->SetSubVector(bvdofs, v); } } else { cout << "\nDiscontinuous nodes not yet supported" << endl; } } return bmesh; } int main (int argc, char *argv[]) { int np = 0; const char *mesh_file = "../../data/beam-hex.mesh"; bool refine = true; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to visualize."); args.AddOption(&np, "-np", "--num-proc", "Load mesh from multiple processors."); args.AddOption(&refine, "-ref", "--refinement", "-no-ref", "--no-refinement", "Prepare the mesh for refinement or not."); args.Parse(); if (!args.Good()) { if (!args.Help()) { args.PrintError(cout); cout << endl; } cout << "Visualize and manipulate a serial mesh:\n" << " mesh-explorer -m <mesh_file>\n" << "Visualize and manipulate a parallel mesh:\n" << " mesh-explorer -np <#proc> -m <mesh_prefix>\n" << endl << "All Options:\n"; args.PrintHelp(cout); return 1; } args.PrintOptions(cout); Mesh *mesh; Mesh *bdr_mesh = NULL; if (np <= 0) { mesh = new Mesh(mesh_file, 1, refine); } else { mesh = read_par_mesh(np, mesh_file); if (mesh == NULL) { return 3; } } int dim = mesh->Dimension(); int sdim = mesh->SpaceDimension(); FiniteElementCollection *bdr_attr_fec = NULL; FiniteElementCollection *attr_fec; if (dim == 2) { attr_fec = new Const2DFECollection; } else { bdr_attr_fec = new Const2DFECollection; attr_fec = new Const3DFECollection; } int print_char = 1; while (1) { if (print_char) { cout << endl; mesh->PrintCharacteristics(); cout << "boundary attribs :"; for (int i = 0; i < mesh->bdr_attributes.Size(); i++) { cout << ' ' << mesh->bdr_attributes[i]; } cout << '\n' << "material attribs :"; for (int i = 0; i < mesh->attributes.Size(); i++) { cout << ' ' << mesh->attributes[i]; } cout << endl; cout << "mesh curvature : "; if (mesh->GetNodalFESpace() != NULL) { cout << mesh->GetNodalFESpace()->FEColl()->Name() << endl; } else { cout << "NONE" << endl; } } print_char = 0; cout << endl; cout << "What would you like to do?\n" "r) Refine\n" "c) Change curvature\n" "s) Scale\n" "t) Transform\n" "j) Jitter\n" "v) View\n" "m) View materials\n" "b) View boundary\n" "e) View elements\n" "h) View element sizes, h\n" "k) View element ratios, kappa\n" "l) Plot a function\n" "x) Print sub-element stats\n" "f) Find physical point in reference space\n" "p) Generate a partitioning\n" "o) Reorder elements\n" "S) Save in MFEM format\n" "V) Save in VTK format (only linear and quadratic meshes)\n" "q) Quit\n" #ifdef MFEM_USE_ZLIB "Z) Save in MFEM format with compression\n" #endif "--> " << flush; char mk; cin >> mk; if (!cin) { break; } if (mk == 'q') { break; } if (mk == 'r') { cout << "Choose type of refinement:\n" "s) standard refinement with Mesh::UniformRefinement()\n" "b) Mesh::UniformRefinement() (bisection for tet meshes)\n" "u) uniform refinement with a factor\n" "g) non-uniform refinement (Gauss-Lobatto) with a factor\n" "l) refine locally using the region() function\n" "--> " << flush; char sk; cin >> sk; switch (sk) { case 's': mesh->UniformRefinement(); // Make sure tet-only meshes are marked for local refinement. mesh->Finalize(true); break; case 'b': mesh->UniformRefinement(1); // ref_algo = 1 break; case 'u': case 'g': { cout << "enter refinement factor --> " << flush; int ref_factor; cin >> ref_factor; if (ref_factor <= 1 || ref_factor > 32) { break; } int ref_type = (sk == 'u') ? BasisType::ClosedUniform : BasisType::GaussLobatto; Mesh *rmesh = new Mesh(mesh, ref_factor, ref_type); delete mesh; mesh = rmesh; break; } case 'l': { Vector pt; Array<int> marked_elements; for (int i = 0; i < mesh->GetNE(); i++) { // check all nodes of the element IsoparametricTransformation T; mesh->GetElementTransformation(i, &T); for (int j = 0; j < T.GetPointMat().Width(); j++) { T.GetPointMat().GetColumnReference(j, pt); if (region(pt) <= region_eps) { marked_elements.Append(i); break; } } } mesh->GeneralRefinement(marked_elements); break; } } print_char = 1; } if (mk == 'c') { int p; cout << "enter new order for mesh curvature --> " << flush; cin >> p; mesh->SetCurvature(p > 0 ? p : -p, p <= 0); print_char = 1; } if (mk == 's') { double factor; cout << "scaling factor ---> " << flush; cin >> factor; GridFunction *nodes = mesh->GetNodes(); if (nodes == NULL) { for (int i = 0; i < mesh->GetNV(); i++) { double *v = mesh->GetVertex(i); v[0] *= factor; v[1] *= factor; if (dim == 3) { v[2] *= factor; } } } else { *nodes *= factor; } print_char = 1; } if (mk == 't') { mesh->Transform(transformation); print_char = 1; } if (mk == 'j') { double jitter; cout << "jitter factor ---> " << flush; cin >> jitter; GridFunction *nodes = mesh->GetNodes(); if (nodes == NULL) { cerr << "The mesh should have nodes, introduce curvature first!\n"; } else { FiniteElementSpace *fespace = nodes->FESpace(); GridFunction rdm(fespace); rdm.Randomize(); rdm -= 0.5; // shift to random values in [-0.5,0.5] rdm *= jitter; // compute minimal local mesh size Vector h0(fespace->GetNDofs()); h0 = infinity(); { Array<int> dofs; for (int i = 0; i < fespace->GetNE(); i++) { fespace->GetElementDofs(i, dofs); for (int j = 0; j < dofs.Size(); j++) { h0(dofs[j]) = std::min(h0(dofs[j]), mesh->GetElementSize(i)); } } } // scale the random values to be of order of the local mesh size for (int i = 0; i < fespace->GetNDofs(); i++) { for (int d = 0; d < dim; d++) { rdm(fespace->DofToVDof(i,d)) *= h0(i); } } char move_bdr = 'n'; cout << "move boundary nodes? [y/n] ---> " << flush; cin >> move_bdr; // don't perturb the boundary if (move_bdr == 'n') { Array<int> vdofs; for (int i = 0; i < fespace->GetNBE(); i++) { fespace->GetBdrElementVDofs(i, vdofs); for (int j = 0; j < vdofs.Size(); j++) { rdm(vdofs[j]) = 0.0; } } } *nodes += rdm; } print_char = 1; } if (mk == 'x') { int sd, nz = 0; DenseMatrix J(dim); double min_det_J, max_det_J, min_det_J_z, max_det_J_z; double min_kappa, max_kappa, max_ratio_det_J_z; min_det_J = min_kappa = infinity(); max_det_J = max_kappa = max_ratio_det_J_z = -infinity(); cout << "subdivision factor ---> " << flush; cin >> sd; Array<int> bad_elems_by_geom(Geometry::NumGeom); bad_elems_by_geom = 0; for (int i = 0; i < mesh->GetNE(); i++) { Geometry::Type geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); RefinedGeometry *RefG = GlobGeometryRefiner.Refine(geom, sd, 1); IntegrationRule &ir = RefG->RefPts; min_det_J_z = infinity(); max_det_J_z = -infinity(); for (int j = 0; j < ir.GetNPoints(); j++) { T->SetIntPoint(&ir.IntPoint(j)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); double det_J = J.Det(); double kappa = J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1); min_det_J_z = fmin(min_det_J_z, det_J); max_det_J_z = fmax(max_det_J_z, det_J); min_kappa = fmin(min_kappa, kappa); max_kappa = fmax(max_kappa, kappa); } max_ratio_det_J_z = fmax(max_ratio_det_J_z, max_det_J_z/min_det_J_z); min_det_J = fmin(min_det_J, min_det_J_z); max_det_J = fmax(max_det_J, max_det_J_z); if (min_det_J_z <= 0.0) { nz++; bad_elems_by_geom[geom]++; } } cout << "\nbad elements = " << nz; if (nz) { cout << " -- "; Mesh::PrintElementsByGeometry(dim, bad_elems_by_geom, cout); } cout << "\nmin det(J) = " << min_det_J << "\nmax det(J) = " << max_det_J << "\nglobal ratio = " << max_det_J/min_det_J << "\nmax el ratio = " << max_ratio_det_J_z << "\nmin kappa = " << min_kappa << "\nmax kappa = " << max_kappa << endl; } if (mk == 'f') { DenseMatrix point_mat(sdim,1); cout << "\npoint in physical space ---> " << flush; for (int i = 0; i < sdim; i++) { cin >> point_mat(i,0); } Array<int> elem_ids; Array<IntegrationPoint> ips; // physical -> reference space mesh->FindPoints(point_mat, elem_ids, ips); cout << "point in reference space:"; if (elem_ids[0] == -1) { cout << " NOT FOUND!\n"; } else { cout << " element " << elem_ids[0] << ", ip ="; cout << " " << ips[0].x; if (sdim > 1) { cout << " " << ips[0].y; if (sdim > 2) { cout << " " << ips[0].z; } } cout << endl; } } if (mk == 'o') { cout << "What type of reordering?\n" "g) Gecko edge-product minimization\n" "h) Hilbert spatial sort\n" "--> " << flush; char rk; cin >> rk; Array<int> ordering, tentative; if (rk == 'h') { mesh->GetHilbertElementOrdering(ordering); mesh->ReorderElements(ordering); } else if (rk == 'g') { int outer, inner, window, period; cout << "Enter number of outer iterations (default 5): " << flush; cin >> outer; cout << "Enter number of inner iterations (default 4): " << flush; cin >> inner; cout << "Enter window size (default 4, beware of exponential cost): " << flush; cin >> window; cout << "Enter period for window size increment (default 2): " << flush; cin >> period; double best_cost = infinity(); for (int i = 0; i < outer; i++) { int seed = i+1; double cost = mesh->GetGeckoElementOrdering( tentative, inner, window, period, seed, true); if (cost < best_cost) { ordering = tentative; best_cost = cost; } } cout << "Final cost: " << best_cost << endl; mesh->ReorderElements(ordering); } } // These are most of the cases that open a new GLVis window if (mk == 'm' || mk == 'b' || mk == 'e' || mk == 'v' || mk == 'h' || mk == 'k' || mk == 'p') { Array<int> bdr_part; Array<int> part(mesh->GetNE()); FiniteElementSpace *bdr_attr_fespace = NULL; FiniteElementSpace *attr_fespace = new FiniteElementSpace(mesh, attr_fec); GridFunction bdr_attr; GridFunction attr(attr_fespace); if (mk == 'm') { for (int i = 0; i < mesh->GetNE(); i++) { part[i] = (attr(i) = mesh->GetAttribute(i)) - 1; } } if (mk == 'b') { if (dim == 3) { delete bdr_mesh; bdr_mesh = skin_mesh(mesh); bdr_attr_fespace = new FiniteElementSpace(bdr_mesh, bdr_attr_fec); bdr_part.SetSize(bdr_mesh->GetNE()); bdr_attr.SetSpace(bdr_attr_fespace); for (int i = 0; i < bdr_mesh->GetNE(); i++) { bdr_part[i] = (bdr_attr(i) = bdr_mesh->GetAttribute(i)) - 1; } } else { attr = 1.0; } } if (mk == 'v') { attr = 1.0; } if (mk == 'e') { Array<int> coloring; srand(time(0)); double a = double(rand()) / (double(RAND_MAX) + 1.); int el0 = (int)floor(a * mesh->GetNE()); cout << "Generating coloring starting with element " << el0+1 << " / " << mesh->GetNE() << endl; mesh->GetElementColoring(coloring, el0); for (int i = 0; i < coloring.Size(); i++) { attr(i) = coloring[i]; } cout << "Number of colors: " << attr.Max() + 1 << endl; for (int i = 0; i < mesh->GetNE(); i++) { // part[i] = i; // checkerboard element coloring attr(i) = part[i] = i; // coloring by element number } } if (mk == 'h') { DenseMatrix J(dim); double h_min, h_max; h_min = infinity(); h_max = -h_min; for (int i = 0; i < mesh->GetNE(); i++) { int geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); T->SetIntPoint(&Geometries.GetCenter(geom)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); attr(i) = J.Det(); if (attr(i) < 0.0) { attr(i) = -pow(-attr(i), 1.0/double(dim)); } else { attr(i) = pow(attr(i), 1.0/double(dim)); } h_min = min(h_min, attr(i)); h_max = max(h_max, attr(i)); } cout << "h_min = " << h_min << ", h_max = " << h_max << endl; } if (mk == 'k') { DenseMatrix J(dim); for (int i = 0; i < mesh->GetNE(); i++) { int geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); T->SetIntPoint(&Geometries.GetCenter(geom)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); attr(i) = J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1); } } if (mk == 'p') { int *partitioning = NULL, np; cout << "What type of partitioning?\n" "c) Cartesian\n" "s) Simple 1D split of the element sequence\n" "0) METIS_PartGraphRecursive (sorted neighbor lists)\n" "1) METIS_PartGraphKway (sorted neighbor lists)" " (default)\n" "2) METIS_PartGraphVKway (sorted neighbor lists)\n" "3) METIS_PartGraphRecursive\n" "4) METIS_PartGraphKway\n" "5) METIS_PartGraphVKway\n" "--> " << flush; char pk; cin >> pk; if (pk == 'c') { int nxyz[3]; cout << "Enter nx: " << flush; cin >> nxyz[0]; np = nxyz[0]; if (mesh->Dimension() > 1) { cout << "Enter ny: " << flush; cin >> nxyz[1]; np *= nxyz[1]; if (mesh->Dimension() > 2) { cout << "Enter nz: " << flush; cin >> nxyz[2]; np *= nxyz[2]; } } partitioning = mesh->CartesianPartitioning(nxyz); } else if (pk == 's') { cout << "Enter number of processors: " << flush; cin >> np; partitioning = new int[mesh->GetNE()]; for (int i = 0; i < mesh->GetNE(); i++) { partitioning[i] = i * np / mesh->GetNE(); } } else { int part_method = pk - '0'; if (part_method < 0 || part_method > 5) { continue; } cout << "Enter number of processors: " << flush; cin >> np; partitioning = mesh->GeneratePartitioning(np, part_method); } if (partitioning) { const char part_file[] = "partitioning.txt"; ofstream opart(part_file); opart << "number_of_elements " << mesh->GetNE() << '\n' << "number_of_processors " << np << '\n'; for (int i = 0; i < mesh->GetNE(); i++) { opart << partitioning[i] << '\n'; } cout << "Partitioning file: " << part_file << endl; Array<int> proc_el(np); proc_el = 0; for (int i = 0; i < mesh->GetNE(); i++) { proc_el[partitioning[i]]++; } int min_el = proc_el[0], max_el = proc_el[0]; for (int i = 1; i < np; i++) { if (min_el > proc_el[i]) { min_el = proc_el[i]; } if (max_el < proc_el[i]) { max_el = proc_el[i]; } } cout << "Partitioning stats:\n" << " " << setw(12) << "minimum" << setw(12) << "average" << setw(12) << "maximum" << setw(12) << "total" << '\n'; cout << " elements " << setw(12) << min_el << setw(12) << double(mesh->GetNE())/np << setw(12) << max_el << setw(12) << mesh->GetNE() << endl; } else { continue; } for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i] = partitioning[i]; } delete [] partitioning; } char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); if (sol_sock.is_open()) { sol_sock.precision(14); if (sdim == 2) { sol_sock << "fem2d_gf_data_keys\n"; if (mk != 'p') { mesh->Print(sol_sock); } else { // NURBS meshes do not support PrintWithPartitioning if (mesh->NURBSext) { mesh->Print(sol_sock); for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i]; } } else { mesh->PrintWithPartitioning(part, sol_sock, 1); } } attr.Save(sol_sock); sol_sock << "RjlmAb***********"; if (mk == 'v') { sol_sock << "e"; } else { sol_sock << "\n"; } } else { sol_sock << "fem3d_gf_data_keys\n"; if (mk == 'v' || mk == 'h' || mk == 'k') { mesh->Print(sol_sock); } else if (mk == 'b') { bdr_mesh->Print(sol_sock); bdr_attr.Save(sol_sock); sol_sock << "mcaaA"; // Switch to a discrete color scale sol_sock << "pppppp" << "pppppp" << "pppppp"; } else { // NURBS meshes do not support PrintWithPartitioning if (mesh->NURBSext) { mesh->Print(sol_sock); for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i]; } } else { mesh->PrintWithPartitioning(part, sol_sock); } } if (mk != 'b') { attr.Save(sol_sock); sol_sock << "maaA"; if (mk == 'v') { sol_sock << "aa"; } else { sol_sock << "\n"; } } } sol_sock << flush; } else { cout << "Unable to connect to " << vishost << ':' << visport << endl; } delete attr_fespace; delete bdr_attr_fespace; } if (mk == 'l') { // Project and plot the function 'f' int p; FiniteElementCollection *fec = NULL; cout << "Enter projection space order: " << flush; cin >> p; if (p >= 1) { fec = new H1_FECollection(p, mesh->Dimension(), BasisType::GaussLobatto); } else { fec = new DG_FECollection(-p, mesh->Dimension(), BasisType::GaussLegendre); } FiniteElementSpace fes(mesh, fec); GridFunction level(&fes); FunctionCoefficient coeff(f); level.ProjectCoefficient(coeff); char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); if (sol_sock.is_open()) { sol_sock.precision(14); sol_sock << "solution\n" << *mesh << level << flush; } else { cout << "Unable to connect to " << vishost << ':' << visport << endl; } delete fec; } if (mk == 'S') { const char mesh_file[] = "mesh-explorer.mesh"; ofstream omesh(mesh_file); omesh.precision(14); mesh->Print(omesh); cout << "New mesh file: " << mesh_file << endl; } if (mk == 'V') { const char mesh_file[] = "mesh-explorer.vtk"; ofstream omesh(mesh_file); omesh.precision(14); mesh->PrintVTK(omesh); cout << "New VTK mesh file: " << mesh_file << endl; } #ifdef MFEM_USE_ZLIB if (mk == 'Z') { const char mesh_file[] = "mesh-explorer.mesh.gz"; ofgzstream omesh(mesh_file, "zwb9"); omesh.precision(14); mesh->Print(omesh); cout << "New mesh file: " << mesh_file << endl; } #endif } delete bdr_attr_fec; delete attr_fec; delete bdr_mesh; delete mesh; return 0; }
30.114815
82
0.432388
liruipeng
04cc4144cb271c7f973845fba2c60cfc12d382c7
2,145
cpp
C++
linear_structures/linked_list/138_copy-list-with-random-pointer.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/linked_list/138_copy-list-with-random-pointer.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/linked_list/138_copy-list-with-random-pointer.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 138_copy-list-with-random-pointer LeetCode Solution: - hashmap - "DNA" replication - for the original linked list: cut and splice */ #include <iostream> #include <unordered_map> using namespace std; // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; class Solution { public: Node* copyRandomList(Node* head) { if (!head) return nullptr; Node* cur{head}; // duplicate each node in chain while (cur) { Node* tmp = new Node(cur->val); tmp->next = cur->next; cur->next = tmp; cur = cur->next->next; } // assign random link for each duplicated node cur = head; while (cur) { cur->next->random = cur->random ? cur->random->next : nullptr; cur = cur->next->next; } // split the chain into two cur = head; Node* cur2 = head->next; Node* res = head->next; while (cur && cur->next) { cur->next = cur->next->next; cur = cur->next; if (cur2->next) { cur2->next = cur2->next->next; cur2 = cur2->next; } } return res; // Node* res = new Node(0); // unordered_map<Node*, Node*> m; // // Node* cur{head}; // Node* cur_r{res}; // while (cur != nullptr) { // cur_r->next = new Node(cur->val); // cur_r = cur_r->next; // m[cur] = cur_r; // // cur = cur->next; // } // cur = head; // cur_r = res->next; // while (cur != nullptr) { // cur_r->random = m[cur->random]; // cur_r = cur_r->next; // cur = cur->next; // } // return res->next; } };
23.315217
75
0.432168
b1tank
04d19bf9db73b0092e647a6310b8fa8531f1bb61
1,943
cpp
C++
src/entities/Entity.cpp
MatthiasvZ/Gesneria
c60f041460a0c3f91a2d0cd34c7e2209fefdee9e
[ "Unlicense" ]
null
null
null
src/entities/Entity.cpp
MatthiasvZ/Gesneria
c60f041460a0c3f91a2d0cd34c7e2209fefdee9e
[ "Unlicense" ]
null
null
null
src/entities/Entity.cpp
MatthiasvZ/Gesneria
c60f041460a0c3f91a2d0cd34c7e2209fefdee9e
[ "Unlicense" ]
null
null
null
#include "Entity.h" Entity::Entity(float x, float y, float hitboxSize) : x(x), y(y), hitboxSize(hitboxSize), acceleration(0.0f), velocity(0.0f), angle(0.0f), speedCap(0.0f), frictionF(0.0f), active(true) { } void Entity::moveTo(float x, float y) { this->x = x; this->y = y; updateVertices(); } void Entity::moveRelative(float x, float y) { this->x += x; this->y += y; updateVertices(); } void Entity::updateVertices() { vertices = { this->x - hitboxSize, this->y - hitboxSize, 0.0f, 0.0f, this->x - hitboxSize, this->y + hitboxSize, 0.0f, 1.0f, this->x + hitboxSize, this->y + hitboxSize, 1.0f, 1.0f, this->x + hitboxSize, this->y - hitboxSize, 1.0f, 0.0f }; } #include <iostream> void Entity::updatePosL(float deltaTime) { updatePosL(deltaTime, angle); } void Entity::updatePosL(float deltaTime, float newAngle) { angle = newAngle; const float movementX = speedCap * deltaTime * cos(angle); const float movementY = speedCap * deltaTime * sin(angle); x += movementX; y += movementY; updateVertices(); } void Entity::updatePosQ(float deltaTime) { updatePosQ(deltaTime, angle); } void Entity::updatePosQ(float deltaTime, float newAngle) { const float movementX = 0.5f * acceleration * deltaTime * deltaTime * cos(newAngle) + velocity * deltaTime * cos(angle); const float movementY = 0.5f * acceleration * deltaTime * deltaTime * sin(newAngle) + velocity * deltaTime * sin(angle); angle = atan2(movementY, movementX); x += movementX; y += movementY; //std::cerr << "angle = " << angle << std::endl; //std::cerr << "vel = " << velocity << ", std::abs(vel) = " << std::abs(velocity) << std::endl; const float friction = ρAir * frictionF * velocity * std::abs(velocity); velocity = std::max(std::min(velocity + acceleration * deltaTime - friction, speedCap), -speedCap); updateVertices(); }
26.986111
136
0.633042
MatthiasvZ
04d3892ce1f9010dd8d3b6675ad7d8e02b095211
652
cpp
C++
math/two_sat/gen/cycle_unsat.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
290
2019-06-06T22:20:36.000Z
2022-03-27T12:45:04.000Z
math/two_sat/gen/cycle_unsat.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
536
2019-06-06T18:25:36.000Z
2022-03-29T11:46:36.000Z
math/two_sat/gen/cycle_unsat.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
82
2019-06-06T18:17:55.000Z
2022-03-21T07:40:31.000Z
#include "random.h" #include <iostream> using namespace std; int main(int, char* argv[]) { long long seed = atoll(argv[1]); auto gen = Random(seed); int n = 500'000 - 2; int m = 500'000; printf("p cnf %d %d\n", n, m); // all same for (int i = 1; i < n; i++) { printf("%d %d 0\n", i, - (i + 1)); } printf("%d -1 0\n", n); // some pair, both true(= all true) int a = gen.uniform(1, n); int b = gen.uniform(1, n); printf("%d %d 0\n", a, b); // some pair, both false(= all false) a = gen.uniform(-n, -1); b = gen.uniform(-n, -1); printf("%d %d 0\n", a, b); return 0; }
20.375
42
0.48773
tko919
04d3b8565fc9d41b44169ea856f352d83d8d5623
2,482
cpp
C++
src/objects/boid/Bird.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
1
2020-04-24T22:55:51.000Z
2020-04-24T22:55:51.000Z
src/objects/boid/Bird.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
null
null
null
src/objects/boid/Bird.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
null
null
null
// // Created by Aloysio Galvão Lopes on 2020-05-30. // #include "utils/Texture.h" #include "Bird.h" std::vector<GLuint> Bird::textures; Bird::Bird(Shaders &shaders, vcl::vec3 pos, float scale, vcl::vec3 speed, float turning) : Object(true), dp(speed), turining(turning), bird("../src/assets/models/bird.fbx", shaders["mesh"]) { position = pos; if (textures.empty()) { Texture feathers("bird"); textures.push_back(feathers.getId()); } bird.set_textures(textures); bird.set_animation("bird|fly"); animationTime = 0; } void Bird::drawMesh(vcl::camera_scene &camera) { bird.set_light(lights[0]); // TODO add scaling to birds // TODO Add bounding sphere orientation = vcl::rotation_euler(dp, turining); vcl::mat4 transform = {orientation, position}; // Bird draw bird.transform(transform); bird.draw(camera, animationTime); } void Bird::update(float time) { vcl::vec3 projDpo = {odp.x, odp.y, 1}; vcl::vec3 projNdp = {ndp.x, ndp.y, 1}; float targetAngle = projDpo.angle(projNdp)*Constants::BIRD_MAX_TURN_FACTOR; if (targetAngle > M_PI_2) targetAngle = M_PI_2; else if (targetAngle < -M_PI_2) targetAngle = -M_PI_2; turining += Constants::BIRD_TURN_FACTOR*(targetAngle-turining); // Animation part float animationNormalizedPosition = fmod(animationTime, Constants::BIRD_ANIMATION_MAX_TIME); float animationTargetPosition = animationNormalizedPosition+Constants::BIRD_ANIMATION_SPEED; float animationSpeedFactor = 1.0f; float inclination = dp.angle({0,0,1}); if (inclination >= M_PI_2+M_PI_4){ animationTargetPosition = 0.6; } else { animationSpeedFactor = (M_PI_2+M_PI_4-inclination)/(M_PI_2+M_PI_4)*0.6+0.4; animationSpeedFactor += (fabs(turining))/M_PI_2; } if (fabs(animationNormalizedPosition-animationTargetPosition) >= Constants::BIRD_ANIMATION_SPEED/2) animationTime += Constants::BIRD_ANIMATION_SPEED*animationSpeedFactor; } vcl::vec3 Bird::getSpeed() { return dp; } void Bird::setFutureSpeed(vcl::vec3 speed) { ndp = speed; } void Bird::addFutureSpeed(vcl::vec3 speed) { ndp += speed; } vcl::vec3 Bird::getFutureSpeed() { return ndp; } void Bird::setPosition(vcl::vec3 pos) { position = pos; } void Bird::stepSpeed() { odp = dp; dp = ndp; } void Bird::stepPosition() { position += dp; } float Bird::getRotation() { return turining; }
25.587629
103
0.67083
asilvaigor
04d3d197efa085417590304d3cc73499fef2ac3c
27,756
cpp
C++
Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
// Generated by Haxe 4.2.0-rc.1+cb30bd580 #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_fracs_Fracs #include <fracs/Fracs.h> #endif #ifndef INCLUDED_fracs__Fraction_Fraction_Impl_ #include <fracs/_Fraction/Fraction_Impl_.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_32__new,"fracs._Fraction.Fraction_Impl_","_new",0x2a584cf7,"fracs._Fraction.Fraction_Impl_._new","fracs/Fraction.hx",32,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_46_optimize,"fracs._Fraction.Fraction_Impl_","optimize",0x00d44773,"fracs._Fraction.Fraction_Impl_.optimize","fracs/Fraction.hx",46,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_50_optimizeFraction,"fracs._Fraction.Fraction_Impl_","optimizeFraction",0xea05c495,"fracs._Fraction.Fraction_Impl_.optimizeFraction","fracs/Fraction.hx",50,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_55_toFloat,"fracs._Fraction.Fraction_Impl_","toFloat",0xab643c4b,"fracs._Fraction.Fraction_Impl_.toFloat","fracs/Fraction.hx",55,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_63_float,"fracs._Fraction.Fraction_Impl_","float",0xe96e3146,"fracs._Fraction.Fraction_Impl_.float","fracs/Fraction.hx",63,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_67_verbose,"fracs._Fraction.Fraction_Impl_","verbose",0x4e0301ac,"fracs._Fraction.Fraction_Impl_.verbose","fracs/Fraction.hx",67,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_71_fromString,"fracs._Fraction.Fraction_Impl_","fromString",0x6a8439f1,"fracs._Fraction.Fraction_Impl_.fromString","fracs/Fraction.hx",71,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_82_toString,"fracs._Fraction.Fraction_Impl_","toString",0x1c2a8b42,"fracs._Fraction.Fraction_Impl_.toString","fracs/Fraction.hx",82,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_98_fromFloat,"fracs._Fraction.Fraction_Impl_","fromFloat",0x17a7387c,"fracs._Fraction.Fraction_Impl_.fromFloat","fracs/Fraction.hx",98,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_119_firstFloat,"fracs._Fraction.Fraction_Impl_","firstFloat",0x56851b62,"fracs._Fraction.Fraction_Impl_.firstFloat","fracs/Fraction.hx",119,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_126_byDenominator,"fracs._Fraction.Fraction_Impl_","byDenominator",0xa7ebbeb9,"fracs._Fraction.Fraction_Impl_.byDenominator","fracs/Fraction.hx",126,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_138_all,"fracs._Fraction.Fraction_Impl_","all",0x2614464b,"fracs._Fraction.Fraction_Impl_.all","fracs/Fraction.hx",138,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_141_similarToFraction,"fracs._Fraction.Fraction_Impl_","similarToFraction",0x69a71b52,"fracs._Fraction.Fraction_Impl_.similarToFraction","fracs/Fraction.hx",141,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_147_similarToValue,"fracs._Fraction.Fraction_Impl_","similarToValue",0x124a8821,"fracs._Fraction.Fraction_Impl_.similarToValue","fracs/Fraction.hx",147,0xf40fb512) namespace fracs{ namespace _Fraction{ void Fraction_Impl__obj::__construct() { } Dynamic Fraction_Impl__obj::__CreateEmpty() { return new Fraction_Impl__obj; } void *Fraction_Impl__obj::_hx_vtable = 0; Dynamic Fraction_Impl__obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< Fraction_Impl__obj > _hx_result = new Fraction_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool Fraction_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1a57794a; } ::Dynamic Fraction_Impl__obj::_new(int numerator,int denominator, ::Dynamic __o_positive, ::Dynamic value){ ::Dynamic positive = __o_positive; if (::hx::IsNull(__o_positive)) positive = true; HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_32__new) HXLINE( 34) bool numNeg = (numerator < 0); HXLINE( 35) bool denoNeg = (denominator < 0); HXLINE( 36) if (::hx::IsNull( value )) { HXLINE( 36) if (( (bool)(positive) )) { HXLINE( 36) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 36) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXLINE( 37) bool _hx_tmp; HXDLIN( 37) if (!(numNeg)) { HXLINE( 37) _hx_tmp = denoNeg; } else { HXLINE( 37) _hx_tmp = true; } HXDLIN( 37) if (_hx_tmp) { HXLINE( 38) bool _hx_tmp; HXDLIN( 38) if (numNeg) { HXLINE( 38) _hx_tmp = denoNeg; } else { HXLINE( 38) _hx_tmp = false; } HXDLIN( 38) if (!(_hx_tmp)) { HXLINE( 38) positive = !(( (bool)(positive) )); } HXLINE( 39) if (numNeg) { HXLINE( 39) numerator = -(numerator); } HXLINE( 40) if (denoNeg) { HXLINE( 40) denominator = -(denominator); } } HXLINE( 32) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXDLIN( 32) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC4(Fraction_Impl__obj,_new,return ) ::Dynamic Fraction_Impl__obj::optimize( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_46_optimize) HXDLIN( 46) Float f = ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ); HXDLIN( 46) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 46) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 46) Float dif; HXDLIN( 46) int l = arr->length; HXDLIN( 46) Float fracFloat; HXDLIN( 46) ::Dynamic frac; HXDLIN( 46) ::Dynamic fracStore = arr->__get(0); HXDLIN( 46) { HXDLIN( 46) int _g = 0; HXDLIN( 46) int _g1 = l; HXDLIN( 46) while((_g < _g1)){ HXDLIN( 46) _g = (_g + 1); HXDLIN( 46) int i = (_g - 1); HXDLIN( 46) ::Dynamic frac = arr->__get(i); HXDLIN( 46) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 46) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 46) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 46) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 46) if ((dif < dist)) { HXDLIN( 46) dist = dif; HXDLIN( 46) fracStore = frac; } } } HXDLIN( 46) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimize,return ) ::Dynamic Fraction_Impl__obj::optimizeFraction( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_50_optimizeFraction) HXDLIN( 50) Float f; HXDLIN( 50) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 50) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 50) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 50) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 50) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 50) Float dif; HXDLIN( 50) int l = arr->length; HXDLIN( 50) Float fracFloat; HXDLIN( 50) ::Dynamic frac; HXDLIN( 50) ::Dynamic fracStore = arr->__get(0); HXDLIN( 50) { HXDLIN( 50) int _g = 0; HXDLIN( 50) int _g1 = l; HXDLIN( 50) while((_g < _g1)){ HXDLIN( 50) _g = (_g + 1); HXDLIN( 50) int i = (_g - 1); HXDLIN( 50) ::Dynamic frac = arr->__get(i); HXDLIN( 50) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 50) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 50) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 50) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 50) if ((dif < dist)) { HXDLIN( 50) dist = dif; HXDLIN( 50) fracStore = frac; } } } HXDLIN( 50) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimizeFraction,return ) Float Fraction_Impl__obj::toFloat( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_55_toFloat) HXDLIN( 55) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 56) return (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 58) return (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 55) return ((Float)0.); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toFloat,return ) Float Fraction_Impl__obj::_hx_float( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_63_float) HXDLIN( 63) return ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,_hx_float,return ) ::String Fraction_Impl__obj::verbose( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_67_verbose) HXDLIN( 67) ::String _hx_tmp = ( (::String)(((((HX_("{ numerator:",16,c9,1c,39) + this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) + HX_(", denominator: ",d8,6e,ff,e1)) + this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) + HX_(", positive: ",13,f9,b0,e4))) ); HXDLIN( 67) ::String _hx_tmp1 = ((_hx_tmp + ::Std_obj::string( ::Dynamic(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)))) + HX_(", value: ",63,80,38,d8)); HXDLIN( 67) return ( (::String)(((_hx_tmp1 + this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) + HX_(" }",5d,1c,00,00))) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,verbose,return ) ::Dynamic Fraction_Impl__obj::fromString(::String val){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_71_fromString) HXLINE( 72) int i = val.indexOf(HX_("/",2f,00,00,00),null()); HXLINE( 73) ::Dynamic frac; HXDLIN( 73) if ((i != -1)) { HXLINE( 74) int numerator = ( (int)(::Std_obj::parseInt(val.substr(0,i))) ); HXDLIN( 74) int denominator = ( (int)(::Std_obj::parseInt(val.substr((i + 1),val.length))) ); HXDLIN( 74) ::Dynamic positive = true; HXDLIN( 74) ::Dynamic value = null(); HXDLIN( 74) bool numNeg = (numerator < 0); HXDLIN( 74) bool denoNeg = (denominator < 0); HXDLIN( 74) if (::hx::IsNull( value )) { HXLINE( 74) if (( (bool)(positive) )) { HXLINE( 74) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 74) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXDLIN( 74) bool frac1; HXDLIN( 74) if (!(numNeg)) { HXLINE( 74) frac1 = denoNeg; } else { HXLINE( 74) frac1 = true; } HXDLIN( 74) if (frac1) { HXLINE( 74) bool frac; HXDLIN( 74) if (numNeg) { HXLINE( 74) frac = denoNeg; } else { HXLINE( 74) frac = false; } HXDLIN( 74) if (!(frac)) { HXLINE( 74) positive = !(( (bool)(positive) )); } HXDLIN( 74) if (numNeg) { HXLINE( 74) numerator = -(numerator); } HXDLIN( 74) if (denoNeg) { HXLINE( 74) denominator = -(denominator); } } HXDLIN( 74) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXLINE( 73) frac = this1; } else { HXLINE( 75) Float f = ::Std_obj::parseFloat(val); HXDLIN( 75) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 75) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 75) Float dif; HXDLIN( 75) int l = arr->length; HXDLIN( 75) Float fracFloat; HXDLIN( 75) ::Dynamic frac1; HXDLIN( 75) ::Dynamic fracStore = arr->__get(0); HXDLIN( 75) { HXLINE( 75) int _g = 0; HXDLIN( 75) int _g1 = l; HXDLIN( 75) while((_g < _g1)){ HXLINE( 75) _g = (_g + 1); HXDLIN( 75) int i = (_g - 1); HXDLIN( 75) ::Dynamic frac = arr->__get(i); HXDLIN( 75) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 75) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 75) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 75) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 75) if ((dif < dist)) { HXLINE( 75) dist = dif; HXDLIN( 75) fracStore = frac; } } } HXLINE( 73) frac = fracStore; } HXLINE( 78) return frac; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromString,return ) ::String Fraction_Impl__obj::toString( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_82_toString) HXLINE( 83) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXLINE( 84) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXLINE( 85) ::String out; HXDLIN( 85) if ((n == 0)) { HXLINE( 85) out = HX_("0",30,00,00,00); } else { HXLINE( 87) if ((n == d)) { HXLINE( 85) out = HX_("1",31,00,00,00); } else { HXLINE( 89) if ((d == 1)) { HXLINE( 90) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 85) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 85) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 92) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 85) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 85) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXLINE( 94) return out; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toString,return ) ::Dynamic Fraction_Impl__obj::fromFloat(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_98_fromFloat) HXLINE( 99) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXLINE( 100) Float dist = ::Math_obj::POSITIVE_INFINITY; HXLINE( 101) Float dif; HXLINE( 102) int l = arr->length; HXLINE( 103) Float fracFloat; HXLINE( 104) ::Dynamic frac; HXLINE( 105) ::Dynamic fracStore = arr->__get(0); HXLINE( 107) { HXLINE( 107) int _g = 0; HXDLIN( 107) int _g1 = l; HXDLIN( 107) while((_g < _g1)){ HXLINE( 107) _g = (_g + 1); HXDLIN( 107) int i = (_g - 1); HXLINE( 108) ::Dynamic frac = arr->__get(i); HXLINE( 109) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 109) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 109) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 110) dif = ::Math_obj::abs((fracFloat - f)); HXLINE( 111) if ((dif < dist)) { HXLINE( 112) dist = dif; HXLINE( 113) fracStore = frac; } } } HXLINE( 116) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromFloat,return ) ::Dynamic Fraction_Impl__obj::firstFloat(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_119_firstFloat) HXLINE( 120) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXLINE( 121) ::Dynamic fracStore = arr->__get(0); HXLINE( 122) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,firstFloat,return ) ::String Fraction_Impl__obj::byDenominator( ::Dynamic this1,int val){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_126_byDenominator) HXLINE( 127) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXDLIN( 127) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXDLIN( 127) ::String out; HXDLIN( 127) if ((n == 0)) { HXLINE( 127) out = HX_("0",30,00,00,00); } else { HXLINE( 127) if ((n == d)) { HXLINE( 127) out = HX_("1",31,00,00,00); } else { HXLINE( 127) if ((d == 1)) { HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 127) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 127) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 127) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 127) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXDLIN( 127) ::String out1 = out; HXLINE( 128) bool _hx_tmp; HXDLIN( 128) bool _hx_tmp1; HXDLIN( 128) if (::hx::IsNotEq( this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic),val )) { HXLINE( 128) _hx_tmp1 = (out1 == HX_("0",30,00,00,00)); } else { HXLINE( 128) _hx_tmp1 = true; } HXDLIN( 128) if (!(_hx_tmp1)) { HXLINE( 128) _hx_tmp = (out1 == HX_("1",31,00,00,00)); } else { HXLINE( 128) _hx_tmp = true; } HXDLIN( 128) if (!(_hx_tmp)) { HXLINE( 130) int dom = ::Math_obj::round((( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ) * ( (Float)(val) ))); HXLINE( 131) int numerator = dom; HXDLIN( 131) int denominator = val; HXDLIN( 131) ::Dynamic positive = true; HXDLIN( 131) ::Dynamic value = null(); HXDLIN( 131) bool numNeg = (numerator < 0); HXDLIN( 131) bool denoNeg = (denominator < 0); HXDLIN( 131) if (::hx::IsNull( value )) { HXLINE( 131) if (( (bool)(positive) )) { HXLINE( 131) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 131) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXDLIN( 131) bool _hx_tmp; HXDLIN( 131) if (!(numNeg)) { HXLINE( 131) _hx_tmp = denoNeg; } else { HXLINE( 131) _hx_tmp = true; } HXDLIN( 131) if (_hx_tmp) { HXLINE( 131) bool _hx_tmp; HXDLIN( 131) if (numNeg) { HXLINE( 131) _hx_tmp = denoNeg; } else { HXLINE( 131) _hx_tmp = false; } HXDLIN( 131) if (!(_hx_tmp)) { HXLINE( 131) positive = !(( (bool)(positive) )); } HXDLIN( 131) if (numNeg) { HXLINE( 131) numerator = -(numerator); } HXDLIN( 131) if (denoNeg) { HXLINE( 131) denominator = -(denominator); } } HXDLIN( 131) ::Dynamic this2 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXDLIN( 131) ::Dynamic frac = this2; HXLINE( 132) int n = ( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXDLIN( 132) int d = ( (int)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXDLIN( 132) ::String out; HXDLIN( 132) if ((n == 0)) { HXLINE( 132) out = HX_("0",30,00,00,00); } else { HXLINE( 132) if ((n == d)) { HXLINE( 132) out = HX_("1",31,00,00,00); } else { HXLINE( 132) if ((d == 1)) { HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 132) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 132) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 132) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 132) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXDLIN( 132) out1 = out; } HXLINE( 134) return out1; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Fraction_Impl__obj,byDenominator,return ) ::Array< ::Dynamic> Fraction_Impl__obj::all(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_138_all) HXDLIN( 138) return ::fracs::Fracs_obj::approximateFractions(f); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,all,return ) ::Array< ::Dynamic> Fraction_Impl__obj::similarToFraction( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_141_similarToFraction) HXLINE( 142) Float f; HXDLIN( 142) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 142) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 142) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 143) return ::fracs::Fracs_obj::approximateFractions(f); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToFraction,return ) ::Array< ::Dynamic> Fraction_Impl__obj::similarToValue( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_147_similarToValue) HXDLIN( 147) return ::fracs::Fracs_obj::approximateFractions(( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) )); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToValue,return ) Fraction_Impl__obj::Fraction_Impl__obj() { } bool Fraction_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"all") ) { outValue = all_dyn(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"float") ) { outValue = _hx_float_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"toFloat") ) { outValue = toFloat_dyn(); return true; } if (HX_FIELD_EQ(inName,"verbose") ) { outValue = verbose_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"optimize") ) { outValue = optimize_dyn(); return true; } if (HX_FIELD_EQ(inName,"toString") ) { outValue = toString_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"fromFloat") ) { outValue = fromFloat_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"fromString") ) { outValue = fromString_dyn(); return true; } if (HX_FIELD_EQ(inName,"firstFloat") ) { outValue = firstFloat_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"byDenominator") ) { outValue = byDenominator_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"similarToValue") ) { outValue = similarToValue_dyn(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"optimizeFraction") ) { outValue = optimizeFraction_dyn(); return true; } break; case 17: if (HX_FIELD_EQ(inName,"similarToFraction") ) { outValue = similarToFraction_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *Fraction_Impl__obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *Fraction_Impl__obj_sStaticStorageInfo = 0; #endif ::hx::Class Fraction_Impl__obj::__mClass; static ::String Fraction_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), HX_("optimize",dd,8c,18,1d), HX_("optimizeFraction",ff,83,8c,53), HX_("toFloat",21,12,1b,cf), HX_("float",9c,c5,96,02), HX_("verbose",82,d7,b9,71), HX_("fromString",db,2d,74,54), HX_("toString",ac,d0,6e,38), HX_("fromFloat",d2,af,1f,b7), HX_("firstFloat",4c,0f,75,40), HX_("byDenominator",0f,99,e1,96), HX_("all",21,f9,49,00), HX_("similarToFraction",a8,d8,07,56), HX_("similarToValue",0b,b9,73,3a), ::String(null()) }; void Fraction_Impl__obj::__register() { Fraction_Impl__obj _hx_dummy; Fraction_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("fracs._Fraction.Fraction_Impl_",98,50,12,83); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Fraction_Impl__obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(Fraction_Impl__obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< Fraction_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Fraction_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Fraction_Impl__obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace fracs } // end namespace _Fraction
43.36875
292
0.60931
TrilateralX
04d5de7bf0de3f81eb9a1ed908f07980b15a5999
832
hpp
C++
SDEngine/include/Utility/Timing.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
SDEngine/include/Utility/Timing.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
4
2021-12-10T05:01:49.000Z
2022-03-19T10:16:14.000Z
SDEngine/include/Utility/Timing.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
#ifndef SD_TIMING_HPP #define SD_TIMING_HPP #include "Utility/Base.hpp" #include <cstdint> #include <queue> #include <chrono> namespace SD { using ClockType = std::chrono::high_resolution_clock; class SD_UTILITY_API Clock { public: Clock(); float GetElapsedMS() const; // Restart the clock, and return elapsed millisecond. float Restart(); private: std::chrono::time_point<ClockType> m_lastTicks; }; class SD_UTILITY_API FPSCounter { public: FPSCounter(uint8_t capacity); FPSCounter(const FPSCounter &) = delete; FPSCounter &operator=(const FPSCounter &) = delete; float GetFPS() const; float GetFrameTime() const; void Probe(); private: Clock m_clock; std::deque<float> m_queue; uint8_t m_capacity; }; } // namespace SD #endif /* SD_TIMING_HPP */
17.333333
57
0.6875
xubury
04d8921962bfed4a4e66aa1b8f2dc444f4b2c589
4,743
cpp
C++
basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp
gramai/school-related
152d67b4e475c3ba7c9370d6de39b38fc453392d
[ "MIT" ]
null
null
null
basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp
gramai/school-related
152d67b4e475c3ba7c9370d6de39b38fc453392d
[ "MIT" ]
null
null
null
basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp
gramai/school-related
152d67b4e475c3ba7c9370d6de39b38fc453392d
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #define NMAX=10 using namespace std; // A class is created to better implement the problem class Bucket{ private: stack <int> liter_list; // Is a stack where each element can be int(1) int bucket_size;// Max size of bucket public: Bucket(int bucket_size){ this->bucket_size=bucket_size; } int getLiters(){ return liter_list.size(); } void emptyBucket(){ liter_list.pop(); } // Transfers from another bucket until target_bucket is full or donor_bucket is empty void fillBucket(Bucket &donor_bucket){ while(liter_list.size()<bucket_size && !donor_bucket.isEmpty()) {donor_bucket.emptyBucket(); liter_list.push(1); } } // Method only used for filling the 20 liters bucket void fillBucket(){ while(liter_list.size()<bucket_size) liter_list.push(1); } int getSize(){ return bucket_size; } bool isEmpty(){ return (liter_list.size()==0); } bool isFull(){ return (liter_list.size()==bucket_size); } }; // Returns state for all 3 buckets (L1, L2, L3) void return_state(Bucket b1, Bucket b2, Bucket b3, int &state){ cout<<"State "<<state<<endl; cout<<"Bucket with max capacity "<<b1.getSize()<<" l holds "<<b1.getLiters()<<" l of wine "<<endl; cout<<"Bucket with max capacity "<<b2.getSize()<<" l holds "<<b2.getLiters()<<" l of wine "<<endl; cout<<"Bucket with max capacity "<<b3.getSize()<<" l holds "<<b3.getLiters()<<" l of wine "<<endl; cout<<endl; state++; } // int no_of_liters is the number of the desired liters to measure void measure_liters(int no_of_liters,Bucket &b8, Bucket &b5,Bucket &b20){ // Checks if any bucket contains the desired no_of_liters int state=1; while (b8.getLiters()!=no_of_liters && b5.getLiters()!=no_of_liters && b20.getLiters()!=no_of_liters ){ /* The algorithm is a circular one and goes like this: b20->b8->b5 Meaning that: -1)b8 is filled from b20 only when b8 is empty -2)b5 is filled from b8 every time b5 contains <5l of wine -is the main element because the quantity will vary between b8 and b5 -3)b5 is emptied in b20 when b5 is full -e.g. :b20=20, b8=0, b5=0; -> b20=12, b8=8, b5=0; ->b20=12, b8=3, b5=5; ->b20=17, b8=3, b5=0; ->b20=17, b8=0, b5=3; ... etc */ if(b8.isEmpty()){ b8.fillBucket(b20); return_state(b8,b5,b20,state); } else if(b5.isEmpty()){ b5.fillBucket(b8); return_state(b8,b5,b20,state); } else if(b5.isFull()){ b20.fillBucket(b5); return_state(b8,b5,b20,state); } else if (!b5.isFull()) {b5.fillBucket(b8); return_state(b8,b5,b20,state); } else{ cout<<"Other state, quitting"<<endl<<endl; return; } } if(b8.getLiters()==no_of_liters) cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 8l max capacity "<<endl<<endl; else if(b5.getLiters()==no_of_liters) cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 5l max capacity "<<endl<<endl; else{ cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 20l max capacity "<<endl<<endl; } } void reset_state(Bucket &b1,Bucket &b2,Bucket &b3){ while(!b1.isEmpty() || !b2.isEmpty() || !b3.isEmpty()){ if(!b1.isEmpty()) b1.emptyBucket(); if(!b2.isEmpty()) b2.emptyBucket(); if(!b3.isEmpty()) b3.emptyBucket(); } b3.fillBucket(); } int main() { // I thought that it would be more interesting to be able to measure any quantity of liters int no_of_liters=0; // inputs desired no. of liters to measure bool entered=0; // checks if there existed a first attempt to insert no_of_lites while(no_of_liters<1 || no_of_liters>20) //asks user to input a correct value of no_of_liters { if(entered==0){ cout<< "Insert number of desired liters to measure (1-20)"<<endl; cin>>no_of_liters; entered=1; } else{ cout<<"Please insert a number between 1 and 20 "<<endl; cin>>no_of_liters; } } // Create 3 buckets with max capacities of 8,5 and 20 liters Bucket b8 = Bucket(8); Bucket b5 = Bucket(5); Bucket b20 = Bucket(20); b20.fillBucket(); // fills the bucket with 20l max capacity measure_liters(no_of_liters,b8,b5,b20); }
32.710345
109
0.580223
gramai