hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
3c2892c1604f28e25e0ad24f7741d61b6dc79556
2,453
cpp
C++
src/engine/statemanager.cpp
bloodythorn/tide
d193b4792d86eb60cf2f9667818ef50d6a13aa71
[ "MIT" ]
null
null
null
src/engine/statemanager.cpp
bloodythorn/tide
d193b4792d86eb60cf2f9667818ef50d6a13aa71
[ "MIT" ]
6
2018-11-24T10:50:31.000Z
2019-05-08T21:23:56.000Z
src/engine/statemanager.cpp
bloodythorn/tide
d193b4792d86eb60cf2f9667818ef50d6a13aa71
[ "MIT" ]
null
null
null
#include "tide/engine/statemanager.hpp" #include <stdexcept> namespace tide { namespace Engine { StateManager::StateManager() { } StateManager::StateManager(const StateManager& p_ot) : m_startState(p_ot.m_startState), m_currentState(p_ot.m_currentState) { m_states.clear(); for(const auto& a : p_ot.m_states) { m_states.insert({a.first, StatePtr(a.second)}); } } StateManager::StateManager(StateManager&& p_ot) : m_startState(p_ot.m_startState), m_currentState(p_ot.m_currentState) { m_states.clear(); for(const auto& a : p_ot.m_states) { m_states.insert({a.first, StatePtr(a.second)}); } p_ot.m_startState = L""; p_ot.m_currentState = L""; p_ot.m_states.clear(); } StateManager::~StateManager() { } StateManager& StateManager::operator=(const StateManager& p_ot) { if(this == &p_ot) { m_startState = p_ot.m_startState; m_currentState = p_ot.m_currentState; m_states.clear(); for(const auto& a : p_ot.m_states) { m_states.insert({a.first, StatePtr(a.second)}); } } return *this; } StateManager& StateManager::operator=(StateManager&& p_ot) { if(this == &p_ot) { m_startState = p_ot.m_startState; p_ot.m_startState = L""; m_currentState = p_ot.m_currentState; p_ot.m_currentState = L""; m_states.clear(); for(const auto& a : p_ot.m_states) { m_states.insert({a.first, StatePtr(a.second)}); } p_ot.m_states.clear(); } return *this; } void StateManager::addStartState(StateManager::StatePtr p_st){ if(m_states.find(p_st->Name()) != m_states.end()) throw std::runtime_error("State already exists!"); if(m_states.size() == 0) m_startState = p_st->Name(); m_states.insert({p_st->Name(), p_st}); m_currentState = p_st->Name(); } void StateManager::handle(Engine& p_en, double p_dt) { auto st = m_states.find(m_currentState); if(st == m_states.end()) throw std::out_of_range("Current state not found!"); m_states[m_currentState]->handle(p_en, p_dt); } void StateManager::update(Engine& p_en, double p_dt) { auto st = m_states.find(m_currentState); if(st == m_states.end()) throw std::out_of_range("Current state not found!"); m_states[m_currentState]->update(p_en, p_dt); } void StateManager::render(Engine& p_en, double p_dt) { auto st = m_states.find(m_currentState); if(st == m_states.end()) throw std::out_of_range("Current state not found!"); m_states[m_currentState]->render(p_en, p_dt); } }/*engine*/}/*tide*/
29.554217
79
0.693437
[ "render" ]
3c296e58c883ae1a8104a898fdab6b3582b0e43b
12,359
cpp
C++
src/components/ColliderComponents.cpp
HugoPeters1024/reactphysics3d
3c4b3a03f644b07783ac87eabc6fd32c4ca32a09
[ "Zlib" ]
1,042
2015-04-02T11:04:01.000Z
2022-03-31T09:23:05.000Z
src/components/ColliderComponents.cpp
HugoPeters1024/reactphysics3d
3c4b3a03f644b07783ac87eabc6fd32c4ca32a09
[ "Zlib" ]
238
2015-01-19T21:22:44.000Z
2022-03-23T09:01:13.000Z
src/components/ColliderComponents.cpp
HugoPeters1024/reactphysics3d
3c4b3a03f644b07783ac87eabc6fd32c4ca32a09
[ "Zlib" ]
191
2015-06-09T07:33:09.000Z
2022-03-30T12:58:54.000Z
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2020 Daniel Chappuis * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ // Libraries #include <reactphysics3d/components/ColliderComponents.h> #include <reactphysics3d/engine/EntityManager.h> #include <reactphysics3d/collision/Collider.h> #include <cassert> #include <random> // We want to use the ReactPhysics3D namespace using namespace reactphysics3d; // Constructor ColliderComponents::ColliderComponents(MemoryAllocator& allocator) :Components(allocator, sizeof(Entity) + sizeof(Entity) + sizeof(Collider*) + sizeof(int32) + sizeof(Transform) + sizeof(CollisionShape*) + sizeof(unsigned short) + sizeof(unsigned short) + sizeof(Transform) + sizeof(List<uint64>) + sizeof(bool) + sizeof(bool)) { // Allocate memory for the components data allocate(INIT_NB_ALLOCATED_COMPONENTS); } // Allocate memory for a given number of components void ColliderComponents::allocate(uint32 nbComponentsToAllocate) { assert(nbComponentsToAllocate > mNbAllocatedComponents); // Size for the data of a single component (in bytes) const size_t totalSizeBytes = nbComponentsToAllocate * mComponentDataSize; // Allocate memory void* newBuffer = mMemoryAllocator.allocate(totalSizeBytes); assert(newBuffer != nullptr); // New pointers to components data Entity* newCollidersEntities = static_cast<Entity*>(newBuffer); Entity* newBodiesEntities = reinterpret_cast<Entity*>(newCollidersEntities + nbComponentsToAllocate); Collider** newColliders = reinterpret_cast<Collider**>(newBodiesEntities + nbComponentsToAllocate); int32* newBroadPhaseIds = reinterpret_cast<int32*>(newColliders + nbComponentsToAllocate); Transform* newLocalToBodyTransforms = reinterpret_cast<Transform*>(newBroadPhaseIds + nbComponentsToAllocate); CollisionShape** newCollisionShapes = reinterpret_cast<CollisionShape**>(newLocalToBodyTransforms + nbComponentsToAllocate); unsigned short* newCollisionCategoryBits = reinterpret_cast<unsigned short*>(newCollisionShapes + nbComponentsToAllocate); unsigned short* newCollideWithMaskBits = reinterpret_cast<unsigned short*>(newCollisionCategoryBits + nbComponentsToAllocate); Transform* newLocalToWorldTransforms = reinterpret_cast<Transform*>(newCollideWithMaskBits + nbComponentsToAllocate); List<uint64>* newOverlappingPairs = reinterpret_cast<List<uint64>*>(newLocalToWorldTransforms + nbComponentsToAllocate); bool* hasCollisionShapeChangedSize = reinterpret_cast<bool*>(newOverlappingPairs + nbComponentsToAllocate); bool* isTrigger = reinterpret_cast<bool*>(hasCollisionShapeChangedSize + nbComponentsToAllocate); // If there was already components before if (mNbComponents > 0) { // Copy component data from the previous buffer to the new one memcpy(newCollidersEntities, mCollidersEntities, mNbComponents * sizeof(Entity)); memcpy(newBodiesEntities, mBodiesEntities, mNbComponents * sizeof(Entity)); memcpy(newColliders, mColliders, mNbComponents * sizeof(Collider*)); memcpy(newBroadPhaseIds, mBroadPhaseIds, mNbComponents * sizeof(int32)); memcpy(newLocalToBodyTransforms, mLocalToBodyTransforms, mNbComponents * sizeof(Transform)); memcpy(newCollisionShapes, mCollisionShapes, mNbComponents * sizeof(CollisionShape*)); memcpy(newCollisionCategoryBits, mCollisionCategoryBits, mNbComponents * sizeof(unsigned short)); memcpy(newCollideWithMaskBits, mCollideWithMaskBits, mNbComponents * sizeof(unsigned short)); memcpy(newLocalToWorldTransforms, mLocalToWorldTransforms, mNbComponents * sizeof(Transform)); memcpy(newOverlappingPairs, mOverlappingPairs, mNbComponents * sizeof(List<uint64>)); memcpy(hasCollisionShapeChangedSize, mHasCollisionShapeChangedSize, mNbComponents * sizeof(bool)); memcpy(isTrigger, mIsTrigger, mNbComponents * sizeof(bool)); // Deallocate previous memory mMemoryAllocator.release(mBuffer, mNbAllocatedComponents * mComponentDataSize); } mBuffer = newBuffer; mCollidersEntities = newCollidersEntities; mBodiesEntities = newBodiesEntities; mCollidersEntities = newCollidersEntities; mColliders = newColliders; mBroadPhaseIds = newBroadPhaseIds; mLocalToBodyTransforms = newLocalToBodyTransforms; mCollisionShapes = newCollisionShapes; mCollisionCategoryBits = newCollisionCategoryBits; mCollideWithMaskBits = newCollideWithMaskBits; mLocalToWorldTransforms = newLocalToWorldTransforms; mOverlappingPairs = newOverlappingPairs; mHasCollisionShapeChangedSize = hasCollisionShapeChangedSize; mIsTrigger = isTrigger; mNbAllocatedComponents = nbComponentsToAllocate; } // Add a component void ColliderComponents::addComponent(Entity colliderEntity, bool isSleeping, const ColliderComponent& component) { // Prepare to add new component (allocate memory if necessary and compute insertion index) uint32 index = prepareAddComponent(isSleeping); // Insert the new component data new (mCollidersEntities + index) Entity(colliderEntity); new (mBodiesEntities + index) Entity(component.bodyEntity); mColliders[index] = component.collider; new (mBroadPhaseIds + index) int32(-1); new (mLocalToBodyTransforms + index) Transform(component.localToBodyTransform); mCollisionShapes[index] = component.collisionShape; new (mCollisionCategoryBits + index) unsigned short(component.collisionCategoryBits); new (mCollideWithMaskBits + index) unsigned short(component.collideWithMaskBits); new (mLocalToWorldTransforms + index) Transform(component.localToWorldTransform); new (mOverlappingPairs + index) List<uint64>(mMemoryAllocator); mHasCollisionShapeChangedSize[index] = false; mIsTrigger[index] = false; // Map the entity with the new component lookup index mMapEntityToComponentIndex.add(Pair<Entity, uint32>(colliderEntity, index)); mNbComponents++; assert(mDisabledStartIndex <= mNbComponents); } // Move a component from a source to a destination index in the components array // The destination location must contain a constructed object void ColliderComponents::moveComponentToIndex(uint32 srcIndex, uint32 destIndex) { const Entity colliderEntity = mCollidersEntities[srcIndex]; // Copy the data of the source component to the destination location new (mCollidersEntities + destIndex) Entity(mCollidersEntities[srcIndex]); new (mBodiesEntities + destIndex) Entity(mBodiesEntities[srcIndex]); mColliders[destIndex] = mColliders[srcIndex]; new (mBroadPhaseIds + destIndex) int32(mBroadPhaseIds[srcIndex]); new (mLocalToBodyTransforms + destIndex) Transform(mLocalToBodyTransforms[srcIndex]); mCollisionShapes[destIndex] = mCollisionShapes[srcIndex]; new (mCollisionCategoryBits + destIndex) unsigned short(mCollisionCategoryBits[srcIndex]); new (mCollideWithMaskBits + destIndex) unsigned short(mCollideWithMaskBits[srcIndex]); new (mLocalToWorldTransforms + destIndex) Transform(mLocalToWorldTransforms[srcIndex]); new (mOverlappingPairs + destIndex) List<uint64>(mOverlappingPairs[srcIndex]); mHasCollisionShapeChangedSize[destIndex] = mHasCollisionShapeChangedSize[srcIndex]; mIsTrigger[destIndex] = mIsTrigger[srcIndex]; // Destroy the source component destroyComponent(srcIndex); assert(!mMapEntityToComponentIndex.containsKey(colliderEntity)); // Update the entity to component index mapping mMapEntityToComponentIndex.add(Pair<Entity, uint32>(colliderEntity, destIndex)); assert(mMapEntityToComponentIndex[mCollidersEntities[destIndex]] == destIndex); } // Swap two components in the array void ColliderComponents::swapComponents(uint32 index1, uint32 index2) { // Copy component 1 data Entity colliderEntity1(mCollidersEntities[index1]); Entity bodyEntity1(mBodiesEntities[index1]); Collider* collider1 = mColliders[index1]; int32 broadPhaseId1 = mBroadPhaseIds[index1]; Transform localToBodyTransform1 = mLocalToBodyTransforms[index1]; CollisionShape* collisionShape1 = mCollisionShapes[index1]; unsigned short collisionCategoryBits1 = mCollisionCategoryBits[index1]; unsigned short collideWithMaskBits1 = mCollideWithMaskBits[index1]; Transform localToWorldTransform1 = mLocalToWorldTransforms[index1]; List<uint64> overlappingPairs = mOverlappingPairs[index1]; bool hasCollisionShapeChangedSize = mHasCollisionShapeChangedSize[index1]; bool isTrigger = mIsTrigger[index1]; // Destroy component 1 destroyComponent(index1); moveComponentToIndex(index2, index1); // Reconstruct component 1 at component 2 location new (mCollidersEntities + index2) Entity(colliderEntity1); new (mBodiesEntities + index2) Entity(bodyEntity1); mColliders[index2] = collider1; new (mBroadPhaseIds + index2) int32(broadPhaseId1); new (mLocalToBodyTransforms + index2) Transform(localToBodyTransform1); mCollisionShapes[index2] = collisionShape1; new (mCollisionCategoryBits + index2) unsigned short(collisionCategoryBits1); new (mCollideWithMaskBits + index2) unsigned short(collideWithMaskBits1); new (mLocalToWorldTransforms + index2) Transform(localToWorldTransform1); new (mOverlappingPairs + index2) List<uint64>(overlappingPairs); mHasCollisionShapeChangedSize[index2] = hasCollisionShapeChangedSize; mIsTrigger[index2] = isTrigger; // Update the entity to component index mapping mMapEntityToComponentIndex.add(Pair<Entity, uint32>(colliderEntity1, index2)); assert(mMapEntityToComponentIndex[mCollidersEntities[index1]] == index1); assert(mMapEntityToComponentIndex[mCollidersEntities[index2]] == index2); assert(mNbComponents == static_cast<uint32>(mMapEntityToComponentIndex.size())); } // Destroy a component at a given index void ColliderComponents::destroyComponent(uint32 index) { Components::destroyComponent(index); assert(mMapEntityToComponentIndex[mCollidersEntities[index]] == index); mMapEntityToComponentIndex.remove(mCollidersEntities[index]); mCollidersEntities[index].~Entity(); mBodiesEntities[index].~Entity(); mColliders[index] = nullptr; mLocalToBodyTransforms[index].~Transform(); mCollisionShapes[index] = nullptr; mLocalToWorldTransforms[index].~Transform(); mOverlappingPairs[index].~List<uint64>(); }
53.271552
130
0.710009
[ "object", "transform" ]
3c2aee303270adf89989a8501048678e0abdcbba
1,134
cpp
C++
src/backend/gporca/libgpos/src/task/CAutoSuspendAbort.cpp
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
1
2021-01-03T17:55:43.000Z
2021-01-03T17:55:43.000Z
src/backend/gporca/libgpos/src/task/CAutoSuspendAbort.cpp
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
16
2020-10-21T18:37:47.000Z
2021-01-13T01:01:15.000Z
src/backend/gporca/libgpos/src/task/CAutoSuspendAbort.cpp
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
1
2020-03-26T02:47:22.000Z
2020-03-26T02:47:22.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CAutoSuspendAbort.cpp // // @doc: // Auto suspend abort object //--------------------------------------------------------------------------- #include <stddef.h> #include "gpos/base.h" #include "gpos/task/CAutoSuspendAbort.h" #include "gpos/task/CTask.h" using namespace gpos; //--------------------------------------------------------------------------- // @function: // CAutoSuspendAbort::CAutoSuspendAbort // // @doc: // ctor // //--------------------------------------------------------------------------- CAutoSuspendAbort::CAutoSuspendAbort() { m_task = CTask::Self(); if (NULL != m_task) { m_task->SuspendAbort(); } } //--------------------------------------------------------------------------- // @function: // CAutoSuspendAbort::~CAutoSuspendAbort // // @doc: // dtor // //--------------------------------------------------------------------------- CAutoSuspendAbort::~CAutoSuspendAbort() { if (NULL != m_task) { m_task->ResumeAbort(); } } // EOF
19.894737
77
0.38448
[ "object" ]
3c2e94f867221b4240065aef0652376daca0b435
4,944
cc
C++
ui/gfx/image/image_skia.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
ui/gfx/image/image_skia.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
ui/gfx/image/image_skia.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/image/image_skia.h" #include <limits> #include <cmath> #include "base/logging.h" #include "base/stl_util.h" namespace gfx { ImageSkia::ImageSkia(const SkBitmap* bitmap) : size_(bitmap->width(), bitmap->height()), mip_map_build_pending_(false) { CHECK(bitmap); // TODO(pkotwicz): Add a CHECK to ensure that !bitmap->isNull() bitmaps_.push_back(bitmap); } ImageSkia::ImageSkia(const std::vector<const SkBitmap*>& bitmaps) : bitmaps_(bitmaps), mip_map_build_pending_(false) { CHECK(!bitmaps_.empty()); // TODO(pkotwicz): Add a CHECK to ensure that !bitmap->isNull() for each // vector element. // Assume that the smallest bitmap represents 1x scale factor. for (size_t i = 0; i < bitmaps_.size(); ++i) { gfx::Size bitmap_size(bitmaps_[i]->width(), bitmaps_[i]->height()); if (size_.IsEmpty() || bitmap_size.GetArea() < size_.GetArea()) size_ = bitmap_size; } } ImageSkia::~ImageSkia() { STLDeleteElements(&bitmaps_); } void ImageSkia::BuildMipMap() { mip_map_build_pending_ = true; } void ImageSkia::DrawToCanvasInt(gfx::Canvas* canvas, int x, int y) { SkPaint p; DrawToCanvasInt(canvas, x, y, p); } void ImageSkia::DrawToCanvasInt(gfx::Canvas* canvas, int x, int y, const SkPaint& paint) { if (IsZeroSized()) return; SkMatrix m = canvas->sk_canvas()->getTotalMatrix(); float scale_x = std::abs(SkScalarToFloat(m.getScaleX())); float scale_y = std::abs(SkScalarToFloat(m.getScaleY())); const SkBitmap* bitmap = GetBitmapForScale(scale_x, scale_y); if (mip_map_build_pending_) { const_cast<SkBitmap*>(bitmap)->buildMipMap(); mip_map_build_pending_ = false; } float bitmap_scale_x = static_cast<float>(bitmap->width()) / width(); float bitmap_scale_y = static_cast<float>(bitmap->height()) / height(); canvas->Save(); canvas->sk_canvas()->scale(1.0f / bitmap_scale_x, 1.0f / bitmap_scale_y); canvas->sk_canvas()->drawBitmap(*bitmap, SkFloatToScalar(x * bitmap_scale_x), SkFloatToScalar(y * bitmap_scale_y)); canvas->Restore(); } void ImageSkia::DrawToCanvasInt(gfx::Canvas* canvas, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h, bool filter) { SkPaint p; DrawToCanvasInt(canvas, src_x, src_y, src_w, src_h, dest_x, dest_y, dest_w, dest_h, filter, p); } void ImageSkia::DrawToCanvasInt(gfx::Canvas* canvas, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h, bool filter, const SkPaint& paint) { if (IsZeroSized()) return; SkMatrix m = canvas->sk_canvas()->getTotalMatrix(); float scale_x = std::abs(SkScalarToFloat(m.getScaleX())); float scale_y = std::abs(SkScalarToFloat(m.getScaleY())); const SkBitmap* bitmap = GetBitmapForScale(scale_x, scale_y); if (mip_map_build_pending_) { const_cast<SkBitmap*>(bitmap)->buildMipMap(); mip_map_build_pending_ = false; } float bitmap_scale_x = static_cast<float>(bitmap->width()) / width(); float bitmap_scale_y = static_cast<float>(bitmap->height()) / height(); canvas->Save(); canvas->sk_canvas()->scale(1.0f / bitmap_scale_x, 1.0f / bitmap_scale_y); canvas->DrawBitmapFloat(*bitmap, src_x * bitmap_scale_x, src_y * bitmap_scale_x, src_w * bitmap_scale_x, src_h * bitmap_scale_y, dest_x * bitmap_scale_x, dest_y * bitmap_scale_y, dest_w * bitmap_scale_x, dest_h * bitmap_scale_y, filter, paint); canvas->Restore(); } const SkBitmap* ImageSkia::GetBitmapForScale(float x_scale_factor, float y_scale_factor) const { // Get the desired bitmap width and height given |x_scale_factor|, // |y_scale_factor| and |size_| at 1x density. float desired_width = size_.width() * x_scale_factor; float desired_height = size_.height() * y_scale_factor; size_t closest_index = 0; float smallest_diff = std::numeric_limits<float>::max(); for (size_t i = 0; i < bitmaps_.size(); ++i) { if (bitmaps_[i]->isNull()) continue; float diff = std::abs(bitmaps_[i]->width() - desired_width) + std::abs(bitmaps_[i]->height() - desired_height); if (diff < smallest_diff) { closest_index = i; smallest_diff = diff; } } return bitmaps_[closest_index]; } } // namespace gfx
33.632653
79
0.622977
[ "vector" ]
3c31e5686a5c92a8773a8d75982acb155fbafaec
36,529
cpp
C++
Sources/Elastos/Frameworks/Droid/DevSamples/WifiDemo/src/elastos/devsamples/wifidemo/CActivityOne.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/DevSamples/WifiDemo/src/elastos/devsamples/wifidemo/CActivityOne.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/DevSamples/WifiDemo/src/elastos/devsamples/wifidemo/CActivityOne.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include <Elastos.Droid.App.h> #include <Elastos.Droid.Content.h> #include <Elastos.Droid.Net.h> #include <Elastos.Droid.Os.h> #include <Elastos.Droid.View.h> #include <Elastos.CoreLibrary.Utility.h> #include "CActivityOne.h" #include "R.h" #include <elastos/core/CoreUtils.h> #include <elastos/core/StringBuilder.h> #include <elastos/utility/logging/Logger.h> using Elastos::Droid::App::IAlertDialog; using Elastos::Droid::App::IAlertDialogBuilder; using Elastos::Droid::App::CAlertDialogBuilder; using Elastos::Droid::Content::EIID_IContext; using Elastos::Droid::Content::EIID_IDialogInterfaceOnClickListener; using Elastos::Droid::Graphics::IPixelFormat; using Elastos::Droid::Graphics::Drawable::IColorDrawable; using Elastos::Droid::Graphics::Drawable::CColorDrawable; using Elastos::Droid::Net::IConnectivityManager; using Elastos::Droid::Net::INetworkInfo; using Elastos::Droid::Os::IPowerManager; using Elastos::Droid::Os::IPowerManagerWakeLock; using Elastos::Droid::View::EIID_IViewOnTouchListener; using Elastos::Droid::View::EIID_IViewOnKeyListener; using Elastos::Droid::View::EIID_IViewOnClickListener; using Elastos::Droid::View::IViewParent; using Elastos::Droid::View::IGravity; using Elastos::Droid::View::IWindowManagerLayoutParams; using Elastos::Droid::View::CWindowManagerLayoutParams; using Elastos::Droid::View::Animation::IRotateAnimation; using Elastos::Droid::View::Animation::CRotateAnimation; using Elastos::Droid::View::Animation::IAlphaAnimation; using Elastos::Droid::View::Animation::CAlphaAnimation; using Elastos::Droid::View::Animation::ITranslateAnimation; using Elastos::Droid::View::Animation::CTranslateAnimation; using Elastos::Droid::View::Animation::IScaleAnimation; using Elastos::Droid::View::Animation::CScaleAnimation; using Elastos::Droid::Widget::EIID_IAdapterViewOnItemClickListener; using Elastos::Droid::Widget::EIID_IAdapterViewOnItemLongClickListener; using Elastos::Droid::Widget::EIID_IRadioGroupOnCheckedChangeListener; using Elastos::Droid::Widget::CPopupWindow; using Elastos::Droid::Widget::ICheckable; using Elastos::Droid::Widget::IArrayAdapter; using Elastos::Droid::Widget::CArrayAdapter; using Elastos::Droid::Widget::EIID_ITextView; using Elastos::Droid::Widget::CSimpleAdapter; using Elastos::Droid::Widget::ISimpleAdapter; using Elastos::Droid::Widget::IAdapter; using Elastos::Droid::Wifi::IScanResult; using Elastos::Droid::Wifi::IWifiConfiguration; using Elastos::Droid::Wifi::CWifiConfiguration; using Elastos::Droid::Wifi::IWifiConfigurationGroupCipher; using Elastos::Droid::Wifi::IWifiConfigurationKeyMgmt; using Elastos::Droid::Wifi::IWifiConfigurationPairwiseCipher; using Elastos::Droid::Wifi::IWifiConfigurationProtocol; using Elastos::Core::CoreUtils; using Elastos::Core::StringBuilder; using Elastos::Utility::IBitSet; using Elastos::Utility::IList; using Elastos::Utility::CArrayList; using Elastos::Utility::IMap; using Elastos::Utility::CHashMap; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace DevSamples { namespace WifiDemo { static const String DBG_TAG("CActivityOne"); //======================================================================= // CActivityOne::MyListener //======================================================================= CAR_INTERFACE_IMPL_7(CActivityOne::MyListener, Object, IViewOnTouchListener, IViewOnKeyListener, IViewOnClickListener, IAdapterViewOnItemClickListener, IAdapterViewOnItemLongClickListener, IDialogInterfaceOnClickListener, IRadioGroupOnCheckedChangeListener) CActivityOne::MyListener::MyListener( /* [in] */ CActivityOne* host) : mHost(host) {} CActivityOne::MyListener::~MyListener() { Logger::D("CActivityOne::MyListener", "destory ~MyListener(): %p", this); } ECode CActivityOne::MyListener::OnTouch( /* [in] */ IView* view, /* [in] */ IMotionEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Logger::D("CActivityOne", "OnTouch"); Int32 id; view->GetId(&id); if (id == R::id::myTextView) { ITextView::Probe(view)->SetText(CoreUtils::Convert("中文")); } if (result) { *result = FALSE;; } return NOERROR; } ECode CActivityOne::MyListener::OnItemClick( /* [in] */ IAdapterView* parent, /* [in] */ IView* view, /* [in] */ Int32 position, /* [in] */ Int64 id) { Logger::D("CActivityOne", "OnItemClick position = %d, id = %lld", position, id); StringBuilder sb("Choosed item "); sb += position; mHost->ShowAlert(sb.ToString()); return NOERROR; } ECode CActivityOne::MyListener::OnItemLongClick( /* [in] */ IAdapterView* parent, /* [in] */ IView* view, /* [in] */ Int32 position, /* [in] */ Int64 id, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Logger::D("CActivityOne", "OnItemLongClick position = %d, id = %lld", position, id); *result = TRUE; return NOERROR; } ECode CActivityOne::MyListener::OnClick( /* [in] */ IView* view) { Int32 id; view->GetId(&id); Logger::D("CActivityOne", "CActivityOne::MyListener::OnClick %08x", id); //if (id == R::id::DialogButton) { // Logger::D("CActivityOne", "Show Dilaog!"); // mHost->ShowDialog(0); //} //else if (id == R::id::PopupWindowButton) { // Logger::D("CActivityOne", "Show PopupWindow!"); // mHost->OnCreatePopupWindow(); //} //else if (id == R::id::PowerManagerButton) { // Logger::D("CActivityOne", "Test PowerManager!"); // mHost->OnTestPowerManager(); //} //else if (id == R::id::ConnectivityManagerButton) { // Logger::D("CActivityOne", "Test ConnectivityManager!"); // mHost->OnTestConnectivityManager(); //} //else if (id == R::id::WifiEnableButton) { Logger::D("CActivityOne", "Test WifiEnable!"); mHost->OnTestWifiEnable(); } else if (id == R::id::WifiDisableButton) { Logger::D("CActivityOne", "Test WifiDisable!"); mHost->OnTestWifiDisable(); } else if (id == R::id::WifiConnectButton) { Logger::D("CActivityOne", "Test WifiConnect!"); mHost->OnTestWifiConnect(); } else if (id == R::id::WifiStartScanButton) { Logger::D("CActivityOne", "Test WifiStartScan!"); mHost->OnTestWifiStartScan(); } else if (id == R::id::WifiDisableLogButton) { Logger::D("CActivityOne", "Test WifiDisableLog!"); mHost->OnTestWifiLog(FALSE); } else if (id == R::id::WifiEnableLogButton) { Logger::D("CActivityOne", "Test WifiEnableLog!"); mHost->OnTestWifiLog(TRUE); } else if (id == R::id::WifiClearConfigsButton) { Logger::D("CActivityOne", "Test WifiClearConfigs!"); mHost->OnTestClearWifiConfigurations(); } else if (id == R::id::RebootButton) { Logger::D("CActivityOne", "Test Reboot!"); mHost->OnTestReboot(String("Reboot")); } //else if (id == R::id::btn_close_popup) { // Logger::D("CActivityOne", "Dismiss PopupWindow!"); // mHost->mPopupWindow->Dismiss(); // mHost->mPopupWindow = NULL; // return NOERROR; //} //else if (id == R::id::AnamtionButton) { // Logger::D("CActivityOne", "AnimationButton"); // static Int32 count = 0; // count = count % 4; // if (count == 0) { // mHost->mDialogButton->StartAnimation(mHost->mAlphaAnimation); // } // else if (count == 1) { // mHost->mDialogButton->StartAnimation(mHost->mRotateAnimation); // } // else if (count == 2) { // mHost->mDialogButton->StartAnimation(mHost->mScaleAnimation); // } // else { // mHost->mDialogButton->StartAnimation(mHost->mTranslateAnimation); // } // count++; //} //else if (id == R::id::chkAndroid) { // Logger::D("CActivityOne", "Click Android CheckBox"); // ICheckable* checkable = ICheckable::Probe(mHost->mAndroidCheckBox); // checkable->SetChecked(TRUE); // checkable = ICheckable::Probe(mHost->mIosCheckBox); // checkable->SetChecked(FALSE); //} //else if (id == R::id::chkIos) { // Logger::D("CActivityOne", "Click iOS CheckBox"); // ICheckable* checkable = ICheckable::Probe(mHost->mAndroidCheckBox); // checkable->SetChecked(FALSE); // checkable = ICheckable::Probe(mHost->mIosCheckBox); // checkable->SetChecked(TRUE); //} return NOERROR; } ECode CActivityOne::MyListener::OnClick( /* [in] */ IDialogInterface* dialog, /* [in] */ Int32 which) { Logger::D("CActivityOne", "CActivityOne::MyListener::OnClick with IDialogInterface"); switch (which) { case IDialogInterface::BUTTON_POSITIVE: { Logger::D("CActivityOne", "点击了确定按钮"); AutoPtr<ICharSequence> ssidCS; ITextView::Probe(mHost->mSSIDEditText)->GetText((ICharSequence**)&ssidCS); String ssid; ssidCS->ToString(&ssid); AutoPtr<ICharSequence> pwCS; ITextView::Probe(mHost->mPWEditText)->GetText((ICharSequence**)&pwCS); String password; pwCS->ToString(&password); mHost->ConnectWifi(ssid, password); break; } case IDialogInterface::BUTTON_NEGATIVE: Logger::D("CActivityOne", "点击了取消按钮"); break; case IDialogInterface::BUTTON_NEUTRAL: Logger::D("CActivityOne", "点击了中立按钮"); break; default: break; } return NOERROR; } ECode CActivityOne::MyListener::OnKey( /* [in] */ IView * view, /* [in] */ Int32 keyCode, /* [in] */ IKeyEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Int32 id; view->GetId(&id); Int32 action; event->GetAction(&action); Char32 label; event->GetDisplayLabel(&label); Logger::D("CActivityOne", "CActivityOne::MyListener::OnKey: view %08x, keyCode: %d, '%c'", id, keyCode, (char)label); if (action == IKeyEvent::ACTION_DOWN) { if (keyCode == IKeyEvent::KEYCODE_0) { Logger::D("CActivityOne", "Key 0 is down."); } } else if (action == IKeyEvent::ACTION_UP) { } if (result) { *result = FALSE; } return NOERROR; } ECode CActivityOne::MyListener::OnCheckedChanged( /* [in] */ IRadioGroup* group, /* [in] */ Int32 checkedId) { Logger::I(DBG_TAG, "mWifiEnable will change from %d to %d", mHost->mWifiEnable, !mHost->mWifiEnable); mHost->mWifiEnable = !mHost->mWifiEnable; return NOERROR; } //======================================================================= // CActivityOne //======================================================================= CAR_OBJECT_IMPL(CActivityOne) ECode CActivityOne::constructor() { Logger::I(DBG_TAG, " >> constructor()"); mWifiEnable = TRUE; return Activity::constructor(); } ECode CActivityOne::OnCreate( /* [in] */ IBundle* savedInstanceState) { Logger::I(DBG_TAG, " >> OnCreate()"); Activity::OnCreate(savedInstanceState); // Setup ContentView // SetContentView(R::layout::main); // Setup TextView // AutoPtr<IView> temp = FindViewById(R::id::myTextView); mTextView = ITextView::Probe(temp); assert(mTextView != NULL); AutoPtr<MyListener> l = new MyListener(this); IViewOnClickListener* clickListener = (IViewOnClickListener*)l.Get(); //temp = FindViewById(R::id::myEditText); //mEditText = IEditText::Probe(temp); //assert(mEditText != NULL); //IViewOnKeyListener* keyListener = (IViewOnKeyListener*)l.Get(); //IView::Probe(mEditText)->SetOnKeyListener(keyListener); temp = FindViewById(R::id::mySSID); mSSIDEditText= IEditText::Probe(temp); assert(mSSIDEditText != NULL); temp = FindViewById(R::id::myPW); mPWEditText = IEditText::Probe(temp); assert(mPWEditText != NULL); // Setup ListView // //temp = FindViewById(R::id::myListView); //mListView = IListView::Probe(temp); //assert(mListView != NULL); //AutoPtr<IList> list; //CArrayList::New((IList**)&list); //for (Int32 i = 0; i < 15; ++i) { // StringBuilder sb("Item "); // sb += i; // list->Add(sb.ToCharSequence()); //} //AutoPtr<IArrayAdapter> adapter; //CArrayAdapter::New(this, R::layout::list_item, list, (IArrayAdapter**)&adapter); //assert(adapter != NULL); //AutoPtr<IAdapterView> ad = IAdapterView::Probe(mListView); //ad->SetAdapter(IAdapter::Probe(adapter)); //TEST SimpleAdapter //{ // AutoPtr<IList> listData; // CArrayList::New((IList**)&listData); // String key1("key1"); // String key2("key2"); // for (Int32 i = 0; i < 20; i++) { // AutoPtr<IMap> map; // CHashMap::New((IMap**)&map); // StringBuilder sb1("Itemkey1 "); // sb1 += i; // map->Put(CoreUtils::Convert(key1), sb1.ToCharSequence()); // StringBuilder sb2("Itemkey2 "); // sb2 += i; // map->Put(CoreUtils::Convert(key2), sb2.ToCharSequence()); // listData->Add(map); // } // AutoPtr<ArrayOf<String> > from = ArrayOf<String>::Alloc(2); // (*from)[0] = key1; // (*from)[1] = key2; // AutoPtr<ArrayOf<Int32> > to = ArrayOf<Int32>::Alloc(2); // (*to)[0] = R::id::textview1; // (*to)[1] = R::id::textview2; // AutoPtr<ISimpleAdapter> siAdapter; // CSimpleAdapter::New(this, listData, R::layout::view, from, to, // (ISimpleAdapter**)&siAdapter); // assert(siAdapter != NULL); // ad->SetAdapter(IAdapter::Probe(siAdapter)); //} ////TEST SimpleAdapter //AutoPtr<IColorDrawable> drawable; //CColorDrawable::New(0xFF0000FF, (IColorDrawable**)&drawable); //assert(drawable != NULL); //mListView->SetDivider(IDrawable::Probe(drawable)); //mListView->SetDividerHeight(1); //IAdapterViewOnItemClickListener* itemClickListener = (IAdapterViewOnItemClickListener*)l.Get(); //ad->SetOnItemClickListener(itemClickListener); //IAdapterViewOnItemLongClickListener* itemLongClickListener = (IAdapterViewOnItemLongClickListener*)l.Get(); //ad->SetOnItemLongClickListener(itemLongClickListener); //// Setup Buttons //// //mAnimationButton = FindViewById(R::id::AnamtionButton); //assert(mAnimationButton != NULL); //mAnimationButton->SetOnClickListener(clickListener); //mDialogButton = FindViewById(R::id::DialogButton); //assert(mDialogButton != NULL); //mDialogButton->SetOnClickListener(clickListener); //mDialogButton->SetOnKeyListener(keyListener); //mPopupWindowButton = FindViewById(R::id::PopupWindowButton); //assert(mPopupWindowButton != NULL); //mPopupWindowButton->SetOnClickListener(clickListener); //mPowerManagerButton = FindViewById(R::id::PowerManagerButton); //assert(mPowerManagerButton != NULL); //mPowerManagerButton->SetOnClickListener(clickListener); //mConnectivityManagerButton = FindViewById(R::id::ConnectivityManagerButton); //assert(mConnectivityManagerButton != NULL); //mConnectivityManagerButton->SetOnClickListener(clickListener); mWifiEnableButton = FindViewById(R::id::WifiEnableButton); assert(mWifiEnableButton != NULL); mWifiEnableButton->SetOnClickListener(clickListener); mWifiDisableButton = FindViewById(R::id::WifiDisableButton); assert(mWifiDisableButton != NULL); mWifiDisableButton->SetOnClickListener(clickListener); mWifiStartScanButton = FindViewById(R::id::WifiStartScanButton); assert(mWifiStartScanButton != NULL); mWifiStartScanButton->SetOnClickListener(clickListener); mWifiConnectButton = FindViewById(R::id::WifiConnectButton); assert(mWifiConnectButton != NULL); mWifiConnectButton->SetOnClickListener(clickListener); mWifiDisableLogButton = FindViewById(R::id::WifiDisableLogButton); assert(mWifiDisableLogButton != NULL); mWifiDisableLogButton->SetOnClickListener(clickListener); mWifiEnableLogButton = FindViewById(R::id::WifiEnableLogButton); assert(mWifiEnableLogButton != NULL); mWifiEnableLogButton->SetOnClickListener(clickListener); mWifiClearConfigsButton = FindViewById(R::id::WifiClearConfigsButton); assert(mWifiClearConfigsButton != NULL); mWifiClearConfigsButton->SetOnClickListener(clickListener); mRebootButton = FindViewById(R::id::RebootButton); assert(mRebootButton != NULL); mRebootButton->SetOnClickListener(clickListener); //// Setup CheckBox //// //temp = FindViewById(R::id::chkAndroid); //mAndroidCheckBox = ICheckBox::Probe(temp); //IView::Probe(mAndroidCheckBox)->SetOnClickListener(clickListener); //temp = FindViewById(R::id::chkIos); //mIosCheckBox = ICheckBox::Probe(temp); //IView::Probe(mIosCheckBox)->SetOnClickListener(clickListener); // RegisterForContextMenu(view); // AutoPtr<IViewParent> parent; // view->GetParent((IViewParent**)&parent); // mContent = IView::Probe(parent); // mContent->SetOnKeyListener(keyListener); // Setup Animations // //CAlphaAnimation::New(0.3f, 1.0f, (IAnimation**)&mAlphaAnimation); //mAlphaAnimation->SetDuration(3000); //CRotateAnimation::New(0.0f, +350.0f, IAnimation::RELATIVE_TO_SELF, // 0.5f,IAnimation::RELATIVE_TO_SELF, 0.5f, // (IAnimation**)&mRotateAnimation); //mRotateAnimation->SetDuration(3000); //CScaleAnimation::New(0.2f, 1.4f, 0.2f, 1.4f, IAnimation::RELATIVE_TO_SELF, // 0.5f, IAnimation::RELATIVE_TO_SELF, 0.5f, // (IAnimation**)&mScaleAnimation); //mScaleAnimation->SetDuration(3000); //CTranslateAnimation::New(300.0f, -20.0f, -10.0f, 30.0f, // (IAnimation**)&mTranslateAnimation); //mTranslateAnimation->SetDuration(3000); // CreateNavigationBar(); //temp = FindViewById(R::id::radioSex); //mRadioSex = IRadioGroup::Probe(temp); //mRadioSex->SetOnCheckedChangeListener(l); AutoPtr<IInterface> obj; GetSystemService(IContext::WIFI_SERVICE, (IInterface**)&obj); mWifiManager = IWifiManager::Probe(obj); assert(mWifiManager != NULL); return NOERROR; } ECode CActivityOne::OnStart() { Logger::I(DBG_TAG, " >> OnStart()"); return Activity::OnStart(); } ECode CActivityOne::OnResume() { Logger::I(DBG_TAG, " >> OnResume()"); return Activity::OnResume(); } ECode CActivityOne::OnPause() { Logger::I(DBG_TAG, " >> OnPause()"); return Activity::OnPause(); } ECode CActivityOne::OnStop() { Logger::I(DBG_TAG, " >> OnStop()"); return Activity::OnStop(); } ECode CActivityOne::OnDestroy() { Logger::I(DBG_TAG, " >> OnDestroy()"); return Activity::OnDestroy(); } ECode CActivityOne::OnActivityResult( /* [in] */ Int32 requestCode, /* [in] */ Int32 resultCode, /* [in] */ IIntent *data) { Logger::I(DBG_TAG, " >> OnActivityResult()"); return Activity::OnActivityResult(requestCode, resultCode, data); } ECode CActivityOne::ShowAlert( /* [in] */ const String& info) { AutoPtr<IAlertDialogBuilder> builder; CAlertDialogBuilder::New(this, (IAlertDialogBuilder**)&builder); builder->SetTitle(CoreUtils::Convert("alert")); builder->SetMessage(CoreUtils::Convert(info)); // Setup Button // AutoPtr<MyListener> l = new MyListener(this); IDialogInterfaceOnClickListener* clickListener = (IDialogInterfaceOnClickListener*)l.Get(); builder->SetPositiveButton(CoreUtils::Convert("确定"), clickListener); builder->SetNegativeButton(CoreUtils::Convert("Cancel"), clickListener); // Create Dialog // AutoPtr<IAlertDialog> dlg; builder->Create((IAlertDialog**)&dlg); // Show Dialog // IDialog::Probe(dlg)->Show(); return NOERROR; } AutoPtr<IDialog> CActivityOne::OnCreateDialog( /* [in] */ Int32 id) { Logger::D("CActivityOne", "CActivityOne::OnCreateDialog"); AutoPtr<IAlertDialogBuilder> builder; CAlertDialogBuilder::New(this, (IAlertDialogBuilder**)&builder); builder->SetTitle(CoreUtils::Convert("普通对话框")); builder->SetMessage(CoreUtils::Convert("这是一个普通对话框")); // Setup Button // AutoPtr<MyListener> l = new MyListener(this); IDialogInterfaceOnClickListener* clickListener = (IDialogInterfaceOnClickListener*)l.Get(); builder->SetPositiveButton(CoreUtils::Convert("确定"), clickListener); builder->SetNeutralButton(CoreUtils::Convert("中立"), clickListener); builder->SetNegativeButton(CoreUtils::Convert("取消"), clickListener); // Create Dialog // AutoPtr<IAlertDialog> dlg; builder->Create((IAlertDialog**)&dlg); // IDialogInterface* di = IDialogInterface::Probe(dlg); return IDialog::Probe(dlg); } ECode CActivityOne::OnCreateContextMenu( /* [in] */ IContextMenu* menu, /* [in] */ IView* v, /* [in] */ IContextMenuInfo* menuInfo) { Logger::D("CActivityOne", "CActivityOne::OnCreateContextMenu"); AutoPtr<IMenu> menuObj = IMenu::Probe(menu); AutoPtr<IMenuItem> item; menuObj->Add(0, 1, 1, CoreUtils::Convert("ctxItem1"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 2, 2, CoreUtils::Convert("ctxItem2"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 3, 3, CoreUtils::Convert("ctxItem3"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 4, 4, CoreUtils::Convert("ctxItem4"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 5, 5, CoreUtils::Convert("ctxItem5"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 6, 6, CoreUtils::Convert("ctxItem6"), (IMenuItem**)&item); item = NULL; menuObj->Add(0, 7, 7, CoreUtils::Convert("ctxItem7"), (IMenuItem**)&item); return NOERROR; } ECode CActivityOne::CreateNavigationBar() { AutoPtr<IInterface> obj; GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&obj); AutoPtr<ILayoutInflater> inflater = ILayoutInflater::Probe(obj); AutoPtr<IView> navigationBar; inflater->Inflate(R::layout::navigationbar, NULL, (IView**)&navigationBar); AutoPtr<IWindowManagerLayoutParams> lp; CWindowManagerLayoutParams::New( IViewGroupLayoutParams::MATCH_PARENT, IViewGroupLayoutParams::MATCH_PARENT, IWindowManagerLayoutParams::TYPE_NAVIGATION_BAR, 0 | IWindowManagerLayoutParams::FLAG_TOUCHABLE_WHEN_WAKING | IWindowManagerLayoutParams::FLAG_NOT_FOCUSABLE | IWindowManagerLayoutParams::FLAG_NOT_TOUCH_MODAL | IWindowManagerLayoutParams::FLAG_SPLIT_TOUCH, IPixelFormat::OPAQUE, (IWindowManagerLayoutParams**)&lp); lp->SetGravity(IGravity::BOTTOM | IGravity::FILL_HORIZONTAL); lp->SetTitle(CoreUtils::Convert("NavigationBar")); AutoPtr<MyListener> l = new MyListener(this); IViewOnClickListener* clickListener = (IViewOnClickListener*)l.Get(); navigationBar->FindViewById(R::id::menu, (IView**)&mBack); assert(mBack != NULL); mBack->SetOnClickListener(clickListener); navigationBar->FindViewById(R::id::back, (IView**)&mHome); assert(mHome != NULL); mHome->SetOnClickListener(clickListener); navigationBar->FindViewById(R::id::home, (IView**)&mMenu); assert(mMenu != NULL); mMenu->SetOnClickListener(clickListener); // AutoPtr<IWindowManager> wm; // CWindowManagerImpl::AcquireSingleton((IWindowManager**)&wm); // wm->AddView(navigationBar, lp); return NOERROR; } ECode CActivityOne::OnCreatePopupWindow() { Logger::D("CActivityOne", "CActivityOne::OnCreatePopupWindow()"); mPopupWindow = NULL; AutoPtr<IInterface> obj; GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&obj); AutoPtr<ILayoutInflater> inflater = ILayoutInflater::Probe(obj); AutoPtr<IView> layout; inflater->Inflate(R::layout::popupwindow, NULL, (IView**)&layout); CPopupWindow::New(layout, 350, 350, TRUE, (IPopupWindow**)&mPopupWindow); mPopupWindow->ShowAtLocation(layout, IGravity::CENTER, 0, 0); // Setup TextView // AutoPtr<IView> temp; layout->FindViewById(R::id::txtView, (IView**)&temp); AutoPtr<ITextView> textView = ITextView::Probe(temp); assert(textView != NULL); textView->SetText(CoreUtils::Convert("PopupWindow 测试程序!")); // Setup Button // AutoPtr<IView> dismissButton; layout->FindViewById(R::id::btn_close_popup, (IView**)&dismissButton); assert(dismissButton != NULL); AutoPtr<MyListener> l = new MyListener(this); IViewOnClickListener* clickListener = (IViewOnClickListener*)l.Get(); dismissButton->SetOnClickListener(clickListener); return NOERROR; } ECode CActivityOne::OnTestPowerManager() { // AutoPtr<IInterface> obj; // GetSystemService(IContext::POWER_SERVICE, (IInterface**)&obj); // AutoPtr<IPowerManager> pm = IPowerManager::Probe(obj); // assert(pm != NULL); // AutoPtr<IPowerManagerWakeLock> wl; // pm->NewWakeLock(IPowerManager::SCREEN_DIM_WAKE_LOCK, String("My Tag"), (IPowerManagerWakeLock**)&wl); // assert(wl != NULL); // wl->AcquireLock(); // // ..screen will stay on during this section.. // wl->ReleaseLock(); AutoPtr<IInterface> obj; GetSystemService(IContext::WIFI_SERVICE, (IInterface**)&obj); AutoPtr<IWifiManager> wifi = IWifiManager::Probe(obj); assert(wifi != NULL); Boolean result; wifi->SetWifiEnabled(TRUE, &result); Logger::D("CActivityOne", "SetWifiEnabled %s", result ? "succeeded!" : "failed!"); sleep(5); wifi->StartScan(&result); Logger::D("CActivityOne", "StartScan %s", result ? "succeeded!" : "failed!"); sleep(5); //AutoPtr<IList> list; //wifi->GetScanResults((IList**)&list); //Logger::D("CActivityOne", "GetScanResults %s", list != NULL ? "succeeded!" : "failed!"); //if (list != NULL) { // Int32 size; // list->GetSize(&size); // for (Int32 i = 0; i < size; ++i) { // AutoPtr<IInterface> obj; // list->Get(i, (IInterface**)&obj); // IScanResult* result = IScanResult::Probe(obj); // String ssid, bssid; // result->GetSSID(&ssid); // result->GetBSSID(&bssid); // Logger::D("CActivityOne", "ssid: %s, bssid: %s", ssid.string(), bssid.string()); // } //} //AutoPtr<IWifiConfiguration> wifiConfig; //CWifiConfiguration::New((IWifiConfiguration**)&wifiConfig); //wifiConfig->SetSSID(String("\"Wireless-Kortide\"")); //wifiConfig->SetPreSharedKey(String("\"Elastos2011\"")); //AutoPtr<IBitSet> groupCiphers, keyMgmt, pairwiseCiphers, protocols; //wifiConfig->GetAllowedGroupCiphers((IBitSet**)&groupCiphers); //groupCiphers->Set(IWifiConfigurationGroupCipher::TKIP); //groupCiphers->Set(IWifiConfigurationGroupCipher::CCMP); //wifiConfig->GetAllowedKeyManagement((IBitSet**)&keyMgmt); //keyMgmt->Set(IWifiConfigurationKeyMgmt::WPA_PSK); //wifiConfig->GetAllowedPairwiseCiphers((IBitSet**)&pairwiseCiphers); //pairwiseCiphers->Set(IWifiConfigurationPairwiseCipher::TKIP); //pairwiseCiphers->Set(IWifiConfigurationPairwiseCipher::CCMP); //wifiConfig->GetAllowedProtocols((IBitSet**)&protocols); //protocols->Set(IWifiConfigurationProtocol::RSN); //Int32 netId; //ECode ec = wifi->AddNetwork(wifiConfig, &netId); //Logger::D("CActivityOne", "AddNetwork %s, netId: %d", SUCCEEDED(ec) ? "succeeded!" : "failed!", netId); //wifi->EnableNetwork(netId, TRUE, &result); //Logger::D("CActivityOne", "EnableNetwork %s", result ? "succeeded!" : "failed!"); return NOERROR; } ECode CActivityOne::OnTestConnectivityManager() { AutoPtr<IInterface> obj; GetSystemService(IContext::CONNECTIVITY_SERVICE, (IInterface**)&obj); AutoPtr<IConnectivityManager> conn = IConnectivityManager::Probe(obj); assert(conn != NULL); AutoPtr<INetworkInfo> info; conn->GetNetworkInfo(IConnectivityManager::TYPE_WIFI, (INetworkInfo**)&info); Logger::D("CActivityOne", "NetworkInfo: %s", TO_CSTR(info)); return NOERROR; } ECode CActivityOne::OnTestWifiEnable() { Logger::D("CActivityOne", "OnTestWifiEnable enter"); assert(mWifiManager != NULL); Logger::D("CActivityOne", "wifiManager: %p", mWifiManager.Get()); Boolean bTemp = FALSE; //if (mWifiEnable) { // wifiManager->SetWifiEnabled(TRUE, &bTemp); // if (bTemp) { // Logger::D("CActivityOne", "wifiEnabled success"); // wifiManager->EnableVerboseLogging(10); // } // else { // Logger::D("CActivityOne", "wifiEnabled fail"); // wifiManager->EnableVerboseLogging(0); // } //} //else { // wifiManager->EnableVerboseLogging(0); // wifiManager->SetWifiEnabled(FALSE, &bTemp); //} mWifiManager->SetWifiEnabled(TRUE, &bTemp); if (bTemp) { Logger::D("CActivityOne", "wifiEnabled success"); //mWifiManager->EnableVerboseLogging(10); } else { Logger::D("CActivityOne", "wifiEnabled fail"); //mWifiManager->EnableVerboseLogging(0); } return NOERROR; } ECode CActivityOne::OnTestWifiDisable() { Logger::D("CActivityOne", "OnTestWifiDisable enter"); assert(mWifiManager != NULL); Logger::D("CActivityOne", "wifiManager: %p", mWifiManager.Get()); Boolean bTemp = FALSE; mWifiManager->SetWifiEnabled(FALSE, &bTemp); if (bTemp) { Logger::D("CActivityOne", "wifiDisabled success"); //mWifiManager->EnableVerboseLogging(0); } else { Logger::D("CActivityOne", "wifiDisabled fail"); //mWifiManager->EnableVerboseLogging(0); } return NOERROR; } ECode CActivityOne::OnTestWifiStartScan() { Boolean result; mWifiManager->StartScan(&result); Logger::D("CActivityOne", "StartScan %s", result ? "succeeded!" : "failed!"); //sleep(5); return NOERROR; } ECode CActivityOne::OnTestWifiConnect() { AutoPtr<IList> list; mWifiManager->GetScanResults((IList**)&list); Logger::D("CActivityOne", "GetScanResults %s", list != NULL ? "succeeded!" : "failed!"); if (list != NULL) { Int32 size; list->GetSize(&size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; list->Get(i, (IInterface**)&obj); IScanResult* result = IScanResult::Probe(obj); String ssid, bssid; Int32 level; result->GetSSID(&ssid); result->GetBSSID(&bssid); result->GetLevel(&level); Logger::D("CActivityOne", "%d, ssid: %s, bssid: %s, level:%d", i, ssid.string(), bssid.string(), level); } } AutoPtr<ICharSequence> ssidCS; ITextView::Probe(mSSIDEditText)->GetText((ICharSequence**)&ssidCS); String ssid; ssidCS->ToString(&ssid); AutoPtr<ICharSequence> pwCS; ITextView::Probe(mPWEditText)->GetText((ICharSequence**)&pwCS); String password; pwCS->ToString(&password); ShowAlert(String("try to connect ") + ssid + String(" with password ") + password); return NOERROR; } ECode CActivityOne::ConnectWifi( /* [in] */ const String& ssid, /* [in] */ const String& passwd) { Logger::D("CActivityOne", " ConnectWifi(), ssid:%s, passwd:%s", ssid.string(), passwd.string()); Boolean result; AutoPtr<IWifiConfiguration> wifiConfig; CWifiConfiguration::New((IWifiConfiguration**)&wifiConfig); wifiConfig->SetSSID(String("\"")+ssid+String("\"")); wifiConfig->SetPreSharedKey(String("\"")+passwd+String("\"")); AutoPtr<IBitSet> groupCiphers, keyMgmt, pairwiseCiphers, protocols; wifiConfig->GetAllowedGroupCiphers((IBitSet**)&groupCiphers); groupCiphers->Set(IWifiConfigurationGroupCipher::TKIP); groupCiphers->Set(IWifiConfigurationGroupCipher::CCMP); wifiConfig->GetAllowedKeyManagement((IBitSet**)&keyMgmt); keyMgmt->Set(IWifiConfigurationKeyMgmt::WPA_PSK); wifiConfig->GetAllowedPairwiseCiphers((IBitSet**)&pairwiseCiphers); pairwiseCiphers->Set(IWifiConfigurationPairwiseCipher::TKIP); pairwiseCiphers->Set(IWifiConfigurationPairwiseCipher::CCMP); wifiConfig->GetAllowedProtocols((IBitSet**)&protocols); protocols->Set(IWifiConfigurationProtocol::RSN); String strWifiConfig; IObject::Probe(wifiConfig)->ToString(&strWifiConfig); Logger::D("CActivityOne", "Before AddNetwork %s", strWifiConfig.string()); Int32 netId = -1; ECode ec = mWifiManager->AddNetwork(wifiConfig, &netId); Logger::D("CActivityOne", "AddNetwork %s, netId: %d", SUCCEEDED(ec) ? "succeeded!" : "failed!", netId); mWifiManager->EnableNetwork(netId, TRUE, &result); Logger::D("CActivityOne", "EnableNetwork %s", result ? "succeeded!" : "failed!"); return NOERROR; } ECode CActivityOne::OnTestWifiLog( /* [in] */ Boolean enable) { Logger::D("CActivityOne", "%s Wifi Log", enable? "Enable": "Disable"); if (enable) { mWifiManager->EnableVerboseLogging(10); } else { mWifiManager->EnableVerboseLogging(0); } return NOERROR; } ECode CActivityOne::OnTestClearWifiConfigurations() { Logger::D("CActivityOne", "try to clear the wifi configurations"); AutoPtr<IList> configs; mWifiManager->GetConfiguredNetworks((IList**)&configs); if (configs != NULL) { Int32 size; configs->GetSize(&size); Logger::D("CActivityOne", "Get %d WifiConfiguration!", size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; configs->Get(i, (IInterface**)&obj); IWifiConfiguration* wifiConfig = IWifiConfiguration::Probe(obj); if (wifiConfig == NULL) { Logger::D("CActivityOne", "the %dth is not a WifiConfiguration !", i); continue; } else { String strWifiConfig; IObject::Probe(wifiConfig)->ToString(&strWifiConfig); Logger::D("CActivityOne", "the %dth AddNetwork is: \n%s", i, strWifiConfig.string()); } Int32 networkId = -1; wifiConfig->GetNetworkId(&networkId); Boolean removed; mWifiManager->RemoveNetwork(networkId, &removed); if (removed) { Logger::D("CActivityOne", "success to RemoveNetwork with networkID:%d", networkId); } else { Logger::D("CActivityOne", "fail to RemoveNetwork with networkID:%d", networkId); } } Logger::D("CActivityOne", "finish clear the wifi configurations"); } else { Logger::D("CActivityOne", "ERROR in GetConfiguredNetworks"); } return NOERROR; } ECode CActivityOne::OnTestPing( /* [in] */ const String& targetUrl) { String url; if (targetUrl.IsNullOrEmpty()) url = String("www.baidu.com"); else url = targetUrl; ShowAlert(String("try to ping ") + url); return NOERROR; } ECode CActivityOne::OnTestReboot( /* [in] */ const String& info) { AutoPtr<IInterface> obj; GetSystemService(IContext::POWER_SERVICE, (IInterface**)&obj); AutoPtr<IPowerManager> powerManager = IPowerManager::Probe(obj); if (powerManager == NULL) { Logger::D("CActivityOne", "OnTestReboot get power manager failed!"); return NOERROR; } powerManager->Reboot(String(NULL)); //Will not return if the reboot is successful. Logger::D("CActivityOne", "OnTestReboot Reboot return!"); return NOERROR; } } // namespace TextViewDemo } // namespace DevSamples } // namespace Elastos
33.823148
116
0.647212
[ "object" ]
3c3251f7dc64e373c62f7d72ca34ba9e01d42465
64,200
cpp
C++
src/SSVOpenHexagon/Core/HGScripting.cpp
IvoryDuke/SSVOpenHexagon
54dd476e93869d563c1b040ace269b549d3224c8
[ "AFL-3.0" ]
null
null
null
src/SSVOpenHexagon/Core/HGScripting.cpp
IvoryDuke/SSVOpenHexagon
54dd476e93869d563c1b040ace269b549d3224c8
[ "AFL-3.0" ]
null
null
null
src/SSVOpenHexagon/Core/HGScripting.cpp
IvoryDuke/SSVOpenHexagon
54dd476e93869d563c1b040ace269b549d3224c8
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2020 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #include "SSVOpenHexagon/Global/Assets.hpp" #include "SSVOpenHexagon/Utils/Utils.hpp" #include "SSVOpenHexagon/Utils/Concat.hpp" #include "SSVOpenHexagon/Utils/ScopeGuard.hpp" #include "SSVOpenHexagon/Core/HexagonGame.hpp" #include "SSVOpenHexagon/Components/CCustomWallHandle.hpp" #include "SSVOpenHexagon/Core/LuaScripting.hpp" #include "SSVOpenHexagon/Utils/TypeWrapper.hpp" #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <algorithm> namespace hg { template <typename F> Utils::LuaMetadataProxy addLuaFn( Lua::LuaContext& lua, const std::string& name, F&& f) { lua.writeVariable(name, std::forward<F>(f)); return Utils::LuaMetadataProxy{ Utils::TypeWrapper<F>{}, LuaScripting::getMetadata(), name}; } void HexagonGame::initLua_Utils() { // ------------------------------------------------------------------------ // Used internally to track values in the console. lua.writeVariable( "u_impl_addTrackedResult", [this](const std::string& result) { ilcLuaTrackedResults.emplace_back(result); }); // ------------------------------------------------------------------------ addLuaFn(lua, "u_setFlashEffect", // [this](float mIntensity) { status.flashEffect = mIntensity; }) .arg("value") .doc("Flash the screen with `$0` intensity (from 0 to 255)."); addLuaFn(lua, "u_log", // [this](const std::string& mLog) { ssvu::lo("lua") << mLog << '\n'; ilcCmdLog.emplace_back("[lua]: " + mLog + '\n'); }) .arg("message") .doc("Print out `$0` to the console."); addLuaFn(lua, "u_execScript", // [this](const std::string& mScriptName) { runLuaFile( Utils::getDependentScriptFilename(execScriptPackPathContext, levelData->packPath.getStr(), mScriptName)); }) .arg("scriptFilename") .doc("Execute the script located at `<pack>/Scripts/$0`."); addLuaFn(lua, "u_execDependencyScript", // [this](const std::string& mPackDisambiguator, const std::string& mPackName, const std::string& mPackAuthor, const std::string& mScriptName) { Utils::withDependencyScriptFilename( [this](const std::string& filename) { runLuaFile(filename); }, execScriptPackPathContext, assets, getPackData(), mPackDisambiguator, mPackName, mPackAuthor, mScriptName); }) .arg("packDisambiguator") .arg("packName") .arg("packAuthor") .arg("scriptFilename") .doc( "Execute the script provided by the dependee pack with " "disambiguator `$0`, name `$1`, author `$2`, located at " "`<dependeePack>/Scripts/$3`."); addLuaFn(lua, "u_isKeyPressed", [this](int mKey) { return window.getInputState()[ssvs::KKey(mKey)]; }) .arg("keyCode") .doc( "Return `true` if the keyboard key with code `$0` is being " "pressed, `false` otherwise. The key code must match the " "definition of the SFML `sf::Keyboard::Key` enumeration."); addLuaFn(lua, "u_haltTime", // [this](double mDuration) { status.pauseTime(ssvu::getFTToSeconds(mDuration)); }) .arg("duration") .doc("Pause the game timer for `$0` seconds."); addLuaFn(lua, "u_clearWalls", // [this] { walls.clear(); }) .doc("Remove all existing walls."); addLuaFn(lua, "u_getPlayerAngle", // [this] { return player.getPlayerAngle(); }) .doc("Return the current angle of the player, in radians."); addLuaFn(lua, "u_setPlayerAngle", [this](float newAng) { player.setPlayerAngle(newAng); }) .arg("angle") .doc("Set the current angle of the player to `$0`, in radians."); addLuaFn(lua, "u_isMouseButtonPressed", [this](int mKey) { return window.getInputState()[ssvs::MBtn(mKey)]; }) .arg("buttonCode") .doc( "Return `true` if the mouse button with code `$0` is being " "pressed, `false` otherwise. The button code must match the " "definition of the SFML `sf::Mouse::Button` enumeration."); addLuaFn(lua, "u_isFastSpinning", // [this] { return status.fastSpin > 0; }) .doc( "Return `true` if the camera is currently \"fast spinning\", " "`false` otherwise."); addLuaFn(lua, "u_forceIncrement", // [this] { incrementDifficulty(); }) .doc( "Immediately force a difficulty increment, regardless of the " "chosen automatic increment parameters."); addLuaFn(lua, "u_getDifficultyMult", // [this] { return difficultyMult; }) .doc("Return the current difficulty multiplier."); addLuaFn(lua, "u_getSpeedMultDM", // [this] { return getSpeedMultDM(); }) .doc( "Return the current speed multiplier, adjusted for the chosen " "difficulty multiplier."); addLuaFn(lua, "u_getDelayMultDM", // [this] { return getDelayMultDM(); }) .doc( "Return the current delay multiplier, adjusted for the chosen " "difficulty multiplier."); addLuaFn(lua, "u_swapPlayer", // [this](bool mPlaySound) { performPlayerSwap(mPlaySound); }) .arg("playSound") .doc( "Force-swaps (180 degrees) the player when invoked. If `$0` is " "`true`, the swap sound will be played."); } void HexagonGame::initLua_AudioControl() { addLuaFn(lua, "a_setMusic", // [this](const std::string& mId) { musicData = assets.getMusicData(levelData->packId, mId); musicData.firstPlay = true; stopLevelMusic(); playLevelMusic(); }) .arg("musicId") .doc( "Stop the current music and play the music with id `$0`. The id is " "defined in the music `.json` file, under `\"id\"`."); addLuaFn(lua, "a_setMusicSegment", // [this](const std::string& mId, int segment) { musicData = assets.getMusicData(levelData->packId, mId); stopLevelMusic(); playLevelMusicAtTime(musicData.getSegment(segment).time); }) .arg("musicId") .arg("segment") .doc( "Stop the current music and play the music with id `$0`, starting " "at segment `$1`. Segments are defined in the music `.json` file, " "under `\"segments\"`."); addLuaFn(lua, "a_setMusicSeconds", // [this](const std::string& mId, float mTime) { musicData = assets.getMusicData(levelData->packId, mId); stopLevelMusic(); playLevelMusicAtTime(mTime); }) .arg("musicId") .arg("time") .doc( "Stop the current music and play the music with id `$0`, starting " "at time `$1` (in seconds)."); addLuaFn(lua, "a_playSound", // [this](const std::string& mId) { assets.playSound(mId); }) .arg("soundId") .doc( "Play the sound with id `$0`. The id must be registered in " "`assets.json`, under `\"soundBuffers\"`."); addLuaFn(lua, "a_playPackSound", // [this](const std::string& fileName) { assets.playPackSound(getPackId(), fileName); }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "plays the specified file `$0`."); addLuaFn(lua, "a_syncMusicToDM", // [this](bool value) { levelStatus.syncMusicToDM = value; sf::Music* current(assets.getMusicPlayer().getCurrent()); if(current == nullptr) { return; } setMusicPitch(*current); }) .arg("value") .doc( "This function, when called, overrides the user's preference of " "adjusting the music's pitch to the difficulty multiplier. Useful " "for levels that rely on the music to time events."); addLuaFn(lua, "a_setMusicPitch", // [this](float mPitch) { levelStatus.musicPitch = mPitch; sf::Music* current(assets.getMusicPlayer().getCurrent()); if(current == nullptr) { return; } }) .arg("pitch") .doc( "Manually adjusts the pitch of the music by multiplying it by " "`$0`. The amount the pitch shifts may change on DM multiplication " "and user's preference of the music pitch. **Negative values will " "not work!**"); addLuaFn(lua, "a_overrideBeepSound", // [this](const std::string& mId) { levelStatus.beepSound = getPackId() + "_" + mId; }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "sets the specified file `$0` to be the new beep sound. This only " "applies to the particular level where this function is called."); addLuaFn(lua, "a_overrideIncrementSound", // [this](const std::string& mId) { levelStatus.levelUpSound = getPackId() + "_" + mId; }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "sets the specified file `$0` to be the new increment sound. This " "only " "applies to the particular level where this function is called."); addLuaFn(lua, "a_overrideSwapSound", // [this](const std::string& mId) { levelStatus.swapSound = getPackId() + "_" + mId; }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "sets the specified file `$0` to be the new swap sound. This only " "applies to the particular level where this function is called."); addLuaFn(lua, "a_overrideDeathSound", // [this](const std::string& mId) { levelStatus.deathSound = getPackId() + "_" + mId; }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "sets the specified file `$0` to be the new death sound. This only " "applies to the particular level where this function is called."); } void HexagonGame::initLua_MainTimeline() { addLuaFn(lua, "t_eval", [this](const std::string& mCode) { timeline.append_do([=, this] { Utils::runLuaCode(lua, mCode); }); }) .arg("code") .doc( "*Add to the main timeline*: evaluate the Lua code specified in " "`$0`."); addLuaFn(lua, "t_clear", [this]() { timeline.clear(); }).doc("Clear the main timeline."); addLuaFn(lua, "t_kill", // [this] { timeline.append_do([this] { death(true); }); }) .doc("*Add to the main timeline*: kill the player."); addLuaFn(lua, "t_wait", [this]( double mDuration) { timeline.append_wait_for_sixths(mDuration); }) .arg("duration") .doc( "*Add to the main timeline*: wait for `$0` frames (under the " "assumption of a 60 FPS frame rate)."); addLuaFn(lua, "t_waitS", // [this]( double mDuration) { timeline.append_wait_for_seconds(mDuration); }) .arg("duration") .doc("*Add to the main timeline*: wait for `$0` seconds."); addLuaFn(lua, "t_waitUntilS", // [this](double mDuration) { timeline.append_wait_until_fn([this, mDuration] { return status.getLevelStartTP() + std::chrono::milliseconds( static_cast<int>(mDuration * 1000.0)); }); }) .arg("duration") .doc( "*Add to the main timeline*: wait until the timer reaches `$0` " "seconds."); } void HexagonGame::initLua_EventTimeline() { addLuaFn(lua, "e_eval", [this](const std::string& mCode) { eventTimeline.append_do( [=, this] { Utils::runLuaCode(lua, mCode); }); }) .arg("code") .doc( "*Add to the event timeline*: evaluate the Lua code specified in " "`$0`. (This is the closest you'll get to 1.92 events)"); addLuaFn(lua, "e_kill", // [this] { eventTimeline.append_do([this] { death(true); }); }) .doc("*Add to the event timeline*: kill the player."); addLuaFn(lua, "e_stopTime", // [this](double mDuration) { eventTimeline.append_do([=, this] { status.pauseTime(ssvu::getFTToSeconds(mDuration)); }); }) .arg("duration") .doc( "*Add to the event timeline*: pause the game timer for `$0` frames " "(under the assumption of a 60 FPS frame rate)."); addLuaFn(lua, "e_stopTimeS", // [this](double mDuration) { eventTimeline.append_do([=, this] { status.pauseTime(mDuration); }); }) .arg("duration") .doc( "*Add to the event timeline*: pause the game timer for `$0` " "seconds."); addLuaFn(lua, "e_wait", [this](double mDuration) { eventTimeline.append_wait_for_sixths(mDuration); }) .arg("duration") .doc( "*Add to the event timeline*: wait for `$0` frames (under the " "assumption of a 60 FPS frame rate)."); addLuaFn(lua, "e_waitS", // [this](double mDuration) { eventTimeline.append_wait_for_seconds(mDuration); }) .arg("duration") .doc("*Add to the event timeline*: wait for `$0` seconds."); addLuaFn(lua, "e_waitUntilS", // [this](double mDuration) { eventTimeline.append_wait_until_fn([this, mDuration] { return status.getLevelStartTP() + std::chrono::milliseconds( static_cast<int>(mDuration * 1000.0)); }); }) .arg("duration") .doc( "*Add to the event timeline*: wait until the timer reaches `$0` " "seconds."); addLuaFn(lua, "e_messageAdd", // [this](const std::string& mMsg, double mDuration) { eventTimeline.append_do([=, this] { if(firstPlay && Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ true); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will only be printed during the first " "run of the level."); addLuaFn(lua, "e_messageAddImportant", // [this](const std::string& mMsg, double mDuration) { eventTimeline.append_do([=, this] { if(Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ true); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will be printed during every run of the " "level."); addLuaFn(lua, "e_messageAddImportantSilent", [this](const std::string& mMsg, double mDuration) { eventTimeline.append_do([=, this] { if(Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ false); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will only be printed during every " "run of the level, and will not produce any sound."); addLuaFn(lua, "e_clearMessages", // [this] { clearMessages(); }) .doc("Remove all previously scheduled messages."); } template <typename T> auto HexagonGame::makeLuaAccessor(T& obj, const std::string& prefix) { return [this, &obj, prefix](const std::string& name, auto pmd, const std::string& getterDesc, const std::string& setterDesc) { using Type = std::decay_t<decltype(obj.*pmd)>; const std::string getterString = prefix + "_get" + name; const std::string setterString = prefix + "_set" + name; addLuaFn(lua, getterString, // [this, pmd, &obj]() -> Type { return obj.*pmd; }) .doc(getterDesc); addLuaFn(lua, setterString, // [this, pmd, &obj](Type mValue) { obj.*pmd = mValue; }) .arg("value") .doc(setterDesc); }; } void HexagonGame::initLua_LevelControl() { const auto lsVar = makeLuaAccessor(levelStatus, "l"); lsVar("SpeedMult", &LevelStatus::speedMult, "Gets the speed multiplier of the level. The speed multiplier is " "the current speed of the walls. Is incremented by ``SpeedInc`` " "every increment and caps at ``speedMax``.", "Sets the speed multiplier of the level to `$0`. Changes do not apply " "to " "all walls immediately, and changes apply as soon as the next wall " "is created."); lsVar("PlayerSpeedMult", &LevelStatus::playerSpeedMult, "Gets the speed multiplier of the player.", "Sets the speed multiplier of the player."); lsVar("SpeedInc", &LevelStatus::speedInc, "Gets the speed increment of the level. This is applied every level " "increment to the speed multiplier. Increments are additive.", "Sets the speed increment of the level to `$0`."); lsVar("SpeedMax", &LevelStatus::speedMax, "Gets the maximum speed of the level. This is the highest that speed " "can go; speed can not get any higher than this.", "Sets the maximum speed of the level to `$0`. Keep in mind that speed " "keeps going past the speed max, so setting a higher speed max may " "make the speed instantly increase to the max."); lsVar("RotationSpeed", &LevelStatus::rotationSpeed, "Gets the rotation speed of the level. Is incremented by " "``RotationSpeedInc`` every increment and caps at " "``RotationSpeedMax``.", "Sets the rotation speed of the level to `$0`. Changes apply " "immediately."); lsVar("RotationSpeedInc", &LevelStatus::rotationSpeedInc, "Gets the rotation speed increment of the level. This is " "applied every level increment to the rotation speed. " "Increments are additive.", "Sets the rotation speed increment of the level to `$0`. " "Is effective on the next level increment."); lsVar("RotationSpeedMax", &LevelStatus::rotationSpeedMax, "Gets the maximum rotation speed of the level. This is the " "highest that rotation speed can go; rotation speed can not " "get any higher than this.", "Sets the maximum rotation speed of the level to `$0`. Keep " "in mind that rotation speed keeps going past the max, so " "setting a higher rotation speed max may make the rotation speed " "instantly increase to the max."); lsVar("DelayMult", &LevelStatus::delayMult, "Gets the delay multiplier of the level. The delay multiplier " "is the multiplier used to assist in spacing patterns, especially " "in cases of higher / lower speeds. Is incremented by ``DelayInc`` " "every increment and is clamped between ``DelayMin`` and ``DelayMax``", "Sets the delay multiplier of the level to `$0`. Changes do not apply " "to " "patterns immediately, and changes apply as soon as the next pattern " "is spawned."); lsVar("DelayInc", &LevelStatus::delayInc, "Gets the delay increment of the level. This is applied every level " "increment to the delay multiplier. Increments are additive.", "Sets the delay increment of the level to `$0`."); lsVar("DelayMin", &LevelStatus::delayMin, "Gets the minimum delay of the level. This is the lowest that delay " "can go; delay can not get any lower than this.", "Sets the minimum delay of the level to `$0`. Keep in mind that delay " "can go below the delay min, so setting a lower delay min may " "make the delay instantly decrease to the minimum."); lsVar("DelayMax", &LevelStatus::delayMax, "Gets the maximum delay of the level. This is the highest that delay " "can go; delay can not get any higher than this.", "Sets the maximum delay of the level to `$0`. Keep in mind that delay " "can go above the delay max, so setting a higher delay max may " "make the delay instantly increase to the maximum."); lsVar("FastSpin", &LevelStatus::fastSpin, "Gets the fast spin of the level. The fast spin is a brief moment that " "starts at level incrementation where the rotation increases speed " "drastically to try and throw off the player a bit. This speed quickly " "(or slowly, depending on the value) decelerates and fades away to the " " updated rotation speed.", "Sets the fast spin of the level to `$0`. A higher value increases " "intensity and duration of the fast spin."); lsVar("IncTime", &LevelStatus::incTime, "Get the incrementation time (in seconds) of a level. This is the " "length " "of a \"level\" in an Open Hexagon level (It's ambiguous but hopefully " "you understand what that means), and when this duration is reached, " "the " "level increments.", "Set the incrementation time (in seconds) of a level to `$0`."); lsVar("PulseMin", &LevelStatus::pulseMin, "Gets the minimum value the pulse can be. Pulse gives variety in " "the wall speed of the level so the wall speed doesn't feel monotone. " "Can also be used to help sync a level up with it's music.", "Sets the minimum pulse value to `$0`."); lsVar("PulseMax", &LevelStatus::pulseMax, "Gets the maximum value the pulse can be. Pulse gives variety in " "the wall speed of the level so the wall speed doesn't feel monotone. " "Can also be used to help sync a level up with it's music.", "Sets the maximum pulse value to `$0`."); lsVar("PulseSpeed", &LevelStatus::pulseSpeed, "Gets the speed the pulse goes from ``PulseMin`` to ``PulseMax``. " "Can also be used to help sync a level up with it's music.", "Sets the speed the pulse goes from ``PulseMin`` to ``PulseMax`` by " "`$0`. Can also be used to help sync a level up with it's music."); lsVar("PulseSpeedR", &LevelStatus::pulseSpeedR, "Gets the speed the pulse goes from ``PulseMax`` to ``PulseMin``.", "Sets the speed the pulse goes from ``PulseMax`` to ``PulseMin`` by " "`$0`. Can also be used to help sync a level up with it's music."); lsVar("PulseDelayMax", &LevelStatus::pulseDelayMax, "Gets the delay the level has to wait before it begins another pulse " "cycle.", "Sets the delay the level has to wait before it begins another pulse " "cycle with `$0`."); lsVar("PulseInitialDelay", &LevelStatus::pulseInitialDelay, "Gets the initial delay the level has to wait before it begins the " "first pulse cycle.", "Sets the initial delay the level has to wait before it begins the " "first pulse cycle with `$0`."); lsVar("SwapCooldownMult", &LevelStatus::swapCooldownMult, "Gets the multiplier that controls the cooldown for the player's 180 " "degrees swap mechanic.", "Sets the multiplier that controls the cooldown for the player's 180 " "degrees swap mechanic to `$0`."); lsVar("BeatPulseMax", &LevelStatus::beatPulseMax, "Gets the maximum beatpulse size of the polygon in a level. This is " "the highest value that the polygon will \"pulse\" in size. Useful for " "syncing the level to the music.", "Sets the maximum beatpulse size of the polygon in a level to `$0`. " "Not to be confused with using this property to resize the polygon, " "which you should be using ``RadiusMin``."); lsVar("BeatPulseDelayMax", &LevelStatus::beatPulseDelayMax, "Gets the delay for how fast the beatpulse pulses in frames (assuming " "60 FPS " "logic). This paired with ``BeatPulseMax`` will be useful to help sync " "a level " "with the music that it's playing.", "Sets the delay for how fast the beatpulse pulses in `$0` frames " "(assuming 60 " "FPS Logic)."); lsVar("BeatPulseInitialDelay", &LevelStatus::beatPulseInitialDelay, "Gets the initial delay before beatpulse begins pulsing. This is very " "useful " "to use at the very beginning of the level to assist syncing the " "beatpulse " "with the song.", "Sets the initial delay before beatpulse begins pulsing to `$0`. " "Highly " "discouraged to use this here. Use this in your music JSON files."); lsVar("BeatPulseSpeedMult", &LevelStatus::beatPulseSpeedMult, "Gets how fast the polygon pulses with the beatpulse. This is very " "useful " "to help keep your level in sync with the music.", "Sets how fast the polygon pulses with beatpulse to `$0`."); lsVar("RadiusMin", &LevelStatus::radiusMin, "Gets the minimum radius of the polygon in a level. This is used to " "determine the absolute size of the polygon in the level.", "Sets the minimum radius of the polygon to `$0`. Use this to set the " "size of the polygon in the level, not ``BeatPulseMax``."); lsVar("WallSkewLeft", &LevelStatus::wallSkewLeft, "Gets the Y axis offset of the top left vertex in all walls.", "Sets the Y axis offset of the top left vertex to `$0` in all newly " "generated " "walls. If you would like to have more individual control of the wall " "vertices, " "please use the custom walls system under the prefix ``cw_``."); lsVar("WallSkewRight", &LevelStatus::wallSkewRight, "Gets the Y axis offset of the top right vertex in all walls.", "Sets the Y axis offset of the top right vertex to `$0` in all newly " "generated " "walls. If you would like to have more individual control of the wall " "vertices, " "please use the custom walls system under the prefix ``cw_``."); lsVar("WallAngleLeft", &LevelStatus::wallAngleLeft, "Gets the X axis offset of the top left vertex in all walls.", "Sets the X axis offset of the top left vertex to `$0` in all newly " "generated " "walls. If you would like to have more individual control of the wall " "vertices, " "please use the custom walls system under the prefix ``cw_``."); lsVar("WallAngleRight", &LevelStatus::wallAngleRight, "Gets the X axis offset of the top right vertex in all walls.", "Sets the X axis offset of the top right vertex to `$0` in all newly " "generated " "walls. If you would like to have more individual control of the wall " "vertices, " "please use the custom walls system under the prefix ``cw_``."); lsVar("WallSpawnDistance", &LevelStatus::wallSpawnDistance, "Gets the distance at which standard walls spawn.", "Sets how far away the walls can spawn from the center. Higher " "values make walls spawn farther away, and will increase the " "player's wait for incoming walls."); lsVar("3dRequired", &LevelStatus::_3DRequired, "Gets whether 3D must be enabled in order to have a valid score in " "this level. " "By default, this value is ``false``.", "Sets whether 3D must be enabled to `$0` to have a valid score. Only " "set this " "to ``true`` if your level relies on 3D effects to work as intended."); // Commenting this one out. This property seems to have NO USE in the actual // game itself. lsVar("3dEffectMultiplier", // &LevelStatus::_3dEffectMultiplier); lsVar("CameraShake", &LevelStatus::cameraShake, "Gets the intensity of the camera shaking in a level.", "Sets the intensity of the camera shaking in a level to `$0`. This " "remains " "permanent until you either set this to 0 or the player dies."); lsVar("Sides", &LevelStatus::sides, "Gets the current number of sides on the polygon in a level.", "Sets the current number of sides on the polygon to `$0`. This change " "happens " "immediately and previously spawned walls will not adjust to the new " "side count."); lsVar("SidesMax", &LevelStatus::sidesMax, "Gets the maximum range that the number of sides can possibly be at " "random. " "``enableRndSideChanges`` must be enabled for this property to have " "any use.", "Sets the maximum range that the number of sides can possibly be to " "`$0`."); lsVar("SidesMin", &LevelStatus::sidesMin, "Gets the minimum range that the number of sides can possibly be at " "random. " "``enableRndSideChanges`` must be enabled for this property to have " "any use.", "Sets the minimum range that the number of sides can possibly be to " "`$0`."); lsVar("SwapEnabled", &LevelStatus::swapEnabled, "Gets whether the swap mechanic is enabled for a level. By default, " "this is " "set to ``false``.", "Sets the swap mechanic's availability to `$0`."); lsVar("TutorialMode", &LevelStatus::tutorialMode, "Gets whether tutorial mode is enabled. In tutorial mode, players are " "granted " "invincibility from dying to walls. This mode is typically enabled " "whenever a " "pack developer needs to demonstrate a new concept to the player so " "that way " "they can easily learn the new mechanic/concept. This invincibility " "will not " "count towards invalidating a score, but it's usually not important to " "score " "on a tutorial level. By default, this is set to ``false``.", "Sets tutorial mode to `$0`. Remember, only enable this if you need to " "demonstrate " "a new concept for players to learn, or use it as a gimmick to a " "level."); lsVar("IncEnabled", &LevelStatus::incEnabled, "Gets whether the level can increment or not. This is Open Hexagon's " "way of " "establishing a difficulty curve in the level and set a sense of " "progression " "throughout the level. By default, this value is set to ``true``.", "Toggles level incrementation to `$0`. Only disable this if you feel " "like the " "level can not benefit from incrementing in any way."); lsVar("DarkenUnevenBackgroundChunk", &LevelStatus::darkenUnevenBackgroundChunk, "Gets whether the ``Nth`` panel of a polygon with ``N`` sides " "(assuming ``N`` is odd) will be darkened to make styles look more " "balanced. By default, this value is set to ``true``, but there can be " "styles where having this darkened panel can look very unpleasing.", "Sets the darkened panel to `$0`."); lsVar("ManualPulseControl", &LevelStatus::manualPulseControl, "Gets whether the pulse effect is being controlled manually via Lua or " "automatically by the C++ engine.", "Sets whether the pulse effect is being controlled manually via Lua or " "automatically by the C++ engine to `$0`."); lsVar("ManualBeatPulseControl", &LevelStatus::manualBeatPulseControl, "Gets whether the beat pulse effect is being controlled manually via " "Lua or automatically by the C++ engine.", "Sets whether the beat pulse effect is being controlled manually via " "Lua or automatically by the C++ engine to `$0`."); lsVar("CurrentIncrements", &LevelStatus::currentIncrements, "Gets the current amount of times the level has incremented. Very " "useful for " "keeping track of levels.", "Sets the current amount of times the level has incremented to `$0`. " "This " "function is utterly pointless to use unless you are tracking this " "variable."); addLuaFn(lua, "l_enableRndSideChanges", // [this](bool mValue) { levelStatus.rndSideChangesEnabled = mValue; }) .arg("enabled") .doc( "Toggles random side changes to `$0`, (not) allowing sides to " "change " "between ``SidesMin`` and ``SidesMax`` inclusively every level " "increment."); addLuaFn(lua, "l_overrideScore", // [this](const std::string& mVar) { try { levelStatus.scoreOverride = mVar; levelStatus.scoreOverridden = true; // Make sure we're not passing in a string lua.executeCode("if (type(" + mVar + R"( ) ~= "number") then error("Score override must be a number value") end )"); } catch(const std::runtime_error& mError) { std::cout << "[l_overrideScore] Runtime error on overriding score " << "with level \"" << levelData->name << "\": \n" << ssvu::toStr(mError.what()) << '\n' << std::endl; if(!Config::getDebug()) { goToMenu(false /* mSendScores */, true /* mError */); } }; }) .arg("variable") .doc( "Overrides the default scoring method and determines score based " "off the value of `$0`. This allows for custom scoring in levels. " "*Avoid using strings, otherwise scores won't sort properly. NOTE: " "Your variable must be global for this to work.*"); addLuaFn(lua, "l_addTracked", // [this](const std::string& mVar, const std::string& mName) { levelStatus.trackedVariables.push_back({mVar, mName}); }) .arg("variable") .arg("name") .doc( "Add the variable `$0` to the list of tracked variables, with name " "`$1`. Tracked variables are displayed in game, below the game " "timer. *NOTE: Your variable must be global for this to work.*"); addLuaFn(lua, "l_clearTracked", // [this] { levelStatus.trackedVariables.clear(); }) .doc("Clears all tracked variables."); addLuaFn(lua, "l_setRotation", // [this](float mValue) { backgroundCamera.setRotation(mValue); }) .arg("angle") .doc("Set the background camera rotation to `$0` degrees."); addLuaFn(lua, "l_getRotation", // [this] { return backgroundCamera.getRotation(); }) .doc("Return the background camera rotation, in degrees."); addLuaFn(lua, "l_getLevelTime", // [this] { return status.getTimeSeconds(); }) .doc("Get the current game timer value, in seconds."); addLuaFn(lua, "l_getOfficial", // [] { return Config::getOfficial(); }) .doc( "Return `true` if \"official mode\" is enabled, `false` " "otherwise."); addLuaFn(lua, "l_resetTime", // [this] { status.resetTime(); }) .doc( "Resets the lever time to zero, also resets increment time and " "pause time."); // TODO: test and consider re-enabling /* addLuaFn(lua, "l_setLevel", [this](const std::string& mId) { setLevelData(assets.getLevelData(mId), true); stopLevelMusic(); playLevelMusic(); }); */ const auto sVar = makeLuaAccessor(status, "l"); sVar("Pulse", &HexagonGameStatus::pulse, "Gets the current pulse value, which will vary between " "`l_getPulseMin()` and `l_getPulseMax()` unless manually overridden.", "Sets the current pulse value to `$0`."); sVar("PulseDirection", &HexagonGameStatus::pulseDirection, "Gets the current pulse direction value, which will either be `-1` or " "`1` unless manually overridden.", "Sets the current pulse direction value to `$0`. Valid choices are " "`-1` or `1`."); sVar("PulseDelay", &HexagonGameStatus::pulseDelay, "Gets the current pulse delay value, which will vary between " "`0` and `l_getPulseDelayMax()` unless manually overridden.", "Sets the current pulse delay value to `$0`."); sVar("BeatPulse", &HexagonGameStatus::beatPulse, "Gets the current beat pulse value, which will vary between `0` and " "`l_getBeatPulseMax()` unless manually overridden.", "Sets the current beat pulse value to `$0`."); sVar("BeatPulseDelay", &HexagonGameStatus::beatPulseDelay, "Gets the current beat pulse delay value, which will vary between " "`0` and `l_getBeatPulseDelayMax()` unless manually overridden.", "Sets the current beat pulse delay value to `$0`."); } void HexagonGame::initLua_StyleControl() { const auto sdVar = makeLuaAccessor(styleData, "s"); sdVar("HueMin", &StyleData::hueMin, "Gets the minimum value for the hue range of a level style. The hue " "attribute is an important attribute that is dedicated specifically to " "all colors that have the ``dynamic`` property enabled.", "Sets the minimum value for the hue range to `$0`. Usually you want " "this value at 0 to start off at completely red."); sdVar("HueMax", &StyleData::hueMax, "Gets the maximum value for the hue range of a level style. Only " "applies to all colors with the ``dynamic`` property enabled.", "Sets the maximum value for the hue range to `$0`. Usually you want " "this value at 360 to end off at red, to hopefully loop the colors " "around."); // backwards-compatible sdVar("HueInc", &StyleData::hueIncrement, "Alias to ``s_getHueIncrement``. Done for backwards compatibility.", "Alias to ``s_setHueIncrement``. Done for backwards compatibility."); sdVar("HueIncrement", &StyleData::hueIncrement, "Gets how fast the hue increments from ``HueMin`` to ``HueMax``. The " "hue value is " "added by this value every 1/60th of a second.", "Sets how fast the hue increments from ``HueMin`` to ``HueMax`` by " "`$0`. Be careful " "with high values, as this can make your style induce epileptic " "seizures."); sdVar("PulseMin", &StyleData::pulseMin, "Gets the minimum range for the multiplier of the ``pulse`` attribute " "in style colors. " "By default, this value is set to 0.", "Sets the minimum range for the multiplier of the ``pulse`` attribute " "to `$0`."); sdVar("PulseMax", &StyleData::pulseMax, "Gets the maximum range for the multiplier of the ``pulse`` attribute " "in style colors. " "By default, this value is set to 0, but ideally it should be set to " "1.", "Sets the maximum range for the multiplier of the ``pulse`` attribute " "to `$0`."); // backwards-compatible sdVar("PulseInc", &StyleData::pulseIncrement, "Alias to ``s_getPulseIncrement``. Done for backwards compatibility.", "Alias to ``s_setPulseIncrement``. Done for backwards compatibility."); sdVar("PulseIncrement", &StyleData::pulseIncrement, "Gets how fast the pulse increments from ``PulseMin`` to ``PulseMax``. " "The pulse value is " "added by this value every 1/60th of a second.", "Sets how fast the pulse increments from ``PulseMin`` to ``PulseMax`` " "by `$0`. Be careful " "with high values, as this can make your style induce epileptic " "seizures."); sdVar("HuePingPong", &StyleData::huePingPong, "Gets whether the hue should go ``Start-End-Start-End`` or " "``Start-End, Start-End`` with " "the hue cycling.", "Toggles ping ponging in the hue cycling (``Start-End-Start-End``) " "with `$0`."); sdVar("MaxSwapTime", &StyleData::maxSwapTime, "Gets the amount of time that has to pass (in 1/100th of a second) " "before the background color offset alternates. " "The background colors by default alternate between 0 and 1. By " "default, this happens every second.", "Sets the amount of time that has to pass (in 1/100th of a second) to " "`$0` before the background color alternates."); sdVar("3dDepth", &StyleData::_3dDepth, "Gets the current amount of 3D layers that are present in the style.", "Sets the amount of 3D layers in a style to `$0`."); sdVar("3dSkew", &StyleData::_3dSkew, "Gets the current value of where the 3D skew is in the style. The Skew " "is what gives the 3D effect in the first " "place, showing the 3D layers and giving the illusion of 3D in the " "game.", "Sets the 3D skew at value `$0`."); sdVar("3dSpacing", &StyleData::_3dSpacing, "Gets the spacing that is done between 3D layers. A higher number " "leads to more separation between layers.", "Sets the spacing between 3D layers to `$0`."); sdVar("3dDarkenMult", &StyleData::_3dDarkenMult, "Gets the darkening multiplier applied to the 3D layers in a style. " "This is taken from the ``main`` color.", "Sets the darkening multiplier to `$0` for the 3D layers."); sdVar("3dAlphaMult", &StyleData::_3dAlphaMult, "Gets the alpha (transparency) multiplier applied to the 3D layers in " "a style. Originally references the " "``main`` color.", "Sets the alpha multiplier to `$0` for the 3D layers. A higher value " "makes the layers more transparent."); sdVar("3dAlphaFalloff", &StyleData::_3dAlphaFalloff, "Gets the alpha (transparency) multiplier applied to the 3D layers " "consecutively in a style. Takes " "reference from the ``main`` color.", "Sets the alpha multiplier to `$0` for for the 3D layers and applies " "them layer after layer. This " "property can get finnicky."); sdVar("3dPulseMax", &StyleData::_3dPulseMax, "Gets the highest value that the ``3DSkew`` can go in a style.", "Sets the highest value the ``3DSkew`` can go to `$0`."); sdVar("3dPulseMin", &StyleData::_3dPulseMin, "Gets the lowest value that the ``3DSkew`` can go in a style.", "Sets the lowest value the ``3DSkew`` can go to `$0`."); sdVar("3dPulseSpeed", &StyleData::_3dPulseSpeed, "Gets how fast the ``3DSkew`` moves between ``3DPulseMin`` and " "``3DPulseMax``.", "Sets how fast the ``3DSkew`` moves between ``3DPulseMin`` and " "``3DPulseMax`` by `$0`."); sdVar("3dPerspectiveMult", &StyleData::_3dPerspectiveMult, "Gets the 3D perspective multiplier of the style. Works with the " "attribute ``3DSpacing`` to space out " "layers.", "Sets the 3D perspective multiplier to `$0`."); sdVar("BGTileRadius", &StyleData::bgTileRadius, "Gets the distances of how far the background panels are drawn. By " "default, this is a big enough value " "so you do not see the border. However, feel free to shrink them if " "you'd like.", "Sets how far the background panels are drawn to distance `$0`."); sdVar("BGColorOffset", &StyleData::BGColorOffset, "Gets the offset of the style by how much the colors shift. Usually " "this sits between 0 and 1, but can " "easily be customized.", "Shifts the background colors to have an offset of `$0`."); sdVar("BGRotationOffset", &StyleData::BGRotOff, "Gets the literal rotation offset of the background panels in degrees. " "This usually stays at 0, but can " "be messed with to make some stylish level styles.", "Sets the rotation offset of the background panels to `$0` degrees."); addLuaFn(lua, "s_setStyle", // [this](const std::string& mId) { styleData = assets.getStyleData(levelData->packId, mId); }) .arg("styleId") .doc( "Set the currently active style to the style with id `$0`. Styles " "can be defined as `.json` files in the `<pack>/Styles/` folder."); // // backwards-compatible // addLuaFn(lua, "s_setCameraShake", // // [this](int mValue) { levelStatus.cameraShake = mValue; }) // .arg("value") // .doc("Start a camera shake with intensity `$0`."); // // backwards-compatible // addLuaFn(lua, "s_getCameraShake", // // [this] { return levelStatus.cameraShake; }) // .doc("Return the current camera shake intensity."); addLuaFn(lua, "s_setCapColorMain", // [this] { styleData.capColor = CapColorMode::Main{}; }) .doc( "Set the color of the center polygon to match the main style " "color."); addLuaFn(lua, "s_setCapColorMainDarkened", // [this] { styleData.capColor = CapColorMode::MainDarkened{}; }) .doc( "Set the color of the center polygon to match the main style " "color, darkened."); addLuaFn(lua, "s_setCapColorByIndex", // [this]( int mIndex) { styleData.capColor = CapColorMode::ByIndex{mIndex}; }) .arg("index") .doc( "Set the color of the center polygon to match the style color with " "index `$0`."); const auto colorToTuple = [](const sf::Color& c) { return std::tuple<int, int, int, int>{c.r, c.g, c.b, c.a}; }; // TODO: const auto sdColorGetter = [this, &colorToTuple](const char* name, const char* docName, auto pmf) { std::string docString = "Return the current "; docString += docName; docString += " color computed by the level style."; addLuaFn(lua, name, [this, &colorToTuple, pmf] { return colorToTuple((styleData.*pmf)()); }).doc(docString); }; sdColorGetter("s_getMainColor", "main", &StyleData::getMainColor); sdColorGetter("s_getPlayerColor", "player", &StyleData::getPlayerColor); sdColorGetter("s_getTextColor", "text", &StyleData::getTextColor); sdColorGetter( "s_get3DOverrideColor", "3D override", &StyleData::get3DOverrideColor); sdColorGetter("s_getCapColorResult", "cap color result", &StyleData::getCapColorResult); addLuaFn(lua, "s_getColor", [this, &colorToTuple]( int mIndex) { return colorToTuple(styleData.getColor(mIndex)); }) .arg("index") .doc( "Return the current color with index `$0` computed by the level " "style."); } void HexagonGame::initLua_WallCreation() { addLuaFn(lua, "w_wall", // [this](int mSide, float mThickness) { timeline.append_do([=, this] { createWall(mSide, mThickness, SpeedData{getSpeedMultDM()}); }); }) .arg("side") .arg("thickness") .doc( "Create a new wall at side `$0`, with thickness `$1`. The speed of " "the wall will be calculated by using the speed multiplier, " "adjusted for the current difficulty multiplier."); addLuaFn(lua, "w_wallAdj", // [this](int mSide, float mThickness, float mSpeedAdj) { timeline.append_do([=, this] { createWall( mSide, mThickness, SpeedData{mSpeedAdj * getSpeedMultDM()}); }); }) .arg("side") .arg("thickness") .arg("speedMult") .doc( "Create a new wall at side `$0`, with thickness `$1`. The speed of " "the wall will be calculated by using the speed multiplier, " "adjusted for the current difficulty multiplier, and finally " "multiplied by `$2`."); addLuaFn(lua, "w_wallAcc", // [this](int mSide, float mThickness, float mSpeedAdj, float mAcceleration, float mMinSpeed, float mMaxSpeed) { timeline.append_do([=, this] { createWall(mSide, mThickness, SpeedData{mSpeedAdj * getSpeedMultDM(), mAcceleration / (std::pow(difficultyMult, 0.65f)), mMinSpeed * getSpeedMultDM(), mMaxSpeed * getSpeedMultDM()}); }); }) .arg("side") .arg("thickness") .arg("speedMult") .arg("acceleration") .arg("minSpeed") .arg("maxSpeed") .doc( "Create a new wall at side `$0`, with thickness `$1`. The speed of " "the wall will be calculated by using the speed multiplier, " "adjusted for the current difficulty multiplier, and finally " "multiplied by `$2`. The wall will have a speed acceleration value " "of `$3`. The minimum and maximum speed of the wall are bounded by " "`$4` and `$5`, adjusted for the current difficulty multiplier."); addLuaFn(lua, "w_wallHModSpeedData", // [this](float mHMod, int mSide, float mThickness, float mSAdj, float mSAcc, float mSMin, float mSMax, bool mSPingPong) { timeline.append_do([=, this] { createWall(mSide, mThickness, SpeedData{mSAdj * getSpeedMultDM(), mSAcc, mSMin, mSMax, mSPingPong}, SpeedData{}, mHMod); }); }) .arg("hueModifier") .arg("side") .arg("thickness") .arg("speedMult") .arg("acceleration") .arg("minSpeed") .arg("maxSpeed") .arg("pingPong") .doc( "Create a new wall at side `$1`, with thickness `$2`. The speed of " "the wall will be calculated by using the speed multiplier, " "adjusted for the current difficulty multiplier, and finally " "multiplied by `$3`. The wall will have a speed acceleration value " "of `$4`. The minimum and maximum speed of the wall are bounded by " "`$5` and `$6`, adjusted for the current difficulty multiplier. " "The hue of the wall will be adjusted by `$0`. If `$7` is enabled, " "the wall will accelerate back and forth between its minimum and " "maximum speed."); addLuaFn(lua, "w_wallHModCurveData", // [this](float mHMod, int mSide, float mThickness, float mCAdj, float mCAcc, float mCMin, float mCMax, bool mCPingPong) { timeline.append_do([=, this] { createWall(mSide, mThickness, SpeedData{getSpeedMultDM()}, SpeedData{mCAdj, mCAcc, mCMin, mCMax, mCPingPong}, mHMod); }); }) .arg("hueModifier") .arg("side") .arg("thickness") .arg("curveSpeedMult") .arg("curveAcceleration") .arg("curveMinSpeed") .arg("curveMaxSpeed") .arg("pingPong") .doc( "Create a new curving wall at side `$1`, with thickness `$2`. The " "curving speed of the wall will be calculated by using the speed " "multiplier, adjusted for the current difficulty multiplier, and " "finally multiplied by `$3`. The wall will have a curving speed " "acceleration value of `$4`. The minimum and maximum curving speed " "of the wall are bounded by `$5` and `$6`, adjusted for the " "current difficulty multiplier. The hue of the wall will be " "adjusted by `$0`. If `$7` is enabled, the wall will accelerate " "back and forth between its minimum and maximum speed."); } void HexagonGame::initLua_Steam() { addLuaFn(lua, "steam_unlockAchievement", // [this](const std::string& mId) { if(inReplay()) { // Do not unlock achievements while watching a replay. return; } if(Config::getOfficial()) { steamManager.unlock_achievement(mId); } }) .arg("achievementId") .doc("Unlock the Steam achievement with id `$0`."); } // These are all deprecated functions that are only being kept for the sake of // lessening the impact of incompatibility. Pack Developers have time to change // to the new functions before they get removed permanently void HexagonGame::initLua_Deprecated() { addLuaFn(lua, "u_kill", // [this] { raiseWarning("u_kill", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"t_kill\" in your level files."); timeline.append_do([this] { death(true); }); }) .doc( "*Add to the main timeline*: kill the player. " "**This function is deprecated and will be removed in a future " "version. Please use t_kill instead!**"); addLuaFn(lua, "u_eventKill", // [this] { raiseWarning("u_eventKill", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_kill\" in your level files."); eventTimeline.append_do([this] { death(true); }); }) .doc( "*Add to the event timeline*: kill the player. " "**This function is deprecated and will be removed in a future " "version. Please use e_kill instead!**"); addLuaFn(lua, "u_playSound", // [this](const std::string& mId) { raiseWarning("u_playSound", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"a_playSound\" in your level files."); assets.playSound(mId); }) .arg("soundId") .doc( "Play the sound with id `$0`. The id must be registered in " "`assets.json`, under `\"soundBuffers\"`. " "**This function is deprecated and will be removed in a future " "version. Please use a_playSound instead!**"); addLuaFn(lua, "u_playPackSound", // [this](const std::string& fileName) { raiseWarning("u_playPackSound", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"a_playPackSound\" in your level files."); assets.playPackSound(getPackId(), fileName); }) .arg("fileName") .doc( "Dives into the `Sounds` folder of the current level pack and " "plays the specified file `$0`. " "**This function is deprecated and will be removed in a future " "version. Please use a_playPackSound instead!**"); addLuaFn(lua, "e_eventStopTime", // [this](double mDuration) { raiseWarning("e_eventStopTime", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_stopTime\" in your level files."); eventTimeline.append_do([=, this] { status.pauseTime(ssvu::getFTToSeconds(mDuration)); }); }) .arg("duration") .doc( "*Add to the event timeline*: pause the game timer for `$0` frames " "(under the assumption of a 60 FPS frame rate). " "**This function is deprecated and will be removed in a future " "version. Please use e_stopTime instead!**"); addLuaFn(lua, "e_eventStopTimeS", // [this](double mDuration) { raiseWarning("e_eventStopTimeS", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_stopTimeS\" in your level files."); eventTimeline.append_do([=, this] { status.pauseTime(mDuration); }); }) .arg("duration") .doc( "*Add to the event timeline*: pause the game timer for `$0` " "seconds. " "**This function is deprecated and will be removed in a future " "version. Please use e_stopTimeS instead!**"); addLuaFn(lua, "e_eventWait", [this](double mDuration) { raiseWarning("e_eventWait", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_wait\" in your level files."); eventTimeline.append_wait_for_sixths(mDuration); }) .arg("duration") .doc( "*Add to the event timeline*: wait for `$0` frames (under the " "assumption of a 60 FPS frame rate). " "**This function is deprecated and will be removed in a future " "version. Please use e_wait instead!**"); addLuaFn(lua, "e_eventWaitS", // [this](double mDuration) { raiseWarning("e_eventWaitS", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_waitS\" in your level files."); eventTimeline.append_wait_for_seconds(mDuration); }) .arg("duration") .doc( "*Add to the event timeline*: wait for `$0` seconds. " "**This function is deprecated and will be removed in a future " "version. Please use e_waitS instead!**"); addLuaFn(lua, "e_eventWaitUntilS", // [this](double mDuration) { raiseWarning("e_eventWaitUntilS", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_waitUntilS\" in your level files."); eventTimeline.append_wait_until_fn([this, mDuration] { return status.getLevelStartTP() + std::chrono::milliseconds( static_cast<int>(mDuration * 1000.0)); }); }) .arg("duration") .doc( "*Add to the event timeline*: wait until the timer reaches `$0` " "seconds. " "**This function is deprecated and will be removed in a future " "version. Please use e_waitUntilS instead!**"); addLuaFn(lua, "m_messageAdd", // [this](const std::string& mMsg, double mDuration) { raiseWarning("m_messageAdd", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_messageAdd\" in your level files and common.lua."); eventTimeline.append_do([=, this] { if(firstPlay && Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ true); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will only be printed during the first " "run of the level. " "**This function is deprecated and will be removed in a future " "version. Please use e_messageAdd instead!**"); addLuaFn(lua, "m_messageAddImportant", // [this](const std::string& mMsg, double mDuration) { raiseWarning("m_messageAddImportant", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_messageAddImportant\" in your level files and " "common.lua."); eventTimeline.append_do([=, this] { if(Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ true); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will be printed during every run of the " "level. " "**This function is deprecated and will be removed in a future " "version. Please use e_messageAddImportant instead!**"); addLuaFn(lua, "m_messageAddImportantSilent", [this](const std::string& mMsg, double mDuration) { raiseWarning("m_messageAddImportantSilent", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_messageAddImportantSilent\" in your level files."); eventTimeline.append_do([=, this] { if(Config::getShowMessages()) { addMessage(mMsg, mDuration, /* mSoundToggle */ false); } }); }) .arg("message") .arg("duration") .doc( "*Add to the event timeline*: print a message with text `$0` for " "`$1` seconds. The message will only be printed during every " "run of the level, and will not produce any sound. " "**This function is deprecated and will be removed in a future " "version. Please use e_messageAddImportantSilent instead!**"); addLuaFn(lua, "m_clearMessages", // [this] { raiseWarning("m_clearMessages", "This function will be removed in a future version of Open " "Hexagon. Please replace all occurrences of this function with " "\"e_clearMessages\" in your level files."); clearMessages(); }) .doc( "Remove all previously scheduled messages. " "**This function is deprecated and will be removed in a future " "version. Please use e_clearMessages instead!**"); } void HexagonGame::initLua() { LuaScripting::init(lua, rng, false /* inMenu */, cwManager); initLua_Utils(); initLua_AudioControl(); initLua_MainTimeline(); initLua_EventTimeline(); initLua_LevelControl(); initLua_StyleControl(); initLua_WallCreation(); initLua_Steam(); initLua_Deprecated(); } void HexagonGame::initLuaAndPrintDocs() { initLua(); LuaScripting::printDocs(); } } // namespace hg
40.504732
80
0.586854
[ "3d" ]
3c32beeec5061500f030306b45b1c2379aeacf7c
3,062
cxx
C++
Utilities/Xdmf2/libsrc/XdmfLightData.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Utilities/Xdmf2/libsrc/XdmfLightData.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Utilities/Xdmf2/libsrc/XdmfLightData.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : $Id$ */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* clarke@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*******************************************************************/ #include "XdmfLightData.h" #include <libxml/tree.h> XdmfLightData::XdmfLightData() { this->WorkingDirectory = NULL; this->FileName = NULL; this->Name = NULL; this->StaticReturnBuffer = NULL; // Defaults this->SetFileName( "XdmfData.xmf" ); this->SetWorkingDirectory("."); } XdmfLightData::~XdmfLightData() { if(this->StaticReturnBuffer){ delete [] this->StaticReturnBuffer; } if(this->WorkingDirectory){ delete [] this->WorkingDirectory; } if(this->Name){ delete [] this->Name; } if(this->FileName){ delete [] this->FileName; } } // Copies xmlChar * to static area then frees chars XdmfConstString XdmfLightData::DupChars(XdmfPointer Chars){ xmlChar *cp; cp = (xmlChar *)Chars; if(!cp) return(NULL); if(this->StaticReturnBuffer) delete [] this->StaticReturnBuffer; this->StaticReturnBuffer = new char[xmlStrlen(cp) + 1]; strcpy(this->StaticReturnBuffer, (char *)cp); xmlFree(cp); return(this->StaticReturnBuffer); } // Copies bufp->content to static area then frees buffer XdmfConstString XdmfLightData::DupBuffer(XdmfPointer Buffer){ xmlBuffer *bufp; bufp = (xmlBuffer *)Buffer; if(!bufp) return(NULL); if(this->StaticReturnBuffer) delete [] this->StaticReturnBuffer; this->StaticReturnBuffer = new char[xmlBufferLength(bufp) + 1]; strcpy(this->StaticReturnBuffer, (char *)xmlBufferContent(bufp)); xmlBufferFree(bufp); return(this->StaticReturnBuffer); }
38.275
69
0.464076
[ "model" ]
3c3863d02d2c612475f544c91473b80eebbf71e0
16,057
cpp
C++
Game/resources.cpp
swick/OpenGothic
7cc7c0539c90a820607b227a38ae1146c104d420
[ "MIT" ]
null
null
null
Game/resources.cpp
swick/OpenGothic
7cc7c0539c90a820607b227a38ae1146c104d420
[ "MIT" ]
null
null
null
Game/resources.cpp
swick/OpenGothic
7cc7c0539c90a820607b227a38ae1146c104d420
[ "MIT" ]
null
null
null
#include "resources.h" #include <Tempest/MemReader> #include <Tempest/Pixmap> #include <Tempest/Device> #include <Tempest/Dir> #include <Tempest/Application> #include <Tempest/Sound> #include <Tempest/SoundEffect> #include <Tempest/Log> #include <zenload/modelScriptParser.h> #include <zenload/zCModelMeshLib.h> #include <zenload/zCMorphMesh.h> #include <zenload/zCProgMeshProto.h> #include <zenload/zenParser.h> #include <zenload/ztex2dds.h> #include <fstream> #include "graphics/submesh/staticmesh.h" #include "graphics/submesh/animmesh.h" #include "graphics/skeleton.h" #include "graphics/protomesh.h" #include "graphics/animation.h" #include "graphics/attachbinder.h" #include "physics/physicmeshshape.h" #include "dmusic/riff.h" #include "gothic.h" using namespace Tempest; Resources* Resources::inst=nullptr; static void emplaceTag(char* buf, char tag){ for(size_t i=1;buf[i];++i){ if(buf[i]==tag && buf[i-1]=='_' && buf[i+1]=='0'){ buf[i ]='%'; buf[i+1]='s'; ++i; return; } } } Resources::Resources(Gothic &gothic, Tempest::Device &device) : device(device), asset("data",device), gothic(gothic) { inst=this; const char* menu = "data/font/menu.ttf"; const char* main = "data/font/main.ttf"; if(/* DISABLES CODE */ (true)) { // international chasters menu = "data/font/Kelvinch-Roman.otf"; main = "data/font/Kelvinch-Roman.otf"; } static std::array<VertexFsq,6> fsqBuf = {{ {-1,-1},{ 1,1},{1,-1}, {-1,-1},{-1,1},{1, 1} }}; fsq = Resources::loadVbo(fsqBuf.data(),fsqBuf.size()); const float mult=0.75f; fBuff .reserve(8*1024*1024); ddsBuf.reserve(8*1024*1024); menuFnt = Font(menu); menuFnt.setPixelSize(44*mult); mainFnt = Font(main); mainFnt.setPixelSize(24*mult); dlgFnt = Font(main); dlgFnt.setPixelSize(32*mult); fallback = device.loadTexture("data/fallback.png"); Pixmap pm(1,1,Pixmap::Format::RGBA); fbZero = device.loadTexture(pm); // TODO: priority for *.mod files std::vector<std::u16string> archives; detectVdf(archives,gothic.path()+u"Data/"); // addon archives first! std::sort(archives.begin(),archives.end(),[](const std::u16string& a,const std::u16string& b){ int aIsMod = (a.rfind(u".mod")==a.size()-4) ? 1 : 0; int bIsMod = (b.rfind(u".mod")==b.size()-4) ? 1 : 0; return std::make_tuple(aIsMod,VDFS::FileIndex::getLastModTime(a)) > std::make_tuple(bIsMod,VDFS::FileIndex::getLastModTime(b)); }); for(auto& i:archives) gothicAssets.loadVDF(i); gothicAssets.finalizeLoad(); // auto v = getFileData("BSANVIL_OC_USE.asc"); // Tempest::WFile f("../internal/BSANVIL_OC_USE.asc"); // f.write(v.data(),v.size()); } Resources::~Resources() { inst=nullptr; } void Resources::detectVdf(std::vector<std::u16string> &ret, const std::u16string &root) { Dir::scan(root,[this,&root,&ret](const std::u16string& vdf,Dir::FileType t){ if(t==Dir::FT_File) { auto file = root + vdf; if(VDFS::FileIndex::getLastModTime(file)>0 || vdf.rfind(u".mod")==vdf.size()-4) ret.emplace_back(std::move(file)); return; } if(t==Dir::FT_Dir && vdf!=u".." && vdf!=u".") { auto dir = root + vdf + u"/"; detectVdf(ret,dir); } }); } Font Resources::fontByName(const std::string &fontName) { if(fontName=="FONT_OLD_10_WHITE.TGA" || fontName=="font_old_10_white.tga"){ return Resources::font(); } else if(fontName=="FONT_OLD_10_WHITE_HI.TGA"){ return Resources::font(); } else if(fontName=="FONT_OLD_20_WHITE.TGA" || fontName=="font_old_20_white.tga"){ return Resources::menuFont(); } else { return Resources::menuFont(); } } const Texture2d& Resources::fallbackTexture() { return inst->fallback; } const Texture2d &Resources::fallbackBlack() { return inst->fbZero; } VDFS::FileIndex& Resources::vdfsIndex() { return inst->gothicAssets; } const Tempest::VertexBuffer<Resources::VertexFsq> &Resources::fsqVbo() { return inst->fsq; } Tempest::Texture2d* Resources::implLoadTexture(std::string name) { if(name.size()==0) return nullptr; auto it=texCache.find(name); if(it!=texCache.end()) return it->second.get(); if(getFileData(name.c_str(),fBuff)) return implLoadTexture(std::move(name),fBuff); if(name.rfind(".TGA")==name.size()-4){ auto n = name; n.resize(n.size()+2); std::memcpy(&n[0]+n.size()-6,"-C.TEX",6); if(!getFileData(n.c_str(),fBuff)) return nullptr; ddsBuf.clear(); ZenLoad::convertZTEX2DDS(fBuff,ddsBuf); return implLoadTexture(std::move(name),ddsBuf); } return nullptr; } Texture2d *Resources::implLoadTexture(std::string&& name,const std::vector<uint8_t> &data) { try { Tempest::MemReader rd(data.data(),data.size()); Tempest::Pixmap pm(rd); std::unique_ptr<Texture2d> t{new Texture2d(device.loadTexture(pm))}; Texture2d* ret=t.get(); texCache[std::move(name)] = std::move(t); return ret; } catch(...){ Log::e("unable to load texture \"",name,"\""); return &fallback; } } ProtoMesh* Resources::implLoadMesh(const std::string &name) { if(name.size()==0) return nullptr; auto it=aniMeshCache.find(name); if(it!=aniMeshCache.end()) return it->second.get(); if(name=="Hum_Head_Pony.MMB")//"Sna_Body.MDM" Log::d(""); try { ZenLoad::PackedMesh sPacked; ZenLoad::zCModelMeshLib library; auto code=loadMesh(sPacked,library,name); std::unique_ptr<ProtoMesh> t{code==MeshLoadCode::Static ? new ProtoMesh(sPacked) : new ProtoMesh(library)}; ProtoMesh* ret=t.get(); aniMeshCache[name] = std::move(t); if(code==MeshLoadCode::Static && sPacked.subMeshes.size()>0) phyMeshCache[ret].reset(PhysicMeshShape::load(sPacked)); if(code==MeshLoadCode::Error) throw std::runtime_error("load failed"); return ret; } catch(...){ Log::e("unable to load mesh \"",name,"\""); return nullptr; } } Skeleton* Resources::implLoadSkeleton(std::string name) { if(name.size()==0) return nullptr; if(name.rfind(".MDS")==name.size()-4 || name.rfind(".mds")==name.size()-4) std::memcpy(&name[name.size()-3],"MDH",3); auto it=skeletonCache.find(name); if(it!=skeletonCache.end()) return it->second.get(); try { ZenLoad::zCModelMeshLib library(name,gothicAssets,1.f); std::unique_ptr<Skeleton> t{new Skeleton(library,name)}; Skeleton* ret=t.get(); skeletonCache[name] = std::move(t); if(!hasFile(name)) throw std::runtime_error("load failed"); return ret; } catch(...){ Log::e("unable to load skeleton \"",name,"\""); return nullptr; } } Animation *Resources::implLoadAnimation(std::string name) { if(name.size()<4) return nullptr; auto it=animCache.find(name); if(it!=animCache.end()) return it->second.get(); try { Animation* ret=nullptr; if(gothic.isGothic2()){ if(name.rfind(".MDS")==name.size()-4 || name.rfind(".mds")==name.size()-4 || name.rfind(".MDH")==name.size()-4) std::memcpy(&name[name.size()-3],"MSB",3); ZenLoad::ZenParser zen(name,gothicAssets); ZenLoad::MdsParserBin p(zen); std::unique_ptr<Animation> t{new Animation(p,name.substr(0,name.size()-4),false)}; ret=t.get(); animCache[name] = std::move(t); } else { if(name.rfind(".MDH")==name.size()-4) std::memcpy(&name[name.size()-3],"MDS",3); ZenLoad::ZenParser zen(name,gothicAssets); ZenLoad::MdsParserTxt p(zen); std::unique_ptr<Animation> t{new Animation(p,name.substr(0,name.size()-4),true)}; ret=t.get(); animCache[name] = std::move(t); } if(!hasFile(name)) throw std::runtime_error("load failed"); return ret; } catch(...){ Log::e("unable to load animation \"",name,"\""); return nullptr; } } SoundEffect *Resources::implLoadSound(const char* name) { if(name==nullptr || *name=='\0') return nullptr; auto it=sndCache.find(name); if(it!=sndCache.end()) return it->second.get(); if(!getFileData(name,fBuff)) return nullptr; try { Tempest::MemReader rd(fBuff.data(),fBuff.size()); auto s = sound.load(rd); std::unique_ptr<SoundEffect> t{new SoundEffect(std::move(s))}; SoundEffect* ret=t.get(); sndCache[name] = std::move(t); return ret; } catch(...){ Log::e("unable to load sound \"",name,"\""); return nullptr; } } Sound Resources::implLoadSoundBuffer(const char *name) { if(!getFileData(name,fBuff)) return Sound(); try { Tempest::MemReader rd(fBuff.data(),fBuff.size()); return Sound(rd); } catch(...){ Log::e("unable to load sound \"",name,"\""); return Sound(); } } Dx8::Segment *Resources::implLoadMusic(const std::string &name) { if(name.size()==0) return nullptr; auto it=musicCache.find(name); if(it!=musicCache.end()) return it->second.get(); try { std::u16string p = gothic.path(); p.append(name.begin(),name.end()); Tempest::RFile fin(p); std::vector<uint8_t> data(fin.size()); fin.read(reinterpret_cast<char*>(&data[0]),data.size()); Dx8::Riff riff{data.data(),data.size()}; std::unique_ptr<Dx8::Segment> t{new Dx8::Segment(riff)}; Dx8::Segment* ret=t.get(); musicCache[name] = std::move(t); return ret; } catch(...){ musicCache[name] = nullptr; Log::e("unable to load music \"",name,"\""); return nullptr; } } bool Resources::hasFile(const std::string &fname) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->gothicAssets.hasFile(fname); } const Texture2d *Resources::loadTexture(const char *name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadTexture(name); } const Tempest::Texture2d* Resources::loadTexture(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadTexture(name); } const Texture2d *Resources::loadTexture(const std::string &name, int32_t iv, int32_t ic) { if(name.size()>=128)// || (iv==0 && ic==0)) return loadTexture(name); char v[16]={}; char c[16]={}; char buf1[128]={}; char buf2[128]={}; std::snprintf(v,sizeof(v),"V%d",iv); std::snprintf(c,sizeof(c),"C%d",ic); std::strcpy(buf1,name.c_str()); emplaceTag(buf1,'V'); std::snprintf(buf2,sizeof(buf2),buf1,v); emplaceTag(buf2,'C'); std::snprintf(buf1,sizeof(buf1),buf2,c); return loadTexture(buf1); } const ProtoMesh *Resources::loadMesh(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadMesh(name); } const Skeleton *Resources::loadSkeleton(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadSkeleton(name); } const Animation *Resources::loadAnimation(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadAnimation(name); } const PhysicMeshShape *Resources::physicMesh(const ProtoMesh *view) { std::lock_guard<std::recursive_mutex> g(inst->sync); if(view==nullptr) return nullptr; auto it = inst->phyMeshCache.find(view); if(it!=inst->phyMeshCache.end()) return it->second.get(); return nullptr; } SoundEffect *Resources::loadSound(const char *name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadSound(name); } SoundEffect *Resources::loadSound(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadSound(name.c_str()); } Sound Resources::loadSoundBuffer(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadSoundBuffer(name.c_str()); } Sound Resources::loadSoundBuffer(const char *name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadSoundBuffer(name); } Dx8::Segment *Resources::loadMusic(const std::string &name) { std::lock_guard<std::recursive_mutex> g(inst->sync); return inst->implLoadMusic(name); } bool Resources::getFileData(const char *name, std::vector<uint8_t> &dat) { dat.clear(); return inst->gothicAssets.getFileData(name,dat); } std::vector<uint8_t> Resources::getFileData(const char *name) { std::vector<uint8_t> data; inst->gothicAssets.getFileData(name,data); return data; } std::vector<uint8_t> Resources::getFileData(const std::string &name) { std::vector<uint8_t> data; inst->gothicAssets.getFileData(name,data); return data; } Resources::MeshLoadCode Resources::loadMesh(ZenLoad::PackedMesh& sPacked, ZenLoad::zCModelMeshLib& library, std::string name) { std::vector<uint8_t> data; std::vector<uint8_t> dds; // Check if this isn't the compiled version if(name.rfind("-C")==std::string::npos) { // Strip the extension ".***" // Add "compiled"-extension if(name.rfind(".3DS")==name.size()-4) std::memcpy(&name[name.size()-3],"MRM",3); else if(name.rfind(".3ds")==name.size()-4) std::memcpy(&name[name.size()-3],"MRM",3); else if(name.rfind(".mms")==name.size()-4) std::memcpy(&name[name.size()-3],"MMB",3); else if(name.rfind(".MMS")==name.size()-4) std::memcpy(&name[name.size()-3],"MMB",3); else if(name.rfind(".ASC")==name.size()-4) std::memcpy(&name[name.size()-3],"MDL",3); else if(name.rfind(".asc")==name.size()-4) std::memcpy(&name[name.size()-3],"MDL",3); } if(name.rfind(".MRM")==name.size()-4) { ZenLoad::zCProgMeshProto zmsh(name,gothicAssets); if(zmsh.getNumSubmeshes()==0) return MeshLoadCode::Error; zmsh.packMesh(sPacked,1.f); return MeshLoadCode::Static; } if(name.rfind(".MMB")==name.size()-4) { ZenLoad::zCMorphMesh zmm(name,gothicAssets); if(zmm.getMesh().getNumSubmeshes()==0) return MeshLoadCode::Error; zmm.getMesh().packMesh(sPacked,1.f); for(auto& i:sPacked.vertices){ // FIXME: hack with morph mesh-normals std::swap(i.Normal.y,i.Normal.z); i.Normal.z=-i.Normal.z; } return MeshLoadCode::Static; } if(name.rfind(".MDMS")==name.size()-5 || name.rfind(".MDS") ==name.size()-4 || name.rfind(".MDL") ==name.size()-4 || name.rfind(".MDM") ==name.size()-4 || name.rfind(".mds") ==name.size()-4){ library = loadMDS(name); return MeshLoadCode::Dynamic; } return MeshLoadCode::Error; } ZenLoad::zCModelMeshLib Resources::loadMDS(std::string &name) { if(name.rfind(".MDMS")==name.size()-5){ name.resize(name.size()-1); return ZenLoad::zCModelMeshLib(name,gothicAssets,1.f); } if(hasFile(name)) return ZenLoad::zCModelMeshLib(name,gothicAssets,1.f); std::memcpy(&name[name.size()-3],"MDL",3); if(hasFile(name)) return ZenLoad::zCModelMeshLib(name,gothicAssets,1.f); std::memcpy(&name[name.size()-3],"MDM",3); if(hasFile(name)) { ZenLoad::zCModelMeshLib lib(name,gothicAssets,1.f); std::memcpy(&name[name.size()-3],"MDH",3); if(hasFile(name)) { auto data=getFileData(name); if(!data.empty()){ ZenLoad::ZenParser parser(data.data(), data.size()); lib.loadMDH(parser,1.f); } } return lib; } std::memcpy(&name[name.size()-3],"MDH",3); if(hasFile(name)) return ZenLoad::zCModelMeshLib(name,gothicAssets,1.f); return ZenLoad::zCModelMeshLib(); } const AttachBinder *Resources::bindMesh(const ProtoMesh &anim, const Skeleton &s, const char *defBone) { std::lock_guard<std::recursive_mutex> g(inst->sync); if(anim.submeshId.size()==0){ static AttachBinder empty; return &empty; } BindK k = BindK(&s,&anim,defBone ? defBone : ""); auto it = inst->bindCache.find(k); if(it!=inst->bindCache.end()) return it->second.get(); std::unique_ptr<AttachBinder> ret(new AttachBinder(s,anim,defBone)); auto p = ret.get(); inst->bindCache[k] = std::move(ret); return p; }
28.170175
127
0.639534
[ "mesh", "vector" ]
3c3aa81b118408da2250feade86b911ff0cd9a80
7,481
cc
C++
cpp/p013.cc
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
4
2018-11-14T12:03:05.000Z
2019-09-03T14:33:28.000Z
cpp/p013.cc
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
null
null
null
cpp/p013.cc
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
1
2018-11-17T14:39:22.000Z
2018-11-17T14:39:22.000Z
/* * Solution to Project Euler problem 13 * by mathm */ #include <string> #include <vector> #include <iostream> class bigint; std::string compute(); int main(){ using std::cout; using std::endl; cout<<compute()<<endl; } class bigint{ static const int base=10; typedef long long int64; public: bigint(){} bigint(std::string s){ for(int i=0;i<s.size();i++){ buf.push_back(s[s.size()-1-i]-'0'); } } bigint( int64 num){ while(num>0){ buf.push_back(num%base); num/=base; } } std::string to_string() { std::string res; for (int i=0;i<buf.size();i++){ res.push_back( buf[size()-1-i]+'0'); } return res; } int size() const { return buf.size(); } std::vector<int> data() const { return buf; } void add(int64); void add( const bigint & other); private: void norm(){ int carry=0; for( int i=0;i<size();i++){ int temp=(buf[i]+carry)%10; carry=(buf[i]+carry)/10; buf[i]=temp; } if( carry>0){ buf.push_back(carry%10); } } std::vector<int> buf; }; void bigint::add(int64 num){ int index=0; while(index<size()){ buf[index++]+=num%10; num/=10; if( num==0) return ; } while(num>=1){ buf.push_back(num%10); num/=10; } norm(); } void bigint::add(const bigint & other){ int m=size(); int n=other.size(); int index =0; if(n<=m){ for( ;index<n;index++){ buf[index]+=other.data()[index]; } norm(); }else{ for(;index<m;index++){ buf[index]+=other.data()[index]; } for(;index<n;index++){ buf.push_back(other.data()[index]); } norm(); } } std::string compute(){ std::vector<std::string> NUMBERS = { "37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690" }; bigint a=NUMBERS[0]; for(int i=1;i<NUMBERS.size();i++){ a.add( bigint(NUMBERS[i])); } return a.to_string().substr(0,10); }
34.159817
55
0.804973
[ "vector" ]
3c3d86f9d23a2616b2691b66801960d1868dd41a
38,934
cpp
C++
src/db/timing/timinglib/timinglib_tcl_command.cpp
zoumingzhe/OpenEDA
e87867044b495e40d4276756a6cb13bb38fe49a9
[ "BSD-3-Clause" ]
1
2021-01-01T23:39:02.000Z
2021-01-01T23:39:02.000Z
src/db/timing/timinglib/timinglib_tcl_command.cpp
zoumingzhe/OpenEDA
e87867044b495e40d4276756a6cb13bb38fe49a9
[ "BSD-3-Clause" ]
null
null
null
src/db/timing/timinglib/timinglib_tcl_command.cpp
zoumingzhe/OpenEDA
e87867044b495e40d4276756a6cb13bb38fe49a9
[ "BSD-3-Clause" ]
null
null
null
/** * @file timinglib_tcl_command.cpp * @date 2020-09-14 * @brief * * Copyright (C) 2020 NIIC EDA * * All rights reserved. * * This software may be modified and distributed under the terms * * of the BSD license. See the LICENSE file for details. */ #include "db/timing/timinglib/timinglib_tcl_command.h" #include <unistd.h> #include <fstream> #include <iostream> #include <list> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "db/core/cell.h" #include "db/core/db.h" #include "db/timing/timinglib/analysis_corner.h" #include "db/timing/timinglib/analysis_mode.h" #include "db/timing/timinglib/analysis_view.h" #include "db/timing/timinglib/libset.h" #include "db/timing/timinglib/timinglib_cell.h" #include "db/timing/timinglib/timinglib_lib.h" #include "db/timing/timinglib/timinglib_libbuilder.h" #include "db/timing/timinglib/timinglib_libsyn.h" #include "db/timing/timinglib/timinglib_pgterm.h" #include "db/timing/timinglib/timinglib_term.h" #include "util/stream.h" #include "util/util.h" namespace open_edi { namespace db { bool buildTermMapping(Cell *cell, const std::vector<TCell *> &tcells) { Cell *topCell = getTopCell(); if (topCell == nullptr) return false; uint64_t size = cell->getNumOfTerms(); std::unordered_map<std::string, Term *> term_map; std::list<std::string> term_names; std::string str = ""; for (uint64_t index = 0; index < size; ++index) { auto p = cell->getTerm(index); if (p != nullptr) { str = p->getName(); term_names.emplace_back(str); term_map[str] = p; } } std::unordered_map<TCell *, std::list<std::string> > cell_tterm_names_map; std::unordered_map<TCell *, std::unordered_map<std::string, TTerm *> > cell_tterm_map; for (auto tcell : tcells) { auto tterms = tcell->getTerms(); std::list<std::string> &tterm_names = cell_tterm_names_map[tcell]; std::unordered_map<std::string, TTerm *> &tterm_map = cell_tterm_map[tcell]; for (auto tterm : tterms) { if (tterm != nullptr) { str = tterm->getName(); tterm_names.emplace_back(str); tterm_map[str] = tterm; } } for (auto &name : tterm_names) { if (term_map.find(name) == term_map.end()) { auto term = topCell->createObject<Term>(kObjectTypeTerm); if (term) { cell->addTerm(term->getId()); term_names.emplace_back(name); term_map[name] = term; } else { open_edi::util::message->issueMsg("TIMINGLIB", 1, kError, "term", str.c_str()); return false; } } } } std::unordered_map<TCell *, std::vector<TTerm *> > tcell_reset_terms_map; for (auto iter : cell_tterm_names_map) { TCell *cell = iter.first; std::list<std::string> &tterm_names = cell_tterm_names_map[cell]; std::unordered_map<std::string, TTerm *> &tterm_map = cell_tterm_map[cell]; for (auto &name : term_names) { if (tterm_map.find(name) != tterm_map.end()) { TTerm *term = tterm_map[name]; if (term) tcell_reset_terms_map[cell].emplace_back(term); } else { TTerm *term = cell->getOrCreateTerm(name); if (term == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, kError, "tterm", name.c_str()); return false; } term->setName(name); term->setDummy(true); tterm_names.emplace_back(name); tterm_map[name] = term; tcell_reset_terms_map[cell].emplace_back(term); } } } std::vector<Term *> reset_terms; reset_terms.reserve(term_names.size()); for (auto &name : term_names) { Term *t = term_map[name]; if (t) reset_terms.emplace_back(t); } cell->resetTerms(reset_terms); for (auto iter : tcell_reset_terms_map) { TCell *cell = iter.first; std::vector<TTerm *> &terms = iter.second; cell->resetTerms(terms); } return true; } void buildTermMapping() { Cell *topCell = getTopCell(); if (topCell == nullptr) return; std::unordered_multimap<std::string, Cell *> cell_map; std::unordered_set<std::string> cell_names; std::function<void(Cell *, std::unordered_multimap<std::string, Cell *> *, std::unordered_set<std::string> *)> getCells; getCells = [&getCells]( Cell *cell, std::unordered_multimap<std::string, Cell *> *cell_map, std::unordered_set<std::string> *cell_names) { uint64_t size = cell->getNumOfCells(); for (uint64_t index = 0; index < size; ++index) { auto c = cell->getCell(index); if (c != nullptr) { cell_map->insert(std::make_pair(c->getName(), c)); cell_names->insert(c->getName()); getCells(c, cell_map, cell_names); } } }; getCells(topCell, &cell_map, &cell_names); if (cell_map.empty()) return; Timing *timing_lib = getTimingLib(); std::unordered_multimap<std::string, TCell *> tcell_map; uint64_t size = timing_lib->getNumOfAnalysisViews(); for (auto index = 0; index < size; ++index) { AnalysisView *view = timing_lib->getAnalysisView(index); if (view == nullptr) continue; auto corner = view->getAnalysisCorner(); if (corner == nullptr) continue; auto libset = corner->getLibset(); if (libset == nullptr) continue; auto libs = libset->getTimingLibs(); for (auto lib : libs) { auto cells = lib->getTimingCells(); for (auto cell : cells) { if (cell) tcell_map.insert(std::make_pair(cell->getName(), cell)); } } } if (tcell_map.empty()) return; for (auto &str : cell_names) { auto iter_cell = cell_map.equal_range(str); std::vector<Cell *> cells; uint64_t cur_cell_count = 0; for (auto t = iter_cell.first; t != iter_cell.second; ++t) { cells.emplace_back(t->second); ++cur_cell_count; } if (cur_cell_count > 1) { open_edi::util::message->issueMsg("TIMINGLIB", 2, kError, "cell", str.c_str()); continue; } auto iter_tcell = tcell_map.equal_range(str); std::vector<TCell *> tcells; for (auto t = iter_tcell.first; t != iter_tcell.second; ++t) { tcells.emplace_back(t->second); } if (tcells.empty()) continue; bool ret = buildTermMapping(cells[0], tcells); if (!ret) return; } } bool parseLib(LibSet *libset, const std::string &file, const std::string &dump_lib_file, const std::string &dump_db_file, const std::string &dump_log_file, bool clearFileContent) { if (libset == nullptr) return false; Timinglib::LibBuilder builder(libset); Timinglib::LibSyn libSyn(&builder); std::string parseLogStr = ""; bool ret = libSyn.parseLibertyFile(file.c_str(), &parseLogStr); if (ret == true) { ret = libSyn.isLibertySyntaxValid(); } else { return false; } if (dump_lib_file != "") { if (false == libSyn.dumpLibFile(dump_lib_file.c_str(), clearFileContent)) return false; } uint8_t endl_c = '\n'; if (dump_log_file != "") { // open_edi::util::message->info("Write file %s...\n", // dump_log_file.c_str()); std::ios_base::openmode mode = std::ios::out; if (clearFileContent) mode = mode | std::ios::trunc; else mode = mode | std::ios::app; std::ofstream os_log(dump_log_file.c_str(), mode); if (os_log.fail()) { open_edi::util::message->issueMsg("TIMINGLIB", 3, kError, dump_log_file.c_str()); return false; } os_log << parseLogStr << endl_c; os_log.close(); // open_edi::util::message->info("Write file %s finished.\n", // dump_log_file.c_str()); } if (dump_db_file != "") { // open_edi::util::message->info("Write file %s...\n", // dump_db_file.c_str()); std::ios_base::openmode mode = std::ios::out; if (clearFileContent) mode = mode | std::ios::trunc; else mode = mode | std::ios::app; OStream<std::ofstream> os(dump_db_file.c_str(), mode); if (!os.isOpen()) { open_edi::util::message->issueMsg("TIMINGLIB", 3, kError, dump_db_file.c_str()); return false; } os << *libset << endl_c; os.close(); // open_edi::util::message->info("Write file %s...\n", // dump_db_file.c_str()); } // open_edi::util::message->info("Building term mapping...\n"); buildTermMapping(); // open_edi::util::message->info("Building term mapping finished.\n"); return true; } int readTimingLibCommand(ClientData cld, Tcl_Interp *itp, int argc, const char *argv[]) { if (argc > 1) { std::vector<std::string> files; std::string dump_lib_file = ""; std::string dump_db_file = ""; std::string dump_log_file = ""; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-dump_lib")) { if ((i + 1) < argc) { dump_lib_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-dump_db")) { if ((i + 1) < argc) { dump_db_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-dump_log")) { if ((i + 1) < argc) { dump_log_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else { files.emplace_back(argv[i]); } } size_t lib_file_count = files.size(); if (lib_file_count == 0) { open_edi::util::message->issueMsg("TIMINGLIB", 4, kError, "liberty"); return TCL_ERROR; } for (int i = 0; i < lib_file_count; ++i) { if (access(files[i].c_str(), F_OK) == -1) { open_edi::util::message->issueMsg( "TIMINGLIB", 5, open_edi::util::kError, files[i].c_str()); return TCL_ERROR; } } Timing *timing_lib = getTimingLib(); if (timing_lib == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 6, open_edi::util::kError, "top container", "reading timing library"); return TCL_ERROR; } std::string default_name = "default"; auto view = timing_lib->getAnalysisView(default_name); AnalysisCorner *corner = nullptr; if (view == nullptr) { auto mode = timing_lib->createAnalysisMode(default_name); if (mode == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 1, open_edi::util::kError, "default", "mode"); return TCL_ERROR; } corner = timing_lib->createAnalysisCorner(default_name); if (corner == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "default", "corner"); return TCL_ERROR; } view = timing_lib->createAnalysisView(default_name); if (view == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 1, open_edi::util::kError, "default", "view"); return TCL_ERROR; } view->setAnalysisMode(mode->getId()); view->setAnalysisCorner(corner->getId()); view->setActive(true); view->setSetup(true); view->setHold(true); timing_lib->addActiveSetupView(view->getId()); timing_lib->addActiveHoldView(view->getId()); } else { corner = view->getAnalysisCorner(); } LibSet *libset = corner->getLibset(); if (libset == nullptr) { libset = Object::createObject<LibSet>(kObjectTypeLibSet, timing_lib->getId()); if (libset == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "default", "libset"); return TCL_ERROR; } libset->setName(corner->getName()); corner->setLibset(libset->getId()); } if (lib_file_count != 0) open_edi::util::message->info("\nReading Timing Library\n"); bool clearFileContent = true; bool bSuccess = true; for (int i = 0; i < lib_file_count; ++i) { if (i != 0) clearFileContent = false; if (false == parseLib(libset, files[i], dump_lib_file, dump_db_file, dump_log_file, clearFileContent)) { bSuccess = false; break; } } if (lib_file_count != 0) { if (bSuccess) { open_edi::util::message->info( "\nRead Timing Library successfully.\n"); return TCL_OK; } else { open_edi::util::message->issueMsg("TIMINGLIB", 9, open_edi::util::kError, "read Timing Library"); return TCL_ERROR; } } } else { open_edi::util::message->issueMsg("TIMINGLIB", 4, kError, "liberty"); return TCL_ERROR; } return TCL_OK; } typedef struct analysisViewArgs { std::string name = ""; std::string mode = ""; std::string corner = ""; } AnalysisViewArgs; void printAnalysisViewCommandHelp() { open_edi::util::message->info("create_analysis_view:\n"); open_edi::util::message->info(" -name xxx\n"); open_edi::util::message->info(" -mode xxx\n"); open_edi::util::message->info(" -corner xxx\n"); open_edi::util::message->info(" -help\n"); } int createAnalysisViewCommand(ClientData cld, Tcl_Interp *itp, int argc, const char *argv[]) { AnalysisViewArgs args; if (argc == 2 && !strcmp(argv[1], "-help")) { printAnalysisViewCommandHelp(); return TCL_OK; } if (argc == 7) { for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-name")) { if ((i + 1) < argc) { args.name = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-mode")) { if ((i + 1) < argc) { args.mode = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-corner")) { if ((i + 1) < argc) { args.corner = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } } Timing *timing_lib = getTimingLib(); if (timing_lib == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 6, open_edi::util::kError, "top container", "creating analysis view"); return TCL_ERROR; } if (args.name == "default") { open_edi::util::message->issueMsg( "TIMINGLIB", 10, open_edi::util::kError, "default"); return TCL_ERROR; } // find AnalysisMode by mode AnalysisMode *analysis_mode = timing_lib->getAnalysisMode(args.mode); if (analysis_mode == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 11, open_edi::util::kError, "mode", args.mode.c_str()); return TCL_ERROR; } auto mode = Object::createObject<AnalysisMode>(kObjectTypeAnalysisMode, timing_lib->getId()); if (mode == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "mode"); return TCL_ERROR; } *mode = *analysis_mode; // find AnalysisCorner by corner AnalysisCorner *analysis_corner = timing_lib->getAnalysisCorner(args.corner); if (analysis_corner == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 11, open_edi::util::kError, "corner", args.corner.c_str()); return TCL_ERROR; } auto corner = Object::createObject<AnalysisCorner>( kObjectTypeAnalysisCorner, timing_lib->getId()); if (corner == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "corner"); return TCL_ERROR; } *corner = *analysis_corner; AnalysisView *analysis_view = timing_lib->createAnalysisView(args.name); if (analysis_view == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 1, open_edi::util::kError, "analysis view", args.name.c_str()); return TCL_ERROR; } mode->setOwner(analysis_view->getId()); analysis_view->setAnalysisMode(mode->getId()); corner->setOwner(analysis_view->getId()); analysis_view->setAnalysisCorner(corner->getId()); open_edi::util::message->info("Creating view %s successfully.\n", args.name.c_str()); return TCL_OK; } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } return TCL_OK; } typedef struct analysisModeArgs { std::string name = ""; std::string constraint_file = ""; } AnalysisModeArgs; void printAnalysisModeCommandHelp() { open_edi::util::message->info("create_analysis_mode:\n"); open_edi::util::message->info(" -name xxx\n"); open_edi::util::message->info( " -constraint_file xxx\n"); open_edi::util::message->info(" -help\n"); } int createAnalysisModeCommand(ClientData cld, Tcl_Interp *itp, int argc, const char *argv[]) { if (argc == 2 && !strcmp(argv[1], "-help")) { printAnalysisModeCommandHelp(); return TCL_OK; } if (argc == 5) { AnalysisModeArgs args; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-name")) { if ((i + 1) < argc) { args.name = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-constraint_file")) { if ((i + 1) < argc) { args.constraint_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } } if (access(args.constraint_file.c_str(), F_OK) == -1) { open_edi::util::message->issueMsg("TIMINGLIB", 5, open_edi::util::kError, args.constraint_file.c_str()); return TCL_ERROR; } Timing *timing_lib = getTimingLib(); if (timing_lib == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 6, open_edi::util::kError, "top container", "creating analysis mode"); return TCL_ERROR; } if (args.name == "default") { open_edi::util::message->issueMsg( "TIMINGLIB", 10, open_edi::util::kError, "default"); return TCL_ERROR; } AnalysisMode *mode = timing_lib->createAnalysisMode(args.name); if (mode == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "mode", args.name.c_str()); return TCL_ERROR; } mode->addConstraintFile(args.constraint_file); open_edi::util::message->info("Creating mode %s successfully.\n", args.name.c_str()); return TCL_OK; } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } return TCL_OK; } typedef struct analysisCornerArgs { std::string name = ""; std::string rc_tech = ""; std::string lib_set = ""; } AnalysisCornerArgs; void printAnalysisCornerCommandHelp() { open_edi::util::message->info("create_analysis_corner:\n"); open_edi::util::message->info(" -name xxx\n"); open_edi::util::message->info(" -rc_tech xxx\n"); open_edi::util::message->info(" -lib_set xxx\n"); open_edi::util::message->info(" -help\n"); } int createAnalysisCornerCommand(ClientData cld, Tcl_Interp *itp, int argc, const char *argv[]) { if (argc == 2 && !strcmp(argv[1], "-help")) { printAnalysisCornerCommandHelp(); return TCL_OK; } if (argc >= 7) { AnalysisCornerArgs args; std::string dump_lib_file = ""; std::string dump_db_file = ""; std::string dump_log_file = ""; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-name")) { if ((i + 1) < argc) { args.name = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-rc_tech")) { if ((i + 1) < argc) { args.rc_tech = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-lib_set")) { if ((i + 1) < argc) { args.lib_set = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-dump_lib")) { if ((i + 1) < argc) { dump_lib_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-dump_db")) { if ((i + 1) < argc) { dump_db_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else if (!strcmp(argv[i], "-dump_log")) { if ((i + 1) < argc) { dump_log_file = argv[++i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } } if (access(args.rc_tech.c_str(), F_OK) == -1) { open_edi::util::message->issueMsg( "TIMINGLIB", 5, open_edi::util::kError, args.rc_tech.c_str()); return TCL_ERROR; } if (access(args.lib_set.c_str(), F_OK) == -1) { open_edi::util::message->issueMsg( "TIMINGLIB", 5, open_edi::util::kError, args.lib_set.c_str()); return TCL_ERROR; } Timing *timing_lib = getTimingLib(); if (timing_lib == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 6, open_edi::util::kError, "top container", "creating anlysis corner"); return TCL_ERROR; } if (args.name == "default") { open_edi::util::message->issueMsg( "TIMINGLIB", 10, open_edi::util::kError, "default"); return TCL_ERROR; } LibSet *libset = Object::createObject<LibSet>(kObjectTypeLibSet, timing_lib->getId()); if (libset == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "libset", args.lib_set.c_str()); return TCL_ERROR; } libset->setName(args.name); open_edi::util::message->info("\nReading Timing Library\n"); if (false == parseLib(libset, args.lib_set, dump_lib_file, dump_db_file, dump_log_file, true)) { // open_edi::util::message->issueMsg("TIMINGLIB", 9, // open_edi::util::kError, "read Timing Library"); open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "corner", args.name.c_str()); return TCL_ERROR; } open_edi::util::message->info("\nRead Timing Library successfully.\n"); AnalysisCorner *corner = timing_lib->createAnalysisCorner(args.name); if (corner == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 1, open_edi::util::kError, "corner", args.name.c_str()); return TCL_ERROR; } corner->setRcTechFile(args.rc_tech); corner->setLibset(libset->getId()); open_edi::util::message->info("Creating corner %s successfully.\n", args.name.c_str()); return TCL_OK; } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } return TCL_OK; } typedef struct setAnalysisViewStatusArgs { bool active = false; bool setup = false; bool hold = false; bool max_tran = false; bool max_cap = false; bool min_cap = false; bool leakage_power = false; bool dynamic_power = false; bool cell_em = false; bool signal_em = false; std::string view_name = ""; } SetAnalysisViewStatusArgs; void printSetAnalysisViewStatusCommandHelp() { open_edi::util::message->info("set_analysis_view_status:\n"); open_edi::util::message->info( " -active true|false\n"); open_edi::util::message->info( " -setup true|false\n"); open_edi::util::message->info( " -hold true|false\n"); open_edi::util::message->info( " -max_tran true|false\n"); open_edi::util::message->info( " -max_cap true|false\n"); open_edi::util::message->info( " -min_cap true|false\n"); open_edi::util::message->info( " -leakage_power true|false\n"); open_edi::util::message->info( " -dynamic_power true|false\n"); open_edi::util::message->info( " -cell_em true|false\n"); open_edi::util::message->info( " -signal_em true|false\n"); open_edi::util::message->info(" -view view_name\n"); open_edi::util::message->info(" -help\n"); } int setAnalysisViewStatusCommand(ClientData cld, Tcl_Interp *itp, int argc, const char *argv[]) { auto getBool = [](const char *optionName, const char *value, bool *retValue) { if (!strcmp(value, "true")) { *retValue = true; return true; } else if (!strcmp(value, "false")) { *retValue = false; return true; } else { open_edi::util::message->issueMsg( "TIMINGLIB", 12, open_edi::util::kError, value, optionName); return false; } }; if (argc == 2 && !strcmp(argv[1], "-help")) { printSetAnalysisViewStatusCommandHelp(); return TCL_OK; } if (argc == 23) { SetAnalysisViewStatusArgs args; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-active")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.active))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-setup")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.setup))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-hold")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.hold))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-max_tran")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.max_tran))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-max_cap")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.max_cap))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-min_cap")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.min_cap))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-leakage_power")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.leakage_power))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-dynamic_power")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.dynamic_power))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-cell_em")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.cell_em))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-signal_em")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } if (!getBool(argv[i], argv[i + 1], &(args.signal_em))) return TCL_ERROR; ++i; } else if (!strcmp(argv[i], "-view")) { if ((i + 1) >= argc) { open_edi::util::message->issueMsg("TIMINGLIB", 7, kError, argv[i]); return TCL_ERROR; } ++i; args.view_name = argv[i]; } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } } Timing *timing_lib = getTimingLib(); if (timing_lib == nullptr) { open_edi::util::message->issueMsg( "TIMINGLIB", 6, open_edi::util::kError, "top container", "set anlysis view status"); return TCL_ERROR; } // find AnalysisView by view name AnalysisView *view = timing_lib->getAnalysisView(args.view_name); if (view == nullptr) { open_edi::util::message->issueMsg("TIMINGLIB", 11, open_edi::util::kError, "view", args.view_name.c_str()); return TCL_ERROR; } view->setActive(args.active); view->setSetup(args.setup); view->setHold(args.hold); view->setMaxTran(args.max_tran); view->setMaxCap(args.max_cap); view->setMinCap(args.min_cap); view->setLeakagePower(args.leakage_power); view->setDynamicPower(args.dynamic_power); view->setCellEm(args.cell_em); view->setSignalEm(args.signal_em); if (args.active && args.setup) { timing_lib->addActiveSetupView(view->getId()); } if (args.active && args.hold) { timing_lib->addActiveHoldView(view->getId()); } open_edi::util::message->info("Setting view %s status successfully.\n", args.view_name.c_str()); return TCL_OK; } else { open_edi::util::message->issueMsg("TIMINGLIB", 16, open_edi::util::kError); return TCL_ERROR; } return TCL_OK; } } // namespace db } // namespace open_edi
39.208459
80
0.465043
[ "object", "vector" ]
3c431cd55af6e2b65a3ffda947329ec8688884af
15,235
cpp
C++
src/drivers/ajax.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
33
2015-08-10T11:13:47.000Z
2021-08-30T10:00:46.000Z
src/drivers/ajax.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
13
2015-08-25T03:53:08.000Z
2022-03-30T18:02:35.000Z
src/drivers/ajax.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
40
2015-08-25T05:09:21.000Z
2022-02-08T05:02:30.000Z
#include "../machine/ajax.cpp" #include "../vidhrdw/ajax.cpp" /*************************************************************************** "AJAX/Typhoon" (Konami GX770) Driver by: Manuel Abadia <manu@teleline.es> TO DO: - Find the CPU core bug, that makes the 052001 to read from 0x0000 ***************************************************************************/ #include "driver.h" #include "vidhrdw/konamiic.h" extern unsigned char *ajax_sharedram; static WRITE_HANDLER( k007232_extvol_w ); static WRITE_HANDLER( sound_bank_w ); /* from machine/ajax.c */ WRITE_HANDLER( ajax_bankswitch_2_w ); READ_HANDLER( ajax_sharedram_r ); WRITE_HANDLER( ajax_sharedram_w ); READ_HANDLER( ajax_ls138_f10_r ); WRITE_HANDLER( ajax_ls138_f10_w ); void ajax_init_machine( void ); int ajax_interrupt( void ); /* from vidhrdw/ajax.c */ int ajax_vh_start( void ); void ajax_vh_stop( void ); void ajax_vh_screenrefresh( struct osd_bitmap *bitmap, int fullrefresh ); /****************************************************************************/ static struct MemoryReadAddress ajax_readmem[] = { { 0x0000, 0x01c0, ajax_ls138_f10_r }, /* inputs + DIPSW */ { 0x0800, 0x0807, K051937_r }, /* sprite control registers */ { 0x0c00, 0x0fff, K051960_r }, /* sprite RAM 2128SL at J7 */ { 0x1000, 0x1fff, MRA_RAM }, /* palette */ { 0x2000, 0x3fff, ajax_sharedram_r }, /* shared RAM with the 6809 */ { 0x4000, 0x5fff, MRA_RAM }, /* RAM 6264L at K10*/ { 0x6000, 0x7fff, MRA_BANK2 }, /* banked ROM */ { 0x8000, 0xffff, MRA_ROM }, /* ROM N11 */ { -1 } }; static struct MemoryWriteAddress ajax_writemem[] = { { 0x0000, 0x01c0, ajax_ls138_f10_w }, /* bankswitch + sound command + FIRQ command */ { 0x0800, 0x0807, K051937_w }, /* sprite control registers */ { 0x0c00, 0x0fff, K051960_w }, /* sprite RAM 2128SL at J7 */ { 0x1000, 0x1fff, paletteram_xBBBBBGGGGGRRRRR_swap_w, &paletteram },/* palette */ { 0x2000, 0x3fff, ajax_sharedram_w }, /* shared RAM with the 6809 */ { 0x4000, 0x5fff, MWA_RAM }, /* RAM 6264L at K10 */ { 0x6000, 0x7fff, MWA_ROM }, /* banked ROM */ { 0x8000, 0xffff, MWA_ROM }, /* ROM N11 */ { -1 } }; static struct MemoryReadAddress ajax_readmem_2[] = { { 0x0000, 0x07ff, K051316_0_r }, /* 051316 zoom/rotation layer */ { 0x1000, 0x17ff, K051316_rom_0_r }, /* 051316 (ROM test) */ { 0x2000, 0x3fff, ajax_sharedram_r }, /* shared RAM with the 052001 */ { 0x4000, 0x7fff, K052109_r }, /* video RAM + color RAM + video registers */ { 0x8000, 0x9fff, MRA_BANK1 }, /* banked ROM */ { 0xa000, 0xffff, MRA_ROM }, /* ROM I16 */ { -1 } }; static struct MemoryWriteAddress ajax_writemem_2[] = { { 0x0000, 0x07ff, K051316_0_w }, /* 051316 zoom/rotation layer */ { 0x0800, 0x080f, K051316_ctrl_0_w }, /* 051316 control registers */ { 0x1800, 0x1800, ajax_bankswitch_2_w }, /* bankswitch control */ { 0x2000, 0x3fff, ajax_sharedram_w, &ajax_sharedram },/* shared RAM with the 052001 */ { 0x4000, 0x7fff, K052109_w }, /* video RAM + color RAM + video registers */ { 0x8000, 0x9fff, MWA_ROM }, /* banked ROM */ { 0xa000, 0xffff, MWA_ROM }, /* ROM I16 */ { -1 } }; static struct MemoryReadAddress ajax_readmem_sound[] = { { 0x0000, 0x7fff, MRA_ROM }, /* ROM F6 */ { 0x8000, 0x87ff, MRA_RAM }, /* RAM 2128SL at D16 */ { 0xa000, 0xa00d, K007232_read_port_0_r }, /* 007232 registers (chip 1) */ { 0xb000, 0xb00d, K007232_read_port_1_r }, /* 007232 registers (chip 2) */ { 0xc001, 0xc001, YM2151_status_port_0_r }, /* YM2151 */ { 0xe000, 0xe000, soundlatch_r }, /* soundlatch_r */ { -1 } }; static struct MemoryWriteAddress ajax_writemem_sound[] = { { 0x0000, 0x7fff, MWA_ROM }, /* ROM F6 */ { 0x8000, 0x87ff, MWA_RAM }, /* RAM 2128SL at D16 */ { 0x9000, 0x9000, sound_bank_w }, /* 007232 bankswitch */ { 0xa000, 0xa00d, K007232_write_port_0_w }, /* 007232 registers (chip 1) */ { 0xb000, 0xb00d, K007232_write_port_1_w }, /* 007232 registers (chip 2) */ { 0xb80c, 0xb80c, k007232_extvol_w }, /* extra volume, goes to the 007232 w/ A11 */ /* selecting a different latch for the external port */ { 0xc000, 0xc000, YM2151_register_port_0_w }, /* YM2151 */ { 0xc001, 0xc001, YM2151_data_port_0_w }, /* YM2151 */ { -1 } }; INPUT_PORTS_START( ajax ) PORT_START /* DSW #1 */ PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x02, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x09, DEF_STR( 1C_7C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x50, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x40, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x30, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x70, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x60, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0xa0, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x90, DEF_STR( 1C_7C ) ) // PORT_DIPSETTING( 0x00, "Coin Slot 2 Invalidity" ) PORT_START /* DSW #2 */ PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x03, "2" ) PORT_DIPSETTING( 0x02, "3" ) PORT_DIPSETTING( 0x01, "5" ) PORT_DIPSETTING( 0x00, "7" ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x18, 0x10, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x18, "30000 150000" ) PORT_DIPSETTING( 0x10, "50000 200000" ) PORT_DIPSETTING( 0x08, "30000" ) PORT_DIPSETTING( 0x00, "50000" ) PORT_DIPNAME( 0x60, 0x40, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x60, "Easy" ) PORT_DIPSETTING( 0x40, "Normal" ) PORT_DIPSETTING( 0x20, "Difficult" ) PORT_DIPSETTING( 0x00, "Very difficult" ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START /* DSW #3 */ PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, "Upright Controls" ) PORT_DIPSETTING( 0x02, "Single" ) PORT_DIPSETTING( 0x00, "Dual" ) PORT_SERVICE( 0x04, IP_ACTIVE_LOW ) PORT_DIPNAME( 0x08, 0x08, "Control in 3D Stages" ) PORT_DIPSETTING( 0x08, "Normal" ) PORT_DIPSETTING( 0x00, "Inverted" ) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START /* COINSW & START */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) /* service */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START /* PLAYER 1 INPUTS */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER1 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START /* PLAYER 2 INPUTS */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END static struct YM2151interface ym2151_interface = { 1, 3579545, /* 3.58 MHz */ { YM3012_VOL(100,MIXER_PAN_LEFT,100,MIXER_PAN_RIGHT) }, { 0 }, }; /* sound_bank_w: Handled by the LS273 Octal +ve edge trigger D-type Flip-flop with Reset at B11: Bit Description --- ----------- 7 CONT1 (???) \ 6 CONT2 (???) / One or both bits are set to 1 when you kill a enemy 5 \ 3 / 4MBANKH 4 \ 2 / 4MBANKL 1 \ 0 / 2MBANK */ static WRITE_HANDLER( sound_bank_w ) { unsigned char *RAM; int bank_A, bank_B; /* banks # for the 007232 (chip 1) */ RAM = memory_region(REGION_SOUND1); bank_A = 0x20000 * ((data >> 1) & 0x01); bank_B = 0x20000 * ((data >> 0) & 0x01); K007232_bankswitch(0,RAM + bank_A,RAM + bank_B); /* banks # for the 007232 (chip 2) */ RAM = memory_region(REGION_SOUND2); bank_A = 0x20000 * ((data >> 4) & 0x03); bank_B = 0x20000 * ((data >> 2) & 0x03); K007232_bankswitch(1,RAM + bank_A,RAM + bank_B); } static void volume_callback0(int v) { K007232_set_volume(0,0,(v >> 4) * 0x11,0); K007232_set_volume(0,1,0,(v & 0x0f) * 0x11); } static WRITE_HANDLER( k007232_extvol_w ) { /* channel A volume (mono) */ K007232_set_volume(1,0,(data & 0x0f) * 0x11/2,(data & 0x0f) * 0x11/2); } static void volume_callback1(int v) { /* channel B volume/pan */ K007232_set_volume(1,1,(v & 0x0f) * 0x11/2,(v >> 4) * 0x11/2); } static struct K007232_interface k007232_interface = { 2, /* number of chips */ { REGION_SOUND1, REGION_SOUND2 }, /* memory regions */ { K007232_VOL(20,MIXER_PAN_CENTER,20,MIXER_PAN_CENTER), K007232_VOL(50,MIXER_PAN_LEFT,50,MIXER_PAN_RIGHT) },/* volume */ { volume_callback0, volume_callback1 } /* external port callback */ }; static struct MachineDriver machine_driver_ajax = { { { CPU_KONAMI, /* Konami Custom 052001 */ 3000000, /* 12/4 MHz*/ ajax_readmem,ajax_writemem,0,0, ajax_interrupt,1 /* IRQs triggered by the 051960 */ }, { CPU_M6809, /* 6809E */ 3000000, /* ? */ ajax_readmem_2, ajax_writemem_2,0,0, ignore_interrupt,1 /* FIRQs triggered by the 052001 */ }, { CPU_Z80, /* Z80A */ 3579545, /* 3.58 MHz */ ajax_readmem_sound, ajax_writemem_sound,0,0, ignore_interrupt,0 /* IRQs triggered by the 052001 */ } }, 60, DEFAULT_60HZ_VBLANK_DURATION, 10, ajax_init_machine, /* video hardware */ 64*8, 32*8, { 14*8, (64-14)*8-1, 2*8, 30*8-1 }, 0, /* gfx decoded by konamiic.c */ 2048, 2048, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, 0, ajax_vh_start, ajax_vh_stop, ajax_vh_screenrefresh, /* sound hardware */ SOUND_SUPPORTS_STEREO,0,0,0, { { SOUND_YM2151, &ym2151_interface }, { SOUND_K007232, &k007232_interface } } }; ROM_START( ajax ) ROM_REGION( 0x28000, REGION_CPU1 ) /* 052001 code */ ROM_LOAD( "m01.n11", 0x10000, 0x08000, 0x4a64e53a ) /* banked ROM */ ROM_CONTINUE( 0x08000, 0x08000 ) /* fixed ROM */ ROM_LOAD( "l02.n12", 0x18000, 0x10000, 0xad7d592b ) /* banked ROM */ ROM_REGION( 0x22000, REGION_CPU2 ) /* 64k + 72k for banked ROMs */ ROM_LOAD( "l05.i16", 0x20000, 0x02000, 0xed64fbb2 ) /* banked ROM */ ROM_CONTINUE( 0x0a000, 0x06000 ) /* fixed ROM */ ROM_LOAD( "f04.g16", 0x10000, 0x10000, 0xe0e4ec9c ) /* banked ROM */ ROM_REGION( 0x10000, REGION_CPU3 ) /* 64k for the SOUND CPU */ ROM_LOAD( "h03.f16", 0x00000, 0x08000, 0x2ffd2afc ) ROM_REGION( 0x080000, REGION_GFX1 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c13", 0x000000, 0x040000, 0xb859ca4e ) /* characters (N22) */ ROM_LOAD( "770c12", 0x040000, 0x040000, 0x50d14b72 ) /* characters (K22) */ ROM_REGION( 0x100000, REGION_GFX2 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c09", 0x000000, 0x080000, 0x1ab4a7ff ) /* sprites (N4) */ ROM_LOAD( "770c08", 0x080000, 0x080000, 0xa8e80586 ) /* sprites (K4) */ ROM_REGION( 0x080000, REGION_GFX3 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c06", 0x000000, 0x040000, 0xd0c592ee ) /* zoom/rotate (F4) */ ROM_LOAD( "770c07", 0x040000, 0x040000, 0x0b399fb1 ) /* zoom/rotate (H4) */ ROM_REGION( 0x0200, REGION_PROMS ) ROM_LOAD( "63s241.j11", 0x0000, 0x0200, 0x9bdd719f ) /* priority encoder (not used) */ ROM_REGION( 0x040000, REGION_SOUND1 ) /* 007232 data (chip 1) */ ROM_LOAD( "770c10", 0x000000, 0x040000, 0x7fac825f ) ROM_REGION( 0x080000, REGION_SOUND2 ) /* 007232 data (chip 2) */ ROM_LOAD( "770c11", 0x000000, 0x080000, 0x299a615a ) ROM_END ROM_START( ajaxj ) ROM_REGION( 0x28000, REGION_CPU1 ) /* 052001 code */ ROM_LOAD( "770l01.bin", 0x10000, 0x08000, 0x7cea5274 ) /* banked ROM */ ROM_CONTINUE( 0x08000, 0x08000 ) /* fixed ROM */ ROM_LOAD( "l02.n12", 0x18000, 0x10000, 0xad7d592b ) /* banked ROM */ ROM_REGION( 0x22000, REGION_CPU2 ) /* 64k + 72k for banked ROMs */ ROM_LOAD( "l05.i16", 0x20000, 0x02000, 0xed64fbb2 ) /* banked ROM */ ROM_CONTINUE( 0x0a000, 0x06000 ) /* fixed ROM */ ROM_LOAD( "f04.g16", 0x10000, 0x10000, 0xe0e4ec9c ) /* banked ROM */ ROM_REGION( 0x10000, REGION_CPU3 ) /* 64k for the SOUND CPU */ ROM_LOAD( "770f03.bin", 0x00000, 0x08000, 0x3fe914fd ) ROM_REGION( 0x080000, REGION_GFX1 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c13", 0x000000, 0x040000, 0xb859ca4e ) /* characters (N22) */ ROM_LOAD( "770c12", 0x040000, 0x040000, 0x50d14b72 ) /* characters (K22) */ ROM_REGION( 0x100000, REGION_GFX2 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c09", 0x000000, 0x080000, 0x1ab4a7ff ) /* sprites (N4) */ ROM_LOAD( "770c08", 0x080000, 0x080000, 0xa8e80586 ) /* sprites (K4) */ ROM_REGION( 0x080000, REGION_GFX3 ) /* graphics (addressable by the main CPU) */ ROM_LOAD( "770c06", 0x000000, 0x040000, 0xd0c592ee ) /* zoom/rotate (F4) */ ROM_LOAD( "770c07", 0x040000, 0x040000, 0x0b399fb1 ) /* zoom/rotate (H4) */ ROM_REGION( 0x0200, REGION_PROMS ) ROM_LOAD( "63s241.j11", 0x0000, 0x0200, 0x9bdd719f ) /* priority encoder (not used) */ ROM_REGION( 0x040000, REGION_SOUND1 ) /* 007232 data (chip 1) */ ROM_LOAD( "770c10", 0x000000, 0x040000, 0x7fac825f ) ROM_REGION( 0x080000, REGION_SOUND2 ) /* 007232 data (chip 2) */ ROM_LOAD( "770c11", 0x000000, 0x080000, 0x299a615a ) ROM_END static void init_ajax(void) { konami_rom_deinterleave_2(REGION_GFX1); konami_rom_deinterleave_2(REGION_GFX2); } GAME( 1987, ajax, 0, ajax, ajax, ajax, ROT90, "Konami", "Ajax" ) GAME( 1987, ajaxj, ajax, ajax, ajax, ajax, ROT90, "Konami", "Ajax (Japan)" )
35.679157
88
0.67509
[ "3d" ]
3c46986b5c8f8717143a31144672bbd07599a8f2
4,188
hpp
C++
include/libpmemobj++/make_persistent_array_atomic.hpp
avdosev/libpmemobj-cpp
45998ede20c0fa8cb5d3c4735e95abdff9d94706
[ "BSD-3-Clause" ]
null
null
null
include/libpmemobj++/make_persistent_array_atomic.hpp
avdosev/libpmemobj-cpp
45998ede20c0fa8cb5d3c4735e95abdff9d94706
[ "BSD-3-Clause" ]
7
2018-12-11T22:16:42.000Z
2019-02-07T16:28:51.000Z
include/libpmemobj++/make_persistent_array_atomic.hpp
szyrom/libpmemobj-cpp
78f10eb6ae76f33043b05cd5d15f1c1594dab421
[ "BSD-3-Clause" ]
2
2019-12-05T08:30:28.000Z
2019-12-06T05:55:47.000Z
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /** * @file * Atomic persistent_ptr allocation functions for arrays. The typical usage * examples would be: * @snippet doc_snippets/make_persistent.cpp make_array_atomic_example */ #ifndef LIBPMEMOBJ_CPP_MAKE_PERSISTENT_ARRAY_ATOMIC_HPP #define LIBPMEMOBJ_CPP_MAKE_PERSISTENT_ARRAY_ATOMIC_HPP #include <libpmemobj++/allocation_flag.hpp> #include <libpmemobj++/detail/array_traits.hpp> #include <libpmemobj++/detail/check_persistent_ptr_array.hpp> #include <libpmemobj++/detail/common.hpp> #include <libpmemobj++/detail/make_atomic_impl.hpp> #include <libpmemobj++/detail/variadic.hpp> #include <libpmemobj++/pexceptions.hpp> #include <libpmemobj/atomic_base.h> namespace pmem { namespace obj { /** * Atomically allocate an array of objects. * * This function can be used to atomically allocate an array of objects. * Cannot be used for simple objects. Do *NOT* use this inside transactions, as * it might lead to undefined behavior in the presence of transaction aborts. * * @param[in,out] pool the pool from which the object will be allocated. * @param[in,out] ptr the persistent pointer to which the allocation * will take place. * @param[in] N the number of array elements. * @param[in] flag affects behaviour of allocator * * @throw std::bad_alloc on allocation failure. */ template <typename T> void make_persistent_atomic( pool_base &pool, typename detail::pp_if_array<T>::type &ptr, std::size_t N, allocation_flag_atomic flag = allocation_flag_atomic::none()) { typedef typename detail::pp_array_type<T>::type I; auto ret = pmemobj_xalloc(pool.handle(), ptr.raw_ptr(), sizeof(I) * N, detail::type_num<I>(), flag.value, &detail::array_constructor<I>, static_cast<void *>(&N)); if (ret != 0) throw std::bad_alloc(); } /** * Atomically allocate an array of objects. * * This function can be used to atomically allocate an array of objects. * Cannot be used for simple objects. Do *NOT* use this inside transactions, as * it might lead to undefined behavior in the presence of transaction aborts. * * @param[in,out] pool the pool from which the object will be allocated. * @param[in,out] ptr the persistent pointer to which the allocation * will take place. * @param[in] flag affects behaviour of allocator * * @throw std::bad_alloc on allocation failure. */ template <typename T> void make_persistent_atomic( pool_base &pool, typename detail::pp_if_size_array<T>::type &ptr, allocation_flag_atomic flag = allocation_flag_atomic::none()) { typedef typename detail::pp_array_type<T>::type I; std::size_t N = detail::pp_array_elems<T>::elems; auto ret = pmemobj_xalloc(pool.handle(), ptr.raw_ptr(), sizeof(I) * N, detail::type_num<I>(), flag.value, &detail::array_constructor<I>, static_cast<void *>(&N)); if (ret != 0) throw std::bad_alloc(); } /** * Atomically deallocate an array of objects. * * There is no way to atomically destroy an object. Any object specific * cleanup must be performed elsewhere. Do *NOT* use this inside transactions, * as it might lead to undefined behavior in the presence of transaction aborts. * * param[in,out] ptr the persistent_ptr whose pointee is to be * deallocated. */ template <typename T> void delete_persistent_atomic(typename detail::pp_if_array<T>::type &ptr, std::size_t) { if (ptr == nullptr) return; /* we CAN'T call destructor */ pmemobj_free(ptr.raw_ptr()); } /** * Atomically deallocate an array of objects. * * There is no way to atomically destroy an object. Any object specific * cleanup must be performed elsewhere. Do *NOT* use this inside transactions, * as it might lead to undefined behavior in the presence of transaction aborts. * * param[in,out] ptr the persistent_ptr whose pointee is to be deallocated. */ template <typename T> void delete_persistent_atomic(typename detail::pp_if_size_array<T>::type &ptr) { if (ptr == nullptr) return; /* we CAN'T call destructor */ pmemobj_free(ptr.raw_ptr()); } } /* namespace obj */ } /* namespace pmem */ #endif /* LIBPMEMOBJ_CPP_MAKE_PERSISTENT_ARRAY_ATOMIC_HPP */
29.702128
80
0.735912
[ "object" ]
3c4eceddeb6443013dd6c0cda18b1c2f22a4c417
2,419
cpp
C++
dbms/src/Columns/Collator.cpp
izebit/ClickHouse
839acc948ec623fc1cb2dcf23dba86d8a81f992e
[ "Apache-2.0" ]
null
null
null
dbms/src/Columns/Collator.cpp
izebit/ClickHouse
839acc948ec623fc1cb2dcf23dba86d8a81f992e
[ "Apache-2.0" ]
null
null
null
dbms/src/Columns/Collator.cpp
izebit/ClickHouse
839acc948ec623fc1cb2dcf23dba86d8a81f992e
[ "Apache-2.0" ]
null
null
null
#include <Columns/Collator.h> #include "config_core.h" #if USE_ICU #include <unicode/ucol.h> #else #ifdef __clang__ #pragma clang diagnostic ignored "-Wunused-private-field" #endif #pragma clang diagnostic ignored "-Wmissing-noreturn" #endif #include <Common/Exception.h> #include <IO/WriteHelpers.h> #include <Poco/String.h> namespace DB { namespace ErrorCodes { extern const int UNSUPPORTED_COLLATION_LOCALE; extern const int COLLATION_COMPARISON_FAILED; extern const int SUPPORT_IS_DISABLED; } } Collator::Collator(const std::string & locale_) : locale(Poco::toLower(locale_)) { #if USE_ICU UErrorCode status = U_ZERO_ERROR; collator = ucol_open(locale.c_str(), &status); if (status != U_ZERO_ERROR) { ucol_close(collator); throw DB::Exception("Unsupported collation locale: " + locale, DB::ErrorCodes::UNSUPPORTED_COLLATION_LOCALE); } #else throw DB::Exception("Collations support is disabled, because ClickHouse was built without ICU library", DB::ErrorCodes::SUPPORT_IS_DISABLED); #endif } Collator::~Collator() { #if USE_ICU ucol_close(collator); #endif } int Collator::compare(const char * str1, size_t length1, const char * str2, size_t length2) const { #if USE_ICU UCharIterator iter1, iter2; uiter_setUTF8(&iter1, str1, length1); uiter_setUTF8(&iter2, str2, length2); UErrorCode status = U_ZERO_ERROR; UCollationResult compare_result = ucol_strcollIter(collator, &iter1, &iter2, &status); if (status != U_ZERO_ERROR) throw DB::Exception("ICU collation comparison failed with error code: " + DB::toString<int>(status), DB::ErrorCodes::COLLATION_COMPARISON_FAILED); /** Values of enum UCollationResult are equals to what exactly we need: * UCOL_EQUAL = 0 * UCOL_GREATER = 1 * UCOL_LESS = -1 */ return compare_result; #else (void)str1; (void)length1; (void)str2; (void)length2; return 0; #endif } const std::string & Collator::getLocale() const { return locale; } std::vector<std::string> Collator::getAvailableCollations() { std::vector<std::string> result; #if USE_ICU size_t available_locales_count = ucol_countAvailable(); for (size_t i = 0; i < available_locales_count; ++i) result.push_back(ucol_getAvailable(i)); #endif return result; }
24.938144
145
0.683754
[ "vector" ]
3c529c93dd5a766e0c01edcb820cee4ec2c12105
1,368
cpp
C++
Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
2
2022-01-13T04:29:38.000Z
2022-03-12T01:05:31.000Z
Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <gtest/gtest.h> #include <QPushButton> #include <QAction> #include <QtTest> #include <Tests/UI/UIFixture.h> #include <EMotionFX/CommandSystem/Source/CommandManager.h> #include <EMotionFX/Source/Actor.h> #include <EMotionFX/Source/AutoRegisteredActor.h> namespace EMotionFX { TEST_F(UIFixture, CanAddActor) { /* Test Case: C14459474 Can Add Actor Imports an Actor to ensure that importing an actor is poosible. */ RecordProperty("test_case_id", "C14459474"); // Ensure that the number of actors loaded is 0 ASSERT_EQ(GetActorManager().GetNumActors(), 0); // Load an Actor const char* actorCmd{ "ImportActor -filename @devroot@/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor" }; { AZStd::string result; EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommand(actorCmd, result)) << result.c_str(); } // Ensure the Actor is correct ASSERT_TRUE(GetActorManager().FindActorByName("rinactor")); EXPECT_EQ(GetActorManager().GetNumActors(), 1); } } // namespace EMotionFX
29.106383
117
0.673246
[ "3d" ]
3c5ca68cf14a1ddb05a8c5df7a51170e2530862e
5,716
cpp
C++
src/daemon-mgr.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
src/daemon-mgr.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
src/daemon-mgr.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
#include <glib-object.h> #include <cstdio> #include <cstdlib> #include <QTimer> #include <QStringList> #include <QString> #include <QDebug> #include <QDir> #include <QCoreApplication> #include "utils/utils.h" #include "utils/process.h" #include "configurator.h" #include "seafile-applet.h" #include "rpc/rpc-client.h" #include "daemon-mgr.h" namespace { const int kConnDaemonIntervalMilli = 1000; const int kMaxDaemonReadyCheck = 15; const int kDaemonRestartInternvalMSecs = 2000; const int kDaemonRestartMaxRetries = 10; #if defined(Q_OS_WIN32) const char *kSeafileDaemonExecutable = "seaf-daemon.exe"; #else const char *kSeafileDaemonExecutable = "seaf-daemon"; #endif typedef enum { DAEMON_INIT = 0, DAEMON_STARTING, DAEMON_CONNECTING, DAEMON_CONNECTED, DAEMON_DEAD, SEAFILE_EXITING, MAX_STATE, } DaemonState; const char *DaemonStateStrs[] = { "init", "starting", "connecting", "connected", "dead", "seafile_exiting" }; const char *stateToStr(int state) { if (state < 0 || state >= MAX_STATE) { return ""; } return DaemonStateStrs[state]; } bool seafileRpcReady() { SeafileRpcClient rpc; if (!rpc.tryConnectDaemon()) { return false; } QString str; return rpc.seafileGetConfig("use_proxy", &str) == 0; } } // namespace DaemonManager::DaemonManager() : seaf_daemon_(nullptr) { current_state_ = DAEMON_INIT; first_start_ = true; restart_retried_ = 0; conn_daemon_timer_ = new QTimer(this); connect(conn_daemon_timer_, SIGNAL(timeout()), this, SLOT(checkDaemonReady())); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(systemShutDown())); } DaemonManager::~DaemonManager() { stopDaemon(); } void DaemonManager::restartSeafileDaemon() { if (current_state_ == SEAFILE_EXITING) { return; } qWarning("Trying to restart seafile daemon"); startSeafileDaemon(); } void DaemonManager::startSeafileDaemon() { seaf_daemon_ = new QProcess(this); connect(seaf_daemon_, SIGNAL(started()), this, SLOT(onDaemonStarted())); connect(seaf_daemon_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(onDaemonFinished(int, QProcess::ExitStatus))); const QString config_dir = seafApplet->configurator()->ccnetDir(); const QString seafile_dir = seafApplet->configurator()->seafileDir(); const QString worktree_dir = seafApplet->configurator()->worktreeDir(); QStringList args; args << "-c" << config_dir << "-d" << seafile_dir << "-w" << worktree_dir; seaf_daemon_->start(RESOURCE_PATH(kSeafileDaemonExecutable), args); qWarning() << "starting seaf-daemon: " << args; transitionState(DAEMON_STARTING); } void DaemonManager::systemShutDown() { transitionState(SEAFILE_EXITING); } void DaemonManager::onDaemonStarted() { qDebug("seafile daemon is now running, checking if the service is ready"); conn_daemon_timer_->start(kConnDaemonIntervalMilli); transitionState(DAEMON_CONNECTING); } void DaemonManager::checkDaemonReady() { QString str; // Because some settings need to be loaded from seaf daemon, we only emit // the "daemonStarted" signal after we're sure the daemon rpc is ready. if (seafileRpcReady()) { qDebug("seaf daemon is ready"); conn_daemon_timer_->stop(); transitionState(DAEMON_CONNECTED); restart_retried_ = 0; if (first_start_) { first_start_ = false; emit daemonStarted(); } else { emit daemonRestarted(); } return; } qDebug("seaf daemon is not ready"); static int maxcheck = 0; if (++maxcheck > kMaxDaemonReadyCheck) { qWarning("seafile rpc is not ready after %d retry, abort", maxcheck); seafApplet->errorAndExit(tr("%1 client failed to initialize").arg(getBrand())); } } void DaemonManager::onDaemonFinished(int exit_code, QProcess::ExitStatus exit_status) { qWarning("Seafile daemon process %s with code %d ", (current_state_ != SEAFILE_EXITING && exit_status == QProcess::CrashExit) ? "crashed" : "exited normally", exit_code); if (current_state_ == DAEMON_CONNECTING) { conn_daemon_timer_->stop(); scheduleRestartDaemon(); } else if (current_state_ != SEAFILE_EXITING) { transitionState(DAEMON_DEAD); emit daemonDead(); scheduleRestartDaemon(); } } void DaemonManager::stopDaemon() { conn_daemon_timer_->stop(); if (seaf_daemon_) { qWarning("[Daemon Mgr] stopping seafile daemon"); // TODO: add an "exit" rpc in seaf-daemon to exit gracefully? seaf_daemon_->kill(); seaf_daemon_->waitForFinished(50); seaf_daemon_ = nullptr; } } void DaemonManager::scheduleRestartDaemon() { // When the daemon crashes when we first start seafile, we should // not retry too many times, because during the retry nothing // would be shown to the user and would confuse him. int max_retry = 2; if (seafApplet->rpcClient() && seafApplet->rpcClient()->isConnected()) { max_retry = kDaemonRestartMaxRetries; } if (++restart_retried_ >= max_retry) { qWarning("reaching max tries of restarting seafile daemon, aborting"); seafApplet->errorAndExit(tr("%1 exited unexpectedly").arg(getBrand())); return; } QTimer::singleShot(kDaemonRestartInternvalMSecs, this, SLOT(restartSeafileDaemon())); } void DaemonManager::transitionState(int new_state) { qDebug("daemon mgr: %s => %s", stateToStr(current_state_), stateToStr(new_state)); current_state_ = new_state; }
26.962264
89
0.670049
[ "object" ]
3c699046130439ad867ccec53c35c907228dc8a4
3,786
cc
C++
third_party/blink/renderer/core/frame/overlay_interstitial_ad_detector.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/frame/overlay_interstitial_ad_detector.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/frame/overlay_interstitial_ad_detector.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/frame/overlay_interstitial_ad_detector.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html/html_frame_owner_element.h" #include "third_party/blink/renderer/core/html/html_image_element.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/layout/layout_object_inlines.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/scroll/scrollable_area.h" namespace blink { namespace { constexpr base::TimeDelta kFireInterval = base::TimeDelta::FromSeconds(1); bool IsIframeAd(Element* element) { HTMLFrameOwnerElement* frame_owner_element = DynamicTo<HTMLFrameOwnerElement>(element); if (!frame_owner_element) return false; Frame* frame = frame_owner_element->ContentFrame(); return frame && frame->IsAdSubframe(); } bool IsImageAd(Element* element) { HTMLImageElement* image_element = DynamicTo<HTMLImageElement>(element); if (!image_element) return false; return image_element->IsAdRelated(); } // An overlay interstitial element shouldn't move with scrolling and should be // able to overlap with other contents. So, either: // 1) one of its container ancestors (including itself) has fixed position. // 2) <body> or <html> has style="overflow:hidden", and among its container // ancestors (including itself), the 2nd to the top (where the top should always // be the <body>) has absolute position. bool IsImmobileAndCanOverlapWithOtherContent(Element* element) { const ComputedStyle* style = nullptr; LayoutView* layout_view = element->GetDocument().GetLayoutView(); LayoutObject* object = element->GetLayoutObject(); DCHECK_NE(object, layout_view); for (; object != layout_view; object = object->Container()) { DCHECK(object); style = object->Style(); } DCHECK(style); // 'style' is now the ComputedStyle for the object whose position depends // on the document. if (style->HasViewportConstrainedPosition() || style->HasStickyConstrainedPosition()) { return true; } if (style->GetPosition() == EPosition::kAbsolute) return !object->StyleRef().ScrollsOverflow(); return false; } bool IsInterstitialAd(Element* element) { return (IsIframeAd(element) || IsImageAd(element)) && IsImmobileAndCanOverlapWithOtherContent(element); } } // namespace void OverlayInterstitialAdDetector::MaybeFireDetection(LocalFrame* main_frame) { DCHECK(main_frame); DCHECK(main_frame->IsMainFrame()); if (done_detection_) return; DCHECK(main_frame->GetDocument()); DCHECK(main_frame->ContentLayoutObject()); base::Time current_time = base::Time::Now(); if (!last_detection_time_.has_value() || current_time - last_detection_time_.value() >= kFireInterval) { IntSize main_frame_size = main_frame->View()->GetScrollableArea()->VisibleContentRect().Size(); HitTestLocation location(DoublePoint(main_frame_size.Width() / 2.0, main_frame_size.Height() / 2.0)); HitTestResult result; main_frame->ContentLayoutObject()->HitTestNoLifecycleUpdate(location, result); Element* element = result.InnerElement(); if (element && IsInterstitialAd(element)) { UseCounter::Count(main_frame->GetDocument(), WebFeature::kOverlayInterstitialAd); done_detection_ = true; } last_detection_time_ = current_time; } } } // namespace blink
34.418182
83
0.720814
[ "object" ]
3c69947aea0322c80d3ebfce7aee82ccb5fdbd2b
3,860
hpp
C++
include/generated/shapes/rectangle_base.hpp
hermet/rive-cpp
d69378d97e7d987930c3764655153bf8ddc65966
[ "MIT" ]
null
null
null
include/generated/shapes/rectangle_base.hpp
hermet/rive-cpp
d69378d97e7d987930c3764655153bf8ddc65966
[ "MIT" ]
null
null
null
include/generated/shapes/rectangle_base.hpp
hermet/rive-cpp
d69378d97e7d987930c3764655153bf8ddc65966
[ "MIT" ]
null
null
null
#ifndef _RIVE_RECTANGLE_BASE_HPP_ #define _RIVE_RECTANGLE_BASE_HPP_ #include "core/field_types/core_bool_type.hpp" #include "core/field_types/core_double_type.hpp" #include "shapes/parametric_path.hpp" namespace rive { class RectangleBase : public ParametricPath { protected: typedef ParametricPath Super; public: static const uint16_t typeKey = 7; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case RectangleBase::typeKey: case ParametricPathBase::typeKey: case PathBase::typeKey: case NodeBase::typeKey: case TransformComponentBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } static const uint16_t linkCornerRadiusPropertyKey = 164; static const uint16_t cornerRadiusTLPropertyKey = 31; static const uint16_t cornerRadiusTRPropertyKey = 161; static const uint16_t cornerRadiusBLPropertyKey = 162; static const uint16_t cornerRadiusBRPropertyKey = 163; private: bool m_LinkCornerRadius = true; float m_CornerRadiusTL = 0.0f; float m_CornerRadiusTR = 0.0f; float m_CornerRadiusBL = 0.0f; float m_CornerRadiusBR = 0.0f; public: inline bool linkCornerRadius() const { return m_LinkCornerRadius; } void linkCornerRadius(bool value) { if (m_LinkCornerRadius == value) { return; } m_LinkCornerRadius = value; linkCornerRadiusChanged(); } inline float cornerRadiusTL() const { return m_CornerRadiusTL; } void cornerRadiusTL(float value) { if (m_CornerRadiusTL == value) { return; } m_CornerRadiusTL = value; cornerRadiusTLChanged(); } inline float cornerRadiusTR() const { return m_CornerRadiusTR; } void cornerRadiusTR(float value) { if (m_CornerRadiusTR == value) { return; } m_CornerRadiusTR = value; cornerRadiusTRChanged(); } inline float cornerRadiusBL() const { return m_CornerRadiusBL; } void cornerRadiusBL(float value) { if (m_CornerRadiusBL == value) { return; } m_CornerRadiusBL = value; cornerRadiusBLChanged(); } inline float cornerRadiusBR() const { return m_CornerRadiusBR; } void cornerRadiusBR(float value) { if (m_CornerRadiusBR == value) { return; } m_CornerRadiusBR = value; cornerRadiusBRChanged(); } Core* clone() const override; void copy(const RectangleBase& object) { m_LinkCornerRadius = object.m_LinkCornerRadius; m_CornerRadiusTL = object.m_CornerRadiusTL; m_CornerRadiusTR = object.m_CornerRadiusTR; m_CornerRadiusBL = object.m_CornerRadiusBL; m_CornerRadiusBR = object.m_CornerRadiusBR; ParametricPath::copy(object); } bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { switch (propertyKey) { case linkCornerRadiusPropertyKey: m_LinkCornerRadius = CoreBoolType::deserialize(reader); return true; case cornerRadiusTLPropertyKey: m_CornerRadiusTL = CoreDoubleType::deserialize(reader); return true; case cornerRadiusTRPropertyKey: m_CornerRadiusTR = CoreDoubleType::deserialize(reader); return true; case cornerRadiusBLPropertyKey: m_CornerRadiusBL = CoreDoubleType::deserialize(reader); return true; case cornerRadiusBRPropertyKey: m_CornerRadiusBR = CoreDoubleType::deserialize(reader); return true; } return ParametricPath::deserialize(propertyKey, reader); } protected: virtual void linkCornerRadiusChanged() {} virtual void cornerRadiusTLChanged() {} virtual void cornerRadiusTRChanged() {} virtual void cornerRadiusBLChanged() {} virtual void cornerRadiusBRChanged() {} }; } // namespace rive #endif
26.081081
74
0.730829
[ "object" ]
3c6e2aaf3cd87a574914dec273574d43f03e6848
9,508
cpp
C++
3rdparty/rwtools/src/ps2native.cpp
mani3xis/gta-draw-call
852e69b7ef99467f8150d15ae0c1be9545c5b5d0
[ "MIT" ]
15
2017-09-26T18:55:30.000Z
2021-06-30T15:19:19.000Z
3rdparty/rwtools/src/ps2native.cpp
mani3xis/gta-draw-call
852e69b7ef99467f8150d15ae0c1be9545c5b5d0
[ "MIT" ]
null
null
null
3rdparty/rwtools/src/ps2native.cpp
mani3xis/gta-draw-call
852e69b7ef99467f8150d15ae0c1be9545c5b5d0
[ "MIT" ]
null
null
null
#include <cstdio> #include <renderware.h> using namespace std; namespace rw { #define NORMALSCALE (1.0/128.0) #define VERTSCALE1 (1.0/128.0) /* normally used */ #define VERTSCALE2 (1.0/1024.0) /* used by objects with normals */ #define UVSCALE (1.0/4096.0) static uint32 index; void Geometry::readPs2NativeData(istream &rw) { HeaderInfo header; READ_HEADER(CHUNK_STRUCT); /* wrong size */ if (readUInt32(rw) != PLATFORM_PS2) { cerr << "error: native data not in ps2 format\n"; return; } index = 0; vector<uint32> typesRead; numIndices = 0; for (uint32 i = 0; i < splits.size(); i++) { uint32 splitSize = readUInt32(rw); rw.seekg(4, ios::cur); // bool: hasNoSectionAData uint32 numIndices = splits[i].indices.size(); splits[i].indices.clear(); uint32 end = splitSize + rw.tellg(); uint8 chunk8[16]; uint32 *chunk32 = (uint32 *) chunk8; uint32 blockStart = rw.tellg(); bool reachedEnd; bool sectionALast = false; bool sectionBLast = false; bool dataAread = false; while (rw.tellg() < end) { /* sectionA */ reachedEnd = false; while (!reachedEnd && !sectionALast) { rw.read((char *) chunk8, 0x10); switch (chunk8[3]) { case 0x30: { /* read all split data when we find the * first data block and ignore all * other blocks */ if (dataAread) { /* skip dummy data */ rw.seekg(0x10, ios::cur); break; } uint32 oldPos = rw.tellg(); uint32 dataPos = blockStart + chunk32[1]*0x10; rw.seekg(dataPos, ios::beg); readData(numIndices,chunk32[3], i, rw); rw.seekg(oldPos + 0x10, ios::beg); break; } case 0x60: sectionALast = true; /* fall through */ case 0x10: reachedEnd = true; dataAread = true; break; default: break; } } /* sectionB */ reachedEnd = false; while (!reachedEnd && !sectionBLast) { rw.read((char *) chunk8, 0x10); switch (chunk8[3]) { case 0x00: case 0x07: readData(chunk8[14],chunk32[3], i, rw); /* remember what sort of data we read */ typesRead.push_back(chunk32[3]); break; case 0x04: if (chunk8[7] == 0x15) ;//first else if (chunk8[7] == 0x17) ;//not first if ((chunk8[11] == 0x11 && chunk8[15] == 0x11) || (chunk8[11] == 0x11 && chunk8[15] == 0x06)) { // last rw.seekg(end, ios::beg); typesRead.clear(); sectionBLast = true; } else if (chunk8[11] == 0 && chunk8[15] == 0 && faceType == FACETYPE_STRIP) { deleteOverlapping(typesRead, i); typesRead.clear(); // not last } reachedEnd = true; break; default: break; } } } this->numIndices += splits[i].indices.size(); // TODO: night vertex colors int nverts = vertices.size()/3; if(flags & FLAGS_NORMALS) normals.resize(nverts*3); if(flags & FLAGS_PRELIT){ vertexColors.resize(nverts*4); nightColors.resize(nverts*4); } if(flags & FLAGS_TEXTURED || flags & FLAGS_TEXTURED2) for(uint32 i = 0; i < numUVs; i++) texCoords[i].resize(nverts*2); } /* int nverts = vertices.size()/3; // this happens in some objects if(flags & FLAGS_NORMALS && normals.size() == 0) normals.resize(vertices.size()); // never seen this but be careful if(flags & FLAGS_PRELIT && vertexColors.size() == 0) vertexColors.resize(nverts*4); // this also happens if(flags & FLAGS_TEXTURED || flags & FLAGS_TEXTURED2) for(uint32 i = 0; i < numUVs; i++) if(texCoords[i].size() == 0) texCoords[i].resize(nverts*2); */ } void Geometry::readData(uint32 vertexCount, uint32 type, uint32 split, istream &rw) { float32 vertexScale = (flags & FLAGS_PRELIT) ? VERTSCALE1 : VERTSCALE2; uint32 size = 0; type &= 0xFF00FFFF; /* TODO: read greater chunks */ switch (type) { /* Vertices */ case 0x68008000: { size = 3 * sizeof(float32); for (uint32 j = 0; j < vertexCount; j++) { vertices.push_back(readFloat32(rw)); vertices.push_back(readFloat32(rw)); vertices.push_back(readFloat32(rw)); splits[split].indices.push_back(index++); } break; } case 0x6D008000: { size = 4 * sizeof(int16); int16 vertex[4]; for (uint32 j = 0; j < vertexCount; j++) { rw.read((char *) (vertex), size); uint32 flag = vertex[3] & 0xFFFF; vertices.push_back(vertex[0] * vertexScale); vertices.push_back(vertex[1] * vertexScale); vertices.push_back(vertex[2] * vertexScale); if (flag == 0x8000){ splits[split].indices.push_back(index-1); splits[split].indices.push_back(index-1); } splits[split].indices.push_back(index++); } break; /* Texture coordinates */ } case 0x64008001: { size = 2 * sizeof(float32); for (uint32 j = 0; j < vertexCount; j++) { texCoords[0].push_back(readFloat32(rw)); texCoords[0].push_back(readFloat32(rw)); } for (uint32 i = 1; i < numUVs; i++) { for (uint32 j = 0; j < vertexCount; j++) { texCoords[i].push_back(0); texCoords[i].push_back(0); } } break; } case 0x6D008001: { size = 2 * sizeof(int16); int16 texCoord[2]; for (uint32 j = 0; j < vertexCount; j++) { for (uint32 i = 0; i < numUVs; i++) { rw.read((char *) (texCoord), size); texCoords[i].push_back(texCoord[0] * UVSCALE); texCoords[i].push_back(texCoord[1] * UVSCALE); } } size *= numUVs; break; } case 0x65008001: { size = 2 * sizeof(int16); int16 texCoord[2]; for (uint32 j = 0; j < vertexCount; j++) { rw.read((char *) (texCoord), size); texCoords[0].push_back(texCoord[0] * UVSCALE); texCoords[0].push_back(texCoord[1] * UVSCALE); } for (uint32 i = 1; i < numUVs; i++) { for (uint32 j = 0; j < vertexCount; j++) { texCoords[i].push_back(0); texCoords[i].push_back(0); } } break; /* Vertex colors */ } case 0x6D00C002: { size = 8 * sizeof(uint8); for (uint32 j = 0; j < vertexCount; j++) { vertexColors.push_back(readUInt8(rw)); nightColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); nightColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); nightColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); nightColors.push_back(readUInt8(rw)); } break; } case 0x6E00C002: { size = 4 * sizeof(uint8); for (uint32 j = 0; j < vertexCount; j++) { vertexColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); vertexColors.push_back(readUInt8(rw)); } break; /* Normals */ } case 0x6E008002: case 0x6E008003: { size = 4 * sizeof(int8); int8 normal[4]; for (uint32 j = 0; j < vertexCount; j++) { rw.read((char *) (normal), size); normals.push_back(normal[0] * NORMALSCALE); normals.push_back(normal[1] * NORMALSCALE); normals.push_back(normal[2] * NORMALSCALE); } break; } case 0x6A008003: { size = 3 * sizeof(int8); int8 normal[3]; for (uint32 j = 0; j < vertexCount; j++) { rw.read((char *) (normal), size); normals.push_back(normal[0] * NORMALSCALE); normals.push_back(normal[1] * NORMALSCALE); normals.push_back(normal[2] * NORMALSCALE); } break; /* Skin weights and indices */ } case 0x6C008004: case 0x6C008003: case 0x6C008001: { size = 4 * sizeof(float32); float32 weight[4]; uint32 *w = (uint32 *) weight; uint8 indices[4];; for (uint32 j = 0; j < vertexCount; j++) { rw.read((char *) (weight), size); for (uint32 i = 0; i < 4; i++) { vertexBoneWeights.push_back(weight[i]); indices[i] = w[i] >> 2; if (indices[i] != 0) indices[i] -= 1; } vertexBoneIndices.push_back(indices[3] << 24 | indices[2] << 16 | indices[1] << 8 | indices[0]); } break; } default: cout << "unknown data type: " << hex << type; cout << " " << filename << " " << hex << rw.tellg() << endl; break; } /* skip padding */ if (vertexCount*size & 0xF) rw.seekg(0x10 - (vertexCount*size & 0xF), ios::cur); } void Geometry::deleteOverlapping(vector<uint32> &typesRead, uint32 split) { uint32 size; for (uint32 i = 0; i < typesRead.size(); i++) { switch (typesRead[i] & 0xFF00FFFF) { /* Vertices */ case 0x68008000: case 0x6D008000: size = vertices.size(); vertices.resize(size-2*3); size = splits[split].indices.size(); splits[split].indices.resize(size-2); index -= 2; break; /* Texture coordinates */ case 0x64008001: case 0x65008001: // size = texCoords[0].size(); // texCoords[0].resize(size-2*2); // break; case 0x6D008001: for (uint32 j = 0; j < numUVs; j++) { size = texCoords[j].size(); texCoords[j].resize(size-2*2); } break; /* Vertex colors */ case 0x6D00C002: size = nightColors.size(); nightColors.resize(size-2*4); /* fall through */ case 0x6E00C002: size = vertexColors.size(); vertexColors.resize(size-2*4); break; /* Normals */ case 0x6E008002: case 0x6E008003: case 0x6A008003: size = normals.size(); normals.resize(size-2*3); break; /* Skin weights and indices*/ case 0x6C008004: case 0x6C008003: case 0x6C008001: size = vertexBoneWeights.size(); vertexBoneWeights.resize(size-2*4); size = vertexBoneIndices.size(); vertexBoneIndices.resize(size-2); break; default: cout << "unknown data type: "; cout << hex <<typesRead[i] << endl; break; } } } }
26.049315
73
0.606647
[ "geometry", "vector" ]
3c78a053a3e9a997ea9718ea63dda86d18c68162
1,504
hpp
C++
source/backend/cpu/compute/ConvolutionWinograd.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
1
2019-08-09T03:16:49.000Z
2019-08-09T03:16:49.000Z
source/backend/cpu/compute/ConvolutionWinograd.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
1
2021-09-07T09:13:03.000Z
2021-09-07T09:13:03.000Z
source/backend/cpu/compute/ConvolutionWinograd.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
1
2021-01-15T06:28:11.000Z
2021-01-15T06:28:11.000Z
// // ConvolutionWinograd.hpp // MNN // // Created by MNN on 2018/08/20. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef ConvolutionWinograd_hpp #define ConvolutionWinograd_hpp #include "CPUConvolution.hpp" #include "ConvolutionFloatFactory.h" #include "WinogradOptFunction.hpp" namespace MNN { class ConvolutionWinograd : public CPUConvolution { public: ConvolutionWinograd(const Convolution2DCommon *convOp, const Tensor *input, const Tensor *output, Backend *b, const float *originWeight, size_t originWeightSize, const float *bias, size_t biasSize, int unit); virtual ~ConvolutionWinograd(); virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; static bool canUseWinograd(const Convolution2DCommon *convOp); static int bestWinogradUnit(const Convolution2DCommon *convOp, const Tensor *input, const Tensor *output, int threadnumber); private: std::shared_ptr<Tensor> mBias; std::shared_ptr<Tensor> mA; std::shared_ptr<Tensor> mB; std::shared_ptr<Tensor> mWeight; Tensor mTempBuffer; Tensor mTransformMidBuffer; WinogradFunction::TransformFunc mSourceTransform; WinogradFunction::TransformFunc mDestTransform; }; } // namespace MNN #endif /* ConvolutionWinograd_hpp */
34.181818
116
0.719415
[ "vector" ]
3c80bd50e9e9691ec7920e34c754738f5d453081
6,431
cpp
C++
src/TAO/API/crypto/change.cpp
beuschl/LLL-TAO
639b9a3e010db3938095b015da35d3fd845d2666
[ "MIT" ]
null
null
null
src/TAO/API/crypto/change.cpp
beuschl/LLL-TAO
639b9a3e010db3938095b015da35d3fd845d2666
[ "MIT" ]
null
null
null
src/TAO/API/crypto/change.cpp
beuschl/LLL-TAO
639b9a3e010db3938095b015da35d3fd845d2666
[ "MIT" ]
null
null
null
/*__________________________________________________________________________________________ (c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ (c) Copyright The Nexus Developers 2014 - 2019 Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. "ad vocem populi" - To the Voice of the People ____________________________________________________________________________________________*/ #include <LLD/include/global.h> #include <TAO/API/objects/types/objects.h> #include <TAO/API/include/global.h> #include <TAO/API/include/utils.h> #include <TAO/API/include/json.h> #include <TAO/Ledger/types/mempool.h> #include <TAO/Operation/include/enum.h> #include <TAO/Register/types/object.h> #include <Util/include/debug.h> #include <Util/include/encoding.h> #include <Util/include/string.h> /* Global TAO namespace. */ namespace TAO { /* API Layer namespace. */ namespace API { /* Change the signature scheme used to generate the public-private keys for the users signature chain as well as keys stored in the crypto object register. */ json::json Crypto::ChangeScheme(const json::json& params, bool fHelp) { /* JSON return value. */ json::json ret; /* The new key scheme */ uint8_t nScheme = 0; /* Authenticate the users credentials */ if(!users->Authenticate(params)) throw APIException(-139, "Invalid credentials"); /* Get the PIN to be used for this API call */ SecureString strPIN = users->GetPin(params, TAO::Ledger::PinUnlock::TRANSACTIONS); /* Get the session to be used for this API call */ Session& session = users->GetSession(params); /* Get the account. */ const memory::encrypted_ptr<TAO::Ledger::SignatureChain>& user = session.GetAccount(); if(!user) throw APIException(-10, "Invalid session ID"); /* Check the caller included the key name */ if(params.find("scheme") == params.end() || params["scheme"].get<std::string>().empty()) throw APIException(-275, "Missing scheme."); /* Get the scheme string */ std::string strScheme = ToLower(params["scheme"].get<std::string>()); /* Convert to scheme type */ if(strScheme == "falcon") nScheme = TAO::Ledger::SIGNATURE::FALCON; else if(strScheme == "brainpool") nScheme = TAO::Ledger::SIGNATURE::BRAINPOOL; else throw APIException(-262, "Invalid scheme."); /* The logged in sig chain genesis hash */ uint256_t hashGenesis = user->Genesis(); /* The address of the crypto object register, which is deterministic based on the genesis */ TAO::Register::Address hashCrypto = TAO::Register::Address(std::string("crypto"), hashGenesis, TAO::Register::Address::CRYPTO); /* Read the crypto object register */ TAO::Register::Object crypto; if(!LLD::Register->ReadState(hashCrypto, crypto, TAO::Ledger::FLAGS::MEMPOOL)) throw APIException(-259, "Could not read crypto object register"); /* Parse the object. */ if(!crypto.Parse()) throw APIException(-36, "Failed to parse object register"); /* Lock the signature chain. */ LOCK(session.CREATE_MUTEX); /* Create the transaction. */ TAO::Ledger::Transaction tx; if(!Users::CreateTransaction(user, strPIN, tx)) throw APIException(-17, "Failed to create transaction"); /* Check the existing scheme */ if(tx.nNextType == nScheme) throw APIException(-278, "Scheme already in use"); /* Set the new key scheme */ tx.nNextType = nScheme; /* Regenerate the next hashed public key based on the new scheme */ tx.NextHash(user->Generate(tx.nSequence + 1, strPIN), tx.nNextType); /* Declare operation stream to serialize all of the field updates*/ TAO::Operation::Stream ssOperationStream; /* Regenerate any keys in the crypto object register */ if(crypto.get<uint256_t>("auth") != 0) ssOperationStream << std::string("auth") << uint8_t(TAO::Operation::OP::TYPES::UINT256_T) << user->KeyHash("auth", 0, strPIN, tx.nNextType); if(crypto.get<uint256_t>("lisp") != 0) ssOperationStream << std::string("lisp") << uint8_t(TAO::Operation::OP::TYPES::UINT256_T) << user->KeyHash("lisp", 0, strPIN, tx.nNextType); if(crypto.get<uint256_t>("network") != 0) ssOperationStream << std::string("network") << uint8_t(TAO::Operation::OP::TYPES::UINT256_T) << user->KeyHash("network", 0, strPIN, tx.nNextType); if(crypto.get<uint256_t>("sign") != 0) ssOperationStream << std::string("sign") << uint8_t(TAO::Operation::OP::TYPES::UINT256_T) << user->KeyHash("sign", 0, strPIN, tx.nNextType); if(crypto.get<uint256_t>("verify") != 0) ssOperationStream << std::string("verify") << uint8_t(TAO::Operation::OP::TYPES::UINT256_T) << user->KeyHash("verify", 0, strPIN, tx.nNextType); /* Add the crypto update contract. */ tx[tx.Size()] << uint8_t(TAO::Operation::OP::WRITE) << hashCrypto << ssOperationStream.Bytes(); /* Add the fee */ AddFee(tx); /* Execute the operations layer. */ if(!tx.Build()) throw APIException(-44, "Transaction failed to build"); /* Sign the transaction. */ if(!tx.Sign(session.GetAccount()->Generate(tx.nSequence, strPIN))) throw APIException(-31, "Ledger failed to sign transaction"); /* Execute the operations layer. */ if(!TAO::Ledger::mempool.Accept(tx)) throw APIException(-32, "Failed to accept"); /* Build a JSON response object. */ ret["txid"] = tx.GetHash().ToString(); return ret; } } }
40.961783
162
0.588555
[ "object" ]
3c80fe32a91ffc15fe2f061c93b2c66c125267a1
8,683
cpp
C++
tools/flash-export/src/xfl/renderer/ShapeDecoder.cpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
12
2021-04-10T18:39:19.000Z
2022-02-01T05:21:42.000Z
tools/flash-export/src/xfl/renderer/ShapeDecoder.cpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
109
2021-09-09T23:53:45.000Z
2022-03-31T23:21:28.000Z
tools/flash-export/src/xfl/renderer/ShapeDecoder.cpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
3
2021-05-20T03:23:10.000Z
2022-01-10T14:22:31.000Z
#include "ShapeDecoder.hpp" #include <ek/log.h> #include <ek/assert.h> namespace ek::xfl { using Op = RenderCommand::Operation; enum EdgeSelectionBit { EdgeSelectionBit_FillStyle0 = 1, EdgeSelectionBit_FillStyle1 = 2, EdgeSelectionBit_Stroke = 4 }; RenderCommand ShapeEdge::to_command() const { if (is_quadratic) { return {Op::curve_to, c, p1}; } else { return {Op::line_to, p1}; } } ShapeEdge ShapeEdge::curve(int style, vec2_t p0, vec2_t c, vec2_t p1) { ShapeEdge result; result.fill_style_idx = style; result.p0 = p0; result.c = c; result.p1 = p1; result.is_quadratic = true; return result; } ShapeEdge ShapeEdge::line(int style, vec2_t p0, vec2_t p1) { ShapeEdge result; result.fill_style_idx = style; result.p0 = p0; result.p1 = p1; result.is_quadratic = false; return result; } ShapeDecoder::ShapeDecoder(const TransformModel& transform) : transform_{transform} { } void ShapeDecoder::decode(const Element& el) { ++total_; const auto& matrix = transform_.matrix; read_fill_styles(el); read_line_styles(el); vec2_t pen = {{0.0f, 0.0f}}; int current_fill_0; int current_fill_1; int current_line = -1; Array<RenderCommand> edges{}; Array<ShapeEdge> fills{}; Array<ShapeEdge> back_fills{}; for (const auto& edge: el.edges) { bool line_started = false; const auto& edgeCommands = edge.commands; const auto& values = edge.values; if (edgeCommands.empty()) { continue; } back_fills.clear(); bool is_new_line_style = edge.stroke_style != current_line; current_fill_0 = edge.fill_style_0; current_fill_1 = edge.fill_style_1; float radius = 0.0f; if (is_new_line_style) { int line_style_idx = edge.stroke_style; edges.push_back(line_styles_[line_style_idx]); current_line = line_style_idx; radius = line_style_idx < 1 ? 0.0f : (el.strokes[line_style_idx - 1].weight / 2.0f); } int valueIndex = 0; for (char cmd: edgeCommands) { if (cmd == '!') { const auto v1 = (float) values[valueIndex++]; const auto v2 = (float) values[valueIndex++]; const auto p = vec2_transform({{v1, v2}}, matrix); //if (px != penX || py != penY) { if (current_line > 0 && !(line_started && almost_eq_vec2(pen, p, MATH_F32_EPSILON))) { extend(p, radius); edges.emplace_back(Op::move_to, p); line_started = true; } //} pen = p; } else if (cmd == '|' || cmd == '/') { const auto v1 = (float) values[valueIndex++]; const auto v2 = (float) values[valueIndex++]; const auto p = vec2_transform({{v1, v2}}, matrix); extend(p, radius); if (current_line > 0) { edges.emplace_back(Op::line_to, p); } else { edges.emplace_back(Op::move_to, p); } if (current_fill_0 > 0) { fills.push_back(ShapeEdge::line(current_fill_0, pen, p)); } if (current_fill_1 > 0) { fills.push_back(ShapeEdge::line(current_fill_1, p, pen)); } pen = p; } else if (cmd == '[' || cmd == ']') { const auto v1 = (float) values[valueIndex++]; const auto v2 = (float) values[valueIndex++]; const auto v3 = (float) values[valueIndex++]; const auto v4 = (float) values[valueIndex++]; const auto c = vec2_transform({{v1, v2}}, matrix); const auto p = vec2_transform({{v3, v4}}, matrix); extend(c, radius); extend(p, radius); if (current_line > 0) { edges.emplace_back(Op::curve_to, c, p); } if (current_fill_0 > 0) { fills.push_back(ShapeEdge::curve(current_fill_0, pen, c, p)); } if (current_fill_1 > 0) { fills.push_back(ShapeEdge::curve(current_fill_1, p, c, pen)); } pen = p; } else if (cmd == 'S') { const auto mask = static_cast<uint32_t>(values[valueIndex++]); // fillStyle0 if ((mask & EdgeSelectionBit_FillStyle0) != 0) { // todo: } // fillStyle1 if ((mask & EdgeSelectionBit_FillStyle1) != 0) { // todo: } // stroke if ((mask & EdgeSelectionBit_Stroke) != 0) { // todo: } } } for (auto& fill: back_fills) { fills.push_back(fill); } } flush_commands(edges, fills); } void ShapeDecoder::read_fill_styles(const Element& el) { auto& result = fill_styles_; result.clear(); // Special null fill-style result.emplace_back(Op::fill_end); for (const auto& fill: el.fills) { result.emplace_back(Op::fill_begin, &fill); } } void ShapeDecoder::read_line_styles(const Element& el) { auto& result = line_styles_; result.clear(); // Special null line-style result.emplace_back(Op::line_style_reset); for (const auto& stroke: el.strokes) { if (stroke.is_solid) { result.emplace_back(Op::line_style_setup, &stroke); } else { /// TODO: check if not solid stroke } } } void ShapeDecoder::flush_commands(const Array<RenderCommand>& edges, Array<ShapeEdge>& fills) { auto left = static_cast<int>(fills.size()); // bool init = false; int current_fill = 0; while (left > 0) { auto first = fills[0]; auto found_fill = false; if (current_fill > 0) { for (int i = 0; i < left; ++i) { if (fills[i].fill_style_idx == current_fill) { first = fills[i]; fills.eraseAt(i); --left; found_fill = true; break; } } } if (!found_fill) { fills[0] = fills[--left]; } if (first.fill_style_idx >= static_cast<int>(fill_styles_.size())) { EK_WARN("Fill Style %d not found", first.fill_style_idx); continue; } // if (!init) { // init = true; if (current_fill != first.fill_style_idx) { commands_.push_back(fill_styles_[first.fill_style_idx]); current_fill = first.fill_style_idx; } // } const vec2_t m = first.p0; commands_.emplace_back(Op::move_to, m); commands_.push_back(first.to_command()); auto prev = first; bool loop = false; while (!loop) { bool found = false; for (int i = 0; i < left; ++i) { if (prev.connects(fills[i])) { prev = fills[i]; fills[i] = fills[--left]; commands_.push_back(prev.to_command()); found = true; if (prev.connects(first)) { loop = true; } break; } } if (!found) { /*trace("Remaining:"); for (f in 0...left) fills[f].dump (); throw("Dangling fill : " + prev.x1 + "," + prev.y1 + " " + prev.fillStyle);*/ break; } } } if (!fills.empty()) { commands_.emplace_back(Op::fill_end); } if (!edges.empty()) { //trace("EDGES: " + edges.toString()); for (const auto& e: edges) { commands_.push_back(e); } commands_.emplace_back(Op::line_style_reset); } } void ShapeDecoder::extend(vec2_t p, float r) { bounds_builder_ = aabb2_add_circle(bounds_builder_, vec3_v(p, r)); } bool ShapeDecoder::empty() const { return aabb2_is_empty(bounds_builder_) || total_ == 0; } RenderCommandsBatch ShapeDecoder::result() const { RenderCommandsBatch res; res.transform = transform_; res.bounds = bounds_builder_; res.total = total_; res.commands = commands_; return res; } }
28.656766
102
0.506507
[ "transform", "solid" ]
3c875d37c8ba7c011753c7614f83f66977f77789
553
cpp
C++
CodeForces/Complete/800-899/869C-TheIntriguingObsession.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/800-899/869C-TheIntriguingObsession.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/800-899/869C-TheIntriguingObsession.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include<iostream> #include<vector> int main(){ const int N = 5005; const int64_t M = 998244353; std::vector<std::vector<int64_t> > f(N, std::vector<int64_t>(N, 0)); for (int p = 1; p < N; p++){f[1][p] = f[p][1] = p + 1;} for (int p = 2; p < N; p++){ for (int q = 2; q < N; q++){ f[p][q] = (f[p - 1][q] + f[p - 1][q - 1] * q % M) % M; } } int a, b, c; scanf("%d %d %d\n", &a, &b, &c); int64_t total = ((f[a][b] * f[a][c] % M) * f[b][c]) % M; printf("%lld \n", total); return 0; }
24.043478
72
0.423146
[ "vector" ]
3c8c4f2ed9db569a00f2694e49e29d7db059b0e9
6,565
cxx
C++
applications/rtkspectralforwardmodel/rtkspectralforwardmodel.cxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
167
2015-02-26T08:39:33.000Z
2022-03-31T04:40:35.000Z
applications/rtkspectralforwardmodel/rtkspectralforwardmodel.cxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
270
2015-02-26T15:34:32.000Z
2022-03-22T09:49:24.000Z
applications/rtkspectralforwardmodel/rtkspectralforwardmodel.cxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
117
2015-05-01T14:56:49.000Z
2022-03-11T03:18:26.000Z
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtkspectralforwardmodel_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "rtkMacro.h" #include "rtkSpectralForwardModelImageFilter.h" #include <itkImageFileReader.h> #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkspectralforwardmodel, args_info); using PixelValueType = float; constexpr unsigned int Dimension = 3; using DecomposedProjectionType = itk::VectorImage<PixelValueType, Dimension>; using DecomposedProjectionReaderType = itk::ImageFileReader<DecomposedProjectionType>; using SpectralProjectionsType = itk::VectorImage<PixelValueType, Dimension>; using SpectralProjectionWriterType = itk::ImageFileWriter<SpectralProjectionsType>; using IncidentSpectrumImageType = itk::VectorImage<PixelValueType, Dimension - 1>; using IncidentSpectrumReaderType = itk::ImageFileReader<IncidentSpectrumImageType>; using DetectorResponseImageType = itk::Image<PixelValueType, Dimension - 1>; using DetectorResponseReaderType = itk::ImageFileReader<DetectorResponseImageType>; using MaterialAttenuationsImageType = itk::Image<PixelValueType, Dimension - 1>; using MaterialAttenuationsReaderType = itk::ImageFileReader<MaterialAttenuationsImageType>; // Read all inputs DecomposedProjectionReaderType::Pointer decomposedProjectionReader = DecomposedProjectionReaderType::New(); decomposedProjectionReader->SetFileName(args_info.input_arg); decomposedProjectionReader->Update(); IncidentSpectrumReaderType::Pointer incidentSpectrumReader = IncidentSpectrumReaderType::New(); incidentSpectrumReader->SetFileName(args_info.incident_arg); incidentSpectrumReader->Update(); DetectorResponseReaderType::Pointer detectorResponseReader = DetectorResponseReaderType::New(); detectorResponseReader->SetFileName(args_info.detector_arg); detectorResponseReader->Update(); MaterialAttenuationsReaderType::Pointer materialAttenuationsReader = MaterialAttenuationsReaderType::New(); materialAttenuationsReader->SetFileName(args_info.attenuations_arg); materialAttenuationsReader->Update(); // Get parameters from the images const unsigned int NumberOfMaterials = materialAttenuationsReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]; const unsigned int NumberOfSpectralBins = args_info.thresholds_given; const unsigned int MaximumEnergy = incidentSpectrumReader->GetOutput()->GetVectorLength(); // Generate a set of zero-filled photon count projections SpectralProjectionsType::Pointer photonCounts = SpectralProjectionsType::New(); photonCounts->CopyInformation(decomposedProjectionReader->GetOutput()); photonCounts->SetVectorLength(NumberOfSpectralBins); photonCounts->Allocate(); // Read the thresholds on command line itk::VariableLengthVector<unsigned int> thresholds; thresholds.SetSize(NumberOfSpectralBins + 1); for (unsigned int i = 0; i < NumberOfSpectralBins; i++) thresholds[i] = args_info.thresholds_arg[i]; // Add the maximum pulse height at the end unsigned int MaximumPulseHeight = detectorResponseReader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; thresholds[NumberOfSpectralBins] = MaximumPulseHeight; // Check that the inputs have the expected size DecomposedProjectionType::IndexType indexDecomp; indexDecomp.Fill(0); if (decomposedProjectionReader->GetOutput()->GetPixel(indexDecomp).Size() != NumberOfMaterials) itkGenericExceptionMacro(<< "Decomposed projections (i.e. initialization data) image has vector size " << decomposedProjectionReader->GetOutput()->GetPixel(indexDecomp).Size() << ", should be " << NumberOfMaterials); SpectralProjectionsType::IndexType indexSpect; indexSpect.Fill(0); if (photonCounts->GetPixel(indexSpect).Size() != NumberOfSpectralBins) itkGenericExceptionMacro(<< "Spectral projections (i.e. photon count data) image has vector size " << photonCounts->GetPixel(indexSpect).Size() << ", should be " << NumberOfSpectralBins); IncidentSpectrumImageType::IndexType indexIncident; indexIncident.Fill(0); if (incidentSpectrumReader->GetOutput()->GetPixel(indexIncident).Size() != MaximumEnergy) itkGenericExceptionMacro(<< "Incident spectrum image has vector size " << incidentSpectrumReader->GetOutput()->GetPixel(indexIncident).Size() << ", should be " << MaximumEnergy); if (detectorResponseReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] != MaximumEnergy) itkGenericExceptionMacro(<< "Detector response image has " << detectorResponseReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] << "energies, should have " << MaximumEnergy); // Create and set the filter using ForwardModelFilterType = rtk::SpectralForwardModelImageFilter<DecomposedProjectionType, SpectralProjectionsType, IncidentSpectrumImageType>; ForwardModelFilterType::Pointer forward = ForwardModelFilterType::New(); forward->SetInputDecomposedProjections(decomposedProjectionReader->GetOutput()); forward->SetInputMeasuredProjections(photonCounts); forward->SetInputIncidentSpectrum(incidentSpectrumReader->GetOutput()); forward->SetDetectorResponse(detectorResponseReader->GetOutput()); forward->SetMaterialAttenuations(materialAttenuationsReader->GetOutput()); forward->SetThresholds(thresholds); forward->SetIsSpectralCT(true); TRY_AND_EXIT_ON_ITK_EXCEPTION(forward->Update()) // Write output SpectralProjectionWriterType::Pointer writer = SpectralProjectionWriterType::New(); writer->SetInput(forward->GetOutput()); writer->SetFileName(args_info.output_arg); writer->Update(); return EXIT_SUCCESS; }
47.572464
119
0.747753
[ "vector" ]
3c905ee63c3b0d25a4d9a11752bbb9b189379b93
4,392
cpp
C++
external/swak/libraries/functionPlugins/swakSurfacesAndSetsFunctionPlugin/surfaceValueMinimumPluginFunction.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/functionPlugins/swakSurfacesAndSetsFunctionPlugin/surfaceValueMinimumPluginFunction.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/functionPlugins/swakSurfacesAndSetsFunctionPlugin/surfaceValueMinimumPluginFunction.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright: ICE Stroemungsfoschungs GmbH Copyright (C) 1991-2008 OpenCFD Ltd. ------------------------------------------------------------------------------- License This file is based on CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Contributors/Copyright: 2012-2013 Bernhard F.W. Gschaider <bgschaid@ice-sf.at> \*---------------------------------------------------------------------------*/ #include "surfaceValueMinimumPluginFunction.hpp" #include "FieldValueExpressionDriver.hpp" #include "addToRunTimeSelectionTable.hpp" namespace CML { typedef surfaceValueMinimumPluginFunction<scalar> surfaceMinimumScalar; defineTemplateTypeNameAndDebug(surfaceMinimumScalar,0); addNamedToRunTimeSelectionTable(FieldValuePluginFunction, surfaceMinimumScalar , name, surfaceValueMinimumScalar); typedef surfaceValueMinimumPluginFunction<vector> surfaceMinimumVector; defineTemplateTypeNameAndDebug(surfaceMinimumVector,0); addNamedToRunTimeSelectionTable(FieldValuePluginFunction, surfaceMinimumVector , name, surfaceValueMinimumVector); typedef surfaceValueMinimumPluginFunction<tensor> surfaceMinimumTensor; defineTemplateTypeNameAndDebug(surfaceMinimumTensor,0); addNamedToRunTimeSelectionTable(FieldValuePluginFunction, surfaceMinimumTensor , name, surfaceValueMinimumTensor); typedef surfaceValueMinimumPluginFunction<symmTensor> surfaceMinimumSymmTensor; defineTemplateTypeNameAndDebug(surfaceMinimumSymmTensor,0); addNamedToRunTimeSelectionTable(FieldValuePluginFunction, surfaceMinimumSymmTensor , name, surfaceValueMinimumSymmTensor); typedef surfaceValueMinimumPluginFunction<sphericalTensor> surfaceMinimumSphericalTensor; defineTemplateTypeNameAndDebug(surfaceMinimumSphericalTensor,0); addNamedToRunTimeSelectionTable(FieldValuePluginFunction, surfaceMinimumSphericalTensor , name, surfaceValueMinimumSphericalTensor); // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Type> surfaceValueMinimumPluginFunction<Type>::surfaceValueMinimumPluginFunction( const FieldValueExpressionDriver &parentDriver, const word &name ): GeneralSurfaceEvaluationPluginFunction<Type>( parentDriver, name ) { } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Type> void surfaceValueMinimumPluginFunction<Type>::doEvaluation() { typedef typename GeneralSurfaceEvaluationPluginFunction<Type>::resultType rType; autoPtr<rType> pValueMinimum( new rType( IOobject( "surfaceValueMinimumInCell", this->mesh().time().timeName(), this->mesh(), IOobject::NO_READ, IOobject::NO_WRITE ), this->mesh(), dimensioned<Type>("no",dimless,pTraits<Type>::zero) ) ); const labelList &cells=this->meshCells(); List<bool> here(pValueMinimum->size(),false); const Field<Type> vals=this->values(); forAll(cells,i) { const label cellI=cells[i]; if(cellI>=0) { if(here[cellI]) { pValueMinimum()[cellI]=min( vals[i], pValueMinimum()[cellI] ); } else { here[cellI]=true; pValueMinimum()[cellI]=vals[i]; } } } pValueMinimum->correctBoundaryConditions(); this->result().setObjectResult(pValueMinimum); } // * * * * * * * * * * * * * * * Friend Operators * * * * * * * * * * * * * // } // namespace // ************************************************************************* //
36.297521
132
0.638889
[ "mesh", "vector" ]
3c96e7ea0ccee657aee0ce89f2b4631ce0e3c7ba
4,743
hpp
C++
Libraries/Editor/ToolControl.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Editor/ToolControl.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Editor/ToolControl.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { class Editor; class ComboBox; class Tool; class SelectTool; class PropertyView; class ToolControl; class CreationTool; class ScrollArea; class ResourceEvent; class PropertyInterface; DeclareEnum2(ShowToolProperties, Show, Auto); namespace Events { DeclareEvent(GetToolInfo); DeclareEvent(SelectTool); DeclareEvent(ShortcutInfoEnter); } // namespace Events /// Allows Ui customization for Tools. This will be sent on the Tool every time /// it is activated. class ToolUiEvent : public Event { public: ZilchDeclareType(ToolUiEvent, TypeCopyMode::ReferenceType); /// Constructor. ToolUiEvent(Composite* parent); /// Getters / setters. Composite* GetParent(); void SetCustomUi(Composite* customUi); Composite* GetCustomUi(); Cog* GetSelectTool(); /// Whether or not to force show the tools window when switched to this tool. bool mNeedsPropertyGrid; Composite* mParent; Composite* mCustomUi; /// Easy access to the Select Tool. It's commonly used in other Tools (such as /// ray casting). Cog* mSelectTool; }; class ToolData { public: /// Constructors. ToolData() { } ToolData(Archetype* archetype); ToolData(BoundType* componentMeta); ~ToolData(); String ToString(bool shortFormat = false) const; String GetName() const; Space* GetSpace(); /// If it was created from an Archetype with the [Tool] tag. HandleOf<Archetype> mArchetype; /// If it was created from a script component with the 'autoRegister' /// property set to true on the [Tool] attribute. BoundTypeHandle mScriptComponentType; HandleOf<Space> mSpace; HandleOf<Cog> mCog; }; class ToolObjectManager : public EditorScriptObjects<ToolData> { public: /// Constructor. ToolObjectManager(ToolControl* toolControl); ~ToolObjectManager(); /// EditorScriptObject Interface. void AddObject(ToolData* object) override; void RemoveObject(ToolData* object) override; ToolData* GetObject(StringParam objectName) override; uint GetObjectCount() override; ToolData* GetObject(uint index) override; ToolData* UpdateData(StringParam objectName) override; Space* GetSpace(ToolData* object) override; void CreateOrUpdateCog(ToolData* object) override; /// All registered tools. Array<ToolData*> mToolArray; ToolControl* mToolControl; }; class ToolControl : public Composite { public: ZilchDeclareType(ToolControl, TypeCopyMode::ReferenceType); ToolControl(Composite* parent); ~ToolControl(); /// Composite Interface. void UpdateTransform() override; /// Creates a tool with the given archetype. If a tool already exists, /// it will re-create the tool to reflect any changes in the Archetype. Cog* AddOrUpdateTool(Archetype* toolArchetype); /// Removes the tool of the given archetype. void RemoveTool(Archetype* toolArchetype); /// Returns the active tool cog. Cog* GetActiveCog(); Cog* GetToolByName(StringParam typeName); /// Returns the PropertyGrid widget. PropertyView* GetPropertyGrid() const; /// Tool Selection. void SelectToolIndex(uint index, ShowToolProperties::Enum showTool = ShowToolProperties::Auto); void SelectToolName(StringParam toolName, ShowToolProperties::Enum showTool = ShowToolProperties::Auto); /// Whether or not the default selection tool is currently selected. bool IsSelectToolActive(); /// Update the shortcut tool when hovering of info icon and tool is changed. void UpdateShortcutsTip(); SelectTool* mSelectTool; CreationTool* mCreationTool; /// The currently selected tool. ToolData* mActiveTool; ToolObjectManager mTools; private: friend class ToolObjectManager; /// Display the mouse/keyboard shortcuts unique to the selected tool. void OnInfoMouseEnter(MouseEvent*); void OnInfoMouseExit(MouseEvent*); /// Change the tool when selected in the dropdown. void OnToolPulldownSelect(ObjectEvent*); /// We want to forward keyboard input to the last viewport to execute /// shortcuts. void OnKeyDown(KeyboardEvent* e); /// When scripts are compiled, re-select the active tool to refresh any /// changes to script tools. void OnScriptsCompiled(Event*); void SelectToolInternal(ToolData* tool, ShowToolProperties::Enum showTool); void BuildShortcutsToolTip(const ShortcutSet* entries); void BuildShorcutsFormat(TreeFormatting* formatting); PropertyInterface* mPropertyInterface; Editor* mEditor; Element* mInfoIcon; ComboBox* mToolBox; PropertyView* mPropertyGrid; ScrollArea* mScrollArea; Composite* mCustomUi; HandleOf<ToolTip> mShortcutsTip; ListView* mShortcutsView; UniquePointer<ListSource> mToolSource; ShortcutSource mShortcutSource; }; } // namespace Zero
25.637838
106
0.752688
[ "object" ]
3ca1456ab9082b9f4734053182c7c1429f380cab
15,081
hpp
C++
include/ponder/detail/string_view.hpp
leomeyer/ponder
8f8d885f612bdc596377de08d4e73a980f16fd2d
[ "MIT" ]
null
null
null
include/ponder/detail/string_view.hpp
leomeyer/ponder
8f8d885f612bdc596377de08d4e73a980f16fd2d
[ "MIT" ]
null
null
null
include/ponder/detail/string_view.hpp
leomeyer/ponder
8f8d885f612bdc596377de08d4e73a980f16fd2d
[ "MIT" ]
null
null
null
#pragma once #ifndef PONDER_STRING_VIEW_HPP #define PONDER_STRING_VIEW_HPP /* Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstddef> // ptrdiff_t #include <string> #include <limits> #include <iterator> #include <stdexcept> #include <algorithm> #ifdef WIN32 #undef min #undef max #endif namespace ponder { namespace detail { #define CONSTEXPR_BACKUP CONSTEXPR #undef CONSTEXPR #if defined(_HAS_CONSTEXPR) || __cplusplus >= 201103L # define CONSTEXPR constexpr #else # define CONSTEXPR #endif #if __cplusplus >= 201402L # define CONSTEXPR_CPP14 constexpr #else # define CONSTEXPR_CPP14 #endif template<typename T> class pointer_iterator :public std::iterator<std::random_access_iterator_tag, T> { public: typedef T* pointer; typedef T& reference; typedef std::ptrdiff_t difference_type; pointer_iterator() :p_(0) {} pointer_iterator(T* x) :p_(x) {} pointer_iterator(const pointer_iterator& it) : p_(it.p_) {} reference operator*() const { return *p_; } pointer_iterator operator+ (difference_type n) const { return pointer_iterator(p_ + n); } pointer_iterator& operator+= (difference_type n) { p_ += n; return *this; } pointer_iterator operator- (difference_type n) const { return pointer_iterator(p_ - n); } pointer_iterator& operator-= (difference_type n) { p_ -= n; return *this; } difference_type operator- (pointer_iterator o) const { return p_ - o.p_; } pointer_iterator& operator++() { p_++; return *this; } pointer_iterator operator++(int) { pointer_iterator tmp(*this); operator++(); return tmp; } pointer_iterator& operator--() { p_--; return *this; } pointer_iterator operator--(int) { pointer_iterator tmp(*this); operator--(); return tmp; } bool operator==(const pointer_iterator& rhs) { return p_ == rhs.p_; } bool operator!=(const pointer_iterator& rhs) { return p_ != rhs.p_; } bool operator<(const pointer_iterator& rhs) { return p_ < rhs.p_; } bool operator>(const pointer_iterator& rhs) { return rhs < *this; } bool operator<=(const pointer_iterator& rhs) { return !(*this > rhs); } bool operator>=(const pointer_iterator& rhs) { return !(*this < rhs); } private: pointer p_; }; template<typename CharT, typename Traits = std::char_traits<CharT> > class basic_string_view { public: typedef Traits traits_type; typedef CharT value_type; typedef CharT* pointer; typedef const CharT* const_pointer; typedef CharT& reference; typedef const CharT& const_reference; typedef pointer_iterator<const CharT> const_iterator; typedef const_iterator iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef const_reverse_iterator reverse_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; #if defined(_HAS_CONSTEXPR) || __cplusplus >= 201103L static constexpr size_type npos = size_type(-1); #else static const size_type npos = size_type(-1); #endif CONSTEXPR basic_string_view() : start_(0),end_(0) {} CONSTEXPR basic_string_view(const basic_string_view& other) : start_(other.start_),end_(other.end_){} template<class Allocator> basic_string_view(const std::basic_string<CharT, Traits, Allocator>& str) :start_(0),end_(0){ if (!str.empty()) { start_ = &str[0]; end_ = start_ + str.size(); } } CONSTEXPR basic_string_view(const CharT* s, size_type count) : start_(s),end_(s+count) {} CONSTEXPR basic_string_view(const CharT* s) : start_(s), end_(s + strlen(s)) {} basic_string_view& operator=(const basic_string_view& view) { this->start_ = view.start_; this->end_ = view.end_; return *this; } CONSTEXPR const_iterator begin() const { return start_; } CONSTEXPR const_iterator cbegin() const { return start_; } CONSTEXPR const_iterator end() const { return end_; } CONSTEXPR const_iterator cend() const { return end_; } CONSTEXPR const_reverse_iterator rbegin() const { return const_reverse_iterator(end_); } CONSTEXPR const_reverse_iterator rend() const { return const_reverse_iterator(start_); } CONSTEXPR const_reference operator[](size_type pos) const { #if __cplusplus >= 201402L assert(pos < size()); #endif return *(start_ + pos); } CONSTEXPR const_reference at(size_type pos) const { return pos >= size()? throw std::out_of_range("basic_string_view at out of range") : *(start_ + pos); } CONSTEXPR const_reference front() const { return *start_; } CONSTEXPR const_reference back() const { return *end_; } CONSTEXPR const_pointer data() const { return &(*start_); } CONSTEXPR size_type size() const { return std::distance(begin(), end()); } CONSTEXPR size_type length() const { return std::distance(begin(), end()); } CONSTEXPR size_type max_size() const { return std::numeric_limits<size_type>::max()/ 2; } CONSTEXPR bool empty() const { return size() == 0; } CONSTEXPR_CPP14 void remove_prefix(size_type n) { assert(n < size()); start_ += n; } CONSTEXPR_CPP14 void remove_suffix(size_type n) { assert(n < size()); end_ -= n; } CONSTEXPR_CPP14 void swap(basic_string_view& v) { std::swap(start_,v.start_); std::swap(end_,v.end_); } #if __cplusplus >= 201103L template<class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> to_string(const Allocator& a = Allocator()) const { return std::basic_string<CharT, Traits, Allocator>(begin(),end()); } // Explicit conversion disallows assignment conversion. template<class Allocator> /*explicit*/ operator std::basic_string<CharT, Traits, Allocator>() const { return std::basic_string<CharT, Traits, Allocator>(begin(), end()); } #else std::basic_string<CharT, Traits> to_string() const { return std::basic_string<CharT, Traits>(begin(),end()); } template<class Allocator> operator std::basic_string<CharT, Traits, Allocator>() const { return std::basic_string<CharT, Traits, Allocator>(begin(), end()); } #endif size_type copy(CharT* dest, size_type count, size_type pos = 0) const { if (pos >= size()) { throw std::out_of_range("basic_string_view::copy out of range"); } for (int i = 0, sz = size(); i < sz; ++i) { dest[i] = operator[](i + pos); } return size(); } CONSTEXPR basic_string_view substr(size_type pos = 0, size_type count = npos) const { return pos >= size() ? throw std::out_of_range("basic_string_view::substr out of range"): (count > size() - pos) ? substr(pos,size() - pos) : basic_string_view(data() + pos, count); } CONSTEXPR_CPP14 int compare(basic_string_view v) const { const int r = traits_type::compare(data(), v.data(), std::min(size(), v.size())); return r==0 ? static_cast<int>(size()-v.size()) : r; } CONSTEXPR_CPP14 int compare(size_type pos1, size_type count1, basic_string_view v) const {return substr(pos1, count1).compare(v);} CONSTEXPR_CPP14 int compare(size_type pos1, size_type count1, basic_string_view v, size_type pos2, size_type count2) const {return substr(pos1, count1).compare(v.substr(pos2, count2));} CONSTEXPR_CPP14 int compare(const CharT* s) const { return compare(basic_string_view(s)); } CONSTEXPR_CPP14 int compare(size_type pos1, size_type count1,const CharT* s) const { return substr(pos1, count1).compare(basic_string_view(s)); } CONSTEXPR_CPP14 int compare(size_type pos1, size_type count1, const CharT* s, size_type count2) const { return substr(pos1, count1).compare(basic_string_view(s, count2)); } CONSTEXPR size_type find(basic_string_view v, size_type pos = 0) const { return pos >= size() ? npos: find_to_pos(std::search(begin() + pos, end(), v.begin(), v.end())); } CONSTEXPR size_type find(CharT c, size_type pos = 0) const {return find(basic_string_view(&c, 1), pos);} CONSTEXPR size_type find(const CharT* s, size_type pos, size_type count) const {return find(basic_string_view(s, count), pos);} CONSTEXPR size_type find(const CharT* s, size_type pos = 0) const {return find(basic_string_view(s), pos);} CONSTEXPR size_type rfind(basic_string_view v, size_type pos = npos) const { return pos > size() ? rfind(v, size()) : rfind_to_pos(std::search(const_reverse_iterator(begin() + pos), rend(), v.rbegin(), v.rend()), v.size()); } CONSTEXPR size_type rfind(CharT c, size_type pos = npos) const {return rfind(basic_string_view(&c, 1), pos);} CONSTEXPR size_type rfind(const CharT* s, size_type pos, size_type count) const {return rfind(basic_string_view(s, count), pos);} CONSTEXPR size_type rfind(const CharT* s, size_type pos = npos) const {return rfind(basic_string_view(s), pos);} CONSTEXPR size_type find_first_of(basic_string_view v, size_type pos = 0) const { return pos >= size()? npos: v.find(*(start_ + pos)) != npos?pos:find_first_of(v, pos + 1); } CONSTEXPR size_type find_first_of(CharT c, size_type pos = 0) const { return find_first_of(basic_string_view(&c, 1), pos); } CONSTEXPR size_type find_first_of(const CharT* s, size_type pos, size_type count) const { return find_first_of(basic_string_view(s, count), pos); } CONSTEXPR size_type find_first_of(const CharT* s, size_type pos = 0) const { return find_first_of(basic_string_view(s), pos);} CONSTEXPR size_type find_last_of(basic_string_view v, size_type pos = npos) const { return pos == 0 ? npos: pos >= size() ? find_last_of(v,size()-1) : v.find(*(start_ + pos)) != npos ? pos : find_last_of(v, pos - 1); } CONSTEXPR size_type find_last_of(CharT c, size_type pos = npos) const { return find_last_of(basic_string_view(&c, 1), pos); } CONSTEXPR size_type find_last_of(const CharT* s, size_type pos, size_type count) const { return find_last_of(basic_string_view(s, count), pos); } CONSTEXPR size_type find_last_of(const CharT* s, size_type pos = npos) const { return find_last_of(basic_string_view(s), pos); } CONSTEXPR size_type find_first_not_of(basic_string_view v, size_type pos = 0) const { return pos >= size() ? npos : v.find(*(start_ + pos)) == npos ? pos : find_first_of(v, pos + 1); } CONSTEXPR size_type find_first_not_of(CharT c, size_type pos = 0) const { return find_first_not_of(basic_string_view(&c, 1), pos); } CONSTEXPR size_type find_first_not_of(const CharT* s, size_type pos, size_type count) const { return find_first_not_of(basic_string_view(s, count), pos); } CONSTEXPR size_type find_first_not_of(const CharT* s, size_type pos = 0) const { return find_first_not_of(basic_string_view(s), pos); } CONSTEXPR size_type find_last_not_of(basic_string_view v, size_type pos = npos) const { return pos == 0 ? npos : pos >= size() ? find_last_not_of(v, size() - 1) : v.find(*(start_ + pos)) == npos ? pos : find_last_of(v, pos - 1); } CONSTEXPR size_type find_last_not_of(CharT c, size_type pos = npos) const { return find_last_not_of(basic_string_view(&c, 1), pos); } CONSTEXPR size_type find_last_not_of(const CharT* s, size_type pos, size_type count) const { return find_last_not_of(basic_string_view(s, count), pos); } CONSTEXPR size_type find_last_not_of(const CharT* s, size_type pos = npos) const { return find_last_not_of(basic_string_view(s), pos); } CONSTEXPR_CPP14 bool operator==(const basic_string_view& rhs) const {return compare(rhs) == 0;} CONSTEXPR_CPP14 bool operator!=(const basic_string_view& rhs) const {return compare(rhs) != 0;} CONSTEXPR_CPP14 bool operator<(const basic_string_view& rhs) const {return compare(rhs) < 0;} CONSTEXPR_CPP14 bool operator>(const basic_string_view& rhs) const {return rhs < *this;} CONSTEXPR_CPP14 bool operator<=(const basic_string_view& rhs) const {return !(*this > rhs);} CONSTEXPR_CPP14 bool operator>=(const basic_string_view& rhs) const {return !(*this < rhs);} private: CONSTEXPR basic_string_view(const iterator& s, const iterator& e) : start_(s), end_(e) {} iterator start_; iterator end_; CONSTEXPR size_type find_to_pos(const_iterator it) const { return it == end() ? npos : size_type(it - begin()); } CONSTEXPR size_type rfind_to_pos(const_reverse_iterator it,size_type search_size) const { return it == rend() ? npos : size_type(it.base() - begin() - search_size); } CONSTEXPR static const_pointer strlen_nullpos(const_pointer str) { return *str == '\0' ? str:strlen_nullpos(str + 1); } CONSTEXPR static size_type strlen(const_pointer str) { return strlen_nullpos(str) - str; } }; #undef CONSTEXPR #define CONSTEXPR CONSTEXPR_BACKUP #undef CONSTEXPR_BACKUP #undef CONSTEXPR_CPP14 typedef basic_string_view<char> string_view; typedef basic_string_view<wchar_t> wstring_view; static inline std::ostream& operator << (std::ostream& os, string_view const& value) { os << value.to_string(); return os; } } // namespace detail } // namespace ponder #endif // PONDER_STRING_VIEW_HPP
40.759459
99
0.679133
[ "object" ]
3ca887f1728da1061ea379b5d84a332a7fbb95c9
25,578
cc
C++
src/core/provider.cc
jobegrabber/tensorrt-inference-server
216b0e59c1d8ad8a862dcc266e6abf35dcb11612
[ "BSD-3-Clause" ]
null
null
null
src/core/provider.cc
jobegrabber/tensorrt-inference-server
216b0e59c1d8ad8a862dcc266e6abf35dcb11612
[ "BSD-3-Clause" ]
null
null
null
src/core/provider.cc
jobegrabber/tensorrt-inference-server
216b0e59c1d8ad8a862dcc266e6abf35dcb11612
[ "BSD-3-Clause" ]
1
2020-08-15T09:56:00.000Z
2020-08-15T09:56:00.000Z
// Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "src/core/provider.h" #include "src/core/backend.h" #include "src/core/constants.h" #include "src/core/logging.h" #include "src/core/model_config.h" #include "src/core/model_config_utils.h" namespace nvidia { namespace inferenceserver { // // SystemMemoryReference // SystemMemoryReference::SystemMemoryReference() : SystemMemory() {} const char* SystemMemoryReference::BufferAt(size_t idx, size_t* byte_size) const { if (idx >= buffer_.size()) { *byte_size = 0; return nullptr; } *byte_size = buffer_[idx].second; return buffer_[idx].first; } size_t SystemMemoryReference::AddBuffer(const char* buffer, size_t byte_size) { total_byte_size_ += byte_size; buffer_.emplace_back(std::make_pair(buffer, byte_size)); return buffer_.size() - 1; } AllocatedSystemMemory::AllocatedSystemMemory(size_t byte_size) : SystemMemory() { total_byte_size_ = byte_size; char* buffer = new char[byte_size]; buffer_.reset(buffer); } const char* AllocatedSystemMemory::BufferAt(size_t idx, size_t* byte_size) const { if (idx != 0) { *byte_size = 0; return nullptr; } *byte_size = total_byte_size_; return buffer_.get(); } char* AllocatedSystemMemory::MutableBuffer() { return buffer_.get(); } // // InferRequestProvider // Status InferRequestProvider::Create( const std::string& model_name, const int64_t model_version, const InferRequestHeader& request_header, const std::unordered_map<std::string, std::shared_ptr<SystemMemory>>& input_buffer, std::shared_ptr<InferRequestProvider>* provider) { provider->reset(new InferRequestProvider(model_name, model_version)); (*provider)->request_header_ = request_header; for (const auto& io : request_header.input()) { auto it = input_buffer.find(io.name()); if (it == input_buffer.end()) { return Status( RequestStatusCode::INVALID_ARG, "input '" + io.name() + "' is specified in request header but" + " not found in memory block mapping for model '" + (*provider)->model_name_ + "'"); } if (io.batch_byte_size() != it->second->TotalByteSize()) { return Status( RequestStatusCode::INVALID_ARG, "unexpected size " + std::to_string(it->second->TotalByteSize()) + " for input '" + io.name() + "', expecting " + std::to_string(io.batch_byte_size()) + " for model '" + (*provider)->model_name_ + "'"); } (*provider)->input_buffer_[io.name()] = std::make_pair(it->second, 0); } return Status::Success; } const std::shared_ptr<InferRequestProvider::InputOverrideMap>& InferRequestProvider::GetInputOverride() const { return overrides_; } Status InferRequestProvider::SetInputOverride( const std::shared_ptr<InputOverrideMap>& override) { overrides_ = override; return Status::Success; } bool InferRequestProvider::GetInputOverrideContent( const std::string& name, const void** content, size_t* content_byte_size) { if (overrides_ != nullptr) { const auto& pr = overrides_->find(name); if (pr != overrides_->end()) { if ((*content_byte_size == 0) || (overrides_consumed_.find(name) != overrides_consumed_.end())) { *content = nullptr; *content_byte_size = 0; } else { std::shared_ptr<InputOverride>& override = pr->second; *content = reinterpret_cast<void*>(&(override->content_[0])); *content_byte_size = override->content_.size(); overrides_consumed_.insert(name); } return true; } } return false; } Status InferRequestProvider::GetNextInputContent( const std::string& name, const void** content, size_t* content_byte_size, bool force_contiguous) { if (*content_byte_size == 0) { *content = nullptr; return Status::Success; } if (!GetInputOverrideContent(name, content, content_byte_size)) { const auto& pr = input_buffer_.find(name); if (pr == input_buffer_.end()) { return Status( RequestStatusCode::INTERNAL, "unexpected input '" + name + "'"); } auto& input_content = pr->second; bool isLastChunk = (input_content.first->BufferAt( input_content.second + 1, content_byte_size) == nullptr); if (!force_contiguous || isLastChunk) { *content = input_content.first->BufferAt( input_content.second++, content_byte_size); } else { size_t total_size = 0; size_t start_idx = input_content.second; do { *content = input_content.first->BufferAt( input_content.second++, content_byte_size); total_size += *content_byte_size; } while (*content != nullptr); contiguous_buffers_.emplace_back(); std::vector<char>& buf = contiguous_buffers_.back(); buf.reserve(total_size); for (size_t i = start_idx; i < input_content.second; i++) { const auto& block = input_content.first->BufferAt(i, content_byte_size); buf.insert(buf.end(), block, block + *content_byte_size); } if (buf.size() != total_size) { return Status(RequestStatusCode::INTERNAL, "contiguous input failed"); } *content = &(buf[0]); *content_byte_size = total_size; } } return Status::Success; } Status InferRequestProvider::GetSystemMemory( const std::string& name, std::shared_ptr<SystemMemory>* input_buffer) { auto it = input_buffer_.find(name); if (it == input_buffer_.end()) { return Status( RequestStatusCode::INVALID_ARG, "input '" + name + "' is not found in the provider"); } *input_buffer = it->second.first; return Status::Success; } // // NULLInferRequestProvider // std::vector<uint8_t> NULLInferRequestProvider::buf_; std::mutex NULLInferRequestProvider::mu_; Status NULLInferRequestProvider::GetNextInputContent( const std::string& name, const void** content, size_t* content_byte_size, bool force_contiguous) { if (*content_byte_size == 0) { *content = nullptr; return Status::Success; } if (!GetInputOverrideContent(name, content, content_byte_size)) { std::lock_guard<std::mutex> lock(mu_); // Must return content with all zero data. This is required by // string-datatype tensors where it is interpreted as all empty // strings. Clamp the maximum size that we allow the buffer to // grow to avoid massive allocation. if (buf_.size() < *content_byte_size) { constexpr size_t max_size = 16 * 1024 * 1024; buf_.resize(std::min(max_size, *content_byte_size), 0); } *content = &(buf_[0]); } return Status::Success; } namespace { template <typename T> void AddClassResults( InferResponseHeader::Output* poutput, char* poutput_buffer, const size_t batch1_element_count, const size_t batch_size, const size_t cls_count, const std::shared_ptr<LabelProvider>& label_provider, const InferResponseProvider::SecondaryLabelProviderMap& lookup_map) { T* probs = reinterpret_cast<T*>(poutput_buffer); const size_t entry_cnt = batch1_element_count; const size_t class_cnt = std::min(cls_count, entry_cnt); std::vector<size_t> idx(entry_cnt); for (size_t i = 0; i < batch_size; ++i) { iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&probs](size_t i1, size_t i2) { return probs[i1] > probs[i2]; }); auto bcls = poutput->add_batch_classes(); for (size_t k = 0; k < class_cnt; ++k) { auto cls = bcls->add_cls(); cls->set_idx(idx[k]); const auto& label = label_provider->GetLabel(poutput->name(), idx[k]); cls->set_label(label); if (label == "" && !lookup_map.empty()) { auto it = lookup_map.find(poutput->name()); if (it != lookup_map.end()) { cls->set_label(it->second.second->GetLabel(it->second.first, idx[k])); } } cls->set_value(static_cast<float>(probs[idx[k]])); } probs += entry_cnt; } } } // namespace // // InferResponseProvider // InferResponseProvider::InferResponseProvider( const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider) : request_header_(request_header), label_provider_(label_provider) { // Create a map from output name to the InferRequestHeader::Output // object for that output. for (const InferRequestHeader::Output& output : request_header.output()) { output_map_.emplace(std::make_pair(output.name(), &output)); } } bool InferResponseProvider::RequiresOutput(const std::string& name) { return output_map_.find(name) != output_map_.end(); } Status InferResponseProvider::OutputBufferContents( const std::string& name, const void** content, size_t* content_byte_size) const { for (const auto& output : outputs_) { if ((name == output.name_) && (output.cls_count_ == 0)) { *content = output.ptr_; *content_byte_size = output.byte_size_; return Status::Success; } } return Status( RequestStatusCode::UNAVAILABLE, "request for unallocated output '" + name + "'"); } Status InferResponseProvider::CheckAndSetIfBufferedOutput( const std::string& name, void** content, size_t content_byte_size, const std::vector<int64_t>& content_shape, Output** output) { const auto& pr = output_map_.find(name); if (pr == output_map_.end()) { return Status( RequestStatusCode::INTERNAL, "unexpected output '" + name + "'"); } outputs_.emplace_back(); Output* loutput = &(outputs_.back()); loutput->name_ = name; loutput->shape_ = content_shape; loutput->cls_count_ = 0; loutput->ptr_ = nullptr; loutput->byte_size_ = content_byte_size; if (pr->second->has_cls()) { loutput->cls_count_ = pr->second->cls().count(); char* buffer = new char[content_byte_size]; *content = static_cast<void*>(buffer); loutput->ptr_ = static_cast<void*>(buffer); loutput->buffer_.reset(buffer); } *output = loutput; return Status::Success; } bool InferResponseProvider::GetSecondaryLabelProvider( const std::string& name, SecondaryLabelProvider* provider) { auto it = secondary_label_provider_map_.find(name); if (it != secondary_label_provider_map_.end()) { *provider = it->second; return true; } return false; } void InferResponseProvider::SetSecondaryLabelProvider( const std::string& name, const SecondaryLabelProvider& provider) { secondary_label_provider_map_[name] = provider; } Status InferResponseProvider::FinalizeResponse(const InferenceBackend& is) { InferResponseHeader* response_header = MutableResponseHeader(); response_header->Clear(); response_header->set_model_name(is.Name()); response_header->set_model_version(is.Version()); const size_t batch_size = request_header_.batch_size(); response_header->set_batch_size(batch_size); int output_idx = 0; for (const auto& output : outputs_) { const ModelOutput* output_config; RETURN_IF_ERROR(is.GetOutput(output.name_, &output_config)); // Verify that the actual output shape matches what is expected by // the model configuration. If there is an output reshape, we've // already verified that reshape and dims have same element count // so don't need to do that here. bool skip_batch = (is.Config().max_batch_size() != 0); DimsList batch1_backend_shape; size_t batch1_element_count = 1; for (auto d : output.shape_) { if (!skip_batch) { batch1_backend_shape.Add(d); batch1_element_count *= (size_t)d; } skip_batch = false; } const DimsList& expected_shape = (output_config->has_reshape()) ? output_config->reshape().shape() : output_config->dims(); if (!CompareDimsWithWildcard(expected_shape, batch1_backend_shape)) { return Status( RequestStatusCode::INVALID_ARG, "output '" + output.name_ + "' for model '" + is.Name() + "' has shape " + DimsListToString(batch1_backend_shape) + " but model configuration specifies shape " + DimsListToString(expected_shape)); } auto poutput = response_header->add_output(); poutput->set_name(output.name_); if (output.cls_count_ == 0) { // Raw result... poutput->mutable_raw()->Clear(); poutput->mutable_raw()->set_batch_byte_size(output.byte_size_); // If there is a reshape them we know that output_config dims // are non-variable so use them directly. If there is not a // reshape then use output shape as that will have actual sized // in place of any wildcard dimensions. if (output_config->has_reshape()) { poutput->mutable_raw()->mutable_dims()->CopyFrom(output_config->dims()); } else { poutput->mutable_raw()->mutable_dims()->CopyFrom(batch1_backend_shape); } } else { // Class result... switch (output_config->data_type()) { case DataType::TYPE_UINT8: AddClassResults<uint8_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_UINT16: AddClassResults<uint16_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_UINT32: AddClassResults<uint32_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_UINT64: AddClassResults<uint64_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_INT8: AddClassResults<int8_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_INT16: AddClassResults<int16_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_INT32: AddClassResults<int32_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_INT64: AddClassResults<int64_t>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_FP32: AddClassResults<float>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; case DataType::TYPE_FP64: AddClassResults<double>( poutput, output.buffer_.get(), batch1_element_count, batch_size, output.cls_count_, label_provider_, secondary_label_provider_map_); break; default: return Status( RequestStatusCode::INVALID_ARG, "class result not available for output '" + output.name_ + "' due to unsupported type '" + DataType_Name(output_config->data_type()) + "'"); } } output_idx++; } return Status::Success; } // // InternalInferResponseProvider // Status InternalInferResponseProvider::Create( const InferenceBackend& is, const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider, std::shared_ptr<InternalInferResponseProvider>* infer_provider) { auto provider = new InternalInferResponseProvider(request_header, label_provider); infer_provider->reset(provider); return Status::Success; } const InferResponseHeader& InternalInferResponseProvider::ResponseHeader() const { return response_header_; } InferResponseHeader* InternalInferResponseProvider::MutableResponseHeader() { return &response_header_; } Status InternalInferResponseProvider::AllocateOutputBuffer( const std::string& name, void** content, size_t content_byte_size, const std::vector<int64_t>& content_shape) { *content = nullptr; Output* output; RETURN_IF_ERROR(CheckAndSetIfBufferedOutput( name, content, content_byte_size, content_shape, &output)); // Always write output tensor to an output buffer no matter // if output has cls field defined auto it = output_buffer_.find(name); if (it == output_buffer_.end()) { it = output_buffer_ .emplace(std::make_pair( name, std::make_shared<AllocatedSystemMemory>(content_byte_size))) .first; } if (content_byte_size != it->second->TotalByteSize()) { return Status( RequestStatusCode::INVALID_ARG, "unexpected size " + std::to_string(it->second->TotalByteSize()) + " for output '" + name + "', expecting " + std::to_string(content_byte_size)); } *content = it->second->MutableBuffer(); output->ptr_ = *content; return Status::Success; } Status InternalInferResponseProvider::GetSystemMemory( const std::string& name, std::shared_ptr<SystemMemory>* output_buffer) { auto it = output_buffer_.find(name); if (it == output_buffer_.end()) { return Status( RequestStatusCode::INVALID_ARG, "output '" + name + "' is not found in response provider"); } *output_buffer = std::static_pointer_cast<SystemMemory>(it->second); return Status::Success; } InternalInferResponseProvider::InternalInferResponseProvider( const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider) : InferResponseProvider(request_header, label_provider) { } // // GRPCInferResponseProvider // Status GRPCInferResponseProvider::Create( const InferRequestHeader& request_header, InferResponse* response, const std::shared_ptr<LabelProvider>& label_provider, std::shared_ptr<GRPCInferResponseProvider>* infer_provider) { GRPCInferResponseProvider* provider = new GRPCInferResponseProvider(request_header, response, label_provider); infer_provider->reset(provider); return Status::Success; } const InferResponseHeader& GRPCInferResponseProvider::ResponseHeader() const { return response_->meta_data(); } InferResponseHeader* GRPCInferResponseProvider::MutableResponseHeader() { return response_->mutable_meta_data(); } Status GRPCInferResponseProvider::AllocateOutputBuffer( const std::string& name, void** content, size_t content_byte_size, const std::vector<int64_t>& content_shape) { Output* output; RETURN_IF_ERROR(CheckAndSetIfBufferedOutput( name, content, content_byte_size, content_shape, &output)); // Must always add a raw output into the list so that the number and // order of raw output entries equals the output meta-data. But // leave empty if not returning raw result for the output. std::string* raw_output = response_->add_raw_output(); if (output->ptr_ == nullptr) { raw_output->resize(content_byte_size); *content = static_cast<void*>(&((*raw_output)[0])); output->ptr_ = *content; } return Status::Success; } // // HTTPInferResponseProvider // HTTPInferResponseProvider::HTTPInferResponseProvider( evbuffer* output_buffer, const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider) : InferResponseProvider(request_header, label_provider), output_buffer_(output_buffer) { } Status HTTPInferResponseProvider::Create( evbuffer* output_buffer, const InferenceBackend& is, const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider, std::shared_ptr<HTTPInferResponseProvider>* infer_provider) { HTTPInferResponseProvider* provider = new HTTPInferResponseProvider( output_buffer, request_header, label_provider); infer_provider->reset(provider); return Status::Success; } const InferResponseHeader& HTTPInferResponseProvider::ResponseHeader() const { return response_header_; } InferResponseHeader* HTTPInferResponseProvider::MutableResponseHeader() { return &response_header_; } Status HTTPInferResponseProvider::AllocateOutputBuffer( const std::string& name, void** content, size_t content_byte_size, const std::vector<int64_t>& content_shape) { *content = nullptr; Output* output; RETURN_IF_ERROR(CheckAndSetIfBufferedOutput( name, content, content_byte_size, content_shape, &output)); if ((output->ptr_ == nullptr) && (content_byte_size > 0)) { // Reserve requested space in evbuffer... struct evbuffer_iovec output_iovec; if (evbuffer_reserve_space( output_buffer_, content_byte_size, &output_iovec, 1) != 1) { return Status( RequestStatusCode::INTERNAL, "failed to reserve " + std::to_string(content_byte_size) + " bytes in output tensor buffer"); } if (output_iovec.iov_len < content_byte_size) { return Status( RequestStatusCode::INTERNAL, "reserved " + std::to_string(output_iovec.iov_len) + " bytes in output tensor buffer, need " + std::to_string(content_byte_size)); } output_iovec.iov_len = content_byte_size; *content = output_iovec.iov_base; output->ptr_ = *content; // Immediately commit the buffer space. Some backends will write // async to the just allocated buffer space so we are relying on // evbuffer not to relocate this space. Because we request a // contiguous chunk every time (above by allowing only a single // entry in output_iovec), this seems to be a valid assumption. if (evbuffer_commit_space(output_buffer_, &output_iovec, 1) != 0) { *content = nullptr; output->ptr_ = nullptr; return Status( RequestStatusCode::INTERNAL, "failed to commit output tensors to output buffer"); } } return Status::Success; } // // DelegatingInferResponseProvider // Status DelegatingInferResponseProvider::Create( const InferRequestHeader& request_header, const std::shared_ptr<LabelProvider>& label_provider, std::shared_ptr<DelegatingInferResponseProvider>* infer_provider) { DelegatingInferResponseProvider* provider = new DelegatingInferResponseProvider(request_header, label_provider); infer_provider->reset(provider); return Status::Success; } const InferResponseHeader& DelegatingInferResponseProvider::ResponseHeader() const { return response_header_; } InferResponseHeader* DelegatingInferResponseProvider::MutableResponseHeader() { return &response_header_; } Status DelegatingInferResponseProvider::AllocateOutputBuffer( const std::string& name, void** content, size_t content_byte_size, const std::vector<int64_t>& content_shape) { *content = nullptr; Output* output; RETURN_IF_ERROR(CheckAndSetIfBufferedOutput( name, content, content_byte_size, content_shape, &output)); if ((output->buffer_ == nullptr) && (content_byte_size > 0)) { char* buffer = new char[content_byte_size]; *content = static_cast<void*>(buffer); output->ptr_ = static_cast<void*>(buffer); output->buffer_.reset(buffer); } return Status::Success; } }} // namespace nvidia::inferenceserver
31.422604
80
0.685276
[ "object", "shape", "vector", "model" ]
3cae518efd678e131132150d8dcc9e78a78f216a
4,960
hpp
C++
ThirdParty-mod/java2cpp/java/security/InvalidAlgorithmParameterException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/security/InvalidAlgorithmParameterException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/security/InvalidAlgorithmParameterException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.security.InvalidAlgorithmParameterException ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_DECL #define J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Throwable; } } } namespace j2cpp { namespace java { namespace security { class GeneralSecurityException; } } } #include <java/lang/String.hpp> #include <java/lang/Throwable.hpp> #include <java/security/GeneralSecurityException.hpp> namespace j2cpp { namespace java { namespace security { class InvalidAlgorithmParameterException; class InvalidAlgorithmParameterException : public object<InvalidAlgorithmParameterException> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) explicit InvalidAlgorithmParameterException(jobject jobj) : object<InvalidAlgorithmParameterException>(jobj) { } operator local_ref<java::security::GeneralSecurityException>() const; InvalidAlgorithmParameterException(local_ref< java::lang::String > const&); InvalidAlgorithmParameterException(); InvalidAlgorithmParameterException(local_ref< java::lang::String > const&, local_ref< java::lang::Throwable > const&); InvalidAlgorithmParameterException(local_ref< java::lang::Throwable > const&); }; //class InvalidAlgorithmParameterException } //namespace security } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_IMPL #define J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_IMPL namespace j2cpp { java::security::InvalidAlgorithmParameterException::operator local_ref<java::security::GeneralSecurityException>() const { return local_ref<java::security::GeneralSecurityException>(get_jobject()); } java::security::InvalidAlgorithmParameterException::InvalidAlgorithmParameterException(local_ref< java::lang::String > const &a0) : object<java::security::InvalidAlgorithmParameterException>( call_new_object< java::security::InvalidAlgorithmParameterException::J2CPP_CLASS_NAME, java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_NAME(0), java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } java::security::InvalidAlgorithmParameterException::InvalidAlgorithmParameterException() : object<java::security::InvalidAlgorithmParameterException>( call_new_object< java::security::InvalidAlgorithmParameterException::J2CPP_CLASS_NAME, java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_NAME(1), java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_SIGNATURE(1) >() ) { } java::security::InvalidAlgorithmParameterException::InvalidAlgorithmParameterException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Throwable > const &a1) : object<java::security::InvalidAlgorithmParameterException>( call_new_object< java::security::InvalidAlgorithmParameterException::J2CPP_CLASS_NAME, java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_NAME(2), java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_SIGNATURE(2) >(a0, a1) ) { } java::security::InvalidAlgorithmParameterException::InvalidAlgorithmParameterException(local_ref< java::lang::Throwable > const &a0) : object<java::security::InvalidAlgorithmParameterException>( call_new_object< java::security::InvalidAlgorithmParameterException::J2CPP_CLASS_NAME, java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_NAME(3), java::security::InvalidAlgorithmParameterException::J2CPP_METHOD_SIGNATURE(3) >(a0) ) { } J2CPP_DEFINE_CLASS(java::security::InvalidAlgorithmParameterException,"java/security/InvalidAlgorithmParameterException") J2CPP_DEFINE_METHOD(java::security::InvalidAlgorithmParameterException,0,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::security::InvalidAlgorithmParameterException,1,"<init>","()V") J2CPP_DEFINE_METHOD(java::security::InvalidAlgorithmParameterException,2,"<init>","(Ljava/lang/String;Ljava/lang/Throwable;)V") J2CPP_DEFINE_METHOD(java::security::InvalidAlgorithmParameterException,3,"<init>","(Ljava/lang/Throwable;)V") } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_INVALIDALGORITHMPARAMETEREXCEPTION_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
35.428571
176
0.770968
[ "object" ]
3cb10066768e74335612ea7d76c6c34f5f03c4ec
2,903
cpp
C++
11_unterricht/sampleGraph/main.cpp
theroyalcoder/HF-ICT-3-SEM-AAD
2dfa964b890199c1097e0c72c8abd68f1703cb29
[ "MIT" ]
null
null
null
11_unterricht/sampleGraph/main.cpp
theroyalcoder/HF-ICT-3-SEM-AAD
2dfa964b890199c1097e0c72c8abd68f1703cb29
[ "MIT" ]
null
null
null
11_unterricht/sampleGraph/main.cpp
theroyalcoder/HF-ICT-3-SEM-AAD
2dfa964b890199c1097e0c72c8abd68f1703cb29
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; class SampleGraph { public: static vector<int>* create(int numberOfNodes, int numberOfConnections, bool isDirected); static void print(vector<int>* graph, int numberOfNodes); }; //<-- --> vector<int>* SampleGraph::create(int numberOfNodes, int numberOfConnections, bool isDirected=false) { auto * result = new vector<int>[numberOfNodes]; int counter = 0; while (counter < numberOfConnections) { int source = rand() % numberOfNodes; int target = rand() % numberOfNodes; if (source != target) { if (find(result[source].begin(), result[source].end(), target) == result[source].end()) { result[source].push_back(target); if(!isDirected) result[target].push_back(source); counter++; } } } for (int i=0; i<numberOfNodes; i++) { sort(result[i].begin(), result[i].end()); } return result; } //<-- --> void SampleGraph::print(vector<int>* graph, int numberOfNodes) { for (int i=0; i<numberOfNodes; i++) { vector<int>::iterator it; cout << "Node " << i << "\t"; for (it=graph[i].begin(); it!=graph[i].end(); it++) { cout << *it << ", "; } cout << endl; } } //<-- Tiefensuche --> void dfs(vector<int>* graph, int numberOfNodes, bool *visited, int currentNode) { visited[currentNode] = true; cout << currentNode << ","; for(auto node : graph[currentNode]){ if(!visited[node]){ dfs(graph,numberOfNodes,visited,node); } } } void dfs(vector<int>* graph, int numberOfNodes) { auto *visited = new bool[numberOfNodes]{false}; dfs(graph, numberOfNodes, visited, 0); } /////////////////////////////////////////////////////////////////////////// void bfs(vector<int>* graph, int numberOfNodes, bool *visited, int currentNode) { visited[currentNode] = true; cout << currentNode << ","; for(auto node : graph[currentNode]) { if (!visited[node]) { bfs(graph, numberOfNodes, visited, node); bfs(graph, numberOfNodes, visited, node); } } } //<-- Breitensuche alle Nachbarn suchen --> void bfs(vector<int>* graph, int numberOfNodes) { auto *visited = new bool[numberOfNodes]{false}; bfs(graph, numberOfNodes, visited, 0); } //<-- --> bool connected(vector<int>* graph, int numberOfNodes, int nodeA, int nodeB) { return false; } int main() { srand(15); const int NUMBER_OF_NODES = 7; const int NUMBER_OF_CONNECTIONS = 12; vector<int>* graph = SampleGraph::create(NUMBER_OF_NODES, NUMBER_OF_CONNECTIONS); SampleGraph::print(SampleGraph::create(NUMBER_OF_NODES, NUMBER_OF_CONNECTIONS), NUMBER_OF_NODES); dfs(graph,NUMBER_OF_NODES); return 0; }
25.243478
101
0.591802
[ "vector" ]
3cb7b4c1e3ca3d325bbb2f98e8a3398fab8a17b0
4,126
cpp
C++
tests/SamplePatternDictionaryTest.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
54
2016-04-05T17:45:19.000Z
2022-01-31T06:27:33.000Z
tests/SamplePatternDictionaryTest.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
25
2016-03-18T04:01:06.000Z
2020-06-27T15:39:35.000Z
tests/SamplePatternDictionaryTest.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
50
2016-03-03T20:31:58.000Z
2022-03-31T18:26:13.000Z
/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkPoint.h" #include "include/core/SkTypes.h" #include "include/utils/SkRandom.h" #include "tests/Test.h" #include <vector> #if SK_SUPPORT_GPU #include "src/gpu/GrSamplePatternDictionary.h" static SkTArray<SkPoint> make_sample_pattern(const std::vector<SkPoint>& sampleLocations) { return SkTArray<SkPoint>(sampleLocations.data(), sampleLocations.size()); } static SkTArray<SkPoint> make_random_sample_pattern(SkRandom* rand) { SkTArray<SkPoint> pattern; int count = rand->nextULessThan(20) + 1; pattern.reset(count); for (int i = 0; i < count; ++i) { pattern[i] = SkPoint::Make(rand->nextF(), rand->nextF()); } return pattern; } // This test ensures that the sample pattern dictionary caches and retrieves patterns correctly. DEF_TEST(SamplePatternDictionary, reporter) { SkTArray<SkTArray<SkPoint>> testPatterns; testPatterns.push_back() = make_sample_pattern({ // Intel on mac, msaa8, offscreen. {0.562500, 0.312500}, {0.437500, 0.687500}, {0.812500, 0.562500}, {0.312500, 0.187500}, {0.187500, 0.812500}, {0.062500, 0.437500}, {0.687500, 0.937500}, {0.937500, 0.062500} }); testPatterns.push_back() = make_sample_pattern({ // Intel on mac, msaa8, on-screen. {0.562500, 0.687500}, {0.437500, 0.312500}, {0.812500, 0.437500}, {0.312500, 0.812500}, {0.187500, 0.187500}, {0.062500, 0.562500}, {0.687500, 0.062500}, {0.937500, 0.937500} }); testPatterns.push_back() = make_sample_pattern({ // NVIDIA, msaa16. {0.062500, 0.000000}, {0.250000, 0.125000}, {0.187500, 0.375000}, {0.437500, 0.312500}, {0.500000, 0.062500}, {0.687500, 0.187500}, {0.750000, 0.437500}, {0.937500, 0.250000}, {0.000000, 0.500000}, {0.312500, 0.625000}, {0.125000, 0.750000}, {0.375000, 0.875000}, {0.562500, 0.562500}, {0.812500, 0.687500}, {0.625000, 0.812500}, {0.875000, 0.937500} }); testPatterns.push_back() = make_sample_pattern({ // NVIDIA, mixed samples, 16:1. {0.250000, 0.125000}, {0.625000, 0.812500}, {0.500000, 0.062500}, {0.812500, 0.687500}, {0.187500, 0.375000}, {0.875000, 0.937500}, {0.125000, 0.750000}, {0.750000, 0.437500}, {0.937500, 0.250000}, {0.312500, 0.625000}, {0.437500, 0.312500}, {0.000000, 0.500000}, {0.375000, 0.875000}, {0.687500, 0.187500}, {0.062500, 0.000000}, {0.562500, 0.562500} }); SkRandom rand; for (int i = 0; i < 23; ++i) { testPatterns.push_back(make_random_sample_pattern(&rand)); } // Duplicate the initial 4 patterns, with slight differences. testPatterns.push_back(testPatterns[0]); testPatterns.back().back().fX += 0.001f; testPatterns.push_back(testPatterns[1]); testPatterns.back().back().fY -= 0.002f; testPatterns.push_back(testPatterns[2]); testPatterns.back().push_back(SkPoint::Make(.5f, .5f)); testPatterns.push_back(testPatterns[3]); testPatterns.back().pop_back(); for (int i = 0; i < 13; ++i) { testPatterns.push_back(make_random_sample_pattern(&rand)); } GrSamplePatternDictionary dict; for (int i = 0; i < 2; ++i) { for (int j = 0; j < testPatterns.count(); ++j) { for (int k = 0; k < 3; ++k) { const SkTArray<SkPoint>& pattern = testPatterns[testPatterns.count() - j - 1]; REPORTER_ASSERT(reporter, j == dict.findOrAssignSamplePatternKey(pattern)); } } } for (int j = 0; j < testPatterns.count(); ++j) { const SkTArray<SkPoint>& pattern = testPatterns[testPatterns.count() - j - 1]; REPORTER_ASSERT(reporter, dict.retrieveSampleLocations(j) == pattern); } } #endif
31.022556
96
0.592341
[ "vector" ]
3cb9c6014085373f7df9c124f7e781eee1df7852
14,699
cpp
C++
Compiler/src/Lexer.cpp
BrandonKi/ATN
68e047132ae5bbc26379ea63b423de4e4974f0fe
[ "MIT" ]
null
null
null
Compiler/src/Lexer.cpp
BrandonKi/ATN
68e047132ae5bbc26379ea63b423de4e4974f0fe
[ "MIT" ]
null
null
null
Compiler/src/Lexer.cpp
BrandonKi/ATN
68e047132ae5bbc26379ea63b423de4e4974f0fe
[ "MIT" ]
null
null
null
#include "Lexer.h" extern ErrorHandler error_log; extern TypeManager type_manager; Lexer::Lexer(const std::string& filename, const char* filedata, size_t filedata_size): filename_(filename), data_(filedata), data_size(filedata_size), tokens_(), index_(0), line_(1), col_(1) { PROFILE(); tokens_.reserve(100); } std::vector<Token> Lexer::lex() { PROFILE(); while(index_ < data_size) { switch(current_char()) { CASE_DIGIT: tokens_.push_back(lex_number_lit()); break; CASE_ID: tokens_.push_back(lex_identifier()); break; case '\'': case '"': tokens_.push_back(lex_string()); break; case '`': //TODO interpolated string literal is not trivial to tokenize tokens_.push_back(lex_interpolated_string()); break; case '{': tokens_.push_back(create_token(ARC_OPEN_BRACE, index_)); break; case '}': tokens_.push_back(create_token(ARC_CLOSE_BRACE, index_)); break; case '[': tokens_.push_back(create_token(ARC_OPEN_BRACKET, index_)); break; case ']': tokens_.push_back(create_token(ARC_CLOSE_BRACKET, index_)); break; case '(': tokens_.push_back(create_token(ARC_OPEN_PAREN, index_)); break; case ')': tokens_.push_back(create_token(ARC_CLOSE_PAREN, index_)); break; case '.': tokens_.push_back(create_token(ARC_DOT, index_)); break; case ',': tokens_.push_back(create_token(ARC_COMMA, index_)); break; case '?': tokens_.push_back(create_token(ARC_TERNARY, index_)); break; case ';': tokens_.push_back(create_token(ARC_SEMICOLON, index_)); break; case ':': tokens_.push_back(lex_colon()); break; case '@': tokens_.push_back(create_token(ARC_AT, index_)); break; case '#': tokens_.push_back(lex_hash()); break; case '$': tokens_.push_back(create_token(ARC_DOLLAR, index_)); break; case '+': tokens_.push_back(lex_add()); break; case '-': tokens_.push_back(lex_sub()); break; case '/': if(peek_next_char() == '/' || peek_next_char() == '*') consume_comment(); else tokens_.push_back(lex_div()); break; case '*': tokens_.push_back(lex_mul()); break; case '%': tokens_.push_back(lex_mod()); break; case '|': tokens_.push_back(lex_or()); break; case '&': tokens_.push_back(lex_and()); break; case '!': tokens_.push_back(lex_not()); break; case '^': tokens_.push_back(lex_xor()); break; case '<': tokens_.push_back(lex_lesser()); break; case '>': tokens_.push_back(lex_greater()); break; case '=': tokens_.push_back(lex_equal()); break; case '\n': line_++; col_ = 0; break; default: break; } next_char_noreturn(); } if(args.lex_out) print_tokens(args.verbose_lex_out); // true for verbose and false for succinct tokens_.push_back(create_token(ARC_EOF, col_, index_)); return std::move(tokens_); // not a big deal but there is no reason to make an extra copy } void Lexer::consume_comment() { PROFILE(); if(next_char() == '*') { next_char_noreturn(); while(index_ < data_size && !(current_char() == '*' && peek_next_char() == '/')){ if(current_char() == '\n') ++line_; next_char_noreturn(); } next_char_noreturn(); } else { while(index_ < data_size && current_char() != '\n'){ next_char_noreturn(); } ++line_; } } Token Lexer::lex_number_lit() { PROFILE(); const auto start_pos = index_; const auto current_col = col_; auto is_float = false; auto is_int = true; if(peek_next_char() == 'x') { //TODO implement hex literal lexing next_char_noreturn(); is_int = false; is_float = false; } while(is_digit(current_char())) { //TODO refactor if(peek_next_char() == '.') { // if(isFloat) //TODO print error message because two "." are present in number literal is_float = true; is_int = false; } next_char_noreturn(); } std::string_view literal{ data_ + start_pos, index_ - start_pos }; prev_char_noreturn(); // the above loop goes one char too far so decrement here if(is_int) return create_token(ARC_INT_LIT, current_col, start_pos, literal); else if(is_float) return create_token(ARC_FLOAT_LIT, current_col, start_pos, literal); else { //TODO convert hex literal to int or float literal return create_token(ARC_INT_LIT, current_col, start_pos, literal); } } Token Lexer::lex_identifier() { PROFILE(); const auto start_pos = index_; const auto current_col = col_; while(is_letter(current_char()) || is_digit(current_char())) { next_char_noreturn(); } // prev_char_noreturn(); // the above loop goes one char too far so decrement here std::string_view id { data_ + start_pos, index_ - start_pos }; prev_char_noreturn(); if(keywords.find(id) != keywords.end()) return create_token(keywords.find(id)->second, current_col, start_pos); return create_token(ARC_ID, current_col, start_pos, id); } Token Lexer::lex_string() { //TODO escape sequences PROFILE(); const auto start_pos = index_; // current_char is either " or ' const auto end = current_char(); while(next_char() != end) { } std::string_view literal { data_ + start_pos, index_ - start_pos }; return create_token(ARC_STRING_LIT, start_pos, literal); } Token Lexer::lex_interpolated_string() { //TODO implement interpolated strings PROFILE(); // FIXME const auto start_pos = index_; const auto start_col = col_; while(next_char() != '`'); auto tkn = create_token(ARC_STRING_LIT, start_col, start_pos); error_log.exit(ErrorMessage{FATAL, tkn.pos, filename_, std::string("interpolated strings are not implemented yet")}); return Token{}; } Token Lexer::lex_colon() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_INFER, start_col, start_pos); } else return create_token(ARC_COLON, start_pos); } Token Lexer::lex_hash() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '<') { next_char_noreturn(); return create_token(ARC_POLY_START, start_col, start_pos); } else return create_token(ARC_HASH, start_col, start_pos); } inline Token Lexer::lex_add() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_ADD_EQUAL, start_col, start_pos); } else if(peek_next_char() == '+') { next_char_noreturn(); if(tokens_.back().kind == ARC_ID) return create_token(ARC_POST_INCREMENT, start_col, start_pos); return create_token(ARC_PRE_INCREMENT, start_col, start_pos); } else return create_token(ARC_ADD, start_pos); } Token Lexer::lex_sub() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_SUB_EQUAL, start_col, start_pos); } else if(peek_next_char() == '-') { next_char_noreturn(); if(!tokens_.empty() && tokens_.back().kind == ARC_ID) // FIXME incorrectly lexes some cases for ex. "4--", "*--4", etc. return create_token(ARC_POST_DECREMENT, start_col, start_pos); return create_token(ARC_PRE_DECREMENT, start_col, start_pos); } else { if(tokens_.empty() || is_operator(tokens_.back().kind) || is_keyword(tokens_.back().kind)) return create_token(ARC_NEGATE, start_pos); return create_token(ARC_SUB, start_pos); // FIXME doesn't even attempt to parse a unary sub } } Token Lexer::lex_div() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_DIV_EQUAL, start_col, start_pos); } else return create_token(ARC_DIV, start_pos); } Token Lexer::lex_mul() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_MUL_EQUAL, start_col, start_pos); } else return create_token(ARC_MUL, start_pos); } Token Lexer::lex_mod() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_MOD_EQUAL, start_col, start_pos); } else return create_token(ARC_MOD, start_pos); } Token Lexer::lex_or() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_OR_EQUAL, start_col, start_pos); } else if(peek_next_char() == '|'){ next_char_noreturn(); return create_token(ARC_LOGICAL_OR, start_col, start_pos); } else return create_token(ARC_BIN_OR, start_pos); } Token Lexer::lex_and() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_AND_EQUAL, start_col, start_pos); } else if(peek_next_char() == '&') { next_char_noreturn(); return create_token(ARC_LOGICAL_AND, start_col, start_pos); } else return create_token(ARC_BIN_AND, start_pos); } Token Lexer::lex_not() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_NOT_EQUAL, start_col, start_pos); } else return create_token(ARC_NOT, start_pos); } Token Lexer::lex_xor(){ PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_XOR_EQUAL, start_col, start_pos); } else return create_token(ARC_XOR, start_pos); } Token Lexer::lex_lesser() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_LESSER_EQUAL, start_col, start_pos); } else if(peek_next_char() == '<') { next_char_noreturn(); return create_token(ARC_LEFT_SHIFT, start_col, start_pos); } else return create_token(ARC_LESSER, start_pos); } Token Lexer::lex_greater() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_GREATER_EQUAL, start_col, start_pos); } else if(peek_next_char() == '>') { next_char_noreturn(); return create_token(ARC_RIGHT_SHIFT, start_col, start_pos); } else return create_token(ARC_GREATER, start_pos); } Token Lexer::lex_equal() { PROFILE(); const auto start_pos = index_; const auto start_col = col_; if(peek_next_char() == '=') { next_char_noreturn(); return create_token(ARC_EQUAL, start_col, start_pos); } else return create_token(ARC_ASSIGN, start_pos); } inline char Lexer::current_char() const { return data_[index_]; } inline char Lexer::next_char() { col_++; return data_[++index_]; } inline char Lexer::prev_char() { col_--; return data_[--index_]; } inline void Lexer::next_char_noreturn() { col_++; index_++; } inline void Lexer::prev_char_noreturn() { col_--; index_--; } inline char Lexer::peek_next_char() const { return data_[index_+1]; } inline char Lexer::peek_prev_char() const { return data_[index_ - 1]; } inline Token Lexer::create_token(const TokenKind kind, const u32 start_pos) const { PROFILE(); return Token {kind, SourcePos{line_, col_, start_pos, index_}, std::string_view{}}; } inline Token Lexer::create_token(const TokenKind kind, const u32 current_col, const u32 start_pos) const { PROFILE(); return Token {kind, SourcePos{line_, current_col, start_pos, index_}, std::string_view{}}; } inline Token Lexer::create_token(const TokenKind kind, const u32 start_pos, std::string_view val) const { PROFILE(); return create_token(kind, col_, start_pos, val); } inline Token Lexer::create_token(const TokenKind kind, const u32 current_col, const u32 start_pos, std::string_view val) const { PROFILE(); return Token {kind, SourcePos{line_, current_col, start_pos, index_}, val}; } inline void Lexer::print_tokens(const bool verbose) const { PROFILE(); if(verbose) for(const auto& tkn : tokens_) println_token(&tkn); else { for(const auto& tkn : tokens_) if(tkn.data.empty()) println(TokenKind2String(tkn.kind) + ": " + get_string(tkn.kind)); else println(TokenKind2String(tkn.kind) + ": " + std::string(tkn.data)); } }
28.105163
129
0.58208
[ "vector" ]
3cc20ef5a8dc6846eb9eefd66b54d01b960f9d3f
16,502
cpp
C++
source/code/scxcorelib/pal/scxthread.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
37
2016-04-14T20:06:15.000Z
2019-05-06T17:30:17.000Z
source/code/scxcorelib/pal/scxthread.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
37
2016-03-11T20:47:11.000Z
2019-04-01T22:53:04.000Z
source/code/scxcorelib/pal/scxthread.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
20
2016-05-26T23:53:01.000Z
2019-05-06T08:54:08.000Z
/*-------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information. */ /** \file \brief Implements the thread handling PAL. \date 2007-06-19 14:00:00 */ /*----------------------------------------------------------------------------*/ #include <scxcorelib/scxcmn.h> #include <scxcorelib/scxthread.h> #include <scxcorelib/stringaid.h> #include <scxcorelib/scxstream.h> #include <sstream> #if defined(WIN32) #elif defined(SCX_UNIX) #include <errno.h> #include <signal.h> #include <unistd.h> #else #error "Platform not implemented" #endif namespace SCXCoreLib { /*----------------------------------------------------------------------------*/ /** A thread param structure used to start threads. This is the parameter sent to the starting thread. This structure is only used in this file. */ struct ThreadStartParams { ThreadStartParams() : body(0), param(0) {} SCXThreadProc body; //!< Pointer to thread body function. SCXThreadParamHandle param; //!< Pointer to thread parameters. }; /*----------------------------------------------------------------------------*/ /** Thread entry point. \param param A ThreadStartParams structure with the actual thread procedure and parameters. \returns Zero All threads started using this PAL are started using this method. */ static #if defined(WIN32) DWORD WINAPI _InternalThreadStartRoutine(void* param) #elif defined(SCX_UNIX) void* _InternalThreadStartRoutine(void* param) #endif { ThreadStartParams* p = static_cast<ThreadStartParams*>(param); SCXASSERT(p != 0); if (p->body != 0) { #if !defined(_DEBUG) try { p->body( p->param ); } catch (const SCXException& e1) { SCXASSERTFAIL(std::wstring(L"ThreadStartRoutine() Thread threw unhandled exception - "). append(e1.What()).append(L" - ").append(e1.Where()).c_str()); } catch (const std::exception& e2) { SCXASSERTFAIL(std::wstring(L"ThreadStartRoutine() Thread threw unhandled exception - "). append(StrFromUTF8(e2.what())).c_str()); } #else p->body( p->param ); #endif /* We would like to catch (...) as well but it seemes we can't since there is a bug in gcc. http://gcc.gnu.org/bugzilla/show_bug.cgi?id=28145 */ } delete p; return 0; } } extern "C" { static void* ThreadStartRoutine(void* param) { return SCXCoreLib::_InternalThreadStartRoutine(param); } } namespace SCXCoreLib { /*----------------------------------------------------------------------------*/ /** Default constructor. */ SCXThreadParam::SCXThreadParam() { m_terminateFlag = false; m_lock = ThreadLockHandleGet(); m_stringValues.clear(); } /*----------------------------------------------------------------------------*/ /** Virtual destructor. */ SCXThreadParam::~SCXThreadParam() { m_stringValues.clear(); } /*----------------------------------------------------------------------------*/ /** Dump object as string (for logging). \returns Object represented as string for logging. */ const std::wstring SCXThreadParam::DumpString() const { return L"SCXThreadParam: " + SCXCoreLib::StrFrom(static_cast<unsigned int>(m_stringValues.size())); } /*----------------------------------------------------------------------------*/ /** Retrieve a thread parameter string value. \param[in] key name of the parameter string value to retrieve \returns A parameter string. \throws SCXInvalidThreadParamValueException if the given key does not exist. */ const std::wstring& SCXThreadParam::GetString(const std::wstring& key) const { SCXThreadLock lock(m_lock); std::map<std::wstring, std::wstring>::const_iterator cv = m_stringValues.find(key); if (cv != m_stringValues.end()) { return cv->second; } lock.Unlock(); // If no value found, raise an exception. throw SCXInvalidThreadParamValueException(key, SCXSRCLOCATION); } /*----------------------------------------------------------------------------*/ /** Set a string value. \param[in] key name of the parameter value \param[in] value value to set. Sets a string parameter value. */ void SCXThreadParam::SetString(const std::wstring& key, const std::wstring& value) { SCXThreadLock lock(m_lock); m_stringValues[key] = value; } /*----------------------------------------------------------------------------*/ /** Default constructor. */ SCXThread::SCXThread() : m_threadID(0) , m_paramHandle(0) #if defined(WIN32) , m_threadHandle(new HANDLE(INVALID_HANDLE_VALUE)) #endif , m_threadMaySurviveDestruction(true) { } /*----------------------------------------------------------------------------*/ /** Start a new thread constructor. \param proc thread entry point \param param thread parameters (default: 0) \param attr thread creation parameters (default: 0) Uses SCXThread::Start to actually start the thread. \note This constructor takes ownership of the given param argument and will delete it once the thread exits. The reason for this is that this is a convenience method to be used instead of the constructor taking a SCXThreadParamHandle. */ SCXThread::SCXThread(SCXThreadProc proc, SCXThreadParam* param /* = 0 */, const SCXThreadAttr* attr /*= 0*/) : m_threadID(0) , m_paramHandle(0) #if defined(WIN32) , m_threadHandle(new HANDLE(INVALID_HANDLE_VALUE)) #endif , m_threadMaySurviveDestruction(true) { Start(proc, param, attr); } /*----------------------------------------------------------------------------*/ /** Start a new thread constructor. \param proc thread entry point \param param thread parameters handle (reference counted) \param attr thread creation parameters (default: 0) Uses SCXThread::Start to actually start the thread. */ SCXThread::SCXThread(SCXThreadProc proc, const SCXThreadParamHandle& param, const SCXThreadAttr* attr /*= 0*/) : m_threadID(0) , m_paramHandle(new SCXThreadParam()) #if defined(WIN32) , m_threadHandle(new HANDLE(INVALID_HANDLE_VALUE)) #endif , m_threadMaySurviveDestruction(true) { Start(proc, param, attr); } /*----------------------------------------------------------------------------*/ /** Helper to start new thread. \param proc thread entry point \param attr thread creation parameters \throws SCXThreadStartException if unable to start a new thread. */ void SCXThread::SCXThreadStartHelper(SCXThreadProc proc, const SCXThreadAttr* attr) { SCXASSERT(0 != m_paramHandle.GetData()); ThreadStartParams* p = new ThreadStartParams; SCXASSERT( NULL != p ); p->body = proc; p->param = m_paramHandle; #if defined(WIN32) *m_threadHandle = CreateThread(NULL, 0, static_cast<LPTHREAD_START_ROUTINE>(ThreadStartRoutine), p, 0, &m_threadID); if (NULL == *m_threadHandle) { *m_threadHandle = INVALID_HANDLE_VALUE; throw SCXThreadStartException(L"CreateThread failed", SCXSRCLOCATION); } #elif defined(SCX_UNIX) int pth_errno; if (0 != (pth_errno = pthread_create(&m_threadID, *attr, ThreadStartRoutine, p))) { throw SCXThreadStartException(SCXCoreLib::StrAppend(L"pthread_create failed, errno=", pth_errno), SCXSRCLOCATION); } #endif } /*----------------------------------------------------------------------------*/ /** Virtual destructor. */ SCXThread::~SCXThread() { #if defined(SCX_UNIX) if (m_threadMaySurviveDestruction) { if (m_threadID != 0) { // Detach the thread to reclaim thread resources automatically. (void)pthread_detach(m_threadID); } } else { // Could only have happened if "Terminate" or "Wait" was called, // therefore no need to terminate the thread here, also // the resources have been reclaimed by pthread_join } #endif #if defined(WIN32) if (INVALID_HANDLE_VALUE != *m_threadHandle) { CloseHandle(*m_threadHandle); *m_threadHandle = INVALID_HANDLE_VALUE; } #endif } /*----------------------------------------------------------------------------*/ /** Dump object as string (for logging). \returns Object represented as string for logging. */ const std::wstring SCXThread::DumpString() const { #if defined(macos) // http://www.webservertalk.com/archive107-2006-7-1577906.html // A pthread_t is only guaranteed to be an arithmetic type - not an // unsigned long int. (it's not uncommon for pthread_t to be a pointer type.) return SCXCoreLib::StrAppend(L"SCXThread: ", reinterpret_cast<scxulong>(m_threadID)); #else return SCXCoreLib::StrAppend(L"SCXThread: ", static_cast<scxulong>(m_threadID)); #endif } /*----------------------------------------------------------------------------*/ /** Thread starter. \param proc thread entry point \param param thread parameters (default: none. Must be specified. May be NULL.) \param attr thread creation parameters (default: 0) \throws SCXThreadStartException if thread could not be started. Uses SCXThread::SCXThreadStartHelper to actually start the thread. \note This method takes ownership of the given param argument and will delete it once the thread exits. The reason for this is that this is a convenience method to be used instead of the method taking a SCXThreadParamHandle. */ void SCXThread::Start(SCXThreadProc proc, SCXThreadParam* param /*= 0*/, const SCXThreadAttr* attr /*= 0*/) { SCXThreadParam* p = param; if (0 == p) { p = new SCXThreadParam(); } SCXThreadParamHandle h(p); Start(proc, h, attr); } /*----------------------------------------------------------------------------*/ /** Thread starter \param proc thread entry point \param param thread parameters handle (reference counted) \param attr thread creation parameters (default: 0) \throws SCXThreadStartException if thread could not be started. Uses SCXThread::SCXThreadStartHelper to actually start the thread. */ void SCXThread::Start(SCXThreadProc proc, const SCXThreadParamHandle& param, const SCXThreadAttr* attr /*= 0*/) { if (0 != m_threadID) { throw SCXThreadStartException(L"Thread already started", SCXSRCLOCATION); } m_paramHandle = param; if (attr == 0) { SCXThreadAttr attr_temp; SCXThreadStartHelper(proc, &attr_temp); } else { SCXThreadStartHelper(proc, attr); } } /*----------------------------------------------------------------------------*/ /** Retrive the thread ID. \returns SCXThreadId of the thread. */ SCXThreadId SCXThread::GetThreadID() const { return m_threadID; } /*----------------------------------------------------------------------------*/ /** Retrive the thread params. \returns SCXThreadParamHandle the thread is using. */ SCXThreadParamHandle& SCXThread::GetThreadParam() { return m_paramHandle; } /*----------------------------------------------------------------------------*/ /** Determine if a thread is alive or not. \returns true if the thread is still active, otherwise false. \note If thread IDs are reused by the underlaying platform and a new thread is started with the same ID, this function may return true because the new thread is active while the original thread is dead. */ bool SCXThread::IsAlive() const { bool r = false; #if defined(WIN32) if (INVALID_HANDLE_VALUE != *m_threadHandle) { DWORD ec = STILL_ACTIVE; if (GetExitCodeThread(*m_threadHandle, &ec)) { if (STILL_ACTIVE == ec) { r = true; } } } #elif defined(SCX_UNIX) if (m_threadID != 0 && 0 == pthread_kill(m_threadID, 0)) { r = true; } #endif return r; } /*----------------------------------------------------------------------------*/ /** Request a thread to terminate. \note This is NOT a forced termination. The thread must support this in the thread procedure by polling the parameter terminate flag. */ void SCXThread::RequestTerminate() { SCXASSERT(0 != m_paramHandle.GetData()); // Signal the thread to shut down SCXConditionHandle h(m_paramHandle->m_cond); m_paramHandle->SetTerminateFlag(); SCXASSERT( true == m_paramHandle->GetTerminateFlag() ); h.Signal(); } /*----------------------------------------------------------------------------*/ /** Wait for the thread to complete execution. \throws SCXInternalErrorException if unable to wait for thread termination. \note There is no need to "Wait" for all threads to remove resources allocated by the thread. This is merely a convenience function to make sure a certain thread has completed. */ void SCXThread::Wait() { m_threadMaySurviveDestruction = false; #if defined(WIN32) if (INVALID_HANDLE_VALUE != *m_threadHandle) { DWORD r = WaitForSingleObject(*m_threadHandle, INFINITE); SCXASSERT(WAIT_OBJECT_0 == r); if (WAIT_OBJECT_0 != r) { throw SCXCoreLib::SCXInternalErrorException(L"WaitForSingleObject did not return WAIT_OBJECT_0", SCXSRCLOCATION); } } #elif defined(SCX_UNIX) if (0 != m_threadID) { int retval = pthread_join(m_threadID, 0); if (retval) { throw SCXCoreLib::SCXErrnoException(L"pthread_join did not succeed", retval, SCXSRCLOCATION); } m_threadID = 0; } #endif } /*----------------------------------------------------------------------------*/ /** Pause (sleep) the calling thread for at least given number of milliseconds. \param[in] milliseconds number of milliseconds to sleep. */ void SCXThread::Sleep(scxulong milliseconds) { #if defined(WIN32) ::Sleep(static_cast<DWORD>(milliseconds)); #elif defined(SCX_UNIX) struct timespec rqtp; rqtp.tv_sec = static_cast<long>(milliseconds/1000); rqtp.tv_nsec = static_cast<long>((milliseconds%1000)*1000*1000); nanosleep(&rqtp, NULL); #else #error "Platform not implemented" #endif } /*----------------------------------------------------------------------------*/ /** Retrieve the calling threads, thread id. \returns SCXThreadId of the calling thread. */ SCXThreadId SCXThread::GetCurrentThreadID() { #if defined(WIN32) return GetCurrentThreadId(); #elif defined(SCX_UNIX) return pthread_self(); #else #error "Platform not implemented" #endif } } /* namespace SCXCoreLib */ /*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/
30.278899
129
0.530178
[ "object" ]
3cc71d889c7576304ee0a74ab27c374dab4ff249
3,287
cpp
C++
Caesar.cpp
YuriySavchenko/CaesarCipher
7aefcc401ac4b58ebb732c12ee35274e32f666f0
[ "Apache-2.0" ]
2
2019-03-19T09:21:16.000Z
2019-03-25T17:32:38.000Z
Caesar.cpp
YuriySavchenko/CaesarCipher
7aefcc401ac4b58ebb732c12ee35274e32f666f0
[ "Apache-2.0" ]
null
null
null
Caesar.cpp
YuriySavchenko/CaesarCipher
7aefcc401ac4b58ebb732c12ee35274e32f666f0
[ "Apache-2.0" ]
1
2019-03-19T09:21:17.000Z
2019-03-19T09:21:17.000Z
// // Created by yuriy on 14.08.18. // #include "Caesar.h" /* function for encrypt available text */ std::string encrypt(std::string text, int key) { std::string result = ""; // string for save result of encrypting std::vector<std::string> words; // vector for save words from text boost::split(words, text, boost::is_any_of("\t ")); // cutting text on pieces by deliminator for (int i=0 ;i < words.size(); i++) { std::string word = words[i]; // string for save word from vector for (int j = 0; j < word.length(); j++) { char symbol = word[j]; // variable for save char from vector // if symbol is not a letter we can add it to result string if (!isalpha(word[j])) result += symbol; // if symbol it's a letter in upper register we are using next formula else if (isupper(word[j])) { symbol += key; if (symbol > 'Z') symbol = symbol -'Z' + 'A' - 1; result += symbol; } // if symbol it's a letter in lower register we are using another formula else if (islower(word[j])) { symbol += key; if (symbol > 'z') symbol = symbol - 'z' + 'a' - 1; result += symbol; } } result += " "; // adding space-symbol to a result } return result; } /* function for decrypt encrypted text */ std::string decrypt(std::string text, int key) { std::string result = ""; // string for save result of decrypting std::vector<std::string> words; // vector for save words from text boost::split(words, text, boost::is_any_of("\t ")); // cutting text on pieces by deliminator for (int i=0; i < words.size(); i++) { std::string word = words[i]; for (int j = 0; j < word.length(); j++) { char symbol = word[j]; // if symbol is not a letter we can add it to result string if (!isalpha(word[j])) result += symbol; // if symbol it's a letter in upper register we are using next formula else if (isupper(word[j])) { symbol -= key; if (symbol > 'Z') symbol = symbol +'Z' - 'A' + 1; if (symbol < 'A') symbol = 'Z' - 'A' + symbol + 1; result += symbol; } // if symbol it's a letter in lower register we are using another formula else if (islower(word[j])) { symbol -= key; if (symbol > 'z') symbol = symbol + 'z' - 'a' + 1; if (symbol < 'a') symbol = 'z' - 'a' + symbol + 1; result += symbol; } } result += " "; // adding space-symbol to a result } return result; }
29.612613
104
0.438698
[ "vector" ]
3cc94b4630d00c8be954c95d1b8615d0a76e1e3a
1,554
hpp
C++
include/codegen/include/GlobalNamespace/AssetObjectListSO.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/AssetObjectListSO.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/AssetObjectListSO.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: PersistentScriptableObject #include "GlobalNamespace/PersistentScriptableObject.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Object because it is already included! } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: AssetObjectListSO class AssetObjectListSO : public GlobalNamespace::PersistentScriptableObject { public: // private UnityEngine.Object[] _objects // Offset: 0x18 ::Array<UnityEngine::Object*>* objects; // public UnityEngine.Object[] get_objects() // Offset: 0xB89464 ::Array<UnityEngine::Object*>* get_objects(); // public System.Void .ctor() // Offset: 0xB8946C // Implemented from: PersistentScriptableObject // Base method: System.Void PersistentScriptableObject::.ctor() // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static AssetObjectListSO* New_ctor(); }; // AssetObjectListSO } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::AssetObjectListSO*, "", "AssetObjectListSO"); #pragma pack(pop)
37.902439
85
0.707207
[ "object" ]
3cd0b192c4a23956a86f82c209e0f60c2b58082a
3,079
hpp
C++
PSME/common/agent-framework/include/agent-framework/command-ref/compute_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/common/agent-framework/include/agent-framework/command-ref/compute_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/common/agent-framework/include/agent-framework/command-ref/compute_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * * @file compute_commands.cpp * * @brief Declarations of all compute commands * */ #pragma once #include "agent-framework/command-ref/command.hpp" #include "agent-framework/module/model/model_compute.hpp" #include "agent-framework/module/requests/common.hpp" #include "agent-framework/module/requests/compute.hpp" #include "agent-framework/module/responses/common.hpp" namespace agent_framework { namespace command_ref { // declarations of get collection methods using GetCollection = Command<model::requests::GetCollection, model::attribute::Array<model::attribute::SubcomponentEntry>>; using GetManagersCollection = Command<model::requests::GetManagersCollection, model::attribute::Array<model::attribute::ManagerEntry>>; using GetTasksCollection = Command<model::requests::GetTasksCollection, model::attribute::Array<model::attribute::TaskEntry>>; // declarations of all get info methods using GetChassisInfo = Command<model::requests::GetChassisInfo, model::Chassis>; using GetMemoryInfo = Command<model::requests::GetMemoryInfo, model::Memory>; using GetDriveInfo = Command<model::requests::GetDriveInfo, model::Drive>; using GetManagerInfo = Command<model::requests::GetManagerInfo, model::Manager>; using GetNetworkInterfaceInfo = Command<model::requests::GetNetworkInterfaceInfo, model::NetworkInterface>; using GetNetworkDeviceInfo = Command<model::requests::GetNetworkDeviceInfo, model::NetworkDevice>; using GetNetworkDeviceFunctionInfo = Command<model::requests::GetNetworkDeviceFunctionInfo, model::NetworkDeviceFunction>; using GetProcessorInfo = Command<model::requests::GetProcessorInfo, model::Processor>; using GetStorageControllerInfo = Command<model::requests::GetStorageControllerInfo, model::StorageController>; using GetSystemInfo = Command<model::requests::GetSystemInfo, model::System>; using GetStorageSubsystemInfo = Command<model::requests::GetStorageSubsystemInfo, model::StorageSubsystem>; using GetTaskInfo = Command<model::requests::GetTaskInfo, model::Task>; using GetTaskResultInfo = Command<model::requests::GetTaskResultInfo, model::responses::GetTaskResultInfo>; // declarations of all set methods using SetComponentAttributes = Command<model::requests::SetComponentAttributes, model::responses::SetComponentAttributes>; using DeleteTask = Command<model::requests::DeleteTask, model::responses::DeleteTask>; } }
43.366197
135
0.791166
[ "model" ]
3cd2d49822e5089e2c62dfdb09682902e33f9bd5
5,858
cpp
C++
src/modules/packetio/port_server.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/packetio/port_server.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/packetio/port_server.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#include "zmq.h" #include "packetio/port_server.hpp" #include "message/serialized_message.hpp" #include "utils/overloaded_visitor.hpp" #include "swagger/v1/model/Port.h" namespace openperf::packetio::port::api { using generic_driver = openperf::packetio::driver::generic_driver; static std::string to_string(const request_msg& request) { return (std::visit(utils::overloaded_visitor( [](const request_list_ports&) { return (std::string("list ports")); }, [](const request_create_port&) { return (std::string("create port")); }, [](const request_get_port& request) { return ("get port " + request.id); }, [](const request_update_port&) { return (std::string("update port")); }, [](const request_delete_port& request) { return ("delete port " + request.id); }), request)); } static std::string to_string(const reply_msg& reply) { if (auto error = std::get_if<reply_error>(&reply)) { return ("failed: " + error->msg); } return ("succeeded"); } static int handle_rpc_request(const op_event_data* data, void* arg) { auto s = reinterpret_cast<server*>(arg); auto reply_errors = 0; while (auto request = message::recv(data->socket, ZMQ_DONTWAIT) .and_then(deserialize_request)) { OP_LOG(OP_LOG_TRACE, "Received request to %s\n", to_string(*request).c_str()); auto request_visitor = [&](auto& request) -> reply_msg { return (s->handle_request(request)); }; auto reply = std::visit(request_visitor, *request); OP_LOG(OP_LOG_TRACE, "Request to %s %s\n", to_string(*request).c_str(), to_string(reply).c_str()); if (message::send(data->socket, serialize_reply(std::move(reply))) == -1) { reply_errors++; OP_LOG( OP_LOG_ERROR, "Error sending reply: %s\n", zmq_strerror(errno)); continue; } } return ((reply_errors || errno == ETERM) ? -1 : 0); } server::server(void* context, openperf::core::event_loop& loop, generic_driver& driver) : m_socket(op_socket_get_server(context, ZMQ_REP, endpoint.data())) , m_driver(driver) { struct op_event_callbacks callbacks = {.on_read = handle_rpc_request}; loop.add(m_socket.get(), &callbacks, this); } reply_msg server::handle_request(const request_list_ports& request) { /* * Retrieve the list of port ids and use that to generate * a vector of port objects. */ auto ids = m_driver.port_ids(); auto ports = std::vector<port::generic_port>{}; std::transform(std::begin(ids), std::end(ids), std::back_inserter(ports), [&](const auto id) { return (m_driver.port(id).value()); }); /* Filter out any ports if necessary */ if (request.filter && request.filter->count(filter_key_type::kind)) { auto& kind = (*request.filter)[filter_key_type::kind]; ports.erase(std::remove_if(std::begin(ports), std::end(ports), [&](const auto& port) { return (port.kind() != kind); }), std::end(ports)); } /* Turn generic port objects into swagger objects */ auto reply = reply_ports{}; std::transform(std::begin(ports), std::end(ports), std::back_inserter(reply.ports), [](const auto& port) { return (make_swagger_port(port)); }); return (reply); }; reply_msg server::handle_request(const request_create_port& request) { /* Fill in id if user did not */ if (request.port->getId().empty()) { request.port->setId(core::to_string(core::uuid::random())); } auto id = request.port->getId(); auto result = m_driver.create_port(id, make_config_data(*request.port)); if (!result) { return ( reply_error{.type = error_type::VERBOSE, .msg = result.error()}); } auto reply = reply_ports{}; reply.ports.emplace_back(make_swagger_port(m_driver.port(id).value())); return (reply); }; reply_msg server::handle_request(const request_get_port& request) { auto port = m_driver.port(request.id); if (!port) { return (reply_error{.type = error_type::NOT_FOUND}); } auto reply = reply_ports{}; reply.ports.emplace_back(make_swagger_port(*port)); return (reply); }; reply_msg server::handle_request(const request_update_port& request) { auto port = m_driver.port(request.port->getId()); if (!port) { return (reply_error{.type = error_type::NOT_FOUND}); } auto success = port->config(make_config_data(*request.port)); if (!success) { return ( reply_error{.type = error_type::VERBOSE, .msg = success.error()}); } auto reply = reply_ports{}; reply.ports.emplace_back( make_swagger_port(m_driver.port(request.port->getId()).value())); return (reply); }; reply_msg server::handle_request(const request_delete_port& request) { auto success = m_driver.delete_port(request.id); if (!success) { return ( reply_error{.type = error_type::VERBOSE, .msg = success.error()}); } return (reply_ok{}); }; } // namespace openperf::packetio::port::api
32.544444
80
0.557187
[ "vector", "model", "transform" ]
3cd300b6f25e544bcd9a1bb660ddba3ab9033f0c
2,285
cpp
C++
Vitis-AI-Library/xnnpp/src/posedetect.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
3
2020-10-29T15:00:30.000Z
2021-10-21T08:09:34.000Z
Vitis-AI-Library/xnnpp/src/posedetect.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
20
2020-10-31T03:19:03.000Z
2020-11-02T18:59:49.000Z
Vitis-AI-Library/xnnpp/src/posedetect.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
9
2020-10-14T02:04:10.000Z
2020-12-01T08:23:02.000Z
/* * Copyright 2019 Xilinx 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. */ #include "vitis/ai/nnpp/posedetect.hpp" #include <array> #include <queue> #include <vector> #include <vitis/ai/math.hpp> #include <vitis/ai/profiling.hpp> using namespace std; namespace vitis { namespace ai { PoseDetectResult pose_detect_post_process( const std::vector<std::vector<vitis::ai::library::InputTensor>>& input_tensors, const std::vector<std::vector<vitis::ai::library::OutputTensor>>& output_tensors, cv::Size size, size_t batch_idx) { std::array<cv::Point2f, 14> pose14pt_arry; auto scale = vitis::ai::library::tensor_scale(output_tensors[1][0]); for (size_t i = 0; i < 14; i++) { pose14pt_arry[i] = cv::Point2f{ ((((int8_t*)(output_tensors[1][0].get_data(batch_idx)))[2 * i] * scale) / size.width), ((((int8_t*)(output_tensors[1][0].get_data(batch_idx)))[2 * i + 1] * scale) / size.height)}; } PoseDetectResult::Pose14Pt* pose14pt = (PoseDetectResult::Pose14Pt*)pose14pt_arry.data(); return PoseDetectResult{(int)input_tensors[0][0].width, (int)input_tensors[0][0].height, *pose14pt}; } std::vector<PoseDetectResult> pose_detect_post_process( const std::vector<std::vector<vitis::ai::library::InputTensor>>& input_tensors, const std::vector<std::vector<vitis::ai::library::OutputTensor>>& output_tensors, cv::Size size) { auto batch_size = input_tensors[0][0].batch; auto ret = std::vector<PoseDetectResult>{}; ret.reserve(batch_size); for (auto i = 0u; i < batch_size; i++) { ret.emplace_back(pose_detect_post_process(input_tensors, output_tensors, size, i)); } return ret; } } // namespace ai } // namespace vitis
34.104478
94
0.684026
[ "vector" ]
3cd35ace879ae4eeaa12b98a30933554b2fdef60
6,188
cc
C++
contrib/gcc-4.1/libstdc++-v3/config/locale/generic/codecvt_members.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
3
2017-03-06T14:12:57.000Z
2019-11-23T09:35:10.000Z
contrib/gcc-4.1/libstdc++-v3/config/locale/generic/codecvt_members.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
contrib/gcc-4.1/libstdc++-v3/config/locale/generic/codecvt_members.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
// std::codecvt implementation details, generic version -*- C++ -*- // Copyright (C) 2002 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 22.2.1.5 - Template class codecvt // // Written by Benjamin Kosnik <bkoz@redhat.com> #include <locale> namespace std { // Specializations. #ifdef _GLIBCXX_USE_WCHAR_T codecvt_base::result codecvt<wchar_t, char, mbstate_t>:: do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { result __ret = ok; // The conversion must be done using a temporary destination buffer // since it is not possible to pass the size of the buffer to wcrtomb state_type __tmp_state(__state); // The conversion must be done by calling wcrtomb in a loop rather // than using wcsrtombs because wcsrtombs assumes that the input is // zero-terminated. // Either we can upper bound the total number of external characters to // something smaller than __to_end - __to or the conversion must be done // using a temporary destination buffer since it is not possible to // pass the size of the buffer to wcrtomb if (MB_CUR_MAX * (__from_end - __from) - (__to_end - __to) <= 0) while (__from < __from_end) { const size_t __conv = wcrtomb(__to, *__from, &__tmp_state); if (__conv == static_cast<size_t>(-1)) { __ret = error; break; } __state = __tmp_state; __to += __conv; __from++; } else { extern_type __buf[MB_LEN_MAX]; while (__from < __from_end && __to < __to_end) { const size_t __conv = wcrtomb(__buf, *__from, &__tmp_state); if (__conv == static_cast<size_t>(-1)) { __ret = error; break; } else if (__conv > static_cast<size_t>(__to_end - __to)) { __ret = partial; break; } memcpy(__to, __buf, __conv); __state = __tmp_state; __to += __conv; __from++; } } if (__ret == ok && __from < __from_end) __ret = partial; __from_next = __from; __to_next = __to; return __ret; } codecvt_base::result codecvt<wchar_t, char, mbstate_t>:: do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { result __ret = ok; // This temporary state object is neccessary so __state won't be modified // if [__from, __from_end) is a partial multibyte character. state_type __tmp_state(__state); // Conversion must be done by calling mbrtowc in a loop rather than // by calling mbsrtowcs because mbsrtowcs assumes that the input // sequence is zero-terminated. while (__from < __from_end && __to < __to_end) { size_t __conv = mbrtowc(__to, __from, __from_end - __from, &__tmp_state); if (__conv == static_cast<size_t>(-1)) { __ret = error; break; } else if (__conv == static_cast<size_t>(-2)) { // It is unclear what to return in this case (see DR 382). __ret = partial; break; } else if (__conv == 0) { // XXX Probably wrong for stateful encodings __conv = 1; *__to = L'\0'; } __state = __tmp_state; __to++; __from += __conv; } // It is not clear that __from < __from_end implies __ret != ok // (see DR 382). if (__ret == ok && __from < __from_end) __ret = partial; __from_next = __from; __to_next = __to; return __ret; } int codecvt<wchar_t, char, mbstate_t>:: do_encoding() const throw() { // XXX This implementation assumes that the encoding is // stateless and is either single-byte or variable-width. int __ret = 0; if (MB_CUR_MAX == 1) __ret = 1; return __ret; } int codecvt<wchar_t, char, mbstate_t>:: do_max_length() const throw() { // XXX Probably wrong for stateful encodings. int __ret = MB_CUR_MAX; return __ret; } int codecvt<wchar_t, char, mbstate_t>:: do_length(state_type& __state, const extern_type* __from, const extern_type* __end, size_t __max) const { int __ret = 0; state_type __tmp_state(__state); while (__from < __end && __max) { size_t __conv = mbrtowc(NULL, __from, __end - __from, &__tmp_state); if (__conv == static_cast<size_t>(-1)) { // Invalid source character break; } else if (__conv == static_cast<size_t>(-2)) { // Remainder of input does not form a complete destination // character. break; } else if (__conv == 0) { // XXX Probably wrong for stateful encodings __conv = 1; } __state = __tmp_state; __from += __conv; __ret += __conv; __max--; } return __ret; } #endif }
28.385321
79
0.667744
[ "object" ]
3cd6cc8e143598c0798acaac4273e385bf8ee65e
7,851
cc
C++
src/operators/Operator_FaceCellSff.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
null
null
null
src/operators/Operator_FaceCellSff.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
null
null
null
src/operators/Operator_FaceCellSff.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
null
null
null
/* Operators Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Authors: Konstantin Lipnikov (lipnikov@lanl.gov) Ethan Coon (ecoon@lanl.gov) Operator whose unknowns are CELL + FACE, but which assembles the FACE only system and Schur complements cells. This uses special assembly. Apply is done as if we had the full FACE+CELL system. SymbolicAssembly() is done as if we had the CELL system, but with an additional step to get the layout due to the Schur'd system on FACE+CELL. Assemble, however, is done using a totally different approach. */ #include <vector> #include "EpetraExt_RowMatrixOut.h" #include "SuperMap.hh" #include "GraphFE.hh" #include "MatrixFE.hh" #include "InverseFactory.hh" #include "OperatorDefs.hh" #include "OperatorUtils.hh" #include "Op.hh" #include "Op_Cell_FaceCell.hh" #include "Op_Cell_Face.hh" #include "Operator_FaceCellSff.hh" namespace Amanzi { namespace Operators { /* ****************************************************************** * Special assemble algorithm is required to deal with Schur complement. ****************************************************************** */ void Operator_FaceCellSff::AssembleMatrix(const SuperMap& map, MatrixFE& matrix, int my_block_row, int my_block_col) const { // Check preconditions -- Scc must have exactly one CELL+FACE schema, // and no other CELL schemas that are not simply diagonal CELL_CELL. // Additionally, collect the diagonal for inversion. Epetra_MultiVector D_c(mesh_->cell_map(false), 1); int num_with_cells = 0; for (const_op_iterator it = begin(); it != end(); ++it) { if ((*it)->schema_old() & OPERATOR_SCHEMA_DOFS_CELL) { if (((*it)->schema_old() == (OPERATOR_SCHEMA_BASE_CELL | OPERATOR_SCHEMA_DOFS_CELL)) && ((*it)->diag->MyLength() == ncells_owned)) { // diagonal schema for (int c = 0; c != ncells_owned; ++c) { D_c[0][c] += (*(*it)->diag)[0][c]; } } else { num_with_cells++; } } } // schur complement int i_schur = 0; for (const_op_iterator it = begin(); it != end(); ++it) { if ((*it)->schema_old() == (OPERATOR_SCHEMA_BASE_CELL | OPERATOR_SCHEMA_DOFS_CELL | OPERATOR_SCHEMA_DOFS_FACE)) { AMANZI_ASSERT((*it)->matrices.size() == ncells_owned); // create or get extra ops, and keep them for future use Teuchos::RCP<Op_Cell_Face> schur_op; if (schur_ops_.size() > i_schur) { // get existing schur_op = schur_ops_[i_schur]; } else { // create and fill AMANZI_ASSERT(i_schur == schur_ops_.size()); std::string name = "Sff alt CELL_FACE"; schur_op = Teuchos::rcp(new Op_Cell_Face(name, mesh_)); schur_ops_.push_back(schur_op); for (int c = 0; c != ncells_owned; ++c) { int nfaces = mesh_->cell_get_num_faces(c); schur_op->matrices[c] = WhetStone::DenseMatrix(nfaces, nfaces); } } // populate the schur component for (int c = 0; c != ncells_owned; ++c) { const auto& faces = mesh_->cell_get_faces(c); int nfaces = faces.size(); WhetStone::DenseMatrix& Scell = schur_op->matrices[c]; WhetStone::DenseMatrix& Acell = (*it)->matrices[c]; double tmp = Acell(nfaces, nfaces) + D_c[0][c]; for (int n = 0; n < nfaces; n++) { for (int m = 0; m < nfaces; m++) { Scell(n, m) = Acell(n, m) - Acell(n, nfaces) * Acell(nfaces, m) / tmp; } } } // Assemble this Schur Op into matrix schur_op->AssembleMatrixOp(this, map, matrix, my_block_row, my_block_col); } else if (((*it)->schema_old() == (OPERATOR_SCHEMA_BASE_CELL | OPERATOR_SCHEMA_DOFS_CELL)) && ((*it)->diag->MyLength() == ncells_owned)) { // pass, already part of cell inverse } else { (*it)->AssembleMatrixOp(this, map, matrix, my_block_row, my_block_col); } } } /* ****************************************************************** * Visit method for Apply -- this is identical to Operator_FaceCell's * version. ****************************************************************** */ int Operator_FaceCellSff::ApplyMatrixFreeOp(const Op_Cell_FaceCell& op, const CompositeVector& X, CompositeVector& Y) const { AMANZI_ASSERT(op.matrices.size() == ncells_owned); const Epetra_MultiVector& Xf = *X.ViewComponent("face", true); const Epetra_MultiVector& Xc = *X.ViewComponent("cell"); { Epetra_MultiVector& Yf = *Y.ViewComponent("face", true); Epetra_MultiVector& Yc = *Y.ViewComponent("cell"); for (int c=0; c!=ncells_owned; ++c) { const auto& faces = mesh_->cell_get_faces(c); int nfaces = faces.size(); WhetStone::DenseVector v(nfaces + 1), av(nfaces + 1); for (int n=0; n!=nfaces; ++n) { v(n) = Xf[0][faces[n]]; } v(nfaces) = Xc[0][c]; const WhetStone::DenseMatrix& Acell = op.matrices[c]; Acell.Multiply(v, av, false); for (int n=0; n!=nfaces; ++n) { Yf[0][faces[n]] += av(n); } Yc[0][c] += av(nfaces); } } return 0; } /* ****************************************************************** * Create a global matrix. ****************************************************************** */ void Operator_FaceCellSff::SymbolicAssembleMatrix() { // SuperMap for Sff is face only CompositeVectorSpace smap_space; smap_space.SetMesh(mesh_)->SetComponent("face", AmanziMesh::FACE, 1); smap_ = createSuperMap(smap_space); // create the graph int row_size = MaxRowSize(*mesh_, schema(), 1); Teuchos::RCP<GraphFE> graph = Teuchos::rcp(new GraphFE(smap_->Map(), smap_->GhostedMap(), smap_->GhostedMap(), row_size)); Operator::SymbolicAssembleMatrix(*smap_, *graph, 0, 0); // Completing and optimizing the graphs int ierr = graph->FillComplete(smap_->Map(), smap_->Map()); AMANZI_ASSERT(!ierr); // create global matrix Amat_ = Teuchos::rcp(new MatrixFE(graph)); A_ = Amat_->Matrix(); } /* ****************************************************************** * visit method for sparsity structure of Schur complement ****************************************************************** */ void Operator_FaceCellSff::SymbolicAssembleMatrixOp(const Op_Cell_FaceCell& op, const SuperMap& map, GraphFE& graph, int my_block_row, int my_block_col) const { std::string name = "Sff alt CELL_FACE"; Op_Cell_Face schur_op(name, mesh_); Operator_FaceCell::SymbolicAssembleMatrixOp(schur_op, map, graph, my_block_row, my_block_col); } void Operator_FaceCellSff::InitializeInverse() { AMANZI_ASSERT(inited_); schur_inv_ = Teuchos::rcp(new AmanziSolvers::InverseSchurComplement()); schur_inv_->set_inverse_parameters(inv_plist_); schur_inv_->set_matrix(Teuchos::rcpFromRef(*this)); if (inv_plist_.isParameter("iterative method")) { preconditioner_ = AmanziSolvers::createIterativeMethod(inv_plist_, Teuchos::rcpFromRef(*this), schur_inv_); } else { preconditioner_ = schur_inv_; } preconditioner_->InitializeInverse(); updated_ = true; computed_ = false; } /* ****************************************************************** * Copy constructor. ****************************************************************** */ Teuchos::RCP<Operator> Operator_FaceCellSff::Clone() const { return Teuchos::rcp(new Operator_FaceCellSff(*this)); } } // namespace Operators } // namespace Amanzi
34.893333
111
0.585785
[ "vector" ]
3cda55c8a5a251122f23f1f60bdddf9bf7980611
1,645
cpp
C++
Raycast2DShadow/Raycast2DShadow/main.cpp
boxerprogrammer/TestCode
6e0a7dfebd2d7e19d043bcaf335ab4fb7f94a0c8
[ "Unlicense" ]
1
2022-01-04T17:39:19.000Z
2022-01-04T17:39:19.000Z
Raycast2DShadow/Raycast2DShadow/main.cpp
boxerprogrammer/TestCode
6e0a7dfebd2d7e19d043bcaf335ab4fb7f94a0c8
[ "Unlicense" ]
null
null
null
Raycast2DShadow/Raycast2DShadow/main.cpp
boxerprogrammer/TestCode
6e0a7dfebd2d7e19d043bcaf335ab4fb7f94a0c8
[ "Unlicense" ]
null
null
null
#include<DxLib.h> #include<vector> #include<algorithm> #include"Geometry.h" using namespace std; int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { ChangeWindowMode(true); if (DxLib::DxLib_Init() == -1) { return -1; } SetDrawScreen(DX_SCREEN_BACK); std::vector<Rect> rects; rects.emplace_back(200, 100, 100, 50); rects.emplace_back(600, 200, 50, 100); rects.emplace_back(500, 300, 50, 50); rects.emplace_back(150, 300, 150, 100); while (ProcessMessage() != -1) { ClearDrawScreen(); int mx, my; GetMousePoint(&mx, &my); auto mousePos = Position2(mx, my); DrawCircleAA(mx, my, 500, 32, 0x888800); DrawCircleAA(mx, my, 240, 32, 0xdddd88); DrawCircleAA(mx, my, 16, 16, 0xffffaa); for (auto& rc : rects) { auto v = rc.Center()-Position2(mx, my); v.Normalize(); DrawLineAA(mx, my, rc.Center().x, rc.Center().y,0xffffff ); auto verts = rc.GetPositions(); std::sort(verts.begin(), verts.end(), [v, mousePos](const Position2& a, const Position2& b) { return Cross(v, (a-mousePos).Normalized()) > Cross(v, (b-mousePos).Normalized()); }); auto v1= verts[0] - Position2(mx, my); auto v2 = verts[3] - Position2(mx, my); v1.Normalize(); v2.Normalize(); auto p1 = verts[0]; auto p2 = verts[0] + v1*1000.0f; auto p3 = verts[3] + v2*1000.0f; auto p4 = verts[3]; DrawQuadrangleAA(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, 0x000000, true); DrawLineAA(mx, my, verts[0].x, verts[0].y, 0xff0000); DrawLineAA(mx, my, verts[3].x, verts[3].y, 0xff0000); } for (auto& rc : rects) { rc.Draw(0x00ff00,true); } ScreenFlip(); } DxLib_End(); return 0; }
24.552239
96
0.632219
[ "geometry", "vector" ]
3cdb7747976b46ca6111e5d6fbc3595de3b4de2c
2,942
hpp
C++
Python/cython_wrapping_cpp/permutations/Cycle.hpp
jessicaleete/numerical_computing
cc71f51f35ca74d00e617af3d1a0223e19fb9a68
[ "CC-BY-3.0" ]
10
2016-10-18T19:54:25.000Z
2021-10-09T20:12:38.000Z
Python/cython_wrapping_cpp/permutations/Cycle.hpp
jessicaleete/numerical_computing
cc71f51f35ca74d00e617af3d1a0223e19fb9a68
[ "CC-BY-3.0" ]
null
null
null
Python/cython_wrapping_cpp/permutations/Cycle.hpp
jessicaleete/numerical_computing
cc71f51f35ca74d00e617af3d1a0223e19fb9a68
[ "CC-BY-3.0" ]
2
2017-05-14T16:07:59.000Z
2020-06-20T09:05:06.000Z
#pragma once #include "Node.hpp" #include <list> #include <vector> #include <string> #include <sstream> #include <algorithm> class Permutation; // TODO: Make sure when constructing new versions that the default constructor is // used instead of manually constructing the vector, etc. // TODO: check corner cases for zero-length construction, etc. // TODO: remove unnecessary constructors. // TODO: redo comments. // TODO: fix -1 increment in indices (Maybe on the Python end?? in the constructor?) class Cycle{ friend class Permutation; public: Cycle(std::list<unsigned int>& indexlist); Cycle(std::vector<unsigned int>& indexvector); Cycle(unsigned int* indexarr, unsigned int size); Cycle(const Cycle& other); ~Cycle(); Cycle& operator=(const Cycle& other); std::string get_string(); unsigned int get_min(); unsigned int get_max(); unsigned int get_size(); bool in(unsigned int index); unsigned int trace(unsigned int index); Cycle* inverse(); unsigned int trace_inverse(unsigned int index); bool operator<(const Cycle& other); bool operator>(const Cycle& other); bool operator<=(const Cycle& other); bool operator>=(const Cycle& other); bool operator==(const Cycle& other); bool operator!=(const Cycle& other); template <class arr_type> void apply(arr_type* arr, unsigned int size, int& info){ if ((this->maximum)<info){ Node* iter = (this->nodes)[0]->next; arr_type temp1 = arr[this->minimum]; arr_type temp2 = temp1; while (iter != (this->nodes)[0]){ temp1 = arr[iter->index]; arr[iter->index] = temp2; temp2 = temp1; iter = iter->next;} info = 0;} else{ info = 1;}} template <class arr_type> void apply_inverse(arr_type* arr, unsigned int size, int& info){ if ((this->maximum)<info){ Node* iter = (this->nodes)[0]->previous; arr_type temp1 = arr[this->minimum]; arr_type temp2 = temp1; while (iter != (this->nodes)[0]){ temp1 = arr[iter->index]; arr[iter->index] = temp2; temp2 = temp1; iter = iter->previous;} info = 0;} else{ info = 1;}} private: unsigned int minimum; unsigned int maximum; unsigned int size; std::vector<Node*> nodes; //Cycle(std::vector<Node*> nodearr, unsigned int size); Cycle(std::list<unsigned int>& indexlist, unsigned int size); Cycle(std::vector<Node*>& nodearr, unsigned int size, unsigned int minimum, unsigned int maximum); bool verify(); void sort();};
36.320988
106
0.564582
[ "vector" ]
3cdd3db533686ce914235328f329f53f4614cc7c
90,541
cpp
C++
westeros-render-embedded.cpp
johnrobinsn/westeros-1
7f130816b434261fe1cafd771eb6bf3551f7983a
[ "Apache-2.0" ]
38
2016-05-18T15:19:31.000Z
2022-03-28T03:28:19.000Z
westeros-render-embedded.cpp
fengying7445/westeros
868a6a2c07d8ba2b9700654a401ab3e89d3ab44b
[ "Apache-2.0" ]
16
2016-07-15T08:40:14.000Z
2021-03-26T20:45:12.000Z
westeros-render-embedded.cpp
fengying7445/westeros
868a6a2c07d8ba2b9700654a401ab3e89d3ab44b
[ "Apache-2.0" ]
36
2016-05-18T14:47:14.000Z
2021-12-24T09:10:00.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2016 RDK Management * * 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 <stdlib.h> #include <stdio.h> #include <memory.h> #include <assert.h> #include <dlfcn.h> #include <sys/time.h> #include <EGL/egl.h> #include <EGL/eglext.h> #if defined (USE_MESA) #include <EGL/eglmesaext.h> #endif #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #else #include <GL/glew.h> #include <GL/gl.h> #endif #if defined (WESTEROS_PLATFORM_EMBEDDED) #include "westeros-gl.h" #endif #if defined (WESTEROS_PLATFORM_RPI) #include <bcm_host.h> #endif #include "westeros-render.h" #include "wayland-server.h" #include "wayland-client.h" #include "wayland-egl.h" #ifdef ENABLE_SBPROTOCOL #include "westeros-simplebuffer.h" #endif #ifdef ENABLE_LDBPROTOCOL #include "linux-dmabuf/westeros-linux-dmabuf.h" #endif #include <vector> //#define WST_DEBUG #ifdef WST_DEBUG #define INT_TRACE(FORMAT,...) printf( FORMAT "\n", __VA_ARGS__) #else #define INT_TRACE(FORMAT,...) #endif #define WST_TRACE(...) INT_TRACE(__VA_ARGS__, "") #define WST_UNUSED( n ) ((void)n) #define DEFAULT_SURFACE_WIDTH (0) #define DEFAULT_SURFACE_HEIGHT (0) #ifndef DRM_FORMAT_R8 #define DRM_FORMAT_R8 (0x20203852) #endif #ifndef DRM_FORMAT_GR88 #define DRM_FORMAT_GR88 (0x38385247) #endif #ifndef DRM_FORMAT_RG88 #define DRM_FORMAT_RG88 (0x38384752) #endif #ifndef DRM_FORMAT_NV12 #define DRM_FORMAT_NV12 (0x3231564E) #endif #ifndef DRM_FORMAT_NV21 #define DRM_FORMAT_NV21 (0x3132564E) #endif static const char *fShaderText = "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform sampler2D texture;\n" "uniform float alpha;\n" "varying vec2 txv;\n" "void main()\n" "{\n" " gl_FragColor= texture2D(texture, txv) * alpha;\n" "}\n"; static const char *vShaderText = "uniform vec2 resolution;\n" "uniform mat4 matrix;\n" "attribute vec2 pos;\n" "attribute vec2 texcoord;\n" "varying vec2 txv;\n" "void main()\n" "{\n" " vec4 p= matrix * vec4(pos, 0, 1);\n" " vec4 zeroToOne= p / vec4(resolution, resolution.x, 1);\n" " vec4 zeroToTwo= zeroToOne * vec4(2.0, 2.0, 1, 1);\n" " vec4 clipSpace= zeroToTwo - vec4(1.0, 1.0, 0, 0);\n" " clipSpace.w= 1.0+clipSpace.z;\n" " gl_Position= clipSpace * vec4(1, -1, 1, 1);\n" " txv= texcoord;\n" "}\n"; static const char *fShaderTextYUV = "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform sampler2D texture;\n" "uniform sampler2D textureuv;\n" "const vec3 cc_r = vec3(1.0, -0.8604, 1.59580);\n" "const vec4 cc_g = vec4(1.0, 0.539815, -0.39173, -0.81290);\n" "const vec3 cc_b = vec3(1.0, -1.071, 2.01700);\n" "uniform float alpha;\n" "varying vec2 txv;\n" "varying vec2 txvuv;\n" "void main()\n" "{\n" " vec4 y_vec= texture2D(texture, txv);\n" " vec4 c_vec= texture2D(textureuv, txvuv);\n" " vec4 temp_vec= vec4(y_vec.a, 1.0, c_vec.b, c_vec.a);\n" " gl_FragColor= vec4( dot(cc_r,temp_vec.xyw), dot(cc_g,temp_vec), dot(cc_b,temp_vec.xyz), alpha );\n" "}\n"; static const char *vShaderTextYUV = "uniform vec2 resolution;\n" "uniform mat4 matrix;\n" "attribute vec2 pos;\n" "attribute vec2 texcoord;\n" "attribute vec2 texcoorduv;\n" "varying vec2 txv;\n" "varying vec2 txvuv;\n" "void main()\n" "{\n" " vec4 p= matrix * vec4(pos, 0, 1);\n" " vec4 zeroToOne= p / vec4(resolution, resolution.x, 1);\n" " vec4 zeroToTwo= zeroToOne * vec4(2.0, 2.0, 1, 1);\n" " vec4 clipSpace= zeroToTwo - vec4(1.0, 1.0, 0, 0);\n" " clipSpace.w= 1.0+clipSpace.z;\n" " gl_Position= clipSpace * vec4(1, -1, 1, 1);\n" " txv= texcoord;\n" " txvuv= texcoorduv;\n" "}\n"; static const char *fShaderText_Y_UV = "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform sampler2D texture;\n" "uniform sampler2D textureuv;\n" "const vec3 cc_r = vec3(1.0, -0.8604, 1.59580);\n" "const vec4 cc_g = vec4(1.0, 0.539815, -0.39173, -0.81290);\n" "const vec3 cc_b = vec3(1.0, -1.071, 2.01700);\n" "varying vec2 txv;\n" "varying vec2 txvuv;\n" "void main()\n" "{\n" " vec4 y_vec= texture2D(texture, txv);\n" " vec4 c_vec= texture2D(textureuv, txvuv);\n" " vec4 temp_vec= vec4(y_vec.r, 1.0, c_vec.r, c_vec.g);\n" " gl_FragColor= vec4( dot(cc_r,temp_vec.xyw), dot(cc_g,temp_vec), dot(cc_b,temp_vec.xyz), 1 );\n" "}\n"; static const char *fShaderTextExternal = "#extension GL_OES_EGL_image_external : require\n" "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform samplerExternalOES texture;\n" "varying vec2 txv;\n" "void main()\n" "{\n" " gl_FragColor= texture2D(texture, txv);\n" "}\n"; typedef enum _WstShaderType { WstShaderType_rgb, WstShaderType_yuv, WstShaderType_external } WstShaderType; typedef struct _WstShader { bool isYUV; GLuint fragShader; GLuint vertShader; GLuint program; GLuint attrPos; GLuint attrTexcoord; GLuint attrTexcoorduv; GLint uniRes; GLint uniMatrix; GLint uniAlpha; GLint uniTexture; GLint uniTextureuv; } WstShader; static char message[1024]; static bool emitFPS= false; #define MAX_TEXTURES (2) struct _WstRenderSurface { int textureCount; bool externalImage; GLuint textureId[MAX_TEXTURES]; int bufferWidth; int bufferHeight; #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) void *nativePixmap; EGLImageKHR eglImage[MAX_TEXTURES]; #endif unsigned char *mem; bool memDirty; int memWidth; int memHeight; GLint memFormatGL; GLenum memType; int x; int y; int width; int height; bool visible; float opacity; float zorder; bool sizeOverride; bool dirty; bool invertedY; bool haveCrop; float cropTextureCoord[4][2]; WstRenderSurface *surfaceFast; }; typedef struct _WstRendererEMB { WstRenderer *renderer; int outputWidth; int outputHeight; #if defined (WESTEROS_PLATFORM_EMBEDDED) WstGLCtx *glCtx; #endif void *nativeWindow; EGLDisplay eglDisplay; EGLContext eglContext; PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR; #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; #endif bool haveDmaBufImport; bool haveDmaBufImportModifiers; bool haveExternalImage; #if defined (WESTEROS_HAVE_WAYLAND_EGL) bool haveWaylandEGL; PFNEGLBINDWAYLANDDISPLAYWL eglBindWaylandDisplayWL; PFNEGLUNBINDWAYLANDDISPLAYWL eglUnbindWaylandDisplayWL; PFNEGLQUERYWAYLANDBUFFERWL eglQueryWaylandBufferWL; #endif #ifdef ENABLE_LDBPROTOCOL PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; PFNEGLQUERYDMABUFMODIFIERSEXTPROC eglQueryDmaBufModifiersEXT; #endif WstShader *textureShader; WstShader *textureShaderYUV; WstShader *textureShaderExternal; std::vector<WstRenderSurface*> surfaces; std::vector<GLuint> deadTextures; bool fastPathActive; WstRenderer *rendererFast; } WstRendererEMB; static WstRendererEMB* wstRendererEMBCreate( WstRenderer *renderer ); static void wstRendererEMBDestroy( WstRendererEMB *renderer ); static WstRenderSurface *wstRendererEMBCreateSurface(WstRendererEMB *renderer); static void wstRendererEMBDestroySurface( WstRendererEMB *renderer, WstRenderSurface *surface ); static void wstRendererEMBFlushSurface( WstRendererEMB *renderer, WstRenderSurface *surface ); static void wstRendererEMBPrepareResource( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource); static void wstRendererEMBCommitShm( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ); #if defined (WESTEROS_HAVE_WAYLAND_EGL) static void wstRendererEMBCommitWaylandEGL( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource, EGLint format ); #endif #ifdef ENABLE_SBPROTOCOL static void wstRendererEMBCommitSB( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ); #endif #ifdef ENABLE_LDBPROTOCOL static void wstRendererEMBCommitLDB( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ); #endif #if defined (WESTEROS_PLATFORM_RPI) static void wstRendererEMBCommitDispmanx( WstRendererEMB *renderer, WstRenderSurface *surface, DISPMANX_RESOURCE_HANDLE_T dispResource, EGLint format, int bufferWidth, int bufferHeight ); #endif static void wstRendererEMBRenderSurface( WstRendererEMB *renderer, WstRenderSurface *surface ); static WstShader* wstRendererEMBCreateShader( WstRendererEMB *renderer, int shaderType ); static void wstRendererEMBDestroyShader( WstShader *shader ); static void wstRendererEMBShaderDraw( WstShader *shader, int width, int height, float* matrix, float alpha, GLuint textureId, GLuint textureUVId, int count, const float* vc, const float* txc ); static void wstRendererHolePunch( WstRenderer *renderer, int x, int y, int width, int height ); static void wstRendererInitFastPath( WstRendererEMB *renderer ); static bool wstRendererActivateFastPath( WstRendererEMB *renderer ); static void wstRendererDeactivateFastPath( WstRendererEMB *renderer ); static void wstRendererDeleteTexture( WstRendererEMB *renderer, GLuint textureId ); static void wstRendererProcessDeadTextures( WstRendererEMB *renderer ); #define RED_SIZE (8) #define GREEN_SIZE (8) #define BLUE_SIZE (8) #define ALPHA_SIZE (8) #define DEPTH_SIZE (0) static WstRendererEMB* wstRendererEMBCreate( WstRenderer *renderer ) { WstRendererEMB *rendererEMB= 0; rendererEMB= (WstRendererEMB*)calloc(1, sizeof(WstRendererEMB) ); if ( rendererEMB ) { if ( getenv("WESTEROS_RENDER_EMBEDDED_FPS" ) ) { emitFPS= true; } rendererEMB->outputWidth= renderer->outputWidth; rendererEMB->outputHeight= renderer->outputHeight; rendererEMB->renderer= renderer; rendererEMB->surfaces= std::vector<WstRenderSurface*>(); rendererEMB->deadTextures= std::vector<GLuint>(); #if defined (WESTEROS_PLATFORM_EMBEDDED) rendererEMB->glCtx= WstGLInit(); if ( !rendererEMB->glCtx ) { free( rendererEMB ); rendererEMB= 0; goto exit; } #endif rendererEMB->eglCreateImageKHR= (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR"); WST_TRACE( "eglCreateImageKHR %p\n", rendererEMB->eglCreateImageKHR); rendererEMB->eglDestroyImageKHR= (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR"); WST_TRACE( "eglDestroyImageKHR %p\n", rendererEMB->eglDestroyImageKHR); #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) rendererEMB->glEGLImageTargetTexture2DOES= (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES"); WST_TRACE( "glEGLImageTargetTexture2DOES %p\n", rendererEMB->glEGLImageTargetTexture2DOES); #endif rendererEMB->eglDisplay= eglGetCurrentDisplay(); if ( rendererEMB->eglDisplay == EGL_NO_DISPLAY ) { rendererEMB->eglDisplay= eglGetDisplay(EGL_DEFAULT_DISPLAY); fprintf(stderr,"no current eglDisplay, get eglDisplay %p\n", rendererEMB->eglDisplay); } #if defined (WESTEROS_HAVE_WAYLAND_EGL) const char *extensions= eglQueryString( rendererEMB->eglDisplay, EGL_EXTENSIONS ); if ( extensions ) { if ( !strstr( extensions, "EGL_WL_bind_wayland_display" ) ) { printf("wayland-egl support expected, but not advertised by eglQueryString(eglDisplay,EGL_EXTENSIONS): not attempting to use\n" ); } else { printf("wayland-egl support expected, and is advertised by eglQueryString(eglDisplay,EGL_EXTENSIONS): proceeding to use \n" ); rendererEMB->eglBindWaylandDisplayWL= (PFNEGLBINDWAYLANDDISPLAYWL)eglGetProcAddress("eglBindWaylandDisplayWL"); printf( "eglBindWaylandDisplayWL %p\n", rendererEMB->eglBindWaylandDisplayWL ); rendererEMB->eglUnbindWaylandDisplayWL= (PFNEGLUNBINDWAYLANDDISPLAYWL)eglGetProcAddress("eglUnbindWaylandDisplayWL"); printf( "eglUnbindWaylandDisplayWL %p\n", rendererEMB->eglUnbindWaylandDisplayWL ); rendererEMB->eglQueryWaylandBufferWL= (PFNEGLQUERYWAYLANDBUFFERWL)eglGetProcAddress("eglQueryWaylandBufferWL"); printf( "eglQueryWaylandBufferWL %p\n", rendererEMB->eglQueryWaylandBufferWL ); if ( rendererEMB->eglBindWaylandDisplayWL && rendererEMB->eglUnbindWaylandDisplayWL && rendererEMB->eglQueryWaylandBufferWL ) { printf("calling eglBindWaylandDisplayWL with eglDisplay %p and wayland display %p\n", rendererEMB->eglDisplay, renderer->display ); EGLBoolean rc= rendererEMB->eglBindWaylandDisplayWL( rendererEMB->eglDisplay, renderer->display ); if ( rc ) { rendererEMB->haveWaylandEGL= true; } else { printf("eglBindWaylandDisplayWL failed: %x\n", eglGetError() ); } } else { printf("wayland-egl support expected, and advertised, but methods are missing: no wayland-egl\n" ); } } if ( strstr( extensions, "EGL_EXT_image_dma_buf_import" ) ) { rendererEMB->haveDmaBufImport= true; } if ( strstr( extensions, "EGL_EXT_image_dma_buf_import_modifiers" ) ) { rendererEMB->haveDmaBufImportModifiers= true; #ifdef ENABLE_LDBPROTOCOL rendererEMB->eglQueryDmaBufFormatsEXT = (PFNEGLQUERYDMABUFFORMATSEXTPROC)eglGetProcAddress("eglQueryDmaBufFormatsEXT"); printf( "eglQueryDmaBufFormatsEXT %p\n", rendererEMB->eglQueryDmaBufFormatsEXT ); rendererEMB->eglQueryDmaBufModifiersEXT = (PFNEGLQUERYDMABUFMODIFIERSEXTPROC)eglGetProcAddress("eglQueryDmaBufModifiersEXT"); printf( "eglQueryDmaBufModifiersEXT %p\n", rendererEMB->eglQueryDmaBufModifiersEXT ); #endif } } extensions= (const char *)glGetString(GL_EXTENSIONS); if ( extensions ) { #ifdef GL_OES_EGL_image_external if ( strstr( extensions, "GL_OES_EGL_image_external" ) ) { rendererEMB->haveExternalImage= true; } #endif } printf("have wayland-egl: %d\n", rendererEMB->haveWaylandEGL ); printf("have dmabuf import: %d\n", rendererEMB->haveDmaBufImport ); printf("have dmabuf import modifiers: %d\n", rendererEMB->haveDmaBufImportModifiers ); printf("have external image: %d\n", rendererEMB->haveExternalImage ); #endif } exit: return rendererEMB; } static void wstRendererEMBDestroy( WstRendererEMB *renderer ) { if ( renderer ) { wstRendererProcessDeadTextures( renderer ); #if defined (WESTEROS_HAVE_WAYLAND_EGL) if ( renderer->haveWaylandEGL ) { renderer->eglUnbindWaylandDisplayWL( renderer->eglDisplay, renderer->renderer->display ); renderer->haveWaylandEGL= false; } #endif if ( renderer->textureShader ) { wstRendererEMBDestroyShader( renderer->textureShader ); renderer->textureShader= 0; } if ( renderer->textureShaderYUV ) { wstRendererEMBDestroyShader( renderer->textureShaderYUV ); renderer->textureShaderYUV= 0; } #if defined (WESTEROS_PLATFORM_EMBEDDED) if ( renderer->glCtx ) { WstGLTerm( renderer->glCtx ); renderer->glCtx= 0; } #endif if ( renderer->rendererFast ) { renderer->rendererFast->renderTerm( renderer->rendererFast ); free( renderer->rendererFast ); renderer->rendererFast= 0; } free( renderer ); } } static WstRenderSurface *wstRendererEMBCreateSurface(WstRendererEMB *renderer) { WstRenderSurface *surface= 0; WST_UNUSED(renderer); surface= (WstRenderSurface*)calloc( 1, sizeof(WstRenderSurface) ); if ( surface ) { surface->textureCount= 1; surface->textureId[0]= GL_NONE; surface->width= DEFAULT_SURFACE_WIDTH; surface->height= DEFAULT_SURFACE_HEIGHT; surface->x= 0; surface->y= 0; surface->visible= true; surface->opacity= 1.0; surface->zorder= 0.5; surface->dirty= true; if ( renderer->fastPathActive ) { surface->surfaceFast= renderer->rendererFast->surfaceCreate( renderer->rendererFast ); if ( !surface->surfaceFast ) { wstRendererDeactivateFastPath( renderer ); } } } return surface; } static void wstRendererEMBDestroySurface( WstRendererEMB *renderer, WstRenderSurface *surface ) { if ( surface ) { wstRendererEMBFlushSurface( renderer, surface ); if ( renderer->rendererFast ) { if ( surface->surfaceFast ) { renderer->rendererFast->surfaceDestroy( renderer->rendererFast, surface->surfaceFast ); surface->surfaceFast= 0; } } free( surface ); } } static void wstRendererEMBFlushSurface( WstRendererEMB *renderer, WstRenderSurface *surface ) { if ( surface ) { for( int i= 0; i < MAX_TEXTURES; ++i ) { if ( surface->textureId[i] ) { wstRendererDeleteTexture( renderer, surface->textureId[i] ); surface->textureId[i]= GL_NONE; } #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) if ( surface->eglImage[i] ) { renderer->eglDestroyImageKHR( renderer->eglDisplay, surface->eglImage[i] ); surface->eglImage[i]= 0; } #endif } #if defined (WESTEROS_PLATFORM_EMBEDDED) if ( surface->nativePixmap ) { WstGLReleaseNativePixmap( renderer->glCtx, surface->nativePixmap ); surface->nativePixmap= 0; } #endif if ( surface->mem ) { free( surface->mem ); surface->mem= 0; } } } static void wstRendererEMBPrepareResource( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { if ( surface && resource ) { EGLImageKHR eglImage= 0; #ifdef ENABLE_SBPROTOCOL struct wl_sb_buffer *sbBuffer; sbBuffer= WstSBBufferGet( resource ); if ( sbBuffer ) { #ifdef EGL_LINUX_DMA_BUF_EXT if ( renderer->haveDmaBufImport ) { if ( WstSBBufferGetFd( sbBuffer ) >= 0 ) { int i; uint32_t frameFormat, frameWidth, frameHeight; int fd[MAX_TEXTURES]; int32_t offset[MAX_TEXTURES], stride[MAX_TEXTURES]; EGLint attr[28]; frameFormat= WstSBBufferGetFormat( sbBuffer ); frameWidth= WstSBBufferGetWidth( sbBuffer ); frameHeight= WstSBBufferGetHeight( sbBuffer ); for( i= 0; i < MAX_TEXTURES; ++i ) { fd[i]= WstSBBufferGetPlaneFd( sbBuffer, i ); WstSBBufferGetPlaneOffsetAndStride( sbBuffer, i, &offset[i], &stride[i] ); } if ( (surface->bufferWidth != frameWidth) || (surface->bufferHeight != frameHeight) ) { surface->bufferWidth= frameWidth; surface->bufferHeight= frameHeight; } for( i= 0; i < MAX_TEXTURES; ++i ) { if ( surface->eglImage[i] ) { renderer->eglDestroyImageKHR( renderer->eglDisplay, surface->eglImage[i] ); surface->eglImage[i]= 0; } } switch( frameFormat ) { case WL_SB_FORMAT_NV12: case WL_SB_FORMAT_NV21: if ( renderer->haveExternalImage ) { if ( fd[1] == -1 ) { fd[1]= fd[0]; } i= 0; attr[i++]= EGL_WIDTH; attr[i++]= frameWidth; attr[i++]= EGL_HEIGHT; attr[i++]= frameHeight; attr[i++]= EGL_LINUX_DRM_FOURCC_EXT; attr[i++]= (frameFormat == WL_SB_FORMAT_NV12 ? DRM_FORMAT_NV12 : DRM_FORMAT_NV21); attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[0]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[0]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[0]; attr[i++]= EGL_DMA_BUF_PLANE1_FD_EXT; attr[i++]= fd[1]; attr[i++]= EGL_DMA_BUF_PLANE1_OFFSET_EXT; attr[i++]= offset[1]; attr[i++]= EGL_DMA_BUF_PLANE1_PITCH_EXT; attr[i++]= stride[1]; attr[i++]= EGL_YUV_COLOR_SPACE_HINT_EXT; attr[i++]= EGL_ITU_REC709_EXT; attr[i++]= EGL_SAMPLE_RANGE_HINT_EXT; attr[i++]= EGL_YUV_FULL_RANGE_EXT; attr[i++]= EGL_NONE; eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, (EGLClientBuffer)NULL, attr ); if ( eglImage ) { surface->eglImage[0]= eglImage; if ( surface->textureId[0] != GL_NONE ) { glDeleteTextures( 1, &surface->textureId[0] ); } surface->textureId[0]= GL_NONE; } else { printf("wstRendererEMBPrepareResource: eglCreateImageKHR failed for fd %d, DRM_FORMAT_NV12: errno %X\n", fd[0], eglGetError()); } surface->textureCount= 1; surface->externalImage= true; } else { if ( fd[1] == -1 ) { fd[1]= fd[0]; } i= 0; attr[i++]= EGL_WIDTH; attr[i++]= frameWidth; attr[i++]= EGL_HEIGHT; attr[i++]= frameHeight; attr[i++]= EGL_LINUX_DRM_FOURCC_EXT; attr[i++]= DRM_FORMAT_R8; attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[0]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[0]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[0]; attr[i++]= EGL_NONE; eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, (EGLClientBuffer)NULL, attr ); if ( eglImage ) { surface->eglImage[0]= eglImage; if ( surface->textureId[0] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[0] ); } surface->textureId[0]= GL_NONE; } else { printf("wstRendererEMBPrepareResource: eglCreateImageKHR failed for fd %d, DRM_FORMAT_R8: errno %X\n", fd[0], eglGetError()); } i= 0; attr[i++]= EGL_WIDTH; attr[i++]= frameWidth/2; attr[i++]= EGL_HEIGHT; attr[i++]= frameHeight/2; attr[i++]= EGL_LINUX_DRM_FOURCC_EXT; attr[i++]= (frameFormat == WL_SB_FORMAT_NV12 ? DRM_FORMAT_GR88 : DRM_FORMAT_RG88); attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[1]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[1]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[1]; attr[i++]= EGL_NONE; eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, (EGLClientBuffer)NULL, attr ); if ( eglImage ) { surface->eglImage[1]= eglImage; if ( surface->textureId[1] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[1] ); } surface->textureId[1]= GL_NONE; } else { printf("wstRendererEMBPrepareResource: eglCreateImageKHR failed for fd %d, DRM_FORMAT_GR88: errno %X\n", fd[1], eglGetError()); } surface->textureCount= 2; } break; default: printf("wstRendererEMBPrepareResource: unsuppprted texture format: %x\n", frameFormat ); break; } } } #endif } #endif } } static void wstRendererEMBCommitShm( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { struct wl_shm_buffer *shmBuffer; int width, height, stride; GLint formatGL; GLenum type; bool transformPixelsA= false; bool transformPixelsB= false; bool fillAlpha= false; void *data; shmBuffer= wl_shm_buffer_get( resource ); if ( shmBuffer ) { width= wl_shm_buffer_get_width(shmBuffer); height= wl_shm_buffer_get_height(shmBuffer); stride= wl_shm_buffer_get_stride(shmBuffer); // The SHM formats describe the structure of the color channels for a pixel as // they would appear in a machine register not the byte order in memory. For // example WL_SHM_FORMAT_ARGB8888 is a 32 bit pixel with alpha in the 8 most significant // bits and blue in the 8 list significant bits. On a little endian machine the // byte order in memory would be B, G, R, A. switch( wl_shm_buffer_get_format(shmBuffer) ) { case WL_SHM_FORMAT_ARGB8888: #ifdef BIG_ENDIAN_CPU formatGL= GL_RGBA; transformPixelsA= true; #else #if defined (WESTEROS_HAVE_WAYLAND_EGL) if ( renderer->haveWaylandEGL ) { formatGL= GL_BGRA_EXT; } else { formatGL= GL_RGBA; transformPixelsB= true; } #elif defined (WESTEROS_PLATFORM_EMBEDDED) formatGL= GL_BGRA_EXT; #else formatGL= GL_RGBA; transformPixelsB= true; #endif #endif type= GL_UNSIGNED_BYTE; break; case WL_SHM_FORMAT_XRGB8888: #ifdef BIG_ENDIAN_CPU formatGL= GL_RGBA; transformPixelsA= true; #else #if defined (WESTEROS_HAVE_WAYLAND_EGL) if ( renderer->haveWaylandEGL ) { formatGL= GL_BGRA_EXT; } else { formatGL= GL_RGBA; transformPixelsB= true; } #elif defined (WESTEROS_PLATFORM_EMBEDDED) formatGL= GL_BGRA_EXT; #else formatGL= GL_RGBA; transformPixelsB= true; #endif #endif type= GL_UNSIGNED_BYTE; fillAlpha= true; break; case WL_SHM_FORMAT_BGRA8888: #ifdef BIG_ENDIAN_CPU #if defined (WESTEROS_HAVE_WAYLAND_EGL) if ( renderer->haveWaylandEGL ) { formatGL= GL_BGRA_EXT; } else { formatGL= GL_RGBA; transformPixelsB= true; } #elif defined (WESTEROS_PLATFORM_EMBEDDED) formatGL= GL_BGRA_EXT; #else formatGL= GL_RGBA; transformPixelsB= true; #endif #else formatGL= GL_RGBA; transformPixelsA= true; #endif type= GL_UNSIGNED_BYTE; break; case WL_SHM_FORMAT_BGRX8888: #ifdef BIG_ENDIAN_CPU #if defined (WESTEROS_HAVE_WAYLAND_EGL) if ( renderer->haveWaylandEGL ) { formatGL= GL_BGRA_EXT; } else { formatGL= GL_RGBA; transformPixelsB= true; } #elif defined (WESTEROS_PLATFORM_EMBEDDED) formatGL= GL_BGRA_EXT; #else formatGL= GL_RGBA; transformPixelsB= true; #endif #else formatGL= GL_RGBA; transformPixelsA= true; #endif type= GL_UNSIGNED_BYTE; fillAlpha= true; break; case WL_SHM_FORMAT_RGB565: formatGL= GL_RGB; type= GL_UNSIGNED_SHORT_5_6_5; break; case WL_SHM_FORMAT_ARGB4444: formatGL= GL_RGBA; type= GL_UNSIGNED_SHORT_4_4_4_4; break; default: formatGL= GL_NONE; break; } if ( formatGL != GL_NONE ) { wl_shm_buffer_begin_access(shmBuffer); data= wl_shm_buffer_get_data(shmBuffer); if ( surface->mem && ( (surface->memWidth != width) || (surface->memHeight != height) || (surface->memFormatGL != formatGL) || (surface->memType != type) ) ) { free( surface->mem ); surface->mem= 0; } if ( !surface->mem ) { surface->mem= (unsigned char*)malloc( stride*height ); } if ( surface->mem ) { memcpy( surface->mem, data, stride*height ); if ( transformPixelsA ) { // transform ARGB to RGBA unsigned int pixel, alpha; unsigned int *pixdata= (unsigned int*)surface->mem; for( int y= 0; y < height; ++y ) { for( int x= 0; x < width; ++x ) { pixel= pixdata[y*width+x]; alpha= (fillAlpha ? 0xFF : (pixel>>24)); pixel= (pixel<<8)|alpha; pixdata[y*width+x]= pixel; } } } else if ( transformPixelsB ) { // transform BGRA to RGBA unsigned char *pixdata= (unsigned char*)surface->mem; for( int y= 0; y < height; ++y ) { for( int x= 0; x < width; ++x ) { if ( fillAlpha ) { pixdata[y*width*4 + x*4 +3]= 0xFF; } unsigned char temp= pixdata[y*width*4 + x*4 +2]; pixdata[y*width*4 + x*4 +2]= pixdata[y*width*4 + x*4 +0]; pixdata[y*width*4 + x*4 +0]= temp; } } } else if ( fillAlpha ) { if ( fillAlpha ) { unsigned char *pixdata= (unsigned char*)surface->mem; for( int y= 0; y < height; ++y ) { for( int x= 0; x < width; ++x ) { pixdata[y*width*4 + x*4 +3]= 0xFF; } } } } surface->bufferWidth= width; surface->bufferHeight= height; surface->memWidth= width; surface->memHeight= height; surface->memFormatGL= formatGL; surface->memType= type; surface->memDirty= true; } wl_shm_buffer_end_access(shmBuffer); } } } #if defined (WESTEROS_HAVE_WAYLAND_EGL) static void wstRendererEMBCommitWaylandEGL( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource, EGLint format ) { EGLImageKHR eglImage= 0; EGLint value; EGLint attrList[3]; int bufferWidth= 0, bufferHeight= 0; if (EGL_TRUE == renderer->eglQueryWaylandBufferWL( renderer->eglDisplay, resource, EGL_WIDTH, &value ) ) { bufferWidth= value; } if (EGL_TRUE == renderer->eglQueryWaylandBufferWL( renderer->eglDisplay, resource, EGL_HEIGHT, &value ) ) { bufferHeight= value; } #if defined (WESTEROS_PLATFORM_RPI) /* * The Userland wayland-egl implementation used on RPI isn't complete in that it does not * support the use of eglCreateImageKHR using the wl_buffer resource and target EGL_WAYLAND_BUFFER_WL. * For that reason we need to supply a different method for handling buffers received via * wayland-egl on RPI */ { DISPMANX_RESOURCE_HANDLE_T dispResource= vc_dispmanx_get_handle_from_wl_buffer(resource); if ( dispResource != DISPMANX_NO_HANDLE ) { wstRendererEMBCommitDispmanx( renderer, surface, dispResource, format, bufferWidth, bufferHeight ); } } #else if ( (surface->bufferWidth != bufferWidth) || (surface->bufferHeight != bufferHeight) ) { surface->bufferWidth= bufferWidth; surface->bufferHeight= bufferHeight; } for( int i= 0; i < MAX_TEXTURES; ++i ) { if ( surface->eglImage[i] ) { renderer->eglDestroyImageKHR( renderer->eglDisplay, surface->eglImage[i] ); surface->eglImage[i]= 0; } } switch ( format ) { case EGL_TEXTURE_RGB: case EGL_TEXTURE_RGBA: eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_WAYLAND_BUFFER_WL, resource, NULL // EGLInt attrList[] ); if ( eglImage ) { /* * We have a new eglImage. Mark the surface as having no texture to * trigger texture creation during the next scene render */ surface->eglImage[0]= eglImage; if ( surface->textureId[0] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[0] ); } surface->textureId[0]= GL_NONE; surface->textureCount= 1; } break; case EGL_TEXTURE_Y_U_V_WL: printf("wstRendererEMBCommitWaylandEGL: EGL_TEXTURE_Y_U_V_WL not supported\n" ); break; case EGL_TEXTURE_Y_UV_WL: attrList[0]= EGL_WAYLAND_PLANE_WL; attrList[2]= EGL_NONE; for( int i= 0; i < 2; ++i ) { attrList[1]= i; eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_WAYLAND_BUFFER_WL, resource, attrList ); if ( eglImage ) { surface->eglImage[i]= eglImage; if ( surface->textureId[i] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[i] ); } surface->textureId[i]= GL_NONE; } } surface->textureCount= 2; break; case EGL_TEXTURE_Y_XUXV_WL: printf("wstRendererEMBCommitWaylandEGL: EGL_TEXTURE_Y_XUXV_WL not supported\n" ); break; default: printf("wstRendererEMBCommitWaylandEGL: unknown texture format: %x\n", format ); break; } #endif #if WESTEROS_INVERTED_Y surface->invertedY= true; #endif } #endif #ifdef ENABLE_SBPROTOCOL static void wstRendererEMBCommitSB( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { struct wl_sb_buffer *sbBuffer; void *deviceBuffer; int bufferWidth, bufferHeight; #if defined WESTEROS_PLATFORM_RPI int sbFormat; EGLint format= EGL_NONE; sbBuffer= WstSBBufferGet( resource ); if ( sbBuffer ) { deviceBuffer= WstSBBufferGetBuffer( sbBuffer ); if ( deviceBuffer ) { DISPMANX_RESOURCE_HANDLE_T dispResource= (DISPMANX_RESOURCE_HANDLE_T)deviceBuffer; bufferWidth= WstSBBufferGetWidth( sbBuffer ); bufferHeight= WstSBBufferGetHeight( sbBuffer ); sbFormat= WstSBBufferGetFormat( sbBuffer ); switch( sbFormat ) { case WL_SB_FORMAT_ARGB8888: case WL_SB_FORMAT_XRGB8888: format= EGL_TEXTURE_RGBA; break; } if ( format != EGL_NONE ) { wstRendererEMBCommitDispmanx( renderer, surface, dispResource, format, bufferWidth, bufferHeight ); } } } #else EGLNativePixmapType eglPixmap= 0; EGLImageKHR eglImage= 0; bool resize= false; sbBuffer= WstSBBufferGet( resource ); if ( sbBuffer ) { deviceBuffer= WstSBBufferGetBuffer( sbBuffer ); if ( deviceBuffer ) { if ( surface->nativePixmap ) { eglPixmap = (EGLNativePixmapType) WstGLGetEGLNativePixmap(renderer->glCtx, surface->nativePixmap); } if ( WstGLGetNativePixmap( renderer->glCtx, deviceBuffer, &surface->nativePixmap ) ) { WstGLGetNativePixmapDimensions( renderer->glCtx, surface->nativePixmap, &bufferWidth, &bufferHeight ); if ( (surface->bufferWidth != bufferWidth) || (surface->bufferHeight != bufferHeight) ) { surface->bufferWidth= bufferWidth; surface->bufferHeight= bufferHeight; resize= true; } if ( resize || (eglPixmap != (EGLNativePixmapType) WstGLGetEGLNativePixmap(renderer->glCtx, surface->nativePixmap)) ) { /* * If the eglPixmap contained by the surface WstGLNativePixmap changed * (because the attached buffer dimensions changed, for example) then we * need to create a new texture */ if ( surface->eglImage[0] ) { renderer->eglDestroyImageKHR( renderer->eglDisplay, surface->eglImage[0] ); surface->eglImage[0]= 0; } eglPixmap = (EGLNativePixmapType) WstGLGetEGLNativePixmap(renderer->glCtx, surface->nativePixmap); } if ( !surface->eglImage[0] ) { eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer) eglPixmap, NULL // EGLInt attrList[] ); if ( eglImage ) { /* * We have a new eglImage. Mark the surface as having no texture to * trigger texture creation during the next scene render */ surface->eglImage[0]= eglImage; if ( surface->textureId[0] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[0] ); } surface->textureId[0]= GL_NONE; } } } } #ifdef EGL_LINUX_DMA_BUF_EXT else if ( renderer->haveDmaBufImport ) { int fd= WstSBBufferGetFd( sbBuffer ); if ( fd >= 0 ) { wstRendererEMBPrepareResource( renderer, surface, resource ); } } #endif } #endif #if WESTEROS_INVERTED_Y surface->invertedY= true; #endif } #endif #ifdef ENABLE_LDBPROTOCOL static void wstRendererEMBPrepareResourceLDB( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { if ( surface && resource ) { EGLImageKHR eglImage= 0; struct wl_ldb_buffer *ldbBuffer; ldbBuffer= WstLDBBufferGet( resource ); if ( ldbBuffer ) { #ifdef EGL_LINUX_DMA_BUF_EXT if ( renderer->haveDmaBufImport ) { if ( WstLDBBufferGetFd( ldbBuffer ) >= 0 ) { int i; uint32_t frameFormat, frameWidth, frameHeight; int fd[MAX_TEXTURES]; int32_t offset[MAX_TEXTURES], stride[MAX_TEXTURES]; uint64_t modifier[MAX_TEXTURES]; bool useModifiers= false; EGLint attr[64]; frameFormat= WstLDBBufferGetFormat( ldbBuffer ); frameWidth= WstLDBBufferGetWidth( ldbBuffer ); frameHeight= WstLDBBufferGetHeight( ldbBuffer ); modifier[0]= DRM_FORMAT_MOD_INVALID; for( i= 0; i < MAX_TEXTURES; ++i ) { fd[i]= WstLDBBufferGetPlaneFd( ldbBuffer, i ); WstLDBBufferGetPlaneOffsetAndStride( ldbBuffer, i, &offset[i], &stride[i] ); if ( renderer->haveDmaBufImportModifiers ) { modifier[i]= WstLDBBufferGetPlaneModifier( ldbBuffer, i); } } useModifiers= renderer->haveDmaBufImportModifiers && (modifier[0] != DRM_FORMAT_MOD_INVALID); if ( (surface->bufferWidth != frameWidth) || (surface->bufferHeight != frameHeight) ) { surface->bufferWidth= frameWidth; surface->bufferHeight= frameHeight; } for( i= 0; i < MAX_TEXTURES; ++i ) { if ( surface->eglImage[i] ) { renderer->eglDestroyImageKHR( renderer->eglDisplay, surface->eglImage[i] ); surface->eglImage[i]= 0; } } i= 0; attr[i++]= EGL_WIDTH; attr[i++]= frameWidth; attr[i++]= EGL_HEIGHT; attr[i++]= frameHeight; attr[i++]= EGL_LINUX_DRM_FOURCC_EXT; attr[i++]= frameFormat; if ( ldbBuffer->info.planeCount > 0 ) { attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[0]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[0]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[0]; if ( useModifiers ) { attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; attr[i++]= (modifier[0] & 0xFFFFFFFFUL); attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; attr[i++]= ((modifier[0] >> 32) & 0xFFFFFFFFUL); } } if ( ldbBuffer->info.planeCount > 1 ) { attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[1]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[1]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[1]; if ( useModifiers ) { attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; attr[i++]= (modifier[1] & 0xFFFFFFFFUL); attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; attr[i++]= ((modifier[1] >> 32) & 0xFFFFFFFFUL); } } if ( ldbBuffer->info.planeCount > 2 ) { attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[2]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[2]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[2]; if ( useModifiers ) { attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; attr[i++]= (modifier[2] & 0xFFFFFFFFUL); attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; attr[i++]= ((modifier[2] >> 32) & 0xFFFFFFFFUL); } } if ( ldbBuffer->info.planeCount > 3 ) { attr[i++]= EGL_DMA_BUF_PLANE0_FD_EXT; attr[i++]= fd[3]; attr[i++]= EGL_DMA_BUF_PLANE0_OFFSET_EXT; attr[i++]= offset[3]; attr[i++]= EGL_DMA_BUF_PLANE0_PITCH_EXT; attr[i++]= stride[3]; if ( useModifiers ) { attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; attr[i++]= (modifier[3] & 0xFFFFFFFFUL); attr[i++]= EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; attr[i++]= ((modifier[3] >> 32) & 0xFFFFFFFFUL); } } attr[i++]= EGL_NONE; eglImage= renderer->eglCreateImageKHR( renderer->eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, (EGLClientBuffer)NULL, attr ); if ( eglImage ) { /* * We have a new eglImage. Mark the surface as having no texture to * trigger texture creation during the next scene render */ surface->eglImage[0]= eglImage; if ( surface->textureId[0] != GL_NONE ) { wstRendererDeleteTexture( renderer, surface->textureId[0] ); } surface->textureId[0]= GL_NONE; } else { printf("wstRendererEMBPrepareResourceLDB: eglCreateImageKHR failed for fd %d, format %X: errno %X\n", fd[0], frameFormat, eglGetError()); } surface->textureCount= 1; } } #endif } } } static void wstRendererEMBCommitLDB( WstRendererEMB *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { struct wl_ldb_buffer *ldbBuffer; void *deviceBuffer; int bufferWidth, bufferHeight; EGLNativePixmapType eglPixmap= 0; EGLImageKHR eglImage= 0; bool resize= false; ldbBuffer= WstLDBBufferGet( resource ); if ( ldbBuffer ) { #ifdef EGL_LINUX_DMA_BUF_EXT if ( renderer->haveDmaBufImport ) { int fd= WstLDBBufferGetFd( ldbBuffer ); if ( fd >= 0 ) { wstRendererEMBPrepareResourceLDB( renderer, surface, resource ); } } #endif } #if WESTEROS_INVERTED_Y surface->invertedY= true; #endif } #endif #if defined (WESTEROS_PLATFORM_RPI) static void wstRendererEMBCommitDispmanx( WstRendererEMB *renderer, WstRenderSurface *surface, DISPMANX_RESOURCE_HANDLE_T dispResource, EGLint format, int bufferWidth, int bufferHeight ) { int stride; GLint formatGL; GLenum type; if ( dispResource != DISPMANX_NO_HANDLE ) { switch ( format ) { case EGL_TEXTURE_RGB: case EGL_TEXTURE_RGBA: { stride= 4*bufferWidth; formatGL= GL_RGBA; type= GL_UNSIGNED_BYTE; if ( surface->mem && ( (surface->memWidth != bufferWidth) || (surface->memHeight != bufferHeight) || (surface->memFormatGL != formatGL) || (surface->memType != type) ) ) { free( surface->mem ); surface->mem= 0; } if ( !surface->mem ) { surface->mem= (unsigned char*)malloc( stride*bufferHeight ); } if ( surface->mem ) { VC_RECT_T rect; int result; rect.x= 0; rect.y= 0; rect.width= bufferWidth; rect.height= bufferHeight; result= vc_dispmanx_resource_read_data( dispResource, &rect, surface->mem, stride ); if ( result >= 0 ) { surface->bufferWidth= bufferWidth; surface->bufferHeight= bufferHeight; surface->memWidth= bufferWidth; surface->memHeight= bufferHeight; surface->memFormatGL= formatGL; surface->memType= type; surface->memDirty= true; } } } break; case EGL_TEXTURE_Y_U_V_WL: printf("wstRendererEMBCommitDispmanx: EGL_TEXTURE_Y_U_V_WL not supported\n" ); break; case EGL_TEXTURE_Y_UV_WL: printf("wstRendererEMBCommitDispmanx: EGL_TEXTURE_Y_UV_WL not supported\n" ); break; case EGL_TEXTURE_Y_XUXV_WL: printf("wstRendererEMBCommitDispmanx: EGL_TEXTURE_Y_XUXV_WL not supported\n" ); break; default: printf("wstRendererEMBCommitDispmanx: unknown texture format: %x\n", format ); break; } } } #endif static void wstRendererEMBRenderSurface( WstRendererEMB *renderer, WstRenderSurface *surface ) { if ( (surface->textureId[0] == GL_NONE) || surface->memDirty || surface->externalImage ) { for ( int i= 0; i < surface->textureCount; ++i ) { if ( surface->textureId[i] == GL_NONE ) { glGenTextures(1, &surface->textureId[i] ); } /* Bind the egl image as a texture */ glActiveTexture(GL_TEXTURE1+i); glBindTexture(GL_TEXTURE_2D, surface->textureId[i] ); #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) if ( surface->eglImage[i] && renderer->eglContext ) { #ifdef GL_OES_EGL_image_external if ( surface->externalImage ) { renderer->glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, surface->eglImage[i]); } else { #endif renderer->glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surface->eglImage[i]); #ifdef GL_OES_EGL_image_external } #endif } else #endif if ( i == 0 ) { if ( surface->mem ) { glTexImage2D( GL_TEXTURE_2D, 0, //level surface->memFormatGL, //internalFormat surface->memWidth, surface->memHeight, 0, // border surface->memFormatGL, //format surface->memType, surface->mem ); surface->memDirty= false; } } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } } if ( !surface->sizeOverride ) { surface->width= surface->bufferWidth; surface->height= surface->bufferHeight; } const float verts[4][2] = { { float(surface->x), float(surface->y) }, { float(surface->x+surface->width), float(surface->y) }, { float(surface->x), float(surface->y+surface->height) }, { float(surface->x+surface->width), float(surface->y+surface->height) } }; const float uvNormal[4][2] = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }; const float uvYInverted[4][2] = { { 0, 1 }, { 1, 1 }, { 0, 0 }, { 1, 0 } }; const float identityMatrix[4][4] = { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1} }; float *matrix= (renderer->renderer->hints & WstHints_applyTransform ? renderer->renderer->matrix : (float*)identityMatrix); float alpha= (renderer->renderer->hints & WstHints_applyTransform ? surface->opacity*renderer->renderer->alpha : surface->opacity ); float *uv; int resW, resH; GLint viewport[4]; if ( surface->haveCrop ) { uv= (float*)surface->cropTextureCoord; } else { uv= surface->invertedY ? (float*)uvYInverted : (float*)uvNormal; } if ( renderer->renderer->hints & WstHints_fboTarget ) { resW= renderer->renderer->outputWidth; resH= renderer->renderer->outputHeight; } else { glGetIntegerv( GL_VIEWPORT, viewport ); resW= viewport[2]; resH= viewport[3]; } if ( surface->textureCount == 1 ) { wstRendererEMBShaderDraw( surface->externalImage ? renderer->textureShaderExternal : renderer->textureShader, resW, resH, (float*)matrix, alpha, surface->textureId[0], GL_NONE, 4, (const float*)verts, (const float*)uv ); } else { wstRendererEMBShaderDraw( renderer->textureShaderYUV, resW, resH, (float*)matrix, alpha, surface->textureId[0], surface->textureId[1], 4, (const float*)verts, (const float*)uv ); } } static WstShader* wstRendererEMBCreateShader( WstRendererEMB *renderer, int shaderType ) { WstShader *shaderNew= 0; GLuint type; const char *typeName= 0, *src= 0; GLint shader, status, len; bool yuv= (shaderType == WstShaderType_yuv); bool noalpha; shaderNew= (WstShader*)calloc( 1, sizeof(WstShader)); if ( !shaderNew ) { printf("wstRendererEMBCreateShader: failed to allocate WstShader\n"); goto exit; } shaderNew->isYUV= yuv; shaderNew->program= GL_NONE; shaderNew->fragShader= GL_NONE; shaderNew->vertShader= GL_NONE; shaderNew->uniRes= -1; shaderNew->uniMatrix= -1; shaderNew->uniAlpha= -1; shaderNew->uniTexture= -1; shaderNew->uniTextureuv= -1; for( int i= 0; i < 2; ++i ) { if ( i == 0 ) { type= GL_FRAGMENT_SHADER; typeName= "fragment"; noalpha= true; if ( yuv ) { src= (renderer->haveDmaBufImport ? fShaderText_Y_UV : fShaderTextYUV); } else if ( shaderType == WstShaderType_external ) { src= fShaderTextExternal; } else { src= fShaderText; noalpha= false; } } else { type= GL_VERTEX_SHADER; typeName= "vertex"; src= ( yuv ? vShaderTextYUV : vShaderText ); } shader= glCreateShader(type); if ( !shader ) { printf("wstRendererEMBCreateShader: glCreateShader (%s) error: %d\n", typeName, glGetError()); goto exit; } glShaderSource(shader, 1, &src, NULL ); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if ( !status ) { glGetShaderInfoLog(shader, sizeof(message), &len, message); printf("wstRendererEMBCreateShader: %s shader compile error: (%s)\n", typeName, message); goto exit; } if ( i == 0 ) shaderNew->fragShader= shader; else shaderNew->vertShader= shader; } shaderNew->program= glCreateProgram(); if ( shaderNew->program == GL_NONE ) { printf("wstRendererEMBCreateShader: glCreateProgram error %d\n", glGetError()); goto exit; } glAttachShader(shaderNew->program, shaderNew->fragShader); glAttachShader(shaderNew->program, shaderNew->vertShader); shaderNew->attrPos= 0; glBindAttribLocation(shaderNew->program, shaderNew->attrPos, "pos"); shaderNew->attrTexcoord= 1; glBindAttribLocation(shaderNew->program, shaderNew->attrTexcoord, "texcoord"); if ( yuv ) { shaderNew->attrTexcoorduv= 2; glBindAttribLocation(shaderNew->program, shaderNew->attrTexcoorduv, "texcoorduv"); } glLinkProgram(shaderNew->program); glGetProgramiv(shaderNew->program, GL_LINK_STATUS, &status); if ( !status ) { glGetProgramInfoLog(shaderNew->program, sizeof(message), &len, message); printf("wstRendererEMBCreateShader: %s shader link error: (%s)\n", typeName, message); goto exit; } shaderNew->uniRes= glGetUniformLocation(shaderNew->program, "resolution"); if ( shaderNew->uniRes == -1 ) { printf("wstRendererEMBCreateShader: uniformn 'resolution' location error\n"); goto exit; } shaderNew->uniMatrix= glGetUniformLocation(shaderNew->program, "matrix"); if ( shaderNew->uniMatrix == -1 ) { printf("wstRendererEMBCreateShader: uniformn 'matrix' location error\n"); goto exit; } shaderNew->uniAlpha= glGetUniformLocation(shaderNew->program, "alpha"); if ( (shaderNew->uniAlpha == -1) && !noalpha ) { printf("wstRendererEMBCreateShader: uniformn 'alpha' location error\n"); goto exit; } shaderNew->uniTexture= glGetUniformLocation(shaderNew->program, "texture"); if ( shaderNew->uniTexture == -1 ) { printf("wstRendererEMBCreateShader: uniformn 'texture' location error\n"); goto exit; } if ( yuv ) { shaderNew->uniTextureuv= glGetUniformLocation(shaderNew->program, "textureuv"); if ( shaderNew->uniTextureuv == -1 ) { printf("wstRendererEMBCreateShader: uniformn 'textureuv' location error\n"); goto exit; } } exit: return shaderNew; } static void wstRendererEMBDestroyShader( WstShader *shader ) { if ( shader ) { if ( shader->program != GL_NONE ) { if ( shader->fragShader != GL_NONE ) { glDetachShader( shader->program, shader->fragShader ); glDeleteShader( shader->fragShader ); shader->fragShader= GL_NONE; } if ( shader->vertShader != GL_NONE ) { glDetachShader( shader->program, shader->vertShader ); glDeleteShader( shader->vertShader ); shader->vertShader= GL_NONE; } glDeleteProgram( shader->program ); shader->program= GL_NONE; } free( shader ); } } static void wstRendererEMBShaderDraw( WstShader *shader, int width, int height, float* matrix, float alpha, GLuint textureId, GLuint textureUVId, int count, const float* vc, const float* txc ) { glUseProgram( shader->program ); glUniformMatrix4fv( shader->uniMatrix, 1, GL_FALSE, matrix ); glUniform2f( shader->uniRes, width, height ); if ( shader->uniAlpha != -1 ) { glUniform1f( shader->uniAlpha, alpha ); } glActiveTexture(GL_TEXTURE1); glBindTexture( GL_TEXTURE_2D, textureId ); glUniform1i( shader->uniTexture, 1 ); if ( shader->isYUV ) { glActiveTexture(GL_TEXTURE2); glBindTexture( GL_TEXTURE_2D, textureUVId ); glUniform1i( shader->uniTextureuv, 2 ); } glVertexAttribPointer( shader->attrPos, 2, GL_FLOAT, GL_FALSE, 0, vc ); glVertexAttribPointer( shader->attrTexcoord, 2, GL_FLOAT, GL_FALSE, 0, txc ); if ( shader->isYUV ) { glVertexAttribPointer( shader->attrTexcoorduv, 2, GL_FLOAT, GL_FALSE, 0, txc ); } glEnableVertexAttribArray( shader->attrPos ); glEnableVertexAttribArray( shader->attrTexcoord ); if ( shader->isYUV ) { glEnableVertexAttribArray( shader->attrTexcoorduv ); } glDrawArrays( GL_TRIANGLE_STRIP, 0, count ); glDisableVertexAttribArray( shader->attrPos ); glDisableVertexAttribArray( shader->attrTexcoord ); if ( shader->isYUV ) { glDisableVertexAttribArray( shader->attrTexcoorduv ); } } static void wstRendererTerm( WstRenderer *renderer ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( rendererEMB ) { wstRendererEMBDestroy( rendererEMB ); renderer->renderer= 0; } } static void wstRendererUpdateScene( WstRenderer *renderer ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; GLuint program; if ( emitFPS ) { static int frameCount= 0; static long long lastReportTime= -1LL; struct timeval tv; long long now; gettimeofday(&tv,0); now= tv.tv_sec*1000LL+(tv.tv_usec/1000LL); ++frameCount; if ( lastReportTime == -1LL ) lastReportTime= now; if ( now-lastReportTime > 5000 ) { double fps= ((double)frameCount*1000)/((double)(now-lastReportTime)); printf("westeros-render-embedded: fps %f\n", fps); lastReportTime= now; frameCount= 0; } } wstRendererProcessDeadTextures( rendererEMB ); if ( renderer->fastHint && rendererEMB->rendererFast && !rendererEMB->fastPathActive ) { rendererEMB->fastPathActive= wstRendererActivateFastPath( rendererEMB ); } if ( !renderer->fastHint && rendererEMB->fastPathActive ) { wstRendererDeactivateFastPath( rendererEMB ); rendererEMB->fastPathActive= false; } if ( rendererEMB->fastPathActive ) { rendererEMB->rendererFast->outputX= renderer->outputX; rendererEMB->rendererFast->outputY= renderer->outputY; rendererEMB->rendererFast->outputWidth= renderer->outputWidth; rendererEMB->rendererFast->outputHeight= renderer->outputHeight; rendererEMB->rendererFast->matrix= renderer->matrix; rendererEMB->rendererFast->alpha= renderer->alpha; if ( renderer->hints & WstHints_holePunch ) { int imax= rendererEMB->surfaces.size(); for( int i= 0; i < imax; ++i ) { WstRenderSurface *surface= rendererEMB->surfaces[i]; if ( surface->visible ) { int sx, sy, sw, sh; if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceGetGeometry( rendererEMB->rendererFast, surface->surfaceFast, &sx, &sy, &sw, &sh ); if ( sw && sh ) { WstRect r; r.x= renderer->matrix[0]*sx+renderer->matrix[12]; r.y= renderer->matrix[5]*sy+renderer->matrix[13]; r.width= renderer->matrix[0]*sw; r.height= renderer->matrix[5]*sh; wstRendererHolePunch( renderer, r.x, r.y, r.width, r.height ); } } } } renderer->needHolePunch= false; } else { renderer->needHolePunch= true; } rendererEMB->rendererFast->delegateUpdateScene( rendererEMB->rendererFast, renderer->rects ); return; } glGetIntegerv( GL_CURRENT_PROGRAM, (GLint*)&program ); if ( !rendererEMB->textureShader ) { rendererEMB->textureShader= wstRendererEMBCreateShader( rendererEMB, WstShaderType_rgb ); rendererEMB->textureShaderYUV= wstRendererEMBCreateShader( rendererEMB, WstShaderType_yuv ); if ( rendererEMB->haveExternalImage ) { rendererEMB->textureShaderExternal= wstRendererEMBCreateShader( rendererEMB, WstShaderType_external ); } rendererEMB->eglContext= eglGetCurrentContext(); } /* * Render surfaces from bottom to top */ int imax= rendererEMB->surfaces.size(); for( int i= 0; i < imax; ++i ) { WstRenderSurface *surface= rendererEMB->surfaces[i]; if ( surface->visible && ( #if defined (WESTEROS_PLATFORM_EMBEDDED) || defined (WESTEROS_HAVE_WAYLAND_EGL) surface->eglImage[0] || #endif surface->memDirty || (surface->textureId[0] != GL_NONE) ) ) { wstRendererEMBRenderSurface( rendererEMB, surface ); } } glUseProgram( program ); #if defined (WESTEROS_PLATFORM_NEXUS ) { static bool needFinish= (getenv("WAYLAND_EGL_BNXS_ZEROCOPY") == NULL); // The calls to glFlush/glFinish are not required except on the Broadcom Nexus platform // when older versions of wayland-egl-bnxs are being used. This code will be removed // in the near future. if ( needFinish ) { glFlush(); glFinish(); } } #endif } static WstRenderSurface* wstRendererSurfaceCreate( WstRenderer *renderer ) { WstRenderSurface *surface; WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; surface= wstRendererEMBCreateSurface(rendererEMB); std::vector<WstRenderSurface*>::iterator it= rendererEMB->surfaces.begin(); while ( it != rendererEMB->surfaces.end() ) { if ( surface->zorder < (*it)->zorder ) { break; } ++it; } rendererEMB->surfaces.insert(it,surface); return surface; } static void wstRendererSurfaceDestroy( WstRenderer *renderer, WstRenderSurface *surface ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; for ( std::vector<WstRenderSurface*>::iterator it= rendererEMB->surfaces.begin(); it != rendererEMB->surfaces.end(); ++it ) { if ( (*it) == surface ) { rendererEMB->surfaces.erase(it); break; } } wstRendererEMBDestroySurface( rendererEMB, surface ); } static void wstRendererSurfaceCommit( WstRenderer *renderer, WstRenderSurface *surface, struct wl_resource *resource ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; EGLint value; if ( renderer->fastHint && rendererEMB->rendererFast && !rendererEMB->fastPathActive ) { rendererEMB->fastPathActive= wstRendererActivateFastPath( rendererEMB ); } if ( !renderer->fastHint && rendererEMB->fastPathActive ) { wstRendererDeactivateFastPath( rendererEMB ); rendererEMB->fastPathActive= false; } if ( rendererEMB->fastPathActive ) { rendererEMB->rendererFast->surfaceCommit( rendererEMB->rendererFast, surface->surfaceFast, resource ); return; } if ( resource ) { if ( wl_shm_buffer_get( resource ) ) { wstRendererEMBCommitShm( rendererEMB, surface, resource ); } #if defined (WESTEROS_HAVE_WAYLAND_EGL) else if ( rendererEMB->haveWaylandEGL && (EGL_TRUE == rendererEMB->eglQueryWaylandBufferWL( rendererEMB->eglDisplay, resource, EGL_TEXTURE_FORMAT, &value ) ) ) { wstRendererEMBCommitWaylandEGL( rendererEMB, surface, resource, value ); } #endif #ifdef ENABLE_SBPROTOCOL else if ( WstSBBufferGet( resource ) ) { wstRendererEMBCommitSB( rendererEMB, surface, resource ); } #endif #ifdef ENABLE_LDBPROTOCOL else if ( WstLDBBufferGet( resource ) ) { wstRendererEMBCommitLDB( rendererEMB, surface, resource ); } #endif else { printf("wstRenderSurfaceCommit: unsupported buffer type\n"); } } else { wstRendererEMBFlushSurface( rendererEMB, surface ); } } static void wstRendererSurfaceSetVisible( WstRenderer *renderer, WstRenderSurface *surface, bool visible ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { surface->visible= visible; if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceSetVisible( rendererEMB->rendererFast, surface->surfaceFast, visible ); } } } static bool wstRendererSurfaceGetVisible( WstRenderer *renderer, WstRenderSurface *surface, bool *visible ) { bool isVisible= false; WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceGetVisible( rendererEMB->rendererFast, surface->surfaceFast, &surface->visible ); } isVisible= surface->visible; *visible= isVisible; } return isVisible; } static void wstRendererSurfaceSetGeometry( WstRenderer *renderer, WstRenderSurface *surface, int x, int y, int width, int height ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { if ( (width != surface->width) || (height != surface->height) ) { surface->sizeOverride= true; } surface->x= x; surface->y= y; surface->width= width; surface->height= height; surface->dirty= true; surface->haveCrop= false; if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceSetGeometry( rendererEMB->rendererFast, surface->surfaceFast, x, y, width, height ); } } } void wstRendererSurfaceGetGeometry( WstRenderer *renderer, WstRenderSurface *surface, int *x, int *y, int *width, int *height ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceGetGeometry( rendererEMB->rendererFast, surface->surfaceFast, &surface->x, &surface->y, &surface->width, &surface->height ); } *x= surface->x; *y= surface->y; *width= surface->width; *height= surface->height; } } static void wstRendererSurfaceSetOpacity( WstRenderer *renderer, WstRenderSurface *surface, float opacity ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { surface->opacity= opacity; if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceSetOpacity( rendererEMB->rendererFast, surface->surfaceFast, opacity ); } } } static float wstRendererSurfaceGetOpacity( WstRenderer *renderer, WstRenderSurface *surface, float *opacity ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; float opacityLevel= 1.0; if ( surface ) { if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceGetOpacity( rendererEMB->rendererFast, surface->surfaceFast, &surface->opacity ); } opacityLevel= surface->opacity; *opacity= opacityLevel; } return opacityLevel; } static void wstRendererSurfaceSetZOrder( WstRenderer *renderer, WstRenderSurface *surface, float z ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { surface->zorder= z; // Remove from surface list for ( std::vector<WstRenderSurface*>::iterator it= rendererEMB->surfaces.begin(); it != rendererEMB->surfaces.end(); ++it ) { if ( (*it) == surface ) { rendererEMB->surfaces.erase(it); break; } } // Re-insert in surface list based on new z-order std::vector<WstRenderSurface*>::iterator it= rendererEMB->surfaces.begin(); while ( it != rendererEMB->surfaces.end() ) { if ( surface->zorder < (*it)->zorder ) { break; } ++it; } rendererEMB->surfaces.insert(it,surface); if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceSetZOrder( rendererEMB->rendererFast, surface->surfaceFast, z ); } } } static float wstRendererSurfaceGetZOrder( WstRenderer *renderer, WstRenderSurface *surface, float *z ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; float zLevel= 1.0; if ( surface ) { if ( surface->surfaceFast ) { rendererEMB->rendererFast->surfaceGetZOrder( rendererEMB->rendererFast, surface->surfaceFast, &surface->zorder ); } zLevel= surface->zorder; *z= zLevel; } return zLevel; } #define TEXTURE_CROP_DENOM (100000) static void wstRendererSurfaceSetCrop( WstRenderer *renderer, WstRenderSurface *surface, float x, float y, float width, float height ) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; if ( surface ) { if ( (surface->width > 0) && (surface->height > 0) ) { float tx1, ty1, tx2, ty2; tx1= x; tx2= x+width; ty1= y; ty2= y+height; if ( surface->invertedY ) { surface->cropTextureCoord[0][0]= tx1; surface->cropTextureCoord[0][1]= ty2; surface->cropTextureCoord[1][0]= tx2; surface->cropTextureCoord[1][1]= ty2; surface->cropTextureCoord[2][0]= tx1; surface->cropTextureCoord[2][1]= ty1; surface->cropTextureCoord[3][0]= tx2; surface->cropTextureCoord[3][1]= ty1; } else { surface->cropTextureCoord[0][0]= tx1; surface->cropTextureCoord[0][1]= ty1; surface->cropTextureCoord[1][0]= tx2; surface->cropTextureCoord[1][1]= ty1; surface->cropTextureCoord[2][0]= tx1; surface->cropTextureCoord[2][1]= ty2; surface->cropTextureCoord[3][0]= tx2; surface->cropTextureCoord[3][1]= ty2; } surface->haveCrop= true; } } } #ifdef ENABLE_LDBPROTOCOL static void wstRendererQueryDmabufFormats( WstRenderer *renderer, int **formats, int *num_formats) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; EGLBoolean b; EGLint numFormats; *num_formats= 0; *formats= 0; b= rendererEMB->eglQueryDmaBufFormatsEXT( rendererEMB->eglDisplay, 0, NULL, &numFormats ); if ( b ) { EGLint *theFormats= 0; theFormats= (EGLint*)calloc( numFormats, sizeof(EGLint) ); if ( theFormats == 0 ) { printf("wstRendererQueryDmabufFormats: eglQueryDmaBufFormatsEXT: failed to get num formats\n" ); goto exit; } b= rendererEMB->eglQueryDmaBufFormatsEXT( rendererEMB->eglDisplay, numFormats, theFormats, &numFormats ); if ( !b ) { printf("wstRendererQueryDmabufFormats: eglQueryDmaBufFormatsEXT: failed to get formats\n" ); free( theFormats ); goto exit; } *num_formats= numFormats; *formats= theFormats; } exit: return; } static void wstRendererQueryDmabufModifiers( WstRenderer *renderer, int format, uint64_t **modifiers, int *num_modifiers) { WstRendererEMB *rendererEMB= (WstRendererEMB*)renderer->renderer; EGLBoolean b; EGLint numModifiers; *num_modifiers= 0; *modifiers= 0; b= rendererEMB->eglQueryDmaBufModifiersEXT( rendererEMB->eglDisplay, format, 0, NULL, NULL, &numModifiers ); if ( b ) { uint64_t *theModifiers= 0; theModifiers= (uint64_t*)calloc( numModifiers, sizeof(uint64_t) ); if ( theModifiers == 0 ) { printf("wstRendererQueryDmabufModifiers: eglQueryDmaBufModifiersEXT: failed to get num modifiers\n" ); goto exit; } b= rendererEMB->eglQueryDmaBufModifiersEXT( rendererEMB->eglDisplay, format, numModifiers, theModifiers, NULL, &numModifiers ); if ( !b ) { printf("wstRendererQueryDmabufModifiers: eglQueryDmaBufModifiersEXT: failed to get modifiers\n" ); free( theModifiers ); goto exit; } *num_modifiers= numModifiers; *modifiers= theModifiers; } exit: return; } #endif static void wstRendererHolePunch( WstRenderer *renderer, int x, int y, int width, int height ) { GLfloat priorColor[4]; GLint priorBox[4]; GLint viewport[4]; WstRect r; bool wasEnabled= glIsEnabled(GL_SCISSOR_TEST); glGetIntegerv( GL_SCISSOR_BOX, priorBox ); glGetFloatv( GL_COLOR_CLEAR_VALUE, priorColor ); glGetIntegerv( GL_VIEWPORT, viewport ); glEnable( GL_SCISSOR_TEST ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); r.x= x; r.y= y; r.width= width; r.height= height; glScissor( r.x, viewport[3]-(r.y+r.height), r.width, r.height ); glClear( GL_COLOR_BUFFER_BIT ); glClearColor( priorColor[0], priorColor[1], priorColor[2], priorColor[3] ); if ( wasEnabled ) { glScissor( priorBox[0], priorBox[1], priorBox[2], priorBox[3] ); } else { glDisable( GL_SCISSOR_TEST ); } } static void wstRendererInitFastPath( WstRendererEMB *renderer ) { bool error= false; void *module= 0, *init; WstRenderer *rendererFast= 0; int rc; char *moduleName= getenv("WESTEROS_FAST_RENDER"); if ( moduleName ) { module= dlopen( moduleName, RTLD_NOW ); if ( !module ) { printf("wstRendererInitFastPath: failed to load module (%s)\n", moduleName); printf(" detail: %s\n", dlerror() ); error= true; goto exit; } init= dlsym( module, RENDERER_MODULE_INIT ); if ( !init ) { printf("wstRendererInitFastPath: failed to find module (%s) method (%s)\n", moduleName, RENDERER_MODULE_INIT ); printf(" detail: %s\n", dlerror() ); error= true; goto exit; } rendererFast= (WstRenderer*)calloc( 1, sizeof(WstRenderer) ); if ( !rendererFast ) { printf("wstRendererInitFastPath: no memory to allocate WstRender\n"); error= true; goto exit; } rendererFast->outputWidth= renderer->renderer->outputWidth; rendererFast->outputHeight= renderer->renderer->outputHeight; rendererFast->nativeWindow= renderer->renderer->nativeWindow; rc= ((WSTMethodRenderInit)init)( rendererFast, 0, NULL ); if ( rc ) { printf("wstRendererInitFastPath: module (%s) init failed: %d\n", moduleName, rc ); error= true; goto exit; } if ( !rendererFast->delegateUpdateScene ) { printf("wstRendererInitFastPath: module (%s) does not support delegation\n", moduleName ); error= true; goto exit; } renderer->rendererFast= rendererFast; printf("wstRendererInitFastPath: module (%s) loaded and intialized\n", moduleName ); } exit: if ( error ) { if ( rendererFast ) { if ( rendererFast->renderer ) { rendererFast->renderTerm( rendererFast ); rendererFast->renderer= 0; } free( rendererFast ); } if ( module ) { dlclose( module ); } } } static bool wstRendererActivateFastPath( WstRendererEMB *renderer ) { bool result= false; if ( renderer->rendererFast ) { result= true; // Create fast surface instances for each surface int imax= renderer->surfaces.size(); for( int i= 0; i < imax; ++i ) { WstRenderSurface *surface= renderer->surfaces[i]; if ( !surface->surfaceFast ) { surface->surfaceFast= renderer->rendererFast->surfaceCreate( renderer->rendererFast ); if ( !surface->surfaceFast ) { result= false; break; } renderer->rendererFast->surfaceSetGeometry( renderer->rendererFast, surface->surfaceFast, surface->x, surface->y, surface->width, surface->height ); renderer->rendererFast->surfaceSetOpacity( renderer->rendererFast, surface->surfaceFast, surface->opacity ); renderer->rendererFast->surfaceSetZOrder( renderer->rendererFast, surface->surfaceFast, surface->zorder ); } } if ( result ) { // Discard texture info for all surfaces for( int i= 0; i < imax; ++i ) { WstRenderSurface *surface= renderer->surfaces[i]; wstRendererEMBFlushSurface( renderer, surface ); } } } return result; } static void wstRendererDeactivateFastPath( WstRendererEMB *renderer ) { if ( renderer->rendererFast ) { // Discard all fast surfaces int imax= renderer->surfaces.size(); for( int i= 0; i < imax; ++i ) { WstRenderSurface *surface= renderer->surfaces[i]; if ( surface->surfaceFast && (surface->zorder != 1000000.0) ) { renderer->rendererFast->surfaceGetGeometry( renderer->rendererFast, surface->surfaceFast, &surface->x, &surface->y, &surface->width, &surface->height ); renderer->rendererFast->surfaceDestroy( renderer->rendererFast, surface->surfaceFast ); surface->surfaceFast= 0; } } } } static void wstRendererDeleteTexture( WstRendererEMB *renderer, GLuint textureId ) { renderer->deadTextures.push_back( textureId ); } static void wstRendererProcessDeadTextures( WstRendererEMB *renderer ) { GLuint textureId; for( int i= renderer->deadTextures.size()-1; i >= 0; --i ) { textureId= renderer->deadTextures[i]; glDeleteTextures( 1, &textureId ); renderer->deadTextures.pop_back(); } } extern "C" { int renderer_init( WstRenderer *renderer, int argc, char **argv ) { int rc= 0; WstRendererEMB *rendererEMB= 0; rendererEMB= wstRendererEMBCreate( renderer ); if ( rendererEMB ) { renderer->renderer= rendererEMB; renderer->renderTerm= wstRendererTerm; renderer->updateScene= wstRendererUpdateScene; renderer->surfaceCreate= wstRendererSurfaceCreate; renderer->surfaceDestroy= wstRendererSurfaceDestroy; renderer->surfaceCommit= wstRendererSurfaceCommit; renderer->surfaceSetVisible= wstRendererSurfaceSetVisible; renderer->surfaceGetVisible= wstRendererSurfaceGetVisible; renderer->surfaceSetGeometry= wstRendererSurfaceSetGeometry; renderer->surfaceGetGeometry= wstRendererSurfaceGetGeometry; renderer->surfaceSetOpacity= wstRendererSurfaceSetOpacity; renderer->surfaceGetOpacity= wstRendererSurfaceGetOpacity; renderer->surfaceSetZOrder= wstRendererSurfaceSetZOrder; renderer->surfaceGetZOrder= wstRendererSurfaceGetZOrder; renderer->surfaceSetCrop= wstRendererSurfaceSetCrop; #ifdef ENABLE_LDBPROTOCOL renderer->queryDmabufFormats= wstRendererQueryDmabufFormats; renderer->queryDmabufModifiers= wstRendererQueryDmabufModifiers; #endif renderer->holePunch= wstRendererHolePunch; wstRendererInitFastPath( rendererEMB ); } else { rc= -1; } exit: return 0; } }
33.201687
155
0.544781
[ "render", "vector", "transform" ]
c9efc846a1492186a6415860b1201eef9477d75d
1,694
hpp
C++
include/codegen/include/System/Text/StringBuilderCache.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Text/StringBuilderCache.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Text/StringBuilderCache.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:42 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: System.Text namespace System::Text { // Autogenerated type: System.Text.StringBuilderCache class StringBuilderCache : public ::Il2CppObject { public: // Get static field: static private System.Text.StringBuilder CachedInstance static System::Text::StringBuilder* _get_CachedInstance(); // Set static field: static private System.Text.StringBuilder CachedInstance static void _set_CachedInstance(System::Text::StringBuilder* value); // static public System.Text.StringBuilder Acquire(System.Int32 capacity) // Offset: 0x13B2E54 static System::Text::StringBuilder* Acquire(int capacity); // static public System.Void Release(System.Text.StringBuilder sb) // Offset: 0x13B2F18 static void Release(System::Text::StringBuilder* sb); // static public System.String GetStringAndRelease(System.Text.StringBuilder sb) // Offset: 0x13B2F98 static ::Il2CppString* GetStringAndRelease(System::Text::StringBuilder* sb); }; // System.Text.StringBuilderCache } DEFINE_IL2CPP_ARG_TYPE(System::Text::StringBuilderCache*, "System.Text", "StringBuilderCache"); #pragma pack(pop)
41.317073
95
0.723731
[ "object" ]
c9f1d93eb87194a2efbf921abf5be3d71baac521
6,394
hpp
C++
openstudiocore/src/model/ElectricLoadCenterInverterLookUpTable.hpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/ElectricLoadCenterInverterLookUpTable.hpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/ElectricLoadCenterInverterLookUpTable.hpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #ifndef MODEL_ELECTRICLOADCENTERINVERTERLOOKUPTABLE_HPP #define MODEL_ELECTRICLOADCENTERINVERTERLOOKUPTABLE_HPP #include "ModelAPI.hpp" #include "Inverter.hpp" namespace openstudio { namespace model { class Schedule; class ThermalZone; namespace detail { class ElectricLoadCenterInverterLookUpTable_Impl; } // detail /** ElectricLoadCenterInverterLookUpTable is a Inverter that wraps the OpenStudio IDD object 'OS:ElectricLoadCenter:Inverter:LookUpTable'. */ class MODEL_API ElectricLoadCenterInverterLookUpTable : public Inverter { public: /** @name Constructors and Destructors */ //@{ explicit ElectricLoadCenterInverterLookUpTable(const Model& model); virtual ~ElectricLoadCenterInverterLookUpTable() {} //@} static IddObjectType iddObjectType(); /** @name Getters */ //@{ boost::optional<Schedule> availabilitySchedule() const; boost::optional<double> radiativeFraction() const; boost::optional<double> ratedMaximumContinuousOutputPower() const; boost::optional<double> nightTareLossPower() const; boost::optional<double> nominalVoltageInput() const; // DLM: the IDD for these fields looks weird, there is no default and the field is not required but I don't // see how the object would work without values for these fields boost::optional<double> efficiencyAt10PowerAndNominalVoltage() const; boost::optional<double> efficiencyAt20PowerAndNominalVoltage() const; boost::optional<double> efficiencyAt30PowerAndNominalVoltage() const; boost::optional<double> efficiencyAt50PowerAndNominalVoltage() const; boost::optional<double> efficiencyAt75PowerAndNominalVoltage() const; boost::optional<double> efficiencyAt100PowerAndNominalVoltage() const; //@} /** @name Setters */ //@{ bool setAvailabilitySchedule(Schedule& schedule); void resetAvailabilitySchedule(); bool setRadiativeFraction(double radiativeFraction); void resetRadiativeFraction(); bool setRatedMaximumContinuousOutputPower(double ratedMaximumContinuousOutputPower); void resetRatedMaximumContinuousOutputPower(); bool setNightTareLossPower(double nightTareLossPower); void resetNightTareLossPower(); bool setNominalVoltageInput(double nominalVoltageInput); void resetNominalVoltageInput(); bool setEfficiencyAt10PowerAndNominalVoltage(double efficiencyAt10PowerAndNominalVoltage); void resetEfficiencyAt10PowerAndNominalVoltage(); bool setEfficiencyAt20PowerAndNominalVoltage(double efficiencyAt20PowerAndNominalVoltage); void resetEfficiencyAt20PowerAndNominalVoltage(); bool setEfficiencyAt30PowerAndNominalVoltage(double efficiencyAt30PowerAndNominalVoltage); void resetEfficiencyAt30PowerAndNominalVoltage(); bool setEfficiencyAt50PowerAndNominalVoltage(double efficiencyAt50PowerAndNominalVoltage); void resetEfficiencyAt50PowerAndNominalVoltage(); bool setEfficiencyAt75PowerAndNominalVoltage(double efficiencyAt75PowerAndNominalVoltage); void resetEfficiencyAt75PowerAndNominalVoltage(); bool setEfficiencyAt100PowerAndNominalVoltage(double efficiencyAt100PowerAndNominalVoltage); void resetEfficiencyAt100PowerAndNominalVoltage(); //@} /** @name Other */ //@{ //@} protected: /// @cond typedef detail::ElectricLoadCenterInverterLookUpTable_Impl ImplType; explicit ElectricLoadCenterInverterLookUpTable(std::shared_ptr<detail::ElectricLoadCenterInverterLookUpTable_Impl> impl); friend class detail::ElectricLoadCenterInverterLookUpTable_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.ElectricLoadCenterInverterLookUpTable"); }; /** \relates ElectricLoadCenterInverterLookUpTable*/ typedef boost::optional<ElectricLoadCenterInverterLookUpTable> OptionalElectricLoadCenterInverterLookUpTable; /** \relates ElectricLoadCenterInverterLookUpTable*/ typedef std::vector<ElectricLoadCenterInverterLookUpTable> ElectricLoadCenterInverterLookUpTableVector; } // model } // openstudio #endif // MODEL_ELECTRICLOADCENTERINVERTERLOOKUPTABLE_HPP
34.376344
141
0.771817
[ "object", "vector", "model" ]
c9f40c40f5199e68411797553563e7d3650b7095
4,078
cpp
C++
src/base/util/SpiceKernelReader.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/base/util/SpiceKernelReader.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/base/util/SpiceKernelReader.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id:$ //------------------------------------------------------------------------------ // SpiceKernelReader //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under // FDSS Task order 28. // // Author: Wendy C. Shoan // Created: 2009.02.24 // /** * Implementation of the SpicKernelReader, which reads SPICE data (kernel) files. * This class calls the JPL-supplied CSPICE routines to read the specified * SPICE file and return the requested data. */ //------------------------------------------------------------------------------ #include "SpiceKernelReader.hpp" #include "A1Mjd.hpp" #include "StringUtil.hpp" #include "MessageInterface.hpp" #include "TimeTypes.hpp" #include "TimeSystemConverter.hpp" #include "UtilityException.hpp" //#define DEBUG_SPICE_KERNEL_READER //--------------------------------- // static data //--------------------------------- const Integer SpiceKernelReader::MAX_IDS_PER_KERNEL = 200; const Integer SpiceKernelReader::MAX_COVERAGE_INTERVALS = 200000; //--------------------------------- // public methods //--------------------------------- //------------------------------------------------------------------------------ // SpiceKernelReader() //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceKernelReader class * (default constructor). * */ //------------------------------------------------------------------------------ SpiceKernelReader::SpiceKernelReader() : SpiceInterface(), objectNameSPICE (NULL), naifIDSPICE (-123456789), etSPICE (0.0), referenceFrameSPICE (NULL) { } //------------------------------------------------------------------------------ // SpiceKernelReader(const SpiceKernelReader &reader) //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceKernelReader class, by copying * the input object. * (copy constructor). * * @param <reader> SpiceKernelReader object to copy. */ //------------------------------------------------------------------------------ SpiceKernelReader::SpiceKernelReader(const SpiceKernelReader &reader) : SpiceInterface(reader), objectNameSPICE (NULL), naifIDSPICE (reader.naifIDSPICE), etSPICE (reader.etSPICE), referenceFrameSPICE (NULL) { } //------------------------------------------------------------------------------ // SpiceKernelReader& operator=(const SpiceKernelReader &reader) //------------------------------------------------------------------------------ /** * This method copies the data from the input object to the object. * * @param <reader> the SpiceKernelReader object whose data to assign to "this" * SpiceKernelReader. * * @return "this" SpiceKernelReader with data of input SpiceKernelReader reader. */ //------------------------------------------------------------------------------ SpiceKernelReader& SpiceKernelReader::operator=(const SpiceKernelReader &reader) { if (&reader == this) return *this; SpiceInterface::operator=(reader); objectNameSPICE = reader.objectNameSPICE; naifIDSPICE = reader.naifIDSPICE; etSPICE = reader.etSPICE; referenceFrameSPICE = reader.referenceFrameSPICE; return *this; } //------------------------------------------------------------------------------ // ~SpiceKernelReader() //------------------------------------------------------------------------------ /** * This method is the destructor for the SpiceKernelReader. * */ //------------------------------------------------------------------------------ SpiceKernelReader::~SpiceKernelReader() { }
33.983333
81
0.47229
[ "object" ]
c9f74839578f3199d695b1be02ea7143a0928c78
3,630
cc
C++
tensorflow/lite/delegates/gpu/gl/kernels/reshape_test.cc
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
7
2022-03-04T21:14:47.000Z
2022-03-22T23:07:39.000Z
tensorflow/lite/delegates/gpu/gl/kernels/reshape_test.cc
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
1
2022-03-08T18:28:46.000Z
2022-03-08T18:37:20.000Z
tensorflow/lite/delegates/gpu/gl/kernels/reshape_test.cc
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
1
2022-03-22T00:45:15.000Z
2022-03-22T00:45:15.000Z
/* Copyright 2019 The TensorFlow 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 "tensorflow/lite/delegates/gpu/gl/kernels/reshape.h" #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/gl/kernels/test_util.h" using ::testing::FloatNear; using ::testing::Pointwise; namespace tflite { namespace gpu { namespace gl { namespace { TEST(Reshape, 1x2x3To3x2x1) { TensorRef<BHWC> input; input.type = DataType::FLOAT32; input.ref = 0; input.shape = BHWC(1, 1, 2, 3); TensorRef<BHWC> output; output.type = DataType::FLOAT32; output.ref = 1; output.shape = BHWC(1, 3, 2, 1); ReshapeAttributes attr; attr.new_shape = output.shape; SingleOpModel model({ToString(OperationType::RESHAPE), attr}, {input}, {output}); ASSERT_TRUE(model.PopulateTensor(0, {1, 2, 3, 4, 5, 6})); ASSERT_OK(model.Invoke(*NewReshapeNodeShader())); EXPECT_THAT(model.GetOutput(0), Pointwise(FloatNear(1e-6), {1, 2, 3, 4, 5, 6})); } TEST(Reshape, 3x1x2To2x1x3) { TensorRef<BHWC> input; input.type = DataType::FLOAT32; input.ref = 0; input.shape = BHWC(1, 3, 1, 2); TensorRef<BHWC> output; output.type = DataType::FLOAT32; output.ref = 1; output.shape = BHWC(1, 2, 1, 3); ReshapeAttributes attr; attr.new_shape = output.shape; SingleOpModel model({ToString(OperationType::RESHAPE), attr}, {input}, {output}); ASSERT_TRUE(model.PopulateTensor(0, {1, 2, 3, 4, 5, 6})); ASSERT_OK(model.Invoke(*NewReshapeNodeShader())); EXPECT_THAT(model.GetOutput(0), Pointwise(FloatNear(1e-6), {1, 2, 3, 4, 5, 6})); } TEST(Reshape, 1x1x4To2x2x1) { TensorRef<BHWC> input; input.type = DataType::FLOAT32; input.ref = 0; input.shape = BHWC(1, 1, 1, 4); TensorRef<BHWC> output; output.type = DataType::FLOAT32; output.ref = 1; output.shape = BHWC(1, 2, 2, 1); ReshapeAttributes attr; attr.new_shape = output.shape; SingleOpModel model({ToString(OperationType::RESHAPE), attr}, {input}, {output}); ASSERT_TRUE(model.PopulateTensor(0, {1, 2, 3, 4})); ASSERT_OK(model.Invoke(*NewReshapeNodeShader())); EXPECT_THAT(model.GetOutput(0), Pointwise(FloatNear(1e-6), {1, 2, 3, 4})); } TEST(Reshape, BatchIsUnsupported) { TensorRef<BHWC> input; input.type = DataType::FLOAT32; input.ref = 0; input.shape = BHWC(4, 1, 1, 1); TensorRef<BHWC> output; output.type = DataType::FLOAT32; output.ref = 1; output.shape = BHWC(1, 2, 2, 1); ReshapeAttributes attr; attr.new_shape = output.shape; SingleOpModel model({ToString(OperationType::RESHAPE), attr}, {input}, {output}); ASSERT_TRUE(model.PopulateTensor(0, {1, 2, 3, 4})); ASSERT_THAT(model.Invoke(*NewReshapeNodeShader()).message(), testing::HasSubstr("Batch size mismatch, expected 4 but got 1")); } } // namespace } // namespace gl } // namespace gpu } // namespace tflite
29.512195
80
0.664463
[ "shape", "vector", "model" ]
c9fc4a690f93387ca4606f7bc16a90228236078c
49,126
cpp
C++
src/platform/msgmgr/MailboxLookupService.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
src/platform/msgmgr/MailboxLookupService.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
src/platform/msgmgr/MailboxLookupService.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * File name: MailboxLookupService.cpp * Subsystem: Platform Services * Description: This class represents the mailbox registry and provides methods * for applications to register, find and deregister their mailboxes * * Name Date Release * -------------------- ---------- --------------------------------------------- * Stephen Horton 01/01/2014 Initial release * * ******************************************************************************/ //----------------------------------------------------------------------------- // System include files, includes 3rd party libraries. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Component includes, includes elements of our system. //----------------------------------------------------------------------------- #include "DiscoveryManager.h" #include "DistributedMailboxProxy.h" #include "GroupMailboxProxy.h" #include "LocalSMMailboxProxy.h" #include "MailboxBase.h" #include "MailboxLookupService.h" #include "MailboxOwnerHandle.h" #include "MailboxHandle.h" #include "platform/logger/Logger.h" #include "platform/common/MailboxNames.h" #include "platform/threadmgr/ThreadManager.h" //----------------------------------------------------------------------------- // Static Declarations. //----------------------------------------------------------------------------- // Map for Local Mailbox registration MailboxLookupService::LocalMailboxRegistry MailboxLookupService::localMailboxRegistry_; // Non-Recursive Thread Mutex for protecting local registration map ACE_Thread_Mutex MailboxLookupService::localRegistryMutex_; // Map for Remote type Proxy Mailbox registration MailboxLookupService::ProxyMailboxRegistry MailboxLookupService::proxyMailboxRegistry_; // Non-Recursive Thread Mutex for protecting proxy registration map ACE_Thread_Mutex MailboxLookupService::proxyRegistryMutex_; // Flag to indicate whether or not the Discovery Manager group mailbox processor // has been initialized bool MailboxLookupService::isDiscoveryStarted_ = false; // Static instance of the DiscoveryManager DiscoveryManager* MailboxLookupService::discoveryManagerInstance_ = NULL; //----------------------------------------------------------------------------- // PUBLIC methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Method Type: Constructor // Description: // Design: //----------------------------------------------------------------------------- MailboxLookupService::MailboxLookupService() { }//end constructor //----------------------------------------------------------------------------- // Method Type: Virtual Destructor // Description: // Design: //----------------------------------------------------------------------------- MailboxLookupService::~MailboxLookupService() { }//end virtual destructor //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Instantiate and start the Discovery Manager // Design: //----------------------------------------------------------------------------- void MailboxLookupService::initializeDiscoveryManager() { if ((isDiscoveryStarted_ == true) || (discoveryManagerInstance_ != NULL)) { TRACELOG(ERRORLOG, MSGMGRLOG, "Discovery Manager already started",0,0,0,0,0,0); return; }//end if else { // Instantiate the static Discovery Manager discoveryManagerInstance_ = new DiscoveryManager(); // Mark the flag to indicate Discovery is started isDiscoveryStarted_ = true; if (discoveryManagerInstance_->initialize() == ERROR) { TRACELOG(ERRORLOG, MSGMGRLOG, "Unable to initialize the discovery manager",0,0,0,0,0,0); delete discoveryManagerInstance_; discoveryManagerInstance_ = NULL; isDiscoveryStarted_ = false; return; }//end if // Spawn a dedicated thread for the Discovery Manager ThreadManager::createThread((ACE_THR_FUNC)MailboxLookupService::startDiscoveryManager, 0, "DiscoveryManager", true); }//end else }//end initializeDiscoveryManager //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method allows tasks to register their mailboxes with the // lookup service. If a task has already registered their mailbox // it will be erased first and the new one registered in it's place. // Design: MailboxLookupService maintains three Mailbox registries (actually, a // 4th registry is used for discovery update notification callbacks): // - one for LocalMailboxes for which the MailboxAddress and a reference/ // handle to the actual mailbox is stored. These are for local // applications to perform a 'find' on and post messages to. // - one for remote type Non-Proxy Mailboxes for which ONLY the Mailbox // Address is stored. These addresses are tracked across cards via // the DiscoveryManager. Since remote type non-proxy mailboxes // also have an underlying Local Mailbox implementation as well, // their local Mailbox equivalent gets stored in the LocalMailbox // registry (for the case where a Local, same process application // wishes to post a message to a Distributed Mailbox's Local Mailbox // queue--without going through message serialization/deserialization). // NOTE: For this reason, it is NOT VALID to have two separate Mailbox // instances--one Local and another remote-- that have the same Mailbox Name. // - one for remote type Proxy Mailboxes for which the MailboxAddress and // a reference/handle to the Proxy mailbox is stored. //----------------------------------------------------------------------------- void MailboxLookupService::registerMailbox(MailboxOwnerHandle* mailboxOwnerHandle, MailboxBase *mailboxPtr) { // Pointer to an old Mailbox that is getting replaced in the registry in the event // that a duplicate is found MailboxBase* mailboxToReplace = NULL; if (mailboxOwnerHandle == NULL) { TRACELOG(ERRORLOG, MSGMGRLOG, "Null OwnerHandle passed to registerMailbox",0,0,0,0,0,0); return; }//end if else if (mailboxPtr == NULL) { TRACELOG(ERRORLOG, MSGMGRLOG, "Null mailbox pointer passed to registerMailbox",0,0,0,0,0,0); return; }//end else if //############## //# Local Registration //############## // Perform registration for Local Mailboxes if (mailboxOwnerHandle->getMailboxAddress().locationType == LOCAL_MAILBOX) { localRegistryMutex_.acquire(); // Here we use a regular iterator (rather than const_iterator) since const_iterator cannot // be used for insert/erase (see Scott Meyers effective STL) LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); pair<LocalMailboxRegistry::iterator, bool> insertResult; // Loop through the map looking for the Mailbox that matches the address. This is a // check to see if the Mailbox has already been registered and we need to replace. while (mailboxIterator != endIterator) { if (mailboxOwnerHandle->getMailboxAddress() == mailboxIterator->first) { ostringstream ostr; ostr << "Deactivating/Replacing the following local registry entry in the Lookup Service: " << mailboxOwnerHandle->getMailboxAddress().toString() << ends; STRACELOG(WARNINGLOG, MSGMGRLOG, ostr.str().c_str()); if (mailboxIterator->second->isActive()) { // Set a flag to later call deactivate on the Mailbox because all // activated mailboxes must be in the registry!! mailboxToReplace = mailboxIterator->second; }//end if else { // Found the corresponding Mailbox Address, so remove the Mailbox so we can replace it. localMailboxRegistry_.erase(mailboxIterator); }//end if break; }//end if mailboxIterator++; }//end while // For new registrations if (mailboxIterator == endIterator) { ostringstream ostr; ostr << "Registering the following Local Address with the MLS: " << mailboxOwnerHandle->getMailboxAddress().toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // After releasing the mutex on the local Registry, if we found the replaced mailbox to be // active, then we must deactivate it (which will ultimately perform the deregistration/erase for us) if (mailboxToReplace != NULL) { // Temporarily release the localMailboxRegistry mutex so that deactivate can perform // deregistration (This is needed since the mutex does NOT support recursive calls--we could use Recursive Mutex) localRegistryMutex_.release(); mailboxToReplace->deactivate(mailboxOwnerHandle); mailboxToReplace = NULL; // Re-acquire so that we can insert the new value into the registry localRegistryMutex_.acquire(); }//end if // Add the new mailbox to the registry (works for replacing existing entry or new) // Now, insert the mailbox/address into the map. This default 'insert' method is the only // one that provides a return/result value; otherwise, we would specify to insert at the end (endIterator) insertResult = localMailboxRegistry_.insert(make_pair(mailboxOwnerHandle->getMailboxAddress(),mailboxPtr)); // Check to see if the map insert was successful if (!insertResult.second) { TRACELOG(ERRORLOG, MSGMGRLOG, "LocalMailboxRegistry map insertion failed",0,0,0,0,0,0); }//end if localRegistryMutex_.release(); }//end if LocalMailbox // Perform registration for all other (Remote) Mailbox types else { //############## //# Non-Proxy Registration //############## // If this is a Non-proxy remote type Mailbox, then we need to register an equivalent // Local Mailbox address into the local registry (for the case where a Local, // same process application wishes to post a message to a Distributed Mailbox's // Local Mailbox queue--without going through message serialization/deserialization if (! mailboxPtr->isProxy()) { localRegistryMutex_.acquire(); // Here we use a regular iterator (rather than const_iterator) since const_iterator cannot // be used for insert/erase (see Scott Meyers effective STL) LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); pair<LocalMailboxRegistry::iterator, bool> insertResult; // Build the equivalent Local Mailbox Address for the remote type Mailbox that // we are attempting to register. NOTE: here Currently the Local Mailbox Addresses // really only consist of the location type and the Mailbox Name. MailboxAddress localAddress; localAddress.locationType = LOCAL_MAILBOX; localAddress.mailboxName = mailboxOwnerHandle->getMailboxAddress().mailboxName; // Loop through the map looping for the Mailbox that matches the address. This is a // check to see if the Mailbox has already been registered and we need to replace. This HERE is // the reason why a Local Mailbox and Remote Mailbox CANNOT have the same MailboxName!! while (mailboxIterator != endIterator) { if (localAddress == mailboxIterator->first) { ostringstream ostr; ostr << "Deactivating/Replacing the following local (remote-equivalent) registry entry in the Lookup Service: " << localAddress.toString() << ends; STRACELOG(WARNINGLOG, MSGMGRLOG, ostr.str().c_str()); if (mailboxIterator->second->isActive()) { // Set a flag to later call deactivate on the Mailbox because all // activated mailboxes must be in the registry!! mailboxToReplace = mailboxIterator->second; }//end if else { // Found the corresponding Mailbox Address, so remove the Mailbox so we can replace it. localMailboxRegistry_.erase(mailboxIterator); }//end if break; }//end if mailboxIterator++; }//end while // For new registrations if (mailboxIterator == endIterator) { ostringstream ostr; ostr << "Registered the following Local Address (remote-equivalent) with the MLS: " << localAddress.toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // After releasing the mutex on the local Registry, if we found the replaced mailbox to be // active, then we must deactivate it (which will ultimately perform the deregistration/erase for us) if (mailboxToReplace != NULL) { // Temporarily release the localMailboxRegistry mutex so that deactivate can perform // deregistration (This is needed since the mutex does NOT support recursive calls; we could use recursive mutex) localRegistryMutex_.release(); mailboxToReplace->deactivate(mailboxOwnerHandle); mailboxToReplace = NULL; // Re-acquire so that we can insert the new value into the registry localRegistryMutex_.acquire(); }//end if // Add the new mailbox to the registry (works for replace existing entry or new) // Now, insert the mailbox/address into the map. This default 'insert' method is the only // one that provides a return/result value; otherwise, we would specify to insert at the end (endIterator) insertResult = localMailboxRegistry_.insert(make_pair(localAddress,mailboxPtr)); // Check to see if the map insert was successful if (!insertResult.second) { TRACELOG(ERRORLOG, MSGMGRLOG, "LocalMailboxRegistry map insertion failed for remote-equivalent",0,0,0,0,0,0); }//end if localRegistryMutex_.release(); // Add the non-proxy remote Address to the Discovery Manager registry and send Discovery updates if (isDiscoveryStarted_) { discoveryManagerInstance_->registerLocalAddress(mailboxOwnerHandle->getMailboxAddress()); }//end if }//end if //############## //# Proxy Registration //############## // Else, for Proxy Mailboxes, register the handler in the proxy registry else { // Note that we do not allow the Discovery Manager Proxy Mailbox to register with // the MLS. We need this check here since the GroupMailboxProxy will regardless try // to perform registration. We will force block it here. if (strcmp (mailboxOwnerHandle->getMailboxAddress().mailboxName.c_str(), DISCOVERY_MANAGER_MAILBOX_NAME) == 0) { TRACELOG(DEVELOPERLOG, MSGMGRLOG, "MLS disallows Discovery Manager Proxy Mailbox to register",0,0,0,0,0,0); return; }//end if proxyRegistryMutex_.acquire(); // Here we use a regular iterator (rather than const_iterator) since const_iterator cannot // be used for insert/erase (see Scott Meyers effective STL) ProxyMailboxRegistry::iterator mailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator endIterator = proxyMailboxRegistry_.end(); pair<ProxyMailboxRegistry::iterator, bool> insertResult; // Loop through the map looping for the Mailbox that matches the address. This is a // check to see if the Mailbox has already been registered and we need to replace. while (mailboxIterator != endIterator) { if (mailboxOwnerHandle->getMailboxAddress() == mailboxIterator->first) { ostringstream ostr; ostr << "Deactivating/Replacing the following proxy registry entry in the Lookup Service: " << mailboxOwnerHandle->getMailboxAddress().toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); if (mailboxIterator->second->isActive()) { // Set a flag to later call deactivate on the Mailbox because all // activated mailboxes must be in the registry!! mailboxToReplace = mailboxIterator->second; }//end if else { // Found the corresponding Mailbox Address, so remove the Mailbox so we can replace it. proxyMailboxRegistry_.erase(mailboxIterator); }//end if break; }//end if mailboxIterator++; }//end while // For new registrations if (mailboxIterator == endIterator) { ostringstream ostr; ostr << "Registered the following proxy registry entry with the MLS: " << mailboxOwnerHandle->getMailboxAddress().toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // After releasing the mutex on the proxy Registry, if we found the replaced mailbox to be // active, then we must deactivate it (which will ultimately perform the deregistration/erase for us) if (mailboxToReplace != NULL) { // Temporarily release the proxyMailboxRegistry mutex so that deactivate can perform // deregistration (This is needed since the mutex supports recursive calls; we could use recursive mutex) proxyRegistryMutex_.release(); mailboxToReplace->deactivate(mailboxOwnerHandle); mailboxToReplace = NULL; // Re-acquire so that we can insert the new value into the registry proxyRegistryMutex_.acquire(); }//end if // Add the new mailbox to the registry (works for replace existing entry or new) // Now, insert the mailbox/address into the map. This default 'insert' method is the only // one that provides a return/result value; otherwise, we would specify to insert at the end (endIterator) insertResult = proxyMailboxRegistry_.insert(make_pair(mailboxOwnerHandle->getMailboxAddress(),mailboxPtr)); // Check to see if the map insert was successful if (!insertResult.second) { TRACELOG(ERRORLOG, MSGMGRLOG, "ProxyMailboxRegistry map insertion failed",0,0,0,0,0,0); }//end if proxyRegistryMutex_.release(); }//end else }//end else // For debugging if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { listAllMailboxAddresses(); }//end if }//end registerMailbox //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method allows tasks to deregister their mailbox. The lookup // service will remove the mailbox entry from the various registries. // Design: //----------------------------------------------------------------------------- void MailboxLookupService::deregisterMailbox(MailboxOwnerHandle* mailboxOwnerHandle) { if (mailboxOwnerHandle == NULL) { TRACELOG(ERRORLOG, MSGMGRLOG, "Null OwnerHandle passed to deregisterMailbox",0,0,0,0,0,0); return; }//end if //############## //# Local DeRegistration //############## // Perform deregistration for Local Mailboxes if (mailboxOwnerHandle->getMailboxAddress().locationType == LOCAL_MAILBOX) { localRegistryMutex_.acquire(); LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map looking for a LocalMailbox that matches the address. while (mailboxIterator != endIterator) { if (mailboxOwnerHandle->getMailboxAddress() == mailboxIterator->first) { ostringstream ostr; ostr << "Deregistering the following Local Address with the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); // Here we don't call deactivate since it could call deregister again if the // mailbox is already activated. We depend on the applications to call // deactivate BEFORE/IF they call deregister // Found the corresponding Mailbox Address, so remove the Mailbox localMailboxRegistry_.erase(mailboxIterator); break; }//end if mailboxIterator++; }//end while localRegistryMutex_.release(); // Check to see if this remote type Non-Proxy Mailbox was registered to receive // discovery update notifications. If so, we need to deregister it. We do this here // because there is currently no limitation that requires Mailboxes to be remote // type to receive discovery update messages (they can be Local or Remote Non-Proxy, // but they of course cannot be Proxy) if (isDiscoveryStarted_) { discoveryManagerInstance_->deregisterForDiscoveryUpdates(mailboxOwnerHandle); }//end if }//end if // Perform deregistration for remote type Mailboxes else { //############## //# Non-Proxy DeRegistration //############## // If this is a Non-proxy remote type Mailbox, then we need to deregister the equivalent // Local Mailbox address from the local registry if (! mailboxOwnerHandle->isProxy()) { localRegistryMutex_.acquire(); // Here we use a regular iterator (rather than const_iterator) since const_iterator cannot // be used for insert/erase (see Scott Meyers effective STL) LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Build the equivalent Local Mailbox Address for the remote type Non-proxy Mailbox that // we are attempting to deregister. NOTE: here Currently the Local Mailbox Addresses // really only consist of the location type and the Mailbox Name. MailboxAddress localAddress; localAddress.locationType = LOCAL_MAILBOX; localAddress.mailboxName = mailboxOwnerHandle->getMailboxAddress().mailboxName; // Loop through the map looking for the Mailbox that matches the address while (mailboxIterator != endIterator) { if (localAddress == mailboxIterator->first) { ostringstream ostr; ostr << "Deregistering the following Local Address (remote-equivalent) with the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); // Here we don't call deactivate since it could call deregister again if the // mailbox is already activated. We depend on the applications to call // deactivate BEFORE/IF they call deregister // Found the corresponding Mailbox Address, so remove the Mailbox localMailboxRegistry_.erase(mailboxIterator); break; }//end if mailboxIterator++; }//end while localRegistryMutex_.release(); // Remove the non-proxy remote Address from the Discovery Manager registry and send Discovery updates if (isDiscoveryStarted_) { // First see if the Mailbox had registered for Discovery updates and deregister those discoveryManagerInstance_->deregisterForDiscoveryUpdates(mailboxOwnerHandle); // Then deregister the mailbox from Discovery discoveryManagerInstance_->deregisterLocalAddress(mailboxOwnerHandle->getMailboxAddress()); }//end if }//end if !proxy //############## //# Proxy Registration //############## // Else, for Proxy Mailboxes, deregister the handler from the proxy registry else { proxyRegistryMutex_.acquire(); ProxyMailboxRegistry::iterator mailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator endIterator = proxyMailboxRegistry_.end(); // Loop through the map looping for the Mailbox that matches the address while (mailboxIterator != endIterator) { if (mailboxOwnerHandle->getMailboxAddress() == mailboxIterator->first) { ostringstream ostr; ostr << "Deregistering the following Proxy Address with the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); // Here we don't call deactivate since it could call deregister again if the // mailbox is already activated. We depend on the applications to call // deactivate BEFORE/IF they call deregister // Found the corresponding Mailbox Address, so remove the Mailbox proxyMailboxRegistry_.erase(mailboxIterator); break; }//end if mailboxIterator++; }//end while proxyRegistryMutex_.release(); }//end else }//end else // For debugging if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { listAllMailboxAddresses(); }//end if }//end deregisterMailbox //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method allows tasks to find other task mailboxes. If the // requested task mailbox exists it creates a handle to the mailbox, // acquires it (done in its constructor) and then returns it. // Otherwise it returns a NULL. // Design: When the requested address is of LocationType LOCAL_MAILBOX, then // the returned handle will point to a Local Mailbox (and posted // messages will be handled by the Local Mailbox post routine). If // the requested address is of a remote LocationType (Distributed, // LocalSM, or Group), then the returned handle will point to a Proxy // Mailbox (and posted messages will be serialized by the Proxy // Mailbox's post routine for remote delivery). // // References to Non-Proxy Remote type Mailboxes DO exist // in the MailboxLookupService, but in the nonProxyRemote registry. They are // not returned by the find() or findOwner() methods because they are // not used by the applications for posting messages (Local Mailbox handles // are used for posting local messages; Proxy Mailbox handles are // used for posting remote type messages). Non-Proxy Remote type // Mailboxes exist in the LookupService for Discovery purposes only. // The flow here is that if an application needs to find all of the // mailboxes of type X, then it will perform a registerForDiscoveryUpdates // method which will return a sequence of matching addresses. // Then, if the application needs to communicate with those mailboxes, // it will perform a 'find' which will create the proxy mailbox // connection to that remote mailbox. //----------------------------------------------------------------------------- MailboxHandle* MailboxLookupService::find(const MailboxAddress& address) { MailboxHandle* mailboxHandlePtr = NULL; if (address.locationType == UNKNOWN_MAILBOX_LOCATION) { TRACELOG(ERRORLOG, MSGMGRLOG, "Attempting to perform find with MailboxAddress LocationType UNKNOWN",0,0,0,0,0,0); return mailboxHandlePtr; }//end if // Find Local type mailboxes else if (address.locationType == LOCAL_MAILBOX) { localRegistryMutex_.acquire(); LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map looking for the Mailbox that matches the address while (mailboxIterator != endIterator) { if ((MailboxAddress)address == mailboxIterator->first) { if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { ostringstream ostr; ostr << "Found the following Local Address in the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // Found the corresponding Mailbox Address, so return a handle to it // HERE, we are allocating memory for the handle on the heap, so it is upto the // application developer to release this memory (Applications OWN the handles) mailboxHandlePtr = new MailboxHandle((*mailboxIterator).second); break; }//end if mailboxIterator++; }//end while // If we cannot find the entry for a LocalMailbox in the registry, then that's an ERROR // (since LocalMailbox should be within the same process as the caller) if (mailboxIterator == endIterator) { TRACELOG(ERRORLOG, MSGMGRLOG, "Cannot find entry in MLS registry for LocalMailbox",0,0,0,0,0,0); }//end if localRegistryMutex_.release(); }//end if // For remote type mailboxes else { proxyRegistryMutex_.acquire(); ProxyMailboxRegistry::iterator mailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator endIterator = proxyMailboxRegistry_.end(); // Loop through the map looking for the Mailbox that matches the address while (mailboxIterator != endIterator) { if ((MailboxAddress)address == mailboxIterator->first) { if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { ostringstream ostr; ostr << "Found the following Remote Address for Proxy Mailbox in the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // Found the corresponding Mailbox Address, so return a handle to it // HERE, we are allocating memory for the handle on the heap, so it is upto the // application developer to release this memory (Applications OWN the handles) mailboxHandlePtr = new MailboxHandle((*mailboxIterator).second); break; }//end if mailboxIterator++; }//end while // If we cannot find the entry for a Remote type Mailbox in the registry, then we attempt to // create a Proxy Mailbox connection to it. if (mailboxIterator == endIterator) { TRACELOG(DEBUGLOG, MSGMGRLOG, "Cannot find entry in MLS registry for Remote type mailbox, attempting proxy connect",0,0,0,0,0,0); // Release the lock on the remote registry before we attempt to activate/register any of // the below proxy mailboxes (this is to prevent deadlock) proxyRegistryMutex_.release(); // Create the proxy mailbox MailboxOwnerHandle* proxyOwnerHandle = NULL; if (address.locationType == LOCAL_SHARED_MEMORY_MAILBOX) { proxyOwnerHandle = LocalSMMailboxProxy::createMailbox(address); }//end if else if (address.locationType == DISTRIBUTED_MAILBOX) { proxyOwnerHandle = DistributedMailboxProxy::createMailbox(address); }//end else if else if (address.locationType == GROUP_MAILBOX) { proxyOwnerHandle = GroupMailboxProxy::createMailbox(address); }//end else if else { TRACELOG(ERRORLOG, MSGMGRLOG, "Failed to find mailbox handle with illegal location type (%d)", address.locationType,0,0,0,0,0); return NULL; }//end else // Perform activate to initiate the connection and register this proxy with the lookup service if (proxyOwnerHandle->activate() == ERROR) { TRACELOG(WARNINGLOG, MSGMGRLOG, "Error activating proxy mailbox, application must retry the find operation",0,0,0,0,0,0); return NULL; }//end if else { TRACELOG(DEBUGLOG, MSGMGRLOG, "Successfully activated proxy mailbox",0,0,0,0,0,0); }//end else // Set the proxy's owner handle to a 'regular' handle type so we can process the location type mailboxHandlePtr = proxyOwnerHandle->generateMailboxHandleCopy(); // Delete the proxy's owner handle so that we only rely on the Application's proxy handle to // to keep the proxy mailbox alive (as long as they don't delete and cause a 'release') delete proxyOwnerHandle; }//end if else { // Release the lock on the remote registry proxyRegistryMutex_.release(); }//end else }//end else // Log the proxy creation or type of mailbox handle returned if (mailboxHandlePtr != NULL) { if (mailboxHandlePtr->getMailboxAddress().locationType == LOCAL_MAILBOX) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Local Mailbox",0,0,0,0,0,0); }//end if else if (mailboxHandlePtr->getMailboxAddress().locationType == DISTRIBUTED_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Distributed Mailbox Proxy",0,0,0,0,0,0); }//endif else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Local Equivalent of Distributed Mailbox",0,0,0,0,0,0); }//end if }//end else if else if (mailboxHandlePtr->getMailboxAddress().locationType == LOCAL_SHARED_MEMORY_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Local Shared Memory Mailbox Proxy",0,0,0,0,0,0); }//end if else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Local Equivalent of Local Shared Memory Mailbox",0,0,0,0,0,0); }//end else }//end else if else if (mailboxHandlePtr->getMailboxAddress().locationType == GROUP_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Group Mailbox Proxy",0,0,0,0,0,0); }//end if else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning handle to Local Equivalent of Group Mailbox",0,0,0,0,0,0); }//end else }//end else if }//end if return mailboxHandlePtr; }//end find //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Allows mailboxes to register for Discovery Update notifications // Design: //----------------------------------------------------------------------------- int MailboxLookupService::registerForDiscoveryUpdates(vector<MailboxAddress>& currentlyRegisteredAddresses, MailboxAddress& matchCriteria, MailboxOwnerHandle* mailboxToNotify) { if (isDiscoveryStarted_) { return discoveryManagerInstance_->registerForDiscoveryUpdates(currentlyRegisteredAddresses, matchCriteria, mailboxToNotify); }//end if return ERROR; }//end registerForDiscoveryUpdates //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method outputs all registered Mailbox Addresses. // Design: Here, we put the results into 3 separate Log Messages to avoid // truncation. //----------------------------------------------------------------------------- void MailboxLookupService::listAllMailboxAddresses() { ostringstream ostr; // Display Local Mailboxes: localRegistryMutex_.acquire(); ostr << "List of currently registered local mailboxes (" << localMailboxRegistry_.size() << "):" << endl; LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map while (mailboxIterator != endIterator) { ostr << "|" << ((MailboxAddress)mailboxIterator->first).toString() << "|" << endl; mailboxIterator++; }//end while localRegistryMutex_.release(); // Log can get very big. May be truncated STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); // Display Remote Proxy Mailboxes: ostringstream ostr2; proxyRegistryMutex_.acquire(); ostr2 << "List of currently registered remote proxy mailboxes (" << proxyMailboxRegistry_.size() << "):" << endl; ProxyMailboxRegistry::iterator rMailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator rEndIterator = proxyMailboxRegistry_.end(); // Loop through the map while (rMailboxIterator != rEndIterator) { ostr2 << "|" << ((MailboxAddress)rMailboxIterator->first).toString() << "|" << endl; rMailboxIterator++; }//end while proxyRegistryMutex_.release(); // Log can get very big. May be truncated STRACELOG(DEBUGLOG, MSGMGRLOG, ostr2.str().c_str()); // Display Remote (via Discovery) and Locally registered Non-Proxy remote type Mailboxes: if (isDiscoveryStarted_) { discoveryManagerInstance_->listAllMailboxAddresses(); }//end if }//end listAllMailboxAddresses //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Set debug flags for all mailboxes // Design: No need to do anything to the nonProxy set since that is only Addresses // and no real references to mailboxes //----------------------------------------------------------------------------- void MailboxLookupService::setDebugForAllMailboxAddresses(int debugValue) { TRACELOG(DEBUGLOG, MSGMGRLOG, "Setting Debug Flag for All Mailboxes to %d",debugValue, 0,0,0,0,0); // Set the local mailboxes localRegistryMutex_.acquire(); LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map while (mailboxIterator != endIterator) { (mailboxIterator->second)->setDebugValue(debugValue); mailboxIterator++; }//end while localRegistryMutex_.release(); // Set the remote proxy mailboxes proxyRegistryMutex_.acquire(); ProxyMailboxRegistry::iterator rMailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator rEndIterator = proxyMailboxRegistry_.end(); // Loop through the map while (rMailboxIterator != rEndIterator) { (rMailboxIterator->second)->setDebugValue(debugValue); rMailboxIterator++; }//end while proxyRegistryMutex_.release(); }//end setDebugForAllMailboxAddresses //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Display debug flags for all mailboxes // Design: No need to do anything to the nonProxy set since that is only Addresses // and no real references to mailboxes //----------------------------------------------------------------------------- void MailboxLookupService::getDebugForAllMailboxAddresses() { ostringstream ostr; ostr << "Debug values for all mailboxes: " << endl; // Local Mailboxes localRegistryMutex_.acquire(); LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map looping for the Mailbox that matches the address while (mailboxIterator != endIterator) { ostr << ((MailboxAddress)mailboxIterator->first).toString() << "-------->" << (mailboxIterator->second)->getDebugValue() << endl; mailboxIterator++; }//end while localRegistryMutex_.release(); // Remote proxy Mailboxes proxyRegistryMutex_.acquire(); ProxyMailboxRegistry::iterator rMailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator rEndIterator = proxyMailboxRegistry_.end(); // Loop through the map looping for the Mailbox that matches the address while (rMailboxIterator != rEndIterator) { ostr << ((MailboxAddress)rMailboxIterator->first).toString() << "-------->" << (rMailboxIterator->second)->getDebugValue() << endl; rMailboxIterator++; }//end while proxyRegistryMutex_.release(); }//end getDebugForAllMailboxAddresses //----------------------------------------------------------------------------- // PROTECTED methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // PRIVATE methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Start the Discovery Manager's mailbox processor in a dedicated // thread. // Design: //----------------------------------------------------------------------------- void MailboxLookupService::startDiscoveryManager() { // Start Discovery Manager's mailbox processing loop discoveryManagerInstance_->processMailbox(); }//end startDiscoveryManager //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method allows tasks to find other task mailboxes. If the // requested task mailbox exists it creates a handle to the mailbox // and returns it. Otherwise it returns a NULL. This handle has // owner privileges as opposed to the handle returned in the find() // Design: Here, Only return existing mailbox Owner handles (do not attempt // any connects). This method is PRIVATE so it should only be used // within the MailboxLookupService. //----------------------------------------------------------------------------- MailboxOwnerHandle* MailboxLookupService::findOwnerHandle(const MailboxAddress& address) { MailboxOwnerHandle* mailboxHandlePtr = NULL; if (address.locationType == UNKNOWN_MAILBOX_LOCATION) { TRACELOG(ERRORLOG, MSGMGRLOG, "Attempting to perform find with MailboxAddress LocationType UNKNOWN",0,0,0,0,0,0); return mailboxHandlePtr; }//end if // Find Local type mailboxes else if (address.locationType == LOCAL_MAILBOX) { localRegistryMutex_.acquire(); LocalMailboxRegistry::iterator mailboxIterator = localMailboxRegistry_.begin(); LocalMailboxRegistry::iterator endIterator = localMailboxRegistry_.end(); // Loop through the map looping for the Mailbox that matches the address while (mailboxIterator != endIterator) { if ((MailboxAddress)address == mailboxIterator->first) { if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { ostringstream ostr; ostr << "Found the following Local Address in the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // Found the corresponding Mailbox Address, so return a handle to it mailboxHandlePtr = new MailboxOwnerHandle((*mailboxIterator).second); break; }//end if mailboxIterator++; }//end while // If we cannot find the entry for a LocalMailbox in the registry. if (mailboxIterator == endIterator) { TRACELOG(WARNINGLOG, MSGMGRLOG, "Cannot find entry in MLS registry for LocalMailbox",0,0,0,0,0,0); }//end if localRegistryMutex_.release(); }//end if // For remote type mailboxes else { proxyRegistryMutex_.acquire(); ProxyMailboxRegistry::iterator mailboxIterator = proxyMailboxRegistry_.begin(); ProxyMailboxRegistry::iterator endIterator = proxyMailboxRegistry_.end(); // Loop through the map looping for the Mailbox that matches the address while (mailboxIterator != endIterator) { if ((MailboxAddress)address == mailboxIterator->first) { if (Logger::getSubsystemLogLevel(MSGMGRLOG) == DEVELOPERLOG) { ostringstream ostr; ostr << "Found the following Remote Address for Proxy Mailbox in the MLS: " << ((MailboxAddress)mailboxIterator->first).toString() << ends; STRACELOG(DEBUGLOG, MSGMGRLOG, ostr.str().c_str()); }//end if // Found the corresponding Mailbox Address, so return a handle to it mailboxHandlePtr = new MailboxOwnerHandle((*mailboxIterator).second); break; }//end if mailboxIterator++; }//end while // If we cannot find the entry for a Remote type Mailbox in the registry if (mailboxIterator == endIterator) { TRACELOG(WARNINGLOG, MSGMGRLOG, "Cannot find entry in MLS registry for Remote type Proxy Mailbox",0,0,0,0,0,0); }//end if proxyRegistryMutex_.release(); }//end else // Log the type of mailbox handle returned if (mailboxHandlePtr != NULL) { if (mailboxHandlePtr->getMailboxAddress().locationType == LOCAL_MAILBOX) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Local Mailbox",0,0,0,0,0,0); }//end if else if (mailboxHandlePtr->getMailboxAddress().locationType == DISTRIBUTED_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Distributed Mailbox Proxy",0,0,0,0,0,0); }//endif else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Local Equivalent of Distributed Mailbox",0,0,0,0,0,0); }//end if }//end else if else if (mailboxHandlePtr->getMailboxAddress().locationType == LOCAL_SHARED_MEMORY_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Local Shared Memory Mailbox Proxy",0,0,0,0,0,0); }//end if else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Local Equivalent of Local Shared Memory Mailbox",0,0,0,0,0,0); }//end else }//end else if else if (mailboxHandlePtr->getMailboxAddress().locationType == GROUP_MAILBOX) { if (mailboxHandlePtr->isProxy()) { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Group Mailbox Proxy",0,0,0,0,0,0); }//end if else { TRACELOG(DEBUGLOG, MSGMGRLOG, "MLS returning owner handle to Local Equivalent of Group Mailbox",0,0,0,0,0,0); }//end else }//end else if }//end if // If we cannot find the entry for a Remote type Mailbox in the registry, then return NULL return mailboxHandlePtr; }//end findOwnerHandle //----------------------------------------------------------------------------- // Nested Class Definitions: //-----------------------------------------------------------------------------
43.628774
138
0.611815
[ "vector" ]
a00af684275048e6c488e7692a23c6ec08a34485
2,892
cc
C++
subprojects/libbeyond-generic-capi/test/unittest_authenticator.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
subprojects/libbeyond-generic-capi/test/unittest_authenticator.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
subprojects/libbeyond-generic-capi/test/unittest_authenticator.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd 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 <gtest/gtest.h> #include <cerrno> #include <beyond/platform/beyond_platform.h> #include <beyond/private/beyond_private.h> #include <beyond/beyond.h> #include <beyond/plugin/authenticator_ssl_plugin.h> #include <beyond/plugin/peer_nn_plugin.h> class AuthenticatorGeneric : public testing::Test { protected: beyond_session_h session; beyond_authenticator_h handle; protected: void SetUp() override { session = beyond_session_create(0, 0); ASSERT_NE(session, nullptr); char *auth_argv[] = { const_cast<char *>(BEYOND_PLUGIN_AUTHENTICATOR_SSL_NAME) }; beyond_argument auth_args = { .argc = sizeof(auth_argv) / sizeof(char *), .argv = auth_argv, }; handle = beyond_authenticator_create(session, &auth_args); ASSERT_NE(handle, nullptr); } void TearDown() override { beyond_authenticator_destroy(handle); beyond_session_destroy(session); } }; TEST_F(AuthenticatorGeneric, positive_beyond_authenticator_configure) { int ret; beyond_config option = { .type = BEYOND_CONFIG_TYPE_AUTHENTICATOR, .object = nullptr, }; ret = beyond_authenticator_configure(handle, &option); EXPECT_EQ(ret, -EINVAL); } TEST_F(AuthenticatorGeneric, positive_beyond_authenticator_for_peer) { beyond_config option; int ret = beyond_authenticator_configure(handle, &option); EXPECT_EQ(ret, -EINVAL); ret = beyond_authenticator_activate(handle); EXPECT_EQ(ret, 0); char *peer_argv[] = { const_cast<char *>(BEYOND_PLUGIN_PEER_NN_NAME), }; beyond_argument peer_args = { .argc = sizeof(peer_argv) / sizeof(char *), .argv = peer_argv, }; auto peerHandle = beyond_peer_create(session, &peer_args); ASSERT_NE(peerHandle, nullptr); option.type = BEYOND_CONFIG_TYPE_AUTHENTICATOR; option.object = handle; ret = beyond_peer_configure(peerHandle, &option); EXPECT_EQ(ret, 0); ret = beyond_peer_activate(peerHandle); EXPECT_EQ(ret, 0); ret = beyond_peer_deactivate(peerHandle); EXPECT_EQ(ret, 0); beyond_peer_destroy(peerHandle); ret = beyond_authenticator_deactivate(handle); EXPECT_EQ(ret, 0); }
27.807692
89
0.698133
[ "object" ]
a00bd24bdd5179e887ec70c4742f711b4eb30c9d
14,165
cpp
C++
Main.cpp
itakawa/Maple-glTF
58b5c1b08ca6d0fc4a89d7c6ba218a08bee3e31d
[ "MIT" ]
null
null
null
Main.cpp
itakawa/Maple-glTF
58b5c1b08ca6d0fc4a89d7c6ba218a08bee3e31d
[ "MIT" ]
null
null
null
Main.cpp
itakawa/Maple-glTF
58b5c1b08ca6d0fc4a89d7c6ba218a08bee3e31d
[ "MIT" ]
null
null
null
 // // Siv3D August 2016 v2 for Visual Studio 2019 // // Requirements // - Visual Studio 2015 (v140) toolset // - Windows 10 SDK (10.0.17763.0) // # include <Siv3D.hpp> #include "3rd/mapleGltf.hpp" // MapleGLTF追加 using namespace s3d::Input; enum ID_ANIME { DIG = 0, JUMP = 1, RUN = 2 ,IDLE = 3 }; Quaternion Q0001 = Quaternion(0, 0, 0, 1); // よくある定数の略称 Float3 sca111 = Float3(1, 1, 1); int32 WW, HH; String GetMap(Float3 flt3,ChunkMap &chunkmap) { auto idx = MaplePos2Idx(flt3, chunkmap); return (idx >= 0) ? chunkmap.Text.substr(idx, 1) : L" "; } void SetMorph(int32 ch, Entity* ent, int32 mtstate, float speed, Array<float> weight) { if (ent == nullptr) return; auto& spd = ent->Morph[ch].Speed; auto& cnt = ent->Morph[ch].CntSpeed; auto& now = ent->Morph[ch].NowTarget; auto& dst = ent->Morph[ch].DstTarget; auto& idx = ent->Morph[ch].IndexTrans; auto& wt = ent->Morph[ch].WeightTrans; if (now != mtstate && idx == 0) { if (ch) now = 0; spd = speed; cnt = 0; dst = mtstate; idx = 1; wt = (weight[0] == -1) ? WEIGHTTRANS : weight; wt.insert(wt.begin(), 0); } } void CtrlMorph(Entity* ent) { if (ent == nullptr) return; for (auto ii = 0; ii < NUMMORPH; ii++) { auto& spd = ent->Morph[ii].Speed; auto& cnt = ent->Morph[ii].CntSpeed; auto& now = ent->Morph[ii].NowTarget; auto& dst = ent->Morph[ii].DstTarget; auto& idx = ent->Morph[ii].IndexTrans; auto& wt = ent->Morph[ii].WeightTrans; if (now == -1) continue; cnt += spd; //モーフ変化量を加算 if (cnt >= 1.0) cnt -= 1.0; else continue; if (now > -1 && idx) { idx++; if (wt[idx] < 0) { idx = 0; if (ii == 0) now = dst; //プライマリ(表情)の場合は遷移する else now = -1; //セカンダリ(瞬き/口パク)の場合は遷移しない } } } } void CtrlKeyboard(Entity* ent, ChunkMap& map) { if (ent == nullptr) return; const int16 DST[] = { -1, 0, 180, -1,270, 315, 225, -1, 90, 45, 135, -1,-1,-1,-1,-1 };//押下キーに対応する方向テーブル static float rad = 0; auto& dir = ent->Rotate[0].y; //現在の方向 // キー入力 uint32 key_m = 8 * KeyNum1.pressed + 4 * KeyNum3.pressed + 2 * KeyNum5.pressed + KeyNum2.pressed; uint32 key_a = 2 * KeyN.clicked + KeyM.clicked; auto& anime_s = ent->Maple->ArgI; // ArgI(アニメ選択)が掘るでも跳ぶでもない if (anime_s == ID_ANIME::IDLE || anime_s == ID_ANIME::RUN) { if (key_m && DST[key_m] != -1) //走る { float vel = 15; //回転の刻みは45度の公約数 int16 dfp = 180 - abs(abs(int16(dir) + vel - DST[key_m]) - 180); int16 dfm = 180 - abs(abs(int16(dir) - vel - DST[key_m]) - 180); if (dfp < dfm) vel = +vel; else vel = -vel; if (dir == DST[key_m]) vel = 0; else dir += vel; if (dir > 360) dir -= 360; else if (dir < 0) dir += 360; ent->qRotate[0] *= Q0001.Yaw(Radians(vel)); // Float3 tra = ent->qRotate[0] * Vec3::Backward * 0.1; //旋回ターン Float3 tra = Q0001.Yaw(Radians(DST[key_m])) * Vec3::Backward * 0.1; //でも、直接ターンにしないと操作性悪すぎ //当たり判定 auto wall_u = GetMap(ent->Trans + Float3(0, 1, 0) + tra * 10, map); // 上半身 auto wall_l = GetMap(ent->Trans + Float3(0, 0, 0) + tra * 10, map); // 下半身 移動成分x10でちょい先読み if (wall_u == L" " && wall_l == L" ") ent->Trans = ent->Trans + tra; auto under = GetMap( ent->Trans + Float3(0, -1, 0), map) ; if (under == L" ") ent->Trans += Float3(0, -0.5, 0); else ent->Trans.y = Floor(ent->Trans.y); //着地時の高さを再計算 anime_s = ID_ANIME::RUN; } if (DST[key_m] == -1 && key_a == 0) anime_s = ID_ANIME::IDLE; //立ち if (KeyB.clicked) anime_s = ID_ANIME::DIG; //掘る if (KeyM.clicked) anime_s = ID_ANIME::JUMP; //ジャンプ if (Key0.clicked) SetMorph(0, ent, 0, 1.0, WEIGHTTRANS); //瞬き else if (Key1.clicked) SetMorph(1, ent, 1, 1.0, WEIGHTBLINK); else if (Key2.clicked) SetMorph(1, ent, 2, 1.0, WEIGHTBLINK); else if (Key3.clicked) SetMorph(2, ent, 3, 1.0, WEIGHTBLINK); else if (Key4.clicked) SetMorph(2, ent, 14, 1.0, WEIGHTBLINK); else if (Key5.clicked) SetMorph(0, ent, 10, 1.0, WEIGHTTRANS); //表情 else if (Key6.clicked) SetMorph(0, ent, 11, 1.0, WEIGHTTRANS); else if (Key7.clicked) SetMorph(0, ent, 12, 1.0, WEIGHTTRANS); else if (Key8.clicked) SetMorph(0, ent, 8, 1.0, WEIGHTTRANS); else if (Key9.clicked) SetMorph(0, ent, 14, 1.0, WEIGHTTRANS); } if (anime_s == ID_ANIME::JUMP) //跳んでからも制御可能(マリオジャンプ) { if (key_m && DST[key_m] != -1) //ジャンプXZ移動 { float vel = 5; //回転の刻みは45度の公約数 int16 dfp = 180 - abs(abs(int16(dir) + vel - DST[key_m]) - 180); int16 dfm = 180 - abs(abs(int16(dir) - vel - DST[key_m]) - 180); if (dfp < dfm) vel = +vel; else vel = -vel; if (dir == DST[key_m]) vel = 0; else dir += vel; if (dir > 360) dir -= 360; else if (dir < 0) dir += 360; ent->qRotate[0] *= Q0001.Yaw(Radians(vel)); Float3 tra = Q0001.Yaw(Radians(DST[key_m])) * Vec3::Backward * 0.1; // 直接 auto wall = GetMap(ent->Trans + tra * 10, map); // 移動成分x10でちょい先読み if (wall == L" ") ent->Trans = ent->Trans + tra; } } } void CtrlAction(MapleMap& maple, Entity* ent, ChunkMap& chunkmap, ChunkMap& chunkatr) { if (ent == nullptr) return; auto& anime_s = ent->Maple->ArgI; auto& currentframe = ent->Maple->AniModel.precAnimes[anime_s].currentframe; auto& animespeed = ent->Maple->ArgF; auto& jump = ent->CtrlF; auto& starty = ent->CtrlF[0]; const Array<float> G = { 27.40f, 26.42f, 25.44f, 24.46f, 23.48f, 22.50f, 21.52f, 20.54f, 19.56f, 18.58f, 17.60f, 16.62f, 15.64f, 14.66f, 13.68f, 12.70f, 11.72f, 10.74f, 9.76f, 8.78f, 7.80f, 6.82f, 5.84f, 4.86f, 3.88f, 2.90f, 1.92f, 0.94f, -0.04f, -1.02f, -2.00f, -2.98f, -3.96f, -4.94f, -5.92f, -6.90f, -7.88f, -8.86f, -9.84f,-10.82f, -11.80f,-12.78f,-13.76f,-14.74f,-15.72f,-16.70f,-17.68f,-18.66f,-19.64f,-20.62f, -21.60f,-22.58f,-23.56f,-24.54f,-25.52f,-26.50f,-25.20f,-0.126f,0,0 }; //初期化 if (ent->CtrlI[0] != anime_s) // [0]:アニメステート履歴で切り替わった時 { if (anime_s == ID_ANIME::DIG) animespeed = 4; // 掘る 倍速設定 else if (anime_s == ID_ANIME::RUN) animespeed = 4;// 走る 倍速設定 else if (anime_s == ID_ANIME::IDLE) animespeed = 2;// 立つ else if (anime_s == ID_ANIME::JUMP) // 跳ぶ { starty = ent->Trans.y; jump.insert(jump.end(), G.begin(), G.end()); ent->CtrlI.emplace_back(1); animespeed = 1; // 等速設定 } currentframe = 1; // フレームカウンタを1に設定してアニメスタート(ループして0で終了) ent->CtrlI[0] = anime_s; } else { //各アニメ制御 if (anime_s == ID_ANIME::IDLE) // 立ち行動の表現 { static int32 cnt = 0; static float sign = +1; static float VEL[] = { 0.0, 0.1, 0.2, 0.4, 0.4, 0.4, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.4, 0.4, 0.4, 0.2, 0.1, -1 }; if (VEL[cnt] == -1) cnt = 0; else { if (cnt == 0 && Random(0.0, 100.0) < 1.0) { cnt = 1; if (Random(0, 10) < 5) sign *= -1; } } animespeed = VEL[cnt] * sign; if (cnt) cnt++; auto under = GetMap(ent->Trans + Float3(0, -1, 0), chunkmap); if (under == L" ") ent->Trans += Float3(0, -0.5, 0); //落下 else ent->Trans.y = Floor(ent->Trans.y); //着地時の高さを再計算 } if (anime_s == ID_ANIME::JUMP) // 跳び行動の表現 { if (currentframe == 0 || ent->CtrlI[1] >= G.size()) { anime_s = ID_ANIME::RUN; // 終わったら2:走るに変更 animespeed = 4; // 走る 倍速設定 ent->Trans.y = starty; ent->CtrlF.resize(1); ent->CtrlI.resize(1); return; } auto tra = // ent->qRotate[0] * Vec3::Backward * 0.08 + // xz平面の移動成分 Float3(0, jump[ent->CtrlI[1]++] / 190, 0); // y軸の移動成分 auto under = GetMap(ent->Trans + Float3(0, -1, 0) + tra, chunkmap); if (tra.y < 0 && under != L" ") { anime_s = ID_ANIME::RUN; // 終わったら2:走るに変更 animespeed = 4; // 走る 倍速設定 ent->CtrlF.resize(1); ent->CtrlI.resize(1); return; } else { auto wall = GetMap(ent->Trans + tra, chunkmap); if (wall == L" ") ent->Trans += tra; else { anime_s = ID_ANIME::RUN; // 終わったら2:走るに変更 animespeed = 4; // 走る 倍速設定 ent->CtrlF.resize(1); ent->CtrlI.resize(1); return; } } } if (anime_s == ID_ANIME::DIG) // 掘り行動の表現 { if (currentframe == 0) anime_s = ID_ANIME::IDLE; // 終わったら3:立つに変更 } //床の重力ベクトル対応(床が動いていたら一緒に動かす) auto map_under = GetMap(ent->Trans + Float3(0, -1, 0), chunkmap); if (map_under != L" ") //足元に何かある { auto atr_under = GetMap(ent->Trans + Float3(0, -1, 0), chunkatr); for (auto& atr : maple.Attribs) { if (atr.Name == atr_under) //取ってきた属性を選択 { ent->Trans += atr.Trans; //属性の重力ベクトルを加算 break; } } } } } void Main() { String maplepath = FileSystem::CurrentPath()+L"Example/MapleGLTF/"; // リソースのパス // マップ定義ファイルから座標リストとマップを生成 CSVReader csv1(maplepath + L"map.csv"); MapleMap maple1; // 物体の座標リスト ChunkMap map1, atr1; // 物体と属性のマップ LoadMaple(maple1, map1, atr1, csv1, maplepath); Window::Resize(1366, 768); WW = Window::Width(); HH = Window::Height(); const Font FontT(15, L"TOD4UI"); // 英数フォント const Font FontM(7); // 日本語フォント // カメラ設置 Camera camera = Graphics3D::GetCamera(); camera.pos = Float3(0.32, 4, 20); camera.lookat = Float3(16, 1, -16); Graphics3D::SetCamera(camera); // 背景色 Graphics::SetBackground(Palette::Midnightblue); Graphics3D::SetAmbientLight(ColorF(0.7, 0.7, 0.7)); //専用制御(モーフ/可変アニメ)のEntityを取得 Entity* ent_s = nullptr; Entity* ent_d = nullptr; Entity* ent_f = nullptr; for (auto& ent : maple1.Entities) { if (ent.Name == L"S") //SIV3DKUNの初期化 { ent_s = &ent; ent_s->Maple->ArgI = ID_ANIME::IDLE; //アニメ種類3:待ち } if (ent.Name == L"D") //情報ブロックの初期化 { ent_d = &ent; ent_d->Count = 100; } if (ent.Name == L"文") //文字列の初期化 { ent_f = &ent; } } //ストップウォッチ開始 // Stopwatch stopwatch; // stopwatch.start(); while (System::Update()) { auto begin = std::chrono::high_resolution_clock::now(); Graphics3D::FreeCamera(); camera = Graphics3D::GetCamera(); CtrlKeyboard(ent_s, map1); // キー入力制御 [1]:←[2]:↓[3]:→[5]:↑[M]:ジャンプ[B]:掘る CtrlMorph(ent_s); // モーフィング制御 CtrlAction(maple1, ent_s, map1, atr1); // 行動制御 RenderMaple(maple1, map1, atr1); // 描画 //情報ブロック表示 if (ent_d) { ent_d->Trans = ent_s->Trans; ent_d->Trans.y = ent_s->Trans.y + 1; ent_d->Maple->Mode = String(L"円:MapPosition X=(X) Y=(Y) Z=(Z)") .replace(L"(X)", Format(ent_s->Trans.x)) .replace(L"(Y)", Format(ent_s->Trans.y)) .replace(L"(Z)", Format(ent_s->Trans.z)); } //文字列表示 if (ent_f) { static float vel = 0.1; ent_f->Count += vel; if ((vel > 0 && ent_f->Count > ent_f->Maple->Mode.length-2) || (vel < 0 && ent_f->Count < 0) ) vel *= -1; } //物体マップ表示 auto &dd = map1.MapSize.z; auto &ww = map1.MapSize.x; for (int32 yy = 0; yy < dd ; yy++) { for (int32 xx = 0; xx < ww; xx++) { int32 idx = MaplePos2Idx(xx, 1, (dd-1) - yy, 32, 32, 32); auto cc = map1.Text.substr(idx, 1); FontM(cc).draw(xx * 8, yy * 8); } } //フレームレート表示 Profiler::FPS(); FontT(String(L"Render:(FPS)/Fps") .replace(L"(FPS)", Format(Profiler::FPS()))) .draw(WW - 300, HH - 80); } }
34.889163
112
0.44857
[ "render" ]
a00c02a2d386ccfdf69381af2fcedb2dae8682ba
2,024
cpp
C++
simulator.cpp
jiegec/tomasulo
f601f5cb50cf953d409f23e1fc14cb4dafc415d3
[ "Unlicense" ]
1
2020-11-26T00:38:55.000Z
2020-11-26T00:38:55.000Z
simulator.cpp
jiegec/tomasulo
f601f5cb50cf953d409f23e1fc14cb4dafc415d3
[ "Unlicense" ]
null
null
null
simulator.cpp
jiegec/tomasulo
f601f5cb50cf953d409f23e1fc14cb4dafc415d3
[ "Unlicense" ]
null
null
null
#include "parser.h" #include <stdio.h> #include <vector> using namespace std; int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: %s input_nel output_trace output_reg\n", argv[0]); return 1; } FILE *input_file = fopen(argv[1], "r"); if (input_file == NULL) { printf("Unable to open file %s\n", argv[1]); return 1; } FILE *output_trace = fopen(argv[2], "w"); if (output_trace == NULL) { printf("Unable to create file %s\n", argv[2]); return 1; } FILE *output_reg = fopen(argv[3], "w"); if (output_reg == NULL) { printf("Unable to create file %s\n", argv[3]); return 1; } char buffer[1024]; vector<Inst> instructions; while (!feof(input_file)) { if (fgets(buffer, sizeof(buffer), input_file) == NULL) { break; } instructions.push_back(parse_inst(buffer)); } printf("Parsed %ld instructions\n", instructions.size()); // simulation without tomasulo size_t pc = 0; int32_t reg[32] = {0}; int cycle = 0; while (pc < instructions.size()) { cycle += 1; struct Inst cur = instructions[pc]; if (cur.type == InstType::Jump) { if (reg[cur.rs1] == cur.imm) { // jump pc += cur.offset; } else { pc += 1; } continue; } else if (cur.type == InstType::Load) { reg[cur.rd] = cur.imm; } else if (cur.type == InstType::Mul) { reg[cur.rd] = reg[cur.rs1] * reg[cur.rs2]; } else if (cur.type == InstType::Div) { if (reg[cur.rs2] == 0) { reg[cur.rd] = reg[cur.rs1]; } else { reg[cur.rd] = reg[cur.rs1] / reg[cur.rs2]; } } else if (cur.type == InstType::Add) { reg[cur.rd] = reg[cur.rs1] + reg[cur.rs2]; } else if (cur.type == InstType::Sub) { reg[cur.rd] = reg[cur.rs1] - reg[cur.rs2]; } pc += 1; fprintf(output_trace, "%02d: R[%02d] = %08x\n", cycle, cur.rd, reg[cur.rd]); } for (int i = 0; i < 32; i++) { fprintf(output_reg, "R[%02d]=%08x\n", i, reg[i]); } return 0; }
25.3
80
0.549407
[ "vector" ]
a00c56866a268a031779c9562cf6009983072e4b
1,590
cpp
C++
ch4-memory_management/lesson5-resource_copying/exclusive_ownership.cpp
ancilmarshall/udacity-cpp
c890b909a113d64b5938860d206028704463b3f3
[ "MIT" ]
null
null
null
ch4-memory_management/lesson5-resource_copying/exclusive_ownership.cpp
ancilmarshall/udacity-cpp
c890b909a113d64b5938860d206028704463b3f3
[ "MIT" ]
null
null
null
ch4-memory_management/lesson5-resource_copying/exclusive_ownership.cpp
ancilmarshall/udacity-cpp
c890b909a113d64b5938860d206028704463b3f3
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; //Key takeaway: Only one pointer can point to the resource. The ownership // of the resource changes on copy. Only a single handle to the resource // exists class ExclusiveCopy { private: int *_myInt; public: //RAII - Resource Allocation Is Initialization. // Resource is allcated when the object is initilized. ExclusiveCopy() { _myInt = (int *) malloc(sizeof(int)); cout << "resource allocated" << endl; } // Rule of three. The desctructor, copy constructor and copy assignment methods are implemented ~ExclusiveCopy() { // needed to check for nullptr to avoid double free. Specific to the Exclusive copy policy if (_myInt!=nullptr){ free(_myInt); cout << "resource freed" << endl; } } ExclusiveCopy(ExclusiveCopy &source) // note the lvalue ref is not const because we want to change it { _myInt = source._myInt; source._myInt = nullptr; // make null. This is why the check is made in the desctructor // Note: the data is not freed, just the ownership is changed } ExclusiveCopy& operator=(ExclusiveCopy &source) { if (this==&source){ return *this; } _myInt = source._myInt; source._myInt = nullptr; return *this; } }; int main() { ExclusiveCopy source; ExclusiveCopy destination; destination = source; // problem... why is there only one "resource freed"? Is there a leak? return 0; }
26.5
105
0.620755
[ "object" ]
a00ec8732fccec5a7ae66d2c3beb263e72d46550
340
cc
C++
problems/hindex/submissions/accepted/hindex-db-2.cc
icpc/na-rocky-mountain-2018-public
416a94258f99ab68ff7d9777faca55c94cdaf5f5
[ "MIT" ]
1
2022-03-22T16:34:26.000Z
2022-03-22T16:34:26.000Z
problems/hindex/submissions/accepted/hindex-db-2.cc
icpc/na-rocky-mountain-2018-public
416a94258f99ab68ff7d9777faca55c94cdaf5f5
[ "MIT" ]
null
null
null
problems/hindex/submissions/accepted/hindex-db-2.cc
icpc/na-rocky-mountain-2018-public
416a94258f99ab68ff7d9777faca55c94cdaf5f5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; vector<int> A(n); for(auto& x : A) cin >> x; int lo = 0, hi = n+1; while(hi > lo + 1){ int mid = (lo+hi)/2; int ctr = count_if(begin(A), end(A), [&](int x){ return x >= mid; }); (ctr >= mid ? lo : hi) = mid; } cout << lo << endl; }
18.888889
73
0.482353
[ "vector" ]
a0136da7eb02f0731a4d39a49163320acb7da9d9
424
cc
C++
doctests/socket_dt.cc
YukunJ/Sponge-TCP-Protocol
85af1055af278abf945fdf11449b14e699f0a5e9
[ "Apache-2.0" ]
8
2021-02-22T01:10:06.000Z
2022-02-28T13:30:26.000Z
doctests/socket_dt.cc
YukunJ/Sponge-TCP-Protocol
85af1055af278abf945fdf11449b14e699f0a5e9
[ "Apache-2.0" ]
2
2021-12-20T04:29:06.000Z
2022-03-21T01:00:19.000Z
cs144/sponge/doctests/socket_dt.cc
rovast/cs-study-plan
7ef96855b0958c4bb40983bcd369912f3da0c59b
[ "CC0-1.0" ]
7
2021-02-22T01:10:16.000Z
2022-02-18T11:49:15.000Z
#include "socket.hh" #include "address.hh" #include "util.hh" #include <array> #include <cstdlib> #include <random> #include <stdexcept> #include <sys/socket.h> #include <vector> int main() { try { { #include "socket_example_1.cc" } { #include "socket_example_2.cc" } { #include "socket_example_3.cc" } } catch (...) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
15.703704
30
0.601415
[ "vector" ]
a014a0f6609fed027cde260dff94f0138bae204a
2,216
hpp
C++
src/NodePart/InputPipe/InputPipeUdp.hpp
therealddx/midvec2-lib
88aa20c32ca59ec6aad80473f76b8c23ca190f40
[ "MIT" ]
2
2022-03-28T17:50:14.000Z
2022-03-29T22:55:45.000Z
src/NodePart/InputPipe/InputPipeUdp.hpp
therealddx/midvec2-lib
88aa20c32ca59ec6aad80473f76b8c23ca190f40
[ "MIT" ]
8
2022-03-12T19:29:50.000Z
2022-03-29T18:51:52.000Z
src/NodePart/InputPipe/InputPipeUdp.hpp
therealddx/midvec2-lib
88aa20c32ca59ec6aad80473f76b8c23ca190f40
[ "MIT" ]
null
null
null
/** * reference LICENSE file provided. * * @file InputPipeUdp.hpp * Declarations for InputPipeUdp * */ #ifndef INPUTPIPEUDP_HPP #define INPUTPIPEUDP_HPP // include: C/C++ standard library. // #include <stdint.h> #include <unistd.h> #include <vector> #include <string> #include <sstream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // include: app. // #include <Exception/ErrorCode.hpp> #include <Message/MessageConstants.hpp> #include "InputPipe.hpp" /** * @class InputPipeUdp * Reads bytes from a UDP socket into Message instances. */ class InputPipeUdp : public InputPipe { public: /** * Constructs an instance to read Message instances from a UDP socket, * by binding to the given IPv4 address:port. * * @param[in] arg_ipv4_bind IPv4 address to bind to. * @param[in] arg_port Port to bind to. */ InputPipeUdp(std::string arg_ipv4_bind, uint16_t arg_port); /** * Destroys this instance, * and releases the IPv4 socket back to the operating system. */ ~InputPipeUdp(); /** * Report the bound IPv4 endpoint. * @return * A human-readable string denoting the address:port this instance is bound to. */ std::string GetBindEndpoint() const; /** * Report the bound IPv4 address. * @return * The IPv4 address this instance is currently bound to, in dotted-quad. */ std::string GetBindAddress() const { return _ipv4; } /** * Report the bound IPv4 port. * @return * The port this instance is currently bound to, in host byte order. */ uint16_t GetBindPort() const { return _port; } private: /** * Satisfies base class. */ ErrorCode GetByte(char* rtn_byte); // members: socket. int32_t _socketFd; struct sockaddr_in _endpoint; // IPv4 info for listener (local). struct sockaddr _clientAddr; // IPv4 info for sender (remote). socklen_t _clientAddrLen; // ^ // members: buffer. static const uint32_t MAX_RXBUFFER_SIZE = 60000; char _rxBuffer[MAX_RXBUFFER_SIZE]; int32_t _rxBufIndex; int32_t _rxBufValid; // members: convenience storage. std::string _ipv4; uint16_t _port; }; #endif // INPUTPIPEUDP_HPP
20.518519
81
0.68231
[ "vector" ]
a017d200f2d442bc7f4b3348e6fd5f23f1b1fd45
9,213
cpp
C++
examples/md_gate.cpp
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
3
2020-02-13T02:08:06.000Z
2020-10-06T16:26:30.000Z
examples/md_gate.cpp
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
null
null
null
examples/md_gate.cpp
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan // Licensed under the MIT License. See LICENSE for details. #include <iostream> #include <set> #include <crab/crab.hpp> #include "gate_message.hpp" // This app connects to md_tcp_source and listens to "financial messages". // If it is disconnected, it reconnects, then requests retransmission of skipped messages // Stream of messages is broadcast via UDP group (A) with low latency // Also skipped messages can be requested for retransmission via HTTP // Retransmitted messages are broadcast in different UDP group (rA) in fair way // So that each connected client gets proportional % of available channel bandwidth // QOS must be setup so that traffic via UDP group (A) has higher priority than UDP group (rA) // Also, rate of incoming IP packets per second must be limited for HTTP port namespace http = crab::http; enum { MAX_DATAGRAM_SIZE = 508 }; // Connects to TCP, reads messages from upstream_socket, immediately retransmits them to udp_a // and sends to message_handler class LowLatencyRetransmitter { public: LowLatencyRetransmitter(const MDSettings &settings, std::function<void(Msg msg)> &&message_handler) : settings(settings) , upstream_socket([&]() { upstream_socket_handler(); }) , upstream_socket_buffer(4096) , message_handler(std::move(message_handler)) , udp_a(settings.md_gate_udp_a(), [&]() {}) // We just skip packets if buffer is full in UDP line A , reconnect_timer([&]() { connect(); }) , simulated_disconnect_timer([&]() { on_simulated_disconnect_timer(); }) { connect(); simulated_disconnect_timer.once(1); } private: void simulated_disconnect() { std::cout << "Simulated disconnected" << std::endl; upstream_socket.close(); upstream_socket_buffer.clear(); reconnect_timer.once(2); } void on_simulated_disconnect_timer() { simulated_disconnect_timer.once(1); if (reconnect_timer.is_set()) return; // Already disconnected if (rand() % 10 == 0) simulated_disconnect(); } void upstream_socket_handler() { if (!upstream_socket.is_open()) return on_upstream_socket_closed(); while (true) { if (upstream_socket_buffer.size() < Msg::size) upstream_socket_buffer.read_from(upstream_socket); const size_t max_count = MAX_DATAGRAM_SIZE / Msg::size; size_t count = std::min(max_count, upstream_socket_buffer.size() / Msg::size); if (count == 0) break; crab::VectorStream vs; upstream_socket_buffer.write_to(vs, count * Msg::size); if (!udp_a.write_datagram(vs.get_buffer().data(), vs.get_buffer().size())) { std::cout << "UDP retransmission buffer full, dropping message" << std::endl; } while (vs.size() >= Msg::size) { Msg msg; msg.read(&vs); message_handler(msg); } } } void on_upstream_socket_closed() { upstream_socket_buffer.clear(); reconnect_timer.once(1); std::cout << "Upstream socket disconnected" << std::endl; } void connect() { if (!upstream_socket.connect(settings.upsteam_tcp())) { reconnect_timer.once(1); } else { std::cout << "Upstream socket connection attempt started..." << std::endl; } } const MDSettings settings; crab::TCPSocket upstream_socket; crab::Buffer upstream_socket_buffer; std::function<void(Msg msg)> message_handler; crab::UDPTransmitter udp_a; crab::Timer reconnect_timer; crab::Timer simulated_disconnect_timer; }; class MDGate { public: explicit MDGate(const MDSettings &settings) : settings(settings) , server(settings.md_gate_http()) , udp_ra(settings.md_gate_udp_ra(), [&]() { broadcast_retransmission(); }) , stat_timer([&]() { on_stat_timer(); }) , ab([&]() { on_fast_queue_changed(); }) , http_client([&]() { on_http_client_data(); }) , reconnect_timer([&]() { connect(); }) , th(&MDGate::retransmitter_thread, this) { connect(); stat_timer.once(1); server.r_handler = [&](http::Client *who, http::Request &&request) { if (request.header.path != "/messages") return who->write(http::Response::simple_html(404)); MDRequest req; crab::IStringStream is(&request.body); req.read(&is); if (req.end <= req.begin) return who->write(http::Response::simple_html(400, "Invalid request range - inverted or empty!")); // TODO - add to data structure here }; } private: void add_message(const Msg &msg) { // Called from other thread std::unique_lock<std::mutex> lock(mutex); fast_queue.push_back(msg); ab.call(); } void on_fast_queue_changed() { std::deque<Msg> fq; { // We lock fast_queue for as little time as possible, so that // latency of add_message() above is not affected std::unique_lock<std::mutex> lock(mutex); fast_queue.swap(fq); } for (; !fq.empty(); fq.pop_front()) { add_message_from_any_source(fq.front()); } broadcast_retransmission(); } void add_message_from_any_source(const Msg &msg) { if (messages.empty()) { std::cout << "First! " << msg.seqnum << std::endl; messages.push_back(msg); return; } auto next_seq = messages.back().seqnum + 1; if (msg.seqnum < next_seq) return; if (msg.seqnum == next_seq) { // std::cout << "Normal " << msg.seqnum << std::endl; messages.push_back(msg); // We could close the gap to the first chunk if (!chunks.empty() && chunks.front().front().seqnum == msg.seqnum + 1) { std::cout << "Closing gap .." << chunks.front().back().seqnum << "]" << std::endl; messages.insert(messages.end(), chunks.front().begin(), chunks.front().end()); chunks.pop_front(); } return; } if (chunks.empty()) { // std::cout << "Created first chunk [" << msg.seqnum << ".." << std::endl; chunks.emplace_back(); chunks.back().push_back(msg); return; } // each chunk is also not empty next_seq = chunks.back().back().seqnum + 1; if (msg.seqnum < next_seq) return; if (msg.seqnum > next_seq) { // std::cout << "Created chunk [" << msg.seqnum << ".." << std::endl; chunks.emplace_back(); } else { // std::cout << "Added to last chunk " << msg.seqnum << std::endl; } chunks.back().push_back(msg); } void on_stat_timer() { if (!messages.empty()) std::cout << "[" << messages.front().seqnum << ".." << messages.back().seqnum << "]"; for (auto &c : chunks) std::cout << " <--> [" << c.front().seqnum << ".." << c.back().seqnum << "]"; std::cout << std::endl; stat_timer.once(1); } void broadcast_retransmission() { if (http_client.get_state() == http::ClientConnection::WAITING_WRITE_REQUEST && !chunks.empty()) { MDRequest req; req.begin = messages.back().seqnum + 1; req.end = chunks.front().front().seqnum; std::cout << "Sending request for [" << req.begin << ".." << req.end << ")" << std::endl; crab::StringStream os; req.write(&os); http::Request request(settings.upstream_address, "GET", "/messages"); request.set_body(std::move(os.get_buffer())); http_client.write(std::move(request)); } } void on_http_client_data() { if (!http_client.is_open()) return on_http_client_closed(); http::Response response; while (http_client.read_next(response)) { if (response.header.status == 200) { crab::IStringStream is(&response.body); while (is.size() >= Msg::size) { Msg msg; msg.read(&is); add_message_from_any_source(msg); } } } broadcast_retransmission(); } void on_http_client_closed() { std::cout << "Incoming http connect closed" << std::endl; reconnect_timer.once(1); } void connect() { if (!http_client.connect(settings.upsteam_http())) { reconnect_timer.once(1); } else { std::cout << "Incoming http connect started" << std::endl; broadcast_retransmission(); } } void retransmitter_thread() { // Separate thread for Retransmitter. Any variables in this thread are inaccessible from outside // while it communicates with MDGate via single point - add_message() crab::RunLoop runloop; LowLatencyRetransmitter gen(settings, [&](Msg msg) { add_message(msg); }); runloop.run(); } const MDSettings settings; http::Server server; // requests for retransmits are received here crab::UDPTransmitter udp_ra; // and broadcasted in fair manner via this UDP multicast group crab::Timer stat_timer; crab::Watcher ab; // Signals about changes in fast_queue std::mutex mutex; // Protects fast_queue std::deque<Msg> fast_queue; // intermediate queue, it will be locked for very short time std::deque<Msg> messages; // continuous stream, with optional non-empty gap to chunks std::deque<std::vector<Msg>> chunks; // non-overlapping chunks with non-empty gaps between them http::ClientConnection http_client; // We keep connection connected all the time crab::Timer reconnect_timer; std::thread th; }; int main(int argc, char *argv[]) { std::cout << "crablib version " << crab::version_string() << std::endl; std::cout << "This gate connects to running instance of md_tcp_source, and broadcasts data via UDP, with support of retransmission requests via HTTP" << std::endl; crab::RunLoop runloop; MDSettings settings; MDGate app(settings); runloop.run(); return 0; }
32.903571
144
0.672202
[ "vector" ]
a0193ec959707401f4ed72cd05e9a16efbca8903
15,713
cpp
C++
heart/src/problem/HeartGeometryInformation.cpp
AvciRecep/chaste_2019
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-04-05T12:11:54.000Z
2020-04-05T12:11:54.000Z
heart/src/problem/HeartGeometryInformation.cpp
AvciRecep/chaste_2019
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
heart/src/problem/HeartGeometryInformation.cpp
AvciRecep/chaste_2019
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-04-05T14:26:13.000Z
2021-03-09T08:18:17.000Z
/* Copyright (c) 2005-2019, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "HeartGeometryInformation.hpp" #include <cmath> #include <fstream> #include <sstream> #include "OutputFileHandler.hpp" #include "Exception.hpp" #include "PetscTools.hpp" // Area of the septum considered to belong to the each ventricle (relative to 1) template<unsigned SPACE_DIM> const double HeartGeometryInformation<SPACE_DIM>::LEFT_SEPTUM_SIZE = 2.0/3.0; template<unsigned SPACE_DIM> const double HeartGeometryInformation<SPACE_DIM>::RIGHT_SEPTUM_SIZE = 1.0/3.0; template<unsigned SPACE_DIM> HeartGeometryInformation<SPACE_DIM>::HeartGeometryInformation(AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>& rMesh, const std::string& rEpiFile, const std::string& rEndoFile, bool indexFromZero) : mpMesh(&rMesh) { DistanceMapCalculator<SPACE_DIM, SPACE_DIM> distance_calculator(*mpMesh); // Get nodes defining each surface GetNodesAtSurface(rEpiFile, mEpiSurface, indexFromZero); GetNodesAtSurface(rEndoFile, mEndoSurface, indexFromZero); // Compute the distance map of each surface distance_calculator.ComputeDistanceMap(mEpiSurface, mDistMapEpicardium); distance_calculator.ComputeDistanceMap(mEndoSurface, mDistMapEndocardium); mNumberOfSurfacesProvided = 2; } template<unsigned SPACE_DIM> HeartGeometryInformation<SPACE_DIM>::HeartGeometryInformation (AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>& rMesh, const std::string& rEpiFile, const std::string& rLVFile, const std::string& rRVFile, bool indexFromZero) : mpMesh(&rMesh) { DistanceMapCalculator<SPACE_DIM, SPACE_DIM> distance_calculator(*mpMesh); // Get nodes defining each surface and compute the distance map of each surface GetNodesAtSurface(rEpiFile, mEpiSurface, indexFromZero); if (rLVFile != "") { GetNodesAtSurface(rLVFile, mLVSurface, indexFromZero); } else { if (rRVFile == "") { EXCEPTION("At least one of left ventricle or right ventricle files is required"); } } if (rRVFile != "") { GetNodesAtSurface(rRVFile, mRVSurface, indexFromZero); } distance_calculator.ComputeDistanceMap(mEpiSurface, mDistMapEpicardium); distance_calculator.ComputeDistanceMap(mLVSurface, mDistMapLeftVentricle); distance_calculator.ComputeDistanceMap(mRVSurface, mDistMapRightVentricle); mNumberOfSurfacesProvided = 3; } template<unsigned SPACE_DIM> HeartGeometryInformation<SPACE_DIM>::HeartGeometryInformation (std::string nodeHeterogeneityFileName) { mpMesh = NULL; std::ifstream heterogeneity_file; heterogeneity_file.open(nodeHeterogeneityFileName.c_str()); if (!(heterogeneity_file.is_open())) { heterogeneity_file.close(); EXCEPTION("Could not open heterogeneities file (" << nodeHeterogeneityFileName << ")"); } while (!heterogeneity_file.eof()) { int value; heterogeneity_file >> value; // Format error (for example read a double), or value not equal to 0, 1, or 2. if ((heterogeneity_file.fail() && !heterogeneity_file.eof()) || value < 0 || value > 2) { heterogeneity_file.close(); EXCEPTION("A value in the heterogeneities file (" << nodeHeterogeneityFileName << ") is out of range (or not an integer). It should be epi = 0, mid = 1, endo = 2"); } if (!heterogeneity_file.eof()) { if (value==0) { mLayerForEachNode.push_back(EPI); } else if (value==1) { mLayerForEachNode.push_back(MID); } else { assert(value==2); mLayerForEachNode.push_back(ENDO); } } } heterogeneity_file.close(); } template<unsigned SPACE_DIM> void HeartGeometryInformation<SPACE_DIM>::ProcessLine( const std::string& rLineFromFile, std::set<unsigned>& rSurfaceNodeIndexSet, unsigned offset) const { std::stringstream line_stream(rLineFromFile); while (!line_stream.eof()) { unsigned item; line_stream >> item; // If offset==1 then shift the nodes, since we are assuming MEMFEM format (numbered from 1 on) if (item == 0 && offset != 0) { EXCEPTION("Error when reading surface file. It was assumed not to be indexed from zero, but zero appeared in the list."); } rSurfaceNodeIndexSet.insert(item-offset); } } template<unsigned SPACE_DIM> void HeartGeometryInformation<SPACE_DIM>::GetNodesAtSurface( const std::string& rSurfaceFileName, std::vector<unsigned>& rSurfaceNodes, bool indexFromZero) const { // Open the file defining the surface std::ifstream file_stream; unsigned offset=0; if (indexFromZero == false) { offset=1; } file_stream.open(rSurfaceFileName.c_str()); if (!file_stream.is_open()) { EXCEPTION("Wrong surface definition file name " + rSurfaceFileName); } // Temporary storage for the nodes, helps discarding repeated values std::set<unsigned> surface_original_node_index_set; // Loop over all the triangles and add node indexes to the set std::string line; getline(file_stream, line); do { ProcessLine(line, surface_original_node_index_set, offset); getline(file_stream, line); } while (!file_stream.eof()); file_stream.close(); // Make vector big enough rSurfaceNodes.reserve(surface_original_node_index_set.size()); if (mpMesh->rGetNodePermutation().empty()) { // Copy the node indexes from the set to the vector as they are for (std::set<unsigned>::iterator node_index_it=surface_original_node_index_set.begin(); node_index_it != surface_original_node_index_set.end(); node_index_it++) { rSurfaceNodes.push_back(*node_index_it); } } else { // Copy the original node indices from the set to the vector applying the permutation for (std::set<unsigned>::iterator node_index_it=surface_original_node_index_set.begin(); node_index_it != surface_original_node_index_set.end(); node_index_it++) { rSurfaceNodes.push_back(mpMesh->rGetNodePermutation()[*node_index_it]); } } } template<unsigned SPACE_DIM> HeartRegionType HeartGeometryInformation<SPACE_DIM>::GetHeartRegion(unsigned nodeIndex) const { if (mDistMapRightVentricle[nodeIndex] >= mDistMapEpicardium[nodeIndex] && mDistMapRightVentricle[nodeIndex] >= mDistMapLeftVentricle[nodeIndex]) { return LEFT_VENTRICLE_WALL; } if (mDistMapLeftVentricle[nodeIndex] >= mDistMapEpicardium[nodeIndex] && mDistMapLeftVentricle[nodeIndex] >= mDistMapRightVentricle[nodeIndex]) { return RIGHT_VENTRICLE_WALL; } if (mDistMapEpicardium[nodeIndex] >= mDistMapLeftVentricle[nodeIndex] && mDistMapEpicardium[nodeIndex] >= mDistMapRightVentricle[nodeIndex]) { if (mDistMapLeftVentricle[nodeIndex] < LEFT_SEPTUM_SIZE*(mDistMapLeftVentricle[nodeIndex] + mDistMapRightVentricle[nodeIndex])) { return LEFT_SEPTUM; } else { return RIGHT_SEPTUM; } } NEVER_REACHED; return UNKNOWN; // LCOV_EXCL_LINE } template<unsigned SPACE_DIM> double HeartGeometryInformation<SPACE_DIM>::GetDistanceToEndo(unsigned nodeIndex) { // General case where you provide 3 surfaces: LV, RV, epicardium if (mNumberOfSurfacesProvided == 3) { HeartRegionType node_region = GetHeartRegion(nodeIndex); switch(node_region) { case LEFT_VENTRICLE_WALL: case LEFT_VENTRICLE_SURFACE: return mDistMapLeftVentricle[nodeIndex]; break; case RIGHT_VENTRICLE_WALL: case RIGHT_VENTRICLE_SURFACE: return mDistMapRightVentricle[nodeIndex]; break; case LEFT_SEPTUM: return mDistMapLeftVentricle[nodeIndex]; break; case RIGHT_SEPTUM: return mDistMapRightVentricle[nodeIndex] ; break; case UNKNOWN: // LCOV_EXCL_START std::cerr << "Wrong distances node: " << nodeIndex << "\t" << "Epi " << mDistMapEpicardium[nodeIndex] << "\t" << "RV " << mDistMapRightVentricle[nodeIndex] << "\t" << "LV " << mDistMapLeftVentricle[nodeIndex] << std::endl; // Make wall_thickness=0 as in Martin's code return 0.0; break; // LCOV_EXCL_STOP default: NEVER_REACHED; } } // Simplified case where you only provide epi and endo surface definitions else { return mDistMapEndocardium[nodeIndex]; } // gcc wants to see a return statement at the end of the method. NEVER_REACHED; return 0.0; // LCOV_EXCL_LINE } template<unsigned SPACE_DIM> double HeartGeometryInformation<SPACE_DIM>::GetDistanceToEpi(unsigned nodeIndex) { return mDistMapEpicardium[nodeIndex]; } template<unsigned SPACE_DIM> double HeartGeometryInformation<SPACE_DIM>::CalculateRelativeWallPosition(unsigned nodeIndex) { double dist_endo = GetDistanceToEndo(nodeIndex); double dist_epi = GetDistanceToEpi(nodeIndex); assert( (dist_endo + dist_epi) != 0 ); /* * A node contained on both epicardium and lv (or rv) surfaces has wall thickness 0/0. * By setting its value to 0 we consider it contained only on the lv (or rv) surface. */ double relative_position = dist_endo / (dist_endo + dist_epi); return relative_position; } template<unsigned SPACE_DIM> void HeartGeometryInformation<SPACE_DIM>::DetermineLayerForEachNode(double epiFraction, double endoFraction) { if (epiFraction+endoFraction>1) { EXCEPTION("The sum of fractions of epicardial and endocardial layers must be lesser than 1"); } if ((endoFraction<0) || (epiFraction<0)) { EXCEPTION("A fraction of a layer must be positive"); } mLayerForEachNode.resize(mpMesh->GetNumNodes()); for (unsigned i=0; i<mpMesh->GetNumNodes(); i++) { double position = CalculateRelativeWallPosition(i); if (position<endoFraction) { mLayerForEachNode[i] = ENDO; } else if (position<(1-epiFraction)) { mLayerForEachNode[i] = MID; } else { mLayerForEachNode[i] = EPI; } } } template<unsigned SPACE_DIM> void HeartGeometryInformation<SPACE_DIM>::WriteLayerForEachNode(std::string outputDir, std::string file) { OutputFileHandler handler(outputDir,false); if (PetscTools::AmMaster()) { out_stream p_file = handler.OpenOutputFile(file); assert(mLayerForEachNode.size()>0); for (unsigned i=0; i<mpMesh->GetNumNodes(); i++) { if (mLayerForEachNode[i]==EPI) { *p_file << "0\n"; } else if (mLayerForEachNode[i]==MID) { *p_file << "1\n"; } else // endo { *p_file << "2\n"; } } p_file->close(); } PetscTools::Barrier("HeartGeometryInformation::WriteLayerForEachNode"); // Make other processes wait until we're done } template<unsigned SPACE_DIM> ChasteCuboid<SPACE_DIM> HeartGeometryInformation<SPACE_DIM>::CalculateBoundingBoxOfSurface( const std::vector<unsigned>& rSurfaceNodes) { assert(rSurfaceNodes.size()>0); //Set min to DBL_MAX etc. c_vector<double, SPACE_DIM> my_minimum_point = scalar_vector<double>(SPACE_DIM, DBL_MAX); //Set max to -DBL_MAX etc. c_vector<double, SPACE_DIM> my_maximum_point=-my_minimum_point; //Iterate through the set of points on the surface for (unsigned surface_index=0; surface_index<rSurfaceNodes.size(); surface_index++) { unsigned global_index=rSurfaceNodes[surface_index]; if (mpMesh->GetDistributedVectorFactory()->IsGlobalIndexLocal(global_index) ) { const c_vector<double, SPACE_DIM>& r_position = mpMesh->GetNode(global_index)->rGetLocation(); //Update max/min for (unsigned i=0; i<SPACE_DIM; i++) { if (r_position[i] < my_minimum_point[i]) { my_minimum_point[i] = r_position[i]; } if (r_position[i] > my_maximum_point[i]) { my_maximum_point[i] = r_position[i]; } } } } //Share the local data and reduce over all processes c_vector<double, SPACE_DIM> global_minimum_point; c_vector<double, SPACE_DIM> global_maximum_point; MPI_Allreduce(&my_minimum_point[0], &global_minimum_point[0], SPACE_DIM, MPI_DOUBLE, MPI_MIN, PETSC_COMM_WORLD); MPI_Allreduce(&my_maximum_point[0], &global_maximum_point[0], SPACE_DIM, MPI_DOUBLE, MPI_MAX, PETSC_COMM_WORLD); ChastePoint<SPACE_DIM> min(global_minimum_point); ChastePoint<SPACE_DIM> max(global_maximum_point); return ChasteCuboid<SPACE_DIM>(min, max); } // Explicit instantiation template class HeartGeometryInformation<2>; template class HeartGeometryInformation<3>;
34.534066
134
0.647426
[ "vector" ]
a01caf88331c24a9de5bfe341a1f2c7693fde5f5
15,189
hpp
C++
vaslib/vas_math.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
vaslib/vas_math.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
vaslib/vas_math.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
#ifndef VAS_MATH_HPP #define VAS_MATH_HPP #include <algorithm> #include <array> #include <cinttypes> #include <cmath> #include <optional> #include "vas_cpp_utils.hpp" using uint = unsigned int; struct SDL_Rect; struct Rect; struct Rectfp; struct vec2i; struct vec2fp; float sine_lut_norm(float x); ///< Table-lookup sine, x is [0, 1] representing [0, 2pi] vec2fp cossin_lut(float rad); ///< Table-lookup cosine (x) + sine (y) /// Integer square root uint isqrt(uint value); /// Quake III float fast_invsqrt(float x); /// Approximate comparison template <typename T1, typename T2, typename T3> bool aequ(T1 v, T2 c, T3 eps) {return std::fabs(v - c) < eps;} inline float fracpart(float v) {return v - static_cast<int>(v);} inline float clampf(float x, float min, float max) {return std::max(min, std::min(max, x));} inline float clampf_n(float x) {return clampf(x, 0, 1);} template <typename T> T clamp(T x, T min, T max) {return std::max(min, std::min(max, x));} template <typename T1, typename T2, typename T3> typename std::common_type_t<T1, T2> lerp (T1 a, T2 b, T3 t) {return a * (1 - t) + b * t;} template <typename T1> T1 inv_lerp(T1 a, T1 b, T1 v) {return (v - a) / (b - a);} template <typename T> int int_round(T value) {return static_cast<int>(std::round(value));} /// Absolute difference in ring of numbers modulo n; a,b ∈ [0, n) template <typename T> typename std::enable_if_t<std::is_signed_v<T>, T> modulo_dist(T a, T b, T n) { T d1 = std::abs(a - b); return std::min(d1, n - d1); } constexpr float deg_to_rad(float x) {return x / 180.f * M_PI;} float wrap_angle_2(float x); ///< Brings to [0; 2pi] float wrap_angle(float x); ///< Brings to [-pi, +pi] /// Returns delta for lerp from current to target (shortest path, [-pi; +pi]) float angle_delta(float target, float current); /// Returns absolute difference between two unbound angles, [0; pi] inline float abs_angle_diff(float a1, float a2) {return std::fabs(wrap_angle( a1 - a2 ));} /// Linear interpolation between two angles, expressed in radians. Handles all cases template <typename T1, typename T2, typename T3> typename std::enable_if_t < std::is_floating_point_v<typename std::common_type_t<T1, T2, T3>>, typename std::common_type_t<T1, T2, T3> > lerp_angle (T1 a, T2 b, T3 t) {return a + t * std::remainder(b - a, M_PI*2);} /// 2D integer vector struct vec2i { int x, y; vec2i() = default; vec2i(int x, int y): x(x),y(y) {} void set(int x, int y) {this->x = x; this->y = y;} vec2i& zero() {x = y = 0; return *this;} static vec2i one( int v ) { return {v, v};} void operator += (const vec2i& v) {x += v.x; y += v.y;} void operator -= (const vec2i& v) {x -= v.x; y -= v.y;} void operator *= (const vec2i& v) {x *= v.x; y *= v.y;} void operator /= (const vec2i& v) {x /= v.x; y /= v.y;} void operator *= (double f) {x = std::floor(x * f); y = std::floor(y * f);} void operator /= (double f) {x = std::floor(x / f); y = std::floor(y / f);} vec2i operator + (const vec2i& v) const {return {x + v.x, y + v.y};} vec2i operator - (const vec2i& v) const {return {x - v.x, y - v.y};} vec2i operator * (const vec2i& v) const {return {x * v.x, y * v.y};} vec2i operator / (const vec2i& v) const {return {x / v.x, y / v.y};} vec2i operator * (double f) const {return vec2i(std::floor(x * f), std::floor(y * f));} vec2i operator / (double f) const {return vec2i(std::floor(x / f), std::floor(y / f));} vec2i operator - () const {return vec2i(-x, -y);} bool operator == (const vec2i& v) const {return x == v.x && y == v.y;} bool operator != (const vec2i& v) const {return x != v.x || y != v.y;} bool is_zero() const {return x == 0 && y == 0;} float len() const {return std::sqrt(x*x + y*y);} ///< Length float angle() const {return y && x? std::atan2( y, x ) : 0;} ///< Rotation angle (radians, [-pi, +pi]) uint len_squ() const {return x*x + y*y;} ///< Square of length uint ilen() const {return isqrt(x*x + y*y);} ///< Integer length (approximate) float dist(const vec2i& v) const {return (*this - v).len();} ///< Straight distance uint ndg_dist(const vec2i& v) const {return std::abs(x - v.x) + std::abs(y - v.y);} ///< Manhattan distance uint int_dist(const vec2i& v) const {return (*this - v).ilen();} ///< Straight integer distance (approximate) vec2i& rot90cw() {int t = x; x = y; y = -t; return *this;} vec2i& rot90ccw() {int t = x; x = -y; y = t; return *this;} vec2fp rotate (double angle) const; ///< Rotation by angle (radians) vec2fp fastrotate (float angle) const; ///< Rotation by angle (radians) using table lookup int area() const {return std::abs(x * y);} int perimeter() const {return (x+y)*2;} vec2i minmax() const; ///< (min, max) double xy_ratio() const {return double(x) / y;} template <typename T> int& operator() (T) = delete; int& operator() (bool is_x) {return is_x? x : y;} operator vec2fp() const; vec2fp get_norm() const; }; inline vec2i abs(const vec2i& p) {return {std::abs(p.x), std::abs(p.y)};} inline vec2i operator * (double f, const vec2i& v) {return vec2i(std::floor(v.x * f), std::floor(v.y * f));} inline vec2i min(const vec2i& a, const vec2i& b) {return {std::min(a.x, b.x), std::min(a.y, b.y)};} inline vec2i max(const vec2i& a, const vec2i& b) {return {std::max(a.x, b.x), std::max(a.y, b.y)};} inline bool any_gtr(const vec2i& p, const vec2i& ref) {return p.x > ref.x || p.y > ref.y;} /// Returns true if point lies in polygon or on it's edge bool is_in_polygon(vec2i p, const vec2i* ps, size_t pn); /// Returns true if point lies inside rectangle ({0,0}, size - {1,1}), including edges bool is_in_bounds(const vec2i& p, const vec2i& size); /// 2D floating-point vector struct vec2fp { float x, y; vec2fp() = default; vec2fp(float x, float y): x(x),y(y) {} void set(float x, float y) {this->x = x; this->y = y;} void zero() {x = y = 0;} static vec2fp one( float v ) { return {v, v};} void operator += (const vec2fp& v) {x += v.x; y += v.y;} void operator -= (const vec2fp& v) {x -= v.x; y -= v.y;} void operator *= (const vec2fp& v) {x *= v.x; y *= v.y;} void operator /= (const vec2fp& v) {x /= v.x; y /= v.y;} void operator *= (float f) {x *= f; y *= f;} void operator /= (float f) {x /= f; y /= f;} vec2fp operator + (const vec2fp& v) const {return {x + v.x, y + v.y};} vec2fp operator - (const vec2fp& v) const {return {x - v.x, y - v.y};} vec2fp operator * (const vec2fp& v) const {return {x * v.x, y * v.y};} vec2fp operator / (const vec2fp& v) const {return {x / v.x, y / v.y};} vec2fp operator * (float f) const {return {x * f, y * f};} vec2fp operator / (float f) const {return {x / f, y / f};} vec2fp operator - () const {return vec2fp(-x, -y);} bool equals(const vec2fp& v, float eps) const { return aequ(x, v.x, eps) && aequ(y, v.y, eps); } bool is_zero(float eps) const {return std::fabs(x) < eps && std::fabs(y) < eps;} bool is_exact_zero() const {return x == 0.f && y == 0.f;} float fastlen() const {return 1.f / fast_invsqrt(x*x + y*y);} ///< Length should be non-zero! float len() const {return std::sqrt(x*x + y*y);} ///< Length float len_squ() const {return x*x + y*y;} ///< Squared length float fastangle() const; ///< Approximate rotation angle (radians, [-pi, +pi]) float angle() const; ///< Rotation angle (radians, [-pi, +pi]) float dist(const vec2fp& v) const {return (*this - v).len();} ///< Straight distance float ndg_dist(const vec2fp& v) const {return std::fabs(x - v.x) + std::fabs(y - v.y);} ///< Manhattan distance float dist_squ(const vec2fp& v) const {return (*this - v).len_squ();} ///< Squared distance vec2fp& rot90cw() {float t = x; x = y; y = -t; return *this;} vec2fp& rot90ccw() {float t = x; x = -y; y = t; return *this;} vec2fp& rotate(double angle); ///< Rotation by angle (radians) vec2fp& fastrotate(float angle); ///< Rotation by angle (radians) using table lookup vec2fp& rotate(float cos, float sin); vec2fp get_rotated(double angle) const {return vec2fp(*this).rotate(angle);} vec2fp& norm(); ///< Normalizes vector vec2fp& norm_to(float n); ///< Brings vector to specified length vec2fp& limit_to(float n); ///< Brings vector to specified length if it exceeds it vec2fp get_norm() const {return vec2fp(*this).norm();} float area() const {return std::fabs(x * y);} vec2fp minmax() const; ///< (min, max) vec2i int_floor() const {return vec2i(std::floor(x), std::floor(y));} vec2i int_round() const {return vec2i(std::round(x), std::round(y));} vec2i int_ceil () const {return vec2i(std::ceil (x), std::ceil (y));} template <typename T> int& operator() (T) = delete; float& operator() (bool is_x) {return is_x? x : y;} }; inline vec2fp abs(const vec2fp& p) {return {std::abs(p.x), std::abs(p.y)};} inline float dot (const vec2fp& a, const vec2fp& b) {return a.x * b.x + a.y * b.y;} inline float cross(const vec2fp& a, const vec2fp& b) {return a.x * b.y - a.y * b.x;} inline vec2fp operator * (double f, const vec2fp& v) {return vec2fp(v.x * f, v.y * f);} /// Spherical linear interpolation of unit vectors vec2fp slerp (const vec2fp &v0, const vec2fp &v1, float t); inline vec2fp min(const vec2fp &a, const vec2fp &b) {return {std::min(a.x, b.x), std::min(a.y, b.y)};} inline vec2fp max(const vec2fp &a, const vec2fp &b) {return {std::max(a.x, b.x), std::max(a.y, b.y)};} /// Returns line segment intersection point, if any std::optional<vec2fp> lineseg_intersect(vec2fp a1, vec2fp a2, vec2fp b1, vec2fp b2, float eps = 1e-10); /// Returns t,u of intersection point a+at*t = b+bt*u if lines aren't collinear or parallel std::optional<std::pair<float, float>> line_intersect_t(vec2fp a, vec2fp at, vec2fp b, vec2fp bt, float eps = 1e-10); /// Returns 't' (C = A + t*(B-A)) - point together with 'p' forming perpendicular to line a-b float lineseg_perpen_t(vec2fp a, vec2fp b, vec2fp p); /// Returns point which together with 'p' forms perpendicular to line a-b, if it lies in segment bounds std::optional<vec2fp> lineseg_perpen(vec2fp a, vec2fp b, vec2fp p); /// Calculates scale and offset to fit rectangle of one size into another, keeping aspect ratio std::pair<float, vec2fp> fit_rect(vec2fp size, vec2fp into); /// Integer rectangle struct Rect { vec2i off, sz; Rect() = default; static Rect bounds(vec2i lower, vec2i upper) {return {lower, upper - lower};} static Rect off_size(vec2i offset, vec2i size) {return {offset, size};} void zero() {off.zero(); sz.zero();} const vec2i& lower() const {return off;} vec2i upper() const {return off + sz;} const vec2i& size() const {return sz;} vec2i center() const {return off + sz /2;} vec2fp fp_center() const {return vec2fp(off) + vec2fp(sz) /2;} void lower(vec2i v) {off = v;} void upper(vec2i v) {sz = v - off;} void size (vec2i v) {sz = v;} static Rect from_center_le(vec2i ctr, vec2i half_size) {return bounds(ctr - half_size, ctr + half_size + vec2i::one(1));} Rectfp to_fp(float mul) const; void shift(vec2i v) {off += v;} void enclose(vec2i v) {off = min(v, off); upper(max(upper(), v + vec2i::one(1)));} vec2i maxpt() const {return off + sz - vec2i::one(1);} ///< Maximum enclosed point bool empty() const {return sz.x <= 0 || sz.y <= 0;} ///< Returns true if rectangle is of zero size bool intersects(const Rect& r) const; ///< Checks if rectangles overlap, including edges bool contains(vec2i p) const; ///< Checks if point is inside, including edges bool contains_le(vec2i p) const; ///< Checks if point is inside, including only lower edges operator Rectfp() const; operator SDL_Rect() const; void set(const SDL_Rect& r); bool operator == (const Rect& r) const {return lower() == r.lower() && sz == r.sz;} bool operator != (const Rect& r) const {return lower() != r.lower() || sz != r.sz;} /// Maps function over entire area, scanline-like. /// Lower edge included, upper excluded. void map(callable_ref<void(vec2i p)> f) const; /// Same as map, but returns false as soon as 'f' does bool map_check(callable_ref<bool(vec2i p)> f) const; /// Maps function over outer border (-1 from lower and ON upper). /// Clockwise, from lower corner void map_outer(callable_ref<void(vec2i p)> f) const; /// Maps function over inner border (on lower and -1 from upper). /// Clockwise, from lower corner void map_inner(callable_ref<void(vec2i p)> f) const; private: Rect(vec2i off, vec2i sz): off(off), sz(sz) {} }; Rect calc_intersection(const Rect& a, const Rect& b); ///< Returns rectangle representing overlap Rect get_bound(const Rect& a, const Rect& b); ///< Returns rectangle enclosing both rectangles uint min_distance(const Rect& a, const Rect& b); ///< Returns minimal straight distance /// Floating-point rectangle struct Rectfp { vec2fp a, b; // lower and upper bounds Rectfp() = default; static Rectfp bounds(vec2fp lower, vec2fp upper) {return {lower, upper};} static Rectfp off_size(vec2fp offset, vec2fp size) {return {offset, offset + size};} void zero() { a.zero(); b.zero(); } const vec2fp& lower() const {return a;} const vec2fp& upper() const {return b;} vec2fp size() const {return b - a;} vec2fp center() const {return a + size() / 2;} void lower (vec2fp v) {a = v;} void upper (vec2fp v) {b = v;} void size (vec2fp v) {b = v + a;} static Rectfp from_center(vec2fp ctr, vec2fp half_size) {return bounds(ctr - half_size, ctr + half_size);} void offset(vec2fp v) {a += v; b += v;} /// Returns points representing same rectangle rotated around center std::array <vec2fp, 4> rotate( float cs, float sn ) const; /// Returns points representing same rectangle rotated around center (uses cossin_ft) std::array <vec2fp, 4> rotate_fast( float rad ) const; void merge( const Rectfp& r ); ///< Expands this rectangle to enclose another bool overlaps( const Rectfp& r ) const; ///< Checks if rectangles overlap, including edges bool contains( const Rectfp& r ) const; ///< Checks if another rectangle is completely within this bool contains( vec2fp p ) const; ///< Checks if point is inside, excluding edges bool contains( vec2fp p, float width ) const; ///< Checks if point is inside; edges are shrinked by width private: Rectfp(vec2fp a, vec2fp b): a(a), b(b) {} }; /// 2D struct Transform { vec2fp pos; float rot; Transform() = default; explicit Transform(vec2fp pos, float rot = 0.f): pos(pos), rot(rot) {} vec2fp apply(vec2fp p) const; ///< Applies transform to point vec2fp reverse(vec2fp p) const; ///< Applies reverse transform to point Transform& combine(const Transform& t); Transform& combine_reversed(const Transform& t); Transform get_combined(const Transform& t) const; Transform& add(const Transform& t); Transform get_add(const Transform& t) const; Transform operator -() const {return Transform{-pos, -rot};} Transform operator * (float t) const; Transform& operator *= (float t); Transform operator / (float t) const; Transform& operator /= (float t); Transform diff(const Transform& t) const; ///< Returns *this - t }; inline Transform lerp (const Transform &a, const Transform &b, float t) { return Transform{lerp(a.pos, b.pos, t), lerp_angle(a.rot, b.rot, t)};} #endif // VAS_MATH_HPP
38.747449
122
0.656396
[ "vector", "transform" ]
a01e32061a18a9b10a32d0c25d52845c6278df68
2,768
hpp
C++
src/Search.hpp
Andrew-Y-Xia/Bitboard-Chess
364524530fc08f288c3c7043f61c8914549f2c47
[ "MIT" ]
null
null
null
src/Search.hpp
Andrew-Y-Xia/Bitboard-Chess
364524530fc08f288c3c7043f61c8914549f2c47
[ "MIT" ]
null
null
null
src/Search.hpp
Andrew-Y-Xia/Bitboard-Chess
364524530fc08f288c3c7043f61c8914549f2c47
[ "MIT" ]
null
null
null
// // Search.hpp // SFML Chess // // Created by Andrew Xia on 4/16/21. // Copyright © 2021 Andy. All rights reserved. // #ifndef Search_hpp #define Search_hpp #include "Board.hpp" #include "Transposition_table.hpp" #include "Opening_book.hpp" #include "Time_handler.hpp" #define MAX_DEPTH 64 #define MAXMATE 2000000 #define MINMATE 1999000 #define PRUNE_MOVE_SCORE 0 #define USE_NULL_MOVE_PRUNING 1 #define USE_ASPIRATION_WINDOWS 1 #define USE_PV_SEARCH 1 #define USE_KILLERS 1 #define USE_HIST_HEURISTIC 1 #define EXTENSION_LIMIT 5 #define USE_DELTA_PRUNING 0 #define USE_LATE_MOVE_REDUCTION 1 #define USE_BOOK 0 #define R 2 extern unsigned int lmr_values[256]; void init_search(); class MovePicker { private: MoveList& moves; int size, visit_count; public: MovePicker(MoveList& init_moves); int finished(); Move operator++(); }; struct SearchTimeout : public std::exception { }; class Search { private: Board board; TT& tt; OpeningBook& opening_book; TimeHandler& time_handler; Move killer_moves[MAX_DEPTH][2]; unsigned int history_moves[2][64][64]; unsigned int nodes_searched; public: Search(Board b, TT& t, OpeningBook& ob, TimeHandler& th); template <bool use_history_heuristic = false> void assign_move_scores(MoveList &moves, HashMove hash_move, Move killers[2]); template <bool use_delta_pruning> void assign_move_scores_quiescent(MoveList &moves, int eval, int alpha); std::vector<Move> get_pv(); void store_pos_result(HashMove best_move, unsigned int depth, unsigned int node_type, int score, unsigned int ply_from_root); void log_search_info(int depth, int eval); void search_finished_message(Move best_move, int depth, int eval); int negamax(unsigned int depth, int alpha, int beta, unsigned int ply_from_root, unsigned int ply_extended, bool do_null_move); void register_killers(unsigned int ply_from_root, Move move); void register_history_move(unsigned int depth, Move move); int quiescence_search(unsigned int ply_from_horizon, int alpha, int beta, unsigned int ply_from_root); Move find_best_move(unsigned int max_depth); long perft(unsigned int depth); long sort_perft(unsigned int depth); long hash_perft(unsigned int depth); long hash_perft_internal(unsigned int depth); long capture_perft(unsigned int depth); void pvs_lmr_core(int alpha, int beta, unsigned int ply_from_root, unsigned int ply_extended, bool do_pvs, int& eval, unsigned int effective_depth, unsigned int depth); unsigned int determine_depth(unsigned int effective_depth, unsigned int depth_reduction_value, Move move, bool do_lmr); }; #endif /* Search_hpp */
24.714286
131
0.73591
[ "vector" ]
a021357c23c73ce8fa60cc5fa97a41836c4b8e2c
2,611
cpp
C++
USACO2020Grind/src/revegetate.cpp
javaarchive/USACOClass2020
4ae563014b9b2da3e1361e175d38e72308a8da89
[ "MIT" ]
null
null
null
USACO2020Grind/src/revegetate.cpp
javaarchive/USACOClass2020
4ae563014b9b2da3e1361e175d38e72308a8da89
[ "MIT" ]
null
null
null
USACO2020Grind/src/revegetate.cpp
javaarchive/USACOClass2020
4ae563014b9b2da3e1361e175d38e72308a8da89
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <vector> #define MAXN 100001 using namespace std; int N,M; bool visited[MAXN] = {false}; int seedType[MAXN] = {0}; const char SAME = 'S'; const char DIFFERENT = 'D'; map<int, vector<pair<int,char>>> requirements; void setIO(string s) { ios_base::sync_with_stdio(0); cin.tie(0); freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } int recurSet(int pos, int newSeedType){ if(visited[pos]){ return 0; // graceful } visited[pos] = true; seedType[pos] = newSeedType; if(requirements.find(pos) != requirements.end()){ if(requirements[pos].size() > 0){ for(auto iter = requirements[pos].begin(); iter != requirements[pos].end(); iter ++ ){ char requirement = iter->second; int nextPos = iter->first; if(!visited[nextPos]){ if(requirement == SAME){ if(recurSet(nextPos, seedType[pos]) == 1){ return 1; } }else if(requirement == DIFFERENT){ if(recurSet(nextPos, 1 - seedType[pos]) == 1){ return 1; } } }else{ // Verify if(requirement == SAME){ if(seedType[pos] != seedType[nextPos]){ return 1; // :O something is defintley wrong } }else if(requirement == DIFFERENT){ if(seedType[pos] == seedType[nextPos]){ return 1; // :O something is defintley wrong } } } } } } return 0; } int main(int argc, const char** argv) { if(argc != 2){ setIO("revegetate"); } cin >> N >> M; int zeros = 0; for(int i = 0; i < M; i ++){ char c; // Type cin >> c; int A,B; cin >> A >> B; A --; B --; requirements[A].push_back(make_pair(B,c)); requirements[B].push_back(make_pair(A,c)); } for(int i = 0; i < N; i ++){ if(!visited[i]){ zeros ++; if(recurSet(i, 0) == 1){ // Contradictory statement cout << 0; return 0; // terminate } } } cout << 1; for(int i = 0; i < zeros; i ++){ cout << 0; } cout << endl; return 0; }
29.011111
98
0.430869
[ "vector" ]
a0251cb58032222bef4b089c0f67e8db3d5b730c
18,838
cpp
C++
applications/ULFapplication/custom_elements/updated_lagrangian_fluid_inc.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/ULFapplication/custom_elements/updated_lagrangian_fluid_inc.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/ULFapplication/custom_elements/updated_lagrangian_fluid_inc.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
/* ============================================================================== KratosULFApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Pawel Ryzhakov pooyan@cimne.upc.edu rrossi@cimne.upc.edu - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last modified by: $Author: anonymous $ // Date: $Date: 2009-01-15 14:50:24 $ // Revision: $Revision: 1.3 $ // // //#define GRADPN_FORM //#define STOKES // System includes // External includes // Project includes #include "includes/define.h" #include "custom_elements/updated_lagrangian_fluid_inc.h" #include "utilities/math_utils.h" #include "ULF_application.h" #include "utilities/geometry_utilities.h" namespace Kratos { //static variables boost::numeric::ublas::bounded_matrix<double,3,6> UpdatedLagrangianFluidInc::msB; boost::numeric::ublas::bounded_matrix<double,3,3> UpdatedLagrangianFluidInc::ms_constitutive_matrix; boost::numeric::ublas::bounded_matrix<double,3,6> UpdatedLagrangianFluidInc::ms_temp; array_1d<double,6> UpdatedLagrangianFluidInc::ms_temp_vec; boost::numeric::ublas::bounded_matrix<double,3,2> UpdatedLagrangianFluidInc::msDN_Dx; array_1d<double,3> UpdatedLagrangianFluidInc::msN; //dimension = number of nodes //************************************************************************************ //************************************************************************************ UpdatedLagrangianFluidInc::UpdatedLagrangianFluidInc(IndexType NewId, GeometryType::Pointer pGeometry) : Element(NewId, pGeometry) { //DO NOT ADD DOFS HERE!!! } //************************************************************************************ //************************************************************************************ UpdatedLagrangianFluidInc::UpdatedLagrangianFluidInc(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties) : Element(NewId, pGeometry, pProperties) { } Element::Pointer UpdatedLagrangianFluidInc::Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const { KRATOS_TRY return Element::Pointer(new UpdatedLagrangianFluidInc(NewId, GetGeometry().Create(ThisNodes), pProperties)); KRATOS_CATCH(""); } UpdatedLagrangianFluidInc::~UpdatedLagrangianFluidInc() { } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY const double& density = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(DENSITY)+ GetGeometry()[1].FastGetSolutionStepValue(DENSITY) + GetGeometry()[2].FastGetSolutionStepValue(DENSITY)); //double K = GetProperties()[BULK_MODULUS]; double K = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(BULK_MODULUS)+ GetGeometry()[1].FastGetSolutionStepValue(BULK_MODULUS) + GetGeometry()[2].FastGetSolutionStepValue(BULK_MODULUS)); K *= density; //unsigned int dim = 2; unsigned int number_of_nodes = 3; if(rLeftHandSideMatrix.size1() != 6) rLeftHandSideMatrix.resize(6,6,false); if(rRightHandSideVector.size() != 6) rRightHandSideVector.resize(6,false); //calculate current area double current_area; GeometryUtils::CalculateGeometryData(GetGeometry(), msDN_Dx, msN, current_area); //writing the body force const array_1d<double,3>& body_force = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE)+ GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE) + GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE)); for(unsigned int i = 0; i<number_of_nodes; i++) { rRightHandSideVector[i*2] = body_force[0]* density * mA0 * 0.3333333333333; rRightHandSideVector[i*2+1] = body_force[1] * density * mA0 * 0.3333333333333; // rRightHandSideVector[i*2] = body_force[0]* density * current_area * 0.3333333333333; //rRightHandSideVector[i*2+1] = body_force[1] * density * current_area * 0.3333333333333; } /* //VISCOUS CONTRIBUTION TO THE STIFFNESS MATRIX // rLeftHandSideMatrix += Laplacian * nu; //filling matrix B for (unsigned int i=0;i<number_of_nodes;i++) { unsigned int index = dim*i; msB(0,index+0)=msDN_Dx(i,0); msB(0,index+1)= 0.0; msB(1,index+0)=0.0; msB(1,index+1)= msDN_Dx(i,1); msB(2,index+0)= msDN_Dx(i,1); msB(2,index+1)= msDN_Dx(i,0); } //constitutive tensor ms_constitutive_matrix(0,0) = K; ms_constitutive_matrix(0,1) = K ; ms_constitutive_matrix(0,2) = 0.0; ms_constitutive_matrix(1,0) = K; ms_constitutive_matrix(1,1) = K; ms_constitutive_matrix(1,2) = 0.0; ms_constitutive_matrix(2,0) = 0.0; ms_constitutive_matrix(2,1) = 0.0; ms_constitutive_matrix(2,2) = 0.0; //calculating viscous contributions ms_temp = prod( ms_constitutive_matrix , msB); noalias(rLeftHandSideMatrix) = prod( trans(msB) , ms_temp); rLeftHandSideMatrix *= -current_area; */ noalias(rLeftHandSideMatrix) = ZeroMatrix(6,6); //get the nodal pressure double p0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE); double p1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE); double p2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE); //adding pressure gradient double pavg = p0 + p1 + p2; //calculate old pressure over the element pavg *= 0.33333333333333333333333 * current_area; rRightHandSideVector[0] += msDN_Dx(0,0)*pavg; rRightHandSideVector[1] += msDN_Dx(0,1)*pavg; rRightHandSideVector[2] += msDN_Dx(1,0)*pavg; rRightHandSideVector[3] += msDN_Dx(1,1)*pavg; rRightHandSideVector[4] += msDN_Dx(2,0)*pavg; rRightHandSideVector[5] += msDN_Dx(2,1)*pavg; KRATOS_CATCH("") } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) { const double& density = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(DENSITY)+ GetGeometry()[1].FastGetSolutionStepValue(DENSITY) + GetGeometry()[2].FastGetSolutionStepValue(DENSITY)); //const double& density = GetProperties()[DENSITY]; //double K = GetProperties()[BULK_MODULUS]; double K = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(BULK_MODULUS)+ GetGeometry()[1].FastGetSolutionStepValue(BULK_MODULUS) + GetGeometry()[2].FastGetSolutionStepValue(BULK_MODULUS)); K *= density; // KRATOS_ERROR(std::logic_error,"not goooood",""); if(rRightHandSideVector.size() != 6) rRightHandSideVector.resize(6,false); unsigned int number_of_nodes = GetGeometry().size(); //calculate current area double current_area; GeometryUtils::CalculateGeometryData(GetGeometry(), msDN_Dx, msN, current_area); //writing the body force const array_1d<double,3>& body_force = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE)+ GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE) + GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE)); //const array_1d<double,3>& body_force = GetProperties()[BODY_FORCE]; for(unsigned int i = 0; i<number_of_nodes; i++) { rRightHandSideVector[i*2] = body_force[0]* density * mA0 * 0.3333333333333; rRightHandSideVector[i*2+1] = body_force[1] * density * mA0 * 0.3333333333333; //rRightHandSideVector[i*2] = body_force[0]* density * current_area * 0.3333333333333; //rRightHandSideVector[i*2+1] = body_force[1] * density * current_area * 0.3333333333333; } //get the nodal pressure double p0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE); double p1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE); double p2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE); //adding pressure gradient double pavg = p0 + p1 + p2; //calculate old pressure over the element pavg *= 0.33333333333333333333333 * current_area; rRightHandSideVector[0] += msDN_Dx(0,0)*pavg; rRightHandSideVector[1] += msDN_Dx(0,1)*pavg; rRightHandSideVector[2] += msDN_Dx(1,0)*pavg; rRightHandSideVector[3] += msDN_Dx(1,1)*pavg; rRightHandSideVector[4] += msDN_Dx(2,0)*pavg; rRightHandSideVector[5] += msDN_Dx(2,1)*pavg; } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::MassMatrix(MatrixType& rMassMatrix, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY const double& density = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(DENSITY)+ GetGeometry()[1].FastGetSolutionStepValue(DENSITY) + GetGeometry()[2].FastGetSolutionStepValue(DENSITY)); //lumped unsigned int dimension = GetGeometry().WorkingSpaceDimension(); unsigned int NumberOfNodes = GetGeometry().size(); unsigned int MatSize = dimension * NumberOfNodes; if(rMassMatrix.size1() != MatSize) rMassMatrix.resize(MatSize,MatSize,false); noalias(rMassMatrix) = ZeroMatrix(MatSize,MatSize); double nodal_mass = mA0 * density * 0.333333333333333333; for(unsigned int i=0; i<NumberOfNodes; i++) { for(unsigned int j=0; j<dimension; j++) { unsigned int index = i*dimension + j; rMassMatrix(index,index) = nodal_mass; } } KRATOS_CATCH("") } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::DampMatrix(MatrixType& rDampMatrix, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY unsigned int NumberOfNodes = GetGeometry().size(); unsigned int dim = GetGeometry().WorkingSpaceDimension(); if(rDampMatrix.size1() != 6) rDampMatrix.resize(6,6,false); //getting data for the given geometry double Area; GeometryUtils::CalculateGeometryData(GetGeometry(), msDN_Dx, msN, Area); //getting properties const double& nu = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(VISCOSITY)+ GetGeometry()[1].FastGetSolutionStepValue(VISCOSITY) + GetGeometry()[2].FastGetSolutionStepValue(VISCOSITY)); //double nu = GetProperties()[VISCOSITY]; //double density = GetProperties()[DENSITY]; const double& density = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(DENSITY)+ GetGeometry()[1].FastGetSolutionStepValue(DENSITY) + GetGeometry()[2].FastGetSolutionStepValue(DENSITY)); //VISCOUS CONTRIBUTION TO THE STIFFNESS MATRIX // rLeftHandSideMatrix += Laplacian * nu; //filling matrix B for (unsigned int i=0;i<NumberOfNodes;i++) { unsigned int index = dim*i; msB(0,index+0)=msDN_Dx(i,0); msB(0,index+1)= 0.0; msB(1,index+0)=0.0; msB(1,index+1)= msDN_Dx(i,1); msB(2,index+0)= msDN_Dx(i,1); msB(2,index+1)= msDN_Dx(i,0); } //constitutive tensor ms_constitutive_matrix(0,0) = (4.0/3.0)*nu*density; ms_constitutive_matrix(0,1) = -2.0/3.0*nu*density; ms_constitutive_matrix(0,2) = 0.0; ms_constitutive_matrix(1,0) = -2.0/3.0*nu*density; ms_constitutive_matrix(1,1) = 4.0/3.0*nu*density; ms_constitutive_matrix(1,2) = 0.0; ms_constitutive_matrix(2,0) = 0.0; ms_constitutive_matrix(2,1) = 0.0; ms_constitutive_matrix(2,2) = nu*density; //calculating viscous contributions ms_temp = prod( ms_constitutive_matrix , msB); noalias(rDampMatrix) = prod( trans(msB) , ms_temp); rDampMatrix *= Area; KRATOS_CATCH("") } //************************************************************************************ //************************************************************************************ // this subroutine calculates the nodal contributions for the explicit steps of the // fractional step procedure void UpdatedLagrangianFluidInc::InitializeSolutionStep(ProcessInfo& CurrentProcessInfo) { KRATOS_TRY //save original Area mA0 = GeometryUtils::CalculateVolume2D(GetGeometry()); KRATOS_CATCH(""); } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::EquationIdVector(EquationIdVectorType& rResult, ProcessInfo& CurrentProcessInfo) { unsigned int number_of_nodes = GetGeometry().PointsNumber(); unsigned int dim = 2; if(rResult.size() != number_of_nodes*dim) rResult.resize(number_of_nodes*dim,false); for (unsigned int i=0;i<number_of_nodes;i++) { rResult[i*dim] = GetGeometry()[i].GetDof(DISPLACEMENT_X).EquationId(); rResult[i*dim+1] = GetGeometry()[i].GetDof(DISPLACEMENT_Y).EquationId(); } } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::GetDofList(DofsVectorType& ElementalDofList,ProcessInfo& CurrentProcessInfo) { unsigned int number_of_nodes = GetGeometry().PointsNumber(); unsigned int dim = 2; if(ElementalDofList.size() != number_of_nodes*dim) ElementalDofList.resize(number_of_nodes*dim); for (unsigned int i=0;i<number_of_nodes;i++) { ElementalDofList[i*dim] = GetGeometry()[i].pGetDof(DISPLACEMENT_X); ElementalDofList[i*dim+1] = GetGeometry()[i].pGetDof(DISPLACEMENT_Y); } } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::GetValuesVector(Vector& values, int Step) { const unsigned int number_of_nodes = GetGeometry().size(); const unsigned int dim = GetGeometry().WorkingSpaceDimension(); unsigned int MatSize = number_of_nodes*dim; if(values.size() != MatSize) values.resize(MatSize,false); for (unsigned int i=0;i<number_of_nodes;i++) { unsigned int index = i*dim; const array_1d<double,3>& disp = GetGeometry()[i].FastGetSolutionStepValue(DISPLACEMENT,Step); values[index] = disp[0]; values[index + 1] = disp[1]; } } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::GetFirstDerivativesVector(Vector& values, int Step) { const unsigned int number_of_nodes = GetGeometry().size(); const unsigned int dim = GetGeometry().WorkingSpaceDimension(); unsigned int MatSize = number_of_nodes*dim; if(values.size() != MatSize) values.resize(MatSize,false); for (unsigned int i=0;i<number_of_nodes;i++) { unsigned int index = i*dim; const array_1d<double,3>& vel = GetGeometry()[i].FastGetSolutionStepValue(VELOCITY,Step); values[index] = vel[0]; values[index + 1] = vel[1]; } } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::GetSecondDerivativesVector(Vector& values, int Step) { const unsigned int number_of_nodes = GetGeometry().size(); const unsigned int dim = GetGeometry().WorkingSpaceDimension(); unsigned int MatSize = number_of_nodes*dim; if(values.size() != MatSize) values.resize(MatSize,false); for (unsigned int i=0;i<number_of_nodes;i++) { unsigned int index = i*dim; const array_1d<double,3>& acc = GetGeometry()[i].FastGetSolutionStepValue(ACCELERATION,Step); values[index] = acc[0]; values[index + 1] = acc[1]; } } //************************************************************************************ //************************************************************************************ void UpdatedLagrangianFluidInc::Calculate(const Variable<double >& rVariable, double& Output, const ProcessInfo& rCurrentProcessInfo) { /* const double& density = 0.333333333*(GetGeometry()[0].FastGetSolutionStepValue(DENSITY)+ GetGeometry()[1].FastGetSolutionStepValue(DENSITY) + GetGeometry()[2].FastGetSolutionStepValue(DENSITY)); //const double& density = GetProperties()[DENSITY]; double K = GetProperties()[BULK_MODULUS]; K *= density; double current_area = GeometryUtils::CalculateVolume2D(GetGeometry()); //add to pavg the increment of pressure inside the time step double dp_area = K * 0.3333333333333333333*(current_area - mA0); GetGeometry()[0].FastGetSolutionStepValue(PRESSURE) += dp_area; GetGeometry()[1].FastGetSolutionStepValue(PRESSURE) += dp_area; GetGeometry()[2].FastGetSolutionStepValue(PRESSURE) += dp_area; */ if(rVariable == PRESSURE) { KRATOS_WATCH("EMPTY FUNCTION FOR THIS ELEMENT - PRESSUREUES ARE UPDATED INSIDE BUILDER AND SOLVER"); } else if (rVariable == IS_FLUID) { GetGeometry()[0].FastGetSolutionStepValue(IS_FLUID) = 1.0 ; GetGeometry()[1].FastGetSolutionStepValue(IS_FLUID) = 1.0 ; GetGeometry()[2].FastGetSolutionStepValue(IS_FLUID) = 1.0 ; } } } // Namespace Kratos
40.511828
154
0.635099
[ "geometry", "vector" ]
a02526c64d786b8ca2543ffe523bf2e7d5b8b3df
4,793
cpp
C++
src/cpp/tests/generateXDMFData/test_generateXDMFData.cpp
lanl/tardigrade-overlap-coupling
a79c8c31b89bc1448ce4a3d438c3f3771f860042
[ "BSD-3-Clause" ]
null
null
null
src/cpp/tests/generateXDMFData/test_generateXDMFData.cpp
lanl/tardigrade-overlap-coupling
a79c8c31b89bc1448ce4a3d438c3f3771f860042
[ "BSD-3-Clause" ]
null
null
null
src/cpp/tests/generateXDMFData/test_generateXDMFData.cpp
lanl/tardigrade-overlap-coupling
a79c8c31b89bc1448ce4a3d438c3f3771f860042
[ "BSD-3-Clause" ]
null
null
null
//!The test file for dataFileInterface.cpp #include<iostream> #include<vector> #include<fstream> #include<math.h> #define USE_EIGEN #include<vector_tools.h> #include<generateXDMFData.h> typedef dataFileInterface::errorNode errorNode; //!Redefinition for the error node typedef dataFileInterface::errorOut errorOut; //!Redefinition for a pointer to the error node typedef dataFileInterface::floatType floatType; //!Define the float values type. typedef dataFileInterface::floatVector floatVector; //! Define a vector of floats typedef dataFileInterface::floatMatrix floatMatrix; //!Define a matrix of floats typedef dataFileInterface::uIntType uIntType; //!Define the unsigned int type typedef dataFileInterface::uIntVector uIntVector; //!Define a vector of unsigned ints typedef dataFileInterface::stringVector stringVector; //!Define a vector of strings bool compareFiles( const std::string &fn1, const std::string &fn2 ){ /*! * Compare two files to determine if they are exactly the same * * :param const std::string &fn1: The first filename * :param const std::string &fn2: The second filename */ std::ifstream f1, f2; f1.open( fn1 ); f2.open( fn2 ); //Check if the files can be opened if ( ( !f1.good( ) ) || ( !f2.good( ) ) ){ return false; } //Check if the files are the same size if ( f1.tellg( ) != f2.tellg( ) ){ return false; } //Rewind the files f1.seekg( 0 ); f2.seekg( 0 ); //Compare the lines std::istreambuf_iterator<char> begin1(f1); std::istreambuf_iterator<char> begin2(f2); return std::equal(begin1,std::istreambuf_iterator<char>(),begin2); //Second argument is end-of-range iterator } int test_fileGenerator_constructor( std::ofstream &results ){ /*! * Test the generateXDMFData constructor * * :param std::ofstream &results: The output file */ remove( "xdmf_out.xdmf" ); //Make sure the default constructor runs fileGenerator::fileGenerator fG; if ( fG.getError( ) ){ fG.getError( )->print( ); results << "test_fileGenerator_constructor (test 1) & False\n"; return 1; } fG = fileGenerator::fileGenerator( "bad_file" ); if ( !fG.getError( ) ){ results << "test_fileGenerator_constructor (test 2) & False\n"; return 1; } fG = fileGenerator::fileGenerator( "testYAML.yaml" ); if ( fG.getError( ) ){ fG.getError( )->print( ); results << "test_fileGenerator_constructor (test 3) & False\n"; return 1; } std::ifstream output_file; output_file.open( "xdmf_out.xdmf" ); if ( !output_file.good( ) ){ results << "test_fileGenerator_constructor (test 4) & False\n"; return 1; } remove( "xdmf_out.xdmf" ); results << "test_fileGenerator_constructor & True\n"; return 0; } int test_fileGenerator_build( std::ofstream &results ){ /*! * Test the function which builds the XDMF file * * :param std::ofstream &results: The output file */ remove( "xdmf_out.xdmf" ); remove( "xdmf_out.h5" ); fileGenerator::fileGenerator fG( "testYAML.yaml" ); if ( fG.getError( ) ){ fG.getError( )->print( ); results << "test_fileGenerator_build & False\n"; return 1; } if ( fG.build( ) ){ fG.getError( )->print( ); results << "test_fileGenerator_build & False\n"; return 1; } if ( *fG.getCurrentIncrement( ) != 1 ){ results << "test_fileGenerator_build (test 1) & False\n"; return 1; } if ( !compareFiles( "xdmf_out.xdmf", "xdmf_answer.xdmf" ) ){ results << "test_fileGenerator_build (test 2) & False\n"; return 1; } remove( "xdmf_out.xdmf" ); remove( "xdmf_out.h5" ); //Tests for errors fG = fileGenerator::fileGenerator( "badYAML.yaml" ); if ( fG.getError( ) ){ fG.getError( )->print( ); results << "test_fileGenerator_build & False\n"; return 1; } if ( !fG.build( ) ){ results << "test_fileGenerator_build (test 3) & False\n"; return 1; } remove( "xdmf_out.xdmf" ); remove( "xdmf_out.h5" ); results << "test_fileGenerator_build & True\n"; return 0; } int main(){ /*! The main loop which runs the tests defined in the accompanying functions. Each function should output the function name followed by & followed by True or False if the test passes or fails respectively. */ //Open the results file std::ofstream results; results.open("results.tex"); test_fileGenerator_constructor( results ); test_fileGenerator_build( results ); //Close the results file results.close(); }
24.706186
113
0.630711
[ "vector" ]
a02b7ae7d6aa6e9adb261d74da1e143098afd1d5
2,880
cc
C++
Validation/RecoTau/plugins/MuonFromPVSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Validation/RecoTau/plugins/MuonFromPVSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Validation/RecoTau/plugins/MuonFromPVSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" #include "CommonTools/Utils/interface/StringCutObjectSelector.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include <memory> #include <numeric> #include <vector> //////////////////////////////////////////////////////////////////////////////// // class definition //////////////////////////////////////////////////////////////////////////////// class MuonFromPVSelector : public edm::global::EDProducer<> { public: explicit MuonFromPVSelector(edm::ParameterSet const&); void produce(edm::StreamID, edm::Event&, edm::EventSetup const&) const override; private: double max_dxy_; double max_dz_; edm::EDGetTokenT<std::vector<reco::Vertex>> v_recoVertexToken_; edm::EDGetTokenT<std::vector<reco::Muon>> v_recoMuonToken_; }; //////////////////////////////////////////////////////////////////////////////// // construction //////////////////////////////////////////////////////////////////////////////// MuonFromPVSelector::MuonFromPVSelector(edm::ParameterSet const& iConfig) : max_dxy_{iConfig.getParameter<double>("max_dxy")} , max_dz_{iConfig.getParameter<double>("max_dz")} , v_recoVertexToken_{consumes<std::vector<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("srcVertex"))} , v_recoMuonToken_{consumes<std::vector<reco::Muon>>(iConfig.getParameter<edm::InputTag>("srcMuon"))} { produces<std::vector<reco::Muon>>(); } //////////////////////////////////////////////////////////////////////////////// // implementation of member functions //////////////////////////////////////////////////////////////////////////////// void MuonFromPVSelector::produce(edm::StreamID, edm::Event& iEvent, edm::EventSetup const&) const { auto goodMuons = std::make_unique<std::vector<reco::Muon>>(); edm::Handle<std::vector<reco::Vertex>> vertices; iEvent.getByToken(v_recoVertexToken_, vertices); edm::Handle<std::vector<reco::Muon>> muons; iEvent.getByToken(v_recoMuonToken_, muons); if (!vertices->empty()) { auto const& pv = vertices->front(); std::copy_if(std::cbegin(*muons), std::cend(*muons), std::back_inserter(*goodMuons), [&pv, this](auto const& muon){ return muon.innerTrack().isNonnull() && std::abs(muon.innerTrack()->dxy(pv.position())) < max_dxy_ && std::abs(muon.innerTrack()->dz(pv.position())) < max_dz_; }); } iEvent.put(std::move(goodMuons)); } DEFINE_FWK_MODULE(MuonFromPVSelector);
36.455696
109
0.596875
[ "vector" ]
a02d555d0cbf7904fafb10827a33cb0305d07a72
14,807
hpp
C++
dxmod/type.hpp
ar-visions/ion-modules
d7eafdb5b027f59433e9897dba8903952944407e
[ "MIT" ]
2
2021-12-07T04:49:16.000Z
2022-01-02T21:55:42.000Z
dxmod/type.hpp
ar-visions/ion-modules
d7eafdb5b027f59433e9897dba8903952944407e
[ "MIT" ]
null
null
null
dxmod/type.hpp
ar-visions/ion-modules
d7eafdb5b027f59433e9897dba8903952944407e
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <cstddef> #include <atomic> #include <string> #include <dx/io.hpp> #include <dx/array.hpp> #include <dx/map.hpp> /// bringing these along struct node; struct var; typedef std::function<bool()> FnBool; typedef std::function<void(void *)> FnArb; typedef std::function<void(void)> FnVoid; typedef std::function<void(var &)> Fn; typedef std::function<void(var &, node *)> FnNode; typedef std::function<var()> FnGet; typedef std::function<void(var &, string &)> FnEach; typedef std::function<void(var &, size_t)> FnArrayEach; /// struct Type { enum Specifier { Undefined, /// null state and arb uses i8, ui8, i16, ui16, i32, ui32, i64, ui64, f32, f64, Bool, /// high level types... Str, Map, Array, Ref, Arb, Node, Lambda, Member, Any, /// and the mighty meta Struct }; /// template <typename T> static constexpr Type::Specifier spec(T *v) { if constexpr (std::is_same_v<T, Fn>) return Type::Lambda; else if constexpr (std::is_same_v<T, bool>) return Type::Bool; else if constexpr (std::is_same_v<T, int8_t>) return Type::i8; else if constexpr (std::is_same_v<T, uint8_t>) return Type::ui8; else if constexpr (std::is_same_v<T, int16_t>) return Type::i16; else if constexpr (std::is_same_v<T, uint16_t>) return Type::ui16; else if constexpr (std::is_same_v<T, int32_t>) return Type::i32; else if constexpr (std::is_same_v<T, uint32_t>) return Type::ui32; else if constexpr (std::is_same_v<T, int64_t>) return Type::i64; else if constexpr (std::is_same_v<T, uint64_t>) return Type::ui64; else if constexpr (std::is_same_v<T, float>) return Type::f32; else if constexpr (std::is_same_v<T, double>) return Type::f64; else if constexpr (is_map<T>()) return Type::Map; return Type::Undefined; } template <typename T> static constexpr Type::Specifier spec() { if constexpr (std::is_same_v<T, Fn>) return Type::Lambda; else if constexpr (std::is_same_v<T, bool>) return Type::Bool; else if constexpr (std::is_same_v<T, int8_t>) return Type::i8; else if constexpr (std::is_same_v<T, uint8_t>) return Type::ui8; else if constexpr (std::is_same_v<T, int16_t>) return Type::i16; else if constexpr (std::is_same_v<T, uint16_t>) return Type::ui16; else if constexpr (std::is_same_v<T, int32_t>) return Type::i32; else if constexpr (std::is_same_v<T, uint32_t>) return Type::ui32; else if constexpr (std::is_same_v<T, int64_t>) return Type::i64; else if constexpr (std::is_same_v<T, uint64_t>) return Type::ui64; else if constexpr (std::is_same_v<T, float>) return Type::f32; else if constexpr (std::is_same_v<T, double>) return Type::f64; else if constexpr (is_map<T>()) return Type::Map; return Type::Undefined; } static size_t size(Type::Specifier t) { switch (t) { case Bool: return 1; case i8: return 1; case ui8: return 1; case i16: return 2; case ui16: return 2; case i32: return 4; case ui32: return 4; case i64: return 8; case ui64: return 8; case f32: return 4; case f64: return 8; default: break; } return 0; } /// needs a few assertions for runtime safety void lock() const { basics->mx.lock(); } void unlock() const { basics->mx.unlock(); } template <typename T> int compare(T *a, T *b) const { return basics->fn_compare(a, b); } template <typename T> int boolean(T *a) const { return basics->fn_boolean(a); } template <typename T> void free(T *ptr, size_t count) const { return basics->fn_free((void *)ptr, count); } template <typename T> T *alloc(size_t count) const { return (T *)basics->fn_alloc(count); } size_t sz() const { assert(!basics); /// this should be the null one for cases designed return size(Specifier(id)); } size_t id = 0; TypeBasics *basics = null; bool operator==(const Type &b) const { return id == b.id; } bool operator==(Type &b) const { return id == b.id; } bool operator==(Type::Specifier b) const { return id == size_t(b); } /// bool operator!=(const Type &b) const { return id != b.id; } bool operator!=(Type &b) const { return id != b.id; } bool operator!=(Type::Specifier b) const { return id != size_t(b); } /// bool operator>=(Type::Specifier b) const { return id >= size_t(b); } bool operator<=(Type::Specifier b) const { return id <= size_t(b); } bool operator> (Type::Specifier b) const { return id > size_t(b); } bool operator< (Type::Specifier b) const { return id < size_t(b); } /// inline operator size_t() const { return id; } inline operator int() const { return int(id); } inline operator bool() const { return id > 0; } /// template <typename T> T name() { return basics ? basics->code_name.c_str() : specifier_name(id); } /// could potentially use an extra flag for knowing origin Type(Specifier id, TypeBasics *basics = null) : id(size_t(id)), basics(basics) { } Type(size_t id, TypeBasics *basics = null) : id(id), basics(basics) { } Type() : basics(null) { } protected: const char *specifier_name(size_t id) { /// allow runtime augmentation of this when useful static std::unordered_map<size_t, const char *> map = { { Undefined, "Undefined" }, { i8, "i8" }, { ui8, "ui8" }, { i16, "i16" }, { ui16, "ui16" }, { i32, "i32" }, { ui32, "ui32" }, { i64, "i64" }, { ui64, "ui64" }, { f32, "f32" }, { f64, "f64" }, { Bool, "Bool" }, { Str, "Str" }, { Map, "Map" }, { Array, "Array" }, { Ref, "Ref" }, { Node, "Node" }, { Lambda, "Lambda" }, { Any, "Any" }, { Struct, "Struct" } }; assert(map.count(id)); return map[id]; } }; template <class T> struct Id:Type { Id() : Type(0) { basics = &(TypeBasics &)type_basics<T>(); id = std::hash<std::string>()(basics->code_name); Type::Specifier ts = Type::spec<T>(); if (ts >= i8 && ts <= Array) { id = ts; } } }; namespace std { template<> struct hash<Type> { size_t operator()(Type const& id) const { return id; } }; } /// definitely want this pattern for var struct Instances { std::unordered_map<Type, void *> allocs; inline size_t count(Type &id) { return allocs.count(id); } template <typename T> inline T *get(Type &id) { return (T *)allocs[id]; } template <typename T> inline void set(Type &id, T *ptr) { allocs[id] = ptr; } }; /// the smart pointer with baked in arrays and a bit of indirection. /// think about its integration with var.. i somehow missed the possibility yesterday. /// its ridiculous not to support vector here too. template <typename T> struct ptr { struct Alloc { Type type = 0; std::atomic<long> refs = 0; int ksize = 0; // ksize = known size, when we manage it ourselves, otherwise -1 when we are importing a pointer of unknown size alignas(16) void *mstart; // imported pointers are not aligned to this spec but our own pointers are. } *info; /// private: void alloc(T *&ptr) { size_t asz = sizeof(Alloc) + sizeof(T); info = (Alloc *)calloc(asz, 1); info->type = Id<T>(); info->refs = 2; /// and i thought i saw a two... info->ksize = sizeof(T); info->mstart = null; ptr = &info->mstart; } public: /// ptr() : info(null) { } /// ptr(const ptr<T> &ref) : info(ref.info) { if (info) info->refs++; } ptr(T *v) { size_t asz = sizeof(Alloc); info = (Alloc *)calloc(asz, 1); info->type = Id<T>(); info->refs = 1; info->ksize = -1; info->mstart = v; /// imported pointer [mode] } /// ptr<T> operator=(T *v) { assert(info == null); size_t asz = sizeof(Alloc); info = (Alloc *)calloc(asz, 1); info->type = Id<T>(); info->refs = 2; /// and i thought i saw a two... info->ksize = -1; info->mstart = v; /// imported pointer [mode] return *this; } /// /// todo: should be recycled based on patterns up to 4-8, 64 in each. its just a queue usage ~ptr() { if (info && --info->refs == 0) { if (info->ksize == -1) free(info->mstart); free(info); info = null; } } /// effective pointer to the data structure; /// for our own they are extensions on the Alloc struct and for imported ones we set the member T *effective() const { return (T *)(info ? (info->ksize > 0) ? &info->mstart : info->mstart : null); } /// T *operator &() { return effective(); } T *operator->() { return effective(); } inline operator T *() { return effective(); } inline operator T &() { return *effective(); } /// bounds check inline T &operator[](size_t index) { assert(info->ksize == -1 || index < info->ksize); return *ptr()[index]; } }; #include <dx/map.hpp> #include <dx/var.hpp> #include <dx/array.hpp> #include <dx/enum.hpp> #include <dx/string.hpp> #include <dx/rand.hpp> #define ex_shim(C,E,D) \ static Symbols symbols;\ C(E t = D):ex<C>(t) { }\ C(string s):ex<C>(D) { kind = resolve(s); } /// ex-bound enums shorthand for most things #define enums(C,E,D,ARGS...) \ struct C:ex<C> {\ static Symbols symbols;\ enum E { ARGS };\ C(E t = D):ex<C>(t) { }\ C(string s):ex<C>(D) { kind = resolve(s); }\ };\ #define io_shim(C,E) \ C(std::nullptr_t n) : C() { } \ C(const C &ref) { copy(ref); }\ C(var &d) { importer(d); }\ operator var() { return exporter(); }\ operator bool() const { return E; }\ bool operator!() const { return !(E); }\ C &operator=(const C &ref) {\ if (this != &ref)\ copy(ref);\ return *this;\ } void _print(str t, array<var> &a, bool error); /// /// best to do this kind of thing in logic that exists with the 'others' struct is_apple : #if defined(__APPLE__) std::true_type #else std::false_type #endif {}; /// struct is_android : #if defined(__ANDROID_API__) std::true_type #else std::false_type #endif {}; /// struct is_win : #if defined(_WIN32) || defined(_WIN64) std::true_type #else std::false_type #endif {}; /// struct is_gpu : std::true_type {}; /// struct is_debug : #if !defined(NDEBUG) std::true_type #else std::false_type #endif {}; template <typename T> static T input() { T v; std::cin >> v; return v; } enum LogType { Dissolvable, Always }; /// could have a kind of Enum for LogType and LogDissolve, if fancied. typedef std::function<void(str &)> FnPrint; template <const LogType L> struct Logger { FnPrint printer; Logger(FnPrint printer = null) : printer(printer) { } /// protected: void intern(str &t, array<var> &a, bool err) { t = var::format(t, a); if (printer != null) printer(t); else { auto &out = err ? std::cout : std::cerr; out << std::string(t) << std::endl << std::flush; } } public: /// print always prints inline void print(str t, array<var> a = {}) { intern(t, a, false); } /// log categorically as error; do not quit inline void error(str t, array<var> a = {}) { intern(t, a, true); } /// log when debugging or LogType:Always, or we are adapting our own logger inline void log(str t, array<var> a = {}) { if (L == Always || printer || is_debug()) intern(t, a, false); } /// assertion test with log out upon error inline void assertion(bool a0, str t, array<var> a = {}) { if (!a0) { intern(t, a, false); /// todo: ion:dx environment assert(a0); } } /// log error, and quit inline void fault(str t, array<var> a = {}) { _print(t, a, true); assert(false); exit(1); } /// prompt for any type of data template <typename T> inline T prompt(str t, array<var> a = {}) { _print(t, a, false); return input<T>(); } }; #if !defined(WIN32) && !defined(WIN64) #define UNIX /// its a unix system. i know this. #endif /// adding these declarations here. dont mind me. enum KeyState { KeyUp, KeyDown }; struct KeyStates { bool shift; bool ctrl; bool meta; }; struct KeyInput { int key; int scancode; int action; int mods; }; enum MouseButton { LeftButton, RightButton, MiddleButton }; /// needs to be ex, but no handlers written yet /* enum KeyCode { Key_D = 68, Key_N = 78, Backspace = 8, Tab = 9, LineFeed = 10, Return = 13, Shift = 16, Ctrl = 17, Alt = 18, Pause = 19, CapsLock = 20, Esc = 27, Space = 32, PageUp = 33, PageDown = 34, End = 35, Home = 36, Left = 37, Up = 38, Right = 39, Down = 40, Insert = 45, Delete = 46, // or 127 ? Meta = 91 }; */ extern Logger<LogType::Dissolvable> console;
30.783784
157
0.519011
[ "vector" ]
a03ad6ec3a1146105f7091e75292dc87b65973e4
788
cc
C++
jni/src/profiling/base.cc
AlexdeT/Profiler
9e3bcc736e5f4012806ed7953f28d0cf0c994783
[ "MIT" ]
3
2015-12-30T07:35:18.000Z
2018-11-16T11:56:26.000Z
jni/src/profiling/base.cc
AlexdeT/Profiler
9e3bcc736e5f4012806ed7953f28d0cf0c994783
[ "MIT" ]
1
2021-03-16T08:47:20.000Z
2021-03-16T08:47:20.000Z
jni/src/profiling/base.cc
adetalhouet/Profiler
9e3bcc736e5f4012806ed7953f28d0cf0c994783
[ "MIT" ]
null
null
null
/** * @file base.cc * @brief DataSet Class file */ #include "base.h" namespace ets { namespace genielog { namespace appwatcher_3 { namespace profiling { namespace core { void base::clearDataSet(std::vector<google::protobuf::Message*>& curDataSet) { // remove all data from vector and delete it carefully while (curDataSet.empty() != true) { google::protobuf::Message* curObject = curDataSet.back(); delete curObject; curObject = 0; curDataSet.pop_back(); } return; } void base::moveDataSet(std::vector<google::protobuf::Message*>& srcDataSet, std::vector<google::protobuf::Message*>& dstDataSet) { while (srcDataSet.empty() != true) { dstDataSet.push_back(srcDataSet.back()); srcDataSet.pop_back(); } return; } } } } } }
20.205128
79
0.664975
[ "vector" ]
a03d96ff5ab48951aa31d5cdfb9f53ca0056a80a
7,708
cc
C++
src/storage/blobfs/test/unit/blob-verifier-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
2
2020-08-16T15:32:35.000Z
2021-11-07T20:09:46.000Z
src/storage/blobfs/test/unit/blob-verifier-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
null
null
null
src/storage/blobfs/test/unit/blob-verifier-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
1
2021-08-15T04:29:11.000Z
2021-08-15T04:29:11.000Z
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blob-verifier.h" #include <random> #include <zxtest/zxtest.h> #include "utils.h" namespace blobfs { namespace { class BlobVerifierTest : public zxtest::Test { public: BlobfsMetrics* Metrics() { return &metrics_; } void SetUp() override { srand(zxtest::Runner::GetInstance()->random_seed()); } private: BlobfsMetrics metrics_; }; void GenerateTree(const uint8_t* data, size_t len, Digest* out_digest, fbl::Array<uint8_t>* out_tree) { digest::MerkleTreeCreator mtc; ASSERT_OK(mtc.SetDataLength(len)); size_t merkle_size = mtc.GetTreeLength(); fbl::Array<uint8_t> merkle_buf(new uint8_t[merkle_size], merkle_size); uint8_t root[digest::kSha256Length]; ASSERT_OK(mtc.SetTree(merkle_buf.get(), merkle_size, root, sizeof(root))); ASSERT_OK(mtc.Append(data, len)); *out_digest = Digest(root); *out_tree = std::move(merkle_buf); } void FillWithRandom(uint8_t* buf, size_t len) { for (unsigned i = 0; i < len; ++i) { buf[i] = (uint8_t)rand(); } } TEST_F(BlobVerifierTest, CreateAndVerify_NullBlob) { fbl::Array<uint8_t> unused_merkle_buf; Digest digest; GenerateTree(nullptr, 0, &digest, &unused_merkle_buf); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::CreateWithoutTree(std::move(digest), Metrics(), 0ul, nullptr, &verifier)); EXPECT_OK(verifier->Verify(nullptr, 0ul, 0ul)); EXPECT_OK(verifier->VerifyPartial(nullptr, 0ul, 0ul, 0ul)); } TEST_F(BlobVerifierTest, CreateAndVerify_SmallBlob) { uint8_t buf[8192]; FillWithRandom(buf, sizeof(buf)); fbl::Array<uint8_t> unused_merkle_buf; Digest digest; GenerateTree(buf, sizeof(buf), &digest, &unused_merkle_buf); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::CreateWithoutTree(std::move(digest), Metrics(), sizeof(buf), nullptr, &verifier)); EXPECT_OK(verifier->Verify(buf, sizeof(buf), sizeof(buf))); EXPECT_OK(verifier->VerifyPartial(buf, 8192, 0, 8192)); // Partial ranges EXPECT_EQ(verifier->VerifyPartial(buf, 8191, 0, 8191), ZX_ERR_INVALID_ARGS); // Verify past the end EXPECT_EQ(verifier->VerifyPartial(buf, 2 * 8192, 0, 2 * 8192), ZX_ERR_INVALID_ARGS); } TEST_F(BlobVerifierTest, CreateAndVerify_SmallBlob_DataCorrupted) { uint8_t buf[8192]; FillWithRandom(buf, sizeof(buf)); fbl::Array<uint8_t> unused_merkle_buf; Digest digest; GenerateTree(buf, sizeof(buf), &digest, &unused_merkle_buf); // Invert one character buf[42] = ~(buf[42]); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::CreateWithoutTree(std::move(digest), Metrics(), sizeof(buf), nullptr, &verifier)); EXPECT_EQ(verifier->Verify(buf, sizeof(buf), sizeof(buf)), ZX_ERR_IO_DATA_INTEGRITY); EXPECT_EQ(verifier->VerifyPartial(buf, 8192, 0, 8192), ZX_ERR_IO_DATA_INTEGRITY); } TEST_F(BlobVerifierTest, CreateAndVerify_BigBlob) { size_t sz = 1 << 16; fbl::Array<uint8_t> buf(new uint8_t[sz], sz); FillWithRandom(buf.get(), sz); fbl::Array<uint8_t> merkle_buf; Digest digest; GenerateTree(buf.get(), sz, &digest, &merkle_buf); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::Create(std::move(digest), Metrics(), merkle_buf.get(), merkle_buf.size(), sz, nullptr, &verifier)); EXPECT_OK(verifier->Verify(buf.get(), sz, sz)); EXPECT_OK(verifier->VerifyPartial(buf.get(), sz, 0, sz)); // Block-by-block for (size_t i = 0; i < sz; i += 8192) { EXPECT_OK(verifier->VerifyPartial(buf.get() + i, 8192, i, 8192)); } // Partial ranges EXPECT_EQ(verifier->VerifyPartial(buf.data(), 8191, 0, 8191), ZX_ERR_INVALID_ARGS); // Verify past the end EXPECT_EQ(verifier->VerifyPartial(buf.data() + (sz - 8192), 2 * 8192, sz - 8192, 2 * 8192), ZX_ERR_INVALID_ARGS); } TEST_F(BlobVerifierTest, CreateAndVerify_BigBlob_DataCorrupted) { size_t sz = 1 << 16; fbl::Array<uint8_t> buf(new uint8_t[sz], sz); FillWithRandom(buf.get(), sz); fbl::Array<uint8_t> merkle_buf; Digest digest; GenerateTree(buf.get(), sz, &digest, &merkle_buf); // Invert a char in the first block. All other blocks are still valid. buf.get()[42] = ~(buf.get()[42]); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::Create(std::move(digest), Metrics(), merkle_buf.get(), merkle_buf.size(), sz, nullptr, &verifier)); EXPECT_EQ(verifier->Verify(buf.get(), sz, sz), ZX_ERR_IO_DATA_INTEGRITY); EXPECT_EQ(verifier->VerifyPartial(buf.get(), sz, 0, sz), ZX_ERR_IO_DATA_INTEGRITY); // Block-by-block -- first block fails, rest succeed for (size_t i = 0; i < sz; i += 8192) { zx_status_t expected_status = i == 0 ? ZX_ERR_IO_DATA_INTEGRITY : ZX_OK; EXPECT_EQ(verifier->VerifyPartial(buf.get() + i, 8192, i, 8192), expected_status); } } TEST_F(BlobVerifierTest, CreateAndVerify_BigBlob_MerkleCorrupted) { size_t sz = 1 << 16; fbl::Array<uint8_t> buf(new uint8_t[sz], sz); FillWithRandom(buf.get(), sz); fbl::Array<uint8_t> merkle_buf; Digest digest; GenerateTree(buf.get(), sz, &digest, &merkle_buf); // Invert a char in the tree. merkle_buf.get()[0] = ~(merkle_buf.get()[0]); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::Create(std::move(digest), Metrics(), merkle_buf.get(), merkle_buf.size(), sz, nullptr, &verifier)); EXPECT_EQ(verifier->Verify(buf.get(), sz, sz), ZX_ERR_IO_DATA_INTEGRITY); EXPECT_EQ(verifier->VerifyPartial(buf.get(), sz, 0, sz), ZX_ERR_IO_DATA_INTEGRITY); // Block-by-block -- everything fails for (size_t i = 0; i < sz; i += 8192) { EXPECT_EQ(verifier->VerifyPartial(buf.get() + i, 8192, i, 8192), ZX_ERR_IO_DATA_INTEGRITY); } } TEST_F(BlobVerifierTest, NonZeroTailCausesVerifyToFail) { constexpr int kBlobSize = 8000; uint8_t buf[kBlobfsBlockSize]; FillWithRandom(buf, kBlobSize); // Zero the tail. memset(&buf[kBlobSize], 0, kBlobfsBlockSize - kBlobSize); fbl::Array<uint8_t> unused_merkle_buf; Digest digest; GenerateTree(buf, kBlobSize, &digest, &unused_merkle_buf); std::unique_ptr<BlobVerifier> verifier; EXPECT_OK( BlobVerifier::CreateWithoutTree(std::move(digest), Metrics(), kBlobSize, nullptr, &verifier)); EXPECT_OK(verifier->Verify(buf, kBlobSize, sizeof(buf))); buf[kBlobSize] = 1; EXPECT_STATUS(verifier->Verify(buf, kBlobSize, sizeof(buf)), ZX_ERR_IO_DATA_INTEGRITY); } TEST_F(BlobVerifierTest, NonZeroTailCausesVerifyPartialToFail) { constexpr unsigned kBlobSize = (1 << 16) - 100; std::vector<uint8_t> buf(fbl::round_up(kBlobSize, kBlobfsBlockSize)); FillWithRandom(buf.data(), kBlobSize); fbl::Array<uint8_t> merkle_buf; Digest digest; GenerateTree(buf.data(), kBlobSize, &digest, &merkle_buf); std::unique_ptr<BlobVerifier> verifier; ASSERT_OK(BlobVerifier::Create(std::move(digest), Metrics(), merkle_buf.get(), merkle_buf.size(), kBlobSize, nullptr, &verifier)); constexpr int kVerifyOffset = kBlobSize - kBlobSize % kBlobfsBlockSize; EXPECT_OK(verifier->VerifyPartial(&buf[kVerifyOffset], kBlobSize - kVerifyOffset, kVerifyOffset, buf.size() - kVerifyOffset)); buf[kBlobSize] = 1; EXPECT_STATUS(verifier->VerifyPartial(&buf[kVerifyOffset], kBlobSize - kVerifyOffset, kVerifyOffset, buf.size() - kVerifyOffset), ZX_ERR_IO_DATA_INTEGRITY); } } // namespace } // namespace blobfs
33.955947
100
0.688635
[ "vector" ]
a044fb65a195471ce7db35647e66edf922c22aa8
8,003
cpp
C++
src/csapex_core/src/param/parameter.cpp
betwo/csapex
f2c896002cf6bd4eb7fba2903ebeea4a1e811191
[ "BSD-3-Clause" ]
21
2016-09-02T15:33:25.000Z
2021-06-10T06:34:39.000Z
src/csapex_core/src/param/parameter.cpp
cogsys-tuebingen/csAPEX
e80051384e08d81497d7605e988cab8c19f6280f
[ "BSD-3-Clause" ]
null
null
null
src/csapex_core/src/param/parameter.cpp
cogsys-tuebingen/csAPEX
e80051384e08d81497d7605e988cab8c19f6280f
[ "BSD-3-Clause" ]
10
2016-10-12T00:55:17.000Z
2020-04-24T19:59:02.000Z
/// HEADER #include <csapex/param/parameter.h> /// PROJECT #include <csapex/param/io.h> #include <csapex/param/value_parameter.h> #include <csapex/serialization/io/std_io.h> #include <csapex/serialization/io/csapex_io.h> #include <csapex/utility/yaml.h> #include <csapex/utility/any.h> /// SYSTEM #ifdef WIN32 #else #include <cxxabi.h> #endif #include <iostream> using namespace csapex; using namespace param; Parameter::Parameter(const std::string& name, const ParameterDescription& description) : name_(name), description_(description), enabled_(true), temporary_(false), hidden_(false), interactive_(false) { } Parameter::Parameter(const Parameter& other) : name_(other.name_) , uuid_(other.uuid_) , description_(other.description_) , enabled_(other.enabled_) , temporary_(other.temporary_) , hidden_(other.hidden_) , interactive_(other.interactive_) , dict_(other.dict_) { } Parameter::~Parameter() { destroyed(this); } Parameter& Parameter::operator=(const Parameter& other) { name_ = other.name_; interactive_ = other.interactive_; enabled_ = other.enabled_; dict_ = other.dict_; description_ = other.description_; // cloneDataFrom(other); return *this; } uint8_t Parameter::getPacketType() const { return PACKET_TYPE_ID; } void Parameter::serialize(SerializationBuffer& data, SemanticVersion& version) const { data << name_; data << uuid_; data << description_.toString(); data << enabled_; data << temporary_; data << hidden_; data << interactive_; data << dict_; } void Parameter::deserialize(const SerializationBuffer& data, const SemanticVersion& version) { data >> name_; data >> uuid_; std::string description; data >> description; description_ = ParameterDescription(description); data >> enabled_; data >> temporary_; data >> hidden_; data >> interactive_; data >> dict_; } void Parameter::setUUID(const UUID& uuid) { if (uuid.global()) { apex_assert_hard(!uuid.globalName().empty()); } uuid_ = uuid; } UUID Parameter::getUUID() const { if (uuid_.global()) { apex_assert_hard(!uuid_.globalName().empty()); } return uuid_; } void Parameter::setEnabled(bool enabled) { if (enabled != enabled_) { enabled_ = enabled; parameter_enabled(this, enabled); } } bool Parameter::isEnabled() const { return enabled_; } void Parameter::setInteractive(bool interactive) { if (interactive != interactive_) { interactive_ = interactive; std::cout << "Param " << name_ << ": interactive = " << interactive_ << std::endl; interactive_changed(this, interactive_); } } bool Parameter::isInteractive() const { return interactive_; } void Parameter::setHidden(bool hidden) { hidden_ = hidden; } bool Parameter::isHidden() const { return hidden_; } void Parameter::setTemporary(bool temporary) { temporary_ = temporary; } bool Parameter::isTemporary() const { return temporary_; } bool Parameter::hasState() const { return true; } Parameter::Lock Parameter::lock() const { return Lock(new std::unique_lock<std::recursive_mutex>(mutex_)); } void Parameter::triggerChange() { parameter_changed(this); } void Parameter::setName(const std::string& name) { name_ = name; } std::string Parameter::name() const { return name_; } const std::type_info& Parameter::type() const { return typeid(void); } std::string Parameter::toString() const { return std::string("[") + name() + ": " + toStringImpl() + "]"; } const ParameterDescription& Parameter::description() const { return description_; } void Parameter::setDescription(const ParameterDescription& desc) { description_ = desc; } std::string Parameter::toStringImpl() const { throw std::logic_error("not implemented"); } void Parameter::serialize_yaml(YAML::Node& n) const { n["type"] = getParameterType(); n["name"] = name(); if (interactive_) { n["interactive"] = interactive_; } if (!dict_.empty()) { n["dict"] = dict_; } try { doSerialize(n); } catch (const std::exception& e) { std::cerr << "cannot serialize parameter " << name() << ": " << e.what() << std::endl; throw e; } } void Parameter::deserialize_yaml(const YAML::Node& n) { if (!n["name"].IsDefined()) { return; } name_ = n["name"].as<std::string>(); if (n["interactive"].IsDefined()) { interactive_ = n["interactive"].as<bool>(); std::cout << "Param " << name_ << " is interactive" << std::endl; } if (n["dict"].IsDefined()) { dict_ = n["dict"].as<std::map<std::string, param::ParameterPtr>>(); } try { doDeserialize(n); } catch (const std::exception& e) { std::cerr << "cannot deserialize parameter " << name() << ": " << e.what() << std::endl; throw e; } } void Parameter::access_unsafe(const Parameter& p, std::any& out) const { p.get_unsafe(out); } std::string Parameter::type2string(const std::type_info& type) { #ifdef WIN32 return type.name(); #else int status; return abi::__cxa_demangle(type.name(), 0, 0, &status); #endif } void Parameter::throwTypeError(const std::type_info& a, const std::type_info& b, const std::string& prefix) const { throw std::runtime_error(prefix + std::string("'") + name() + "' is not of type '" + type2string(a) + "' but '" + type2string(b) + "'"); } bool Parameter::accepts(const std::type_info& t) const { return type() == t; } void Parameter::setDictionaryEntry(const std::string& key, const param::ParameterPtr& p) { dict_[key] = p; dictionary_entry_changed(key); } param::ParameterPtr Parameter::getDictionaryEntry(const std::string& key) const { return dict_.at(key); } namespace csapex { namespace param { template <typename T> void Parameter::setDictionaryValue(const std::string& key, const T& value) { param::ValueParameterPtr p = std::make_shared<param::ValueParameter>(); p->set(value); setDictionaryEntry(key, p); } /// EXPLICIT INSTANTIATON namespace { template <typename T> struct argument_type; template <typename T, typename U> struct argument_type<T(U)> { typedef U type; }; } // namespace #define INSTANTIATE_AS(T) template CSAPEX_PARAM_EXPORT argument_type<void(T)>::type Parameter::as_impl<argument_type<void(T)>::type>() const; #define INSTANTIATE_SILENT(T) template CSAPEX_PARAM_EXPORT bool Parameter::setSilent<argument_type<void(T)>::type>(const argument_type<void(T)>::type& value); #define INSTANTIATE(T) \ INSTANTIATE_AS(T) \ INSTANTIATE_SILENT(T) INSTANTIATE(bool) INSTANTIATE(int) INSTANTIATE(long) INSTANTIATE(double) INSTANTIATE(std::string) INSTANTIATE((std::pair<int, int>)) INSTANTIATE((std::pair<double, double>)) INSTANTIATE((std::pair<std::string, bool>)) INSTANTIATE((std::vector<int>)) INSTANTIATE((std::vector<double>)) INSTANTIATE((std::vector<std::string>)) template CSAPEX_PARAM_EXPORT void Parameter::setDictionaryValue<bool>(const std::string& key, const bool& value); template CSAPEX_PARAM_EXPORT void Parameter::setDictionaryValue<int>(const std::string& key, const int& value); template CSAPEX_PARAM_EXPORT void Parameter::setDictionaryValue<long>(const std::string& key, const long& value); template CSAPEX_PARAM_EXPORT void Parameter::setDictionaryValue<double>(const std::string& key, const double& value); template CSAPEX_PARAM_EXPORT void Parameter::setDictionaryValue<std::string>(const std::string& key, const std::string& value); } // namespace param } // namespace csapex
23.889552
200
0.646383
[ "vector" ]
a0458bc0c6b2dfde2605b0bd06f07b789321291e
1,730
cpp
C++
leetcode/problems/medium/1962-remove-stones-to-minimize-the-total.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/1962-remove-stones-to-minimize-the-total.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/1962-remove-stones-to-minimize-the-total.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Remove Stones to Minimize the Total https://leetcode.com/problems/remove-stones-to-minimize-the-total/ You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations. floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). Example 1: Input: piles = [5,4,9], k = 2 Output: 12 Explanation: Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are [5,4,5]. - Apply the operation on pile 0. The resulting piles are [3,4,5]. The total number of stones in [3,4,5] is 12. Example 2: Input: piles = [4,3,6,7], k = 3 Output: 12 Explanation: Steps of a possible scenario are: - Apply the operation on pile 3. The resulting piles are [4,3,3,7]. - Apply the operation on pile 4. The resulting piles are [4,3,3,4]. - Apply the operation on pile 0. The resulting piles are [2,3,3,4]. The total number of stones in [2,3,3,4] is 12. Constraints: 1 <= piles.length <= 105 1 <= piles[i] <= 104 1 <= k <= 105 */ class Solution { public: int minStoneSum(vector<int>& piles, int k) { priority_queue<int> pq; for(int x : piles) pq.push(x); for(int i = 0; i < k; i++) { int x = pq.top(); pq.pop(); pq.push((x + 1) / 2); } int ans = 0; while(!pq.empty()) { ans += pq.top(); pq.pop(); } return ans; } };
30.350877
186
0.652023
[ "vector" ]
a046ea3829f10774fa4e8ee0cbae95671e257fcb
3,308
cc
C++
src/main/c++/util/options.cc
gkohri/stochastico
e40ca1731f3dfe8782d8e5fa008790c8b80a1681
[ "Apache-2.0" ]
null
null
null
src/main/c++/util/options.cc
gkohri/stochastico
e40ca1731f3dfe8782d8e5fa008790c8b80a1681
[ "Apache-2.0" ]
null
null
null
src/main/c++/util/options.cc
gkohri/stochastico
e40ca1731f3dfe8782d8e5fa008790c8b80a1681
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2011 The Stochastico Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "util/options.h" //========================================================================== // The Options class implementation. //========================================================================== #include <string> #include <cstdlib> #include <vector> #include <stdio.h> #include "util/functions.h" namespace util { using std::exit; using std::string; using std::vector; //========================================================================== // Friend Functions //========================================================================== void get_command_line_options( int argc, char **argv, vector<Option*> &table) { unsigned op = 0; unsigned this_op = 0; int found= 0; int c = 0; for (int arg = 1; arg < argc; arg++ ){ found = 0; for ( op = 0 ; op < table.size(); op++) { c = 0; while ( table[op]->name[c] == argv[arg][c] ) { if (argv[arg][++c] == '\0') { found++; this_op = op; break; } } } if( found > 1 ) { fprintf(stderr,"\n\t%s%s\n","Ambiguous argument: ", argv[arg]); usage( argv[0], table ); } else if (found == 1) { if ( table[this_op]->value_required){ if ( arg+1 == argc ) { fprintf(stderr,"\n\t%s%s\n","Argument required! ", argv[arg]); usage( argv[0], table ); } table[this_op]->value = argv[arg+1]; arg++ ; } else { table[this_op]->value = table[this_op]->default_value; } } else { fprintf(stderr,"\n\t%s%s\n","Invalid argument: ", argv[arg]); usage( argv[0], table ); } } }; /* // usage of a general program // */ void usage( char *program, vector<Option*> &options ) { fprintf(stderr,"\n\t%s%s%s\n","Usage: ", program," [option [value] ]"); fprintf(stderr,"\n\n\t%s\n\n","where 'option' is one of:"); for ( unsigned op = 0 ; op < options.size(); op++ ) { if ( options[op]->value_required ){ fprintf(stderr,"\t\t%s\t\t%s\n", options[op]->name.c_str(), " Argument"); } else { fprintf(stderr,"\t\t%s\t\t%s\n", options[op]->name.c_str(), " No Argument"); } } fprintf(stderr,"\n\t%s\n", "Option names may be abreviated provided the abreviation is unique "); exit( EXIT_FAILURE ); }; } // namespace util
27.566667
101
0.46584
[ "vector" ]
a04b4ddb8ccf179d8ecbeb02888fa72d71787d93
642
hpp
C++
libuavcan_drivers/linux/include/uavcan_linux/exception.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
libuavcan_drivers/linux/include/uavcan_linux/exception.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
libuavcan_drivers/linux/include/uavcan_linux/exception.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #pragma once #include <cerrno> #include <stdexcept> namespace uavcan_linux { /** * This is the root exception class for all exceptions that can be thrown from the libuavcan Linux driver. */ class Exception : public std::runtime_error { const int errno_; public: explicit Exception(const std::string& descr) : std::runtime_error(descr) , errno_(errno) { } /** * Returns standard UNIX errno value captured at the moment * when this exception object was constructed. */ int getErrno() const { return errno_; } }; }
19.454545
106
0.669782
[ "object" ]
a05159d32ae7ab5e97867733d1367f2a0cce7c37
5,170
cpp
C++
projects/multiSeg/convertPixelLabels.cpp
exoad/drwn
3cc9faaa99602cb7ab69af795ec6e4194ff1919f
[ "BSD-3-Clause" ]
40
2015-01-26T21:58:25.000Z
2021-11-03T13:52:40.000Z
projects/multiSeg/convertPixelLabels.cpp
exoad/drwn
3cc9faaa99602cb7ab69af795ec6e4194ff1919f
[ "BSD-3-Clause" ]
7
2015-04-08T23:44:17.000Z
2016-05-09T11:29:38.000Z
projects/multiSeg/convertPixelLabels.cpp
exoad/drwn
3cc9faaa99602cb7ab69af795ec6e4194ff1919f
[ "BSD-3-Clause" ]
32
2015-01-12T01:47:58.000Z
2022-01-12T10:08:59.000Z
/***************************************************************************** ** DARWIN: A FRAMEWORK FOR MACHINE LEARNING RESEARCH AND DEVELOPMENT ** Distributed under the terms of the BSD license (see the LICENSE file) ** Copyright (c) 2007-2017, Stephen Gould ** All rights reserved. ** ****************************************************************************** ** FILENAME: convertPixelLabels.cpp ** AUTHOR(S): Stephen Gould <stephen.gould@anu.edu.au> ** DESCRIPTION: ** Application for converting (colour) annotated images to label files. ** *****************************************************************************/ // c++ standard headers #include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <iomanip> // opencv library headers #include "cv.h" #include "highgui.h" // darwin library headers #include "drwnBase.h" #include "drwnIO.h" #include "drwnML.h" #include "drwnVision.h" #define WINDOW_NAME "convertPixelLabels" using namespace std; // usage --------------------------------------------------------------------- void usage() { cerr << DRWN_USAGE_HEADER << endl; cerr << "USAGE: ./convertPixelLabels [OPTIONS] (<imageList>|<baseName>)\n"; cerr << "OPTIONS:\n" << " -i <ext> :: extension for image input (default: .bmp)\n" << " -o <ext> :: extension for label output (default: .txt)\n" << " -x :: visualize\n" << DRWN_STANDARD_OPTIONS_USAGE << endl; } // main ---------------------------------------------------------------------- int main(int argc, char *argv[]) { const char *inExt = ".bmp"; const char *outExt = ".txt"; bool bVisualize = false; // process commandline arguments DRWN_BEGIN_CMDLINE_PROCESSING(argc, argv) DRWN_CMDLINE_STR_OPTION("-i", inExt) DRWN_CMDLINE_STR_OPTION("-o", outExt) DRWN_CMDLINE_BOOL_OPTION("-x", bVisualize) DRWN_END_CMDLINE_PROCESSING(usage()); if (DRWN_CMDLINE_ARGC != 1) { usage(); return -1; } drwnCodeProfiler::tic(drwnCodeProfiler::getHandle("main")); // read list of evaluation images const char *imageList = DRWN_CMDLINE_ARGV[0]; vector<string> baseNames; if (drwnFileExists(imageList)) { DRWN_LOG_MESSAGE("Reading image list from " << imageList << "..."); baseNames = drwnReadFile(imageList); DRWN_LOG_MESSAGE("...read " << baseNames.size() << " images"); } else { DRWN_LOG_MESSAGE("Processing single image " << imageList << "..."); baseNames.push_back(string(imageList)); } // check for input directory if (!drwnDirExists(gMultiSegConfig.filebase("lblDir", "").c_str())) { DRWN_LOG_FATAL("input/output labels directory " << gMultiSegConfig.filebase("lblDir", "") << " does not exist"); } // construct colour-to-key table map<unsigned int, int> table; set<int> keys(gMultiSegRegionDefs.keys()); for (set<int>::const_iterator ik = keys.begin(); ik != keys.end(); ++ik) { table[gMultiSegRegionDefs.color(*ik)] = *ik; } for (map<unsigned int, int>::const_iterator it = table.begin(); it != table.end(); ++it) { DRWN_LOG_DEBUG("colour (" << (int)gMultiSegRegionDefs.red(it->first) << ", " << (int)gMultiSegRegionDefs.green(it->first) << ", " << (int)gMultiSegRegionDefs.blue(it->first) << ") corresponds to label " << it->second); } // iterate over images for (int i = 0; i < (int)baseNames.size(); i++) { // load annotated images const string inFilename = gMultiSegConfig.filebase("lblDir", baseNames[i]) + string(inExt); cv::Mat img = cv::imread(inFilename, CV_LOAD_IMAGE_COLOR); DRWN_ASSERT_MSG(img.data != NULL, "could not load image " << inFilename); // show image if (bVisualize) { cv::namedWindow(WINDOW_NAME); cv::imshow(WINDOW_NAME, img); cv::waitKey(100); } // write label file const string outFilename = gMultiSegConfig.filebase("lblDir", baseNames[i]) + string(outExt); ofstream ofs(outFilename.c_str()); for (int y = 0; y < img.rows; y++) { for (int x = 0; x < img.cols; x++) { if (x != 0) ofs << " "; unsigned char red = img.at<unsigned char>(y, 3 * x + 2); unsigned char green = img.at<unsigned char>(y, 3 * x + 1); unsigned char blue = img.at<unsigned char>(y, 3 * x + 0); unsigned int c = (red << 16) | (green << 8) | blue; map<unsigned int, int>::const_iterator it = table.find(c); ofs << ((it == table.end()) ? -1 : it->second); } ofs << "\n"; } ofs.close(); } // wait for keypress if only image if (bVisualize && (baseNames.size() == 1)) { cv::waitKey(-1); } // clean up and print profile information cv::destroyAllWindows(); drwnCodeProfiler::toc(drwnCodeProfiler::getHandle("main")); drwnCodeProfiler::print(); return 0; }
33.141026
97
0.545068
[ "vector" ]
a0572e22d491abeb24c3c13d7e76893b98f42c5e
6,972
cpp
C++
code/Kreyvium/main.cpp
hukaisdu/massive_superpoly_recovery
6dd3a22a4dbae8d0caffa4d5f3c04a35cb5d2923
[ "MIT" ]
6
2021-09-22T12:43:30.000Z
2022-01-25T11:54:27.000Z
code/Kreyvium/main.cpp
hukaisdu/massive_superpoly_recovery
6dd3a22a4dbae8d0caffa4d5f3c04a35cb5d2923
[ "MIT" ]
null
null
null
code/Kreyvium/main.cpp
hukaisdu/massive_superpoly_recovery
6dd3a22a4dbae8d0caffa4d5f3c04a35cb5d2923
[ "MIT" ]
null
null
null
#include<iostream> #include<fstream> #include<vector> #include<bitset> #include<algorithm> #include<thread> #include<mutex> #include<future> #include"log.h" #include"deg.h" #include"thread_pool.h" #include"kreyvium.h" using namespace std; using namespace thread_pool; mutex stream_mutex; mutex map_mutex; mutex term_mutex; int THREAD_NUM = 64; void filterMap( map<bitset<544>, int, CMPS<544>> & mp ) { int size0 = mp.size(); map< bitset<544>, int, CMPS<544>> tmp( mp ); mp.clear(); for ( auto it : tmp ) { if ( it.second % 2 == 1 ) mp[it.first] = it.second; } int size1 = mp.size(); logger( __func__ + string(": ") + to_string( size0 ) + string( "\t" ) + to_string( size1 ) ); } void printSol( int rounds, const bitset<544> & vector, const map<bitset<128>, int, CMPS<128>> & solutions ) { logger( __func__ + string(": " ) + to_string( rounds ) + string("\t") + vector.to_string() ); string path = string ( "TERM/" ) + to_string( rounds ) + string ( ".txt" ); ofstream os; os.open( path, ios::out | ios::app ); os << rounds << "\t" << vector << endl; for ( auto it : solutions ) os << it.first << "\t" << it.second << "\n"; os << endl; os.close(); } void SolutionSearcherWorker( const bitset<544> & vec, int ROUND, const bitset<128> & cube, vector< bitset<544> > & layerTerms, float time, int singlethread ) { map<bitset<128>, int, CMPS<128>> solutions; auto status = MidSolutionCounter( ROUND, cube, vec, solutions, time, singlethread ); if ( status == EXPAND ) { lock_guard<mutex> guard( map_mutex ); layerTerms.push_back( vec ); } else if ( status == SOLUTION ) { lock_guard<mutex> guard( stream_mutex ); printSol( ROUND, vec, solutions ); } } void ExpandWorker( const vector<bitset<544>> & layerTerm, const bitset<128> & cube, int start, int end, int step, map<bitset<544>, int, CMPS<544>> & layerMap, int singlethread ) { //map<bitset<80>, int, CMPS<80>> solutions; map<bitset<544>, int, CMPS<544>> threadLayerMap; int END = end <= layerTerm.size() ? end : layerTerm.size(); vector<bitset<544>> terms; for ( int i = start; i < END; i++ ) { //MidSolutionCounter( ROUND, cube, layerMap[i], // solutions, time, singlethread ); terms.clear(); SecondBackExpandPolynomial( step, layerTerm[i], terms, singlethread ); //filterTerms( cube, ROUND, terms ); for ( auto it : terms ) threadLayerMap[it] += 1; } lock_guard<mutex> guard( term_mutex ); for ( auto & it : threadLayerMap ) layerMap[it.first] += it.second; } void filterTerms( const bitset<128> & cube, int rounds, vector<bitset<544>> & terms ) { int size0 = terms.size(); vector<bitset<544>> tmp( terms.begin(), terms.end() ); terms.clear(); for ( auto it : tmp ) { auto d = computeDegree( cube, rounds, it ); if ( d >= cube.count() ) terms.push_back( it ); } int size1 = terms.size(); logger( __func__ + string(": ") + to_string( size0 ) + string( "\t" ) + to_string( size1 ) ); } int main() { /* change cubeIndex to test other cube */ vector<int> cubeIndex{ 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,/**/ 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /**/ 39, 40, 41, 42, 43, /**/ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /**/ 62, 63, 64, 65, 67, 68, 69, 70, 71, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127 }; bitset<128> cube{ 0 }; for ( auto it : cubeIndex ) cube[it] = 1; /*change the ROUND to test the 894 round */ int ROUND = 893; int step = 200; float time = 0; map<bitset<128>, int, CMPS<128>> solutions; vector<bitset<544>> terms; vector<bitset<544>> layerTerms; map<bitset<544>, int, CMPS<544>> layerMap; BackExpandPolynomial( step, terms ); ROUND = ROUND - step; /* use numeric mapping to filter out some terms that have no contribution to * the superpoly */ filterTerms( cube, ROUND, terms ); logger( __func__ + string( "First expand" ) ); layerMap.clear(); for ( auto it : terms ) layerMap[it] ++; ThreadPool thread_pool{}; vector<bitset<544>> mapTmp; while ( true ) { // push all the terms into LayerMap layerTerms.clear(); filterMap( layerMap ); int singlethread = 2; mapTmp.clear(); for ( auto& it : layerMap ) mapTmp.push_back( it.first ); /* numeric mapping to filter out some terms */ filterTerms( cube, ROUND, mapTmp ); /* ChooseTi, change it to adjust the costs of time and memory */ if ( ROUND > 600 ) time = 60; else if ( ROUND > 500 ) time = 120; else if ( ROUND > 400 ) time = 180; else if ( ROUND > 300 ) time = 360; else if ( ROUND > 200 ) time = 720; else time = 0; /* compute small superpoly */ vector<std::future<void>> futures; for (auto & it : mapTmp ) futures.emplace_back( thread_pool.Submit( SolutionSearcherWorker, it, ROUND, ref(cube), ref( layerTerms ), time, singlethread ) ); for (auto & it : futures) it.get(); logger( string( "layerTermsSize " ) + to_string( layerTerms.size() ) ); if ( layerTerms.size() == 0 ) break; if ( ROUND <= 0 ) cerr << "Error " << ROUND << endl; else if (ROUND < 10) time = 0; step = 0; layerMap.clear(); vector<thread> threads; /* ChooseRi, change 10000 to adjust the memory and time costs */ while( layerMap.size() < 10000 ) { step ++; layerMap.clear(); int size = layerTerms.size(); int base = ( size / THREAD_NUM ) >= 1 ? (size / THREAD_NUM) : 1; int size_multiple = base * THREAD_NUM; threads.clear(); singlethread = 2; // expand the terms for ( int i = 0; i < THREAD_NUM; i++ ) threads.push_back( thread ( ExpandWorker, ref( layerTerms ), ref ( cube ), base * i, base * (i + 1), step , ref (layerMap ), singlethread ) ); for ( auto & th : threads ) th.join(); if ( size > size_multiple ) { threads.clear(); for ( int i = 0; i < THREAD_NUM; i++ ) threads.push_back( thread ( ExpandWorker, ref( layerTerms ), ref( cube ), size_multiple + i, size_multiple + i + 1, step, ref( layerMap ), singlethread ) ); for ( auto & th : threads ) th.join(); } } ROUND = ROUND - step; logger( "Step New " + to_string( step ) ); logger( "Round New " + to_string( ROUND ) ); logger( string( "layerMapSize " ) + to_string( layerMap.size() ) ); } cout << "Success!" << endl; }
26.712644
108
0.574584
[ "vector" ]
a05ffbbdd8196f188e17bf60e3da113e0567e641
7,659
cxx
C++
SkeletalRepresentationInitializer/qSlicerSkeletalRepresentationInitializerModuleWidget.cxx
ZhiyLiu/SRepExtension
1efc05eeca75f5d54c4c15712ba62e25ca93c0cf
[ "Apache-2.0" ]
1
2019-12-23T01:47:19.000Z
2019-12-23T01:47:19.000Z
SkeletalRepresentationInitializer/qSlicerSkeletalRepresentationInitializerModuleWidget.cxx
ZhiyLiu/SRepExtension
1efc05eeca75f5d54c4c15712ba62e25ca93c0cf
[ "Apache-2.0" ]
null
null
null
SkeletalRepresentationInitializer/qSlicerSkeletalRepresentationInitializerModuleWidget.cxx
ZhiyLiu/SRepExtension
1efc05eeca75f5d54c4c15712ba62e25ca93c0cf
[ "Apache-2.0" ]
1
2019-03-20T19:29:42.000Z
2019-03-20T19:29:42.000Z
/*============================================================================== Program: 3D Slicer Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. ==============================================================================*/ // Qt includes #include <QDebug> // SlicerQt includes #include "qSlicerSkeletalRepresentationInitializerModuleWidget.h" #include "ui_qSlicerSkeletalRepresentationInitializerModuleWidget.h" // module logic file #include "vtkSlicerSkeletalRepresentationInitializerLogic.h" #include <QFileDialog> #include <QMessageBox> //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_ExtensionTemplate class qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate: public Ui_qSlicerSkeletalRepresentationInitializerModuleWidget { Q_DECLARE_PUBLIC(qSlicerSkeletalRepresentationInitializerModuleWidget) protected: qSlicerSkeletalRepresentationInitializerModuleWidget* const q_ptr; public: qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate(qSlicerSkeletalRepresentationInitializerModuleWidget &); ~qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate(); vtkSlicerSkeletalRepresentationInitializerLogic* logic() const; }; //----------------------------------------------------------------------------- // qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate methods //----------------------------------------------------------------------------- qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate::qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate(qSlicerSkeletalRepresentationInitializerModuleWidget& object) : q_ptr(&object) { } qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate::~qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate(){} vtkSlicerSkeletalRepresentationInitializerLogic* qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate::logic() const { Q_Q(const qSlicerSkeletalRepresentationInitializerModuleWidget); return vtkSlicerSkeletalRepresentationInitializerLogic::SafeDownCast(q->logic()); } //----------------------------------------------------------------------------- // qSlicerSkeletalRepresentationInitializerModuleWidget methods //----------------------------------------------------------------------------- qSlicerSkeletalRepresentationInitializerModuleWidget::qSlicerSkeletalRepresentationInitializerModuleWidget(QWidget* _parent) : Superclass( _parent ) , d_ptr( new qSlicerSkeletalRepresentationInitializerModuleWidgetPrivate(*this) ) { } //----------------------------------------------------------------------------- qSlicerSkeletalRepresentationInitializerModuleWidget::~qSlicerSkeletalRepresentationInitializerModuleWidget() { } //----------------------------------------------------------------------------- void qSlicerSkeletalRepresentationInitializerModuleWidget::setup() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); d->setupUi(this); this->Superclass::setup(); QObject::connect(d->SelectInputButton, SIGNAL(clicked()), this, SLOT(selectInput())); QObject::connect(d->btn_flow, SIGNAL(clicked()), this, SLOT(flow())); //QObject::connect(d->btn_one_step_flow, SIGNAL(clicked()), this, SLOT(flowOneStep())); //QObject::connect(d->btn_match_ell, SIGNAL(clicked()), this, SLOT(pullUpFittingEllipsoid())); //QObject::connect(d->btn_inkling_flow, SIGNAL(clicked()), this, SLOT(inklingFlow())); QObject::connect(d->btn_back_flow, SIGNAL(clicked()), this, SLOT(backwardFlow())); QObject::connect(d->btn_output, SIGNAL(clicked()), this, SLOT(outputPath())); QObject::connect(d->btn_reorder_skeleton, SIGNAL(clicked()), this, SLOT(rotateSkeleton())); } void qSlicerSkeletalRepresentationInitializerModuleWidget::pullUpFittingEllipsoid() { // Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); //d->logic()->DummyShowFittingEllipsoid(); } void qSlicerSkeletalRepresentationInitializerModuleWidget::selectInput() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); QString fileName = QFileDialog::getOpenFileName(this, "Select input mesh"); d->lb_input_file_path->setText(fileName.toUtf8().constData()); d->logic()->SetInputFileName(fileName.toUtf8().constData()); } void qSlicerSkeletalRepresentationInitializerModuleWidget::outputPath() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); QString fileName = QFileDialog::getExistingDirectory(this, "Select refinement output folder"); d->lb_output_path->setText(fileName.toUtf8().constData()); d->logic()->SetOutputPath(fileName.toUtf8().constData()); } void qSlicerSkeletalRepresentationInitializerModuleWidget::rotateSkeleton() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); int numCols = static_cast<int>(d->sl_num_cols->value()); int numRows = static_cast<int>(d->sl_num_rows->value()); d->logic()->SetRows(numRows); d->logic()->SetCols(numCols); d->logic()->RotateSkeleton(d->cb_flip_green->isChecked(),d->cb_flip_red->isChecked(), d->cb_flip_blue->isChecked()); } void qSlicerSkeletalRepresentationInitializerModuleWidget::flow() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); std::string fileName= d->lb_input_file_path->text().toUtf8().constData(); double dt = d->sl_dt->value(); double smoothAmount = d->sl_smooth_amount->value(); int maxIter = int(d->sl_max_iter->value()); int freq_output = int(d->sl_freq_output->value()); int numCols = static_cast<int>(d->sl_num_cols->value()); int numRows = static_cast<int>(d->sl_num_rows->value()); // odd rows is required if(numRows % 2 == 0) { numRows += 1; } // odd cols is required if(numCols % 2 == 0) { numCols += 1; } d->sl_num_cols->setValue(numCols); d->sl_num_rows->setValue(numRows); d->logic()->SetRows(numRows); d->logic()->SetCols(numCols); d->logic()->FlowSurfaceMesh(fileName, dt, smoothAmount, maxIter, freq_output); } void qSlicerSkeletalRepresentationInitializerModuleWidget::flowOneStep() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); std::string fileName= d->lb_input_file_path->text().toUtf8().constData(); double dt = d->sl_dt->value(); double smoothAmount = d->sl_smooth_amount->value(); d->logic()->FlowSurfaceOneStep(fileName, dt, smoothAmount); } void qSlicerSkeletalRepresentationInitializerModuleWidget::inklingFlow() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); std::string fileName= d->lb_input_file_path->text().toUtf8().constData(); double dt = d->sl_dt->value(); double smoothAmount = d->sl_smooth_amount->value(); int maxIter = int(d->sl_max_iter->value()); int freq_output = int(d->sl_freq_output->value()); // double threshold = d->sl_threshold->value(); double threshold = 13.0;// for test d->logic()->InklingFlow(fileName, dt, smoothAmount, maxIter, freq_output, threshold); } void qSlicerSkeletalRepresentationInitializerModuleWidget::backwardFlow() { Q_D(qSlicerSkeletalRepresentationInitializerModuleWidget); int maxIter = static_cast<int>(d->sl_max_iter->value()); d->logic()->BackwardFlow(maxIter); }
41.625
199
0.704008
[ "mesh", "object", "3d" ]
a061914829698cbbbf9ea624c2caa306dc021c85
9,438
cpp
C++
Examples/CoulombSum3d/CoulombSum3d.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
32
2017-09-12T23:52:52.000Z
2020-12-09T07:13:24.000Z
Examples/CoulombSum3d/CoulombSum3d.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
23
2017-05-11T14:38:45.000Z
2021-02-03T13:45:14.000Z
Examples/CoulombSum3d/CoulombSum3d.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
5
2017-11-06T12:40:05.000Z
2020-06-16T13:11:24.000Z
#include <iostream> #include <random> #include <string> #include <vector> #include <Ktt.h> #if defined(_MSC_VER) const std::string kernelPrefix = ""; #else const std::string kernelPrefix = "../"; #endif #if KTT_CUDA_EXAMPLE const std::string defaultKernelFile = kernelPrefix + "../Examples/CoulombSum3d/CoulombSum3d.cu"; const std::string defaultReferenceKernelFile = kernelPrefix + "../Examples/CoulombSum3d/CoulombSum3dReference.cu"; const auto computeApi = ktt::ComputeApi::CUDA; #elif KTT_OPENCL_EXAMPLE const std::string defaultKernelFile = kernelPrefix + "../Examples/CoulombSum3d/CoulombSum3d.cl"; const std::string defaultReferenceKernelFile = kernelPrefix + "../Examples/CoulombSum3d/CoulombSum3dReference.cl"; const auto computeApi = ktt::ComputeApi::OpenCL; #endif // Toggle rapid test (e.g., disable output validation). const bool rapidTest = false; // Toggle kernel profiling. const bool useProfiling = false; // Add denser values to tuning parameters (useDenseParameters = true). const bool useDenseParameters = false; // Add wider ranges of tuning parameters (useWideParameters = true). const bool useWideParameters = false; int main(int argc, char** argv) { ktt::PlatformIndex platformIndex = 0; ktt::DeviceIndex deviceIndex = 0; std::string kernelFile = defaultKernelFile; std::string referenceKernelFile = defaultReferenceKernelFile; if (argc >= 2) { platformIndex = std::stoul(std::string(argv[1])); if (argc >= 3) { deviceIndex = std::stoul(std::string(argv[2])); if (argc >= 4) { kernelFile = std::string(argv[3]); if (argc >= 5) { referenceKernelFile = std::string(argv[4]); } } } } // Declare and initialize data const int gridSize = 256; int atoms; if constexpr (!useProfiling) { atoms = 4000; } else { atoms = 64; /* faster execution of slowly profiled kernel */ } const ktt::DimensionVector referenceNdRangeDimensions(gridSize / 16, gridSize / 16, gridSize); const ktt::DimensionVector referenceWorkGroupDimensions(16, 16); const ktt::DimensionVector ndRangeDimensions(gridSize, gridSize, gridSize); const ktt::DimensionVector workGroupDimensions; std::vector<float> atomInfoX(atoms); std::vector<float> atomInfoY(atoms); std::vector<float> atomInfoZ(atoms); std::vector<float> atomInfoW(atoms); std::vector<float> atomInfo(4 * atoms); std::vector<float> energyGrid(gridSize * gridSize * gridSize, 0.0f); // Initialize data std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<float> distribution(0.0f, 20.0f); const float gridSpacing = 0.5f; // in Angstroms for (int i = 0; i < atoms; ++i) { atomInfoX[i] = distribution(engine); atomInfoY[i] = distribution(engine); atomInfoZ[i] = distribution(engine); atomInfoW[i] = distribution(engine) / 40.0f; atomInfo[4 * i] = atomInfoX[i]; atomInfo[4 * i + 1] = atomInfoY[i]; atomInfo[4 * i + 2] = atomInfoZ[i]; atomInfo[4 * i + 3] = atomInfoW[i]; } ktt::Tuner tuner(platformIndex, deviceIndex, computeApi); tuner.SetGlobalSizeType(ktt::GlobalSizeType::CUDA); tuner.SetTimeUnit(ktt::TimeUnit::Microseconds); if constexpr (computeApi == ktt::ComputeApi::OpenCL) { tuner.SetCompilerOptions("-cl-fast-relaxed-math"); } else { tuner.SetCompilerOptions("-use_fast_math"); if constexpr (useProfiling) { printf("Executing with profiling switched ON.\n"); tuner.SetProfiling(true); } } const ktt::KernelDefinitionId definition = tuner.AddKernelDefinitionFromFile("directCoulombSum", kernelFile, ndRangeDimensions, workGroupDimensions); const ktt::KernelDefinitionId referenceDefinition = tuner.AddKernelDefinitionFromFile("directCoulombSumReference", referenceKernelFile, referenceNdRangeDimensions, referenceWorkGroupDimensions); const ktt::KernelId kernel = tuner.CreateSimpleKernel("CoulombSum", definition); const ktt::KernelId referenceKernel = tuner.CreateSimpleKernel("CoulombSumReference", referenceDefinition); const ktt::ArgumentId aiId = tuner.AddArgumentVector(atomInfo, ktt::ArgumentAccessType::ReadOnly); const ktt::ArgumentId aixId = tuner.AddArgumentVector(atomInfoX, ktt::ArgumentAccessType::ReadOnly); const ktt::ArgumentId aiyId = tuner.AddArgumentVector(atomInfoY, ktt::ArgumentAccessType::ReadOnly); const ktt::ArgumentId aizId = tuner.AddArgumentVector(atomInfoZ, ktt::ArgumentAccessType::ReadOnly); const ktt::ArgumentId aiwId = tuner.AddArgumentVector(atomInfoW, ktt::ArgumentAccessType::ReadOnly); const ktt::ArgumentId aId = tuner.AddArgumentScalar(atoms); const ktt::ArgumentId gsId = tuner.AddArgumentScalar(gridSpacing); const ktt::ArgumentId gridDim = tuner.AddArgumentScalar(gridSize); const ktt::ArgumentId gridId = tuner.AddArgumentVector(energyGrid, ktt::ArgumentAccessType::WriteOnly); if constexpr (!useDenseParameters) { tuner.AddParameter(kernel, "WORK_GROUP_SIZE_X", std::vector<uint64_t>{16, 32}); } else { tuner.AddParameter(kernel, "WORK_GROUP_SIZE_X", std::vector<uint64_t>{8, 16, 24, 32}); } tuner.AddThreadModifier(kernel, {definition}, ktt::ModifierType::Local, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::Multiply); tuner.AddThreadModifier(kernel, {definition}, ktt::ModifierType::Global, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::DivideCeil); if constexpr (!useDenseParameters && !useWideParameters) { tuner.AddParameter(kernel, "WORK_GROUP_SIZE_Y", std::vector<uint64_t>{1, 2, 4, 8}); } else if constexpr (!useWideParameters) { tuner.AddParameter(kernel, "WORK_GROUP_SIZE_Y", std::vector<uint64_t>{1, 2, 3, 4, 5, 6, 7, 8}); } else { tuner.AddParameter(kernel, "WORK_GROUP_SIZE_Y", std::vector<uint64_t>{1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32}); } tuner.AddThreadModifier(kernel, {definition}, ktt::ModifierType::Local, ktt::ModifierDimension::Y, "WORK_GROUP_SIZE_Y", ktt::ModifierAction::Multiply); tuner.AddThreadModifier(kernel, {definition}, ktt::ModifierType::Global, ktt::ModifierDimension::Y, "WORK_GROUP_SIZE_Y", ktt::ModifierAction::DivideCeil); tuner.AddParameter(kernel, "WORK_GROUP_SIZE_Z", std::vector<uint64_t>{1}); if constexpr (!useDenseParameters && !useWideParameters) { tuner.AddParameter(kernel, "Z_ITERATIONS", std::vector<uint64_t>{1, 2, 4, 8, 16, 32}); } else { tuner.AddParameter(kernel, "Z_ITERATIONS", std::vector<uint64_t>{1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32}); } tuner.AddThreadModifier(kernel, {definition}, ktt::ModifierType::Global, ktt::ModifierDimension::Z, "Z_ITERATIONS", ktt::ModifierAction::DivideCeil); if constexpr (!useDenseParameters && !useWideParameters) { tuner.AddParameter(kernel, "INNER_UNROLL_FACTOR", std::vector<uint64_t>{0, 1, 2, 4, 8, 16, 32}); } else { tuner.AddParameter(kernel, "INNER_UNROLL_FACTOR", std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32}); } if constexpr (computeApi == ktt::ComputeApi::OpenCL) { tuner.AddParameter(kernel, "USE_CONSTANT_MEMORY", std::vector<uint64_t>{0, 1}); tuner.AddParameter(kernel, "USE_SOA", std::vector<uint64_t>{0, 1}); tuner.AddParameter(kernel, "VECTOR_SIZE", std::vector<uint64_t>{1, 2 , 4, 8, 16}); } else { // Not implemented in CUDA tuner.AddParameter(kernel, "USE_CONSTANT_MEMORY", std::vector<uint64_t>{0}); tuner.AddParameter(kernel, "USE_SOA", std::vector<uint64_t>{0, 1}); tuner.AddParameter(kernel, "VECTOR_SIZE", std::vector<uint64_t>{1}); } auto lt = [](const std::vector<uint64_t>& vector) {return vector.at(0) < vector.at(1);}; tuner.AddConstraint(kernel, {"INNER_UNROLL_FACTOR", "Z_ITERATIONS"}, lt); auto vec = [](const std::vector<uint64_t>& vector) {return vector.at(0) || vector.at(1) == 1;}; tuner.AddConstraint(kernel, {"USE_SOA", "VECTOR_SIZE"}, vec); auto par = [](const std::vector<uint64_t>& vector) {return vector.at(0) * vector.at(1) >= 64;}; tuner.AddConstraint(kernel, {"WORK_GROUP_SIZE_X", "WORK_GROUP_SIZE_Y"}, par); tuner.SetArguments(definition, std::vector<ktt::ArgumentId>{aiId, aixId, aiyId, aizId, aiwId, aId, gsId, gridDim, gridId}); tuner.SetArguments(referenceDefinition, std::vector<ktt::ArgumentId>{aiId, aId, gsId, gridDim, gridId}); if constexpr (!useProfiling && !rapidTest) { //TODO: this is temporary hack, there should be composition of zeroizing and Coulomb kernel, // otherwise, multiple profiling runs corrupt results tuner.SetReferenceKernel(gridId, referenceKernel, ktt::KernelConfiguration()); tuner.SetValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.01); } const auto results = tuner.Tune(kernel); tuner.SaveResults(results, "CoulombSumOutput", ktt::OutputFormat::JSON); return 0; }
40.506438
153
0.676097
[ "vector" ]
a069887a4534f42c6efe049941fc17713bb07fc5
6,108
cpp
C++
android-31/android/media/AudioAttributes.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/media/AudioAttributes.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/media/AudioAttributes.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../os/Parcel.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "./AudioAttributes.hpp" namespace android::media { // Fields jint AudioAttributes::ALLOW_CAPTURE_BY_ALL() { return getStaticField<jint>( "android.media.AudioAttributes", "ALLOW_CAPTURE_BY_ALL" ); } jint AudioAttributes::ALLOW_CAPTURE_BY_NONE() { return getStaticField<jint>( "android.media.AudioAttributes", "ALLOW_CAPTURE_BY_NONE" ); } jint AudioAttributes::ALLOW_CAPTURE_BY_SYSTEM() { return getStaticField<jint>( "android.media.AudioAttributes", "ALLOW_CAPTURE_BY_SYSTEM" ); } jint AudioAttributes::CONTENT_TYPE_MOVIE() { return getStaticField<jint>( "android.media.AudioAttributes", "CONTENT_TYPE_MOVIE" ); } jint AudioAttributes::CONTENT_TYPE_MUSIC() { return getStaticField<jint>( "android.media.AudioAttributes", "CONTENT_TYPE_MUSIC" ); } jint AudioAttributes::CONTENT_TYPE_SONIFICATION() { return getStaticField<jint>( "android.media.AudioAttributes", "CONTENT_TYPE_SONIFICATION" ); } jint AudioAttributes::CONTENT_TYPE_SPEECH() { return getStaticField<jint>( "android.media.AudioAttributes", "CONTENT_TYPE_SPEECH" ); } jint AudioAttributes::CONTENT_TYPE_UNKNOWN() { return getStaticField<jint>( "android.media.AudioAttributes", "CONTENT_TYPE_UNKNOWN" ); } JObject AudioAttributes::CREATOR() { return getStaticObjectField( "android.media.AudioAttributes", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } jint AudioAttributes::FLAG_AUDIBILITY_ENFORCED() { return getStaticField<jint>( "android.media.AudioAttributes", "FLAG_AUDIBILITY_ENFORCED" ); } jint AudioAttributes::FLAG_HW_AV_SYNC() { return getStaticField<jint>( "android.media.AudioAttributes", "FLAG_HW_AV_SYNC" ); } jint AudioAttributes::FLAG_LOW_LATENCY() { return getStaticField<jint>( "android.media.AudioAttributes", "FLAG_LOW_LATENCY" ); } jint AudioAttributes::USAGE_ALARM() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_ALARM" ); } jint AudioAttributes::USAGE_ASSISTANCE_ACCESSIBILITY() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_ASSISTANCE_ACCESSIBILITY" ); } jint AudioAttributes::USAGE_ASSISTANCE_NAVIGATION_GUIDANCE() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_ASSISTANCE_NAVIGATION_GUIDANCE" ); } jint AudioAttributes::USAGE_ASSISTANCE_SONIFICATION() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_ASSISTANCE_SONIFICATION" ); } jint AudioAttributes::USAGE_ASSISTANT() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_ASSISTANT" ); } jint AudioAttributes::USAGE_GAME() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_GAME" ); } jint AudioAttributes::USAGE_MEDIA() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_MEDIA" ); } jint AudioAttributes::USAGE_NOTIFICATION() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION" ); } jint AudioAttributes::USAGE_NOTIFICATION_COMMUNICATION_DELAYED() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION_COMMUNICATION_DELAYED" ); } jint AudioAttributes::USAGE_NOTIFICATION_COMMUNICATION_INSTANT() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION_COMMUNICATION_INSTANT" ); } jint AudioAttributes::USAGE_NOTIFICATION_COMMUNICATION_REQUEST() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION_COMMUNICATION_REQUEST" ); } jint AudioAttributes::USAGE_NOTIFICATION_EVENT() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION_EVENT" ); } jint AudioAttributes::USAGE_NOTIFICATION_RINGTONE() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_NOTIFICATION_RINGTONE" ); } jint AudioAttributes::USAGE_UNKNOWN() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_UNKNOWN" ); } jint AudioAttributes::USAGE_VOICE_COMMUNICATION() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_VOICE_COMMUNICATION" ); } jint AudioAttributes::USAGE_VOICE_COMMUNICATION_SIGNALLING() { return getStaticField<jint>( "android.media.AudioAttributes", "USAGE_VOICE_COMMUNICATION_SIGNALLING" ); } // QJniObject forward AudioAttributes::AudioAttributes(QJniObject obj) : JObject(obj) {} // Constructors // Methods jboolean AudioAttributes::areHapticChannelsMuted() const { return callMethod<jboolean>( "areHapticChannelsMuted", "()Z" ); } jint AudioAttributes::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } jboolean AudioAttributes::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } jint AudioAttributes::getAllowedCapturePolicy() const { return callMethod<jint>( "getAllowedCapturePolicy", "()I" ); } jint AudioAttributes::getContentType() const { return callMethod<jint>( "getContentType", "()I" ); } jint AudioAttributes::getFlags() const { return callMethod<jint>( "getFlags", "()I" ); } jint AudioAttributes::getUsage() const { return callMethod<jint>( "getUsage", "()I" ); } jint AudioAttributes::getVolumeControlStream() const { return callMethod<jint>( "getVolumeControlStream", "()I" ); } jint AudioAttributes::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } JString AudioAttributes::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } void AudioAttributes::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::media
20.705085
79
0.718566
[ "object" ]
a06aa5ef2c76a5d10290bea1d0f04c696cc22540
3,405
cpp
C++
aws-cpp-sdk-mediaconvert/source/model/MotionImageInserter.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-mediaconvert/source/model/MotionImageInserter.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-mediaconvert/source/model/MotionImageInserter.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/mediaconvert/model/MotionImageInserter.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaConvert { namespace Model { MotionImageInserter::MotionImageInserter() : m_framerateHasBeenSet(false), m_inputHasBeenSet(false), m_insertionMode(MotionImageInsertionMode::NOT_SET), m_insertionModeHasBeenSet(false), m_offsetHasBeenSet(false), m_playback(MotionImagePlayback::NOT_SET), m_playbackHasBeenSet(false), m_startTimeHasBeenSet(false) { } MotionImageInserter::MotionImageInserter(JsonView jsonValue) : m_framerateHasBeenSet(false), m_inputHasBeenSet(false), m_insertionMode(MotionImageInsertionMode::NOT_SET), m_insertionModeHasBeenSet(false), m_offsetHasBeenSet(false), m_playback(MotionImagePlayback::NOT_SET), m_playbackHasBeenSet(false), m_startTimeHasBeenSet(false) { *this = jsonValue; } MotionImageInserter& MotionImageInserter::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("framerate")) { m_framerate = jsonValue.GetObject("framerate"); m_framerateHasBeenSet = true; } if(jsonValue.ValueExists("input")) { m_input = jsonValue.GetString("input"); m_inputHasBeenSet = true; } if(jsonValue.ValueExists("insertionMode")) { m_insertionMode = MotionImageInsertionModeMapper::GetMotionImageInsertionModeForName(jsonValue.GetString("insertionMode")); m_insertionModeHasBeenSet = true; } if(jsonValue.ValueExists("offset")) { m_offset = jsonValue.GetObject("offset"); m_offsetHasBeenSet = true; } if(jsonValue.ValueExists("playback")) { m_playback = MotionImagePlaybackMapper::GetMotionImagePlaybackForName(jsonValue.GetString("playback")); m_playbackHasBeenSet = true; } if(jsonValue.ValueExists("startTime")) { m_startTime = jsonValue.GetString("startTime"); m_startTimeHasBeenSet = true; } return *this; } JsonValue MotionImageInserter::Jsonize() const { JsonValue payload; if(m_framerateHasBeenSet) { payload.WithObject("framerate", m_framerate.Jsonize()); } if(m_inputHasBeenSet) { payload.WithString("input", m_input); } if(m_insertionModeHasBeenSet) { payload.WithString("insertionMode", MotionImageInsertionModeMapper::GetNameForMotionImageInsertionMode(m_insertionMode)); } if(m_offsetHasBeenSet) { payload.WithObject("offset", m_offset.Jsonize()); } if(m_playbackHasBeenSet) { payload.WithString("playback", MotionImagePlaybackMapper::GetNameForMotionImagePlayback(m_playback)); } if(m_startTimeHasBeenSet) { payload.WithString("startTime", m_startTime); } return payload; } } // namespace Model } // namespace MediaConvert } // namespace Aws
23.163265
127
0.743612
[ "model" ]
a06d70b97b9488a507debaad9943649f191b9d05
35,873
cpp
C++
src/dwarf2pdb.cpp
vadimcn/cv2pdb
69d12da2717fa0540a2ab22c2542e0601fbf73dc
[ "Artistic-2.0" ]
null
null
null
src/dwarf2pdb.cpp
vadimcn/cv2pdb
69d12da2717fa0540a2ab22c2542e0601fbf73dc
[ "Artistic-2.0" ]
null
null
null
src/dwarf2pdb.cpp
vadimcn/cv2pdb
69d12da2717fa0540a2ab22c2542e0601fbf73dc
[ "Artistic-2.0" ]
null
null
null
// Convert DMD CodeView/DWARF debug information to PDB files // Copyright (c) 2009-2012 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details // // todo: // display associative array // 64 bit: // - arguments passed by register // - real #include "cv2pdb.h" #include "PEImage.h" #include "symutil.h" #include "cvutil.h" #include "dwarf.h" #include <assert.h> #include <string> #include <vector> void CV2PDB::checkDWARFTypeAlloc(int size, int add) { if (cbDwarfTypes + size > allocDwarfTypes) { //allocDwarfTypes += size + add; allocDwarfTypes += allocDwarfTypes/2 + size + add; dwarfTypes = (BYTE*) realloc(dwarfTypes, allocDwarfTypes); if (dwarfTypes == nullptr) __debugbreak(); } } enum CV_X86_REG { CV_REG_NONE = 0, CV_REG_EAX = 17, CV_REG_ECX = 18, CV_REG_EDX = 19, CV_REG_EBX = 20, CV_REG_ESP = 21, CV_REG_EBP = 22, CV_REG_ESI = 23, CV_REG_EDI = 24, CV_REG_ES = 25, CV_REG_CS = 26, CV_REG_SS = 27, CV_REG_DS = 28, CV_REG_FS = 29, CV_REG_GS = 30, CV_REG_IP = 31, CV_REG_FLAGS = 32, CV_REG_EIP = 33, CV_REG_EFLAGS = 34, CV_REG_ST0 = 128, /* this includes ST1 to ST7 */ CV_REG_XMM0 = 154 /* this includes XMM1 to XMM7 */ }; CV_X86_REG dwarf_to_x86_reg(unsigned dwarf_reg) { switch (dwarf_reg) { case 0: return CV_REG_EAX; case 1: return CV_REG_ECX; case 2: return CV_REG_EDX; case 3: return CV_REG_EBX; case 4: return CV_REG_ESP; case 5: return CV_REG_EBP; case 6: return CV_REG_ESI; case 7: return CV_REG_EDI; case 8: return CV_REG_EIP; case 9: return CV_REG_EFLAGS; case 10: return CV_REG_CS; case 11: return CV_REG_SS; case 12: return CV_REG_DS; case 13: return CV_REG_ES; case 14: return CV_REG_FS; case 15: return CV_REG_GS; case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: return (CV_X86_REG)(CV_REG_ST0 + dwarf_reg - 16); case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: return (CV_X86_REG)(CV_REG_XMM0 + dwarf_reg - 32); default: return CV_REG_NONE; } } void CV2PDB::appendStackVar(const char* name, int type, Location& loc) { unsigned int len; unsigned int align = 4; checkUdtSymbolAlloc(100 + kMaxNameLen); codeview_symbol*cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); CV_X86_REG baseReg = dwarf_to_x86_reg(loc.reg); if (baseReg == CV_REG_NONE) return; if (baseReg == CV_REG_EBP) { cvs->stack_v2.id = v3 ? S_BPREL_V3 : S_BPREL_V2; cvs->stack_v2.offset = loc.off; cvs->stack_v2.symtype = type; len = cstrcpy_v(v3, (BYTE*)&cvs->stack_v2.p_name, name); len += (BYTE*)&cvs->stack_v2.p_name - (BYTE*)cvs; } else { cvs->regrel_v3.id = S_REGREL_V3; cvs->regrel_v3.reg = baseReg; cvs->regrel_v3.offset = loc.off; cvs->regrel_v3.symtype = type; len = cstrcpy_v(true, (BYTE*)cvs->regrel_v3.name, name); len += (BYTE*)&cvs->regrel_v3.name - (BYTE*)cvs; } for (; len & (align-1); len++) udtSymbols[cbUdtSymbols + len] = 0xf4 - (len & 3); cvs->stack_v2.len = len - 2; cbUdtSymbols += len; } void CV2PDB::appendGlobalVar(const char* name, int type, int seg, int offset) { unsigned int len; unsigned int align = 4; for(char* cname = (char*) name; *cname; cname++) if (*cname == '.') *cname = dotReplacementChar; checkUdtSymbolAlloc(100 + kMaxNameLen); codeview_symbol*cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); cvs->data_v2.id = v3 ? S_GDATA_V3 : S_GDATA_V2; cvs->data_v2.offset = offset; cvs->data_v2.symtype = type; cvs->data_v2.segment = seg; len = cstrcpy_v (v3, (BYTE*) &cvs->data_v2.p_name, name); len += (BYTE*) &cvs->data_v2.p_name - (BYTE*) cvs; for (; len & (align-1); len++) udtSymbols[cbUdtSymbols + len] = 0xf4 - (len & 3); cvs->data_v2.len = len - 2; cbUdtSymbols += len; } bool CV2PDB::appendEndArg() { checkUdtSymbolAlloc(8); codeview_symbol*cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); cvs->generic.id = S_ENDARG_V1; cvs->generic.len = 2; cbUdtSymbols += 4; return true; } void CV2PDB::appendEnd() { checkUdtSymbolAlloc(8); codeview_symbol*cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); cvs->generic.id = S_END_V1; cvs->generic.len = 2; cbUdtSymbols += 4; } void CV2PDB::appendLexicalBlock(unsigned pclo, unsigned pchi) { checkUdtSymbolAlloc(32); codeview_symbol*dsym = (codeview_symbol*) (udtSymbols + cbUdtSymbols); dsym->block_v3.id = S_BLOCK_V3; dsym->block_v3.parent = 0; dsym->block_v3.end = 0; // destSize + sizeof(dsym->block_v3) + 12; dsym->block_v3.length = pchi - pclo; dsym->block_v3.offset = pclo - codeSegOff; dsym->block_v3.segment = img.codeSegment + 1; dsym->block_v3.name[0] = 0; int len = sizeof(dsym->block_v3); for (; len & 3; len++) udtSymbols[cbUdtSymbols + len] = 0xf4 - (len & 3); dsym->block_v3.len = len - 2; cbUdtSymbols += len; } bool CV2PDB::addDWARFProc(DWARF_InfoData& procid, DWARF_CompilationUnit* cu, DIECursor cursor) { unsigned int pclo = procid.pclo - codeSegOff; unsigned int pchi = procid.pchi - codeSegOff; unsigned int len; unsigned int align = 4; checkUdtSymbolAlloc(100 + kMaxNameLen); // GLOBALPROC codeview_symbol*cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); cvs->proc_v2.id = v3 ? S_GPROC_V3 : S_GPROC_V2; cvs->proc_v2.pparent = 0; cvs->proc_v2.pend = 0; cvs->proc_v2.next = 0; cvs->proc_v2.proc_len = pchi - pclo; cvs->proc_v2.debug_start = pclo - pclo; cvs->proc_v2.debug_end = pchi - pclo; cvs->proc_v2.offset = pclo; cvs->proc_v2.segment = img.codeSegment + 1; cvs->proc_v2.proctype = 0; // translateType(sym->proc_v1.proctype); cvs->proc_v2.flags = 0; // printf("GlobalPROC %s\n", procid.name); len = cstrcpy_v (v3, (BYTE*) &cvs->proc_v2.p_name, procid.name); len += (BYTE*) &cvs->proc_v2.p_name - (BYTE*) cvs; for (; len & (align-1); len++) udtSymbols[cbUdtSymbols + len] = 0xf4 - (len & 3); cvs->proc_v2.len = len - 2; cbUdtSymbols += len; #if 0 // add funcinfo cvs = (codeview_symbol*) (udtSymbols + cbUdtSymbols); cvs->funcinfo_32.id = S_FUNCINFO_32; cvs->funcinfo_32.sizeLocals = 20; memset(cvs->funcinfo_32.unknown, 0, sizeof(cvs->funcinfo_32.unknown)); cvs->funcinfo_32.unknown[5] = 4; cvs->funcinfo_32.info = 0x4200; cvs->funcinfo_32.unknown2 = 0x11; len = sizeof(cvs->funcinfo_32); for (; len & (align-1); len++) udtSymbols[cbUdtSymbols + len] = 0xf4 - (len & 3); cvs->funcinfo_32.len = len - 2; cbUdtSymbols += len; #endif #if 0 addStackVar("local_var", 0x1001, 8); #endif Location frameBase = decodeLocation(procid.frame_base); if (cu) { DWARF_InfoData id; DIECursor prev = cursor; while (cursor.readSibling(id) && id.tag == DW_TAG_formal_parameter) { if (id.tag == DW_TAG_formal_parameter) { if (id.name && id.location.type == ExprLoc) { Location loc = decodeLocation(id.location, &frameBase); if (loc.is_regrel()) appendStackVar(id.name, getTypeByDWARFPtr(cu, id.type), loc); } } prev = cursor; } appendEndArg(); addLexicalBlocks(cu, prev, frameBase); appendEnd(); } else { appendEndArg(); appendEnd(); } return true; } bool CV2PDB::addLexicalBlocks(DWARF_CompilationUnit* cu, DIECursor cursor, Location frameBase) { DWARF_InfoData id; while (cursor.readSibling(id)) { if (id.tag == DW_TAG_variable) { if (id.name && id.location.type == ExprLoc) { Location loc = decodeLocation(id.location, &frameBase); if (loc.is_regrel()) appendStackVar(id.name, getTypeByDWARFPtr(cu, id.type), loc); } } else if (id.tag == DW_TAG_lexical_block) { if (id.hasChild) { if (id.ranges != -1) { // iterate over all code ranges unsigned char* r = (unsigned char*)img.debug_ranges + id.ranges; unsigned char* rend = (unsigned char*)img.debug_ranges + img.debug_ranges_length; while (r < rend) { unsigned long pclo = RD4(r); unsigned long pchi = RD4(r); if (pclo == 0 && pchi == 0) break; appendLexicalBlock(pclo, pchi); addLexicalBlocks(cu, cursor.getSubtreeCursor(), frameBase); appendEnd(); } } else if (id.pchi != id.pclo) { appendLexicalBlock(id.pclo, id.pchi); addLexicalBlocks(cu, cursor.getSubtreeCursor(), frameBase); appendEnd(); } } } } return true; } int CV2PDB::addDWARFStructure(DWARF_InfoData& structid, DWARF_CompilationUnit* cu, DIECursor cursor) { //printf("Adding struct %s, entryoff %d, abbrev %d\n", structid.name, structid.entryOff, structid.abbrev); bool isunion = structid.tag == DW_TAG_union_type; int fieldlistType = 0; int nfields = 0; if (cu) { checkDWARFTypeAlloc(100); codeview_reftype* fl = (codeview_reftype*) (dwarfTypes + cbDwarfTypes); int flbegin = cbDwarfTypes; fl->fieldlist.id = LF_FIELDLIST_V2; cbDwarfTypes += 4; #if 0 if(structid.containing_type && structid.containing_type != structid.entryOff) { codeview_fieldtype* bc = (codeview_fieldtype*) (dwarfTypes + cbDwarfTypes); bc->bclass_v2.id = LF_BCLASS_V2; bc->bclass_v2.offset = 0; bc->bclass_v2.type = getTypeByDWARFPtr(cu, structid.containing_type); bc->bclass_v2.attribute = 3; // public cbDwarfTypes += sizeof(bc->bclass_v2); for (; cbDwarfTypes & 3; cbDwarfTypes++) dwarfTypes[cbDwarfTypes] = 0xf4 - (cbDwarfTypes & 3); nfields++; } #endif DWARF_InfoData id; int len = 0; while (cursor.readSibling(id)) { int cvid = -1; if (id.tag == DW_TAG_member && id.name) { //printf(" Adding field %s\n", id.name); int off = 0; if (!isunion) { Location loc = decodeLocation(id.member_location); if (loc.is_abs()) { off = loc.off; cvid = S_CONSTANT_V2; } } if(isunion || cvid == S_CONSTANT_V2) { checkDWARFTypeAlloc(kMaxNameLen + 100); codeview_fieldtype* dfieldtype = (codeview_fieldtype*) (dwarfTypes + cbDwarfTypes); cbDwarfTypes += addFieldMember(dfieldtype, 0, off, getTypeByDWARFPtr(cu, id.type), id.name); nfields++; } } else if(id.tag == DW_TAG_inheritance) { int off; Location loc = decodeLocation(id.member_location); if (loc.is_abs()) { cvid = S_CONSTANT_V2; off = loc.off; } if(cvid == S_CONSTANT_V2) { codeview_fieldtype* bc = (codeview_fieldtype*) (dwarfTypes + cbDwarfTypes); bc->bclass_v2.id = LF_BCLASS_V2; bc->bclass_v2.offset = off; bc->bclass_v2.type = getTypeByDWARFPtr(cu, id.type); bc->bclass_v2.attribute = 3; // public cbDwarfTypes += sizeof(bc->bclass_v2); for (; cbDwarfTypes & 3; cbDwarfTypes++) dwarfTypes[cbDwarfTypes] = 0xf4 - (cbDwarfTypes & 3); nfields++; } } } fl = (codeview_reftype*) (dwarfTypes + flbegin); fl->fieldlist.len = cbDwarfTypes - flbegin - 2; fieldlistType = nextDwarfType++; } checkUserTypeAlloc(kMaxNameLen + 100); codeview_type* cvt = (codeview_type*) (userTypes + cbUserTypes); const char* name = (structid.name ? structid.name : "__noname"); int attr = fieldlistType ? 0 : kPropIncomplete; int len = addAggregate(cvt, false, nfields, fieldlistType, attr, 0, 0, structid.byte_size, name); cbUserTypes += len; //ensureUDT()? int cvtype = nextUserType++; addUdtSymbol(cvtype, name); return cvtype; } int CV2PDB::getDWARFArrayBounds(DWARF_InfoData& arrayid, DWARF_CompilationUnit* cu, DIECursor cursor, int& upperBound) { int lowerBound = 0; if (cu) { DWARF_InfoData id; while (cursor.readSibling(id)) { int cvid = -1; if (id.tag == DW_TAG_subrange_type) { lowerBound = id.lower_bound; upperBound = id.upper_bound; } } } return lowerBound; } int CV2PDB::addDWARFArray(DWARF_InfoData& arrayid, DWARF_CompilationUnit* cu, DIECursor cursor) { int upperBound, lowerBound = getDWARFArrayBounds(arrayid, cu, cursor, upperBound); checkUserTypeAlloc(kMaxNameLen + 100); codeview_type* cvt = (codeview_type*) (userTypes + cbUserTypes); cvt->array_v2.id = v3 ? LF_ARRAY_V3 : LF_ARRAY_V2; cvt->array_v2.elemtype = getTypeByDWARFPtr(cu, arrayid.type); cvt->array_v2.idxtype = 0x74; int len = (BYTE*)&cvt->array_v2.arrlen - (BYTE*)cvt; int size = (upperBound - lowerBound + 1) * getDWARFTypeSize(cu, arrayid.type); len += write_numeric_leaf(size, &cvt->array_v2.arrlen); ((BYTE*)cvt)[len++] = 0; // empty name for (; len & 3; len++) userTypes[cbUserTypes + len] = 0xf4 - (len & 3); cvt->array_v2.len = len - 2; cbUserTypes += len; int cvtype = nextUserType++; return cvtype; } bool CV2PDB::addDWARFTypes() { checkUdtSymbolAlloc(100); int prefix = 4; DWORD* ddata = new DWORD [img.debug_info_length/4]; // large enough unsigned char *data = (unsigned char*) (ddata + prefix); unsigned int off = 0; unsigned int len; unsigned int align = 4; // SSEARCH codeview_symbol* cvs = (codeview_symbol*) (data + off); cvs->ssearch_v1.id = S_SSEARCH_V1; cvs->ssearch_v1.segment = img.codeSegment + 1; cvs->ssearch_v1.offset = 0; len = sizeof(cvs->ssearch_v1); for (; len & (align-1); len++) data[off + len] = 0xf4 - (len & 3); cvs->ssearch_v1.len = len - 2; off += len; // COMPILAND cvs = (codeview_symbol*) (data + off); cvs->compiland_v1.id = S_COMPILAND_V1; cvs->compiland_v1.unknown = 0x800100; // ?, 0x100: C++, cvs->compiland_v1.unknown |= img.isX64() ? 0xd0 : 6; //0x06: Pentium Pro/II, 0xd0: x64 len = sizeof(cvs->compiland_v1) - sizeof(cvs->compiland_v1.p_name); len += c2p("cv2pdb", cvs->compiland_v1.p_name); for (; len & (align-1); len++) data[off + len] = 0xf4 - (len & 3); cvs->compiland_v1.len = len - 2; off += len; #if 0 // define one proc over everything int s = codeSegment; int pclo = 0; // img.getImageBase() + img.getSection(s).VirtualAddress; int pchi = pclo + img.getSection(s).Misc.VirtualSize; addDWARFProc("procall", pclo, pchi, 0, 0, 0); #endif ////////////////////////// mspdb::Mod* mod = globalMod(); //return writeSymbols (mod, ddata, off, prefix, true); return addSymbols (mod, data, off, true); } bool CV2PDB::addDWARFSectionContrib(mspdb::Mod* mod, unsigned long pclo, unsigned long pchi) { int segIndex = img.findSection(pclo); if(segIndex >= 0) { int segFlags = 0x60101020; // 0x40401040, 0x60500020; // TODO int rc = mod->AddSecContrib(segIndex, pclo, pchi - pclo, segFlags); if (rc <= 0) return setError("cannot add section contribution to module"); } return true; } int CV2PDB::addDWARFBasicType(const char*name, int encoding, int byte_size) { int type = 0, mode = 0, size = 0; switch(encoding) { case DW_ATE_boolean: type = 3; break; case DW_ATE_complex_float: type = 5; byte_size /= 2; break; case DW_ATE_float: type = 4; break; case DW_ATE_signed: type = 1; break; case DW_ATE_signed_char: type = 7; break; case DW_ATE_unsigned: type = 2; break; case DW_ATE_unsigned_char: type = 7; break; case DW_ATE_imaginary_float:type = 4; break; default: setError("unknown basic type encoding"); } switch(type) { case 1: // signed case 2: // unsigned case 3: // boolean switch(byte_size) { case 1: size = 0; break; case 2: size = 1; break; case 4: size = 2; break; case 8: size = 3; break; default: setError("unsupported integer type size"); } break; case 4: case 5: switch(byte_size) { case 4: size = 0; break; case 8: size = 1; break; case 10: size = 2; break; case 12: size = 2; break; // with padding bytes case 16: size = 3; break; case 6: size = 4; break; default: setError("unsupported real type size"); } break; case 7: switch(byte_size) { case 1: size = 0; break; case 2: size = encoding == DW_ATE_signed_char ? 2 : 3; break; case 4: size = encoding == DW_ATE_signed_char ? 4 : 5; break; case 8: size = encoding == DW_ATE_signed_char ? 6 : 7; break; default: setError("unsupported real int type size"); } } int t = size | (type << 4); t = translateType(t); int cvtype = appendTypedef(t, name, false); if(useTypedefEnum) addUdtSymbol(cvtype, name); return cvtype; } int CV2PDB::getTypeByDWARFPtr(DWARF_CompilationUnit* cu, byte* ptr) { std::unordered_map<byte*, int>::iterator it = mapOffsetToType.find(ptr); if(it == mapOffsetToType.end()) return 0x03; // void return it->second; } int CV2PDB::getDWARFTypeSize(DWARF_CompilationUnit* cu, byte* typePtr) { DWARF_InfoData id; DIECursor cursor(cu, typePtr); if (!cursor.readNext(id)) return 0; if(id.byte_size > 0) return id.byte_size; switch(id.tag) { case DW_TAG_ptr_to_member_type: case DW_TAG_reference_type: case DW_TAG_pointer_type: return cu->address_size; case DW_TAG_array_type: { int upperBound, lowerBound = getDWARFArrayBounds(id, cu, cursor, upperBound); return (upperBound + lowerBound + 1) * getDWARFTypeSize(cu, id.type); } default: if(id.type) return getDWARFTypeSize(cu, id.type); break; } return 0; } bool CV2PDB::mapTypes() { int typeID = nextUserType; unsigned long off = 0; while (off < img.debug_info_length) { DWARF_CompilationUnit* cu = (DWARF_CompilationUnit*)(img.debug_info + off); DIECursor cursor(cu, (byte*)cu + sizeof(DWARF_CompilationUnit)); DWARF_InfoData id; while (cursor.readNext(id)) { //printf("0x%08x, level = %d, id.code = %d, id.tag = %d\n", // (unsigned char*)cu + id.entryOff - (unsigned char*)img.debug_info, cursor.level, id.code, id.tag); switch (id.tag) { case DW_TAG_base_type: case DW_TAG_typedef: case DW_TAG_pointer_type: case DW_TAG_subroutine_type: case DW_TAG_array_type: case DW_TAG_const_type: case DW_TAG_structure_type: case DW_TAG_reference_type: case DW_TAG_class_type: case DW_TAG_enumeration_type: case DW_TAG_string_type: case DW_TAG_union_type: case DW_TAG_ptr_to_member_type: case DW_TAG_set_type: case DW_TAG_subrange_type: case DW_TAG_file_type: case DW_TAG_packed_type: case DW_TAG_thrown_type: case DW_TAG_volatile_type: case DW_TAG_restrict_type: // DWARF3 case DW_TAG_interface_type: case DW_TAG_unspecified_type: case DW_TAG_mutable_type: // withdrawn case DW_TAG_shared_type: case DW_TAG_rvalue_reference_type: mapOffsetToType.insert(std::make_pair(id.entryPtr, typeID)); typeID++; } } off += sizeof(cu->unit_length) + cu->unit_length; } nextDwarfType = typeID; return true; } bool CV2PDB::createTypes() { mspdb::Mod* mod = globalMod(); int typeID = nextUserType; int pointerAttr = img.isX64() ? 0x1000C : 0x800A; unsigned long off = 0; while (off < img.debug_info_length) { DWARF_CompilationUnit* cu = (DWARF_CompilationUnit*)(img.debug_info + off); DIECursor cursor(cu, (byte*)cu + sizeof(DWARF_CompilationUnit)); DWARF_InfoData id; while (cursor.readNext(id)) { //printf("0x%08x, level = %d, id.code = %d, id.tag = %d\n", // (unsigned char*)cu + id.entryOff - (unsigned char*)img.debug_info, cursor.level, id.code, id.tag); if (id.specification) { DIECursor specCursor(cu, id.specification); DWARF_InfoData idspec; specCursor.readNext(idspec); assert(id.tag == idspec.tag); id.merge(idspec); } int cvtype = -1; switch (id.tag) { case DW_TAG_base_type: cvtype = addDWARFBasicType(id.name, id.encoding, id.byte_size); break; case DW_TAG_typedef: cvtype = appendModifierType(getTypeByDWARFPtr(cu, id.type), 0); addUdtSymbol(cvtype, id.name); break; case DW_TAG_pointer_type: cvtype = appendPointerType(getTypeByDWARFPtr(cu, id.type), pointerAttr); break; case DW_TAG_const_type: cvtype = appendModifierType(getTypeByDWARFPtr(cu, id.type), 1); break; case DW_TAG_reference_type: cvtype = appendPointerType(getTypeByDWARFPtr(cu, id.type), pointerAttr | 0x20); break; case DW_TAG_class_type: case DW_TAG_structure_type: case DW_TAG_union_type: cvtype = addDWARFStructure(id, cu, cursor.getSubtreeCursor()); break; case DW_TAG_array_type: cvtype = addDWARFArray(id, cu, cursor.getSubtreeCursor()); break; case DW_TAG_subroutine_type: case DW_TAG_subrange_type: case DW_TAG_enumeration_type: case DW_TAG_string_type: case DW_TAG_ptr_to_member_type: case DW_TAG_set_type: case DW_TAG_file_type: case DW_TAG_packed_type: case DW_TAG_thrown_type: case DW_TAG_volatile_type: case DW_TAG_restrict_type: // DWARF3 case DW_TAG_interface_type: case DW_TAG_unspecified_type: case DW_TAG_mutable_type: // withdrawn case DW_TAG_shared_type: case DW_TAG_rvalue_reference_type: cvtype = appendPointerType(0x74, pointerAttr); break; case DW_TAG_subprogram: if (id.name && id.pclo && id.pchi) { addDWARFProc(id, cu, cursor.getSubtreeCursor()); int rc = mod->AddPublic2(id.name, img.codeSegment + 1, id.pclo - codeSegOff, 0); } break; case DW_TAG_compile_unit: #if !FULL_CONTRIB if (id.dir && id.name) { if (id.ranges != -1 && id.ranges < img.debug_ranges_length) { unsigned char* r = (unsigned char*)img.debug_ranges + id.ranges; unsigned char* rend = (unsigned char*)img.debug_ranges + img.debug_ranges_length; while (r < rend) { unsigned long pclo = RD4(r); unsigned long pchi = RD4(r); if (pclo == 0 && pchi == 0) break; //printf("%s %s %x - %x\n", dir, name, pclo, pchi); if (!addDWARFSectionContrib(mod, pclo, pchi)) return false; } } else { //printf("%s %s %x - %x\n", dir, name, pclo, pchi); if (!addDWARFSectionContrib(mod, id.pclo, id.pchi)) return false; } } #endif break; case DW_TAG_variable: if (id.name) { int seg = -1; unsigned long segOff; if (id.location.type == Invalid && id.external && id.linkage_name) { seg = img.findSymbol(id.linkage_name, segOff); } else { Location loc = decodeLocation(id.location); if (loc.is_abs()) { segOff = loc.off; seg = img.findSection(segOff); if (seg >= 0) segOff -= img.getImageBase() + img.getSection(seg).VirtualAddress; } } if (seg >= 0) { int type = getTypeByDWARFPtr(cu, id.type); appendGlobalVar(id.name, type, seg + 1, segOff); int rc = mod->AddPublic2(id.name, seg + 1, segOff, type); } } break; case DW_TAG_formal_parameter: case DW_TAG_unspecified_parameters: case DW_TAG_inheritance: case DW_TAG_member: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: default: break; } if (cvtype >= 0) { assert(cvtype == typeID); typeID++; assert(mapOffsetToType[id.entryPtr] == cvtype); } } off += sizeof(cu->unit_length) + cu->unit_length; } return true; } bool CV2PDB::createDWARFModules() { if(!img.debug_info) return setError("no .debug_info section found"); codeSegOff = img.getImageBase() + img.getSection(img.codeSegment).VirtualAddress; mspdb::Mod* mod = globalMod(); for (int s = 0; s < img.countSections(); s++) { const IMAGE_SECTION_HEADER& sec = img.getSection(s); int rc = dbi->AddSec(s + 1, 0x10d, 0, sec.SizeOfRawData); if (rc <= 0) return setError("cannot add section"); } #define FULL_CONTRIB 1 #if FULL_CONTRIB // we use a single global module, so we can simply add the whole text segment int segFlags = 0x60101020; // 0x40401040, 0x60500020; // TODO int s = img.codeSegment; int pclo = 0; // img.getImageBase() + img.getSection(s).VirtualAddress; int pchi = pclo + img.getSection(s).Misc.VirtualSize; int rc = mod->AddSecContrib(s + 1, pclo, pchi - pclo, segFlags); if (rc <= 0) return setError("cannot add section contribution to module"); #endif checkUserTypeAlloc(); *(DWORD*) userTypes = 4; cbUserTypes = 4; createEmptyFieldListType(); if(Dversion > 0) { appendComplex(0x50, 0x40, 4, "cfloat"); appendComplex(0x51, 0x41, 8, "cdouble"); appendComplex(0x52, 0x42, 12, "creal"); } DIECursor::setContext(&img); countEntries = 0; if (!mapTypes()) return false; if (!createTypes()) return false; /* if(!iterateDWARFDebugInfo(kOpMapTypes)) return false; if(!iterateDWARFDebugInfo(kOpCreateTypes)) return false; */ #if 0 modules = new mspdb::Mod* [countEntries]; memset (modules, 0, countEntries * sizeof(*modules)); for (int m = 0; m < countEntries; m++) { mspdb::Mod* mod = globalMod(); } #endif if(cbUserTypes > 0 || cbDwarfTypes) { if(dwarfTypes) { checkUserTypeAlloc(cbDwarfTypes); memcpy(userTypes + cbUserTypes, dwarfTypes, cbDwarfTypes); cbUserTypes += cbDwarfTypes; cbDwarfTypes = 0; } int rc = mod->AddTypes(userTypes, cbUserTypes); if (rc <= 0) return setError("cannot add type info to module"); } return true; } bool isRelativePath(const std::string& s) { if(s.length() < 1) return true; if(s[0] == '/' || s[0] == '\\') return false; if(s.length() < 2) return true; if(s[1] == ':') return false; return true; } static int cmpAdr(const void* s1, const void* s2) { const mspdb::LineInfoEntry* e1 = (const mspdb::LineInfoEntry*) s1; const mspdb::LineInfoEntry* e2 = (const mspdb::LineInfoEntry*) s2; return e1->offset - e2->offset; } bool _flushDWARFLines(CV2PDB* cv2pdb, DWARF_LineState& state) { if(state.lineInfo.size() == 0) return true; unsigned int saddr = state.lineInfo[0].offset; unsigned int eaddr = state.lineInfo.back().offset; int segIndex = cv2pdb->img.findSection(saddr + state.seg_offset); if(segIndex < 0) { // throw away invalid lines (mostly due to "set address to 0") state.lineInfo.resize(0); return true; //return false; } // if(saddr >= 0x4000) // return true; const DWARF_FileName* dfn; if(state.file == 0) dfn = state.file_ptr; else if(state.file > 0 && state.file <= state.files.size()) dfn = &state.files[state.file - 1]; else return false; std::string fname = dfn->file_name; if(isRelativePath(fname) && dfn->dir_index > 0 && dfn->dir_index <= state.include_dirs.size()) { std::string dir = state.include_dirs[dfn->dir_index - 1]; if(dir.length() > 0 && dir[dir.length() - 1] != '/' && dir[dir.length() - 1] != '\\') dir.append("\\"); fname = dir + fname; } for(size_t i = 0; i < fname.length(); i++) if(fname[i] == '/') fname[i] = '\\'; mspdb::Mod* mod = cv2pdb->globalMod(); #if 1 bool dump = false; // (fname == "cvtest.d"); //qsort(&state.lineInfo[0], state.lineInfo.size(), sizeof(state.lineInfo[0]), cmpAdr); #if 0 printf("%s:\n", fname.c_str()); for(size_t ln = 0; ln < state.lineInfo.size(); ln++) printf(" %08x: %4d\n", state.lineInfo[ln].offset + 0x401000, state.lineInfo[ln].line); #endif unsigned int firstLine = state.lineInfo[0].line; unsigned int firstAddr = state.lineInfo[0].offset; unsigned int firstEntry = 0; unsigned int entry = 0; for(size_t ln = firstEntry; ln < state.lineInfo.size(); ln++) { if(state.lineInfo[ln].line < firstLine || state.lineInfo[ln].offset < firstAddr) { if(ln > firstEntry) { unsigned int length = state.lineInfo[entry-1].offset + 1; // firstAddr has been subtracted before if(dump) printf("AddLines(%08x+%04x, Line=%4d+%3d, %s)\n", firstAddr, length, firstLine, entry - firstEntry, fname.c_str()); int rc = mod->AddLines(fname.c_str(), segIndex + 1, firstAddr, length, firstAddr, firstLine, (unsigned char*) &state.lineInfo[firstEntry], (ln - firstEntry) * sizeof(state.lineInfo[0])); firstLine = state.lineInfo[ln].line; firstAddr = state.lineInfo[ln].offset; firstEntry = entry; } } else if(ln > firstEntry && state.lineInfo[ln].offset == state.lineInfo[ln-1].offset) continue; // skip entries without offset change state.lineInfo[entry].line = state.lineInfo[ln].line - firstLine; state.lineInfo[entry].offset = state.lineInfo[ln].offset - firstAddr; entry++; } unsigned int length = eaddr - firstAddr; if(dump) printf("AddLines(%08x+%04x, Line=%4d+%3d, %s)\n", firstAddr, length, firstLine, entry - firstEntry, fname.c_str()); int rc = mod->AddLines(fname.c_str(), segIndex + 1, firstAddr, length, firstAddr, firstLine, (unsigned char*) &state.lineInfo[firstEntry], (entry - firstEntry) * sizeof(state.lineInfo[0])); #else unsigned int firstLine = 0; unsigned int firstAddr = 0; int rc = mod->AddLines(fname.c_str(), segIndex + 1, saddr, eaddr - saddr, firstAddr, firstLine, (unsigned char*) &state.lineInfo[0], state.lineInfo.size() * sizeof(state.lineInfo[0])); #endif state.lineInfo.resize(0); return rc > 0; } bool CV2PDB::addDWARFLines() { if(!img.debug_line) return setError("no .debug_line section found"); mspdb::Mod* mod = globalMod(); for(unsigned long off = 0; off < img.debug_line_length; ) { DWARF_LineNumberProgramHeader* hdr = (DWARF_LineNumberProgramHeader*) (img.debug_line + off); int length = hdr->unit_length; if(length < 0) break; length += sizeof(length); unsigned char* p = (unsigned char*) (hdr + 1); unsigned char* end = (unsigned char*) hdr + length; std::vector<unsigned int> opcode_lengths; opcode_lengths.resize(hdr->opcode_base); opcode_lengths[0] = 0; for(int o = 1; o < hdr->opcode_base && p < end; o++) opcode_lengths[o] = LEB128(p); DWARF_LineState state; state.seg_offset = img.getImageBase() + img.getSection(img.codeSegment).VirtualAddress; // dirs while(p < end) { if(*p == 0) break; state.include_dirs.push_back((const char*) p); p += strlen((const char*) p) + 1; } p++; // files DWARF_FileName fname; while(p < end && *p) { fname.read(p); state.files.push_back(fname); } p++; std::vector<mspdb::LineInfoEntry> lineInfo; state.init(hdr); while(p < end) { int opcode = *p++; if(opcode >= hdr->opcode_base) { // special opcode int adjusted_opcode = opcode - hdr->opcode_base; int operation_advance = adjusted_opcode / hdr->line_range; state.advance_addr(hdr, operation_advance); int line_advance = hdr->line_base + (adjusted_opcode % hdr->line_range); state.line += line_advance; state.addLineInfo(); state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; } else { switch(opcode) { case 0: // extended { int exlength = LEB128(p); unsigned char* q = p + exlength; int excode = *p++; switch(excode) { case DW_LNE_end_sequence: if((char*)p - img.debug_line >= 0xe4e0) p = p; state.end_sequence = true; state.last_addr = state.address; state.addLineInfo(); if(!_flushDWARFLines(this, state)) return setError("cannot add line number info to module"); state.init(hdr); break; case DW_LNE_set_address: if(unsigned long adr = RD4(p)) state.address = adr; else state.address = state.last_addr; // strange adr 0 for templates? state.op_index = 0; break; case DW_LNE_define_file: fname.read(p); state.file_ptr = &fname; state.file = 0; break; case DW_LNE_set_discriminator: state.discriminator = LEB128(p); break; } p = q; } break; case DW_LNS_copy: state.addLineInfo(); state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; break; case DW_LNS_advance_pc: state.advance_addr(hdr, LEB128(p)); break; case DW_LNS_advance_line: state.line += SLEB128(p); break; case DW_LNS_set_file: if(!_flushDWARFLines(this, state)) return setError("cannot add line number info to module"); state.file = LEB128(p); break; case DW_LNS_set_column: state.column = LEB128(p); break; case DW_LNS_negate_stmt: state.is_stmt = !state.is_stmt; break; case DW_LNS_set_basic_block: state.basic_block = true; break; case DW_LNS_const_add_pc: state.advance_addr(hdr, (255 - hdr->opcode_base) / hdr->line_range); break; case DW_LNS_fixed_advance_pc: state.address += RD2(p); state.op_index = 0; break; case DW_LNS_set_prologue_end: state.prologue_end = true; break; case DW_LNS_set_epilogue_begin: state.epilogue_end = true; break; case DW_LNS_set_isa: state.isa = LEB128(p); break; default: // unknown standard opcode for(unsigned int arg = 0; arg < opcode_lengths[opcode]; arg++) LEB128(p); break; } } } if(!_flushDWARFLines(this, state)) return setError("cannot add line number info to module"); off += length; } return true; } bool CV2PDB::relocateDebugLineInfo() { if(!img.reloc || !img.reloc_length) return true; unsigned int img_base = 0x400000; char* relocbase = img.reloc; char* relocend = img.reloc + img.reloc_length; while(relocbase < relocend) { unsigned int virtadr = *(unsigned int *) relocbase; unsigned int chksize = *(unsigned int *) (relocbase + 4); char* p = img.RVA<char> (virtadr, 1); if(p >= img.debug_line && p < img.debug_line + img.debug_line_length) { for (unsigned int w = 8; w < chksize; w += 2) { unsigned short entry = *(unsigned short*)(relocbase + w); unsigned short type = (entry >> 12) & 0xf; unsigned short off = entry & 0xfff; if(type == 3) // HIGHLOW { *(long*) (p + off) += img_base; } } } if(chksize == 0 || chksize >= img.reloc_length) break; relocbase += chksize; } return true; } bool CV2PDB::addDWARFPublics() { mspdb::Mod* mod = globalMod(); int type = 0; int rc = mod->AddPublic2("public_all", img.codeSegment + 1, 0, 0x1000); if (rc <= 0) return setError("cannot add public"); return true; } bool CV2PDB::writeDWARFImage(const TCHAR* opath) { int len = sizeof(*rsds) + strlen((char*)(rsds + 1)) + 1; if (!img.replaceDebugSection(rsds, len, false)) return setError(img.getLastError()); if (!img.save(opath)) return setError(img.getLastError()); return true; }
28.291009
121
0.627603
[ "vector", "3d" ]
a074a2bb86075e520eb05a473338c8d8fa6ba69f
6,980
cpp
C++
source/gomaengine/aplication.cpp
FelipeOrtuzar/CraftEngine
a14549f3e6cbdc30cbc09503c600b8acba504853
[ "MIT" ]
2
2022-03-05T03:04:25.000Z
2022-03-05T03:04:50.000Z
source/gomaengine/aplication.cpp
dantros/CraftEngine
a14549f3e6cbdc30cbc09503c600b8acba504853
[ "MIT" ]
null
null
null
source/gomaengine/aplication.cpp
dantros/CraftEngine
a14549f3e6cbdc30cbc09503c600b8acba504853
[ "MIT" ]
1
2022-02-28T03:47:08.000Z
2022-02-28T03:47:08.000Z
#include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/System.hpp> #include <iostream> #include <string> #include "aplication.h" #include "root_directory.h" namespace gomaengine { int Aplication::update() { sf::RenderWindow window(sf::VideoMode(window_app.window_size_x, window_app.window_size_y), "My window"); sf::View terrain_view(sf::Vector2f(window_app.window_size_x/2.f, window_app.window_size_y / 2.f), sf::Vector2f(window_app.window_size_x , window_app.window_size_y)); //sf::View down_ui_view(sf::Vector2f(50, 50), sf::Vector2f(100, 100)); //terrain_view.setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f)); //down_ui_view.setViewport(sf::FloatRect(0.75f, 0.f, 0.25f, 0.25f)); window.setFramerateLimit(60); GameObject* clicked_model = nullptr; //LOADING THE TEXTURES for (GameObject* model : model_vct) { model->get_texture().load_resources(); } /*for (Model* model : model_vct) { model->get_sound_component()->reload_sound(); }*/ //MUSIC sf::Music music; if (!music.openFromFile(getPath("assets/sounds/field_theme_1.wav").string())) printf("Could load music"); music.setLoop(true); music.play(); //FONTS 1 sf::Font font; if (!font.loadFromFile("C:\\Windows\\Fonts\\comic.ttf")) { printf("Couldn't load font"); } //TEXTO2 //fonts sf::Text text2; // select the font text2.setFont(font); // font is a sf::Font // set the string to display text2.setString("Clicked object: None"); // set the character size text2.setCharacterSize(24); text2.setPosition(800.0, 10.0); //TEXTO3 sf::Text text3; // select the font text3.setFont(font); // font is a sf::Font // set the string to display text3.setString("FPS: None"); // set the character size text3.setCharacterSize(24); text3.setPosition(50.0, 10.0); sf::Time elapsed_time = sf::seconds(0); // run the program as long as the window is open while (window.isOpen()) { // Se toma el tiempo sf::Clock clock; // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: // window closed window.close(); case sf::Event::KeyPressed: // key pressed if (event.key.code == sf::Keyboard::Escape) { window.close(); } if (event.key.code == sf::Keyboard::P) { if (!music.openFromFile(getPath("assets/sounds/background_musicwav.wav").string())) printf("Could load music"); music.setLoop(true); music.play(); } if (event.key.code == sf::Keyboard::O) { if (!music.openFromFile(getPath("assets/sounds/field_theme_1.wav").string())) printf("Could load music"); music.setLoop(true); music.play(); } if (event.key.code == sf::Keyboard::A) { terrain_view.move(-20.f, 0.f); } if (event.key.code == sf::Keyboard::S) { terrain_view.move(0.f, 20.f); } if (event.key.code == sf::Keyboard::D) { terrain_view.move(20.f, 0.f); } if (event.key.code == sf::Keyboard::W) { terrain_view.move(0.f, -20.f); } default: break; } } if (!(this->was_Mouse_Left_pressed_before) && sf::Mouse::isButtonPressed(sf::Mouse::Left)) { text2.setString("Left mouse key has been pressed."); if (!model_vct.empty()) { Vector local_position = Vector::to_Vector(sf::Mouse::getPosition(window)); float min_radio = 35.0f; float min_distance = 100000000.0f; GameObject* min_model = nullptr; // left mouse button is pressed for (GameObject* model : model_vct) { float actual_dist = Vector::distance(model->get_position(), local_position); min_model = min_radio > actual_dist ? model : min_model; } clicked_model = min_model; } if (clicked_model != nullptr) { std::string one_text = "Clicked object's name: "; one_text.append(clicked_model->get_name()); text2.setString(one_text); clicked_model->is_clicked(); } } if (!(this->was_Mouse_Right_pressed_before) && sf::Mouse::isButtonPressed(sf::Mouse::Right)) { text2.setString("Right mouse key has been pressed."); if (clicked_model != nullptr) { Vector mouse_pos = Vector::to_Vector(sf::Mouse::getPosition(window)); clicked_model->set_target(mouse_pos); } } //Updating MovableComponent for (GameObject* model : model_vct) { //model->get_position().print(); } //model_vct.at(2)->set_position((Vector::to_Vector(sf::Mouse::getPosition())).sum(Vector(-90.0, -120.0))); window.clear(sf::Color::Cyan); //////////////UPDATE//////////////////// for (GameObject* model : model_vct) { model->update(this->previous_dt, window); } this->was_Mouse_Left_pressed_before = sf::Mouse::isButtonPressed(sf::Mouse::Left); this->was_Mouse_Right_pressed_before = sf::Mouse::isButtonPressed(sf::Mouse::Right); //TEXT window.draw(text2); window.draw(text3); window.setView(terrain_view); //window.setView(down_ui_view); window.display(); //TIME sf::Time elapsed_time = clock.getElapsedTime(); int fps_f = (int) 1.0 / elapsed_time.asMilliseconds() ; previous_dt = fps_f; std::string fps_s = "FPS: "; std::string fps = std::to_string(fps_f); text3.setString(fps_s + fps ); } return 0; } Aplication::Aplication(Window _window, std::vector<GameObject*> _model_vct){ this->window_app = _window; this->model_vct = _model_vct; } }
33.883495
118
0.517049
[ "object", "vector", "model" ]
a0769226d305b698d15694a25bef3fa014e55301
6,452
hpp
C++
video/src/d3d11/shader.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
2
2020-11-19T03:23:35.000Z
2021-02-25T03:34:40.000Z
video/src/d3d11/shader.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
video/src/d3d11/shader.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
/******************************************************************************* MIT License Copyright (c) 2021 Romain Vinders 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 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. -------------------------------------------------------------------------------- Implementation included in renderer.cpp (grouped object improves compiler optimizations + greatly reduces executable size) *******************************************************************************/ #if defined(_WINDOWS) && defined(_VIDEO_D3D11_SUPPORT) // includes + namespaces: in renderer.cpp // -- create/compile shaders -- ------------------------------------------------ # ifdef _P_VIDEO_SHADER_COMPILERS // Get D3D11 shader model ID static const char* __getShaderModel(ShaderType type) noexcept { switch (type) { case ShaderType::vertex: return "vs_5_0"; case ShaderType::tessCtrl: return "hs_5_0"; case ShaderType::tessEval: return "ds_5_0"; case ShaderType::geometry: return "gs_5_0"; case ShaderType::fragment: return "ps_5_0"; case ShaderType::compute: return "cs_5_0"; default: return ""; } } // Compile shader from text content Shader::Builder Shader::Builder::compile(ShaderType type, const char* textContent, size_t length, const char* entryPoint, bool isStrict) { ID3DBlob* errorMessage = nullptr; ID3DBlob* shaderBuffer = nullptr; const char* shaderModel = __getShaderModel(type); HRESULT result = D3DCompile((LPCVOID)textContent, (SIZE_T)length, nullptr, nullptr, nullptr, entryPoint, shaderModel, isStrict ? D3DCOMPILE_ENABLE_STRICTNESS : 0, 0, &shaderBuffer, &errorMessage); if (FAILED(result)) throwShaderError(errorMessage, "Shader: compile error", shaderModel); return Shader::Builder(type, shaderBuffer); } // Compile shader from text file Shader::Builder Shader::Builder::compileFromFile(ShaderType type, const wchar_t* filePath, const char* entryPoint, bool isStrict) { ID3DBlob* errorMessage = nullptr; ID3DBlob* shaderBuffer = nullptr; const char* shaderModel = __getShaderModel(type); HRESULT result = D3DCompileFromFile(filePath, nullptr, nullptr, entryPoint, shaderModel, isStrict ? D3DCOMPILE_ENABLE_STRICTNESS : 0, 0, &shaderBuffer, &errorMessage); if (FAILED(result)) throwShaderError(errorMessage, "Shader: file/compile error", shaderModel); return Shader::Builder(type, shaderBuffer); } # endif // -- create shader objects -- ------------------------------------------------- // Create shader object Shader Shader::Builder::createShader(DeviceResourceManager device) const { HRESULT result; Shader::Handle handle = nullptr; switch (this->_type) { case ShaderType::vertex: result = device->CreateVertexShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11VertexShader**)&handle); break; case ShaderType::tessCtrl: result = device->CreateHullShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11HullShader**)&handle); break; case ShaderType::tessEval: result = device->CreateDomainShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11DomainShader**)&handle); break; case ShaderType::geometry: result = device->CreateGeometryShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11GeometryShader**)&handle); break; case ShaderType::fragment: result = device->CreatePixelShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11PixelShader**)&handle); break; default: result = device->CreateComputeShader((const void*)this->_data, (SIZE_T)this->_length, nullptr, (ID3D11ComputeShader**)&handle); break; } if (FAILED(result) || handle == nullptr) throwError(result, "Shader: creation error"); return Shader(handle, this->_type); } // Destroy shader object void Shader::release() noexcept { if (this->_handle != nullptr) { try { switch (this->_type) { case ShaderType::vertex: ((ID3D11VertexShader*)this->_handle)->Release(); break; case ShaderType::tessCtrl: ((ID3D11HullShader*)this->_handle)->Release(); break; case ShaderType::tessEval: ((ID3D11DomainShader*)this->_handle)->Release(); break; case ShaderType::geometry: ((ID3D11GeometryShader*)this->_handle)->Release(); break; case ShaderType::fragment: ((ID3D11PixelShader*)this->_handle)->Release(); break; case ShaderType::compute: ((ID3D11ComputeShader*)this->_handle)->Release(); break; default: break; } this->_handle = nullptr; } catch (...) {} } } // --- // Create input layout for shader object InputLayout Shader::Builder::createInputLayout(DeviceResourceManager device, D3D11_INPUT_ELEMENT_DESC* layoutElements, size_t length) const { ID3D11InputLayout* inputLayout = nullptr; HRESULT result = device->CreateInputLayout((D3D11_INPUT_ELEMENT_DESC*)layoutElements, (UINT)length, (const void*)this->_data, (SIZE_T)this->_length, &inputLayout); if (FAILED(result) || inputLayout == nullptr) throwError(result, "Shader: layout creation error"); return InputLayout((InputLayoutHandle)inputLayout); } #endif
48.511278
143
0.643366
[ "geometry", "object", "model" ]
a07a7785f529759bdf136e47a850f1903107f077
1,755
hpp
C++
integration/vertex/VertexData.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
19
2020-02-02T16:36:46.000Z
2021-12-25T07:02:28.000Z
integration/vertex/VertexData.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
103
2020-10-13T09:03:42.000Z
2022-03-26T03:41:50.000Z
integration/vertex/VertexData.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
5
2020-03-13T06:14:37.000Z
2021-12-12T02:13:46.000Z
/// /// VertexData.hpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #ifndef GALAXY_GRAPHICS_VERTEX_VERTEXDATA_HPP_ #define GALAXY_GRAPHICS_VERTEX_VERTEXDATA_HPP_ #include "galaxy/graphics/vertex/VertexArray.hpp" namespace galaxy { namespace graphics { /// /// Provides a class with a method of rendering to screen. /// class VertexData { public: /// /// Constructor. /// VertexData() noexcept = default; /// /// Move constructor. /// VertexData(VertexData&&) noexcept; /// /// Move assignment operator. /// VertexData& operator=(VertexData&&) noexcept; /// /// Virtual destructor. /// virtual ~VertexData() noexcept = default; /// /// Get IBO. /// /// \return Reference to IBO. /// [[nodiscard]] IndexBuffer& get_ibo() noexcept; /// /// Get VBO. /// /// \return Reference to VBO. /// [[nodiscard]] VertexBuffer& get_vbo() noexcept; /// /// Get VAO. /// /// \return Reference to VAO. /// [[nodiscard]] VertexArray& get_vao() noexcept; /// /// Get index count. /// /// \return Const unsigned integer. /// [[nodiscard]] const unsigned int index_count() const noexcept; protected: /// /// OpenGL Vertex Array Object. /// VertexArray m_va; /// /// Vertex buffer. /// VertexBuffer m_vb; /// /// Index (Element) buffer. /// IndexBuffer m_ib; /// /// Vertex layout. /// VertexLayout m_layout; private: /// /// Copy constructor. /// VertexData(const VertexData&) = delete; /// /// Copy assignment operator. /// VertexData& operator=(const VertexData&) = delete; }; } // namespace graphics } // namespace galaxy #endif
16.556604
65
0.584046
[ "object" ]
a07f4ee1a69083e1b4c4d515d1cbc676ad1aa997
22,737
hpp
C++
Ipopt-releases-3.12.7/Ipopt/examples/ScalableProblems/MittelmannDistCntrlNeumB.hpp
cw26378/Project-Motion-Predictive-Control
f589ea443644e627a75eaf8b991ccd70b5e38de8
[ "MIT" ]
null
null
null
Ipopt-releases-3.12.7/Ipopt/examples/ScalableProblems/MittelmannDistCntrlNeumB.hpp
cw26378/Project-Motion-Predictive-Control
f589ea443644e627a75eaf8b991ccd70b5e38de8
[ "MIT" ]
null
null
null
Ipopt-releases-3.12.7/Ipopt/examples/ScalableProblems/MittelmannDistCntrlNeumB.hpp
cw26378/Project-Motion-Predictive-Control
f589ea443644e627a75eaf8b991ccd70b5e38de8
[ "MIT" ]
null
null
null
// Copyright (C) 2005, 2006 International Business Machines and others. // All Rights Reserved. // This code is published under the Eclipse Public License. // // $Id$ // // Authors: Andreas Waechter IBM 2005-10-18 // based on MyNLP.hpp #ifndef __MITTELMANNDISTRCNTRLNEUMB_HPP__ #define __MITTELMANNDISTRCNTRLNEUMB_HPP__ #include "IpTNLP.hpp" #include "RegisteredTNLP.hpp" #ifdef HAVE_CONFIG_H #include "config.h" #else #include "configall_system.h" #endif #ifdef HAVE_CMATH # include <cmath> #else # ifdef HAVE_MATH_H # include <math.h> # else # error "don't have header file for math" # endif #endif #ifdef HAVE_CSTDIO # include <cstdio> #else # ifdef HAVE_STDIO_H # include <stdio.h> # else # error "don't have header file for stdio" # endif #endif using namespace Ipopt; /** Base class for distributed control problems with homogeneous * Neumann boundary conditions, as formulated by Hans Mittelmann as * Examples 4-6 in "Optimization Techniques for Solving Elliptic * Control Problems with Control and State Constraints. Part 2: * Distributed Control" */ class MittelmannDistCntrlNeumBBase : public RegisteredTNLP { public: /** Constructor. N is the number of mesh points in one dimension * (excluding boundary). */ MittelmannDistCntrlNeumBBase(); /** Default destructor */ virtual ~MittelmannDistCntrlNeumBBase(); /**@name Overloaded from TNLP */ //@{ /** Method to return some info about the nlp */ virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, Index& nnz_h_lag, IndexStyleEnum& index_style); /** Method to return the bounds for my problem */ virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u); /** Method to return the starting point for the algorithm */ virtual bool get_starting_point(Index n, bool init_x, Number* x, bool init_z, Number* z_L, Number* z_U, Index m, bool init_lambda, Number* lambda); /** Method to return the objective value */ virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); /** Method to return the gradient of the objective */ virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); /** Method to return the constraint residuals */ virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); /** Method to return: * 1) The structure of the jacobian (if "values" is NULL) * 2) The values of the jacobian (if "values" is not NULL) */ virtual bool eval_jac_g(Index n, const Number* x, bool new_x, Index m, Index nele_jac, Index* iRow, Index *jCol, Number* values); /** Method to return: * 1) The structure of the hessian of the lagrangian (if "values" is NULL) * 2) The values of the hessian of the lagrangian (if "values" is not NULL) */ virtual bool eval_h(Index n, const Number* x, bool new_x, Number obj_factor, Index m, const Number* lambda, bool new_lambda, Index nele_hess, Index* iRow, Index* jCol, Number* values); //@} /** Method for returning scaling parameters */ virtual bool get_scaling_parameters(Number& obj_scaling, bool& use_x_scaling, Index n, Number* x_scaling, bool& use_g_scaling, Index m, Number* g_scaling); /** @name Solution Methods */ //@{ /** This method is called after the optimization, and could write an * output file with the optimal profiles */ virtual void finalize_solution(SolverReturn status, Index n, const Number* x, const Number* z_L, const Number* z_U, Index m, const Number* g, const Number* lambda, Number obj_value, const IpoptData* ip_data, IpoptCalculatedQuantities* ip_cq); //@} protected: /** Method for setting the internal parameters that define the * problem. It must be called by the child class in its * implementation of InitializeParameters. */ void SetBaseParameters(Index N, Number lb_y, Number ub_y, Number lb_u, Number ub_u, Number b_0j, Number b_1j, Number b_i0, Number b_i1, Number u_init); /**@name Functions that defines a particular instance. */ //@{ /** Target profile function for y (and initial guess function) */ virtual Number y_d_cont(Number x1, Number x2) const =0; /** Integrant in objective function */ virtual Number fint_cont(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of fint_cont w.r.t. y */ virtual Number fint_cont_dy(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of fint_cont w.r.t. u */ virtual Number fint_cont_du(Number x1, Number x2, Number y, Number u) const =0; /** Second partial derivative of fint_cont w.r.t. y,y */ virtual Number fint_cont_dydy(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of fint_cont * w.r.t. y,y is always zero. */ virtual bool fint_cont_dydy_alwayszero() const =0; /** Second partial derivative of fint_cont w.r.t. u,u */ virtual Number fint_cont_dudu(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of fint_cont * w.r.t. u,u is always zero. */ virtual bool fint_cont_dudu_alwayszero() const =0; /** Second partial derivative of fint_cont w.r.t. y,u */ virtual Number fint_cont_dydu(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of fint_cont * w.r.t. y,u is always zero. */ virtual bool fint_cont_dydu_alwayszero() const =0; /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of forcing function w.r.t. u */ virtual Number d_cont_du(Number x1, Number x2, Number y, Number u) const =0; /** Second partial derivative of forcing function w.r.t. y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const =0; /** Second partial derivative of forcing function w.r.t. u,u */ virtual Number d_cont_dudu(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dudu_alwayszero() const =0; /** Second partial derivative of forcing function w.r.t. y,u */ virtual Number d_cont_dydu(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of d_cont * w.r.t. y,u is always zero. */ virtual bool d_cont_dydu_alwayszero() const =0; //@} private: /**@name Methods to block default compiler methods. * The compiler automatically generates the following three methods. * Since the default compiler implementation is generally not what * you want (for all but the most simple classes), we usually * put the declarations of these methods in the private section * and never implement them. This prevents the compiler from * implementing an incorrect "default" behavior without us * knowing. (See Scott Meyers book, "Effective C++") * */ //@{ MittelmannDistCntrlNeumBBase(const MittelmannDistCntrlNeumBBase&); MittelmannDistCntrlNeumBBase& operator=(const MittelmannDistCntrlNeumBBase&); //@} /**@name Problem specification */ //@{ /** Number of mesh points in one dimension (excluding boundary) */ Index N_; /** Step size */ Number h_; /** h_ squaredd */ Number hh_; /** overall lower bound on y */ Number lb_y_; /** overall upper bound on y */ Number ub_y_; /** overall lower bound on u */ Number lb_u_; /** overall upper bound on u */ Number ub_u_; /** Value of beta function (in Neumann boundary condition) for * (0,x2) bounray */ Number b_0j_; /** Value of beta function (in Neumann boundary condition) for * (1,x2) bounray */ Number b_1j_; /** Value of beta function (in Neumann boundary condition) for * (x1,0) bounray */ Number b_i0_; /** Value of beta function (in Neumann boundary condition) for * (x1,1) bounray */ Number b_i1_; /** Initial value for the constrols u */ Number u_init_; /** Array for the target profile for y */ Number* y_d_; //@} /**@name Auxilliary methods */ //@{ /** Translation of mesh point indices to NLP variable indices for * y(x_ij) */ inline Index y_index(Index i, Index j) const { return j + (N_+2)*i; } /** Translation of mesh point indices to NLP variable indices for * u(x_ij) */ inline Index u_index(Index i, Index j) const { return (N_+2)*(N_+2) + (j-1) + (N_)*(i-1); } /** Translation of interior mesh point indices to the corresponding * PDE constraint number */ inline Index pde_index(Index i, Index j) const { return (j-1) + N_*(i-1); } /** Compute the grid coordinate for given index in x1 direction */ inline Number x1_grid(Index i) const { return h_*(Number)i; } /** Compute the grid coordinate for given index in x2 direction */ inline Number x2_grid(Index i) const { return h_*(Number)i; } //@} }; /** Class implementating Example 4 */ class MittelmannDistCntrlNeumB1 : public MittelmannDistCntrlNeumBBase { public: MittelmannDistCntrlNeumB1() : pi_(4.*atan(1.)), alpha_(0.001) {} virtual ~MittelmannDistCntrlNeumB1() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number lb_y = -1e20; Number ub_y = 0.371; Number lb_u = -8.; Number ub_u = 9.; Number b_0j = 1.; Number b_1j = 1.; Number b_i0 = 1.; Number b_i1 = 1.; Number u_init = (ub_u + lb_u)/2.; SetBaseParameters(N, lb_y, ub_y, lb_u, ub_u, b_0j, b_1j, b_i0, b_i1, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return sin(2.*pi_*x1)*sin(2.*pi_*x2); } /** Integrant in objective function */ virtual Number fint_cont(Number x1, Number x2, Number y, Number u) const { Number diff_y = y-y_d_cont(x1,x2); return 0.5*(diff_y*diff_y + alpha_*u*u); } /** First partial derivative of fint_cont w.r.t. y */ virtual Number fint_cont_dy(Number x1, Number x2, Number y, Number u) const { return y-y_d_cont(x1,x2); } /** First partial derivative of fint_cont w.r.t. u */ virtual Number fint_cont_du(Number x1, Number x2, Number y, Number u) const { return alpha_*u; } /** Second partial derivative of fint_cont w.r.t. y,y */ virtual Number fint_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 1.; } /** returns true if second partial derivative of fint_cont * w.r.t. y,y is always zero. */ virtual bool fint_cont_dydy_alwayszero() const { return false; } /** Second partial derivative of fint_cont w.r.t. u,u */ virtual Number fint_cont_dudu(Number x1, Number x2, Number y, Number u) const { return alpha_; } /** returns true if second partial derivative of fint_cont * w.r.t. u,u is always zero. */ virtual bool fint_cont_dudu_alwayszero() const { return false; } /** Second partial derivative of fint_cont w.r.t. y,u */ virtual Number fint_cont_dydu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of fint_cont * w.r.t. y,u is always zero. */ virtual bool fint_cont_dydu_alwayszero() const { return true; } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y, Number u) const { return -exp(y) - u; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y, Number u) const { return -exp(y); } /** First partial derivative of forcing function w.r.t. u */ virtual Number d_cont_du(Number x1, Number x2, Number y, Number u) const { return -1.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y, Number u) const { return -exp(y); } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return false; } /** Second partial derivative of forcing function w.r.t. u,u */ virtual Number d_cont_dudu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dudu_alwayszero() const { return true; } /** Second partial derivative of forcing function w.r.t. y,u */ virtual Number d_cont_dydu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,u is always zero. */ virtual bool d_cont_dydu_alwayszero() const { return true; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannDistCntrlNeumB1(const MittelmannDistCntrlNeumB1&); MittelmannDistCntrlNeumB1& operator=(const MittelmannDistCntrlNeumB1&); //@} /** Value of pi (made available for convenience) */ const Number pi_; /** Value for parameter alpha in objective functin */ const Number alpha_; }; /** Class implementating Example 5 */ class MittelmannDistCntrlNeumB2 : public MittelmannDistCntrlNeumBBase { public: MittelmannDistCntrlNeumB2() : pi_(4.*atan(1.)) {} virtual ~MittelmannDistCntrlNeumB2() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number lb_y = -1e20; Number ub_y = 0.371; Number lb_u = -8.; Number ub_u = 9.; Number b_0j = 1.; Number b_1j = 1.; Number b_i0 = 1.; Number b_i1 = 1.; Number u_init = (ub_u + lb_u)/2.; SetBaseParameters(N, lb_y, ub_y, lb_u, ub_u, b_0j, b_1j, b_i0, b_i1, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return sin(2.*pi_*x1)*sin(2.*pi_*x2); } /** Integrant in objective function */ virtual Number fint_cont(Number x1, Number x2, Number y, Number u) const { Number diff_y = y-y_d_cont(x1,x2); return 0.5*diff_y*diff_y; } /** First partial derivative of fint_cont w.r.t. y */ virtual Number fint_cont_dy(Number x1, Number x2, Number y, Number u) const { return y-y_d_cont(x1,x2); } /** First partial derivative of fint_cont w.r.t. u */ virtual Number fint_cont_du(Number x1, Number x2, Number y, Number u) const { return 0.; } /** Second partial derivative of fint_cont w.r.t. y,y */ virtual Number fint_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 1.; } /** returns true if second partial derivative of fint_cont * w.r.t. y,y is always zero. */ virtual bool fint_cont_dydy_alwayszero() const { return false; } /** Second partial derivative of fint_cont w.r.t. u,u */ virtual Number fint_cont_dudu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of fint_cont * w.r.t. u,u is always zero. */ virtual bool fint_cont_dudu_alwayszero() const { return true; } /** Second partial derivative of fint_cont w.r.t. y,u */ virtual Number fint_cont_dydu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of fint_cont * w.r.t. y,u is always zero. */ virtual bool fint_cont_dydu_alwayszero() const { return true; } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y, Number u) const { return -exp(y) - u; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y, Number u) const { return -exp(y); } /** First partial derivative of forcing function w.r.t. u */ virtual Number d_cont_du(Number x1, Number x2, Number y, Number u) const { return -1.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y, Number u) const { return -exp(y); } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return false; } /** Second partial derivative of forcing function w.r.t. u,u */ virtual Number d_cont_dudu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dudu_alwayszero() const { return true; } /** Second partial derivative of forcing function w.r.t. y,u */ virtual Number d_cont_dydu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,u is always zero. */ virtual bool d_cont_dydu_alwayszero() const { return true; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannDistCntrlNeumB2(const MittelmannDistCntrlNeumB2&); MittelmannDistCntrlNeumB2& operator=(const MittelmannDistCntrlNeumB2&); //@} /** Value of pi (made available for convenience) */ const Number pi_; }; /** Class implementating Example 6 */ class MittelmannDistCntrlNeumB3 : public MittelmannDistCntrlNeumBBase { public: MittelmannDistCntrlNeumB3() : pi_(4.*atan(1.)), M_(1.), K_(0.8), b_(1.) {} virtual ~MittelmannDistCntrlNeumB3() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number lb_y = 3.;//-1e20; Number ub_y = 6.09; Number lb_u = 1.4; Number ub_u = 1.6; Number b_0j = 1.; Number b_1j = 0.; Number b_i0 = 1.; Number b_i1 = 0.; Number u_init = (ub_u + lb_u)/2.; SetBaseParameters(N, lb_y, ub_y, lb_u, ub_u, b_0j, b_1j, b_i0, b_i1, u_init); return true; } protected: /** Profile function for initial y */ virtual Number y_d_cont(Number x1, Number x2) const { return 6.; } /** Integrant in objective function */ virtual Number fint_cont(Number x1, Number x2, Number y, Number u) const { return u*(M_*u - K_*y); } /** First partial derivative of fint_cont w.r.t. y */ virtual Number fint_cont_dy(Number x1, Number x2, Number y, Number u) const { return -K_*u; } /** First partial derivative of fint_cont w.r.t. u */ virtual Number fint_cont_du(Number x1, Number x2, Number y, Number u) const { return 2.*M_*u - K_*y; } /** Second partial derivative of fint_cont w.r.t. y,y */ virtual Number fint_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of fint_cont * w.r.t. y,y is always zero. */ virtual bool fint_cont_dydy_alwayszero() const { return true; } /** Second partial derivative of fint_cont w.r.t. u,u */ virtual Number fint_cont_dudu(Number x1, Number x2, Number y, Number u) const { return 2.*M_; } /** returns true if second partial derivative of fint_cont * w.r.t. u,u is always zero. */ virtual bool fint_cont_dudu_alwayszero() const { return false; } /** Second partial derivative of fint_cont w.r.t. y,u */ virtual Number fint_cont_dydu(Number x1, Number x2, Number y, Number u) const { return -K_; } /** returns true if second partial derivative of fint_cont * w.r.t. y,u is always zero. */ virtual bool fint_cont_dydu_alwayszero() const { return false; } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y, Number u) const { return y*(u + b_*y - a(x1,x2)); } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y, Number u) const { return (u + 2.*b_*y -a(x1,x2)); } /** First partial derivative of forcing function w.r.t. u */ virtual Number d_cont_du(Number x1, Number x2, Number y, Number u) const { return y; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 2.*b_; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return false; } /** Second partial derivative of forcing function w.r.t. u,u */ virtual Number d_cont_dudu(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dudu_alwayszero() const { return true; } /** Second partial derivative of forcing function w.r.t. y,u */ virtual Number d_cont_dydu(Number x1, Number x2, Number y, Number u) const { return 1.; } /** returns true if second partial derivative of d_cont * w.r.t. y,u is always zero. */ virtual bool d_cont_dydu_alwayszero() const { return false; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannDistCntrlNeumB3(const MittelmannDistCntrlNeumB3&); MittelmannDistCntrlNeumB3& operator=(const MittelmannDistCntrlNeumB3&); //@} /** Value of pi (made available for convenience) */ const Number pi_; /*@name constrants appearing in problem formulation */ //@{ const Number M_; const Number K_; const Number b_; //@} //* Auxiliary function for state equation */ inline Number a(Number x1, Number x2) const { return 7. + 4.*sin(2.*pi_*x1*x2); } }; #endif
31.8
96
0.657167
[ "mesh" ]
a0811618dd6b4e4fffe04d21f5875a34d6266bea
4,737
hpp
C++
cpp/src/dotcpp/dot/detail/struct_wrapper.hpp
dotcpp/dotcpp
ba786aa072dd0612f5249de63f80bc540203840e
[ "Apache-2.0" ]
4
2019-08-08T03:53:37.000Z
2021-01-31T06:51:56.000Z
cpp/src/dotcpp/dot/detail/struct_wrapper.hpp
compatibl/dotcpp-mongo
e329e5a0523577b0d1f36c82d5caaac2e92e1023
[ "Apache-2.0" ]
null
null
null
cpp/src/dotcpp/dot/detail/struct_wrapper.hpp
compatibl/dotcpp-mongo
e329e5a0523577b0d1f36c82d5caaac2e92e1023
[ "Apache-2.0" ]
1
2015-03-28T15:52:01.000Z
2015-03-28T15:52:01.000Z
/* Copyright (C) 2015-present The DotCpp Authors. This file is part of .C++, a native C++ implementation of popular .NET class library APIs developed to facilitate code reuse between C# and C++. http://github.com/dotcpp/dotcpp (source) http://dotcpp.org (documentation) 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 namespace dot { class object_impl; class string; class object; class object_impl; namespace detail { /// Empty structure. class dummy_no_to_string : public virtual object_impl {}; /// objects inherit this structure in case their inner struct class has method to_string /// so object also have these method. template <class W, class T> class obj_to_string : public virtual object_impl { public: virtual string to_string() override { return static_cast<T*>(static_cast<W*>(this))->to_string(); } }; /// Detects existance of to_string method. template<class T> struct has_to_string { private: static dummy_no_to_string detect(...); template<class U> static decltype(std::declval<U>().to_string()) detect(const U&); public: static constexpr bool value = !std::is_same<dummy_no_to_string, decltype(detect(std::declval<T>()))>::value; typedef std::integral_constant<bool, value> type; }; /// For inheritance of to_string method. template<class W, class T> class inherit_to_string : public std::conditional< has_to_string<T>::value, obj_to_string<W, T>, dummy_no_to_string >::type {}; /// Empty structure. class dummy_no_get_hashcode : public virtual object_impl {}; /// objects inherit this structure in case their inner struct class has method hash_code /// so object also have these method. template <class W, class T> class obj_get_hashcode : public virtual object_impl { public: virtual size_t hash_code() override { return static_cast<T*>(static_cast<W*>(this))->hash_code(); } }; /// Detects existance of hash_code method. template<class T> struct has_get_hashcode { private: static dummy_no_get_hashcode detect(...); template<class U> static decltype(std::declval<U>().hash_code()) detect(const U&); public: static constexpr bool value = !std::is_same<dummy_no_get_hashcode, decltype(detect(std::declval<T>()))>::value; typedef std::integral_constant<bool, value> type; }; /// For inheritance of hash_code method. template<class W, class T> class inherit_get_hashcode : public std::conditional< has_get_hashcode<T>::value, obj_get_hashcode<W, T>, dummy_no_get_hashcode >::type {}; /// Empty structure. class dummy_no_equals : public virtual object_impl {}; /// objects inherit this structure in case their inner struct class has method Equals /// so object also have these method. template <class W, class T> class obj_equals : public virtual object_impl { public: bool equals(object obj) override { return static_cast<T*>(static_cast<W*>(this))->equals(obj); } }; /// Detects existance of Equals method. template<class T> struct has_equals { private: static dummy_no_equals detect(...); template<class U> static decltype(std::declval<U>().Equals(std::declval<object>())) detect(const U&); public: static constexpr bool value = !std::is_same<dummy_no_equals, decltype(detect(std::declval<T>()))>::value; typedef std::integral_constant<bool, value> type; }; /// For inheritance of Equals method. template<class W, class T> class inherit_equals : public std::conditional< has_equals<T>::value, obj_equals<W, T>, dummy_no_equals >::type {}; } }
34.326087
123
0.619379
[ "object" ]
a0867ef60cffdc4cb86751c22185d2dc465279d8
9,516
cpp
C++
Oem/dbxml/xqilla/src/functions/FunctionParseJSON.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/xqilla/src/functions/FunctionParseJSON.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/xqilla/src/functions/FunctionParseJSON.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
/* * Copyright (c) 2001-2008 * DecisionSoft Limited. All rights reserved. * Copyright (c) 2004-2008 * Oracle. 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. * * $Id$ */ #include "../config/xqilla_config.h" #include <stdio.h> // for sprintf #ifdef _MSC_VER #define snprintf _snprintf #endif #include <xqilla/functions/FunctionParseJSON.hpp> #include <xqilla/context/DynamicContext.hpp> #include <xqilla/exceptions/FunctionException.hpp> #include <xqilla/ast/StaticAnalysis.hpp> #include <xqilla/utils/UTF8Str.hpp> #include <xqilla/events/SequenceBuilder.hpp> #include <xqilla/events/QueryPathTreeFilter.hpp> #include <xqilla/schema/DocumentCache.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include "../yajl/yajl_parse.h" XERCES_CPP_NAMESPACE_USE; using namespace std; const XMLCh FunctionParseJSON::name[] = { chLatin_p, chLatin_a, chLatin_r, chLatin_s, chLatin_e, chDash, chLatin_j, chLatin_s, chLatin_o, chLatin_n, chNull }; const unsigned int FunctionParseJSON::minArgs = 1; const unsigned int FunctionParseJSON::maxArgs = 1; /** * xqilla:parse-json($xml as xs:string?) as element()? */ FunctionParseJSON::FunctionParseJSON(const VectorOfASTNodes &args, XPath2MemoryManager* memMgr) : XQillaFunction(name, minArgs, maxArgs, "string?", args, memMgr), queryPathTree_(0) { } ASTNode *FunctionParseJSON::staticTypingImpl(StaticContext *context) { _src.clear(); _src.setProperties(StaticAnalysis::DOCORDER | StaticAnalysis::GROUPED | StaticAnalysis::PEER | StaticAnalysis::SUBTREE | StaticAnalysis::ONENODE); _src.getStaticType() = StaticType(StaticType::ELEMENT_TYPE, 0, 1); _src.creative(true); return calculateSRCForArguments(context); } const XMLCh JSON2XML_json[] = { 'j', 's', 'o', 'n', 0 }; const XMLCh JSON2XML_item[] = { 'i', 't', 'e', 'm', 0 }; const XMLCh JSON2XML_pair[] = { 'p', 'a', 'i', 'r', 0 }; const XMLCh JSON2XML_name[] = { 'n', 'a', 'm', 'e', 0 }; const XMLCh JSON2XML_type[] = { 't', 'y', 'p', 'e', 0 }; const XMLCh JSON2XML_array[] = { 'a', 'r', 'r', 'a', 'y', 0 }; const XMLCh JSON2XML_object[] = { 'o', 'b', 'j', 'e', 'c', 't', 0 }; const XMLCh JSON2XML_string[] = { 's', 't', 'r', 'i', 'n', 'g', 0 }; const XMLCh JSON2XML_boolean[] = { 'b', 'o', 'o', 'l', 'e', 'a', 'n', 0 }; const XMLCh JSON2XML_number[] = { 'n', 'u', 'm', 'b', 'e', 'r', 0 }; const XMLCh JSON2XML_null[] = { 'n', 'u', 'l', 'l', 0 }; struct JSON2XML_Env { EventHandler *handler; enum Type { MAP, ARRAY }; vector<Type> stack; void startValue() { if(stack.empty()) { // Do nothing } else if(stack.back() == JSON2XML_Env::ARRAY) { handler->startElementEvent(0, 0, JSON2XML_item); } } void endValue() { if(stack.empty()) { // Do nothing } else if(stack.back() == JSON2XML_Env::MAP) { handler->endElementEvent(0, 0, JSON2XML_pair, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, DocumentCache::g_szUntyped); } else { handler->endElementEvent(0, 0, JSON2XML_item, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, DocumentCache::g_szUntyped); } } }; int json2xml_null(void *ctx) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_null, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->endValue(); return 1; } int json2xml_boolean(void * ctx, int boolVal) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_boolean, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->handler->textEvent(boolVal ? SchemaSymbols::fgATTVAL_TRUE : SchemaSymbols::fgATTVAL_FALSE); env->endValue(); return 1; } int json2xml_integer(void *ctx, long integerVal) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; char intString[256]; snprintf(intString, 256,"%lld", (xq_int64_t)integerVal); env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_number, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->handler->textEvent(X(intString)); env->endValue(); return 1; } int json2xml_double(void *ctx, double doubleVal) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; char doubleString[256]; snprintf(doubleString, 256,"%lf", doubleVal); env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_number, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->handler->textEvent(X(doubleString)); env->endValue(); return 1; } int json2xml_string(void *ctx, const unsigned char * stringVal, unsigned int stringLen) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; AutoDeleteArray<char> str(new char[stringLen + 1]); memcpy(str.get(), stringVal, stringLen); str.get()[stringLen] = 0; env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_string, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->handler->textEvent(X(str.get())); env->endValue(); return 1; } int json2xml_map_key(void *ctx, const unsigned char * stringVal, unsigned int stringLen) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; AutoDeleteArray<char> str(new char[stringLen + 1]); memcpy(str.get(), stringVal, stringLen); str.get()[stringLen] = 0; env->handler->startElementEvent(0, 0, JSON2XML_pair); env->handler->attributeEvent(0, 0, JSON2XML_name, X(str.get()), SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); return 1; } int json2xml_start_map(void *ctx) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_object, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->stack.push_back(JSON2XML_Env::MAP); return 1; } int json2xml_end_map(void *ctx) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->stack.pop_back(); env->endValue(); return 1; } int json2xml_start_array(void *ctx) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->startValue(); env->handler->attributeEvent(0, 0, JSON2XML_type, JSON2XML_array, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, ATUntypedAtomic::fgDT_UNTYPEDATOMIC); env->stack.push_back(JSON2XML_Env::ARRAY); return 1; } int json2xml_end_array(void *ctx) { JSON2XML_Env *env = (JSON2XML_Env*)ctx; env->stack.pop_back(); env->endValue(); return 1; } static yajl_callbacks json2xml_callbacks = { json2xml_null, json2xml_boolean, json2xml_integer, json2xml_double, json2xml_string, json2xml_start_map, json2xml_map_key, json2xml_end_map, json2xml_start_array, json2xml_end_array }; void FunctionParseJSON::parseJSON(const XMLCh *jsonString, EventHandler *handler, DynamicContext *context, const LocationInfo *location) { UTF8Str utf8(jsonString); JSON2XML_Env env; env.handler = handler; handler->startElementEvent(0, 0, JSON2XML_json); yajl_parser_config cfg = { 0 }; yajl_handle yajl = yajl_alloc(&json2xml_callbacks, &cfg, &env); yajl_status stat = yajl_parse(yajl, (unsigned char*)utf8.str(), (unsigned int)strlen(utf8.str())); if(stat != yajl_status_ok) { XMLBuffer buf; buf.append(X("JSON ")); unsigned char *str = yajl_get_error(yajl, 1, (unsigned char*)utf8.str(), (unsigned int)strlen(utf8.str())); buf.append(X((char*)str)); yajl_free_error(str); XQThrow3(FunctionException, X("FunctionParseJSON::parseJSON"), buf.getRawBuffer(), location); } handler->endElementEvent(0, 0, JSON2XML_json, SchemaSymbols::fgURI_SCHEMAFORSCHEMA, DocumentCache::g_szUntyped); } Sequence FunctionParseJSON::createSequence(DynamicContext* context, int flags) const { Item::Ptr item = getParamNumber(1, context)->next(context); if(item.isNull()) return Sequence(context->getMemoryManager()); AutoDelete<SequenceBuilder> builder(context->createSequenceBuilder()); QueryPathTreeFilter qptf(queryPathTree_, builder.get()); EventHandler *handler = queryPathTree_ ? (EventHandler*)&qptf : (EventHandler*)builder.get(); parseJSON(item->asString(context), handler, context, this); handler->endEvent(); return builder->getSequence(); }
30.696774
136
0.655422
[ "vector" ]
a08a2599a4a1ce74681b9013af1b52ec101bcf0b
2,327
cpp
C++
test/seatalk/Test_seatalk_message_23.cpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
test/seatalk/Test_seatalk_message_23.cpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
1
2021-11-10T14:40:21.000Z
2021-11-10T14:40:21.000Z
test/seatalk/Test_seatalk_message_23.cpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
1
2020-12-21T16:38:02.000Z
2020-12-21T16:38:02.000Z
#include <gtest/gtest.h> #include <marnav/seatalk/message_23.hpp> namespace { using namespace marnav; class Test_seatalk_message_23 : public ::testing::Test { }; TEST_F(Test_seatalk_message_23, construction) { seatalk::message_23 m; } TEST_F(Test_seatalk_message_23, parse_invalid_data_size) { EXPECT_ANY_THROW(seatalk::message_23::parse({3, 0x00})); EXPECT_ANY_THROW(seatalk::message_23::parse({5, 0x00})); } TEST_F(Test_seatalk_message_23, parse_invalid_length) { EXPECT_ANY_THROW(seatalk::message_23::parse({0x23, 0x00, 0x00, 0x00})); EXPECT_ANY_THROW(seatalk::message_23::parse({0x23, 0x02, 0x00, 0x00})); } TEST_F(Test_seatalk_message_23, parse) { struct test_case { seatalk::raw data; bool sensor_defective; uint8_t temperature_celsius; uint8_t temperature_fahrenheit; }; std::vector<test_case> cases{ {{0x23, 0x01, 0x00, 0x00}, false, 0, 0}, {{0x23, 0x41, 0x00, 0x00}, true, 0, 0}, {{0x23, 0x01, 0x01, 0x00}, false, 1, 0}, {{0x23, 0x01, 0x00, 0x01}, false, 0, 1}, {{0x23, 0x01, 0x64, 0x00}, false, 100, 0}, {{0x23, 0x01, 0x00, 0x64}, false, 0, 100}, }; for (auto const & t : cases) { auto generic_message = seatalk::message_23::parse(t.data); ASSERT_TRUE(generic_message != nullptr); auto m = seatalk::message_cast<seatalk::message_23>(generic_message); ASSERT_TRUE(m != nullptr); EXPECT_EQ(seatalk::message_id::water_temperature_1, m->type()); EXPECT_EQ(t.sensor_defective, m->get_sensor_defective()); EXPECT_EQ(t.temperature_celsius, m->get_celsius()); EXPECT_EQ(t.temperature_fahrenheit, m->get_fahrenheit()); } } TEST_F(Test_seatalk_message_23, write_default) { const seatalk::raw expected{0x23, 0x01, 0x00, 0x00}; seatalk::message_23 m; EXPECT_EQ(expected, m.get_data()); } TEST_F(Test_seatalk_message_23, write_sensor_defectie) { const seatalk::raw expected{0x23, 0x41, 0x00, 0x00}; seatalk::message_23 m; m.set_sensor_defective(true); EXPECT_EQ(expected, m.get_data()); } TEST_F(Test_seatalk_message_23, write_celcius) { const seatalk::raw expected{0x23, 0x01, 0x01, 0x00}; seatalk::message_23 m; m.set_celsius(1); EXPECT_EQ(expected, m.get_data()); } TEST_F(Test_seatalk_message_23, write_fahrenheit) { const seatalk::raw expected{0x23, 0x01, 0x00, 0x01}; seatalk::message_23 m; m.set_fahrenheit(1); EXPECT_EQ(expected, m.get_data()); } }
25.293478
87
0.731844
[ "vector" ]
a08c9c9db44f521d67a122bef5d8ff180861e42a
40,411
cpp
C++
vendor/mysql-connector-c++-1.1.3/test/unit/classes/preparedstatement.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
1
2015-12-01T04:16:54.000Z
2015-12-01T04:16:54.000Z
vendor/mysql-connector-c++-1.1.3/test/unit/classes/preparedstatement.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
null
null
null
vendor/mysql-connector-c++-1.1.3/test/unit/classes/preparedstatement.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cppconn/prepared_statement.h> #include <cppconn/connection.h> #include <cppconn/warning.h> #include "preparedstatement.h" #include <stdlib.h> #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> namespace testsuite { namespace classes { void preparedstatement::InsertSelectAllTypes() { logMsg("preparedstatement::InsertSelectAllTypes() - MySQL_PreparedStatement::*"); std::stringstream sql; std::vector<columndefinition>::iterator it; stmt.reset(con->createStatement()); bool got_warning=false; size_t len; try { for (it=columns.end(), it--; it != columns.begin(); it--) { stmt->execute("DROP TABLE IF EXISTS test"); sql.str(""); sql << "CREATE TABLE test(dummy TIMESTAMP, id " << it->sqldef << ")"; try { stmt->execute(sql.str()); sql.str(""); sql << "... testing '" << it->sqldef << "'"; logMsg(sql.str()); } catch (sql::SQLException &) { sql.str(""); sql << "... skipping '" << it->sqldef << "'"; logMsg(sql.str()); continue; } pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setString(1, it->value); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt.reset(con->prepareStatement("SELECT id, NULL FROM test")); res.reset(pstmt->executeQuery()); checkResultSetScrolling(res); ASSERT(res->next()); res.reset(); res.reset(pstmt->executeQuery()); checkResultSetScrolling(res); ASSERT(res->next()); if (it->check_as_string && (res->getString(1) != it->as_string)) { sql.str(""); sql << "... \t\tWARNING - SQL: '" << it->sqldef << "' - expecting '" << it->as_string << "'"; sql << " got '" << res->getString(1) << "'"; logMsg(sql.str()); got_warning=true; } ASSERT_EQUALS(res->getString("id"), res->getString(1)); try { res->getString(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getString(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getString(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getString(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getDouble("id"), res->getDouble(1)); try { res->getDouble(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getDouble(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getDouble(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getDouble(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getInt(1), res->getInt("id")); try { res->getInt(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getInt(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getInt(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getInt(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getUInt(1), res->getUInt("id")); try { res->getUInt(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getUInt(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getUInt(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getUInt(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getInt64("id"), res->getInt64(1)); try { res->getInt64(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getInt64(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getInt64(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getInt64(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getUInt64("id"), res->getUInt64(1)); try { res->getUInt64(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getUInt64(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getUInt64(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getUInt64(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); ASSERT_EQUALS(res->getBoolean("id"), res->getBoolean(1)); try { res->getBoolean(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getBoolean(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getBoolean(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getBoolean(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); // TODO - make BLOB if (it->check_as_string) { { boost::scoped_ptr<std::istream> blob_output_stream(res->getBlob(1)); len=it->as_string.length(); boost::scoped_array<char> blob_out(new char[len]); blob_output_stream->read(blob_out.get(), len); if (it->as_string.compare(0, blob_output_stream->gcount() , blob_out.get(), blob_output_stream->gcount())) { sql.str(""); sql << "... \t\tWARNING - SQL: '" << it->sqldef << "' - expecting '" << it->as_string << "'"; sql << " got '" << res->getString(1) << "'"; logMsg(sql.str()); got_warning=true; } } { boost::scoped_ptr<std::istream> blob_output_stream(res->getBlob("id")); len=it->as_string.length(); boost::scoped_array<char> blob_out(new char[len]); blob_output_stream->read(blob_out.get(), len); if (it->as_string.compare(0, blob_output_stream->gcount() , blob_out.get(), blob_output_stream->gcount())) { sql.str(""); sql << "... \t\tWARNING - SQL: '" << it->sqldef << "' - expecting '" << it->as_string << "'"; sql << " got '" << res->getString(1) << "'"; logMsg(sql.str()); got_warning=true; } } } try { res->getBlob(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } try { res->getBlob(3); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->beforeFirst(); try { res->getBlob(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->afterLast(); try { res->getBlob(1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException &) { } res->first(); } stmt->execute("DROP TABLE IF EXISTS test"); if (got_warning) FAIL("See warnings"); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::assortedSetType() { logMsg("preparedstatement::assortedSetType() - MySQL_PreparedStatement::set*"); std::stringstream sql; std::vector<columndefinition>::iterator it; stmt.reset(con->createStatement()); bool got_warning=false; try { for (it=columns.end(), it--; it != columns.begin(); it--) { stmt->execute("DROP TABLE IF EXISTS test"); sql.str(""); sql << "CREATE TABLE test(dummy TIMESTAMP, id " << it->sqldef << ")"; try { stmt->execute(sql.str()); sql.str(""); sql << "... testing '" << it->sqldef << "'"; logMsg(sql.str()); } catch (sql::SQLException &) { sql.str(""); sql << "... skipping '" << it->sqldef << "'"; logMsg(sql.str()); continue; } pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setString(1, it->value); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setString(0, "overflow"); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setString(2, "invalid"); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setBigInt(1, it->value); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setBigInt(0, it->value); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setBigInt(2, it->value); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setBoolean(1, false); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setBoolean(0, false); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setBoolean(2, false); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setDateTime(1, it->value); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setDateTime(0, it->value); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setDateTime(2, it->value); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setDouble(1, (double) 1.23); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setDouble(0, (double) 1.23); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setDouble(2, (double) 1.23); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setInt(1, (int32_t) - 1); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setInt(0, (int32_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setInt(2, (int32_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setUInt(1, (uint32_t) 1); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setUInt(0, (uint32_t) 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setUInt(2, (uint32_t) 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setInt64(1, (int64_t) - 123); ASSERT_EQUALS(1, pstmt->executeUpdate()); if (it->is_nullable) { pstmt->clearParameters(); pstmt->setNull(1, it->ctype); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setNull(0, it->ctype); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setNull(2, it->ctype); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } } pstmt->clearParameters(); pstmt->setUInt(1, (uint32_t) 1); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setUInt(0, (uint32_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setUInt(2, (uint32_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); pstmt->setUInt64(1, (uint64_t) 123); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setUInt64(0, (uint64_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setUInt64(2, (uint64_t) - 1); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); std::stringstream blob_input_stream; blob_input_stream.str(it->value); pstmt->setBlob(1, &blob_input_stream); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt->clearParameters(); try { pstmt->setBlob(0, &blob_input_stream); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt->clearParameters(); try { pstmt->setBlob(2, &blob_input_stream); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } pstmt.reset(con->prepareStatement("SELECT COUNT(IFNULL(id, 1)) AS _num FROM test")); res.reset(pstmt->executeQuery()); checkResultSetScrolling(res); ASSERT(res->next()); if (res->getInt("_num") != (11 + (int) it->is_nullable)) { sql.str(""); sql << "....\t\tWARNING, SQL: " << it->sqldef << ", nullable " << std::boolalpha; sql << it->is_nullable << ", found " << res->getInt(1) << "columns but"; sql << " expecting " << (11 + (int) it->is_nullable); logMsg(sql.str()); got_warning=true; } } stmt->execute("DROP TABLE IF EXISTS test"); if (got_warning) FAIL("See warnings"); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::setNull() { logMsg("preparedstatement::setNull() - MySQL_PreparedStatement::*"); std::stringstream sql; stmt.reset(con->createStatement()); try { stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(id INT)"); pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setNull(1, sql::DataType::INTEGER); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt.reset(con->prepareStatement("SELECT id FROM test")); res.reset(pstmt->executeQuery()); checkResultSetScrolling(res); ASSERT(res->next()); ASSERT(res->isNull(1)); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } try { stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(id INT NOT NULL)"); pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setNull(1, sql::DataType::INTEGER); pstmt->executeUpdate(); FAIL("Should fail"); } catch (sql::SQLException &) { } } void preparedstatement::checkClosed() { logMsg("preparedstatement::checkClosed() - MySQL_PreparedStatement::close()"); try { pstmt.reset(con->prepareStatement("SELECT 1")); pstmt->close(); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::getMetaData() { logMsg("preparedstatement::getMetaData() - MySQL_PreparedStatement::getMetaData()"); std::stringstream sql; std::vector<columndefinition>::iterator it; stmt.reset(con->createStatement()); ResultSetMetaData * meta_ps; ResultSetMetaData * meta_st; ResultSet res_st; bool got_warning=false; unsigned int i; try { for (it=columns.end(), it--; it != columns.begin(); it--) { stmt->execute("DROP TABLE IF EXISTS test"); sql.str(""); sql << "CREATE TABLE test(dummy TIMESTAMP, id " << it->sqldef << ")"; try { stmt->execute(sql.str()); sql.str(""); sql << "... testing '" << it->sqldef << "'"; logMsg(sql.str()); } catch (sql::SQLException &) { sql.str(""); sql << "... skipping '" << it->sqldef << "'"; logMsg(sql.str()); continue; } pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setString(1, it->value); ASSERT_EQUALS(1, pstmt->executeUpdate()); pstmt.reset(con->prepareStatement("SELECT id, dummy, NULL, -1.1234, 'Warum nicht...' FROM test")); res.reset(pstmt->executeQuery()); meta_ps=res->getMetaData(); res_st.reset(stmt->executeQuery("SELECT id, dummy, NULL, -1.1234, 'Warum nicht...' FROM test")); meta_st=res->getMetaData(); ASSERT_EQUALS(meta_ps->getColumnCount(), meta_st->getColumnCount()); for (i=1; i <= meta_ps->getColumnCount(); i++) { ASSERT_EQUALS(meta_ps->getCatalogName(i), meta_st->getCatalogName(i)); ASSERT_EQUALS(meta_ps->getColumnDisplaySize(i), meta_st->getColumnDisplaySize(i)); ASSERT_EQUALS(meta_ps->getColumnLabel(i), meta_st->getColumnLabel(i)); ASSERT_EQUALS(meta_ps->getColumnName(i), meta_st->getColumnName(i)); ASSERT_EQUALS(meta_ps->getColumnType(i), meta_st->getColumnType(i)); ASSERT_EQUALS(meta_ps->getColumnTypeName(i), meta_st->getColumnTypeName(i)); ASSERT_EQUALS(meta_ps->getPrecision(i), meta_st->getPrecision(i)); ASSERT_EQUALS(meta_ps->getScale(i), meta_st->getScale(i)); ASSERT_EQUALS(meta_ps->getSchemaName(i), meta_st->getSchemaName(i)); ASSERT_EQUALS(meta_ps->getTableName(i), meta_st->getTableName(i)); ASSERT_EQUALS(meta_ps->isAutoIncrement(i), meta_st->isAutoIncrement(i)); ASSERT_EQUALS(meta_ps->isCaseSensitive(i), meta_st->isCaseSensitive(i)); ASSERT_EQUALS(meta_ps->isCurrency(i), meta_st->isCurrency(i)); ASSERT_EQUALS(meta_ps->isDefinitelyWritable(i), meta_st->isDefinitelyWritable(i)); ASSERT_EQUALS(meta_ps->isNullable(i), meta_st->isNullable(i)); ASSERT_EQUALS(meta_ps->isReadOnly(i), meta_st->isReadOnly(i)); ASSERT_EQUALS(meta_ps->isSearchable(i), meta_st->isSearchable(i)); ASSERT_EQUALS(meta_ps->isSigned(i), meta_st->isSigned(i)); ASSERT_EQUALS(meta_ps->isWritable(i), meta_st->isWritable(i)); } try { meta_ps->getCatalogName(0); FAIL("Invalid argument not detected"); } catch (sql::InvalidArgumentException) { } } stmt->execute("DROP TABLE IF EXISTS test"); if (got_warning) FAIL("See warnings"); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } bool preparedstatement::createSP(std::string sp_code) { try { stmt.reset(con->createStatement()); stmt->execute("DROP PROCEDURE IF EXISTS p"); } catch (sql::SQLException &e) { logMsg(e.what()); return false; } try { pstmt.reset(con->prepareStatement(sp_code)); ASSERT(!pstmt->execute()); logMsg("... using PS for everything"); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg; msg.str(""); msg << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg.str()); fail(e.what(), __FILE__, __LINE__); } stmt->execute(sp_code); } return true; } void preparedstatement::callSP() { logMsg("preparedstatement::callSP() - MySQL_PreparedStatement::*()"); std::string sp_code("CREATE PROCEDURE p(OUT ver_param VARCHAR(250)) BEGIN SELECT VERSION() INTO ver_param; END;"); try { if (!createSP(sp_code)) { logMsg("... skipping:"); return; } DatabaseMetaData * dbmeta=con->getMetaData(); try { pstmt.reset(con->prepareStatement("CALL p(@version)")); ASSERT(!pstmt->execute()); ASSERT(!pstmt->execute()); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg; msg.str(""); msg << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg.str()); fail(e.what(), __FILE__, __LINE__); } // PS protocol does not support CALL return; } pstmt.reset(con->prepareStatement("SELECT @version AS _version")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS(dbmeta->getDatabaseProductVersion(), res->getString("_version")); pstmt.reset(con->prepareStatement("SET @version='no_version'")); ASSERT(!pstmt->execute()); pstmt.reset(con->prepareStatement("CALL p(@version)")); ASSERT(!pstmt->execute()); pstmt.reset(con->prepareStatement("SELECT @version AS _version")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS(dbmeta->getDatabaseProductVersion(), res->getString("_version")); } catch (sql::SQLException &e) { logErr(e.what()); std::stringstream msg; msg.str(""); msg << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg.str()); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::callSPInOut() { logMsg("preparedstatement::callSPInOut() - MySQL_PreparedStatement::*()"); std::string sp_code("CREATE PROCEDURE p(IN ver_in VARCHAR(25), OUT ver_out VARCHAR(25)) BEGIN SELECT ver_in INTO ver_out; END;"); try { if (!createSP(sp_code)) { logMsg("... skipping: cannot create SP"); return; } try { pstmt.reset(con->prepareStatement("CALL p('myver', @version)")); ASSERT(!pstmt->execute()); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg1; msg1.str(""); msg1 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg1.str()); fail(e.what(), __FILE__, __LINE__); } // PS protocol does not support CALL logMsg("... skipping: PS protocol does not support CALL"); return; } pstmt.reset(con->prepareStatement("SELECT @version AS _version")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS("myver", res->getString("_version")); } catch (sql::SQLException &e) { logErr(e.what()); std::stringstream msg2; msg2.str(""); msg2 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg2.str()); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::callSPWithPS() { logMsg("preparedstatement::callSPWithPS() - MySQL_PreparedStatement::*()"); try { int mysql_version=getMySQLVersion(con); if (mysql_version < 60000) SKIP("http://bugs.mysql.com/bug.php?id=44495 - Server crash"); std::string sp_code("CREATE PROCEDURE p(IN val VARCHAR(25)) BEGIN SET @sql = CONCAT('SELECT \"', val, '\"'); PREPARE stmt FROM @sql; EXECUTE stmt; DROP PREPARE stmt; END;"); if (!createSP(sp_code)) { logMsg("... skipping:"); return; } try { pstmt.reset(con->prepareStatement("CALL p('abc')")); res.reset(pstmt->executeQuery()); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg1; msg1.str(""); msg1 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg1.str()); fail(e.what(), __FILE__, __LINE__); } // PS interface cannot call this kind of statement return; } ASSERT(res->next()); ASSERT_EQUALS("abc", res->getString(1)); std::stringstream msg2; msg2.str(""); msg2 << "... val = '" << res->getString(1) << "'"; logMsg(msg2.str()); try { pstmt.reset(con->prepareStatement("CALL p(?)")); pstmt->setString(1, "123"); res.reset(pstmt->executeQuery()); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg3; msg3.str(""); msg3 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg3.str()); fail(e.what(), __FILE__, __LINE__); } // PS interface cannot call this kind of statement return; } res->close(); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg4; msg4.str(""); msg4 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg4.str()); fail(e.what(), __FILE__, __LINE__); } } } void preparedstatement::callSPMultiRes() { logMsg("preparedstatement::callSPMultiRes() - MySQL_PreparedStatement::*()"); int mysql_version=getMySQLVersion(con); if (mysql_version < 60008) SKIP("http://bugs.mysql.com/bug.php?id=44521 - Server crash"); try { std::string sp_code("CREATE PROCEDURE p() BEGIN SELECT 1; SELECT 2; SELECT 3; END;"); if (!createSP(sp_code)) { logMsg("... skipping:"); return; } try { pstmt.reset(con->prepareStatement("CALL p()")); ASSERT(pstmt->execute()); } catch (sql::SQLException &e) { if (e.getErrorCode() != 1295) { logErr(e.what()); std::stringstream msg1; msg1.str(""); msg1 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg1.str()); fail(e.what(), __FILE__, __LINE__); } // PS interface cannot call this kind of statement return; } // Should not work prior to MySQL 6.0 std::stringstream msg2; msg2.str(""); do { res.reset(pstmt->getResultSet()); while (res->next()) { msg2 << res->getString(1); } } while (pstmt->getMoreResults()); ASSERT_EQUALS("123", msg2.str()); } catch (sql::SQLException &e) { logErr(e.what()); std::stringstream msg3; msg3.str(""); msg3 << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg3.str()); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::anonymousSelect() { logMsg("preparedstatement::anonymousSelect() - MySQL_PreparedStatement::*, MYSQL_PS_Resultset::*"); try { pstmt.reset(con->prepareStatement("SELECT ' ', NULL")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS(" ", res->getString(1)); std::string mynull(res->getString(2)); ASSERT(res->isNull(2)); ASSERT(res->wasNull()); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::crash() { logMsg("preparedstatement::crash() - MySQL_PreparedStatement::*"); try { int mysql_version=getMySQLVersion(con); if ((mysql_version > 50000 && mysql_version < 50082) || (mysql_version > 51000 && mysql_version < 51035) || (mysql_version > 60000 && mysql_version < 60012)) SKIP("http://bugs.mysql.com/bug.php?id=43833 - Server crash"); stmt.reset(con->createStatement()); stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(dummy TIMESTAMP, id VARCHAR(1))"); pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->clearParameters(); pstmt->setDouble(1, (double) 1.23); ASSERT_EQUALS(1, pstmt->executeUpdate()); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::getWarnings() { logMsg("preparedstatement::getWarnings() - MySQL_PreparedStatement::get|clearWarnings()"); std::stringstream msg; stmt.reset(con->createStatement()); try { stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(id INT UNSIGNED)"); // Generating 2 warnings to make sure we get only the last 1 - won't hurt // Lets hope that this will always cause a 1264 or similar warning pstmt.reset(con->prepareStatement("INSERT INTO test(id) VALUES (?)")); pstmt->setInt(1, -2); pstmt->executeUpdate(); pstmt->setInt(1, -1); pstmt->executeUpdate(); int count= 0; for (const sql::SQLWarning* warn=pstmt->getWarnings(); warn; warn=warn->getNextWarning()) { msg.str(""); msg << "... ErrorCode = '" << warn->getErrorCode() << "', "; msg << "SQLState = '" << warn->getSQLState() << "', "; msg << "ErrorMessage = '" << warn->getMessage() << "'"; logMsg(msg.str()); ASSERT((0 != warn->getErrorCode())); if (1264 == warn->getErrorCode()) { ASSERT_EQUALS("22003", warn->getSQLState()); } else { ASSERT(("" != warn->getSQLState())); } ASSERT(("" != warn->getMessage())); ++count; } ASSERT_EQUALS(1, count); for (const sql::SQLWarning* warn=pstmt->getWarnings(); warn; warn=warn->getNextWarning()) { msg.str(""); msg << "... ErrorCode = '" << warn->getErrorCode() << "', "; msg << "SQLState = '" << warn->getSQLState() << "', "; msg << "ErrorMessage = '" << warn->getMessage() << "'"; logMsg(msg.str()); ASSERT((0 != warn->getErrorCode())); if (1264 == warn->getErrorCode()) { ASSERT_EQUALS("22003", warn->getSQLState()); } else { ASSERT(("" != warn->getSQLState())); } ASSERT(("" != warn->getMessage())); } pstmt->clearWarnings(); for (const sql::SQLWarning* warn=pstmt->getWarnings(); warn; warn=warn->getNextWarning()) { FAIL("There should be no more warnings!"); } pstmt->setInt(1, -3); pstmt->executeUpdate(); ASSERT(pstmt->getWarnings() != NULL); // Statement without tables access does not reset warnings. pstmt.reset(con->prepareStatement("SELECT 1")); res.reset(pstmt->executeQuery()); ASSERT(pstmt->getWarnings() == NULL); ASSERT(res->next()); // TODO - how to use getNextWarning() ? stmt->execute("DROP TABLE IF EXISTS test"); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::blob() { logMsg("preparedstatement::blob() - MySQL_PreparedStatement::*"); char blob_input[512]; std::stringstream blob_input_stream; std::stringstream msg; char blob_output[512]; int id; int offset=0; try { pstmt.reset(con->prepareStatement("DROP TABLE IF EXISTS test")); pstmt->execute(); pstmt.reset(con->prepareStatement("CREATE TABLE test(id INT, col1 TINYBLOB, col2 TINYBLOB)")); pstmt->execute(); // Most basic INSERT/SELECT... pstmt.reset(con->prepareStatement("INSERT INTO test(id, col1) VALUES (?, ?)")); for (char ascii_code=CHAR_MIN; ascii_code < CHAR_MAX; ascii_code++) { blob_output[offset]='\0'; blob_input[offset++]=ascii_code; } blob_input[offset]='\0'; blob_output[offset]='\0'; for (char ascii_code=CHAR_MAX; ascii_code > CHAR_MIN; ascii_code--) { blob_output[offset]='\0'; blob_input[offset++]=ascii_code; } blob_input[offset]='\0'; blob_output[offset]='\0'; id=1; blob_input_stream << blob_input; pstmt->setInt(1, id); pstmt->setBlob(2, &blob_input_stream); try { pstmt->setBlob(3, &blob_input_stream); FAIL("Invalid index not detected"); } catch (sql::SQLException) { } pstmt->execute(); pstmt.reset(con->prepareStatement("SELECT id, col1 FROM test WHERE id = 1")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); msg.str(""); msg << "... simple INSERT/SELECT, '" << blob_input << "' =? '" << res->getString(2) << "'"; logMsg(msg.str()); ASSERT_EQUALS(res->getInt(1), id); ASSERT_EQUALS(res->getString(2), blob_input_stream.str()); ASSERT_EQUALS(res->getString(2), blob_input); ASSERT_EQUALS(res->getString("col1"), blob_input_stream.str()); ASSERT_EQUALS(res->getString("col1"), blob_input); std::auto_ptr< std::istream > blob_output_stream(res->getBlob(2)); blob_output_stream->seekg(std::ios::beg); blob_output_stream->get(blob_output, offset + 1); ASSERT_EQUALS(blob_input_stream.str(), blob_output); blob_output_stream.reset(res->getBlob("col1")); blob_output_stream->seekg(std::ios::beg); blob_output_stream->get(blob_output, offset + 1); ASSERT_EQUALS(blob_input, blob_output); msg.str(""); msg << "... second check, '" << blob_input << "' =? '" << blob_output << "'"; logMsg(msg.str()); ASSERT(!res->next()); res->close(); msg.str(""); // Data is too long to be stored in a TINYBLOB column msg << "... this is more than TINYBLOB can hold: "; msg << "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; pstmt.reset(con->prepareStatement("INSERT INTO test(id, col1) VALUES (?, ?)")); id=2; pstmt->setInt(1, id); pstmt->setBlob(2, &msg); pstmt->execute(); pstmt.reset(con->prepareStatement("SELECT id, col1 FROM test WHERE id = 2")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS(res->getInt(1), id); ASSERT_GT((int) (res->getString(2).length()), (int) (msg.str().length())); ASSERT(!res->next()); res->close(); msg << "- what has happened to the stream?"; logMsg(msg.str()); pstmt.reset(con->prepareStatement("DROP TABLE IF EXISTS test")); pstmt->execute(); } catch (sql::SQLException &e) { logErr(e.what()); logErr("SQLState: " + std::string(e.getSQLState())); fail(e.what(), __FILE__, __LINE__); } } void preparedstatement::executeQuery() { logMsg("preparedstatement::executeQuery() - MySQL_PreparedStatement::executeQuery"); try { const sql::SQLString option("defaultPreparedStatementResultType"); int value=sql::ResultSet::TYPE_FORWARD_ONLY; con->setClientOption(option, static_cast<void *> (&value)); } catch (sql::MethodNotImplementedException &/*e*/) { /* not available */ return; } try { stmt.reset(con->createStatement()); stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(id INT UNSIGNED)"); stmt->execute("INSERT INTO test(id) VALUES (1), (2), (3)"); pstmt.reset(con->prepareStatement("SELECT id FROM test ORDER BY id ASC")); res.reset(pstmt->executeQuery()); ASSERT(res->next()); ASSERT_EQUALS(res->getInt("id"), 1); pstmt.reset(con->prepareStatement("DROP TABLE IF EXISTS test")); pstmt->execute(); } catch (sql::SQLException &e) { logErr(e.what()); std::stringstream msg; msg.str(""); msg << "SQLState: " << e.getSQLState() << ", MySQL error code: " << e.getErrorCode(); logErr(msg.str()); fail(e.what(), __FILE__, __LINE__); } } } /* namespace preparedstatement */ } /* namespace testsuite */
26.343546
274
0.576254
[ "vector" ]
a0920e420f93047e325372e9230bd1e4694ca9c2
5,838
cpp
C++
i23dSFM/linearProgramming/linearProgramming_test.cpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
null
null
null
i23dSFM/linearProgramming/linearProgramming_test.cpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
null
null
null
i23dSFM/linearProgramming/linearProgramming_test.cpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
1
2019-02-18T09:49:32.000Z
2019-02-18T09:49:32.000Z
// Copyright (c) 2012 Pierre MOULON. // 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 <algorithm> #include <iostream> #include <vector> #include "testing/testing.h" #include "i23dSFM/linearProgramming/linearProgrammingMOSEK.hpp" #include "i23dSFM/linearProgramming/linearProgrammingOSI_X.hpp" using namespace i23dSFM; using namespace i23dSFM::linearProgramming; // Setup : // max(143x + 60y) // s.t. // 120x + 210y <= 15000 // 110x + 30y <= 4000 // x + y <= 75 // x >= 0 // y >= 0 void BuildLinearProblem(LP_Constraints & cstraint) { cstraint._nbParams = 2; cstraint._bminimize = false; //Configure objective cstraint._vec_cost.push_back(143); cstraint._vec_cost.push_back(60); cstraint._constraintMat = Mat(5,2); cstraint._constraintMat << 120, 210, 110, 30, 1, 1, 1, 0, 0, 1; cstraint._Cst_objective = Vec(5); cstraint._Cst_objective << 15000, 4000, 75, 0, 0; cstraint._vec_sign.resize(5); std::fill_n(cstraint._vec_sign.begin(), 3, LP_Constraints::LP_LESS_OR_EQUAL); std::fill_n(cstraint._vec_sign.begin()+3, 2, LP_Constraints::LP_GREATER_OR_EQUAL); cstraint._vec_bounds = std::vector< std::pair<double,double> >(cstraint._nbParams); fill(cstraint._vec_bounds.begin(),cstraint._vec_bounds.end(), std::make_pair((double)-1e+30, (double)1e+30)); } #ifdef I23DSFM_HAVE_MOSEK // LP_Solve website example solving with the HighLevelFramework TEST(linearProgramming, MOSEK_dense_sample) { LP_Constraints cstraint; BuildLinearProblem(cstraint); //Solve std::vector<double> vec_solution(2); MOSEK_SolveWrapper solver(2); solver.setup(cstraint); EXPECT_TRUE(solver.solve()); solver.getSolution(vec_solution); EXPECT_NEAR( 21.875000, vec_solution[0], 1e-6); EXPECT_NEAR( 53.125000, vec_solution[1], 1e-6); std::cout << "Solution : " << vec_solution[0] << " " << vec_solution[1] << std::endl; } #endif // I23DSFM_HAVE_MOSEK TEST(linearProgramming, osiclp_dense_sample) { LP_Constraints cstraint; BuildLinearProblem(cstraint); //Solve std::vector<double> vec_solution(2); OSI_CLP_SolverWrapper solver(2); solver.setup(cstraint); EXPECT_TRUE(solver.solve()); solver.getSolution(vec_solution); EXPECT_NEAR( 21.875000, vec_solution[0], 1e-6); EXPECT_NEAR( 53.125000, vec_solution[1], 1e-6); } // Setup example from MOSEK API // maximize : // 3 x0 + 1 x1 + 5 x2 + 1 x3 // subject to // 3 x0 + 1 x1 + 2 x2 = 30 // 2 x0 + 1 x1 + 3 x2 + 1 x3 >= 15 // 2 w1 + 3 x3 <= 25 // bounds // 0 <= x0, x2, x3 < infinity // 0 <= x1 <= 10 void BuildSparseLinearProblem(LP_Constraints_Sparse & cstraint) { // Number of variable we are looking for cstraint._nbParams = 4; // {x0, x1, x2, x3} // Constraint coefficient sRMat & A = cstraint._constraintMat; A.resize(3,4); A.coeffRef(0,0) = 3; A.coeffRef(0,1) = 1; A.coeffRef(0,2) = 2; A.coeffRef(1,0) = 2; A.coeffRef(1,1) = 1; A.coeffRef(1,2) = 3; A.coeffRef(1,3) = 1; A.coeffRef(2,1) = 2; A.coeffRef(2,3) = 3; // Constraint objective Vec & C = cstraint._Cst_objective; C.resize(3, 1); C[0] = 30; C[1] = 15; C[2] = 25; // Constraint sign std::vector<LP_Constraints::eLP_SIGN> & vec_sign = cstraint._vec_sign; vec_sign.resize(3); vec_sign[0] = LP_Constraints::LP_EQUAL; vec_sign[1] = LP_Constraints::LP_GREATER_OR_EQUAL; vec_sign[2] = LP_Constraints::LP_LESS_OR_EQUAL; // Variable bounds cstraint._vec_bounds = std::vector< std::pair<double,double> >(4); fill(cstraint._vec_bounds.begin(),cstraint._vec_bounds.end(), std::make_pair(0.0, (double)1e+30)); cstraint._vec_bounds[1].second = 10; // Objective to maximize cstraint._bminimize = false; cstraint._vec_cost.resize(4); cstraint._vec_cost[0] = 3; cstraint._vec_cost[1] = 1; cstraint._vec_cost[2] = 5; cstraint._vec_cost[3] = 1; } #ifdef I23DSFM_HAVE_MOSEK // Unit test on mosek Sparse constraint TEST(linearProgramming, mosek_sparse_sample) { LP_Constraints_Sparse cstraint; BuildSparseLinearProblem(cstraint); //Solve std::vector<double> vec_solution(4); MOSEK_SolveWrapper solver(4); solver.setup(cstraint); EXPECT_TRUE(solver.solve()); solver.getSolution(vec_solution); EXPECT_NEAR( 0.00, vec_solution[0], 1e-2); EXPECT_NEAR( 0.00, vec_solution[1], 1e-2); EXPECT_NEAR( 15, vec_solution[2], 1e-2); EXPECT_NEAR( 8.33, vec_solution[3], 1e-2); } #endif // #ifdef I23DSFM_HAVE_MOSEK TEST(linearProgramming, osiclp_sparse_sample) { LP_Constraints_Sparse cstraint; BuildSparseLinearProblem(cstraint); //Solve std::vector<double> vec_solution(4); OSI_CLP_SolverWrapper solver(4); solver.setup(cstraint); EXPECT_TRUE(solver.solve()); solver.getSolution(vec_solution); EXPECT_NEAR( 0.00, vec_solution[0], 1e-2); EXPECT_NEAR( 0.00, vec_solution[1], 1e-2); EXPECT_NEAR( 15, vec_solution[2], 1e-2); EXPECT_NEAR( 8.33, vec_solution[3], 1e-2); } #ifdef I23DSFM_HAVE_MOSEK TEST(linearProgramming, osi_mosek_sparse_sample) { LP_Constraints_Sparse cstraint; BuildSparseLinearProblem(cstraint); //Solve std::vector<double> vec_solution(4); OSI_MOSEK_SolverWrapper solver(4); solver.setup(cstraint); EXPECT_TRUE(solver.solve()); solver.getSolution(vec_solution); EXPECT_NEAR( 0.00, vec_solution[0], 1e-2); EXPECT_NEAR( 0.00, vec_solution[1], 1e-2); EXPECT_NEAR( 15, vec_solution[2], 1e-2); EXPECT_NEAR( 8.33, vec_solution[3], 1e-2); } #endif // #ifdef I23DSFM_HAVE_MOSEK /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
26.297297
87
0.679171
[ "vector" ]
90bf31d156ad2c57837f387910ef389b2d965d17
14,696
cpp
C++
Doremi/Core/Source/Manager/AI/AITargetManager.cpp
meraz/doremi
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:05.000Z
2020-03-23T15:42:05.000Z
Doremi/Core/Source/Manager/AI/AITargetManager.cpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
Doremi/Core/Source/Manager/AI/AITargetManager.cpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
/// Project #include <Doremi/Core/Include/Manager/AI/AITargetManager.hpp> #include <PlayerHandlerServer.hpp> // Components #include <EntityComponent/EntityHandler.hpp> #include <EntityComponent/Components/TransformComponent.hpp> #include <EntityComponent/Components/RangeComponent.hpp> #include <EntityComponent/Components/EntityTypeComponent.hpp> #include <EntityComponent/Components/RigidBodyComponent.hpp> #include <EntityComponent/Components/PhysicsMaterialComponent.hpp> #include <EntityComponent/Components/AiAgentComponent.hpp> #include <EntityComponent/Components/PotentialFieldComponent.hpp> #include <EntityComponent/Components/MovementComponent.hpp> // Events #include <Doremi/Core/Include/EventHandler/EventHandler.hpp> #include <Doremi/Core/Include/EventHandler/Events/AnimationTransitionEvent.hpp> #include <Doremi/Core/Include/EventHandler/Events/DamageTakenEvent.hpp> // Helper #include <Helper/ProximityChecker.hpp> /// Engine // Physics #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RayCastManager.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> // Config #include <DoremiEngine/Configuration/Include/ConfigurationModule.hpp> // Third party #include <DirectXMath.h> #include <iostream> namespace Doremi { namespace Core { AITargetManager::AITargetManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "AITargetManager") { m_playerMovementImpact = m_sharedContext.GetConfigurationModule().GetAllConfigurationValues().AIAimOffset; m_maxActorsUpdated = 1; // We may only update one AI per update... TODOCONFIG m_actorToUpdate = 0; } AITargetManager::~AITargetManager() {} void AITargetManager::Update(double p_dt) { using namespace DirectX; int updatedActors = 0; int lastUpdatedActor = 0; // gets all the players in the world, used to see if we can see anyone of them std::map<uint32_t, PlayerServer*>& t_players = static_cast<PlayerHandlerServer*>(PlayerHandler::GetInstance())->GetPlayerMap(); size_t length = EntityHandler::GetInstance().GetLastEntityIndex(); EntityHandler& t_entityHandler = EntityHandler::GetInstance(); // TODOXX this have very bad coupling and if possible should be done in the damage manager std::map<int, float> damageToPlayer; for(size_t i = m_actorToUpdate + 1; i != m_actorToUpdate; i++) { if(i > length) { i = 0; if(i == m_actorToUpdate) { break; } } // Check and update the attack timer bool shouldFire = false; if(t_entityHandler.HasComponents(i, (int)ComponentType::AIAgent)) { AIAgentComponent* timer = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); timer->attackTimer += static_cast<float>(p_dt); // If above attack freq we should attack if(timer->attackTimer > timer->attackFrequency) { shouldFire = true; } else { // else continue to next for itteration shouldFire = false; } } else { shouldFire = false; // No timer? TODOKO log error and dont let it fire! } if(t_entityHandler.HasComponents(i, (int)ComponentType::Range | (int)ComponentType::AIAgent | (int)ComponentType::Transform) && updatedActors < m_maxActorsUpdated) { // They have a range component and are AI agents, let's see if a player is in range! // I use proximitychecker here because i'm guessing it's faster than raycast TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(i); RangeComponent* aiRange = t_entityHandler.GetComponentFromStorage<RangeComponent>(i); int closestVisiblePlayer = -1; float checkRange = 1400; float closestDistance = checkRange; // Hardcoded range, not intreseted if player is outside this int onlyOnePlayerCounts = 1; // Check waht player is close and visible for(auto pairs : t_players) { int playerID = pairs.second->m_playerEntityID; float distanceToPlayer = ProximityChecker::GetInstance().GetDistanceBetweenEntities(pairs.second->m_playerEntityID, i); if(distanceToPlayer < closestDistance) { // It's after this we start whit heavy computation so this is counted as a updated actor lastUpdatedActor = i; updatedActors += onlyOnePlayerCounts; onlyOnePlayerCounts = 0; // Potential player found, check if we see him // We are in range!! Let's raycast in a appropirate direction!! so start with finding that direction! if(!EntityHandler::GetInstance().HasComponents(playerID, (int)ComponentType::Transform)) // Just for saftey :D { std::cout << "Player missing transformcomponent?" << std::endl; return; } // Fetch some components TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(playerID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // Calculate direction XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); // Offset origin of ray so we dont hit ourself XMVECTOR rayOrigin = AIPos + direction * 5.0f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 rayOriginFloat; XMStoreFloat3(&rayOriginFloat, rayOrigin); // Send it to physx for raycast calculation int bodyHit = m_sharedContext.GetPhysicsModule().GetRayCastManager().CastRay(rayOriginFloat, directionFloat, checkRange); if(bodyHit == -1) { continue; } // we check if it was a bullet we did hit, in this case we probably did hit our own bullet and should take this as a // player hit // This is a bit of a wild guess and we should probably do a new raycast from the hit location but screw that! bool wasBullet = false; if(EntityHandler::GetInstance().HasComponents(bodyHit, (int)ComponentType::EntityType)) { EntityTypeComponent* typeComp = EntityHandler::GetInstance().GetComponentFromStorage<EntityTypeComponent>(bodyHit); if(((int)typeComp->type & (int)EntityType::EnemyBullet) == (int)EntityType::EnemyBullet) // if first entity is bullet { wasBullet = true; } } bool wasNonRenderObject = false; // object which was hit doesn't have render component - don't collide with it if(!EntityHandler::GetInstance().HasComponents(bodyHit, (int)ComponentType::Render)) { wasNonRenderObject = true; } if(bodyHit == playerID || wasBullet || wasNonRenderObject) { closestDistance = distanceToPlayer; closestVisiblePlayer = pairs.second->m_playerEntityID; // Rotate the enemy to face the player XMMATRIX mat = XMMatrixInverse(nullptr, XMMatrixLookAtLH(AIPos, AIPos + direction, XMLoadFloat3(&XMFLOAT3(0, 1, 0)))); XMVECTOR rotation = XMQuaternionRotationMatrix(mat); XMFLOAT4 quater; XMStoreFloat4(&quater, rotation); AITransform->rotation = quater; } } } if(closestVisiblePlayer != -1) { // We now know what player is closest and visible if(shouldFire) { if(closestDistance <= aiRange->range) { AIAgentComponent* agent = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); agent->attackTimer = 0; if(agent->type == AIType::Melee) { // melee attack logic, just deal the damage :P if(damageToPlayer.count(closestVisiblePlayer) == 0) { damageToPlayer[closestVisiblePlayer] = 0; } damageToPlayer[closestVisiblePlayer] += 10; // TODOCONFIG Melee enemy damage } else if(agent->type == AIType::SmallRanged) { FireAtEntity(closestVisiblePlayer, i, closestDistance); } AnimationTransitionEvent* t_animationTransition = new AnimationTransitionEvent(i, Animation::ATTACK); EventHandler::GetInstance()->BroadcastEvent(t_animationTransition); } } // If we see a player turn off the phermonetrail if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(false); pfComp->ChargedActor->SetActivePotentialVsType(DoremiEngine::AI::AIActorType::Player, true); } } else if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { // if we dont see a player set phemonetrail and shit PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(true); } } } m_actorToUpdate = lastUpdatedActor; // Send events for all the players that were immediatly damage by enemies for(auto pairs : damageToPlayer) { DamageTakenEvent* t_damageTakenEvent = new DamageTakenEvent(pairs.second, pairs.first); EventHandler::GetInstance()->BroadcastEvent(t_damageTakenEvent); } damageToPlayer.clear(); } void AITargetManager::FireAtEntity(const size_t& p_entityID, const size_t& p_enemyID, const float& p_distance) { EntityHandler& t_entityHandler = EntityHandler::GetInstance(); TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_entityID); MovementComponent* playerMovement = t_entityHandler.GetComponentFromStorage<MovementComponent>(p_entityID); TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_enemyID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // calculate direction again... XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); direction += XMVector3Normalize(XMLoadFloat3(&playerMovement->movement) * m_playerMovementImpact); direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); XMVECTOR bulletOrigin = AIPos + direction * 5.0f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 bulletOriginFloat; XMStoreFloat3(&bulletOriginFloat, bulletOrigin); int id = t_entityHandler.CreateEntity(Blueprints::BulletEntity, bulletOriginFloat); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetCallbackFiltering(id, 3, 1, 8, 2); // Add a force to the body TODOCONFIG should not be hard coded the force amount direction *= 1500.0f; XMFLOAT3 force; XMStoreFloat3(&force, direction); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(id, force); } } }
54.835821
150
0.548449
[ "render", "object", "transform" ]
90bf7242095d792fb2f9b26f2c8c211799d7a700
8,550
cpp
C++
app/src/main/jni/gles3jni.cpp
DeLaSalleUniversity-Manila/opengles3-melvincabatuan
a4715fabf86a7e4f49bbaf236fcb656ec8f3f486
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/gles3jni.cpp
DeLaSalleUniversity-Manila/opengles3-melvincabatuan
a4715fabf86a7e4f49bbaf236fcb656ec8f3f486
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/gles3jni.cpp
DeLaSalleUniversity-Manila/opengles3-melvincabatuan
a4715fabf86a7e4f49bbaf236fcb656ec8f3f486
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <jni.h> #include <stdlib.h> #include <time.h> #include "gles3jni.h" const Vertex QUAD[4] = { // Square with diagonal < 2 so that it fits in a [-1 .. 1]^2 square // regardless of rotation. {{-0.7f, -0.7f}, {0x00, 0xFF, 0x00}}, {{ 0.7f, -0.7f}, {0x00, 0x00, 0xFF}}, {{-0.7f, 0.7f}, {0xFF, 0x00, 0x00}}, {{ 0.7f, 0.7f}, {0xFF, 0xFF, 0xFF}}, }; bool checkGlError(const char* funcName) { GLint err = glGetError(); if (err != GL_NO_ERROR) { ALOGE("GL error after %s(): 0x%08x\n", funcName, err); return true; } return false; } GLuint createShader(GLenum shaderType, const char* src) { GLuint shader = glCreateShader(shaderType); if (!shader) { checkGlError("glCreateShader"); return 0; } glShaderSource(shader, 1, &src, NULL); GLint compiled = GL_FALSE; glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLogLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen); if (infoLogLen > 0) { GLchar* infoLog = (GLchar*)malloc(infoLogLen); if (infoLog) { glGetShaderInfoLog(shader, infoLogLen, NULL, infoLog); ALOGE("Could not compile %s shader:\n%s\n", shaderType == GL_VERTEX_SHADER ? "vertex" : "fragment", infoLog); free(infoLog); } } glDeleteShader(shader); return 0; } return shader; } GLuint createProgram(const char* vtxSrc, const char* fragSrc) { GLuint vtxShader = 0; GLuint fragShader = 0; GLuint program = 0; GLint linked = GL_FALSE; vtxShader = createShader(GL_VERTEX_SHADER, vtxSrc); if (!vtxShader) goto exit; fragShader = createShader(GL_FRAGMENT_SHADER, fragSrc); if (!fragShader) goto exit; program = glCreateProgram(); if (!program) { checkGlError("glCreateProgram"); goto exit; } glAttachShader(program, vtxShader); glAttachShader(program, fragShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &linked); if (!linked) { ALOGE("Could not link program"); GLint infoLogLen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLen); if (infoLogLen) { GLchar* infoLog = (GLchar*)malloc(infoLogLen); if (infoLog) { glGetProgramInfoLog(program, infoLogLen, NULL, infoLog); ALOGE("Could not link program:\n%s\n", infoLog); free(infoLog); } } glDeleteProgram(program); program = 0; } exit: glDeleteShader(vtxShader); glDeleteShader(fragShader); return program; } static void printGlString(const char* name, GLenum s) { const char* v = (const char*)glGetString(s); ALOGV("GL %s: %s\n", name, v); } // ---------------------------------------------------------------------------- Renderer::Renderer() : mNumInstances(0), mLastFrameNs(0) { memset(mScale, 0, sizeof(mScale)); memset(mAngularVelocity, 0, sizeof(mAngularVelocity)); memset(mAngles, 0, sizeof(mAngles)); } Renderer::~Renderer() { } void Renderer::resize(int w, int h) { float* offsets = mapOffsetBuf(); calcSceneParams(w, h, offsets); unmapOffsetBuf(); for (unsigned int i = 0; i < mNumInstances; i++) { mAngles[i] = drand48() * TWO_PI; mAngularVelocity[i] = MAX_ROT_SPEED * (2.0*drand48() - 1.0); } mLastFrameNs = 0; glViewport(0, 0, w, h); } void Renderer::calcSceneParams(unsigned int w, unsigned int h, float* offsets) { // number of cells along the larger screen dimension const float NCELLS_MAJOR = MAX_INSTANCES_PER_SIDE; // cell size in scene space const float CELL_SIZE = 2.0f / NCELLS_MAJOR; // Calculations are done in "landscape", i.e. assuming dim[0] >= dim[1]. // Only at the end are values put in the opposite order if h > w. const float dim[2] = {fmaxf(w,h), fminf(w,h)}; const float aspect[2] = {dim[0] / dim[1], dim[1] / dim[0]}; const float scene2clip[2] = {1.0f, aspect[0]}; const int ncells[2] = { NCELLS_MAJOR, (int)floorf(NCELLS_MAJOR * aspect[1]) }; float centers[2][MAX_INSTANCES_PER_SIDE]; for (int d = 0; d < 2; d++) { float offset = -ncells[d] / NCELLS_MAJOR; // -1.0 for d=0 for (int i = 0; i < ncells[d]; i++) { centers[d][i] = scene2clip[d] * (CELL_SIZE*(i + 0.5f) + offset); } } int major = w >= h ? 0 : 1; int minor = w >= h ? 1 : 0; // outer product of centers[0] and centers[1] for (int i = 0; i < ncells[0]; i++) { for (int j = 0; j < ncells[1]; j++) { int idx = i*ncells[1] + j; offsets[2*idx + major] = centers[0][i]; offsets[2*idx + minor] = centers[1][j]; } } mNumInstances = ncells[0] * ncells[1]; mScale[major] = 0.5f * CELL_SIZE * scene2clip[0]; mScale[minor] = 0.5f * CELL_SIZE * scene2clip[1]; } void Renderer::step() { timespec now; clock_gettime(CLOCK_MONOTONIC, &now); uint64_t nowNs = now.tv_sec*1000000000ull + now.tv_nsec; if (mLastFrameNs > 0) { float dt = float(nowNs - mLastFrameNs) * 0.000000001f; for (unsigned int i = 0; i < mNumInstances; i++) { mAngles[i] += mAngularVelocity[i] * dt; if (mAngles[i] >= TWO_PI) { mAngles[i] -= TWO_PI; } else if (mAngles[i] <= -TWO_PI) { mAngles[i] += TWO_PI; } } float* transforms = mapTransformBuf(); for (unsigned int i = 0; i < mNumInstances; i++) { float s = sinf(mAngles[i]); float c = cosf(mAngles[i]); transforms[4*i + 0] = c * mScale[0]; transforms[4*i + 1] = s * mScale[1]; transforms[4*i + 2] = -s * mScale[0]; transforms[4*i + 3] = c * mScale[1]; } unmapTransformBuf(); } mLastFrameNs = nowNs; } void Renderer::render() { step(); glClearColor(0.2f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw(mNumInstances); checkGlError("Renderer::render"); } // ---------------------------------------------------------------------------- static Renderer* g_renderer = NULL; extern "C" { JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_init(JNIEnv* env, jobject obj); JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_resize(JNIEnv* env, jobject obj, jint width, jint height); JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_step(JNIEnv* env, jobject obj); }; #if !defined(DYNAMIC_ES3) static GLboolean gl3stubInit() { return GL_TRUE; } #endif JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_init(JNIEnv* env, jobject obj) { if (g_renderer) { delete g_renderer; g_renderer = NULL; } printGlString("Version", GL_VERSION); printGlString("Vendor", GL_VENDOR); printGlString("Renderer", GL_RENDERER); printGlString("Extensions", GL_EXTENSIONS); const char* versionStr = (const char*)glGetString(GL_VERSION); if (strstr(versionStr, "OpenGL ES 3.") && gl3stubInit()) { g_renderer = createES3Renderer(); } else if (strstr(versionStr, "OpenGL ES 2.")) { g_renderer = createES2Renderer(); } else { ALOGE("Unsupported OpenGL ES version"); } } JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_resize(JNIEnv* env, jobject obj, jint width, jint height) { if (g_renderer) { g_renderer->resize(width, height); } } JNIEXPORT void JNICALL Java_ph_edu_dlsu_opengles3_GLES3JNILib_step(JNIEnv* env, jobject obj) { if (g_renderer) { g_renderer->render(); } }
30.105634
124
0.594737
[ "render" ]
90c1978663e2ed8fa56e33c011e4ad83909f500e
12,189
cpp
C++
BezierC2.cpp
michalMilewski-8/MillingSimulator
5f914a36233004c43bc6e48dfb6dd8850ad521b9
[ "MIT" ]
null
null
null
BezierC2.cpp
michalMilewski-8/MillingSimulator
5f914a36233004c43bc6e48dfb6dd8850ad521b9
[ "MIT" ]
null
null
null
BezierC2.cpp
michalMilewski-8/MillingSimulator
5f914a36233004c43bc6e48dfb6dd8850ad521b9
[ "MIT" ]
1
2021-07-20T11:59:45.000Z
2021-07-20T11:59:45.000Z
#include "BezierC2.h" unsigned int BezierC2::counter = 1; BezierC2::BezierC2(Shader& sh) : Bezier(sh), polygon(std::make_shared<Line>(sh)), polygon_bezier(std::make_shared<Line>(sh)), geom_shader("shader_bezier_c0.vs", "shader.fs", "shader_bezier_c0.gs") { sprintf_s(name, 512, ("BezierC2 " + std::to_string(counter)).c_str()); constname = "BezierC2 " + std::to_string(counter); counter++; number_of_divisions = 100; points = std::vector<std::weak_ptr<Point>>(); this->color = { 0.7f,0.7f,0.7f,0.7f }; update_object(); } void BezierC2::DrawObject(glm::mat4 mvp_) { moved = false; if (points.size() < 2) return; if (need_update) { mvp = mvp_; update_object(); need_update = false; } else { mvp = mvp_; } if (draw_polygon) polygon->DrawObject(mvp_); if (draw_polygon_bezier) { polygon_bezier->DrawObject(mvp_); } if (show_bezier_points) { for (auto point : bezier_points) { point->DrawObject(mvp_); } } geom_shader.use(); int projectionLoc = glGetUniformLocation(geom_shader.ID, "mvp"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(mvp)); float start = 0.0f; float end = 0.0f; int number_of_divisions_greater = std::ceil(number_of_divisions / 120.0f); float stride = 1.0f / number_of_divisions_greater; glBindVertexArray(VAO); for (int i = 0; i <= number_of_divisions_greater; i++) { start = end; end = start + stride; int startLoc = glGetUniformLocation(geom_shader.ID, "start"); int endLoc = glGetUniformLocation(geom_shader.ID, "end"); glUniform1f(startLoc, start); glUniform1f(endLoc, end); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_LINES_ADJACENCY, lines.size(), GL_UNSIGNED_INT, 0); } glBindVertexArray(0); } void BezierC2::CreateMenu() { float color_new[4]; char buffer[512]; char buf[512]; int to_delete = -1; sprintf_s(buffer, "%s###%sdup2", name, constname); if (ImGui::TreeNode(buffer)) { if (ImGui::BeginPopupContextItem()) { ImGui::Text("Edit name:"); ImGui::InputText("##edit", name, IM_ARRAYSIZE(name)); if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } for (int i = 0; i < 4; i++) color_new[i] = color[i]; ImGui::Checkbox("Selected", &selected); if (selected != was_selected_in_last_frame) { Update(); was_selected_in_last_frame = selected; } ImGui::Checkbox("Draw De Bohr Polygon", &draw_polygon); if (draw_polygon != was_draw_polygon) { Update(); was_draw_polygon = draw_polygon; } ImGui::Checkbox("Show Bezier Points", &show_bezier_points); ImGui::Checkbox("Draw Bezier Polygon", &draw_polygon_bezier); if (draw_polygon_bezier != was_draw_polygon_bezier) { Update(); was_draw_polygon_bezier = draw_polygon_bezier; } ImGui::Text("Set color:"); ImGui::ColorPicker4("Color", color_new); if (ImGui::CollapsingHeader("De Bohr Points on Curve")) { for (int i = 0; i < points.size(); i++) { if (points[i].expired()) { to_delete = i; continue; } auto sp = points[i].lock(); ImGui::Text(sp->name); ImGui::SameLine(); sprintf_s(buf, "Remove###%sRm%d", sp->name, i); if (ImGui::Button(buf)) { to_delete = i; } } } if (to_delete >= 0) { points.erase(points.begin() + to_delete); polygon->DeletePoint(to_delete); Update(); } /*if (ImGui::CollapsingHeader("Bezier Points on Curve")) { for (int i = 0; i < bezier_points.size(); i++) { auto sp = bezier_points[i]; ImGui::Text(sp->name); sprintf_s(buf, "Select###%sSel%d", sp->name, i); if (ImGui::Button(buf)) { sp->Select(); } } }*/ ImGui::TreePop(); ImGui::Separator(); bool difference = false; for (int i = 0; i < 4; i++) if (color_new[i] != color[i]) { difference = true; break; } if (difference) { color = { color_new[0],color_new[1],color_new[2],color_new[3] }; Update(); } } } void BezierC2::AddPointToCurve(std::shared_ptr<Point>& point) { if (point.get()) { points.push_back(point); point->AddOwner(shared_from_this()); polygon->AddPoint(point); Update(); } } void BezierC2::Update() { need_update = true; polygon->Update(); polygon_bezier->Update(); } std::vector<std::shared_ptr<Object>> BezierC2::GetVirtualObjects() { auto res = std::vector<std::shared_ptr<Object>>(); for (auto& pt : bezier_points) { res.push_back(pt); } return res; } void BezierC2::Serialize(xml_document<>& document, xml_node<>* scene) { auto figure = document.allocate_node(node_element, "BezierC2"); figure->append_attribute(document.allocate_attribute("Name", document.allocate_string(constname.c_str()))); auto pointsNode = document.allocate_node(node_element, "Points"); for (auto& point : points) { if (!point.expired()) { auto point_rel = point.lock(); auto pointRef = document.allocate_node(node_element, "PointRef"); pointRef->append_attribute(document.allocate_attribute("Name", document.allocate_string(point_rel->constname.c_str()))); pointsNode->append_node(pointRef); } } figure->append_node(pointsNode); scene->append_node(figure); } void BezierC2::UpdateMyPointer(std::string constname_, const std::shared_ptr<Object> new_point) { for (int i = 0; i < points.size(); i++) { if (points[i].expired()) continue; auto point = points[i].lock(); if (point->CompareName(constname_)) { points.erase(points.begin() + i); points.insert(points.begin() + i, std::dynamic_pointer_cast<Point>(new_point)); } } } void BezierC2::update_object() { lines.clear(); points_on_curve.clear(); int k = 0; for (auto& pt : de_points_) { while (k < points.size() && points[k].expired()) k++; if (k >= points.size() || pt != points[k].lock()->GetPosition()) { need_new_bezier_generation = true; break; } k++; } if( k != points.size()) need_new_bezier_generation = true; if (need_new_bezier_generation) { need_new_bezier_generation = false; generate_bezier_points(); } else { k = 0; int moved_point_index = -1; for (auto& pt : points_) { if (k >= bezier_points.size() || pt != bezier_points[k]->GetPosition()) { moved_point_index = k; break; } k++; } if (moved_point_index >= 0) { translate_bezier_movement_to_de_boor(moved_point_index); generate_bezier_points(); bezier_points[moved_point_index]->Select(); } } points_.clear(); position = glm::vec3{ 0,0,0 }; int licznik = 0; for (auto& point : bezier_points) { auto sp = point->GetPosition(); points_.push_back(sp); position += sp; licznik++; } position /= licznik; create_curve(); // 1. bind Vertex Array Object glBindVertexArray(VAO); // 2. copy our vertices array in a vertex buffer for OpenGL to use glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * points_on_curve.size(), points_on_curve.data(), GL_DYNAMIC_DRAW); // 3. copy our index array in a element buffer for OpenGL to use glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * lines.size(), lines.data(), GL_DYNAMIC_DRAW); // 4. then set the vertex attributes pointers glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, description_number * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, description_number * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); } void BezierC2::create_curve() { for (int iter = 0; iter + 1 < points_.size();) { int start = iter; int end = iter + 1; for (int i = 0; i < 3 && end < points_.size(); i++) { iter++; end++; } int number_of_divisions_loc = 1; for (int odl = start; odl < end - 1; odl++) { glm::vec4 A = { points_[odl],1 }; glm::vec4 B = { points_[odl + 1],1 }; A = mvp * A; A /= A.w; B = mvp * B; B /= B.w; glm::vec2 screenA = { (A.x + 1.0f) * *screen_width / 2.0f, (B.y + 1.0f) * *screen_height / 2.0f, }; glm::vec2 screenB = { (B.x + 1.0f) * *screen_width / 2.0f, (B.y + 1.0f) * *screen_height / 2.0f, }; float len = glm::length(screenA - screenB); if (len > 0) number_of_divisions_loc += len; } if (number_of_divisions_loc > number_of_divisions) number_of_divisions = number_of_divisions_loc; } int k = 0; for (k = 0; k < points_.size(); k += 3) { for (int j = 0; j < 4; j++) { lines.push_back(k + j); } } for (auto& vec : points_) { points_on_curve.push_back(vec.x); points_on_curve.push_back(vec.y); points_on_curve.push_back(vec.z); points_on_curve.push_back(color.r); points_on_curve.push_back(color.g); points_on_curve.push_back(color.b); points_on_curve.push_back(color.a); } if (lines.size() == 0) return; int left = (lines.back() - points_.size()) + 1; while (left > 0) { points_on_curve.push_back(0.0f); points_on_curve.push_back(0.0f); points_on_curve.push_back(0.0f); points_on_curve.push_back(-1.0f); points_on_curve.push_back(-1.0f); points_on_curve.push_back(-1.0f); points_on_curve.push_back(-1.0f); left--; } } void BezierC2::generate_bezier_points() { bezier_points.clear(); de_points_.clear(); polygon_bezier->ClearPoints(); for (auto& point : points) { if (!point.expired()) { de_points_.push_back(point.lock()->GetPosition()); } } if (de_points_.size() < 4) { need_new_bezier_generation = true; return; } glm::vec3 first_pos = de_points_[0]; glm::vec3 second_pos = de_points_[1]; glm::vec3 third_pos = de_points_[2]; glm::vec3 fourth_pos = de_points_[3]; glm::vec3 second_point, third_point, fourth_point; glm::vec3 first_vec, second_vec, third_vec; glm::vec3 helper_fifth; first_vec = second_pos - first_pos; second_vec = third_pos - second_pos; third_vec = fourth_pos - third_pos; third_point = second_pos - (first_vec / 3.0f); helper_fifth = second_pos + (second_vec / 3.0f); fourth_point = third_point + (helper_fifth - third_point) / 2.0f; add_bezier_point(fourth_point); for (int i = 4; i < de_points_.size(); i++) { second_point = helper_fifth; third_point = third_pos - (second_vec / 3.0f); helper_fifth = third_pos + (third_vec / 3.0f); fourth_point = third_point + (helper_fifth- third_point) / 2.0f; add_bezier_point(second_point); add_bezier_point(third_point); add_bezier_point(fourth_point); third_pos = fourth_pos; fourth_pos = de_points_[i]; first_vec = second_vec; second_vec = third_vec; third_vec = fourth_pos - third_pos; } second_point = helper_fifth; third_point = third_pos - (second_vec / 3.0f); helper_fifth = third_pos + (third_vec / 3.0f); fourth_point = third_point + (helper_fifth - third_point) / 2.0f; add_bezier_point(second_point); add_bezier_point(third_point); add_bezier_point(fourth_point); bezier_points.shrink_to_fit(); } void BezierC2::add_bezier_point(glm::vec3 position) { auto point = std::make_shared<Point>(position, shader); bezier_points.push_back(point); point->AddOwner(shared_from_this()); polygon_bezier->AddPoint(point); point->AddOwner(polygon_bezier); } void BezierC2::translate_bezier_movement_to_de_boor(int point_index) { int moving_de_boor_point_index = 1 + point_index / 3; Point* moving_de_boor_point = get_de_boor_point(moving_de_boor_point_index); Point* right = get_de_boor_point(moving_de_boor_point_index + 1); if (!moving_de_boor_point || !right) return; glm::vec3 right_pos = right->GetPosition(); glm::vec3 sr; glm::vec3 current_bezier_point_pos = bezier_points[point_index]->GetPosition(); float multiplication_number = 1.5f; if (point_index % 3 == 0) { Point* left = get_de_boor_point(moving_de_boor_point_index - 1); if (!left ) return; glm::vec3 left_pos = left->GetPosition(); sr = left_pos + (right_pos - left_pos) / 2.0f; } else { sr = right_pos; if (point_index % 3 == 2) multiplication_number = 3.0f; } glm::vec3 intended_position = sr + (current_bezier_point_pos - sr) * multiplication_number; moving_de_boor_point->MoveObjectTo(intended_position); } Point* BezierC2::get_de_boor_point(int position) { int r = 0; for (auto& pt : points) { if (pt.expired()) continue; if (r == position) return pt.lock().get(); r++; } return nullptr; }
27.702273
123
0.67766
[ "object", "vector" ]
90d1c5efb6aabaadb9073f1ce81cddedd050385f
2,382
hpp
C++
src/trainer/trainer_pool.hpp
alexge233/cuANN
bea3db46fa38e19642ef930ab89c56b5be96ba0b
[ "Apache-2.0" ]
5
2016-02-26T02:11:14.000Z
2020-04-02T19:56:59.000Z
src/trainer/trainer_pool.hpp
alexge233/cuANN
bea3db46fa38e19642ef930ab89c56b5be96ba0b
[ "Apache-2.0" ]
null
null
null
src/trainer/trainer_pool.hpp
alexge233/cuANN
bea3db46fa38e19642ef930ab89c56b5be96ba0b
[ "Apache-2.0" ]
3
2016-07-06T00:59:17.000Z
2018-11-04T15:18:44.000Z
#ifndef _cuANN_trainer_pool_HPP_ #define _cuANN_trainer_pool_HPP_ #include "includes.ihh" #include "trainer.hpp" namespace cuANN { /// @author Alexander Giokas <a.gkiokas@warwick.ac.uk> /// @date November 2015 /// @version 1 /// @brief Trainer thread pool, used to control parallel execution of training threads. class trainer_pool { public: /// Construct for @param max_threads trainer_pool ( unsigned int max_threads, std::vector<std::shared_ptr<trainer_data>> & thread_data ) : _max_threads_(max_threads), _work(_io_service), _thread_data(thread_data) {} /// Start processing threads void start() { _threads.reserve(_max_threads_); for (int i = 0 ; i < _max_threads_; ++i) _threads.emplace_back(std::bind(&trainer_pool::thread_proc, this)); } /// Wait for the next available slot void wait() { std::unique_lock<std::mutex> lock(_cvm); _cv.wait(lock, [this] { return _tasks == 0; }); } /// Wait for all threads to finish and stop void stop() { wait(); _io_service.stop(); for (auto& t : _threads) { if (t.joinable()) t.join(); } _threads.clear(); } /// Process threads void thread_proc() { while (!_io_service.stopped()) _io_service.run(); } /// Reduce count void reduce() { std::unique_lock<std::mutex> lock(_cvm); if (--_tasks == 0) { lock.unlock(); _cv.notify_all(); } } /// Submit a new Job (worker) template <class A,class D> void submit(cuANN::trainer<A,D> & job) { std::unique_lock<std::mutex> lock(_cvm); ++ _tasks; lock.unlock(); _io_service.post([this,job] () mutable { job(_thread_data); reduce(); }); } private: unsigned int _max_threads_; boost::asio::io_service _io_service; boost::asio::io_service::work _work; std::vector<std::thread> _threads; std::vector<std::shared_ptr<trainer_data>> & _thread_data; std::condition_variable _cv; std::mutex _cvm; size_t _tasks = 0; }; } #endif
24.8125
87
0.543241
[ "vector" ]
90d40097d72f0a2222b1f5c019b1c1181e6dba82
68,436
cpp
C++
TemplePlus/gamesystems/legacysystems.cpp
mercurier/TemplePlus
244f83346d1f1afb64017ee2a8d6e3639e43320d
[ "MIT" ]
null
null
null
TemplePlus/gamesystems/legacysystems.cpp
mercurier/TemplePlus
244f83346d1f1afb64017ee2a8d6e3639e43320d
[ "MIT" ]
null
null
null
TemplePlus/gamesystems/legacysystems.cpp
mercurier/TemplePlus
244f83346d1f1afb64017ee2a8d6e3639e43320d
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <infrastructure/exception.h> #include <temple/dll.h> #include "legacysystems.h" #include <util/fixes.h> #include "gamesystems.h" #include "timeevents.h" #include <graphics/device.h> #include <graphics/camera.h> #include <config/config.h> #include <util/streams.h> #include "objects/objevent.h" #include <condition.h> #include <sound.h> #include <d20_level.h> #include <damage.h> #include <ui/ui_item_creation.h> #include "d20/d20stats.h" #include "deity/legacydeitysystem.h" #include "ui/ui_systems.h" #include "fade.h" #include "objects/objsystem.h" #include "infrastructure/vfs.h" #include "infrastructure/elfhash.h" #include "infrastructure/mesparser.h" #include "legacymapsystems.h" #include "infrastructure/meshes.h" #include "turn_based.h" #include "d20_race.h" //***************************************************************************** //* Vagrant //***************************************************************************** VagrantSystem::VagrantSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10086ae0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Vagrant"); } } VagrantSystem::~VagrantSystem() { auto shutdown = temple::GetPointer<void()>(0x10086b10); shutdown(); } void VagrantSystem::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x10086cb0); advanceTime(time); } const std::string &VagrantSystem::GetName() const { static std::string name("Vagrant"); return name; } //***************************************************************************** //* Description //***************************************************************************** DescriptionSystem::DescriptionSystem(const GameSystemConf &config) { //auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100865d0); if (!description.Init(config)){ //if (!startup(&config)) { throw TempleException("Unable to initialize game system Description"); } } DescriptionSystem::~DescriptionSystem() { /*auto shutdown = temple::GetPointer<void()>(0x10086670); shutdown();*/ description.Exit(); } void DescriptionSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10086710); if (!loadModule()) { throw TempleException("Unable to load module data for game system Description"); } } void DescriptionSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x10086780); unloadModule(); } void DescriptionSystem::Reset() { /*auto reset = temple::GetPointer<void()>(0x100866c0); reset();*/ description.Reset(); } bool DescriptionSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x10086810); return save(file) == 1; } bool DescriptionSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100868b0); return load(saveFile) == 1; } const std::string &DescriptionSystem::GetName() const { static std::string name("Description"); return name; } bool DescriptionSystem::ReadCustomNames(GameSystemSaveFile * file, std::vector<std::string>& customNamesOut){ auto count = 0; if (!tio_fread(&count, sizeof(int), 1, file->file)) return false; if (count <= 0) return true; for (auto i=0; i < count; i++){ auto nameLen = 0; tio_fread(&nameLen, sizeof(int), 1, file->file); std::string tmpStr; tmpStr.resize(nameLen + 1); tio_fread(&tmpStr[0], sizeof(char), nameLen, file->file); tmpStr[nameLen] = 0; customNamesOut.push_back(tmpStr); } return true; } //***************************************************************************** //* ItemEffect //***************************************************************************** ItemEffectSystem::ItemEffectSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100864d0); if (!startup(&config)) { throw TempleException("Unable to initialize game system ItemEffect"); } } ItemEffectSystem::~ItemEffectSystem() { auto shutdown = temple::GetPointer<void()>(0x10086550); shutdown(); } void ItemEffectSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10086560); if (!loadModule()) { throw TempleException("Unable to load module data for game system ItemEffect"); } } void ItemEffectSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x100865c0); unloadModule(); } const std::string &ItemEffectSystem::GetName() const { static std::string name("ItemEffect"); return name; } //***************************************************************************** //* Teleport //***************************************************************************** TeleportSystem::TeleportSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10084a20); if (!startup(&config)) { throw TempleException("Unable to initialize game system Teleport"); } } TeleportSystem::~TeleportSystem() { auto shutdown = temple::GetPointer<void()>(0x10084fa0); shutdown(); } void TeleportSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10084f60); reset(); } void TeleportSystem::AdvanceTime(uint32_t time) { auto &fadeAndTeleportActive = temple::GetRef<BOOL>(0x10AB74C0); if (!fadeAndTeleportActive) return; auto &teleportProcessActive = temple::GetRef<BOOL>(0x10AB74B8); teleportProcessActive = 1; tbSys.groupInitiativeList->Clear(); // fix for common crash - sometimes initiative list isn't cleared and then some other processes get invalid crap auto teleportProcess = temple::GetRef<void(__cdecl)(FadeAndTeleportArgs&)>(0x10085AA0); auto &teleportPacket = temple::GetRef<FadeAndTeleportArgs>(0x10AB74C8); teleportProcess(teleportPacket); teleportProcessActive = 0; fadeAndTeleportActive = 0; if (teleportPacket.flags & FadeAndTeleportFlags::ftf_unk80000000){ if (teleportPacket.flags & FadeAndTeleportFlags::ftf_unk20){ temple::GetRef<void(__cdecl)()>(0x100027E0)(); // GameEnableDrawing } } /*auto advanceTime = temple::GetPointer<void(uint32_t)>(0x10086480); advanceTime(time);*/ } const std::string &TeleportSystem::GetName() const { static std::string name("Teleport"); return name; } // Originally @ 0x10084af0 bool TeleportSystem::IsObjectTeleporting(objHndl handle) const { static auto orgMethod = temple::GetPointer<BOOL(objHndl)>(0x10084af0); return orgMethod(handle) == 1; } //***************************************************************************** //* Sector //***************************************************************************** SectorSystem::SectorSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10082db0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Sector"); } } SectorSystem::~SectorSystem() { auto shutdown = temple::GetPointer<void()>(0x10081bc0); shutdown(); } void SectorSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10081bb0); reset(); } bool SectorSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x10081be0); return save(file) == 1; } bool SectorSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x10081d20); return load(saveFile) == 1; } const std::string &SectorSystem::GetName() const { static std::string name("Sector"); return name; } void SectorSystem::SetLimits(uint64_t limitX, uint64_t limitY) { static auto set_sector_limit = temple::GetPointer<BOOL(uint64_t, uint64_t)>(0x10081940); set_sector_limit(limitX, limitY); } bool SectorSystem::ReadSectorTimes(GameSystemSaveFile * saveFile, std::vector<SectorTime>& sectorTimes){ auto count = 0; if (!tio_fread(&count, sizeof(int), 1, saveFile->file)) return false; if (count > 2 * config.sectorCacheSize) return false; sectorTimes.resize(count); if (!count) return true; if (tio_fread(&sectorTimes[0], sizeof(SectorTime), count, saveFile->file) != count) return false; return true; } //***************************************************************************** //* Random //***************************************************************************** RandomSystem::RandomSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10039040); if (!startup(&config)) { throw TempleException("Unable to initialize game system Random"); } } const std::string &RandomSystem::GetName() const { static std::string name("Random"); return name; } //***************************************************************************** //* Critter //***************************************************************************** CritterSystem::CritterSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007e310); if (!startup(&config)) { throw TempleException("Unable to initialize game system Critter"); } } CritterSystem::~CritterSystem() { auto shutdown = temple::GetPointer<void()>(0x1007e3f0); shutdown(); } const std::string &CritterSystem::GetName() const { static std::string name("Critter"); return name; } void CritterSystem::UpdateNpcHealingTimers() { auto updateHealing = temple::GetPointer<void()>(0x10080490); updateHealing(); } //***************************************************************************** //* ScriptName //***************************************************************************** ScriptNameSystem::ScriptNameSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007e000); if (!startup(&config)) { throw TempleException("Unable to initialize game system ScriptName"); } } ScriptNameSystem::~ScriptNameSystem() { auto shutdown = temple::GetPointer<void()>(0x1007e0c0); shutdown(); } void ScriptNameSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1007e0e0); if (!loadModule()) { throw TempleException("Unable to load module data for game system ScriptName"); } } void ScriptNameSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x1007e1b0); unloadModule(); } const std::string &ScriptNameSystem::GetName() const { static std::string name("ScriptName"); return name; } //***************************************************************************** //* Portrait //***************************************************************************** PortraitSystem::PortraitSystem(const GameSystemConf &config) { //auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007de10); if (!mesFuncs.Open("art\\interface\\portraits\\portraits.mes", &mPortraitsMes)){ throw TempleException("Unable to initialize game system Portrait"); } TioFileList flist; tio_filelist_create(&flist, "art\\interface\\portraits\\*"); for (auto i=0; i < flist.count; i++){ auto &fentry = flist.files[i]; if (!(fentry.attribs & TioFileAttribs::TFA_SUBDIR)) continue; if (!_strcmpi(fentry.name, ".") || !_strcmpi(fentry.name, "..")) continue; PortraitPack porPackNew; porPackNew.path = fmt::format("art\\interface\\portraits\\{}", fentry.name); porPackNew.key = ElfHash::Hash(fentry.name); if (porPackNew.key > 0 && porPackNew.key <= PORTRAIT_MAX_ID){ porPackNew.key = ElfHash::Hash(fmt::format("{}a{}b{}c{}",fentry.name, fentry.name, fentry.name, fentry.name)); } auto portFname = fmt::format("{}\\portraits.mes", porPackNew.path); if (!tio_fileexists(portFname.c_str())) continue; auto mesContent = MesFile::ParseFile(portFname); TioFileList portraitTgaFiles; tio_filelist_create(&portraitTgaFiles, fmt::format("{}\\*.tga", porPackNew.path).c_str()); auto lastIdx = 0; for (auto it: mesContent){ auto portraitFname = fmt::format("{}\\{}",porPackNew.path, it.second); //if (!tio_fileexists(portraitFname.c_str())) // so it doesn't list non-existant entries (i.e. stuff that's not in the extension folder) // continue; auto foundFile = false; for (auto j= 0 ; j < portraitTgaFiles.count; j++){ if (!_strcmpi(portraitTgaFiles.files[ (j + lastIdx) % portraitTgaFiles.count].name, it.second.c_str())){ foundFile = true; lastIdx = j + lastIdx + 1; break; } } if (!foundFile) continue; porPackNew.packContents[it.first] = it.second; } tio_filelist_destroy(&portraitTgaFiles); mPortraitPacks.push_back(porPackNew); } tio_filelist_destroy(&flist); } PortraitSystem::~PortraitSystem() { /*auto shutdown = temple::GetPointer<void()>(0x1007de30); shutdown();*/ mesFuncs.Close(mPortraitsMes); } const std::string &PortraitSystem::GetName() const { static std::string name("Portrait"); return name; } bool PortraitSystem::GetFirstId(objHndl handle, int* idxOut) const { *idxOut = 0; MesLine line; if (!mesFuncs.GetFirstLine(mPortraitsMes, &line)) return false; auto mesFindLine = temple::GetRef<BOOL(__cdecl)(MesHandle, MesLine*)>(0x101E6650); while (line.key % 10 || !IsPortraitFilenameValid(handle, line.value)){ if (!mesFindLine(mPortraitsMes, &line)) return false; } *idxOut = line.key; return true; } bool PortraitSystem::GetNextId(objHndl handle, int* idxOut) const { MesLine line(*idxOut); auto findNextLine = temple::GetRef<BOOL(__cdecl)(MesHandle, MesLine*)>(0x101E6650); MesHandle mh = mPortraitsMes; auto packKey = GetKeyFromId(line.key); auto moveToFirstPortraitPack = [&](){ // moves to first portrait pack (if any is found) after exhausting the "normal" portraits if (!mPortraitPacks.size()) return false; if (!mPortraitPacks[0].packContents.size()) return false; packKey = mPortraitPacks[0].key; *idxOut = mPortraitPacks[0].packContents.begin()->first ^ packKey; return true; }; // normal portraits retrieval if (packKey == 0){ if (!findNextLine(mh, &line)){ return moveToFirstPortraitPack(); } while (line.key % 10 || !IsPortraitFilenameValid(handle, line.value)) { if (!findNextLine(mh, &line)){ return moveToFirstPortraitPack(); } } *idxOut = (line.key ^ packKey); return true; } auto moveToNextPortraitPack= [&](){ auto isNextOne = false; for (auto it : mPortraitPacks){ if (isNextOne) { if (!it.packContents.size()) continue; /// todo verify is multiple of 10 *idxOut = it.packContents.begin()->first ^ it.key; return true; } if (it.key == packKey){ isNextOne = true; continue; } } return false; }; if (packKey != 0){ for (auto it: mPortraitPacks){ if (it.key != packKey) continue; // found the portrait pack from the id auto foundPortrait = false; auto dekey = *idxOut ^ packKey; auto nextId = it.packContents.find(dekey); do { std::advance(nextId, 1); } while (nextId != it.packContents.end() && (nextId->first % 10) ); if (nextId == it.packContents.end()){ return moveToNextPortraitPack(); } auto result = nextId->first; *idxOut = result ^ packKey; return true; } } return false; } int PortraitSystem::GetKeyFromId(int id) const{ if (id < PORTRAIT_MAX_ID) return 0; for (auto it : mPortraitPacks){ auto dekey = (int)(id ^ it.key); if (dekey > 0 && dekey < PORTRAIT_MAX_ID) return it.key; } return 0; } std::string PortraitSystem::GetPortraitFileFromId(int id, int subId){ auto packKey = GetKeyFromId(id); auto result = fmt::format("art\\interface\\portraits\\"); MesLine line(id + subId); if(!packKey){ // normal portraits.mes if (!mesFuncs.GetLine(mPortraitsMes, &line)) { // If not found, use TempMan line.key = 0 + subId; mesFuncs.GetLine(mPortraitsMes, &line); } result.append(line.value); return result; } // get from new portrait pack for (auto it: mPortraitPacks){ if (it.key != packKey) continue; auto dekey = id ^ packKey; auto portFind = it.packContents.find(dekey + subId); if (portFind == it.packContents.end()){ // not found, return TempMan line.key = 0 + subId; mesFuncs.GetLine(mPortraitsMes, &line); result.append(line.value); return result; } result = fmt::format("{}\\{}", it.path, portFind->second); return result; } // failsafe line.key = 0 + subId; mesFuncs.GetLine(mPortraitsMes, &line); result.append(line.value); return result; } bool PortraitSystem::IsModularId(int id){ return ((unsigned int)id) >= PORTRAIT_MAX_ID; } bool PortraitSystem::IsPortraitFilenameValid(objHndl handle, const char* filename) { if (!filename || !*filename || !_strnicmp("TMP", filename, 3)) return false; if (!_strnicmp("NPC", filename, 3) || !_strnicmp("MOO", filename, 3)) { return objSystem->GetObject(handle)->IsNPC(); } return true; } //***************************************************************************** //* Skill //***************************************************************************** SkillSystem::SkillSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007cfa0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Skill"); } } SkillSystem::~SkillSystem() { auto shutdown = temple::GetPointer<void()>(0x1007d0c0); shutdown(); } bool SkillSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1007d110); return save(file) == 1; } bool SkillSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1007d0e0); return load(saveFile) == 1; } const std::string &SkillSystem::GetName() const { static std::string name("Skill"); return name; } bool SkillSystem::ReadUnknown(GameSystemSaveFile * saveFile, int & unk){ return tio_fread(&unk, sizeof(int), 1, saveFile->file) == 1; } //***************************************************************************** //* Feat //***************************************************************************** FeatSystem::FeatSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007bfa0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Feat"); } } FeatSystem::~FeatSystem() { auto shutdown = temple::GetPointer<void()>(0x1007b900); shutdown(); } const std::string &FeatSystem::GetName() const { static std::string name("Feat"); return name; } //***************************************************************************** //* Spell //***************************************************************************** SpellSystem::SpellSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1007b740); if (!startup(&config)) { throw TempleException("Unable to initialize game system Spell"); } spellSys.Init(config); } SpellSystem::~SpellSystem() { auto shutdown = temple::GetPointer<void()>(0x100791d0); mesFuncs.Close(spellSys.spellEnumsExt); mesFuncs.Close(spellSys.spellMesExt); shutdown(); } void SpellSystem::Reset() { auto reset = temple::GetPointer<void()>(0x100750f0); reset(); } const std::string &SpellSystem::GetName() const { static std::string name("Spell"); return name; } bool SpellSystem::Save(TioFile* file) { logger->debug("Saving Spells: {} spells initially in SpellsCastRegistry." , spellSys.spellCastIdxTable->itemCount); spellSys.SpellSavePruneInactive(); logger->debug("Saving Spells: {} spells after pruning.", spellSys.spellCastIdxTable->itemCount); TioOutputStream tios(file); auto spellIdSerial = temple::GetPointer<int>(0x10AAF204); tios.WriteInt32(*spellIdSerial); // tio_fwrite(spellIdSerial, sizeof(int), 1, file); int numSpells = spellSys.spellCastIdxTable->itemCount; tios.WriteInt32(numSpells); /*if (!tio_fwrite(&numSpells, sizeof(int), 1, file)) return FALSE;*/ auto numSerialized = spellSys.SpellSave(tios); if (numSerialized != numSpells) { logger->error("Serialized wrong number of spells! SAVE IS CORRUPT! Serialized: {}, expected: {}", numSerialized, numSpells); } return TRUE; static auto spell_save = temple::GetPointer<BOOL(TioFile *)>(0x10079220); auto result = spell_save(file); return result == TRUE; } bool SpellSystem::Load(GameSystemSaveFile* file) { logger->info("Loading Spells: {} spells initially in SpellsCastRegistry.", spellSys.spellCastIdxTable->itemCount); static auto spell__spell_load = temple::GetPointer<BOOL(GameSystemSaveFile*)>(0x100792a0); auto spellIdSerial = temple::GetPointer<uint32_t>(0x10AAF204); tio_fread(spellIdSerial, sizeof(int), 1, file->file); uint32_t numSpells; if (tio_fread(&numSpells, 4, 1, file->file) != 1) return FALSE; Expects(numSpells >= 0); Expects(*spellIdSerial >= numSpells); if (numSpells <= 0) return TRUE; uint32_t spellId; SpellPacket pkt; for (uint32_t i = 0; i < numSpells; i++) { if (spellSys.LoadActiveSpellElement(file->file, spellId, pkt) != 1 ){ logger->warn("Loading Spells: Failure! {} spells in SpellsCastRegistry after loading.", spellSys.spellCastIdxTable->itemCount); return FALSE; } if (! (spellId <= *spellIdSerial)){ logger->warn("Invalid spellId {} detected, greater than spellIdSerial!", spellId); } if (!pkt.spellPktBody.caster) { logger->warn("Null caster object!", spellId); } spellSys.SpellsCastRegistryPut(spellId, pkt); } logger->info("Loading Spells: {} spells in SpellsCastRegistry after loading.", spellSys.spellCastIdxTable->itemCount); return TRUE; auto result = spell__spell_load(file); return result == TRUE; } //***************************************************************************** //* Stat //***************************************************************************** StatSystem::StatSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10073680); if (!startup(&config)) { throw TempleException("Unable to initialize game system Stat"); } d20Stats.Init(config); // registers the T+ overrides } StatSystem::~StatSystem() { auto shutdown = temple::GetPointer<void()>(0x100739b0); shutdown(); } const std::string &StatSystem::GetName() const { static std::string name("Stat"); return name; } //***************************************************************************** //* Script //***************************************************************************** ScriptSystem::ScriptSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10006580); if (!startup(&config)) { throw TempleException("Unable to initialize game system Script"); } } ScriptSystem::~ScriptSystem() { auto shutdown = temple::GetPointer<void()>(0x10007b60); shutdown(); } void ScriptSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10006630); if (!loadModule()) { throw TempleException("Unable to load module data for game system Script"); } } void ScriptSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x10006650); unloadModule(); } void ScriptSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10007ae0); reset(); } bool ScriptSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100066e0); return save(file) == 1; } bool ScriptSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x10006670); return load(saveFile) == 1; } const std::string &ScriptSystem::GetName() const { static std::string name("Script"); return name; } bool ScriptSystem::ReadGlobalVars(GameSystemSaveFile * saveFile, std::vector<int>& globalVars, std::vector<int>& globalFlagsData, int & storyState){ globalVars.resize(2000); globalFlagsData.resize(100); if (!tio_fread(&globalVars[0], sizeof(int) * 2000, 1, saveFile->file) || !tio_fread(&globalFlagsData[0], sizeof(int) * 100, 1, saveFile->file) || !tio_fread(&storyState, sizeof(int), 1, saveFile->file) ) return false; return true; } bool ScriptSystem::ReadEncounterQueue(GameSystemSaveFile * saveFile, std::vector<int>& encounterQueue){ int count = 0; if (!tio_fread(&count, sizeof(int), 1, saveFile->file)) return false; encounterQueue.resize(count); if (!count) return true; if (tio_fread(&encounterQueue[0], sizeof(int), count, saveFile->file) != count) return false; return true; } //***************************************************************************** //* Level //***************************************************************************** LevelSystem::LevelSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10072f50); if (!startup(&config)) { throw TempleException("Unable to initialize game system Level"); } } LevelSystem::~LevelSystem() { auto shutdown = temple::GetPointer<void()>(0x10073180); shutdown(); } const std::string &LevelSystem::GetName() const { static std::string name("Level"); return name; } //***************************************************************************** //* D20 //***************************************************************************** D20System::D20System(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1004c8a0); if (!startup(&config)) { throw TempleException("Unable to initialize game system D20"); } d20RaceSys.GetRaceSpecsFromPython(); conds.RegisterNewConditions(); // also initializes tpdp and race_defs modules d20ClassSys.GetClassSpecs(); d20LevelSys.GenerateSpellsPerLevelTables(); damage.Init(); d20Sys.GetPythonActionSpecs(); } D20System::~D20System() { auto shutdown = temple::GetPointer<void()>(0x1004c950); shutdown(); damage.Exit(); } void D20System::Reset() { auto reset = temple::GetPointer<void()>(0x1004c9b0); reset(); } void D20System::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x1004fc40); advanceTime(time); } const std::string &D20System::GetName() const { static std::string name("D20"); return name; } void D20System::RemoveDispatcher(objHndl obj) { using FnRemoveDispatcher = void(objHndl); static FnRemoveDispatcher* removeDispatcher = temple::GetPointer<FnRemoveDispatcher>(0x1004FEE0); removeDispatcher(obj); } void D20System::ResetRadialMenus() { static auto radialmenu_reset = temple::GetPointer<void()>(0x100eff40); radialmenu_reset(); } //***************************************************************************** //* LightScheme //***************************************************************************** LightSchemeSystem::LightSchemeSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1006ef30); if (!startup(&config)) { throw TempleException("Unable to initialize game system LightScheme"); } } LightSchemeSystem::~LightSchemeSystem() { auto shutdown = temple::GetPointer<void()>(0x1006ef80); shutdown(); } void LightSchemeSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1006f440); if (!loadModule()) { throw TempleException("Unable to load module data for game system LightScheme"); } } void LightSchemeSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x1006ef50); unloadModule(); } void LightSchemeSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1006f430); reset(); } bool LightSchemeSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1006ef90); return save(file) == 1; } bool LightSchemeSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1006f470); return load(saveFile) == 1; } const std::string &LightSchemeSystem::GetName() const { static std::string name("LightScheme"); return name; } void LightSchemeSystem::SetLightSchemeId(int schemeId) { static auto set_map_lightscheme_id = temple::GetPointer<BOOL(int)>(0x1006efd0); set_map_lightscheme_id(schemeId); } void LightSchemeSystem::SetLightScheme(int schemeId, int hour) { static auto set_lightscheme = temple::GetPointer<signed int(int lightSchemeId, int hourOfDay)>(0x1006f350); set_lightscheme(schemeId, hour); } int LightSchemeSystem::GetHourOfDay() { static auto lightscheme_get_hour = temple::GetPointer<int()>(0x1006f0b0); return lightscheme_get_hour(); } bool LightSchemeSystem::IsUpdating() const { static auto lightscheme_is_updating = temple::GetPointer<int()>(0x1006f0c0); return lightscheme_is_updating() == 1; } //***************************************************************************** //* Player //***************************************************************************** PlayerSystem::PlayerSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1006ede0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Player"); } } PlayerSystem::~PlayerSystem() { auto shutdown = temple::GetPointer<void()>(0x1006ee40); shutdown(); } void PlayerSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1006ee00); reset(); } bool PlayerSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x101f5850); return save(file) == 1; } bool PlayerSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x101f5850); return load(saveFile) == 1; } const std::string &PlayerSystem::GetName() const { static std::string name("Player"); return name; } //***************************************************************************** //* Area //***************************************************************************** AreaSystem::AreaSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1006e550); if (!startup(&config)) { throw TempleException("Unable to initialize game system Area"); } } void AreaSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1006e590); if (!loadModule()) { throw TempleException("Unable to load module data for game system Area"); } } void AreaSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x1006e860); unloadModule(); } void AreaSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1006e560); reset(); } bool AreaSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1006e920); return save(file) == 1; } bool AreaSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1006e8d0); return load(saveFile) == 1; } const std::string &AreaSystem::GetName() const { static std::string name("Area"); return name; } //***************************************************************************** //* Dialog //***************************************************************************** DialogSystem::DialogSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10036040); if (!startup(&config)) { throw TempleException("Unable to initialize game system Dialog"); } } DialogSystem::~DialogSystem() { auto shutdown = temple::GetPointer<void()>(0x10036080); shutdown(); } const std::string &DialogSystem::GetName() const { static std::string name("Dialog"); return name; } //***************************************************************************** //* SoundMap //***************************************************************************** SoundMapSystem::SoundMapSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1006ded0); if (!startup(&config)) { throw TempleException("Unable to initialize game system SoundMap"); } } const std::string &SoundMapSystem::GetName() const { static std::string name("SoundMap"); return name; } //***************************************************************************** //* SoundGame //***************************************************************************** SoundGameSystem::SoundGameSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1003d4a0); if (!startup(&config)) { throw TempleException("Unable to initialize game system SoundGame"); } sound.Init(); // init user_sounds extensions } SoundGameSystem::~SoundGameSystem() { auto shutdown = temple::GetPointer<void()>(0x1003bb10); shutdown(); } void SoundGameSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1003bb80); if (!loadModule()) { throw TempleException("Unable to load module data for game system SoundGame"); } mesFuncs.Open("tpmes\\sounds.mes", &sound.tpSounds); } void SoundGameSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x1003bbc0); unloadModule(); mesFuncs.Close(sound.tpSounds); } void SoundGameSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1003cb30); reset(); } bool SoundGameSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1003bbd0); return save(file) == 1; } bool SoundGameSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1003cb70); return load(saveFile) == 1; } void SoundGameSystem::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x1003dc50); advanceTime(time); } const std::string &SoundGameSystem::GetName() const { static std::string name("SoundGame"); return name; } void SoundGameSystem::SetSoundSchemeIds(int scheme1, int scheme2) { static auto soundscheme_set = temple::GetPointer<void(int, int)>(0x1003c4d0); soundscheme_set(scheme1, scheme2); } void SoundGameSystem::StopAll(bool flag) { static auto soundgame_stop_all = temple::GetPointer<void(int a1)>(0x1003c5b0); soundgame_stop_all(flag ? TRUE : FALSE); } //***************************************************************************** //* Item //***************************************************************************** ItemSystem::ItemSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10063c70); if (!startup(&config)) { throw TempleException("Unable to initialize game system Item"); } } ItemSystem::~ItemSystem() { auto shutdown = temple::GetPointer<void()>(0x10063dc0); shutdown(); } void ItemSystem::ResetBuffers(const RebuildBufferInfo& rebuildInfo) { auto resetBuffers = temple::GetPointer<void(const RebuildBufferInfo*)>(0x10063df0); resetBuffers(&rebuildInfo); } const std::string &ItemSystem::GetName() const { static std::string name("Item"); return name; } //***************************************************************************** //* Combat //***************************************************************************** CombatSystem::CombatSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10063ba0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Combat"); } } CombatSystem::~CombatSystem() { auto shutdown = temple::GetPointer<void()>(0x10062eb0); shutdown(); } void CombatSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10062ed0); reset(); } bool CombatSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x10062440); return save(file) == 1; } bool CombatSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x10062470); return load(saveFile) == 1; } void CombatSystem::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x10062e20); advanceTime(time); } const std::string &CombatSystem::GetName() const { static std::string name("Combat"); return name; } //***************************************************************************** //* Rumor //***************************************************************************** RumorSystem::RumorSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1005f960); if (!startup(&config)) { throw TempleException("Unable to initialize game system Rumor"); } } RumorSystem::~RumorSystem() { auto shutdown = temple::GetPointer<void()>(0x1005f9d0); shutdown(); } void RumorSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x101f5850); if (!loadModule()) { throw TempleException("Unable to load module data for game system Rumor"); } } bool RumorSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x101f5850); return save(file) == 1; } bool RumorSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x101f5850); return load(saveFile) == 1; } const std::string &RumorSystem::GetName() const { static std::string name("Rumor"); return name; } //***************************************************************************** //* Quest //***************************************************************************** QuestSystem::QuestSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1005f660); if (!startup(&config)) { throw TempleException("Unable to initialize game system Quest"); } } QuestSystem::~QuestSystem() { auto shutdown = temple::GetPointer<void()>(0x1005f2d0); shutdown(); } void QuestSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1005f310); if (!loadModule()) { throw TempleException("Unable to load module data for game system Quest"); } } void QuestSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1005f2a0); reset(); } bool QuestSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1005f3a0); return save(file) == 1; } bool QuestSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1005f320); return load(saveFile) == 1; } const std::string &QuestSystem::GetName() const { static std::string name("Quest"); return name; } //***************************************************************************** //* AI //***************************************************************************** AISystem::AISystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10056d50); if (!startup(&config)) { throw TempleException("Unable to initialize game system AI"); } } void AISystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10056e30); if (!loadModule()) { throw TempleException("Unable to load module data for game system AI"); } } const std::string &AISystem::GetName() const { static std::string name("AI"); return name; } void AISystem::AddAiTimer(objHndl handle) { static auto ai_schedule_npc_timer = temple::GetPointer<void(objHndl)>(0x1005d5e0); ai_schedule_npc_timer(handle); } //***************************************************************************** //* AnimPrivate //***************************************************************************** AnimPrivateSystem::AnimPrivateSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10055280); if (!startup(&config)) { throw TempleException("Unable to initialize game system AnimPrivate"); } } AnimPrivateSystem::~AnimPrivateSystem() { auto shutdown = temple::GetPointer<void()>(0x100552f0); shutdown(); } void AnimPrivateSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10054dd0); reset(); } const std::string &AnimPrivateSystem::GetName() const { static std::string name("AnimPrivate"); return name; } //***************************************************************************** //* Reputation //***************************************************************************** ReputationSystem::ReputationSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10054b00); if (!startup(&config)) { throw TempleException("Unable to initialize game system Reputation"); } } ReputationSystem::~ReputationSystem() { auto shutdown = temple::GetPointer<void()>(0x10054240); shutdown(); } void ReputationSystem::Reset() { auto reset = temple::GetPointer<void()>(0x100542a0); reset(); } bool ReputationSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100542d0); return save(file) == 1; } bool ReputationSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100542f0); return load(saveFile) == 1; } const std::string &ReputationSystem::GetName() const { static std::string name("Reputation"); return name; } //***************************************************************************** //* Reaction //***************************************************************************** ReactionSystem::ReactionSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10053bd0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Reaction"); } } ReactionSystem::~ReactionSystem() { auto shutdown = temple::GetPointer<void()>(0x10053c50); shutdown(); } const std::string &ReactionSystem::GetName() const { static std::string name("Reaction"); return name; } //***************************************************************************** //* TileScript //***************************************************************************** TileScriptSystem::TileScriptSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10053980); if (!startup(&config)) { throw TempleException("Unable to initialize game system TileScript"); } } TileScriptSystem::~TileScriptSystem() { auto shutdown = temple::GetPointer<void()>(0x100539d0); shutdown(); } const std::string &TileScriptSystem::GetName() const { static std::string name("TileScript"); return name; } //***************************************************************************** //* SectorScript //***************************************************************************** SectorScriptSystem::SectorScriptSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x101f5850); if (!startup(&config)) { throw TempleException("Unable to initialize game system SectorScript"); } } const std::string &SectorScriptSystem::GetName() const { static std::string name("SectorScript"); return name; } //***************************************************************************** //* WP //***************************************************************************** WPSystem::WPSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100533c0); if (!startup(&config)) { throw TempleException("Unable to initialize game system WP"); } } WPSystem::~WPSystem() { auto shutdown = temple::GetPointer<void()>(0x10053410); shutdown(); } void WPSystem::ResetBuffers(const RebuildBufferInfo& rebuildInfo) { auto resetBuffers = temple::GetPointer<void(const RebuildBufferInfo*)>(0x10053430); resetBuffers(&rebuildInfo); } const std::string &WPSystem::GetName() const { static std::string name("WP"); return name; } //***************************************************************************** //* InvenSource //***************************************************************************** InvenSourceSystem::InvenSourceSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10053220); if (!startup(&config)) { throw TempleException("Unable to initialize game system InvenSource"); } } InvenSourceSystem::~InvenSourceSystem() { auto shutdown = temple::GetPointer<void()>(0x100525f0); shutdown(); } const std::string &InvenSourceSystem::GetName() const { static std::string name("InvenSource"); return name; } //***************************************************************************** //* TownMap //***************************************************************************** void TownMapSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10051cd0); if (!loadModule()) { throw TempleException("Unable to load module data for game system TownMap"); } } void TownMapSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x10052130); unloadModule(); } void TownMapSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10052100); reset(); } const std::string &TownMapSystem::GetName() const { static std::string name("TownMap"); return name; } //***************************************************************************** //* GMovie //***************************************************************************** void GMovieSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x10033d90); if (!loadModule()) { throw TempleException("Unable to load module data for game system GMovie"); } } void GMovieSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x10033dc0); unloadModule(); } const std::string &GMovieSystem::GetName() const { static std::string name("GMovie"); return name; } //***************************************************************************** //* Brightness //***************************************************************************** BrightnessSystem::BrightnessSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10051ca0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Brightness"); } } const std::string &BrightnessSystem::GetName() const { static std::string name("Brightness"); return name; } //***************************************************************************** //* GFade //***************************************************************************** GFadeSystem::GFadeSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100519e0); if (!startup(&config)) { throw TempleException("Unable to initialize game system GFade"); } } void GFadeSystem::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x10051a10); advanceTime(time); } const std::string &GFadeSystem::GetName() const { static std::string name("GFade"); return name; } //***************************************************************************** //* AntiTeleport //***************************************************************************** AntiTeleportSystem::AntiTeleportSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10051830); if (!startup(&config)) { throw TempleException("Unable to initialize game system AntiTeleport"); } } AntiTeleportSystem::~AntiTeleportSystem() { auto shutdown = temple::GetPointer<void()>(0x10051870); shutdown(); } void AntiTeleportSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x100518c0); if (!loadModule()) { throw TempleException("Unable to load module data for game system AntiTeleport"); } } void AntiTeleportSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x10051990); unloadModule(); } const std::string &AntiTeleportSystem::GetName() const { static std::string name("AntiTeleport"); return name; } //***************************************************************************** //* Trap //***************************************************************************** TrapSystem::TrapSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10050da0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Trap"); } } TrapSystem::~TrapSystem() { auto shutdown = temple::GetPointer<void()>(0x10050940); shutdown(); } const std::string &TrapSystem::GetName() const { static std::string name("Trap"); return name; } //***************************************************************************** //* MonsterGen //***************************************************************************** MonsterGenSystem::MonsterGenSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100500c0); if (!startup(&config)) { throw TempleException("Unable to initialize game system MonsterGen"); } } MonsterGenSystem::~MonsterGenSystem() { auto shutdown = temple::GetPointer<void()>(0x10050160); shutdown(); } void MonsterGenSystem::ResetBuffers(const RebuildBufferInfo& rebuildInfo) { auto resetBuffers = temple::GetPointer<void(const RebuildBufferInfo*)>(0x10050170); resetBuffers(&rebuildInfo); } void MonsterGenSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10050140); reset(); } bool MonsterGenSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100501d0); return save(file) == 1; } bool MonsterGenSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100501a0); return load(saveFile) == 1; } const std::string &MonsterGenSystem::GetName() const { static std::string name("MonsterGen"); return name; } //***************************************************************************** //* Party //***************************************************************************** PartySystem::PartySystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1002b9d0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Party"); } } void PartySystem::Reset() { auto reset = temple::GetPointer<void()>(0x1002ac00); reset(); } bool PartySystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1002ac70); return save(file) == 1; } bool PartySystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1002ad80); return load(saveFile) == 1; } const std::string &PartySystem::GetName() const { static std::string name("Party"); return name; } void PartySystem::SaveCurrent() { auto saveCurrent = temple::GetPointer<void()>(0x1002BA40); saveCurrent(); } void PartySystem::RestoreCurrent() { auto restoreCurrent = temple::GetPointer<void()>(0x1002AEA0); restoreCurrent(); } bool PartySystem::IsInParty(objHndl obj) const { static auto IsInParty = temple::GetPointer<BOOL(objHndl)>(0x1002b1b0); return IsInParty(obj) == TRUE; } void PartySystem::ForEachInParty(std::function<void(objHndl)> callback) { static auto party_size = temple::GetPointer<size_t()>(0x1002b2b0); static auto party_get = temple::GetPointer<objHndl(size_t)>(0x1002b150); auto count = party_size(); for (size_t i = 0; i < count; ++i) { auto handle = party_get(i); callback(handle); } } //***************************************************************************** //* D20LoadSave //***************************************************************************** bool D20LoadSaveSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x1004fb70); return save(file) == 1; } bool D20LoadSaveSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x1004fbd0); return load(saveFile) == 1; } const std::string &D20LoadSaveSystem::GetName() const { static std::string name("D20LoadSave"); return name; } //***************************************************************************** //* GameInit //***************************************************************************** GameInitSystem::GameInitSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1004c610); if (!startup(&config)) { throw TempleException("Unable to initialize game system GameInit"); } } GameInitSystem::~GameInitSystem() { auto shutdown = temple::GetPointer<void()>(0x1004c690); shutdown(); } void GameInitSystem::LoadModule() { auto loadModule = temple::GetPointer<int()>(0x1004c6a0); if (!loadModule()) { throw TempleException("Unable to load module data for game system GameInit"); } } void GameInitSystem::UnloadModule() { auto unloadModule = temple::GetPointer<void()>(0x1004c850); unloadModule(); } void GameInitSystem::Reset() { auto reset = temple::GetPointer<void()>(0x1004c660); reset(); } const std::string &GameInitSystem::GetName() const { static std::string name("GameInit"); return name; } //***************************************************************************** //* Deity //***************************************************************************** DeitySystem::DeitySystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1004a760); if (!startup(&config)) { throw TempleException("Unable to initialize game system Deity"); } deitySys.Init(); } DeitySystem::~DeitySystem() { auto shutdown = temple::GetPointer<void()>(0x1004a800); shutdown(); } const std::string &DeitySystem::GetName() const { static std::string name("Deity"); return name; } //***************************************************************************** //* UiArtManager //***************************************************************************** UiArtManagerSystem::UiArtManagerSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x1004a610); if (!startup(&config)) { throw TempleException("Unable to initialize game system UiArtManager"); } } UiArtManagerSystem::~UiArtManagerSystem() { auto shutdown = temple::GetPointer<void()>(0x1004a250); shutdown(); } const std::string &UiArtManagerSystem::GetName() const { static std::string name("UiArtManager"); return name; } //***************************************************************************** //* Cheats //***************************************************************************** CheatsSystem::CheatsSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10048a60); if (!startup(&config)) { throw TempleException("Unable to initialize game system Cheats"); } } const std::string &CheatsSystem::GetName() const { static std::string name("Cheats"); return name; } //***************************************************************************** //* D20Rolls //***************************************************************************** D20RollsSystem::D20RollsSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100475d0); if (!startup(&config)) { throw TempleException("Unable to initialize game system D20Rolls"); } } D20RollsSystem::~D20RollsSystem() { auto shutdown = temple::GetPointer<void()>(0x10047150); shutdown(); } void D20RollsSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10047160); reset(); } bool D20RollsSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100471a0); return save(file) == 1; } bool D20RollsSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100471e0); return load(saveFile) == 1; } const std::string &D20RollsSystem::GetName() const { static std::string name("D20Rolls"); return name; } //***************************************************************************** //* Secretdoor //***************************************************************************** SecretdoorSystem::SecretdoorSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10046370); if (!startup(&config)) { throw TempleException("Unable to initialize game system Secretdoor"); } } void SecretdoorSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10046390); reset(); } bool SecretdoorSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100463b0); return save(file) == 1; } bool SecretdoorSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x10046400); return load(saveFile) == 1; } const std::string &SecretdoorSystem::GetName() const { static std::string name("Secretdoor"); return name; } //***************************************************************************** //* MapFogging //***************************************************************************** MapFoggingSystem::MapFoggingSystem(gfx::RenderingDevice &device) : mDevice(device) { mFogCheckData = nullptr; mFoggingEnabled = true; for (size_t i = 0; i < 8; i++) { mFogBuffers[i] = malloc(16 * sFogBufferDim * sFogBufferDim); } InitScreenBuffers(); mEsdLoaded = 0; memset(&mEsdSectorLocs[0], 0, 32 * sizeof(uint64_t)); config.AddVanillaSetting("fog checks", "1", [&]() { mFogChecks = config.GetVanillaInt("fog checks"); }); } MapFoggingSystem::~MapFoggingSystem() { if (mFoggingEnabled) { free(mFogCheckData); for (size_t i = 0; i < 8; ++i) { free(mFogBuffers[i]); } } } void MapFoggingSystem::ResetBuffers(const RebuildBufferInfo& rebuildInfo) { InitScreenBuffers(); } void MapFoggingSystem::Reset() { // Previously: 1002EBD0 mEsdLoaded = 0; memset(&mEsdSectorLocs[0], 0, 32 * sizeof(uint64_t)); mDoFullUpdate = false; } const std::string &MapFoggingSystem::GetName() const { static std::string name("MapFogging"); return name; } void MapFoggingSystem::LoadFogColor(const std::string & dataDir) { static auto loadFogColor = temple::GetPointer<void(const char*)>(0x10030BF0); loadFogColor(dataDir.c_str()); } void MapFoggingSystem::Enable() { static auto map_fogging_enable = temple::GetPointer<void()>(0x1002ec80); map_fogging_enable(); } void MapFoggingSystem::Disable() { static auto map_fogging_disable = temple::GetPointer<void()>(0x1002ec90); map_fogging_disable(); } void MapFoggingSystem::LoadExploredTileData(int mapId) { static auto map_fogging_load_etd = temple::GetPointer<void(int)>(0x10030d10); map_fogging_load_etd(mapId); } void MapFoggingSystem::SaveExploredTileData(int mapId) { static auto map_fogging_save_etd = temple::GetPointer<void(int)>(0x10030e20); map_fogging_save_etd(mapId); } void MapFoggingSystem::SaveEsd() { static auto map_flush_esd = temple::GetPointer<void()>(0x10030f40); map_flush_esd(); } void MapFoggingSystem::PerformCheckForCritter(objHndl handle, int idx){ memset(&mFogBuffers[idx], 0, 4 * sFogBufferDim* sFogBufferDim); auto obj = objSystem->GetObject(handle); auto objLoc = obj->GetLocation(); auto fogBufferDim_div3 = sFogBufferDim / 3; int64_t (& objsRelX)[] = temple::GetRef<int64_t[]>(0x1080FB88); int64_t (& objsRelY)[] = temple::GetRef<int64_t[]>(0x108EC550); objsRelX[idx] = objLoc.locx - fogBufferDim_div3; objsRelY[idx] = objLoc.locy - fogBufferDim_div3; TileRect tiles; tiles.x1 = objLoc.locx - fogBufferDim_div3; tiles.x2 = objLoc.locx + fogBufferDim_div3; tiles.y1 = objLoc.locy - fogBufferDim_div3; tiles.y2 = objLoc.locy + fogBufferDim_div3; auto sectorList = sectorSys.BuildSectorList(&tiles); if (!sectorList) return; auto listNode = sectorList; while (listNode){ Sector *sect; if (!sectorSys.SectorLock(listNode->sector, &sect)){ listNode = listNode->next; continue; } auto secLoc = listNode->sector; auto baseTile=secLoc.GetBaseTile(); auto svb = gameSystems->GetSectorVB().GetSvb(secLoc); auto relX = objsRelX[idx]; auto relY = objsRelY[idx]; auto cornerX = listNode->cornerTile.locx; auto cornerY = listNode->cornerTile.locy; auto deltaX = cornerX - baseTile.locx; auto deltaY = cornerY - baseTile.locy; auto &objNodes = sect->objects; auto objNode = objNodes.tiles[deltaX + (deltaY << 6)]; for (; objNode != nullptr; objNode = objNode->next) { auto objNodeItem = objNode->handle; if (!objNodeItem){ continue; } auto objNodeObj = objSystem->GetObject(objNodeItem); if (objNodeObj->type != obj_t_portal) continue; auto aasParams = objects.GetAnimParams(objNodeItem); auto model = objects.GetAnimHandle(objNodeItem); auto submeshes = model->GetSubmeshes(); for (auto i_submesh=0; i_submesh<submeshes.size(); i_submesh++){ auto doorSubmesh = model->GetSubmesh(aasParams, submeshes[i_submesh]); auto vertPos = doorSubmesh->GetPositions(); auto indices = doorSubmesh->GetIndices(); auto primCount = doorSubmesh->GetPrimitiveCount(); for (auto i_prim = 0; i_prim < primCount; i_prim++){ // todo: fill triangle with value 8 } } } // unlock sector TODO svb sectorSys.SectorUnlock(listNode->sector); listNode = listNode->next; } sectorSys.SectorListReturnToPool(sectorList); } int MapFoggingSystem::IsPosExplored(LocAndOffsets location) { static auto is_pos_explored = temple::GetPointer<int(LocAndOffsets)>(0x1002ecb0); return is_pos_explored(location); } void MapFoggingSystem::InitScreenBuffers() { mScreenWidth = config.renderWidth; mScreenHeight = config.renderHeight; // Calculate the tile locations in each corner of the screen auto topLeftLoc = mDevice.GetCamera().ScreenToTile(0, 0); auto topRightLoc = mDevice.GetCamera().ScreenToTile(mScreenWidth, 0); auto bottomLeftLoc = mDevice.GetCamera().ScreenToTile(0, mScreenHeight); auto bottomRightLoc = mDevice.GetCamera().ScreenToTile(mScreenWidth, mScreenHeight); mFogMinX = topRightLoc.location.locx; mFogMinY = topLeftLoc.location.locy; // Whatever the point of this may be ... if (topLeftLoc.off_y < topLeftLoc.off_x || topLeftLoc.off_y < -topLeftLoc.off_x) { mFogMinY--; } mSubtilesX = (bottomLeftLoc.location.locx - mFogMinX + 3) * 3; mSubtilesY = (bottomRightLoc.location.locy - mFogMinY + 3) * 3; mFogCheckData = (uint8_t*)malloc((size_t)(mSubtilesX * mSubtilesY)); memset(mFogCheckData, 0, (size_t)(mSubtilesX * mSubtilesY)); mDoFullUpdate = TRUE; } //***************************************************************************** //* RandomEncounter //***************************************************************************** RandomEncounterSystem::RandomEncounterSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100457b0); if (!startup(&config)) { throw TempleException("Unable to initialize game system RandomEncounter"); } } RandomEncounterSystem::~RandomEncounterSystem() { auto shutdown = temple::GetPointer<void()>(0x10045830); shutdown(); } bool RandomEncounterSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x101f5850); return save(file) == 1; } bool RandomEncounterSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100458c0); return load(saveFile) == 1; } const std::string &RandomEncounterSystem::GetName() const { static std::string name("RandomEncounter"); return name; } //***************************************************************************** //* ObjectEvent //***************************************************************************** ObjectEventSystem::ObjectEventSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10045110); if (!startup(&config)) { throw TempleException("Unable to initialize game system ObjectEvent"); } } ObjectEventSystem::~ObjectEventSystem() { auto shutdown = temple::GetPointer<void()>(0x10045140); shutdown(); } void ObjectEventSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10045160); reset(); } bool ObjectEventSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x100456d0); return save(file) == 1; } bool ObjectEventSystem::LoadGame(GameSystemSaveFile* saveFile) { /*auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100451b0); auto result = load(saveFile) == 1;*/ return objEvents.ObjEventLoadGame(saveFile) == TRUE; } void ObjectEventSystem::AdvanceTime(uint32_t time) { //auto advanceTime = temple::GetPointer<void(uint32_t)>(0x10045740); //advanceTime(time); objEvents.AdvanceTime(); } const std::string &ObjectEventSystem::GetName() const { static std::string name("ObjectEvent"); return name; } //***************************************************************************** //* Formation //***************************************************************************** FormationSystem::FormationSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100437c0); if (!startup(&config)) { throw TempleException("Unable to initialize game system Formation"); } } void FormationSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10043250); reset(); } bool FormationSystem::SaveGame(TioFile *file) { auto save = temple::GetPointer<int(TioFile*)>(0x10043270); return save(file) == 1; } bool FormationSystem::LoadGame(GameSystemSaveFile* saveFile) { auto load = temple::GetPointer<int(GameSystemSaveFile*)>(0x100432e0); return load(saveFile) == 1; } const std::string &FormationSystem::GetName() const { static std::string name("Formation"); return name; } //***************************************************************************** //* ItemHighlight //***************************************************************************** ItemHighlightSystem::ItemHighlightSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x100431b0); if (!startup(&config)) { throw TempleException("Unable to initialize game system ItemHighlight"); } } void ItemHighlightSystem::Reset() { auto reset = temple::GetPointer<void()>(0x100431d0); reset(); } void ItemHighlightSystem::AdvanceTime(uint32_t time) { auto advanceTime = temple::GetPointer<void(uint32_t)>(0x100431f0); advanceTime(time); } const std::string &ItemHighlightSystem::GetName() const { static std::string name("ItemHighlight"); return name; } //***************************************************************************** //* PathX //***************************************************************************** PathXSystem::PathXSystem(const GameSystemConf &config) { auto startup = temple::GetPointer<int(const GameSystemConf*)>(0x10042a90); if (!startup(&config)) { throw TempleException("Unable to initialize game system PathX"); } } void PathXSystem::Reset() { auto reset = temple::GetPointer<void()>(0x10042aa0); reset(); } const std::string &PathXSystem::GetName() const { static std::string name("PathX"); return name; }
32.205176
150
0.612353
[ "object", "vector", "model" ]
90d7d0539ff8da4739e62260a5e19510d5f68d5f
44,988
cc
C++
src/genomicMSA.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
1
2021-03-25T17:53:03.000Z
2021-03-25T17:53:03.000Z
src/genomicMSA.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
null
null
null
src/genomicMSA.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
null
null
null
/* * genomicMSA.cc * * License: Artistic License, see file LICENSE.TXT or * https://opensource.org/licenses/artistic-license-1.0 * * Description: Generation of exon candidates */ #include "genomicMSA.hh" #include <fstream> #include <iostream> #include <string> #include <cfloat> #include <algorithm> #include <boost/tuple/tuple.hpp> #include <boost/graph/exception.hpp> #include <boost/graph/bellman_ford_shortest_paths.hpp> //#include <boost/graph/topological_sort.hpp> #include <unordered_set> using boost::graph_bundle; using boost::property_map; using boost::vertex_index_t; using boost::vertex_index; using boost::graph_traits; void eraseListRange(list<int> L, list<int>::reverse_iterator from, list<int>::reverse_iterator to){ L.erase(to.base(), from.base()); } void eraseListRange(list<int> L, list<int>::iterator from, list<int>::iterator to){ L.erase(from, to); } int GenomicMSA::maxIntronLen = 100000; int GenomicMSA::minGeneLen = 2000; // should be at least 1, otherwise empty alignments are not filtered out int GenomicMSA::maxGeneLen = 100000; // currently only used to prune alignment paths less ostream& operator<< (ostream& strm, const MsaSignature &sig){ strm << sig.numAli << "\t" << sig.sumCumFragLen << "\t" << sig.sumAliLen << "\t" << sig.depth << setw(15); if (sig.color < NUMCOLNAMES) cout << colornames[NUMCOLNAMES - 1 - sig.color]; else cout << sig.color; cout << setw(MsaSignature::maxSigStrLen+1) << sig.sigstr();// << "\t"; // for (list<int>::const_iterator it = sig.nodes.begin(); it != sig.nodes.end(); ++it) // cout << *it << " "; return strm; } bool cmpSigPtr(const MsaSignature *s1, const MsaSignature *s2){ return *s1 < *s2; } #ifdef TESTING /* * added by Giovanna Migliorelli 14.05.2020 * to read chr/scaffold names manually since boost serialization seems to have some problem with strings : needs replacing with better solution! */ void GenomicMSA::readNameDB(string dir) { cout << "Entering readNameDB..." << endl; int n, numSpecies; string seqID, filename; numSpecies = rsa->getNumSpecies(); // clean up previous read seqID2seqIDarhive.clear(); seqIDarhive2seqID.clear(); seqID2seqIDarhive.resize(numSpecies); seqIDarhive2seqID.resize(numSpecies); // move data to output vector (even if we could have used a vector from the beginning) , search within a map for duplicates is more efficient for(int s=0;s<numSpecies;++s){ filename = dir + "names." + rsa->getSname(s); ifstream ifs(filename); if(ifs.is_open()){ while(ifs){ ifs >> seqID; if(!seqID.empty()){ if(seqID2seqIDarhive[s].find(seqID) == seqID2seqIDarhive[s].end()){ n = seqID2seqIDarhive[s].size(); seqID2seqIDarhive[s].insert(make_pair(seqID, n)); seqIDarhive2seqID[s].insert(make_pair(n, seqID)); // cout << rsa->getSname(s) << "." << seqID << " " << n << endl; } } } ifs.close(); } } cout << "Leaving readNameDB..." << endl; } #endif /* *.maf file is read and saved into this->alignment * only the species with names in the given list are considered, the rest is ignored */ void GenomicMSA::readAlignment(string alignFilename) { int index = 0; string rowseq, buffer; string completeName; char strandChar; AlignmentRow *row; Alignment *alignBlock; map<string, size_t> notExistingSpecies; int lenOfChr; string speciesName; string seqID; int chrStart; int seqLen; Strand strand; #ifdef TESTING string testMode; try { testMode = Properties::getProperty("/Testing/testMode"); } catch (...) { testMode = "none"; } #endif numSpecies = rsa->getNumSpecies(); ifstream Alignmentfile; Alignmentfile.open(alignFilename.c_str(), ifstream::in); if (!Alignmentfile) { string errmsg = "Could not open the alignment file " + alignFilename + "."; throw PropertiesError(errmsg); } while (!Alignmentfile.eof()) { try { Alignmentfile >> buffer; } catch (std::ios_base::failure &e) { throw ProjectError(string("Could not open file ") + alignFilename + ". Make sure this is not a directory.\n"); } int numSpeciesFound = 0; if (buffer == "s") { alignBlock = new Alignment(numSpecies); // create new empty alignment block // loop over the lines of the alignment block, don't search any further if enough species were found while (numSpeciesFound < numSpecies && buffer == "s" && !Alignmentfile.eof()) { // reads the name of the species and the seqID from the first column // TODO: may have to be checked/adjusted for general .maf files Alignmentfile >> completeName >> chrStart >> seqLen >> strandChar >> lenOfChr >> rowseq >> buffer; /* * GM added the following to correctly handle names containing the symbol '-' when the dot works as a separator * GM the case not handled yet relates strings containing dashes in the name and using a dash as a separator (this case though should be infrequent) */ size_t dotAt = completeName.find('.'); if (dotAt != string::npos){ // use the dot found at position dotAt as a separator speciesName = completeName.substr(0,dotAt); seqID = completeName.substr(dotAt+1, string::npos); // some input file have a suffix "(..)" that needs to be stripped string::size_type p = seqID.find_first_of("("); if (p != std::string::npos) seqID = seqID.erase(p); if (dotAt == completeName.length()-1) { speciesName = completeName; seqID = "unknown"; } } else{ // no dot present, use dash as a separator // split species name and sequence ID for (int i=0; i<completeName.length(); i++) { if (completeName[i] == '-') { speciesName = completeName.substr(0,i); seqID = completeName.substr(i+1, string::npos); // some input file have a suffix "(..)" that needs to be stripped string::size_type p = seqID.find_first_of("("); if (p != std::string::npos) seqID = seqID.erase(p); break; } if (i == completeName.length()-1) { speciesName = completeName; seqID = "unknown"; } } } if (strandChar == '+') { strand = plusstrand; } else if (strandChar == '-') { strand = minusstrand; } else { strand = STRAND_UNKNOWN; } if (!alignBlock->aliLen) alignBlock->aliLen = rowseq.length(); else if (alignBlock->aliLen != rowseq.length()) { throw ProjectError("Error in MAF in sequence " + seqID + " at position " + itoa(chrStart) + ". Alignment row does not agree in length."); } row = new AlignmentRow (seqID, chrStart, strand, rowseq); if (seqLen != row->getSeqLen()) cerr << "Inconsistenty in .maf file: Sequence length different from number of non-gap characters in row:" << endl << "speciesName" << "." << seqID << "\t" << chrStart << "\t" << seqLen << "\t" << rowseq << endl; index = rsa->getIdx(speciesName); if (index >= 0) { // species name in the white list #ifdef TESTING if(testMode!="none"){ // added for the sake of deserialization row->chrLen = lenOfChr; // temporarily added to come around some problem with boost string serialization row->seqIDarchive = seqID2seqIDarhive[index][seqID]; } #endif if (!(alignBlock->rows[index])){ // first row for this species in this block alignBlock->rows[index] = row; // place at the right position // store chrLen and check whether consistent with previous chrLen try { rsa->setLength(index, row->seqID, lenOfChr); } catch (ProjectError &e){ cerr << e.getMessage() << endl << "MAF file inconsistent." << endl; throw e; } numSpeciesFound++; } else { // multiple rows of same species in same block // compare row with the old row for this species and overwrite if 'row' has more non-gap characters if(alignBlock->rows[index]->getSeqLen() >= seqLen ){ delete row; } else{ delete alignBlock->rows[index]; alignBlock->rows[index] = row; try { rsa->setLength(index, row->seqID, lenOfChr); } catch (ProjectError &e){ cerr << e.getMessage() << endl << "MAF file inconsistent." << endl; throw e; } } } } else { // "Species " << speciesName << " not in tree" notExistingSpecies.insert(pair<string, size_t>(speciesName, 1)); delete row; } } if (numSpeciesFound > 1) // do not consider alignments with less than 2 rows alignment.push_back(alignBlock); else delete alignBlock; } } // clean up Alignmentfile.close(); if (!notExistingSpecies.empty()){ cerr << "Warning: Species "; for (map<string,size_t>::iterator it = notExistingSpecies.begin(); it != notExistingSpecies.end(); ++it) cerr << it->first << " "; cerr << ((notExistingSpecies.size() > 1)? "are": "is") << " not included in the target list of species. These alignment lines are ingored." << endl; } } /* printMAF * print alignment, to stdout if outFname is empty string */ void GenomicMSA::printAlignment(string outFname){ Alignment *aliblock; for (list<Alignment*>::iterator alit = alignment.begin(); alit != alignment.end(); alit++) { aliblock = *alit; cout << *aliblock << endl << endl; /*for(vector<AlignmentRow*>::iterator aseqit = aliblock->rows.begin(); aseqit != aliblock->rows.end(); aseqit++){ AlignmentRow* row = *aseqit; if (row) { cout << setw(15) << row->seqID << "\tstart=" << row->start << "\tseqLen=" << row->seqLen << "\t" << ((row->strand == plusstrand)? "+":"_"); cout << "\tstarts:"; for (vector<int *>::iterator startsit = row->cmpStarts.begin(); startsit != row->cmpStarts.end(); ++startsit){ cout << **startsit; if (startsit+1 != row->cmpStarts.end()) cout << ","; } cout << "\tsequence:"; for (list<block>::iterator bit = row->sequence.begin(); bit != row->sequence.end();){ cout << "(" << bit->begin << "," << bit->length << "," << bit->previousGaps << ")"; if (++bit != row->sequence.end()) cout << ";"; } } else { cout << "no alignment"; } cout << endl; } cout << endl;*/ } } /** * Merges pairs of alignments in trivial cases in order to reduce the alignment number without doing any potentially false mergers. * The priority is on avoiding mergers, where there is more than one possibility to merge. * Not all trivial mergers are guaranteed to be realized, though. * Trivial mergers are found by sorting with respect to a number of (unsystematically chosen) different species. */ void GenomicMSA::compactify(){ int numSortRefs = 3; // Sort wrt to at most this many species, a larger value requires more time now // but may save time later by reducing alignments. For genomic alignments, where the first species is // present in ALL alignments (e.g. UCSC vertebrate), this only needs to be 1 int numAlis = alignment.size(); if (numSortRefs > numSpecies) numSortRefs = numSpecies; for (int i=0; i< numSortRefs; i++){ // use the first species (probably often important to users) // and otherwise evenly spaced indices to the list of species size_t s = i * numSpecies / numSortRefs; alignment.sort(SortCriterion(s)); // sort by species number s list<Alignment*>::iterator ait, bit; for (ait = alignment.begin(); ait != alignment.end();) { bit = ait; ++bit; if (bit == alignment.end()) break; // ait and bit point to neighbors in this order // all rows present in both alignments must be very close neighbors (at most 3 codons distance) if (mergeable(*ait, *bit, 9, 1.0, false)){ (*ait)->merge(*bit); alignment.erase(bit); } else { ++ait; } } } cout << "MAF compatification reduced the number of aligments from " << numAlis << " to " << alignment.size() << " (to " << setprecision(3) << (100.0 * alignment.size() / numAlis) << "%)." << endl; } /** * */ void GenomicMSA::findGeneRanges(){ AlignmentGraph::out_edge_iterator ei, ei_end, uoi, uoi_end, voi, voi_end; AlignmentGraph::in_edge_iterator vi, vi_end, ui, ui_end; AlignmentGraph::edge_iterator fi, fi_end; vertex_descriptor u, v, w; edge_descriptor e; Alignment *ua, *va; int uid, vid, wid; int numAlis = alignment.size(); int itnr = 0; alignment.sort(SortCriterion(0)); // sort by first species vector<Alignment*> nodesA(alignment.begin(), alignment.end()); // make vector copy of alignment list for random access list<int> nodesI; // indices to nodesA AlignmentGraph aliG(numAlis); for (int i=0; i < numAlis; i++){ nodesI.push_back(i); // starting order as in nodesA: sorted by first species v = vertex(i, aliG); aliG[v].a = alignment.front(); alignment.pop_front(); } property_map<AlignmentGraph, vertex_index_t>::type index = get(vertex_index, aliG); int numSortRefs = numSpecies; // sort wrt to at most this many species if (numSortRefs > 30) numSortRefs = 30; for (int i=0; i < numSortRefs; i++){ size_t s = i * numSpecies / numSortRefs; if (i>0) // no need to sort again by 1st species nodesI.sort(IdxSortCriterion(nodesA, s)); // sort indices by species number s list<int>::iterator ait, bit; for (ait = nodesI.begin(); ait != nodesI.end(); ++ait) { bit = ait; ++bit; if (bit == nodesI.end()) break; uid = *ait; vid = *bit; ua = aliG[vertex(uid, aliG)].a; va = aliG[vertex(vid, aliG)].a; // u and v index neighbors in this order if (ua && ua->rows[s] && va && va->rows[s] && mergeable(ua, va, maxIntronLen, 0.6, false)){ // add edge if not already present add_edge(uid, vid, aliG); } } } // writeDot(aliG, "aliGraph." + itoa(itnr++) + ".dot"); /* a__ a * \ \ \ implode any edges u->v, where * c-u--v-w ==> c-u+v-w 1) alignments u and v are mergeable with mergeableFrac 1.0 * \ \ \ and any path through u or v may as well use edge u->v: * ---d d 2) predecessors(v) \setminus {u} \subset predecessors(u) * 3) successors(u) \setminus {v} \subset successors(v) */ // AlignmentGraph::edge_iterator e; int numNodes = numAlis, numNodesOld; // iterate over all nodes u do { numNodesOld = numNodes; for (uid = 0; uid < num_vertices(aliG); uid++){ u = vertex(uid, aliG); ua = aliG[u].a; if (!ua) continue; bool merged = true; while (out_degree(u, aliG) >0 && merged){ //cout << "checking " << uid << endl; merged = false; for (tie(ei, ei_end) = out_edges(u, aliG); ei != ei_end && !merged; ++ei){ v = target(*ei, aliG); vid = index[v]; va = aliG[v].a; //cout << " v= " << vid << " "; if (va && mergeable(ua, va, maxIntronLen, 1.0, false)){ // cout << "mergeable" << endl; // check whether predecessors(v) \setminus {u} \subset predecessors(u) tie(vi, vi_end) = in_edges(v, aliG); tie(ui, ui_end) = in_edges(u, aliG); bool predIncluded = true; while (vi != vi_end && ui != ui_end && predIncluded){ if (source(*ui, aliG) < source(*vi, aliG)) ++ui; else if (source(*vi, aliG) == u) ++ui; else if (source(*ui, aliG) == source(*vi, aliG)){ ++ui; ++vi; } else predIncluded = false; } // at most the predecessor u of v may be left in the remaining predecessors(v) list predIncluded &= (vi == vi_end || (source(*vi, aliG) == u && ++vi == vi_end)); //cout << "predIncluded = " << predIncluded; if (predIncluded){ // check whether successors(u) \setminus {v} \subset successors(v) tie(voi, voi_end) = out_edges(v, aliG); tie(uoi, uoi_end) = out_edges(u, aliG); bool succIncluded = true; while (voi != voi_end && uoi != uoi_end && succIncluded){ if (target(*voi, aliG) < target(*uoi, aliG)) ++voi; else if (target(*uoi, aliG) == v) ++uoi; else if (target(*uoi, aliG) == target(*voi, aliG)){ ++uoi; ++voi; } else succIncluded = false; } // at most the successor v of u may be left in the remaining successors(u) list predIncluded &= (uoi == uoi_end || (target(*uoi, aliG) == v && ++uoi == uoi_end)); //cout << " succIncluded = " << succIncluded; if (succIncluded){ // append alignment v to u ua->merge(va); // add edges u->w for all edges v->w for (tie(voi, voi_end) = out_edges(v, aliG); voi != voi_end; ++voi){ w = target(*voi, aliG); wid = index[w]; add_edge(uid, wid, aliG); } // delete v from graph clear_vertex(v, aliG); aliG[v].a = NULL; // deactivate node //remove_vertex(v, aliG); merged = true; } } } //cout << endl; } } } numNodes = 0; for (uid = 0; uid < num_vertices(aliG); uid++) if (aliG[vertex(uid, aliG)].a) numNodes++; } while (numNodes < numNodesOld); cout << "number of nodes: " << numNodes << endl; // writeDot(aliG, "aliGraph." + itoa(itnr++) + ".dot"); // take all singleton alignments that are now long enough // at the same time, pack all alignments // TODO: this could instead look more generally into connected components and see whether they are too small // single nodes are then just a special case and this could reduce the number of signatures further alignment.clear(); int numNodes2 = 0; for (uid = 0; uid < num_vertices(aliG); uid++){ Alignment* a = aliG[vertex(uid, aliG)].a; if (a){ a->pack(); if (out_degree(uid, aliG) == 0 && in_degree(uid, aliG) == 0){ if (a->aliLen >= minGeneLen) // discard alignments that are too short to hold at least a short gene alignment.push_back(a); aliG[vertex(uid, aliG)].a = NULL; // deactivate node } else numNodes2++; } } // make a new graph, only of the active nodes that hold an alignment (consequence of vecS as node container class) // store all signatures AlignmentGraph aliG2(numNodes2+2); // node 0 is source, node 2 is sink add_edge(0, 1, aliG2); // edge from source to sink directly to allow finding the empty path map<string, MsaSignature>::iterator sit; aliG2[0].a = aliG2[1].a = NULL; // no alignment for source and sink aliG2[0].covered = aliG2[1].covered = true; // no need to cover source and sink numNodes2 = 2; // node numers 0 and 1 are reserved bool esucc; for (uid = 0; uid < num_vertices(aliG); uid++){ Alignment* a = aliG[vertex(uid, aliG)].a; if (a){ v = vertex(uid, aliG); aliG[v].id = numNodes2; // id node attributes in old graph aliG are now the node indices in the new graph aliG2 and vice versa aliG2[numNodes2].a = a; aliG2[numNodes2].id = uid; aliG2[numNodes2].covered = false; // add signature string sigstr = a->getSignature(); MsaSignature &sig = signatures[sigstr]; if (sig.numAli == 0){ sig.depth = a->numFilledRows(); sig.sigrows.resize(a->numRows(), ""); for (size_t s = 0; s < sig.sigrows.size(); ++s) if (a->rows[s]) sig.sigrows[s] = a->rows[s]->seqID + strandChar(a->rows[s]->strand); if (sigstr.length() > MsaSignature::maxSigStrLen) MsaSignature::maxSigStrLen = sigstr.length(); } sig.numAli += 1; sig.sumAliLen += a->aliLen; sig.sumCumFragLen += a->getCumFragLen(); //sig.nodes.push_back(uid); tie(e, esucc) = add_edge(0, numNodes2, aliG2); // edge from source to any other node aliG2[e].weight = 0; tie(e, esucc) = add_edge(numNodes2, 1, aliG2); // edge from any node to sink aliG2[e].weight = 0; numNodes2++; } } // add edges to new graph aliG2 for (tie(fi, fi_end) = edges(aliG); fi != fi_end; ++fi){ int u = index[source(*fi, aliG)]; int v = index[target(*fi, aliG)]; add_edge(aliG[u].id, aliG[v].id, aliG2); } // sort topologically to detect cycles aliG2[graph_bundle].topo.resize(numNodes2); // take the reversed finishing times of depth first search as proxy to a topological order // this is a topological ordering if aliG2 is a DAG, otherwise below maximum weight path search // may find subtoptimal paths dfs_time_visitor vis(&aliG2[graph_bundle].topo[0], numNodes2); depth_first_search(aliG2, visitor(vis)); for (int i=0; i<numNodes2; i++) // store topo sorting index for each node to prevent circles below aliG2[aliG2[graph_bundle].topo[i]].topoIdx = i; #ifdef DEBUG cout << "reverse DFS finishing order (approx topological): "; for (int i=0; i<numNodes2; i++) cout << aliG2[graph_bundle].topo[i] << " "; cout << endl; #endif list<MsaSignature*> siglist; for (sit = signatures.begin(); sit != signatures.end(); ++sit) siglist.push_back(&sit->second); siglist.sort(cmpSigPtr); int color = 0; cout << "number of signatures=" << signatures.size() << ". First 10 signatures are:" << endl; cout << "numAli\tsumCumFragLen\tsumAliLen\tdepth\tcolor\tsignature" << endl; for (list<MsaSignature*>::iterator it = siglist.begin(); it != siglist.end(); ++it){ (*it)->color = color++; if (color <= 10) cout << **it << endl; } vector<AliPath> allPaths; // writeDot(aliG2, "aliGraph." + itoa(itnr++) + ".dot"); int i=0; int maxSignatures = 100; // in addition to maxSignatures signatures, take only those, which int minAvCumFragLen = 1000; // cover on average minAvCumFragLen bp per species for (list<MsaSignature*>::iterator sit = siglist.begin(); sit != siglist.end(); ++sit){ if (i < maxSignatures || (*sit)->sumCumFragLen / numSpecies >= minAvCumFragLen){ project(aliG2, *sit); // set weights wrt to signature // cout << (*sit)->sigstr() << endl; // cout << " writing aliGraph." + itoa(itnr) + ".dot" << endl; if (itnr < 0) writeDot(aliG2, "aliGraph." + itoa(itnr++) + ".dot", *sit); int numNewCovered = 1; while (numNewCovered > 0){ AliPath path = getBestConsensus(aliG2, *sit, numNewCovered); // determine additional value (e.g. weight of newly covered nodes if (numNewCovered > 0){ // and if additional value large enough // cout << "found new path " << path << endl; allPaths.push_back(path); } } i++; } } cout << "found " << allPaths.size() << " paths" << endl; #ifdef DEBUG // for (int i=0; i<allPaths.size(); i++) // cout << i << "\t" << allPaths[i] << endl; #endif // repeat pruning until nothing changes (usually changes only in the first iteration) int totalNumNodes; while (prunePaths(allPaths, aliG2)){ #ifdef DEBUG cout << "allPaths after pruning:" << endl; #endif totalNumNodes = 0; for (int i=0; i < allPaths.size(); i++){ if (allPaths[i].path.size() > 0){ totalNumNodes += allPaths[i].path.size(); #ifdef DEBUG // cout << allPaths[i] << endl; #endif } } cout << "aliG2 nodes " << num_vertices(aliG2) << " allPaths nodes " << totalNumNodes << " ratio: " << (float) totalNumNodes/num_vertices(aliG2) << endl; } // for each path, make a single alignment and add to alignment list for (int i=0; i < allPaths.size(); i++){ if (allPaths[i].path.size() > 0){ // cout << "alignment " << i << " from path " << allPaths[i] << endl; list<Alignment* > plist; list<int> &p = allPaths[i].path; for (list<int>::iterator it = p.begin(); it != p.end(); ++it) plist.push_back(aliG2[*it].a); va = mergeAliList(plist, allPaths[i].sig); if (va && va->aliLen >= minGeneLen){ // discard alignments that are too short to hold at least a short gene //va->printTextGraph(cout); alignment.push_back(va); } else{ //cout << "deleted (too short)" << endl; delete va; } } } int sizeBeforeCapping = alignment.size(); int mz = Properties::getIntProperty( "maxDNAPieceSize" ); capAliSize(alignment, mz); if (alignment.size() > sizeBeforeCapping) cout << "very large alignments (>" << mz << ") had to be cut " << alignment.size() - sizeBeforeCapping << " times." << endl; float covPen; size_t maxCov; try { covPen = Properties::getdoubleProperty( "/CompPred/covPen" ); } catch (...) { covPen = 0.2; // default: uncovered bases are punished 5 times more than each base covered too often } try { maxCov = Properties::getIntProperty( "/CompPred/maxCov" ); } catch (...) { maxCov = 3; // default: the same region covered by more than 3 alignments in penalized } reduceOvlpRanges(alignment, maxCov, covPen); //alignment.sort(SortCriterion(0)); // sort (arbitrarily) by first species cout << "findGeneRanges " << ((alignment.size() <= numAlis)? "reduced" : "increased") << " the number of aligments from " << numAlis << " to " << alignment.size() << " (to " << setprecision(3) << (100.0 * alignment.size() / numAlis) << "%)." << endl; // delete all alignments from the graph nodes for (uid = 0; uid < num_vertices(aliG2); uid++){ Alignment* a = aliG2[uid].a; if (a) delete a; } } bool GenomicMSA::prunePaths(vector<AliPath> &allPaths, AlignmentGraph &g){ bool changed = false; int i, j, m = allPaths.size(); // first create a data structure that allows to quickly find all pairs of paths (i,j) // that share any alignment (=collision) int n = num_vertices(g), k; vector<unordered_set<int> > pathsByAlignment(n); // for each alignment indexed by 0 <= k < n store the set of indices i to // allPaths of paths that contain the alignment for (i=0; i<m; i++){ for (list<int>::iterator it = allPaths[i].path.begin(); it != allPaths[i].path.end(); ++it){ k = *it; pathsByAlignment[k].insert(i); // path i contains alignment k } } set<pair<int,int>> collisions; // sorted set of pair, sorted first by 'first' then by 'second' for (k=0; k<n; k++){ if (!pathsByAlignment[k].empty()){ // cout << "alignment " << k << " is shared by " << pathsByAlignment[k].size() << " paths" //<< " paths." << endl; unordered_set<int>::iterator iti, itj, it_end; it_end = pathsByAlignment[k].end(); for (iti = pathsByAlignment[k].begin(); iti != it_end; ++iti){ itj = iti; ++itj; for (;itj != it_end; ++itj){ int i = *iti, j = *itj; if (i<j) collisions.insert(pair<int,int>(i,j)); // insert pair of paths (i,j) into collision data structure else collisions.insert(pair<int,int>(j,i)); // make pairs unique by sorting } } } } cout << "Have " << collisions.size() << " collisions." << endl; for (set<pair<int,int> >::iterator colit = collisions.begin(); colit != collisions.end(); ++colit){ i = colit->first; j = colit->second; bool mods[6] = {false, false, false, false, false, false}, mod; mods[0] = prunePathWrt2Other(allPaths[j], allPaths[j].path.begin(), allPaths[j].path.end(), allPaths[i], allPaths[i].path.begin(), allPaths[i].path.end(), g, true); mods[1] = prunePathWrt2Other(allPaths[j], allPaths[j].path.rbegin(), allPaths[j].path.rend(), allPaths[i], allPaths[i].path.rbegin(), allPaths[i].path.rend(), g, false); mods[2] = deletePathWrt2Other(allPaths[j], allPaths[i], g); mods[3] = prunePathWrt2Other(allPaths[i], allPaths[i].path.begin(), allPaths[i].path.end(), allPaths[j], allPaths[j].path.begin(), allPaths[j].path.end(), g, true); mods[4] = prunePathWrt2Other(allPaths[i], allPaths[i].path.rbegin(), allPaths[i].path.rend(), allPaths[j], allPaths[j].path.rbegin(), allPaths[j].path.rend(), g, false); mods[5]= deletePathWrt2Other(allPaths[i], allPaths[j], g); mod = mods[0] || mods[1] || mods[2] || mods[3] || mods[4] || mods[5]; if (mod && false) cout << "Have pruned a path from collision " << i << "\t" //<< allPaths[i] << endl << " and " << j << "\t" << mods[0] << mods[1] << mods[2] << mods[3] << mods[4] << mods[5] << endl; //"\t" << allPaths[j] << endl; changed |= mod; } return changed; } /* * Remove from the left end of p the longest contiguous sequence of alignments that is contiguously included in 'other'. * The part to remove from p is extended alignment by alignment as long as node the weight wrt to the respective signature * is at least as large in 'other'. * p: a4 a2 a9 a3 a5 a6 a0 * other: a1 a4 a2 a9 a7 a8 a0 * afterwards p: a3 a5 a6 a0 * If at the determined cut point the sequence for at least one species ends, then it is assumed that possibly the assembly * fragments a gene and the part to remove is shortened by as many aligments as cumulatively span on average maxGeneLen. * * p may become the empty path. Iterators can be reverse_iterators in which case the fragment is removed from the right end. * forward is true if the iterators are forward iterators, i.e. alignments are interated in increasing order */ template< class Iterator > bool GenomicMSA::prunePathWrt2Other(AliPath &p, Iterator pstart, Iterator pend, AliPath &other, Iterator ostart, Iterator oend, AlignmentGraph &g, bool forward){ bool ausgabe = false; // TEMPorary if (ausgabe) cout << "prunePathWrt2Other(" << p << endl << other << ")" << endl; // match from the left end of p Iterator pa, oa; pa = pstart; oa = ostart; // find start of match of first node of p in other while (oa != oend && (*pa != *oa)) ++oa; if (oa != oend){ // match found while (oa != oend && pa != pend && *pa == *oa && weight(g[*oa].a, other.sig) >= weight(g[*pa].a, p.sig)){ ++oa; ++pa; } if (pstart != pa){ if (pa != pend){ // in this case path p is completely contained and removed // check whether removing up to pa would remove too much Iterator paprev = pa; --paprev; if (ausgabe) cout << "pa=" << *pa << " paprev= " << *paprev << endl; // determine if we would possibly prune too much: // Does the signature of p change only because some sequence ends in alignment pa? int median_dist = 0; vector<int> distances; int dist; // determine median distance (gap length) in chromosomal coordinates to previous alignment for (size_t s=0; s<numSpecies; s++){ dist = -1; AlignmentRow *curr = g[*pa].a->rows[s], *prev = g[*paprev].a->rows[s]; if (curr && prev && curr->strand == prev->strand && curr->seqID == prev->seqID){ if (forward) dist = curr->chrStart() - prev->chrEnd(); else dist = prev->chrStart() - curr->chrEnd(); if (dist >= 0) distances.push_back(dist); } } if (distances.size()>0) median_dist = quantile(distances, 0.5); bool seqEnds = false; for (size_t s=0; s<numSpecies && !seqEnds; s++){ seqEnds |= g[*pa].a->rows[s] && ((forward && g[*pa].a->rows[s]->chrStart() < median_dist) || (!forward && rsa->getChrLen(s, g[*pa].a->rows[s]->seqID) - g[*pa].a->rows[s]->chrEnd() < median_dist)); if (seqEnds && ausgabe) cout << "sequence "<< g[*pa].a->rows[s]->seqID << " ends" << endl; } if (seqEnds){ if (ausgabe) cout << "median " << (forward? "fw" :"rv") << " chromosomal distance between alignments " << *paprev << endl //<< *(g[*paprev].a) << endl << "and " << *pa << endl //<< *(g[*pa].a) << endl << " is " << median_dist << endl; // signature changes between paprev and pa because of assembly fragmentation // decrease pa iterator so that maxGeneLen additional chromosomal range is covered // before the fragmentation int range = 0; paprev = pa; while (paprev != pstart && range < GenomicMSA::maxGeneLen) { paprev--; if (forward) range = medianChrStartEndDiff(g[*pa].a, g[*paprev].a); else range = medianChrStartEndDiff(g[*paprev].a, g[*pa].a); if (ausgabe) cout << "paprev=" << *paprev << " range=" << range << endl; } if (paprev != pa && range >= GenomicMSA::maxGeneLen) paprev++; // first alignment that exceeds range threshold is not included anymore pa = paprev; if (ausgabe) cout << "reducing pruning until alignment " << *paprev << endl; } } // prune path until pa (exclusive pa) // a (future) alternative is introduce two iterators as members in AliPath: // the interval [first, last) that is to be kept. Then a piece of the neighboring // alignments can still be used to generate a better "overhang". if (pstart != pa){ eraseListRange(p.path, pstart, pa); p.ranges.clear(); if (ausgabe) cout << "pruned to " << p << endl; return true; } } } return false; } /* * Remove path p competely if the additionally aligned sequence ranges are not negligible wrt to the alignment length * p may become the empty path. */ bool GenomicMSA::deletePathWrt2Other(AliPath &p, AliPath &other, AlignmentGraph &g){ if (p.path.empty() || other.path.empty()) return false; const double superfluousfrac = 1.1; // path must have at least this many times weighted alignments compared to the intersection of paths bool superfluous = false; // set<string> ranges[3]; // 0:p 1:other 2:intersection AliPath *ap[2]; ap[0] = &p; ap[1] = &other; const MsaSignature *sigs[2]; sigs[0] = p.sig; sigs[1] = other.sig; Alignment *a; for (int i=0; i<2; i++){ if (ap[i]->ranges.empty()){ ap[i]->weights = 0; for (list<int>::iterator it = ap[i]->path.begin(); it != ap[i]->path.end(); ++it){ for (int s=0; s<numSpecies; s++){ a = g[*it].a; if (a->rows[s] && sigs[i]->fits(*a, s)){ string key = itoa(s) + ":" + a->rows[s]->seqID + itoa(a->rows[s]->strand) + " " + itoa(a->rows[s]->chrStart()) + "-" + itoa(a->rows[s]->chrEnd()); ap[i]->ranges.insert(key); ap[i]->weights += a->rows[s]->chrEnd() - a->rows[s]->chrStart() + 1; } } } } } set<string> intersection; set_intersection(p.ranges.begin(), p.ranges.end(), other.ranges.begin(), other.ranges.end(), std::inserter( intersection, intersection.begin())); int weights = 0; // weight the sets with the sequence range sizes for (set<string>::iterator it = intersection.begin(); it != intersection.end(); ++it){ string s = *it; int pos1 = s.find(" "); int pos2 = s.find("-", pos1); int start = atoi(s.substr(pos1+1, pos2-pos1-1).c_str()); int stop = atoi(s.substr(pos2+1).c_str()); weights += stop - start + 1; } // check whether p has too few or short additional aligned regions that are not shared by 'other' if (p.weights < superfluousfrac * weights){ superfluous = true; // cout << p << endl << "is superfluous because of" << endl << other << endl; } if (superfluous){ p.path.clear(); // delete all alignments from path, will be discarded later p.ranges.clear(); } return superfluous; } AliPath GenomicMSA::getBestConsensus(AlignmentGraph &g, const MsaSignature *sig, int &numNewCovered){ AliPath p; Alignment *a; int N = num_vertices(g); vector<int> pred(N); // predecessor for each node on shortest path int vid; int maxWeight = findBestPath(g); numNewCovered = 0; vid = g[1].pred; // last node on best path string newlyids = ""; while(vid != 0){ // until source node is reached p.path.push_front(vid); a = g[vid].a; if (!g[vid].covered && a->numFitting(sig) == a->numFilledRows()){ g[vid].covered = true; // path covers all alignments with the exact signature or a subset thereof g[vid].weight = weight(g[vid].a, sig); numNewCovered++; newlyids = itoa(vid) + " " + newlyids; } vid = g[vid].pred; } if (numNewCovered>0 && false) cout << "newly covered " << newlyids << "\t" << numNewCovered << " new nodes. With exact signature: " << maxWeight / g[graph_bundle].maxWexceptCov << endl; p.sig = sig; return p; } int GenomicMSA::findBestPath(AlignmentGraph &g){ // relax all nodes in topologial order int N = num_vertices(g); int i, vid, wid; AlignmentGraph::out_edge_iterator ei, ei_end; property_map<AlignmentGraph, vertex_index_t>::type index = get(vertex_index, g); vertex_descriptor v, w; vector<int> maxCumW(N, -INT_MAX); // currently maximal weight of any path from source to each node if (g[graph_bundle].topo.size() != N) throw ProjectError("Topological order required for findBestPath."); // initialize source node maxCumW[0] = 0; g[0].pred = 0; // source node has itself as predecessor for (i=0; i<N; i++){ vid = g[graph_bundle].topo[i]; v = vertex(vid, g); // relax all outgoing edges from v for (tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei){ w = target(*ei, g); wid = index[w]; if (g[*ei].weight > -INT_MAX && g[wid].weight > -INT_MAX && maxCumW[vid] + g[*ei].weight + g[wid].weight > maxCumW[wid]){ //cout << "relaxed " << vid << " -> " << wid << endl; if (g[vid].topoIdx < g[wid].topoIdx) { maxCumW[wid] = maxCumW[vid] + g[*ei].weight + g[wid].weight; g[wid].pred = v; } else { // cout << "error: circular predecessor path" << endl; } } } } //for (vid=0; vid<N; vid++) //cout << vid << "\t" << g[vid].pred << " " << maxCumW[vid] << endl; return maxCumW[1]; } void GenomicMSA::project(AlignmentGraph &g, const MsaSignature *sig){ Alignment *a, *b; vertex_descriptor u, v; int maxWexceptCov = 0; // set node weights for (int vid = 0; vid < num_vertices(g); vid++){ v = vertex(vid, g); a = g[v].a; g[v].weight = weight(a, sig); if (g[v].weight > 0) maxWexceptCov += g[v].weight; } AlignmentGraph::edge_iterator ei, ei_end; // set edge weights for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei){ u = source(*ei, g); v = target(*ei, g); a = g[u].a; b = g[v].a; g[*ei].weight = weight(a, b, sig); if (g[*ei].weight > 0) maxWexceptCov += g[*ei].weight; } g[graph_bundle].maxWexceptCov = maxWexceptCov; //cout << "maxWexceptCov = " << maxWexceptCov << endl; // increase node weights for not yet covered nodes of the given signature, so they are first priority for (int vid = 0; vid < num_vertices(g); vid++){ v = vertex(vid, g); if (!g[v].covered && sig->sigstr() == g[vid].a->getSignature()) g[v].weight += maxWexceptCov + 1; } } /* * Node weight, when projecting a to sig: * -Infty, if less than 2 rows agree with signature, otherwise it is the cumulative Fragment length of the fitting rows */ int GenomicMSA::weight(const Alignment *a, const MsaSignature *sig){ int cumFragLen = 0; if (!a) return 0; if (a->numFitting(sig) < 2) return -INT_MAX; for (size_t s = 0; s < a->numRows(); s++){ if (sig->fits(*a, s)) cumFragLen += a->rows[s]->getCumFragLen(); } return cumFragLen; } /* * Edge weight, when projecting a to sig: * -Infty, if the projected alignments are not mergeable. */ int GenomicMSA::weight(const Alignment *a, const Alignment *b, const MsaSignature *sig){ int numFitting = 0; if (!a || !b) return 0; for (size_t s = 0; s < a->numRows(); s++){ if (sig->fits(*a, s) && sig->fits(*b, s)){ int dist = b->rows[s]->chrStart() - a->rows[s]->chrEnd() - 1; if (dist >=0 && dist <= maxIntronLen) numFitting++; } } if (numFitting < 2) return -INT_MAX; return 0; } void GenomicMSA::writeDot(AlignmentGraph const &g, string fname, MsaSignature const *superSig){ property_map<AlignmentGraph, vertex_index_t>::type index = get(vertex_index, g); ofstream dot(fname); dot << "digraph G {" << endl; dot << "node[shape=box];" << endl; // legend box with species names dot << "legend1[label=<<TABLE BORDER=\"0\"><TR><TD COLSPAN=\"2\" BGCOLOR=\"deepskyblue1\"><B>Species</B></TD></TR>" << endl; for (size_t s=0; s<numSpecies; s++){ dot << "<TR><TD align=\"left\""; if (s < NUMCOLNAMES) dot << " BGCOLOR=\"" << colornames[s] << "\""; dot << ">" << s << "</TD><TD align=\"right\">" << rsa->getSname(s) << "</TD></TR>" << endl; } dot << "</TABLE>>];" << endl; // legend box for alignments dot << "legend2[label=<<TABLE BORDER=\"0\"><TR><TD COLSPAN=\"5\" BGCOLOR=\"deepskyblue1\"><B>Alignment</B></TD></TR>"; dot << "<TR><TD COLSPAN=\"2\">id</TD><TD COLSPAN=\"3\">alignment length</TD></TR>"; dot << "<TR><TD align=\"left\" BGCOLOR=\"" << colornames[0] << "\">0</TD><TD align=\"right\">chrN</TD>" << "<TD>strand</TD><TD>genomeStartPos</TD><TD>genomeEndPos+1</TD></TR>"; if (superSig) dot << "<TR><TD COLSPAN=\"3\">weight</TD><TD COLSPAN=\"2\">covered</TD></TR>"; dot << "</TABLE>>];" << endl; dot << "rankdir=LR;" << endl; graph_traits<AlignmentGraph>::vertex_iterator vi, vi_end; AlignmentRow *row; for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi){ int i = index[*vi]; // index of vertex Alignment *ia = g[*vi].a; if (ia){ MsaSignature sig; string sigbgcol = ""; if (signatures.size()>0){ sig = signatures[ia->getSignature()]; // signature of this node if (sig.color < NUMCOLNAMES) sigbgcol = " BGCOLOR=\"" + colornames[NUMCOLNAMES - 1 - sig.color] + "\""; } dot << i << "[label=<<TABLE BORDER=\"0\">"; dot << "<TR><TD COLSPAN=\"2\">" << i << "=" << g[*vi].id << "</TD><TD COLSPAN=\"3\">" << ia->aliLen << "</TD></TR>" << endl; for (size_t s = 0; s < ia->rows.size(); s++){ dot << "<TR>"; row = ia->rows[s]; if (row) { dot << "<TD align=\"right\""; if (s < NUMCOLNAMES){ dot << " BGCOLOR=\"" << colornames[s] << "\""; } dot << ">" << s << "</TD>"; dot << "<TD align=\"left\"" << ((!superSig || superSig->fits(*ia, s))? sigbgcol : "" ) << ">" << row->seqID << "</TD>"; dot << "<TD" << ((!superSig || superSig->fits(*ia, s))? sigbgcol : "" ) << ">" << row->strand << "</TD>"; dot << "<TD align=\"right\">" << row->chrStart() << "</TD>"; dot << "<TD align=\"right\">" << row->chrEnd() << "</TD>"; } else dot << "<TD></TD><TD></TD><TD></TD><TD></TD><TD></TD>"; dot << "</TR>" << endl;; } if (superSig) { dot << "<TR><TD COLSPAN=\"3\">"; if (g[*vi].weight > -INT_MAX) dot << g[*vi].weight; else dot << "-infty"; dot << "</TD><TD COLSPAN=\"2\">" << g[*vi].covered << "</TD></TR>" << endl; } dot << "</TABLE>>"; if (superSig){ if (g[*vi].weight == -INT_MAX) dot << ",style=dotted"; else { dot << ",color=red"; if (sig.sigstr() == superSig->sigstr()) dot << ",peripheries=2,style=filled"; } } dot << "];" << endl; } } graph_traits<AlignmentGraph>::edge_iterator ei, ei_end; for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei){ int u = index[source(*ei, g)]; int v = index[target(*ei, g)]; Alignment *ua = g[vertex(u, g)].a; Alignment *va = g[vertex(v, g)].a; if (ua && va){ // do not display edges from source and to sink node // compute average gap length between the two aligments int k=0; int avGapLen = 0; for (size_t s=0; s < numSpecies; s++) if (ua->rows[s] && va->rows[s] && ua->rows[s]->seqID == va->rows[s]->seqID && ua->rows[s]->strand == va->rows[s]->strand && (!superSig || (superSig->fits(*ua, s) && superSig->fits(*va, s)))){ int gapLen = va->rows[s]->chrStart() - ua->rows[s]->chrEnd() - 1; if (gapLen >= 0){ avGapLen += gapLen; k++; } } if (k > 0) avGapLen /= k; dot << u << "->" << v << "[label=" << avGapLen; if (superSig){ if (g[*ei].weight == -INT_MAX) dot << ",style=dotted"; else dot << ",color=red"; } dot << "];" << endl; } } dot << "}" << endl; dot.close(); } // pops the first alignment from list GeneMSA* GenomicMSA::getNextGene() { if (alignment.empty()) return NULL; GeneMSA *geneRange = new GeneMSA(rsa, alignment.front()); alignment.pop_front(); return geneRange; } #ifdef TESTING // pops the first alignment from list without constructing any gene range Alignment* GenomicMSA::getNextAlignment() { if (alignment.empty()) return NULL; Alignment *ali = alignment.front(); alignment.pop_front(); return ali; } #endif ostream& operator<< (ostream& strm, const AliPath &p){ for(list<int>::const_iterator pit = p.path.begin(); pit != p.path.end(); ++pit) strm << *pit << " "; strm << "\t" << p.sig->sigstr(); return strm; }
37.427621
156
0.598626
[ "shape", "vector" ]
90e12c8190b8323766a0ce4b0ec33e67c810ba94
30,773
cpp
C++
Modules/QtWidgets/src/QmitkDataStorageTreeModel.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Modules/QtWidgets/src/QmitkDataStorageTreeModel.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Modules/QtWidgets/src/QmitkDataStorageTreeModel.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkStringProperty.h> #include <mitkNodePredicateFirstLevel.h> #include <mitkNodePredicateAnd.h> #include <mitkNodePredicateData.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateOr.h> #include <mitkNodePredicateProperty.h> #include <mitkPlanarFigure.h> #include <mitkProperties.h> #include <mitkRenderingManager.h> #include "QmitkDataStorageTreeModel.h" #include "QmitkNodeDescriptorManager.h" #include <QmitkEnums.h> #include <QmitkCustomVariants.h> #include <QmitkMimeTypes.h> #include <QIcon> #include <QMimeData> #include <QTextStream> #include <QFile> #include <map> #include <mitkCoreServices.h> QmitkDataStorageTreeModel::QmitkDataStorageTreeModel( mitk::DataStorage* _DataStorage , bool _PlaceNewNodesOnTop , QObject* parent ) : QAbstractItemModel(parent) , m_DataStorage(0) , m_PlaceNewNodesOnTop(_PlaceNewNodesOnTop) , m_Root(0) , m_BlockDataStorageEvents(false) , m_AllowHierarchyChange(false) { this->SetDataStorage(_DataStorage); } QmitkDataStorageTreeModel::~QmitkDataStorageTreeModel() { // set data storage to 0 = remove all listeners this->SetDataStorage(0); m_Root->Delete(); m_Root = 0; } mitk::DataNode::Pointer QmitkDataStorageTreeModel::GetNode( const QModelIndex &index ) const { return this->TreeItemFromIndex(index)->GetDataNode(); } const mitk::DataStorage::Pointer QmitkDataStorageTreeModel::GetDataStorage() const { return m_DataStorage.GetPointer(); } QModelIndex QmitkDataStorageTreeModel::index( int row, int column, const QModelIndex & parent ) const { TreeItem* parentItem; if (!parent.isValid()) parentItem = m_Root; else parentItem = static_cast<TreeItem*>(parent.internalPointer()); TreeItem *childItem = parentItem->GetChild(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } int QmitkDataStorageTreeModel::rowCount(const QModelIndex &parent) const { TreeItem *parentTreeItem = this->TreeItemFromIndex(parent); return parentTreeItem->GetChildCount(); } Qt::ItemFlags QmitkDataStorageTreeModel::flags( const QModelIndex& index ) const { mitk::DataNode* dataNode = this->TreeItemFromIndex(index)->GetDataNode(); if (index.isValid()) { if(DicomPropertiesExists(*dataNode)) { return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; }else{ return Qt::ItemIsDropEnabled; } } int QmitkDataStorageTreeModel::columnCount( const QModelIndex& /* parent = QModelIndex() */ ) const { return 1; } QModelIndex QmitkDataStorageTreeModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); TreeItem *childItem = this->TreeItemFromIndex(index); TreeItem *parentItem = childItem->GetParent(); if (parentItem == m_Root) return QModelIndex(); return this->createIndex(parentItem->GetIndex(), 0, parentItem); } QmitkDataStorageTreeModel::TreeItem* QmitkDataStorageTreeModel::TreeItemFromIndex( const QModelIndex &index ) const { if (index.isValid()) return static_cast<TreeItem *>(index.internalPointer()); else return m_Root; } Qt::DropActions QmitkDataStorageTreeModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } Qt::DropActions QmitkDataStorageTreeModel::supportedDragActions() const { return Qt::CopyAction | Qt::MoveAction; } bool QmitkDataStorageTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex &parent) { // Early exit, returning true, but not actually doing anything (ignoring data). if (action == Qt::IgnoreAction) { return true; } // Note, we are returning true if we handled it, and false otherwise bool returnValue = false; if(data->hasFormat("application/x-qabstractitemmodeldatalist")) { returnValue = true; // First we extract a Qlist of TreeItem* pointers. QList<TreeItem*> listOfItemsToDrop = ToTreeItemPtrList(data); if (listOfItemsToDrop.size() == 0) { return false; } // Retrieve the TreeItem* where we are dropping stuff, and its parent. TreeItem* dropItem = this->TreeItemFromIndex(parent); TreeItem* parentItem = dropItem->GetParent(); // If item was dropped onto empty space, we select the root node if(dropItem == m_Root) { parentItem = m_Root; } // Dragging and Dropping is only allowed within the same parent, so use the first item in list to validate. // (otherwise, you could have a derived image such as a segmentation, and assign it to another image). // NOTE: We are assuming the input list is valid... i.e. when it was dragged, all the items had the same parent. // Determine whether or not the drag and drop operation is a valid one. // Examples of invalid operations include: // - dragging nodes with different parents // - dragging nodes from one parent to another parent, if m_AllowHierarchyChange is false // - dragging a node on one of its child nodes (only relevant if m_AllowHierarchyChange is true) bool isValidDragAndDropOperation(true); // different parents { TreeItem* firstParent = listOfItemsToDrop[0]->GetParent(); QList<TreeItem*>::iterator diIter; for (diIter = listOfItemsToDrop.begin() +1; diIter != listOfItemsToDrop.end(); diIter++) { if (firstParent != (*diIter)->GetParent()) { isValidDragAndDropOperation = false; break; } } } // dragging from one parent to another if((!m_AllowHierarchyChange) && isValidDragAndDropOperation) { if (row == -1)// drag onto a node { isValidDragAndDropOperation = listOfItemsToDrop[0]->GetParent() == parentItem; } else // drag between nodes { isValidDragAndDropOperation = listOfItemsToDrop[0]->GetParent() == dropItem; } } // dragging on a child node of one the dragged nodes { QList<TreeItem*>::iterator diIter; for (diIter = listOfItemsToDrop.begin(); diIter != listOfItemsToDrop.end(); diIter++) { TreeItem* tempItem = dropItem; while (tempItem != m_Root) { tempItem = tempItem->GetParent(); if (tempItem == *diIter) { isValidDragAndDropOperation = false; } } } } if (!isValidDragAndDropOperation) return isValidDragAndDropOperation; if (listOfItemsToDrop[0] != dropItem && isValidDragAndDropOperation) { // Retrieve the index of where we are dropping stuff. QModelIndex parentModelIndex = this->IndexFromTreeItem(parentItem); int dragIndex = 0; this->beginResetModel(); // Iterate through the list of TreeItem (which may be at non-consecutive indexes). QList<TreeItem*>::iterator diIter; for (diIter = listOfItemsToDrop.begin(); diIter != listOfItemsToDrop.end(); diIter++) { TreeItem* itemToDrop = *diIter; // if the item is dragged down we have to compensate its final position for the // fact it is deleted lateron, this only applies if it is dragged within the same level if ( (itemToDrop->GetIndex() < row) && (itemToDrop->GetParent() == dropItem)) { dragIndex = 1; } // Here we assume that as you remove items, one at a time, that GetIndex() will be valid. itemToDrop->GetParent()->RemoveChild(itemToDrop); } // row = -1 dropped on an item, row != -1 dropped in between two items // Select the target index position, or put it at the end of the list. int dropIndex = 0; if (row != -1) { if (dragIndex == 0) dropIndex = std::min(row, parentItem->GetChildCount() - 1); else dropIndex = std::min(row - 1, parentItem->GetChildCount() - 1); } else { dropIndex = dropItem->GetIndex(); } QModelIndex dropItemModelIndex = this->IndexFromTreeItem(dropItem); if ((row == -1 && dropItemModelIndex.row() == -1) || dropItemModelIndex.row() > parentItem->GetChildCount()) dropIndex = parentItem->GetChildCount() - 1; // Now insert items again at the drop item position for (diIter = listOfItemsToDrop.begin(); diIter != listOfItemsToDrop.end(); diIter++) { // dropped on node, behaviour depends on preference setting if (m_AllowHierarchyChange) { m_BlockDataStorageEvents = true; mitk::DataNode* droppedNode = (*diIter)->GetDataNode(); mitk::DataNode* dropOntoNode = dropItem->GetDataNode(); m_DataStorage->Remove(droppedNode); m_DataStorage->Add(droppedNode, dropOntoNode); m_BlockDataStorageEvents = false; dropItem->InsertChild((*diIter), dropIndex); } else { if (row == -1)// drag onto a node { parentItem->InsertChild((*diIter), dropIndex); } else // drag between nodes { dropItem->InsertChild((*diIter), dropIndex); } } dropIndex++; } // Change Layers to match. this->AdjustLayerProperty(); this->endResetModel(); } } else if(data->hasFormat("application/x-mitk-datanodes")) { returnValue = true; int numberOfNodesDropped = 0; QList<mitk::DataNode*> dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data); mitk::DataNode* node = NULL; foreach(node, dataNodeList) { if(node && m_DataStorage.IsNotNull() && !m_DataStorage->Exists(node)) { m_DataStorage->Add( node ); mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); numberOfNodesDropped++; } } } // Only do a rendering update, if we actually dropped anything. if (numberOfNodesDropped > 0) { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } return returnValue; } QStringList QmitkDataStorageTreeModel::mimeTypes() const { QStringList types = QAbstractItemModel::mimeTypes(); types << "application/x-qabstractitemmodeldatalist"; types << "application/x-mitk-datanodes"; return types; } QMimeData * QmitkDataStorageTreeModel::mimeData(const QModelIndexList & indexes) const { return mimeDataFromModelIndexList(indexes); } QMimeData *QmitkDataStorageTreeModel::mimeDataFromModelIndexList(const QModelIndexList &indexes) { QMimeData * ret = new QMimeData; QString treeItemAddresses(""); QString dataNodeAddresses(""); QByteArray baTreeItemPtrs; QByteArray baDataNodePtrs; QDataStream dsTreeItemPtrs(&baTreeItemPtrs, QIODevice::WriteOnly); QDataStream dsDataNodePtrs(&baDataNodePtrs, QIODevice::WriteOnly); for (int i = 0; i < indexes.size(); i++) { TreeItem* treeItem = static_cast<TreeItem*>(indexes.at(i).internalPointer()); dsTreeItemPtrs << reinterpret_cast<quintptr>(treeItem); dsDataNodePtrs << reinterpret_cast<quintptr>(treeItem->GetDataNode().GetPointer()); // --------------- deprecated ----------------- unsigned long long treeItemAddress = reinterpret_cast<unsigned long long>(treeItem); unsigned long long dataNodeAddress = reinterpret_cast<unsigned long long>(treeItem->GetDataNode().GetPointer()); QTextStream(&treeItemAddresses) << treeItemAddress; QTextStream(&dataNodeAddresses) << dataNodeAddress; if (i != indexes.size() - 1) { QTextStream(&treeItemAddresses) << ","; QTextStream(&dataNodeAddresses) << ","; } // -------------- end deprecated ------------- } // ------------------ deprecated ----------------- ret->setData("application/x-qabstractitemmodeldatalist", QByteArray(treeItemAddresses.toLatin1())); ret->setData("application/x-mitk-datanodes", QByteArray(dataNodeAddresses.toLatin1())); // --------------- end deprecated ----------------- ret->setData(QmitkMimeTypes::DataStorageTreeItemPtrs, baTreeItemPtrs); ret->setData(QmitkMimeTypes::DataNodePtrs, baDataNodePtrs); return ret; } QVariant QmitkDataStorageTreeModel::data( const QModelIndex & index, int role ) const { mitk::DataNode* dataNode = this->TreeItemFromIndex(index)->GetDataNode(); // get name of treeItem (may also be edited) QString nodeName; if(DicomPropertiesExists(*dataNode)) { mitk::BaseProperty* seriesDescription = (dataNode->GetProperty("dicom.series.SeriesDescription")); mitk::BaseProperty* studyDescription = (dataNode->GetProperty("dicom.study.StudyDescription")); mitk::BaseProperty* patientsName = (dataNode->GetProperty("dicom.patient.PatientsName")); nodeName += QFile::encodeName(patientsName->GetValueAsString().c_str()) + "\n"; nodeName += QFile::encodeName(studyDescription->GetValueAsString().c_str()) + "\n"; nodeName += QFile::encodeName(seriesDescription->GetValueAsString().c_str()); } else { nodeName = QFile::encodeName(dataNode->GetName().c_str()); } if(nodeName.isEmpty()) { nodeName = "unnamed"; } if (role == Qt::DisplayRole) return nodeName; else if(role == Qt::ToolTipRole) return nodeName; else if(role == Qt::DecorationRole) { QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode); return nodeDescriptor->GetIcon(); } else if(role == Qt::CheckStateRole) { return dataNode->IsVisible(0); } else if(role == QmitkDataNodeRole) { return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode)); } else if(role == QmitkDataNodeRawPointerRole) { return QVariant::fromValue<mitk::DataNode*>(dataNode); } return QVariant(); } bool QmitkDataStorageTreeModel::DicomPropertiesExists(const mitk::DataNode& node) const { bool propertiesExists = false; mitk::BaseProperty* seriesDescription = (node.GetProperty("dicom.series.SeriesDescription")); mitk::BaseProperty* studyDescription = (node.GetProperty("dicom.study.StudyDescription")); mitk::BaseProperty* patientsName = (node.GetProperty("dicom.patient.PatientsName")); if(patientsName!=NULL && studyDescription!=NULL && seriesDescription!=NULL) { if((!patientsName->GetValueAsString().empty())&& (!studyDescription->GetValueAsString().empty())&& (!seriesDescription->GetValueAsString().empty())) { propertiesExists = true; } } return propertiesExists; } QVariant QmitkDataStorageTreeModel::headerData(int /*section*/, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole && m_Root) return QString::fromStdString(m_Root->GetDataNode()->GetName()); return QVariant(); } void QmitkDataStorageTreeModel::SetDataStorage( mitk::DataStorage* _DataStorage ) { if(m_DataStorage != _DataStorage) // dont take the same again { if(m_DataStorage.IsNotNull()) { // remove Listener for the data storage itself m_DataStorage.ObjectDelete.RemoveListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const itk::Object*>( this, &QmitkDataStorageTreeModel::SetDataStorageDeleted ) ); // remove listeners for the nodes m_DataStorage->AddNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::AddNode ) ); m_DataStorage->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::SetNodeModified ) ); m_DataStorage->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::RemoveNode ) ); } // take over the new data storage m_DataStorage = _DataStorage; // delete the old root (if necessary, create new) if(m_Root) m_Root->Delete(); mitk::DataNode::Pointer rootDataNode = mitk::DataNode::New(); rootDataNode->SetName("Data Manager"); m_Root = new TreeItem(rootDataNode, 0); this->beginResetModel(); this->endResetModel(); if(m_DataStorage.IsNotNull()) { // add Listener for the data storage itself m_DataStorage.ObjectDelete.AddListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const itk::Object*>( this, &QmitkDataStorageTreeModel::SetDataStorageDeleted ) ); // add listeners for the nodes m_DataStorage->AddNodeEvent.AddListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::AddNode ) ); m_DataStorage->ChangedNodeEvent.AddListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::SetNodeModified ) ); m_DataStorage->RemoveNodeEvent.AddFirstListener( mitk::MessageDelegate1<QmitkDataStorageTreeModel , const mitk::DataNode*>( this, &QmitkDataStorageTreeModel::RemoveNode ) ); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = m_DataStorage->GetSubset(m_Predicate); // finally add all nodes to the model this->Update(); } } } void QmitkDataStorageTreeModel::SetDataStorageDeleted( const itk::Object* /*_DataStorage*/ ) { this->SetDataStorage(0); } void QmitkDataStorageTreeModel::AddNodeInternal(const mitk::DataNode *node) { if(node == 0 || m_DataStorage.IsNull() || !m_DataStorage->Exists(node) || m_Root->Find(node) != 0) return; // find out if we have a root node TreeItem* parentTreeItem = m_Root; QModelIndex index; mitk::DataNode* parentDataNode = this->GetParentNode(node); if(parentDataNode) // no top level data node { parentTreeItem = m_Root->Find(parentDataNode); // find the corresponding tree item if(!parentTreeItem) { this->AddNode(parentDataNode); parentTreeItem = m_Root->Find(parentDataNode); if(!parentTreeItem) return; } // get the index of this parent with the help of the grand parent index = this->createIndex(parentTreeItem->GetIndex(), 0, parentTreeItem); } // add node if(m_PlaceNewNodesOnTop) { // emit beginInsertRows event beginInsertRows(index, 0, 0); parentTreeItem->InsertChild(new TreeItem( const_cast<mitk::DataNode*>(node)), 0); } else { beginInsertRows(index, parentTreeItem->GetChildCount() , parentTreeItem->GetChildCount()); new TreeItem(const_cast<mitk::DataNode*>(node), parentTreeItem); } // emit endInsertRows event endInsertRows(); // Adjusting moved to Autoplan Seg Manger //this->AdjustLayerProperty(); } void QmitkDataStorageTreeModel::AddNode( const mitk::DataNode* node ) { if(node == 0 || m_BlockDataStorageEvents || m_DataStorage.IsNull() || !m_DataStorage->Exists(node) || m_Root->Find(node) != 0) return; this->AddNodeInternal(node); } void QmitkDataStorageTreeModel::SetPlaceNewNodesOnTop(bool _PlaceNewNodesOnTop) { m_PlaceNewNodesOnTop = _PlaceNewNodesOnTop; } void QmitkDataStorageTreeModel::RemoveNodeInternal( const mitk::DataNode* node ) { if(!m_Root) return; TreeItem* treeItem = m_Root->Find(node); if(!treeItem) return; // return because there is no treeitem containing this node TreeItem* parentTreeItem = treeItem->GetParent(); QModelIndex parentIndex = this->IndexFromTreeItem(parentTreeItem); if (!parentIndex.isValid() && parentTreeItem != m_Root) { return; } // emit beginRemoveRows event (QModelIndex is empty because we dont have a tree model) this->beginRemoveRows(parentIndex, treeItem->GetIndex(), treeItem->GetIndex()); // remove node std::vector<TreeItem*> children = treeItem->GetChildren(); delete treeItem; // emit endRemoveRows event endRemoveRows(); // move all children of deleted node into its parent for ( std::vector<TreeItem*>::iterator it = children.begin() ; it != children.end(); it++) { // emit beginInsertRows event beginInsertRows(parentIndex, parentTreeItem->GetChildCount(), parentTreeItem->GetChildCount()); // add nodes again parentTreeItem->AddChild(*it); // emit endInsertRows event endInsertRows(); } // Adjusting moved to Autoplan Seg Manger //this->AdjustLayerProperty(); } void QmitkDataStorageTreeModel::RemoveNode(const mitk::DataNode* node ) { if (node == 0 || m_BlockDataStorageEvents) return; this->RemoveNodeInternal(node); } void QmitkDataStorageTreeModel::SetNodeModified( const mitk::DataNode* node ) { TreeItem* treeItem = m_Root->Find(node); if(treeItem) { TreeItem* parentTreeItem = treeItem->GetParent(); // as the root node should not be removed one should always have a parent item if(!parentTreeItem) return; QModelIndex index = this->createIndex(treeItem->GetIndex(), 0, treeItem); // now emit the dataChanged signal emit dataChanged(index, index); } } mitk::DataNode* QmitkDataStorageTreeModel::GetParentNode( const mitk::DataNode* node ) const { mitk::DataNode* dataNode = 0; mitk::DataStorage::SetOfObjects::ConstPointer _Sources = m_DataStorage->GetSources(node); if(_Sources->Size() > 0) dataNode = _Sources->front(); return dataNode; } bool QmitkDataStorageTreeModel::setData( const QModelIndex &index, const QVariant &value, int role ) { mitk::DataNode* dataNode = this->TreeItemFromIndex(index)->GetDataNode(); if(!dataNode) return false; if(role == Qt::EditRole && !value.toString().isEmpty()) { dataNode->SetStringProperty("name", value.toString().toStdString().c_str()); mitk::PlanarFigure* planarFigure = dynamic_cast<mitk::PlanarFigure*>(dataNode->GetData()); if (planarFigure != NULL) mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } else if(role == Qt::CheckStateRole) { // Please note: value.toInt() returns 2, independentely from the actual checkstate of the index element. // Therefore the checkstate is being estimated again here. QVariant qcheckstate = index.data(Qt::CheckStateRole); int checkstate = qcheckstate.toInt(); bool isVisible = bool(checkstate); dataNode->SetVisibility(!isVisible); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } // inform listeners about changes emit dataChanged(index, index); return true; } bool QmitkDataStorageTreeModel::setHeaderData( int /*section*/, Qt::Orientation /*orientation*/, const QVariant& /* value */, int /*role = Qt::EditRole*/ ) { return false; } void QmitkDataStorageTreeModel::AdjustLayerProperty() { auto isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); auto isSegmentation = mitk::NodePredicateProperty::New("segmentation", mitk::BoolProperty::New(true)); auto isBinaryOrSegmentation = mitk::NodePredicateOr::New(isBinary, isSegmentation); /// transform the tree into an array and set the layer property descending std::vector<TreeItem*> vec; this->TreeToVector(m_Root, vec); int i = vec.size() - 1; auto adjustLayer = [&i](mitk::DataNode::Pointer dataNode) { bool fixedLayer = false; if (!(dataNode->GetBoolProperty("fixedLayer", fixedLayer) && fixedLayer)) dataNode->SetIntProperty("layer", i); --i; }; // First, process segmentations for(std::vector<TreeItem*>::const_iterator it = vec.begin(); it != vec.end(); ++it) { mitk::DataNode::Pointer dataNode = (*it)->GetDataNode(); if (isBinaryOrSegmentation->CheckNode(dataNode)) adjustLayer(dataNode); } // Second, process non-segmentation nodes for (std::vector<TreeItem*>::const_iterator it = vec.begin(); it != vec.end(); ++it) { mitk::DataNode::Pointer dataNode = (*it)->GetDataNode(); if (!isBinaryOrSegmentation->CheckNode(dataNode)) adjustLayer(dataNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataStorageTreeModel::TreeToVector(TreeItem* parent, std::vector<TreeItem*>& vec) const { TreeItem* current; for(int i = 0; i<parent->GetChildCount(); ++i) { current = parent->GetChild(i); this->TreeToVector(current, vec); vec.push_back(current); } } QModelIndex QmitkDataStorageTreeModel::IndexFromTreeItem( TreeItem* item ) const { if(item == m_Root) return QModelIndex(); else return this->createIndex(item->GetIndex(), 0, item); } QList<mitk::DataNode::Pointer> QmitkDataStorageTreeModel::GetNodeSet() const { QList<mitk::DataNode::Pointer> res; if(m_Root) this->TreeToNodeSet(m_Root, res); return res; } void QmitkDataStorageTreeModel::TreeToNodeSet( TreeItem* parent, QList<mitk::DataNode::Pointer>& vec ) const { TreeItem* current; for(int i = 0; i<parent->GetChildCount(); ++i) { current = parent->GetChild(i); vec.push_back(current->GetDataNode()); this->TreeToNodeSet(current, vec); } } QModelIndex QmitkDataStorageTreeModel::GetIndex( const mitk::DataNode* node ) const { if(m_Root) { TreeItem* item = m_Root->Find(node); if(item) return this->IndexFromTreeItem(item); } return QModelIndex(); } QList<QmitkDataStorageTreeModel::TreeItem *> QmitkDataStorageTreeModel::ToTreeItemPtrList(const QMimeData* mimeData) { if (mimeData == NULL || !mimeData->hasFormat(QmitkMimeTypes::DataStorageTreeItemPtrs)) { return QList<TreeItem*>(); } return ToTreeItemPtrList(mimeData->data(QmitkMimeTypes::DataStorageTreeItemPtrs)); } QList<QmitkDataStorageTreeModel::TreeItem *> QmitkDataStorageTreeModel::ToTreeItemPtrList(const QByteArray& ba) { QList<TreeItem*> result; QDataStream ds(ba); while(!ds.atEnd()) { quintptr treeItemPtr; ds >> treeItemPtr; result.push_back(reinterpret_cast<TreeItem*>(treeItemPtr)); } return result; } QmitkDataStorageTreeModel::TreeItem::TreeItem( mitk::DataNode* _DataNode, TreeItem* _Parent ) : m_Parent(_Parent) , m_DataNode(_DataNode) { if(m_Parent) m_Parent->AddChild(this); } QmitkDataStorageTreeModel::TreeItem::~TreeItem() { if(m_Parent) m_Parent->RemoveChild(this); } void QmitkDataStorageTreeModel::TreeItem::Delete() { while(m_Children.size() > 0) delete m_Children.back(); delete this; } QmitkDataStorageTreeModel::TreeItem* QmitkDataStorageTreeModel::TreeItem::Find( const mitk::DataNode* _DataNode ) const { QmitkDataStorageTreeModel::TreeItem* item = 0; if(_DataNode) { if(m_DataNode == _DataNode) item = const_cast<TreeItem*>(this); else { for(std::vector<TreeItem*>::const_iterator it = m_Children.begin(); it != m_Children.end(); ++it) { if(item) break; item = (*it)->Find(_DataNode); } } } return item; } int QmitkDataStorageTreeModel::TreeItem::IndexOfChild( const TreeItem* item ) const { std::vector<TreeItem*>::const_iterator it = std::find(m_Children.begin(), m_Children.end(), item); return it != m_Children.end() ? std::distance(m_Children.begin(), it): -1; } QmitkDataStorageTreeModel::TreeItem* QmitkDataStorageTreeModel::TreeItem::GetChild( int index ) const { return (m_Children.size() > 0 && index >= 0 && index < (int)m_Children.size())? m_Children.at(index): 0; } void QmitkDataStorageTreeModel::TreeItem::AddChild( TreeItem* item ) { this->InsertChild(item); } void QmitkDataStorageTreeModel::TreeItem::RemoveChild( TreeItem* item ) { std::vector<TreeItem*>::iterator it = std::find(m_Children.begin(), m_Children.end(), item); if(it != m_Children.end()) { m_Children.erase(it); item->SetParent(0); } } int QmitkDataStorageTreeModel::TreeItem::GetChildCount() const { return m_Children.size(); } int QmitkDataStorageTreeModel::TreeItem::GetIndex() const { if (m_Parent) return m_Parent->IndexOfChild(this); return 0; } QmitkDataStorageTreeModel::TreeItem* QmitkDataStorageTreeModel::TreeItem::GetParent() const { return m_Parent; } mitk::DataNode::Pointer QmitkDataStorageTreeModel::TreeItem::GetDataNode() const { return m_DataNode; } void QmitkDataStorageTreeModel::TreeItem::InsertChild( TreeItem* item, int index ) { std::vector<TreeItem*>::iterator it = std::find(m_Children.begin(), m_Children.end(), item); if(it == m_Children.end()) { if(m_Children.size() > 0 && index >= 0 && index < (int)m_Children.size()) { it = m_Children.begin(); std::advance(it, index); m_Children.insert(it, item); } else m_Children.push_back(item); // add parent if necessary if(item->GetParent() != this) item->SetParent(this); } } std::vector<QmitkDataStorageTreeModel::TreeItem*> QmitkDataStorageTreeModel::TreeItem::GetChildren() const { return m_Children; } void QmitkDataStorageTreeModel::TreeItem::SetParent( TreeItem* _Parent ) { m_Parent = _Parent; if(m_Parent) m_Parent->AddChild(this); } void QmitkDataStorageTreeModel::Update() { if (m_DataStorage.IsNotNull()) { this->beginResetModel(); this->endResetModel(); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = m_DataStorage->GetAll(); for (mitk::DataStorage::SetOfObjects::const_iterator it = _NodeSet->begin(); it != _NodeSet->end(); it++) { // save node this->AddNodeInternal(*it); } } } void QmitkDataStorageTreeModel::SetAllowHierarchyChange(bool allowHierarchyChange) { m_AllowHierarchyChange = allowHierarchyChange; }
30.6199
155
0.678614
[ "object", "vector", "model", "transform" ]
90ea5c8198efc170e5c3b567df660cbf2647d767
27,249
cpp
C++
code/main/RayCaster.cpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
4
2020-12-31T00:01:32.000Z
2021-11-20T15:39:46.000Z
code/main/RayCaster.cpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
null
null
null
code/main/RayCaster.cpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
1
2021-11-10T16:55:09.000Z
2021-11-10T16:55:09.000Z
/*# This file is part of the # ██████╗ ██╗ ██╗██╗ ██╗ ██╗ ██████╗ ██╗ ███████╗ # ██╔══██╗╚██╗██╔╝██║ ██║ ██║██╔═══██╗██║ ██╔════╝ # ██████╔╝ ╚███╔╝ ██║ ██║ █╗ ██║██║ ██║██║ █████╗ # ██╔═══╝ ██╔██╗ ██║ ██║███╗██║██║ ██║██║ ██╔══╝ # ██║ ██╔╝ ██╗███████╗╚███╔███╔╝╚██████╔╝███████╗██║ # ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚══════╝╚═╝ # project # # https://github.com/jacmoe/pxlwolf # # (c) 2020 - 2021 Jacob Moena # # MIT License #*/ #include <cmath> #include "stb_image.h" #include "spdlog/spdlog.h" #include "main/RayCaster.hpp" #include "main/types.hpp" #include "utility/packer.hpp" #include "utility/unpacker.hpp" RayCaster::RayCaster() { } RayCaster::~RayCaster() { } void RayCaster::init(uint32_t width, uint32_t height, std::shared_ptr<utility::Map> map, std::shared_ptr<Pixelator> pixelator) { m_map = map; m_pixelator = pixelator; m_width = width; m_height = height; initDepthBuffer(); tex_tile_width = 128; tex_tile_height = 128; ceil_tile_width = 512; ceil_tile_height = 512; initRayTexture("assets/textures/wolfsheet.png", tex_tile_width, tex_tile_height, 35); initWallCeilTexture("assets/textures/ceilfloor.png", ceil_tile_width, ceil_tile_height, 2); } /** RaycasterEngine::generateAngleValues * @brief Creates a pregenerated list of angle offsets for Camera * TODO: Consolidate w/ Camera struct and GameEngine code * @param width Width in pixels to generate offsets for * @param camera Camera for offsets */ void RayCaster::generateAngleValues(uint32_t width, Camera* camera) { double adjFactor = (double)width / (2 * tan(camera->fov / 2)); camera->angleValues[0] = atan((width / 2) / adjFactor) - atan((width / 2 - 1) / adjFactor); for (uint32_t i = 1; i < width; i++) { if(i < width / 2) { camera->angleValues[i] = camera->angleValues[i-1] + atan((width / 2 - i) / adjFactor) - atan((width / 2 - i - 1) / adjFactor); } else { camera->angleValues[i] = camera->angleValues[i-1] + atan((i + 1 - width / 2) / adjFactor) - atan((i - width / 2) / adjFactor); } } } void RayCaster::drawMinimap(const std::string& buffer_name, const Camera& camera, int blockSize) { utility::Map* map = m_map.get(); int row, col; IntRect mapRect; mapRect.width = map->width() * blockSize; mapRect.height = map->height() * blockSize; mapRect.top = mapRect.top = 0; mapRect.left = 0; IntRect blockRect; blockRect.width = blockSize; blockRect.height = blockSize; int p_x = static_cast<int>(camera.x); int p_y = static_cast<int>(camera.y); /* Draw map tiles */ for(row = 0; row < map->height(); row++) { for(col = 0; col < map->width(); col++) { uint8_t p_row = (uint8_t)row; uint8_t p_col = (uint8_t)col; uint32_t p_tile = utility::pack(p_col,p_row,1,1); blockRect.left = mapRect.left + col * blockSize; blockRect.top = mapRect.top + row * blockSize; if( (map->walls()[row * map->width() + col] > 0) /*&& ( m_global_visited.find(p_tile) != m_global_visited.end() )*/) { ALLEGRO_COLOR blockcolor = map->wall_element(map->walls()[row * map->width() + col]).color; m_pixelator.get()->drawFilledRect(buffer_name, blockRect, blockcolor); } else { ALLEGRO_COLOR background_color = al_map_rgba(112,112,112,255); m_pixelator.get()->drawFilledRect(buffer_name, blockRect, background_color); } if(p_y == row && p_x == col) { /* Draw the player */ ALLEGRO_COLOR sepiaPink = al_map_rgba(221,153,153,255); m_pixelator.get()->drawFilledRect(buffer_name, blockRect, sepiaPink); } } } } ALLEGRO_COLOR RayCaster::pixelGradientShader(ALLEGRO_COLOR pixel, double percent, ALLEGRO_COLOR target) { uint8_t r, g, b, a; al_unmap_rgba(pixel, &r, &g, &b, &a); uint8_t tr, tg, tb, ta; al_unmap_rgba(target, &tr, &tg, &tb, &ta); uint8_t dr = tr - r; uint8_t dg = tg - g; uint8_t db = tb - b; uint8_t da = ta - a; r += (uint8_t)((double)dr * percent); g += (uint8_t)((double)dg * percent); b += (uint8_t)((double)db * percent); a += (uint8_t)((double)da * percent); return al_map_rgba(r,g,b,a); } /** * @brief * * @param buffer * @param x * @param y * @param color * @param alphaNum * @param depth */ void RayCaster::setPixelAlphaDepth(uint32_t x, uint32_t y, ALLEGRO_COLOR color, double alphaNum, double depth) { uint8_t color_r, color_g, color_b, color_a; al_unmap_rgba(color, &color_r, &color_g, &color_b, &color_a); if (x >= 0 && x < m_width && y >= 0 && y < m_height) { // Keep pixel in alpha layer if (alphaNum < 1 || color_a < 255) { // If new alpha in front double pixDepth = getDepth(x, y, BL_ALPHA); if (pixDepth > depth) { setDepth(x, y, BL_ALPHA, depth); if (pixDepth == INFINITY) { color_a *= alphaNum; m_pixelator.get()->setPixel("alphaBuffer", x, y, al_map_rgba(color_r, color_g, color_b, color_a)); } else { m_pixelator.get()->setPixel("alphaBuffer", x, y, color); } } else { m_pixelator.get()->setPixel("alphaBuffer", x, y, color); //PixelRenderer::drawPix(buffer->alphaBuffer, x, y, PixelRenderer::blendAlpha(color, PixelRenderer::getPix(buffer->alphaBuffer, x, y), 1)); } } // For opaque layer else { // If new pixel in front if (getDepth(x, y, BL_BASE) > depth) { setDepth(x, y, BL_BASE, depth); m_pixelator.get()->setPixel("pixelBuffer", x, y, color); //PixelRenderer::drawPix(buffer->pixelBuffer, x, y, color); } } } } /** getInterDist * @brief Compute linear interpolation of ray intersect with wall * * @param dx x displacement along ray step * @param dy y displacement along ray step * @param xi Initial x coordinate * @param yi Initial y coordinate * @param coordX Grid tile x coordinate * @param coordY Grid tile y coordinate * @param newX Interpolated x coordinate * @param newY Interpolated y coordinate * @param side Numerical representation of side of intersect * @return double Adjusted distance to intersect */ double RayCaster::getInterDist(double dx, double dy, double xi, double yi, double coordX, double coordY, double* newX, double* newY, uint8_t* side) { // Check side intercepts first double slope = (dy/dx); double leftCoord = slope * (coordX - xi) + yi; double rightCoord = slope * (coordX + 1 - xi) + yi; slope = (dx/dy); double topCoord = slope * (coordY - yi) + xi; double bottomCoord = slope * (coordY + 1 - yi) + xi; double dist; double minDist = -1; if ((int)floor(leftCoord) == (int)coordY) // Left side { minDist = (xi - coordX)*(xi - coordX) + (yi - leftCoord)*(yi - leftCoord); *side = 0; *newX = coordX; *newY = leftCoord; } dist = (coordX + 1 - xi)*(coordX + 1 - xi) + (rightCoord - yi)*(rightCoord - yi); if ((int)floor(rightCoord) == (int)coordY && (dist < minDist || minDist == -1)) // Right side { minDist = dist; *side = 1; *newX = coordX + 1; *newY = rightCoord; } dist = (xi - topCoord)*(xi - topCoord) + (yi - coordY)*(yi - coordY); if ((int)floor(topCoord) == (int)coordX && (dist < minDist || minDist == -1)) // Top side { minDist = dist; *side = 2; *newX = topCoord; *newY = coordY; } dist = (xi - bottomCoord)*(xi - bottomCoord) + (yi - coordY - 1)*(yi - coordY - 1); if ((int)floor(bottomCoord) == (int)coordX && (dist < minDist || minDist == -1)) // Bottom side { minDist = dist; *side = 3; *newX = bottomCoord; *newY = coordY + 1; } return minDist; } void RayCaster::initDepthBuffer() { Pixelator* pixelator = m_pixelator.get(); pixelator->addBuffer("pixelBuffer", m_width, m_height); pixelator->addBuffer("alphaBuffer", m_width, m_height); m_pixel_depth.assign(m_width * m_height, INFINITY); m_alpha_depth.assign(m_width * m_height, INFINITY); } void RayCaster::resetDepthBuffer() { Pixelator* pixelator = m_pixelator.get(); pixelator->clear("pixelBuffer"); pixelator->clear("alphaBuffer"); m_pixel_depth.assign(m_width * m_height, INFINITY); m_alpha_depth.assign(m_width * m_height, INFINITY); } double RayCaster::getDepth(uint32_t x, uint32_t y, uint8_t layer) { return layer ? m_alpha_depth[m_width * y + x] : m_pixel_depth[m_width * y + x]; } void RayCaster::setDepth(uint32_t x, uint32_t y, uint8_t layer, double depth) { if (layer) { m_alpha_depth[m_width * y + x] = depth; } else { m_pixel_depth[m_width * y + x] = depth; } } /** RaycasterEngine::renderBuffer * @brief Merges opaque and alpha layers of buffer for rendering * * @param buffer Buffer to render */ void RayCaster::renderBuffer() { ALLEGRO_COLOR pixel; for (uint32_t i = 0; i < m_width; i++) { for (uint32_t j = 0; j < m_height; j++) { if (getDepth(i, j, BL_BASE) > getDepth(i, j, BL_ALPHA)) { pixel = m_pixelator.get()->getPixel("alphaBuffer", i, j); m_pixelator.get()->setPixel("pixelBuffer", i, j, pixel); } } } } void RayCaster::drawTextureColumn(uint32_t x, int32_t y, int32_t h, double depth, uint8_t tileNum, double alphaNum, uint32_t column, double fadePercent, ALLEGRO_COLOR targetColor) { if (y + h < 0 || fadePercent > 1.0) { return; // Sorry, messy fix but it works } int32_t offH = h; int32_t offY = 0; if (y < 0) { offY = -y; h = h + y; y = 0; } if (y + h > m_height) { h = m_height - y; } for (int32_t i = 0; i < h; i++) { int magic_number = tileNum * tex_tile_width * tex_tile_height + (uint32_t)floor(((double)(offY + i) / (double)offH) * (tex_tile_height)) * tex_tile_width + column; const uint8_t* pixel = &m_pixels[magic_number * 4]; ALLEGRO_COLOR pix = al_map_rgba(pixel[0], pixel[1], pixel[2], pixel[3]); //if (pix & 0xFF) //{ pix = pixelGradientShader(pix, fadePercent, targetColor); setPixelAlphaDepth(x, i+y, pix, alphaNum, depth); //} } } void RayCaster::drawTextureColumnEx(uint32_t x, int32_t y, int32_t h, double depth, Texture texture, uint8_t tileNum, double alphaNum, uint32_t column, double fadePercent, ALLEGRO_COLOR targetColor) { if (y + h < 0 || fadePercent > 1.0) { return; // Sorry, messy fix but it works } int32_t offH = h; int32_t offY = 0; if (y < 0) { offY = -y; h = h + y; y = 0; } if (y + h > m_height) { h = m_height - y; } for (int32_t i = 0; i < h; i++) { int magic_number = tileNum * texture.tile_width * texture.tile_height + (uint32_t)floor(((double)(offY + i) / (double)offH) * (texture.tile_height)) * texture.tile_width + column; const uint8_t* pixel = &m_pixels[magic_number * 4]; ALLEGRO_COLOR pix = al_map_rgba(pixel[0], pixel[1], pixel[2], pixel[3]); //if (pix & 0xFF) //{ pix = pixelGradientShader(pix, fadePercent, targetColor); setPixelAlphaDepth(x, i+y, pix, alphaNum, depth); //} } } //! RayBuffer dependent void RayCaster::raycastRender(Camera* camera, double resolution) { // Establish starting angle and sweep per column double startAngle = camera->angle - camera->fov / 2.0; double adjFactor = m_width / (2 * tan(camera->fov / 2)); double scaleFactor = (double)m_width / (double)m_height * 2.4; double rayAngle = startAngle; utility::Map* map = m_map.get(); // clear the set of visited tiles m_visited.clear(); // Sweeeeep for each column #pragma omp parallel for schedule(dynamic,1) private(rayAngle) for (uint32_t i = 0; i < m_width; i++) { rayAngle = startAngle + camera->angleValues[i]; double rayX = camera->x; double rayY = camera->y; double rayStepX = (resolution) * cos(rayAngle); double rayStepY = (resolution) * sin(rayAngle); double stepLen = (resolution) / scaleFactor; double rayLen = 0; int rayStep = 0; int rayOffX = 0; int rayOffY = 0; int collisions = 0; while (rayLen < camera->dist && collisions < 3) { int coordX = (int)floor(rayX+rayOffX); int coordY = (int)floor(rayY+rayOffY); // pack visited tile into a 32 bit int uint8_t theX = (uint8_t)floor(rayX+rayOffX); uint8_t theY = (uint8_t)floor(rayY+rayOffY); uint32_t tilenum = utility::pack(theX,theY,1,1); // store it in the visited set m_visited.insert(tilenum); // store it in the global visited set m_global_visited.insert(tilenum); if ((coordX >= 0.0 && coordY >= 0.0) && (coordX < map->width() && coordY < map->height()) && (map->walls()[coordY * map->width() + coordX] != 0)) { uint8_t mapTile = map->walls()[coordY * map->width() + coordX]; ALLEGRO_COLOR colorDat = {0,0,0,255}; if (rayLen != 0) { uint8_t side; double newX; double newY; double rayLen = sqrt(getInterDist(rayStepX, rayStepY, camera->x + rayOffX, camera->y + rayOffY, (double)coordX, (double)coordY, &newX, &newY, &side))/scaleFactor; uint32_t texCoord; if (side > 1) { texCoord = (uint32_t)floor((newX - coordX) * tex_tile_width); } else { texCoord = (uint32_t)floor((newY - coordY) * tex_tile_height); } double depth = (double)(rayLen * cos(rayAngle - camera->angle)); //double colorGrad = (depth) / camera->dist; //* Note: This is an awful mess but it is a temporary fix to get around rounding issues int32_t drawHeight = (int32_t)ceil((double)m_height / (depth * 5)); int32_t wallHeight = (int32_t)round(-camera->h * drawHeight); int32_t startY = m_height / 2 - drawHeight / 2 - wallHeight; int32_t offsetStartY = m_height / 2 - drawHeight / 2; int32_t deltaY = m_height - offsetStartY * 2; //ALLEGRO_COLOR fadeColor = {77,150,154,255}; double colorGrad; double fogConstant = 1.5/5; if (rayLen < (camera->dist*fogConstant)) { colorGrad = (rayLen) / (camera->dist*fogConstant); } else { colorGrad = 1.0; } ALLEGRO_COLOR fadeColor = {50,20,50,255}; drawTextureColumn( i, startY, deltaY, depth, mapTile - 1, 1.0, texCoord, colorGrad, fadeColor ); // Check for texture column transparency bool hasAlpha = false; int border = 2; for (uint32_t p = 0; p < tex_tile_height; p++) { if (( m_pixels[(mapTile-1)*tex_tile_width*tex_tile_height+texCoord+(tex_tile_width*p)] & 0xFF) < 0xFF) { collisions++; if (side == 0) // Hit from left { rayX += 1; rayY += rayStepY * (1.0/rayStepX); } else if (side == 1) // Hit from right { rayX -= 1; rayY -= rayStepY * (1.0/rayStepX); } else if (side == 2) // Hit from top { rayX += rayStepX * (1.0/rayStepY); rayY += 1; } else // Hit from bottom { rayX -= rayStepX * (1.0/rayStepY); rayY -= 1; } if (rayX+rayOffX < -border) { rayOffX += map->width() + border * 2; } else if (rayX+rayOffX >= map->width() + border) { rayOffX -= map->width() + border * 2; } if (rayY+rayOffY < -border) { rayOffY += map->height() + border*2; } else if (rayY+rayOffY >= map->height() + border) { rayOffY -= map->height() + border*2; } rayLen = sqrt((rayX-camera->x)*(rayX-camera->x) + (rayY-camera->y)*(rayY-camera->y)); rayStep++; hasAlpha = 1; break; } } if (hasAlpha) { continue; } } break; } rayX += rayStepX; rayY += rayStepY; int map_border = 2; if (rayX+rayOffX < - map_border) { rayOffX += map->width() + map_border * 2; } else if (rayX+rayOffX >= map->width() + map_border) { rayOffX -= map->width() + map_border * 2; } if (rayY+rayOffY < -map_border) { rayOffY += map->height() + map_border*2; } else if (rayY+rayOffY >= map->height() + map_border) { rayOffY -= map->height() + map_border * 2; } rayStep++; rayLen += stepLen; } } } void RayCaster::initRayTexture(const std::string& path, int tile_width, int tile_height, int num_tiles) { int32_t mPixWidth; int32_t mPixHeight; uint8_t* rgbaData = stbi_load(path.c_str(), &mPixWidth, &mPixHeight, NULL, 0); if (!rgbaData) { SPDLOG_ERROR("Could not load texture '{}'", path); return; } Pixelator* pixelator = m_pixelator.get(); pixelator->addBuffer("raytex"); pixelator->setSize("raytex", Vector2i(mPixWidth, mPixHeight)); std::string buf = pixelator->getActiveBuffer(); pixelator->setActiveBuffer("raytex"); pixelator->copy(rgbaData, Vector2i(mPixWidth, mPixHeight), 0, 0, IntRect(0, 0, mPixWidth, mPixHeight)); m_pixels.resize(mPixWidth * mPixHeight * 4); memcpy(&m_pixels[0], pixelator->getPixelsPtr(), mPixWidth * mPixHeight * 4); pixelator->setActiveBuffer(buf); pixelator->removeBuffer("raytex"); stbi_image_free(rgbaData); } void RayCaster::initWallCeilTexture(const std::string& path, int tile_width, int tile_height, int num_tiles) { int32_t mPixWidth; int32_t mPixHeight; uint8_t* rgbaData = stbi_load(path.c_str(), &mPixWidth, &mPixHeight, NULL, 0); if (!rgbaData) { SPDLOG_ERROR("Could not load texture '{}'", path); return; } Pixelator* pixelator = m_pixelator.get(); pixelator->addBuffer("ceiltex"); pixelator->setSize("ceiltex", Vector2i(mPixWidth, mPixHeight)); std::string buf = pixelator->getActiveBuffer(); pixelator->setActiveBuffer("ceiltex"); pixelator->copy(rgbaData, Vector2i(mPixWidth, mPixHeight), 0, 0, IntRect(0, 0, mPixWidth, mPixHeight)); m_wall_ceil_pixels.resize(mPixWidth * mPixHeight * 4); memcpy(&m_wall_ceil_pixels[0], pixelator->getPixelsPtr(), mPixWidth * mPixHeight * 4); pixelator->setActiveBuffer(buf); pixelator->removeBuffer("ceiltex"); stbi_image_free(rgbaData); } void RayCaster::renderFloor(Camera* camera, double resolution) { int tileNum = 0; double scaleFactor = (double)m_width / (double)m_height * 2.4; // Get initial coordinate position at top-left of floor space uint32_t startX = 0; uint32_t startY = m_height / 2; double pixelX; double pixelY; double pixelDist; double pixelDepth; double fadePercent; uint32_t texX; uint32_t texY; double startAngle = camera->angle - camera->fov / 2.0; double rayAngle; double rayCos; ALLEGRO_COLOR fadeColor = al_map_rgba(50,20,50,255); // iterate through *all* pixels... for (int x = startX; x < m_width; x++) { // Establish angle of column... rayAngle = startAngle + camera->angleValues[x]; rayCos = cos(rayAngle - camera->angle); for (int y = startY + 1; y < m_height; y++) { // Compute the distance to the pixel... pixelDist = (double)m_height * (1 + 2 * camera->h) / (10.0 * (y-startY-1) * rayCos) * scaleFactor; double fogConstant = 4.0/5; pixelDepth = (pixelDist * rayCos); fadePercent = pixelDist / (camera->dist * fogConstant); pixelX = camera->x + pixelDist * cos(rayAngle); pixelY = camera->y + pixelDist * sin(rayAngle); // Wow, is that really it? The math says so... int r; int g; int b; // r = 74; // g = 82; // b = 99; if (pixelDist < camera->dist * fogConstant) { // Get associated coordinate pixel... // TODO: some grid code... texX = (uint32_t)floor((double)ceil_tile_width * (pixelX - floor(pixelX))); texY = (uint32_t)floor((double)ceil_tile_height * (pixelY - floor(pixelY))); uint32_t pixColor = m_wall_ceil_pixels[tileNum * ceil_tile_width * ceil_tile_height + texX + texY * ceil_tile_width]; r = (int)(pixColor >> 3*8); g = (int)((pixColor >> 2*8) & 0xFF); b = (int)((pixColor >> 8) & 0xFF); int dr = fadeColor.r - r; int dg = fadeColor.g - g; int db = fadeColor.b - b; r += (int)((double)dr * fadePercent); g += (int)((double)dg * fadePercent); b += (int)((double)db * fadePercent); } else { r = fadeColor.r; g = fadeColor.g; b = fadeColor.b; } // buffer->pixels[x + y * buffer->width] = ((uint32_t)r << 3*8 | (uint32_t)g << 2*8 | (uint32_t)b << 8 | (uint32_t)0xFF); m_pixelator.get()->setPixel(x, y, al_map_rgba(r, g, b, 255)); // buffer->pixels[x + y * buffer->width] = ((uint32_t)r << 3*8 | (uint32_t)g << 2*8 | (uint32_t)b << 8 | (uint32_t)0xFF); } } } void RayCaster::renderCeiling(Camera* camera, double resolution) { int tileNum = 1; double scaleFactor = (double)m_width / (double)m_height * 2.4; // Get initial coordinate position at top-left of floor space uint32_t startX = 0; uint32_t startY = 0; double pixelX; double pixelY; double pixelDist; double pixelDepth; double fadePercent; uint32_t texX; uint32_t texY; double startAngle = camera->angle - camera->fov / 2.0; double rayAngle; double rayCos; ALLEGRO_COLOR fadeColor = {50,20,50,255}; // iterate through *all* pixels... for (int x = startX; x < m_width; x++) { // Establish angle of column... rayAngle = startAngle + camera->angleValues[x]; rayCos = cos(rayAngle - camera->angle); for (int y = startY; y < (m_height / 2)+1; y++) { // Compute the distance to the pixel... pixelDist = (double)m_height * (1 - 2 * camera->h) / (10.0 * (m_height / 2 - y) * rayCos) * scaleFactor; pixelDepth = (pixelDist * rayCos); double fogConstant = 4.0/5; fadePercent = pixelDist / (camera->dist * fogConstant); pixelX = camera->x + pixelDist * cos(rayAngle); pixelY = camera->y + pixelDist * sin(rayAngle); // Wow, is that really it? The math says so... int r; int g; int b; // r = 110; // g = 118; // b = 135; if (pixelDist < camera->dist * fogConstant) { // Get associated coordinate pixel... // TODO: some grid code... texX = (uint32_t)floor((double)ceil_tile_width * (pixelX - floor(pixelX))); texY = (uint32_t)floor((double)ceil_tile_height * (pixelY - floor(pixelY))); uint32_t pixColor = m_wall_ceil_pixels[tileNum * ceil_tile_width * ceil_tile_height + texX + texY * ceil_tile_width]; r = (int)(pixColor >> 3*8); g = (int)((pixColor >> 2*8) & 0xFF); b = (int)((pixColor >> 8) & 0xFF); int dr = fadeColor.r - r; int dg = fadeColor.g - g; int db = fadeColor.b - b; r += (int)((double)dr * fadePercent); g += (int)((double)dg * fadePercent); b += (int)((double)db * fadePercent); } else { r = fadeColor.r; g = fadeColor.g; b = fadeColor.b; } // PixelRenderer::drawPix(buffer, x, y, PixelRenderer::toPixColor(r,g,b,0xff)); m_pixelator.get()->setPixel(x, y, al_map_rgba(r, g, b, 255)); } } }
35.712975
182
0.510074
[ "render" ]
90eedabde19cb7ead5c2b205b475dfb10ebb3397
2,417
cpp
C++
contest-5-problem-C/main.cpp
tkharisov7/Algo-2-sem
71ea2850a05a887a57bbb7e92b22ae6566a88fd7
[ "MIT" ]
null
null
null
contest-5-problem-C/main.cpp
tkharisov7/Algo-2-sem
71ea2850a05a887a57bbb7e92b22ae6566a88fd7
[ "MIT" ]
null
null
null
contest-5-problem-C/main.cpp
tkharisov7/Algo-2-sem
71ea2850a05a887a57bbb7e92b22ae6566a88fd7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> bool IsInside(int x, int y, int width, int height) { return !(x < 1 || x > width || y < 1 || y > height); } class HashTable { public: HashTable(size_t capacity = 4) : capacity_(capacity), amount_(0), hash_table_(std::vector<Node*>(capacity, nullptr)) {} size_t Amount() const { return amount_; } void Add(const int x, const int y, const int width, const int height) { if (!IsInside(x, y, width, height)) { return; } size_t hash_value = HashFunction(x, y); Node* cur = hash_table_[hash_value]; Node* parent = nullptr; std::pair<int, int> point = {x, y}; while (cur != nullptr && cur->value != point) { parent = cur; cur = cur->child; } if (cur == nullptr) { ++amount_; Node* new_node = new Node; new_node->value = point; if (parent == nullptr) { hash_table_[hash_value] = new_node; } else { parent->child = new_node; } } } ~HashTable() { for (auto current : hash_table_) { while (current != nullptr) { Node* child = current->child; delete current; current = child; } } } private: struct Node { std::pair<int, int> value; Node* child{nullptr}; }; size_t capacity_{4}; size_t amount_{0}; std::vector<Node*> hash_table_; const long PRIME1 = 1117809793; const long PRIME2 = 965100379; size_t HashFunction(const long arg1, const long arg2) const {//using hash_table polynomial one here return static_cast<size_t>((arg1 * PRIME1 + arg2) % PRIME2 % capacity_); } }; void Solve(HashTable& hash_table, int width, int height, int n) { while (n-- > 0) { int x, y; std::cin >> x >> y; hash_table.Add(x, y, width, height); hash_table.Add(x, y - 1, width, height); hash_table.Add(x, y + 1, width, height); hash_table.Add(x - 1, y, width, height); hash_table.Add(x + 1, y, width, height); } if (static_cast<long long>(hash_table.Amount()) < static_cast<long long>(width) * static_cast<long long>(height)) { std::cout << "No"; } else { std::cout << "Yes"; } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); HashTable hash_table(2500000); int width, height, n; std::cin >> width >> height >> n; Solve(hash_table, width, height, n); }
25.712766
117
0.590815
[ "vector" ]
90f0537ecf6a881489e841d2c26d20f3f7303541
24,501
cpp
C++
src/host/ft_host/API_DimensionsTests.cpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
5
2019-05-10T19:37:22.000Z
2021-02-14T12:22:35.000Z
src/host/ft_host/API_DimensionsTests.cpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
2
2019-05-27T11:40:16.000Z
2019-09-03T05:58:42.000Z
src/host/ft_host/API_DimensionsTests.cpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
2
2019-12-21T19:14:22.000Z
2021-02-17T16:12:52.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" // This class is intended to test: // GetConsoleScreenBufferInfo // GetConsoleScreenBufferInfoEx // GetLargestConsoleWindowSize // SetConsoleScreenBufferInfoEx --> SetScreenBufferInfo internally // SetConsoleScreenBufferSize // SetConsoleWindowInfo class DimensionsTests { BEGIN_TEST_CLASS(DimensionsTests) TEST_CLASS_PROPERTY(L"BinaryUnderTest", L"conhost.exe") TEST_CLASS_PROPERTY(L"ArtifactUnderTest", L"wincon.h") TEST_CLASS_PROPERTY(L"ArtifactUnderTest", L"winconp.h") TEST_CLASS_PROPERTY(L"ArtifactUnderTest", L"wincontypes.h") TEST_CLASS_PROPERTY(L"ArtifactUnderTest", L"conmsgl1.h") TEST_CLASS_PROPERTY(L"ArtifactUnderTest", L"conmsgl2.h") END_TEST_CLASS() TEST_METHOD_SETUP(TestSetup); TEST_METHOD_CLEANUP(TestCleanup); TEST_METHOD(TestGetLargestConsoleWindowSize); TEST_METHOD(TestGetConsoleScreenBufferInfoAndEx); BEGIN_TEST_METHOD(TestSetConsoleWindowInfo) // This needs to run in both absolute and relative modes. TEST_METHOD_PROPERTY(L"Data:bAbsolute", L"{TRUE, FALSE}") END_TEST_METHOD() BEGIN_TEST_METHOD(TestSetConsoleScreenBufferSize) // 0x1 = X, 0x2 = Y, 0x3 = Both TEST_METHOD_PROPERTY(L"Data:scaleChoices", L"{1, 2, 3}") END_TEST_METHOD() TEST_METHOD(TestZeroSizedConsoleScreenBuffers); TEST_METHOD(TestSetConsoleScreenBufferInfoEx); }; bool DimensionsTests::TestSetup() { return Common::TestBufferSetup(); } bool DimensionsTests::TestCleanup() { return Common::TestBufferCleanup(); } void DimensionsTests::TestGetLargestConsoleWindowSize() { if (!OneCoreDelay::IsIsWindowPresent()) { Log::Comment(L"Largest window size scenario can't be checked on platform without classic window operations."); Log::Result(WEX::Logging::TestResults::Skipped); return; } // Note that this API is named "window size" but actually refers to the maximum viewport. // Viewport is defined as the character count that can fit within one client area of the window. // It has nothing to do with the outer pixel dimensions of the window. // To know the largest window size, we need: // - The size of the monitor that the console window is on // - The style of the window // - The current size of the font used within that window // The "largest window size" is the maximum number of rows and columns worth of characters // that can be displayed if the current console window was stretched as large as it is currently // allowed to be on the given monitor. // NOTE: The legacy behavior of this function (in v1) was to give the "full screen window" size as the largest // even if it was in windowed mode and wouldn't fit on the monitor. // Get the window handle HWND const hWindow = GetConsoleWindow(); VerifySucceededGLE(VERIFY_IS_TRUE(!!IsWindow(hWindow), L"Get the window handle for the window.")); // Get the dimensions of the monitor that the window is on. HMONITOR const hMonitor = MonitorFromWindow(hWindow, MONITOR_DEFAULTTONULL); VerifySucceededGLE(VERIFY_IS_NOT_NULL(hMonitor, L"Get the monitor handle corresponding to the console window.")); MONITORINFO mi = { 0 }; mi.cbSize = sizeof(MONITORINFO); VERIFY_WIN32_BOOL_SUCCEEDED(GetMonitorInfoW(hMonitor, &mi), L"Get monitor information for the handle."); // Get the styles for the window from the handle DWORD const dwStyle = GetWindowStyle(hWindow); DWORD const dwStyleEx = GetWindowExStyle(hWindow); BOOL const bHasMenu = OneCoreDelay::GetMenu(hWindow) != nullptr; // Get the current font size CONSOLE_FONT_INFO cfi; VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFont(Common::_hConsole, FALSE, &cfi), L"Get the current console font structure."); // Now use what we've learned to attempt to calculate the expected size COORD coordExpected = { 0 }; RECT rcPixels = mi.rcWork; // start from the monitor work area as the maximum pixel size // we have to adjust the work area by the size of the window borders to compensate for a maximized window // where the window manager will render the borders off the edges of the screen. WINDOWINFO wi = { 0 }; wi.cbSize = sizeof(WINDOWINFO); VERIFY_WIN32_BOOL_SUCCEEDED(GetWindowInfo(hWindow, &wi), L"Get window information to obtain window border sizes."); rcPixels.top -= wi.cyWindowBorders; rcPixels.bottom += wi.cyWindowBorders; rcPixels.left -= wi.cxWindowBorders; rcPixels.right += wi.cxWindowBorders; UnadjustWindowRectEx(&rcPixels, dwStyle, bHasMenu, dwStyleEx); // convert outer window dimensions into client area size // Do not reserve space for scroll bars. // Now take width and height and divide them by the size of a character to get the max character count. coordExpected.X = (SHORT)((rcPixels.right - rcPixels.left) / cfi.dwFontSize.X); coordExpected.Y = (SHORT)((rcPixels.bottom - rcPixels.top) / cfi.dwFontSize.Y); // Now finally ask the console what it thinks its largest size should be and compare. COORD const coordLargest = GetLargestConsoleWindowSize(Common::_hConsole); VerifySucceededGLE(VERIFY_IS_NOT_NULL(coordLargest, L"Now ask what the console thinks the largest size should be.")); VERIFY_ARE_EQUAL(coordExpected, coordLargest, L"Compare what we calculated to what the console says the largest size should be."); } void DimensionsTests::TestGetConsoleScreenBufferInfoAndEx() { // Get both structures CONSOLE_SCREEN_BUFFER_INFO sbi = { 0 }; CONSOLE_SCREEN_BUFFER_INFOEX sbiex = { 0 }; sbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfo(Common::_hConsole, &sbi), L"Retrieve old-style buffer info."); VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Retrieve extended buffer info."); Log::Comment(NoThrowString().Format(L"Verify overlapping values are the same between both call types.")); VERIFY_ARE_EQUAL(sbi.dwCursorPosition, sbiex.dwCursorPosition); VERIFY_ARE_EQUAL(sbi.dwMaximumWindowSize, sbi.dwMaximumWindowSize); VERIFY_ARE_EQUAL(sbi.dwSize, sbiex.dwSize); VERIFY_ARE_EQUAL(sbi.srWindow, sbiex.srWindow); VERIFY_ARE_EQUAL(sbi.wAttributes, sbiex.wAttributes); } void ConvertAbsoluteToRelative(bool const bAbsolute, SMALL_RECT* const srViewport, const SMALL_RECT* const srOriginalWindow) { if (!bAbsolute) { srViewport->Left -= srOriginalWindow->Left; srViewport->Right -= srOriginalWindow->Right; srViewport->Top -= srOriginalWindow->Top; srViewport->Bottom -= srOriginalWindow->Bottom; } } void TestSetConsoleWindowInfoHelper(bool const bAbsolute, const SMALL_RECT* const srViewport, const SMALL_RECT* const srOriginalViewport, bool const bExpectedResult, PCWSTR pwszDescription) { SMALL_RECT srTest = *srViewport; ConvertAbsoluteToRelative(bAbsolute, &srTest, srOriginalViewport); Log::Comment(NoThrowString().Format(L"Abs:%s Original:%s Viewport:%s", bAbsolute ? L"True" : L"False", VerifyOutputTraits<SMALL_RECT>::ToString(*srOriginalViewport).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"), VerifyOutputTraits<SMALL_RECT>::ToString(srTest).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"))); if (bExpectedResult) { VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleWindowInfo(Common::_hConsole, bAbsolute, &srTest), pwszDescription); } else { VERIFY_WIN32_BOOL_FAILED(SetConsoleWindowInfo(Common::_hConsole, bAbsolute, &srTest), pwszDescription); } } void DimensionsTests::TestSetConsoleWindowInfo() { bool bAbsolute; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"bAbsolute", bAbsolute), L"Get absolute vs. relative parameter"); // Get window and buffer information CONSOLE_SCREEN_BUFFER_INFOEX sbiex = { 0 }; sbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Get initial buffer and window information."); SMALL_RECT srViewport = { 0 }; // Test with and without absolute // Left > Right, Top > Bottom (INVALID) srViewport.Right = sbiex.srWindow.Left; srViewport.Left = sbiex.srWindow.Right; srViewport.Bottom = sbiex.srWindow.Top; srViewport.Top = sbiex.srWindow.Bottom; TestSetConsoleWindowInfoHelper(bAbsolute, &srViewport, &sbiex.srWindow, false, L"Ensure Left > Right, Top > Bottom is marked invalid."); // Window greater than, equal to and less than the max client window // Window > Max ( INVALID ) srViewport.Left = 0; srViewport.Top = 0; srViewport.Right = sbiex.dwMaximumWindowSize.X; // this is 1 larger than the valid right bound since it's 0-based array indexes srViewport.Bottom = sbiex.dwMaximumWindowSize.Y; TestSetConsoleWindowInfoHelper(bAbsolute, &srViewport, &sbiex.srWindow, false, L"Ensure window larger than max is marked invalid."); // Set to same position we were just at (full screen or not) // VALID, SUCCESS srViewport = sbiex.srWindow; TestSetConsoleWindowInfoHelper(bAbsolute, &srViewport, &sbiex.srWindow, true, L"Set to the original window size"); TestSetConsoleWindowInfoHelper(bAbsolute, &srViewport, &sbiex.srWindow, true, L"Confirm that setting it again to the same position works."); // Will fail while in full screen, but no current way to set that mode externally. :( // Finally, check roundtrip by changing window. srViewport = sbiex.srWindow; srViewport.Left += 1; srViewport.Right -= 1; srViewport.Top += 1; srViewport.Bottom -= 1; // Verify the assumption that the viewport was sufficiently large to shrink it in the above manner. if (srViewport.Left > srViewport.Right || srViewport.Top > srViewport.Bottom || (srViewport.Right - srViewport.Left) < 1 || (srViewport.Bottom - srViewport.Top) < 1) { VERIFY_FAIL(NoThrowString().Format(L"Adjusted viewport is invalid. %s", VerifyOutputTraits<SMALL_RECT>::ToString(srViewport).GetBuffer())); } // Store a copy of the original (for comparison in case the relative translation is applied). SMALL_RECT const srViewportBefore = srViewport; TestSetConsoleWindowInfoHelper(bAbsolute, &srViewport, &sbiex.srWindow, true, L"Attempt shrinking the window in a valid manner."); // Get it back and ensure it's the same dimensions CONSOLE_SCREEN_BUFFER_INFO sbi = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfo(Common::_hConsole, &sbi), L"Confirm the size we specified round-trips through to the Get API."); VERIFY_ARE_EQUAL(srViewportBefore, sbi.srWindow, L"Match before and after viewport sizes."); } void RestrictDimensionsHelper(COORD* const coordTest, SHORT const x, SHORT const y, bool const fUseX, bool const fUseY) { if (fUseX) { coordTest->X = x; } if (fUseY) { coordTest->Y = y; } } void DimensionsTests::TestSetConsoleScreenBufferSize() { DWORD dwMode = { 0 }; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"scaleChoices", dwMode), L"Get active mode"); bool fAdjustX = false; bool fAdjustY = false; if ((dwMode & 0x1) != 0) { fAdjustX = true; Log::Comment(L"Adjusting X dimension"); } if ((dwMode & 0x2) != 0) { fAdjustY = true; Log::Comment(L"Adjusting Y dimension"); } CONSOLE_SCREEN_BUFFER_INFO sbi = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfo(Common::_hConsole, &sbi), L"Get initial buffer/window information."); COORD coordSize = { 0 }; // Ensure buffer size cannot be smaller than minimum RestrictDimensionsHelper(&coordSize, 0, 0, fAdjustX, fAdjustY); VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Set buffer size to smaller than minimum possible."); // Ensure buffer size cannot be excessively large. RestrictDimensionsHelper(&coordSize, SHRT_MAX, SHRT_MAX, fAdjustX, fAdjustY); VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Set buffer size to very, very large."); // Ensure buffer size cannot be excessively small (negative). RestrictDimensionsHelper(&coordSize, SHRT_MIN, SHRT_MIN, fAdjustX, fAdjustY); VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Set buffer size to negative values."); // Ensure success on giving the same size back that we started with coordSize = sbi.dwSize; VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Set it to the same size as initial."); // save the dimensions of the window for use in tests relative to window size COORD coordWindowDim; coordWindowDim.X = sbi.srWindow.Right - sbi.srWindow.Left; coordWindowDim.Y = sbi.srWindow.Bottom - sbi.srWindow.Top; // Ensure buffer size cannot be smaller than the window coordSize = coordWindowDim; RestrictDimensionsHelper(&coordSize, coordSize.X - 1, coordSize.Y - 1, fAdjustX, fAdjustY); VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Try to make buffer smaller than the window size."); // Success on setting a buffer larger than the window coordSize = coordWindowDim; coordSize.X++; coordSize.Y++; VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleScreenBufferSize(Common::_hConsole, coordSize), L"Try to make buffer larger than the window size."); } void DimensionsTests::TestZeroSizedConsoleScreenBuffers() { // Make sure we never accept zero-sized console buffers through the public API const COORD rgTestCoords[] = { { 0, 0 }, { 0, 1 }, { 1, 0 } }; for (size_t i = 0; i < ARRAYSIZE(rgTestCoords); i++) { const BOOL fSucceeded = SetConsoleScreenBufferSize(Common::_hConsole, rgTestCoords[i]); VERIFY_IS_FALSE(!!fSucceeded, NoThrowString().Format(L"Setting zero console size should always fail (x: %d y:%d)", rgTestCoords[i].X, rgTestCoords[i].Y)); VERIFY_ARE_EQUAL((DWORD)ERROR_INVALID_PARAMETER, GetLastError()); } } template<typename T> void TestSetConsoleScreenBufferInfoExHelper(bool const fShouldHaveChanged, T const pOriginal, T const pTest, T const pReturned, PCWSTR pwszDescriptor) { if (fShouldHaveChanged) { VERIFY_ARE_EQUAL(pTest, pReturned, NoThrowString().Format(L"Verify %s has changed to match the test value.", pwszDescriptor)); VERIFY_ARE_NOT_EQUAL(pOriginal, pReturned, NoThrowString().Format(L"Verify %s does not match original value.", pwszDescriptor)); } else { VERIFY_ARE_NOT_EQUAL(pTest, pReturned, NoThrowString().Format(L"Verify %s has NOT changed to match the test value.", pwszDescriptor)); VERIFY_ARE_EQUAL(pOriginal, pReturned, NoThrowString().Format(L"Verify %s DOES match original value.", pwszDescriptor)); } } void DimensionsTests::TestSetConsoleScreenBufferInfoEx() { CONSOLE_SCREEN_BUFFER_INFOEX sbiex = { 0 }; sbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); // <n/a> = cbSize // Attributes = wAttributes // ColorTable = ColorTable // CursorPosition = dwCursorPosition // FullscreenSupported = bFullscreenSupported // MaximumWindowSize = dwMaximumWindowSize // PopupAttributes = wPopupAttributes // Size = dwSize // combine to make srWindow. Translated inside the driver \minkernel\console\client\getset.c // CurrentWindowSize // ScrollPosition VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Get original buffer state."); // save a copy for the final comparison. CONSOLE_SCREEN_BUFFER_INFOEX const sbiexOriginal = sbiex; // check invalid values of viewport size sbiex = sbiexOriginal; sbiex.dwSize.X = 0; sbiex.dwSize.Y = 0; VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Try 0x0 viewport size."); sbiex = sbiexOriginal; sbiex.dwSize.X = MAXSHORT; sbiex.dwSize.Y = MAXSHORT; VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Try MAX by MAX viewport size."); // Fill the entire structure with new data and set sbiex.dwSize.X = 200; sbiex.dwSize.Y = 5555; sbiex.srWindow.Left = 0; sbiex.srWindow.Right = 79; sbiex.srWindow.Top = 0; sbiex.srWindow.Bottom = 49; sbiex.wAttributes = BACKGROUND_BLUE | BACKGROUND_INTENSITY | FOREGROUND_RED; sbiex.wPopupAttributes = BACKGROUND_GREEN | FOREGROUND_RED; sbiex.ColorTable[0] = 0x0000000F; sbiex.ColorTable[1] = 0x000000F0; sbiex.ColorTable[2] = 0x00000F00; sbiex.ColorTable[3] = 0x0000F000; sbiex.ColorTable[4] = 0x000F0000; sbiex.ColorTable[5] = 0x00F00000; sbiex.ColorTable[6] = 0x000000FF; sbiex.ColorTable[7] = 0x00000FF0; sbiex.ColorTable[8] = 0x0000FF00; sbiex.ColorTable[9] = 0x000FF000; sbiex.ColorTable[10] = 0x00FF0000; sbiex.ColorTable[11] = 0x00000FFF; sbiex.ColorTable[12] = 0x0000FFF0; sbiex.ColorTable[13] = 0x000FFF00; sbiex.ColorTable[14] = 0x00FFF000; sbiex.ColorTable[15] = 0x0000FFFF; sbiex.dwMaximumWindowSize.X = 100; sbiex.dwMaximumWindowSize.Y = 80; sbiex.bFullscreenSupported = !sbiex.bFullscreenSupported; // set to opposite // DO NOT TRY TO SET THE CURSOR. It may or may not be in the same place. The Set API actually never obeyed the request // to set the position and we can't fix it now. VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Attempt to set structure with all new data."); // Confirm that the prompt stored settings as appropriate CONSOLE_SCREEN_BUFFER_INFOEX sbiexAfter = { 0 }; sbiexAfter.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiexAfter), L"Retrieve set data with get."); // Verify that relevant properties were stored into the console. // The buffer size is weird because there are currently two valid answers. // This is due to the word wrap status of the console which is currently not visible through the API. // We must accept either answer as valid. bool fBufferSizePassed = false; // 1. The buffer size we set matches exactly with what we retrieved after it was done. (classic behavior, no word wrap) if (VerifyCompareTraits<COORD, COORD>().AreEqual(sbiex.dwSize, sbiexAfter.dwSize)) { fBufferSizePassed = true; } // 2. The buffer size is restricted/pegged to the width (X dimension) of the window. (new behavior, word wrap) short sWidthLimit = (sbiex.srWindow.Right - sbiex.srWindow.Left) + 1; // the right index counts as valid, so right - left + 1 for total width. // 2a. Width expected might be reduced if the buffer is taller than the window. If so, reduce by a scroll bar in width. if (sbiex.dwSize.Y > ((sbiex.srWindow.Bottom - sbiex.srWindow.Top) + 1)) // the bottom index counts as valid, so bottom - top + 1 for total height. { // Get pixel size of a vertical scroll bar. short const sVerticalScrollWidthPx = (SHORT)GetSystemMetrics(SM_CXVSCROLL); // Get the current font size CONSOLE_FONT_INFO cfi; VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFont(Common::_hConsole, FALSE, &cfi), L"Get the current console font structure."); if (VERIFY_ARE_NOT_EQUAL(0, cfi.dwFontSize.X, L"Verify that the font width is not zero or we'll have a division error.")) { // Figure out how many character widths to reduce by. short sReduceBy = 0; // Divide the size of a scroll bar by the font widths. sReduceBy = sVerticalScrollWidthPx / cfi.dwFontSize.X; // If there is a remainder, add one more. We can't render partial characters. sReduceBy += sVerticalScrollWidthPx % cfi.dwFontSize.X ? 1 : 0; // Subtract the number of characters being reserved for the scroll bar. sWidthLimit -= sReduceBy; } } // 2b. Do the comparison. Y should be correct, but X will be the lesser of the size we asked for or the window limit for word wrap. if (sbiex.dwSize.Y == sbiexAfter.dwSize.Y && min(sbiex.dwSize.X, sWidthLimit) == sbiexAfter.dwSize.X) { fBufferSizePassed = true; } VERIFY_IS_TRUE(fBufferSizePassed, L"Verify Buffer Size has changed as expected."); // Test remaining parameters are the same TestSetConsoleScreenBufferInfoExHelper(true, sbiexOriginal.wAttributes, sbiex.wAttributes, sbiexAfter.wAttributes, L"Attributes (Fg/Bg Colors)"); TestSetConsoleScreenBufferInfoExHelper(true, sbiexOriginal.wPopupAttributes, sbiex.wPopupAttributes, sbiexAfter.wPopupAttributes, L"Popup Attributes (Fg/Bg Colors)"); // verify colors match for (UINT i = 0; i < 16; i++) { TestSetConsoleScreenBufferInfoExHelper(true, sbiexOriginal.ColorTable[i], sbiex.ColorTable[i], sbiexAfter.ColorTable[i], NoThrowString().Format(L"Color %x", i)); } // NOTE: Max window size and the positioning of the window are adjusted at the discretion of the console. // They will not necessarily match, so we're not testing them. // NOTE: Full screen will NOT be changed by this API and should match the originals. TestSetConsoleScreenBufferInfoExHelper(false, sbiexOriginal.bFullscreenSupported, sbiex.bFullscreenSupported, sbiexAfter.bFullscreenSupported, L"Fullscreen"); // NOTE: Ignore cursor position. It can change or not depending on the word wrap mode and the API set doesn't do anything. // BUG: This is a long standing bug in the console which some of our customers have documented on the MSDN page. // The console driver (\minkernel\console\client\getset.c) is treating the viewport as an "exclusive" rectangle where it is actually "inclusive" // of its edges. This means when it does a width calculation, it has an off-by-one error and will shrink the window in height and width by 1 each // trip around. For example, normally we do viewport width as Right-Left+1, and the driver does it as Right-Left. // As this has lasted so long, it's likely a compat issue to fix now. So we'll leave it in and compensate for it in the test here. // See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686039(v=vs.85).aspx CONSOLE_SCREEN_BUFFER_INFOEX sbiexBug = sbiexOriginal; sbiexBug.srWindow.Bottom++; sbiexBug.srWindow.Right++; // Restore original settings VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiexBug), L"Restore original settings."); // Ensure originals are restored. VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiexAfter), L"Retrieve what we just set."); // NOTE: Set the two cursor positions to the same thing because we don't care to compare them. They can // be different or they may not be different. The SET API doesn't actually work so it depends on the other state, // which we're not measuring now. sbiexAfter.dwCursorPosition = sbiexOriginal.dwCursorPosition; VERIFY_ARE_EQUAL(sbiexAfter, sbiexOriginal, L"Ensure settings are back to original values."); }
46.228302
171
0.697523
[ "render" ]
90f14e8ca0b9ae04404e80f8fe2577bf384013ec
1,008
cpp
C++
meta/test/src/Mapped.cpp
Rerito/suffix-tree-v2
651ccd17a2a5dce67be04e2f9df4a65f8df2f2e7
[ "MIT" ]
6
2019-01-22T00:16:51.000Z
2020-11-13T11:45:04.000Z
meta/test/src/Mapped.cpp
Rerito/Penjing
651ccd17a2a5dce67be04e2f9df4a65f8df2f2e7
[ "MIT" ]
3
2022-02-28T12:25:52.000Z
2022-03-03T20:54:07.000Z
meta/test/src/Mapped.cpp
Rerito/suffix-tree-v2
651ccd17a2a5dce67be04e2f9df4a65f8df2f2e7
[ "MIT" ]
null
null
null
// Copyright (c) 2021, Rerito // SPDX-License-Identifier: MIT #include <map> #include <unordered_map> #include <vector> #include <gtest/gtest.h> #include <Penjing/Meta/CustomizationPoints/Mapped.hpp> TEST(CustomizationPoints, mappedAt) { std::unordered_map< int, int > m{{1, 2}, {3, 4}, {5, 6}}; auto at1 = Penjing::Meta::mappedAt(m, 1); ASSERT_TRUE(!!at1); ASSERT_EQ(2, *at1); auto at2 = Penjing::Meta::mappedAt(m, 2); ASSERT_TRUE(!at2); } TEST(CustomizationPoints, unsafeMappedAt) { std::unordered_map< int, int > m{{1, 2}, {3, 4}, {5, 6}}; int& at1 = Penjing::Meta::unsafeMappedAt(m, 1); ASSERT_EQ(at1, 2); ASSERT_THROW(Penjing::Meta::unsafeMappedAt(m, 2), std::invalid_argument); } TEST(CustomizationPoints, mapped) { std::map< int, int > m{{1, 2}, {3, 4}, {5, 6}}; std::vector< int > values{2, 4, 6}; std::vector< int > result; std::ranges::copy(Penjing::Meta::mapped(m), std::back_inserter(result)); ASSERT_EQ(values, result); }
22.4
77
0.633929
[ "vector" ]
90f29597ca26665f81be08b5c72859b225c24cb3
5,391
cpp
C++
source/vgagfx.cpp
TerrySoba/DosPlatformGame
ce688db9e5b9fb1db6180774c73aeb0aeb16f4a8
[ "MIT" ]
null
null
null
source/vgagfx.cpp
TerrySoba/DosPlatformGame
ce688db9e5b9fb1db6180774c73aeb0aeb16f4a8
[ "MIT" ]
null
null
null
source/vgagfx.cpp
TerrySoba/DosPlatformGame
ce688db9e5b9fb1db6180774c73aeb0aeb16f4a8
[ "MIT" ]
null
null
null
#include "vgagfx.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dos.h> #include <conio.h> #include <stdio.h> #define inport(px) inpw(px) #define inportb(px) inp(px) #define SCREEN_W 320L #define SCREEN_H 200L extern void videoInit(uint8_t mode); #pragma aux videoInit = \ "mov ah, 0" \ "int 10h" \ modify [ax] \ parm [al]; int compareRectangles(const void* a, const void* b) { return ( ((Rectangle*)a)->y > ((Rectangle*)b)->y ); } void sortRects(tnd::vector<Rectangle>& rects) { qsort(&rects[0], rects.size(), sizeof(Rectangle), compareRectangles); } VgaGfx::VgaGfx() { long int screenBytes = SCREEN_W * SCREEN_H; m_backgroundImage = new char[screenBytes]; m_screenBuffer = new char[screenBytes]; memset(m_backgroundImage, 0xff, screenBytes); memset(m_screenBuffer, 0x0, screenBytes); Rectangle rect(0, 0, SCREEN_W, SCREEN_H); m_dirtyRects.push_back(rect); videoInit(0x13); } VgaGfx::~VgaGfx() { delete[] m_screenBuffer; delete[] m_backgroundImage; videoInit(0x03); } #define CGA_STATUS_REG 0x03DA #define VERTICAL_RETRACE_BIT 0x08 #define waitForVsync() \ while (inportb(CGA_STATUS_REG) & VERTICAL_RETRACE_BIT); \ while (!(inportb(CGA_STATUS_REG) & VERTICAL_RETRACE_BIT)) #define LINE_BYTES SCREEN_W static char far* screen = (char far*)(0xA0000000L); #define getScreenLine(line) (screen + LINE_BYTES * (line)) #define getBackBufferLine(line) (m_screenBuffer + LINE_BYTES * (line)) #define getBackgroundImageLine(line) (m_backgroundImage + LINE_BYTES * (line)) void VgaGfx::vsync() { waitForVsync(); } #define lower(x) (x & 0x0f) #define upper(x) ((x & 0xf0) >> 4) #define set_lower(x, val) ((x & 0xf0) | val) #define set_upper(x, val) ((x & 0x0f) | (val << 4)) void VgaGfx::draw(const Drawable& image, int16_t x, int16_t y) { Rectangle rect( x, y, image.width(), image.height()); rect = rect.intersection(Rectangle(0, 0, SCREEN_W, SCREEN_H)); m_dirtyRects.push_back(rect); m_undrawnRects.push_back(rect); image.draw(m_screenBuffer, SCREEN_W, SCREEN_H, x, y); } void VgaGfx::drawBackground(const Drawable& image, int16_t x, int16_t y) { Rectangle rect( x, y, image.width(), image.height()); rect = rect.intersection(Rectangle(0, 0, SCREEN_W, SCREEN_H)); m_dirtyRects.push_back(rect); image.draw(m_backgroundImage, SCREEN_W, SCREEN_H, x, y); } void VgaGfx::clear() { for (int i = 0; i < m_dirtyRects.size(); ++i) { m_undrawnRects.push_back(m_dirtyRects[i]); const Rectangle& rect = m_dirtyRects[i]; int16_t rectHeight = rect.height; int16_t rectWidth = rect.width; int16_t rectY = rect.y; int16_t rectX = rect.x; for (int16_t y = 0; y < rectHeight; ++y) { memcpy(getBackBufferLine(y + rectY) + rectX, getBackgroundImageLine(y + rectY) + rectX, rectWidth); } } m_dirtyRects.clear(); } void VgaGfx::drawScreen() { vsync(); // todo: Create minimal set of rectangles to redraw. for (int i = 0; i < m_undrawnRects.size(); ++i) { Rectangle& rect = m_undrawnRects[i]; int16_t rectHeight = rect.height; int16_t rectWidth = rect.width; int16_t rectY = rect.y; int16_t rectX = rect.x; for (int16_t y = 0; y < rectHeight; ++y) { memcpy(getScreenLine(y + rectY) + rectX, getBackBufferLine(y + rectY) + rectX, rectWidth); } } m_undrawnRects.clear(); } void VgaGfx::setBackground(const ImageBase& image) { if (image.width() == SCREEN_W && image.height() == SCREEN_H) { memcpy(m_backgroundImage, image.data(), SCREEN_W * SCREEN_H); Rectangle rect( 0, 0, image.width(), image.height()); m_dirtyRects.push_back(rect); } } static const uint8_t rgbiColors[] = { 0x00,0x00,0x00, 0xAA,0x00,0x00, 0x00,0xAA,0x00, 0xAA,0xAA,0x00, 0x00,0x00,0xAA, 0xAA,0x00,0xAA, 0x00,0x55,0xAA, 0xAA,0xAA,0xAA, 0x55,0x55,0x55, 0xFF,0x55,0x55, 0x55,0xFF,0x55, 0xFF,0xFF,0x55, 0xFF,0x55,0xFF, 0xFF,0x55,0xFF, 0x55,0xFF,0xFF, 0xFF,0xFF,0xFF, }; void write16bit(uint16_t data, FILE* fp) { fwrite(&data, 2, 1, fp); } void write8bit(uint8_t data, FILE* fp) { fwrite(&data, 1, 1, fp); } void convertToTga(char far* data, const char* filename) { FILE* fp = fopen(filename, "wb"); write8bit(0, fp); // id length in bytes write8bit(1, fp); // color map type (1 == color map / palette present) write8bit(1, fp); // image type (1 == uncompressed color-mapped image) write16bit(0, fp); // color map origin write16bit(16, fp); // color map length write8bit(24, fp); // color map depth (bits per palette entry) write16bit(0, fp); // x origin write16bit(0, fp); // y origin write16bit(320, fp); // image width write16bit(200, fp); // image height write8bit(8, fp); // bits per pixel write8bit((1 << 5), fp); // image descriptor // we do not have id data, so do not write any fwrite(rgbiColors, 1, 16 * 3, fp); // write uncompressed fwrite(data, 1, 320 * 200, fp); fclose(fp); } void VgaGfx::saveAsTgaImage(const char* filename) { convertToTga(screen, filename); }
24.283784
111
0.627713
[ "vector" ]
90f4de6600e676fc5f55f71f972df6684cb3afae
8,406
cpp
C++
FECore/FEConstValueVec3.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
59
2020-06-15T12:38:49.000Z
2022-03-29T19:14:47.000Z
FECore/FEConstValueVec3.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
36
2020-06-14T21:10:01.000Z
2022-03-12T12:03:14.000Z
FECore/FEConstValueVec3.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
26
2020-06-25T15:02:13.000Z
2022-03-10T09:14:03.000Z
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FEConstValueVec3.h" #include "FEMaterialPoint.h" #include "FEMeshPartition.h" #include "FENode.h" #include "quatd.h" //================================================================================== BEGIN_FECORE_CLASS(FEConstValueVec3, FEVec3dValuator) ADD_PARAMETER(m_val, "vector"); END_FECORE_CLASS(); FEConstValueVec3::FEConstValueVec3(FEModel* fem) : FEVec3dValuator(fem) {} FEVec3dValuator* FEConstValueVec3::copy() { FEConstValueVec3* val = new FEConstValueVec3(GetFEModel()); val->m_val = m_val; return val; } //================================================================================== BEGIN_FECORE_CLASS(FEMathValueVec3, FEVec3dValuator) ADD_PARAMETER(m_expr, "math"); END_FECORE_CLASS(); FEMathValueVec3::FEMathValueVec3(FEModel* fem) : FEVec3dValuator(fem) { } //--------------------------------------------------------------------------------------- bool FEMathValueVec3::Init() { size_t c1 = m_expr.find(',', 0); if (c1 == string::npos) return false; size_t c2 = m_expr.find(',', c1 + 1); if (c2 == string::npos) return false; string sx = m_expr.substr(0, c1); string sy = m_expr.substr(c1 + 1, c2 - c1); string sz = m_expr.substr(c2 + 1, string::npos); return create(sx, sy, sz); } //--------------------------------------------------------------------------------------- bool FEMathValueVec3::create(const std::string& sx, const std::string& sy, const std::string& sz) { for (int i = 0; i < 3; ++i) { m_math[i].AddVariable("X"); m_math[i].AddVariable("Y"); m_math[i].AddVariable("Z"); } bool b; b = m_math[0].Create(sx); assert(b); b = m_math[1].Create(sy); assert(b); b = m_math[2].Create(sz); assert(b); return true; } vec3d FEMathValueVec3::operator()(const FEMaterialPoint& pt) { std::vector<double> var(3); var[0] = pt.m_r0.x; var[1] = pt.m_r0.y; var[2] = pt.m_r0.z; double vx = m_math[0].value_s(var); double vy = m_math[1].value_s(var); double vz = m_math[2].value_s(var); return vec3d(vx, vy, vz); } //--------------------------------------------------------------------------------------- FEVec3dValuator* FEMathValueVec3::copy() { FEMathValueVec3* newVal = new FEMathValueVec3(GetFEModel()); newVal->m_math[0] = m_math[0]; newVal->m_math[1] = m_math[1]; newVal->m_math[2] = m_math[2]; return newVal; } //--------------------------------------------------------------------------------------- FEMappedValueVec3::FEMappedValueVec3(FEModel* fem) : FEVec3dValuator(fem) { m_val = nullptr; } void FEMappedValueVec3::setDataMap(FEDataMap* val, vec3d scl) { m_val = val; } vec3d FEMappedValueVec3::operator()(const FEMaterialPoint& pt) { vec3d r = m_val->valueVec3d(pt); return vec3d(r.x, r.y, r.z); } FEVec3dValuator* FEMappedValueVec3::copy() { FEMappedValueVec3* map = new FEMappedValueVec3(GetFEModel()); map->m_val = m_val; return map; } void FEMappedValueVec3::Serialize(DumpStream& ar) { FEVec3dValuator::Serialize(ar); if (ar.IsShallow()) return; ar & m_val; } //================================================================================================= BEGIN_FECORE_CLASS(FELocalVectorGenerator, FEVec3dValuator) ADD_PARAMETER(m_n, 2, "local"); END_FECORE_CLASS(); FELocalVectorGenerator::FELocalVectorGenerator(FEModel* fem) : FEVec3dValuator(fem) { m_n[0] = m_n[1] = 0; } bool FELocalVectorGenerator::Init() { if ((m_n[0] <= 0) && (m_n[1] <= 0)) { m_n[0] = 1; m_n[1] = 2; } if ((m_n[0] <= 0) || (m_n[1] <= 0)) return false; return FEVec3dValuator::Init(); } vec3d FELocalVectorGenerator::operator () (const FEMaterialPoint& mp) { FEElement* el = mp.m_elem; assert(el); FEMeshPartition* dom = el->GetMeshPartition(); vec3d r0 = dom->Node(el->m_lnode[m_n[0]-1]).m_r0; vec3d r1 = dom->Node(el->m_lnode[m_n[1]-1]).m_r0; vec3d n = r1 - r0; n.unit(); return n; } FEVec3dValuator* FELocalVectorGenerator::copy() { FELocalVectorGenerator* map = new FELocalVectorGenerator(GetFEModel()); map->m_n[0] = m_n[0]; map->m_n[1] = m_n[1]; return map; } //================================================================================================= BEGIN_FECORE_CLASS(FESphericalVectorGenerator, FEVec3dValuator) ADD_PARAMETER(m_center, "center"); ADD_PARAMETER(m_vector, "vector"); END_FECORE_CLASS(); FESphericalVectorGenerator::FESphericalVectorGenerator(FEModel* fem) : FEVec3dValuator(fem) { m_center = vec3d(0, 0, 0); m_vector = vec3d(1, 0, 0); } bool FESphericalVectorGenerator::Init() { // Make sure the vector is a unit vector m_vector.unit(); return true; } FEVec3dValuator* FESphericalVectorGenerator::copy() { FESphericalVectorGenerator* map = new FESphericalVectorGenerator(GetFEModel()); map->m_center = m_center; map->m_vector = m_vector; return map; } vec3d FESphericalVectorGenerator::operator () (const FEMaterialPoint& mp) { vec3d a = mp.m_r0 - m_center; a.unit(); // setup the rotation vec3d e1(1, 0, 0); quatd q(e1, a); vec3d v = m_vector; // v.unit(); q.RotateVector(v); return v; } //================================================================================================= BEGIN_FECORE_CLASS(FECylindricalVectorGenerator, FEVec3dValuator) ADD_PARAMETER(m_center, "center"); ADD_PARAMETER(m_axis, "axis") ADD_PARAMETER(m_vector, "vector"); END_FECORE_CLASS(); FECylindricalVectorGenerator::FECylindricalVectorGenerator(FEModel* fem) : FEVec3dValuator(fem) { m_center = vec3d(0, 0, 0); m_axis = vec3d(0, 0, 1); m_vector = vec3d(1, 0, 0); } bool FECylindricalVectorGenerator::Init() { // Make sure the axis and vector are unit vectors m_axis.unit(); m_vector.unit(); return true; } vec3d FECylindricalVectorGenerator::operator () (const FEMaterialPoint& mp) { vec3d p = mp.m_r0 - m_center; // find the vector to the axis vec3d b = p - m_axis * (m_axis*p); b.unit(); // setup the rotation vec3d e1(1, 0, 0); quatd q(e1, b); vec3d r = m_vector; // r.unit(); q.RotateVector(r); return r; } FEVec3dValuator* FECylindricalVectorGenerator::copy() { FECylindricalVectorGenerator* map = new FECylindricalVectorGenerator(GetFEModel()); map->m_center = m_center; map->m_axis = m_axis; map->m_vector = m_vector; return map; } //================================================================================================= BEGIN_FECORE_CLASS(FESphericalAnglesVectorGenerator, FEVec3dValuator) ADD_PARAMETER(m_theta, "theta"); ADD_PARAMETER(m_phi, "phi"); END_FECORE_CLASS(); FESphericalAnglesVectorGenerator::FESphericalAnglesVectorGenerator(FEModel* fem) : FEVec3dValuator(fem) { // equal to x-axis (1,0,0) m_theta = 0.0; m_phi = 90.0; } vec3d FESphericalAnglesVectorGenerator::operator () (const FEMaterialPoint& mp) { // convert from degress to radians const double the = m_theta(mp)* PI / 180.; const double phi = m_phi(mp)* PI / 180.; // the fiber vector vec3d a; a.x = cos(the)*sin(phi); a.y = sin(the)*sin(phi); a.z = cos(phi); return a; } FEVec3dValuator* FESphericalAnglesVectorGenerator::copy() { FESphericalAnglesVectorGenerator* v = fecore_alloc(FESphericalAnglesVectorGenerator, GetFEModel()); v->m_theta = m_theta; v->m_phi = m_phi; return v; }
26.942308
103
0.644064
[ "vector" ]
90f9f130fd2c6c078c3ba8df1e7c96ea5d46e38b
7,836
cpp
C++
fbpcs/data_processing/sharding/test/HashBasedSharderTest.cpp
rohantiru/fbpcs
5685b54fd4641145b61118dcf3f2f80637c8c7e2
[ "MIT" ]
null
null
null
fbpcs/data_processing/sharding/test/HashBasedSharderTest.cpp
rohantiru/fbpcs
5685b54fd4641145b61118dcf3f2f80637c8c7e2
[ "MIT" ]
null
null
null
fbpcs/data_processing/sharding/test/HashBasedSharderTest.cpp
rohantiru/fbpcs
5685b54fd4641145b61118dcf3f2f80637c8c7e2
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <string> #include <vector> #include <gtest/gtest.h> #include <folly/Random.h> #include "fbpcs/data_processing/sharding/HashBasedSharder.h" #include "fbpcs/data_processing/test_utils/FileIOTestUtils.h" namespace data_processing::sharder { TEST(HashBasedSharderTest, TestToBytes) { std::string key = "abcd"; std::vector<unsigned char> expected{ static_cast<unsigned char>('a'), static_cast<unsigned char>('b'), static_cast<unsigned char>('c'), static_cast<unsigned char>('d')}; EXPECT_EQ(detail::toBytes(key), expected); } TEST(HashBasedSharderTest, TestBytesToIntSimple) { // First a very simple test (but still important for endianness correctness!) std::vector<unsigned char> bytes{0, 0, 0, 1}; EXPECT_EQ(1, detail::bytesToInt(bytes)); // Assuming network byte order, big-endian 0x1 | 0x0 | 0x0 | 0x0 // is equivalent to integer 16777216 (2^24). In binary, we recognize this // number as 0b 0000 0001 0000 0000 0000 0000 0000 0000 std::vector<unsigned char> bytes2{1, 0, 0, 0}; EXPECT_EQ(1 << 24, detail::bytesToInt(bytes2)); } TEST(HashBasedSharderTest, TestBytesToIntAdvanced) { // Don't throw std::out_of_range if bytes is empty std::vector<unsigned char> bytes{}; EXPECT_EQ(0, detail::bytesToInt(bytes)); // If bytes are missing, we still copy the bytes array from the "start" so // this is equivalent to the test in TestBytesToIntSimple. In other words, // this is like copying [0b 0000 0001 0000 0000 [implicit 0000 0000 0000 0000] // Hopefully this is clear -- the lower two bytes were never "overridden" so // they still contain zero. std::vector<unsigned char> bytes2{1, 0}; EXPECT_EQ(1 << 24, detail::bytesToInt(bytes2)); } TEST(HashBasedSharderTest, TestGetShardFor) { // Assuming toBytes and bytesToInt have been tested elsewhere, this is a // straightforward modulo operation. HashBasedSharder sharder{"unused", {/* unused */}, 123, ""}; std::string key = "abcd"; auto integerValue = detail::bytesToInt(detail::toBytes(key)); EXPECT_EQ(sharder.getShardFor(key, 123), integerValue % 123); // Anything % 1 should be zero EXPECT_EQ(sharder.getShardFor(key, 1), 0); } TEST(HashBasedSharderTest, TestShardLineNoHmacKey) { std::string line = "abcd,1,2,3"; std::vector<std::unique_ptr<std::ofstream>> streams; auto randStart = folly::Random::secureRand64(); std::vector<std::string> outputPaths{ "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart), "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart + 1), }; streams.push_back(std::make_unique<std::ofstream>(outputPaths.at(0))); streams.push_back(std::make_unique<std::ofstream>(outputPaths.at(1))); HashBasedSharder sharder{"unused", outputPaths, 123, ""}; sharder.shardLine(line, streams); // We can just reset the underlying unique_ptr to flush the writes to disk streams.at(0).reset(); streams.at(1).reset(); // We didn't write headers, so we expect to *just* have the written line std::vector<std::string> expected0{"abcd,1,2,3"}; std::vector<std::string> expected1{}; data_processing::test_utils::expectFileRowsEqual(outputPaths.at(0), expected0); data_processing::test_utils::expectFileRowsEqual(outputPaths.at(1), expected1); } TEST(HashBasedSharderTest, TestShardLineWithHmacKey) { std::string line = "abcd,1,2,3"; std::vector<std::unique_ptr<std::ofstream>> streams; auto randStart = folly::Random::secureRand64(); std::vector<std::string> outputPaths{ "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart), "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart + 1), }; streams.push_back(std::make_unique<std::ofstream>(outputPaths.at(0))); streams.push_back(std::make_unique<std::ofstream>(outputPaths.at(1))); std::string hmacKey = "abcd1234"; HashBasedSharder sharder{"unused", outputPaths, 123, hmacKey}; sharder.shardLine(line, streams); // We can just reset the underlying unique_ptr to flush the writes to disk streams.at(0).reset(); streams.at(1).reset(); // We didn't write headers, so we expect to *just* have the written line std::vector<std::string> expected0{}; std::vector<std::string> expected1{"9BX9ClsYtFj3L8N023K3mJnw1vemIGqenY5vfAY0/cg=,1,2,3"}; data_processing::test_utils::expectFileRowsEqual(outputPaths.at(0), expected0); data_processing::test_utils::expectFileRowsEqual(outputPaths.at(1), expected1); } TEST(HashBasedSharderTest, TestShardNoHmacKey) { std::vector<std::string> rows{ "id_,a,b,c", "abcd,1,2,3", "abcd,4,5,6", "defg,7,8,9", "hijk,0,0,0", }; std::string inputPath = "/tmp/HashBasedSharderTestShardInput" + std::to_string(folly::Random::secureRand64()); data_processing::test_utils::writeVecToFile(rows, inputPath); // TODO: Would be great to mock out inputstream/outputstream stuff auto randStart = folly::Random::secureRand64(); std::vector<std::string> outputPaths{ "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart), "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart + 1), }; HashBasedSharder sharder{inputPath, outputPaths, 123, ""}; sharder.shard(); std::vector<std::string> expected0{ "id_,a,b,c", "abcd,1,2,3", "abcd,4,5,6", }; std::vector<std::string> expected1{ "id_,a,b,c", "defg,7,8,9", "hijk,0,0,0", }; data_processing::test_utils::expectFileRowsEqual(outputPaths.at(0), expected0); data_processing::test_utils::expectFileRowsEqual(outputPaths.at(1), expected1); } TEST(HashBasedSharderTest, TestShardWithHmacKey) { std::vector<std::string> rows{ "id_,a,b,c", "abcd,1,2,3", "abcd,4,5,6", "defg,7,8,9", "hijk,0,0,0", }; std::string hmacKey = "abcd1234"; std::string inputPath = "/tmp/HashBasedSharderTestShardInput" + std::to_string(folly::Random::secureRand64()); data_processing::test_utils::writeVecToFile(rows, inputPath); // TODO: Would be great to mock out inputstream/outputstream stuff auto randStart = folly::Random::secureRand64(); std::vector<std::string> outputPaths{ "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart), "/tmp/HashBasedSharderTestShardOutput" + std::to_string(randStart + 1), }; HashBasedSharder sharder{inputPath, outputPaths, 123, hmacKey}; sharder.shard(); // HMAC was applied offline, which is how we got these expected lines // HMAC_SHA256(CAST(id AS VARBINARY), FROM_BASE64(hmacKey)) in Presto is a // good way to generate more of these given our I/O specification. std::vector<std::string> expected0{ "id_,a,b,c", "bSRNJ92+ML97JRfp1lEvqssXNCX+lI2T/HQtHRTkBk4=,7,8,9", // defg line "ZGCVov/c63+N2Swslf6pY6pWsNzS1IkXKVi+lmAD6yU=,0,0,0", // hijk line }; std::vector<std::string> expected1{ "id_,a,b,c", "9BX9ClsYtFj3L8N023K3mJnw1vemIGqenY5vfAY0/cg=,1,2,3", // first abcd line "9BX9ClsYtFj3L8N023K3mJnw1vemIGqenY5vfAY0/cg=,4,5,6", // second abcd line }; data_processing::test_utils::expectFileRowsEqual(outputPaths.at(0), expected0); data_processing::test_utils::expectFileRowsEqual(outputPaths.at(1), expected1); } } // namespace data_processing::sharder
40.601036
91
0.674706
[ "vector" ]
90ff25d392edaf74a07bac4b699d2c4f0d6b32f2
20,379
cpp
C++
Engine/Source/Runtime/Windows/D3D11RHI/Private/D3D11Viewport.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Windows/D3D11RHI/Private/D3D11Viewport.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Windows/D3D11RHI/Private/D3D11Viewport.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= D3D11Viewport.cpp: D3D viewport RHI implementation. =============================================================================*/ #include "D3D11RHIPrivate.h" #include "RenderCore.h" #ifndef D3D11_WITH_DWMAPI #if WINVER > 0x502 // Windows XP doesn't support DWM #define D3D11_WITH_DWMAPI 1 #else #define D3D11_WITH_DWMAPI 0 #endif #endif #if D3D11_WITH_DWMAPI #include "AllowWindowsPlatformTypes.h" #include <dwmapi.h> #endif //D3D11_WITH_DWMAPI /** * RHI console variables used by viewports. */ namespace RHIConsoleVariables { int32 bSyncWithDWM = 0; static FAutoConsoleVariableRef CVarSyncWithDWM( TEXT("RHI.SyncWithDWM"), bSyncWithDWM, TEXT("If true, synchronize with the desktop window manager for vblank."), ECVF_RenderThreadSafe ); float RefreshPercentageBeforePresent = 1.0f; static FAutoConsoleVariableRef CVarRefreshPercentageBeforePresent( TEXT("RHI.RefreshPercentageBeforePresent"), RefreshPercentageBeforePresent, TEXT("The percentage of the refresh period to wait before presenting."), ECVF_RenderThreadSafe ); int32 TargetRefreshRate = 0; static FAutoConsoleVariableRef CVarTargetRefreshRate( TEXT("RHI.TargetRefreshRate"), TargetRefreshRate, TEXT("If non-zero, the display will never update more often than the target refresh rate (in Hz)."), ECVF_RenderThreadSafe ); int32 SyncInterval = 1; static FAutoConsoleVariableRef CVarSyncInterval( TEXT("RHI.SyncInterval"), SyncInterval, TEXT("When synchronizing with D3D, specifies the interval at which to refresh."), ECVF_RenderThreadSafe ); float SyncRefreshThreshold = 1.05f; static FAutoConsoleVariableRef CVarSyncRefreshThreshold( TEXT("RHI.SyncRefreshThreshold"), SyncRefreshThreshold, TEXT("Threshold for time above which vsync will be disabled as a percentage of the refresh rate."), ECVF_RenderThreadSafe ); int32 MaxSyncCounter = 8; static FAutoConsoleVariableRef CVarMaxSyncCounter( TEXT("RHI.MaxSyncCounter"), MaxSyncCounter, TEXT("Maximum sync counter to smooth out vsync transitions."), ECVF_RenderThreadSafe ); int32 SyncThreshold = 7; static FAutoConsoleVariableRef CVarSyncThreshold( TEXT("RHI.SyncThreshold"), SyncThreshold, TEXT("Number of consecutive 'fast' frames before vsync is enabled."), ECVF_RenderThreadSafe ); int32 MaximumFrameLatency = 3; static FAutoConsoleVariableRef CVarMaximumFrameLatency( TEXT("RHI.MaximumFrameLatency"), MaximumFrameLatency, TEXT("Number of frames that can be queued for render."), ECVF_RenderThreadSafe ); }; extern void D3D11TextureAllocated2D( FD3D11Texture2D& Texture ); /** * Creates a FD3D11Surface to represent a swap chain's back buffer. */ FD3D11Texture2D* GetSwapChainSurface(FD3D11DynamicRHI* D3DRHI, EPixelFormat PixelFormat, IDXGISwapChain* SwapChain) { // Grab the back buffer TRefCountPtr<ID3D11Texture2D> BackBufferResource; VERIFYD3D11RESULT_EX(SwapChain->GetBuffer(0,IID_ID3D11Texture2D,(void**)BackBufferResource.GetInitReference()), D3DRHI->GetDevice()); // create the render target view TRefCountPtr<ID3D11RenderTargetView> BackBufferRenderTargetView; D3D11_RENDER_TARGET_VIEW_DESC RTVDesc; RTVDesc.Format = DXGI_FORMAT_UNKNOWN; RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; RTVDesc.Texture2D.MipSlice = 0; VERIFYD3D11RESULT_EX(D3DRHI->GetDevice()->CreateRenderTargetView(BackBufferResource,&RTVDesc,BackBufferRenderTargetView.GetInitReference()), D3DRHI->GetDevice()); D3D11_TEXTURE2D_DESC TextureDesc; BackBufferResource->GetDesc(&TextureDesc); TArray<TRefCountPtr<ID3D11RenderTargetView> > RenderTargetViews; RenderTargetViews.Add(BackBufferRenderTargetView); // create a shader resource view to allow using the backbuffer as a texture TRefCountPtr<ID3D11ShaderResourceView> BackBufferShaderResourceView; D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; SRVDesc.Format = DXGI_FORMAT_UNKNOWN; SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MostDetailedMip = 0; SRVDesc.Texture2D.MipLevels = 1; VERIFYD3D11RESULT_EX(D3DRHI->GetDevice()->CreateShaderResourceView(BackBufferResource,&SRVDesc,BackBufferShaderResourceView.GetInitReference()), D3DRHI->GetDevice()); FD3D11Texture2D* NewTexture = new FD3D11Texture2D( D3DRHI, BackBufferResource, BackBufferShaderResourceView, false, 1, RenderTargetViews, NULL, TextureDesc.Width, TextureDesc.Height, 1, 1, 1, PixelFormat, false, false, false, FClearValueBinding() ); D3D11TextureAllocated2D(*NewTexture); NewTexture->DoNoDeferDelete(); return NewTexture; } FD3D11Viewport::~FD3D11Viewport() { check(IsInRenderingThread()); // Turn off HDR display mode D3DRHI->ShutdownHDR(); // If the swap chain was in fullscreen mode, switch back to windowed before releasing the swap chain. // DXGI throws an error otherwise. VERIFYD3D11RESULT_EX(SwapChain->SetFullscreenState(false,NULL), D3DRHI->GetDevice()); FrameSyncEvent.ReleaseResource(); D3DRHI->Viewports.Remove(this); } DXGI_MODE_DESC FD3D11Viewport::SetupDXGI_MODE_DESC() const { DXGI_MODE_DESC Ret; Ret.Width = SizeX; Ret.Height = SizeY; Ret.RefreshRate.Numerator = 0; // illamas: use 0 to avoid a potential mismatch with hw Ret.RefreshRate.Denominator = 0; // illamas: ditto Ret.Format = GetRenderTargetFormat(PixelFormat); Ret.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; Ret.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; return Ret; } void FD3D11Viewport::Resize(uint32 InSizeX, uint32 InSizeY, bool bInIsFullscreen, EPixelFormat PreferredPixelFormat) { // Unbind any dangling references to resources D3DRHI->RHISetRenderTargets(0, nullptr, nullptr, 0, nullptr); D3DRHI->ClearState(); D3DRHI->GetDeviceContext()->Flush(); // Potential perf hit if (IsValidRef(CustomPresent)) { CustomPresent->OnBackBufferResize(); } // Release our backbuffer reference, as required by DXGI before calling ResizeBuffers. if (IsValidRef(BackBuffer)) { check(BackBuffer->GetRefCount() == 1); checkComRefCount(BackBuffer->GetResource(),1); checkComRefCount(BackBuffer->GetRenderTargetView(0, -1),1); checkComRefCount(BackBuffer->GetShaderResourceView(),1); } BackBuffer.SafeRelease(); if(SizeX != InSizeX || SizeY != InSizeY || PixelFormat != PreferredPixelFormat) { SizeX = InSizeX; SizeY = InSizeY; PixelFormat = PreferredPixelFormat; check(SizeX > 0); check(SizeY > 0); // Resize the swap chain. DXGI_FORMAT RenderTargetFormat = GetRenderTargetFormat(PixelFormat); VERIFYD3D11RESIZEVIEWPORTRESULT(SwapChain->ResizeBuffers(1,SizeX,SizeY,RenderTargetFormat,DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH),SizeX,SizeY,RenderTargetFormat, D3DRHI->GetDevice()); if(bInIsFullscreen) { DXGI_MODE_DESC BufferDesc = SetupDXGI_MODE_DESC(); if (FAILED(SwapChain->ResizeTarget(&BufferDesc))) { ConditionalResetSwapChain(true); } } } if(bIsFullscreen != bInIsFullscreen) { bIsFullscreen = bInIsFullscreen; bIsValid = false; // Use ConditionalResetSwapChain to call SetFullscreenState, to handle the failure case. // Ignore the viewport's focus state; since Resize is called as the result of a user action we assume authority without waiting for Focus. ConditionalResetSwapChain(true); } // Float RGBA backbuffers are requested whenever HDR mode is desired if (PixelFormat == GRHIHDRDisplayOutputFormat && bIsFullscreen) { D3DRHI->EnableHDR(); } else { D3DRHI->ShutdownHDR(); } // Create a RHI surface to represent the viewport's back buffer. BackBuffer = GetSwapChainSurface(D3DRHI, PixelFormat, SwapChain); } /** Returns true if desktop composition is enabled. */ static bool IsCompositionEnabled() { BOOL bDwmEnabled = false; #if D3D11_WITH_DWMAPI DwmIsCompositionEnabled(&bDwmEnabled); #endif //D3D11_WITH_DWMAPI return !!bDwmEnabled; } /** Presents the swap chain checking the return result. */ bool FD3D11Viewport::PresentChecked(int32 SyncInterval) { HRESULT Result = S_OK; bool bNeedNativePresent = true; if (IsValidRef(CustomPresent)) { bNeedNativePresent = CustomPresent->Present(SyncInterval); } if (bNeedNativePresent) { // Present the back buffer to the viewport window. Result = SwapChain->Present(SyncInterval, 0); if (IsValidRef(CustomPresent)) { CustomPresent->PostPresent(); } } VERIFYD3D11RESULT_EX(Result, D3DRHI->GetDevice()); return bNeedNativePresent; } /** Blocks the CPU to synchronize with vblank by communicating with DWM. */ void FD3D11Viewport::PresentWithVsyncDWM() { #if D3D11_WITH_DWMAPI LARGE_INTEGER Cycles; DWM_TIMING_INFO TimingInfo; // Find out how long since we last flipped and query DWM for timing information. QueryPerformanceCounter(&Cycles); FMemory::Memzero(TimingInfo); TimingInfo.cbSize = sizeof(DWM_TIMING_INFO); // Starting at windows 8.1 null must be passed into this method for it to work. null also works on previous versions DwmGetCompositionTimingInfo(nullptr, &TimingInfo); uint64 QpcAtFlip = Cycles.QuadPart; uint64 CyclesSinceLastFlip = Cycles.QuadPart - LastFlipTime; float CPUTime = FPlatformTime::ToMilliseconds(CyclesSinceLastFlip); float GPUTime = FPlatformTime::ToMilliseconds(TimingInfo.qpcFrameComplete - LastCompleteTime); float DisplayRefreshPeriod = FPlatformTime::ToMilliseconds(TimingInfo.qpcRefreshPeriod); // Find the smallest multiple of the refresh rate that is >= 33ms, our target frame rate. float RefreshPeriod = DisplayRefreshPeriod; if(RHIConsoleVariables::TargetRefreshRate > 0 && RefreshPeriod > 1.0f) { while(RefreshPeriod - (1000.0f / RHIConsoleVariables::TargetRefreshRate) < -1.0f) { RefreshPeriod *= 2.0f; } } // If the last frame hasn't completed yet, we don't know how long the GPU took. bool bValidGPUTime = (TimingInfo.cFrameComplete > LastFrameComplete); if (bValidGPUTime) { GPUTime /= (float)(TimingInfo.cFrameComplete - LastFrameComplete); } // Update the sync counter depending on how much time it took to complete the previous frame. float FrameTime = FMath::Max<float>(CPUTime, GPUTime); if (FrameTime >= RHIConsoleVariables::SyncRefreshThreshold * RefreshPeriod) { SyncCounter--; } else if (bValidGPUTime) { SyncCounter++; } SyncCounter = FMath::Clamp<int32>(SyncCounter, 0, RHIConsoleVariables::MaxSyncCounter); // If frames are being completed quickly enough, block for vsync. bool bSync = (SyncCounter >= RHIConsoleVariables::SyncThreshold); if (bSync) { // This flushes the previous present call and blocks until it is made available to DWM. D3DRHI->GetDeviceContext()->Flush(); DwmFlush(); // We sleep a percentage of the remaining time. The trick is to get the // present call in after the vblank we just synced for but with time to // spare for the next vblank. float MinFrameTime = RefreshPeriod * RHIConsoleVariables::RefreshPercentageBeforePresent; float TimeToSleep; do { QueryPerformanceCounter(&Cycles); float TimeSinceFlip = FPlatformTime::ToMilliseconds(Cycles.QuadPart - LastFlipTime); TimeToSleep = (MinFrameTime - TimeSinceFlip); if (TimeToSleep > 0.0f) { FPlatformProcess::Sleep(TimeToSleep * 0.001f); } } while (TimeToSleep > 0.0f); } // Present. PresentChecked(/*SyncInterval=*/ 0); // If we are forcing <= 30Hz, block the CPU an additional amount of time if needed. // This second block is only needed when RefreshPercentageBeforePresent < 1.0. if (bSync) { LARGE_INTEGER LocalCycles; float TimeToSleep; bool bSaveCycles = false; do { QueryPerformanceCounter(&LocalCycles); float TimeSinceFlip = FPlatformTime::ToMilliseconds(LocalCycles.QuadPart - LastFlipTime); TimeToSleep = (RefreshPeriod - TimeSinceFlip); if (TimeToSleep > 0.0f) { bSaveCycles = true; FPlatformProcess::Sleep(TimeToSleep * 0.001f); } } while (TimeToSleep > 0.0f); if (bSaveCycles) { Cycles = LocalCycles; } } // If we are dropping vsync reset the counter. This provides a debounce time // before which we try to vsync again. if (!bSync && bSyncedLastFrame) { SyncCounter = 0; } if (bSync != bSyncedLastFrame || UE_LOG_ACTIVE(LogRHI,VeryVerbose)) { UE_LOG(LogRHI,Verbose,TEXT("BlockForVsync[%d]: CPUTime:%.2fms GPUTime[%d]:%.2fms Blocked:%.2fms Pending/Complete:%d/%d"), bSync, CPUTime, bValidGPUTime, GPUTime, FPlatformTime::ToMilliseconds(Cycles.QuadPart - QpcAtFlip), TimingInfo.cFramePending, TimingInfo.cFrameComplete); } // Remember if we synced, when the frame completed, etc. bSyncedLastFrame = bSync; LastFlipTime = Cycles.QuadPart; LastFrameComplete = TimingInfo.cFrameComplete; LastCompleteTime = TimingInfo.qpcFrameComplete; #endif //D3D11_WITH_DWMAPI } bool FD3D11Viewport::Present(bool bLockToVsync) { bool bNativelyPresented = true; #if D3D11_WITH_DWMAPI // We can't call Present if !bIsValid, as it waits a window message to be processed, but the main thread may not be pumping the message handler. if(bIsValid) { // Check if the viewport's swap chain has been invalidated by DXGI. BOOL bSwapChainFullscreenState; TRefCountPtr<IDXGIOutput> SwapChainOutput; VERIFYD3D11RESULT_EX(SwapChain->GetFullscreenState(&bSwapChainFullscreenState,SwapChainOutput.GetInitReference()), D3DRHI->GetDevice()); // Can't compare BOOL with bool... if ( (!!bSwapChainFullscreenState) != bIsFullscreen ) { bIsValid = false; // Minimize the window. // use SW_FORCEMINIMIZE if the messaging thread is likely to be blocked for a sizeable period. // SW_FORCEMINIMIZE also prevents the minimize animation from playing. ::ShowWindow(WindowHandle,SW_MINIMIZE); } } if (MaximumFrameLatency != RHIConsoleVariables::MaximumFrameLatency) { MaximumFrameLatency = RHIConsoleVariables::MaximumFrameLatency; TRefCountPtr<IDXGIDevice1> DXGIDevice; VERIFYD3D11RESULT_EX(D3DRHI->GetDevice()->QueryInterface(IID_IDXGIDevice, (void**)DXGIDevice.GetInitReference()), D3DRHI->GetDevice()); DXGIDevice->SetMaximumFrameLatency(MaximumFrameLatency); } // When desktop composition is enabled, locking to vsync via the Present // call is unreliable. Instead, communicate with the desktop window manager // directly to enable vsync. const bool bSyncWithDWM = bLockToVsync && !bIsFullscreen && RHIConsoleVariables::bSyncWithDWM && IsCompositionEnabled(); if (bSyncWithDWM) { PresentWithVsyncDWM(); } else #endif //D3D11_WITH_DWMAPI { // Present the back buffer to the viewport window. bNativelyPresented = PresentChecked(bLockToVsync ? RHIConsoleVariables::SyncInterval : 0); } return bNativelyPresented; } /*============================================================================= * The following RHI functions must be called from the main thread. *=============================================================================*/ FViewportRHIRef FD3D11DynamicRHI::RHICreateViewport(void* WindowHandle,uint32 SizeX,uint32 SizeY,bool bIsFullscreen,EPixelFormat PreferredPixelFormat) { check( IsInGameThread() ); // Use a default pixel format if none was specified if (PreferredPixelFormat == EPixelFormat::PF_Unknown) { PreferredPixelFormat = EPixelFormat::PF_A2B10G10R10; } return new FD3D11Viewport(this,(HWND)WindowHandle,SizeX,SizeY,bIsFullscreen,PreferredPixelFormat); } void FD3D11DynamicRHI::RHIResizeViewport(FViewportRHIParamRef ViewportRHI,uint32 SizeX,uint32 SizeY,bool bIsFullscreen) { FD3D11Viewport* Viewport = ResourceCast(ViewportRHI); check( IsInGameThread() ); Viewport->Resize(SizeX,SizeY,bIsFullscreen, PF_Unknown); } void FD3D11DynamicRHI::RHIResizeViewport(FViewportRHIParamRef ViewportRHI, uint32 SizeX, uint32 SizeY, bool bIsFullscreen, EPixelFormat PreferredPixelFormat) { FD3D11Viewport* Viewport = ResourceCast(ViewportRHI); check(IsInGameThread()); // Use a default pixel format if none was specified if (PreferredPixelFormat == EPixelFormat::PF_Unknown) { PreferredPixelFormat = EPixelFormat::PF_A2B10G10R10; } Viewport->Resize(SizeX, SizeY, bIsFullscreen, PreferredPixelFormat); } void FD3D11DynamicRHI::RHITick( float DeltaTime ) { check( IsInGameThread() ); // Check if any swap chains have been invalidated. for(int32 ViewportIndex = 0; ViewportIndex < Viewports.Num(); ViewportIndex++) { Viewports[ViewportIndex]->ConditionalResetSwapChain(false); } } /*============================================================================= * Viewport functions. *=============================================================================*/ void FD3D11DynamicRHI::RHIBeginDrawingViewport(FViewportRHIParamRef ViewportRHI, FTextureRHIParamRef RenderTarget) { FD3D11Viewport* Viewport = ResourceCast(ViewportRHI); SCOPE_CYCLE_COUNTER(STAT_D3D11PresentTime); check(!DrawingViewport); DrawingViewport = Viewport; // Set the render target and viewport. if( RenderTarget == NULL ) { RenderTarget = Viewport->GetBackBuffer(); RHITransitionResources(EResourceTransitionAccess::EWritable, &RenderTarget, 1); } FRHIRenderTargetView View(RenderTarget, ERenderTargetLoadAction::ELoad); RHISetRenderTargets(1,&View,nullptr,0,NULL); // Set an initially disabled scissor rect. RHISetScissorRect(false,0,0,0,0); } void FD3D11DynamicRHI::RHIEndDrawingViewport(FViewportRHIParamRef ViewportRHI,bool bPresent,bool bLockToVsync) { ++PresentCounter; FD3D11Viewport* Viewport = ResourceCast(ViewportRHI); SCOPE_CYCLE_COUNTER(STAT_D3D11PresentTime); check(DrawingViewport.GetReference() == Viewport); DrawingViewport = NULL; // Clear references the device might have to resources. CurrentDepthTexture = NULL; CurrentDepthStencilTarget = NULL; CurrentDSVAccessType = FExclusiveDepthStencil::DepthWrite_StencilWrite; CurrentRenderTargets[0] = NULL; for(uint32 RenderTargetIndex = 1;RenderTargetIndex < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT;++RenderTargetIndex) { CurrentRenderTargets[RenderTargetIndex] = NULL; } ClearAllShaderResources(); CommitRenderTargetsAndUAVs(); StateCache.SetVertexShader(nullptr); uint16 NullStreamStrides[MaxVertexElementCount] = {0}; StateCache.SetStreamStrides(NullStreamStrides); for (uint32 StreamIndex = 0; StreamIndex < MaxVertexElementCount; ++StreamIndex) { StateCache.SetStreamSource(nullptr, StreamIndex, 0, 0); } StateCache.SetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0); StateCache.SetPixelShader(nullptr); StateCache.SetHullShader(nullptr); StateCache.SetDomainShader(nullptr); StateCache.SetGeometryShader(nullptr); // Compute Shader is set to NULL after each Dispatch call, so no need to clear it here bool bNativelyPresented = Viewport->Present(bLockToVsync); // Don't wait on the GPU when using SLI, let the driver determine how many frames behind the GPU should be allowed to get if (GNumActiveGPUsForRendering == 1) { if (bNativelyPresented) { static const auto CFinishFrameVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.FinishCurrentFrame")); if (!CFinishFrameVar->GetValueOnRenderThread()) { // Wait for the GPU to finish rendering the previous frame before finishing this frame. Viewport->WaitForFrameEventCompletion(); Viewport->IssueFrameEvent(); } else { // Finish current frame immediately to reduce latency Viewport->IssueFrameEvent(); Viewport->WaitForFrameEventCompletion(); } } // If the input latency timer has been triggered, block until the GPU is completely // finished displaying this frame and calculate the delta time. if ( GInputLatencyTimer.RenderThreadTrigger ) { Viewport->WaitForFrameEventCompletion(); uint32 EndTime = FPlatformTime::Cycles(); GInputLatencyTimer.DeltaTime = EndTime - GInputLatencyTimer.StartTime; GInputLatencyTimer.RenderThreadTrigger = false; } } #if CHECK_SRV_TRANSITIONS check(UnresolvedTargetsConcurrencyGuard.Increment() == 1); UnresolvedTargets.Reset(); check(UnresolvedTargetsConcurrencyGuard.Decrement() == 0); #endif } void FD3D11DynamicRHI::RHIAdvanceFrameForGetViewportBackBuffer(FViewportRHIParamRef Viewport) { } FTexture2DRHIRef FD3D11DynamicRHI::RHIGetViewportBackBuffer(FViewportRHIParamRef ViewportRHI) { FD3D11Viewport* Viewport = ResourceCast(ViewportRHI); return Viewport->GetBackBuffer(); } #if D3D11_WITH_DWMAPI #include "HideWindowsPlatformTypes.h" #endif //D3D11_WITH_DWMAPI
31.64441
185
0.754551
[ "render" ]