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
84d03ebec54798af2041612a80b4784d5ee3151a
5,052
cc
C++
be/src/runtime/hbase-table.cc
suifengzhuliu/impala
611f4c6f3b18cfcddff3b2956cbb87c295a87655
[ "Apache-2.0" ]
1,523
2015-01-01T03:42:24.000Z
2022-02-06T22:24:04.000Z
be/src/runtime/hbase-table.cc
suifengzhuliu/impala
611f4c6f3b18cfcddff3b2956cbb87c295a87655
[ "Apache-2.0" ]
10
2015-01-09T06:46:05.000Z
2022-03-29T21:57:57.000Z
be/src/runtime/hbase-table.cc
suifengzhuliu/impala
611f4c6f3b18cfcddff3b2956cbb87c295a87655
[ "Apache-2.0" ]
647
2015-01-02T04:01:40.000Z
2022-03-30T15:57:35.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "runtime/hbase-table.h" #include <string> #include "runtime/runtime-state.h" #include "util/jni-util.h" #include "common/names.h" namespace impala { jclass HBaseTable::table_cl_ = NULL; jmethodID HBaseTable::table_close_id_ = NULL; jmethodID HBaseTable::table_get_scanner_id_ = NULL; jmethodID HBaseTable::table_put_id_ = NULL; jclass HBaseTable::connection_cl_ = NULL; jmethodID HBaseTable::connection_get_table_id_ = NULL; jclass HBaseTable::table_name_cl_ = NULL; jmethodID HBaseTable::table_name_value_of_id_ = NULL; HBaseTable::HBaseTable(const string& table_name, jobject connection) : table_name_(table_name), connection_(connection), table_(NULL) { } HBaseTable::~HBaseTable() { DCHECK(table_ == NULL) << "Must call Close()"; } void HBaseTable::Close(RuntimeState* state) { // If this has already been closed then return out early. if (table_ == NULL) return; JNIEnv* env = getJNIEnv(); if (env == NULL) { state->LogError(ErrorMsg( TErrorCode::GENERAL, "HBaseTable::Close(): Error creating JNIEnv")); } else { env->CallObjectMethod(table_, table_close_id_); Status s = JniUtil::GetJniExceptionMsg(env, true, "HBaseTable::Close(): "); if (!s.ok()) state->LogError(s.msg()); env->DeleteGlobalRef(table_); } table_ = NULL; } Status HBaseTable::Init() { JNIEnv* env = getJNIEnv(); JniLocalFrame jni_frame; RETURN_IF_ERROR(jni_frame.push(env)); if (env == NULL) return Status("Error creating JNIEnv"); // Get a TableName object from the table name jstring jtable_name_string = env->NewStringUTF(table_name_.c_str()); RETURN_ERROR_IF_EXC(env); // Convert into a TableName object jobject jtable_name = env->CallStaticObjectMethod(table_name_cl_, table_name_value_of_id_, jtable_name_string); RETURN_ERROR_IF_EXC(env); // Get a Table from the Connection. jobject local_table = env->CallObjectMethod(connection_, connection_get_table_id_, jtable_name); RETURN_ERROR_IF_EXC(env); // Make sure the GC doesn't remove the Table until told to. All local refs // will be deleted when the JniLocalFrame goes out of scope. RETURN_IF_ERROR(JniUtil::LocalToGlobalRef(env, local_table, &table_)); return Status::OK(); } Status HBaseTable::InitJNI() { JNIEnv* env = getJNIEnv(); if (env == NULL) { return Status("Failed to get/create JVM"); } // TableName RETURN_IF_ERROR( JniUtil::GetGlobalClassRef(env, "org/apache/hadoop/hbase/TableName", &table_name_cl_)); table_name_value_of_id_ = env->GetStaticMethodID(table_name_cl_, "valueOf", "(Ljava/lang/String;)Lorg/apache/hadoop/hbase/TableName;"); RETURN_ERROR_IF_EXC(env); // Table RETURN_IF_ERROR( JniUtil::GetGlobalClassRef(env, "org/apache/hadoop/hbase/client/Table", &table_cl_)); table_close_id_ = env->GetMethodID(table_cl_, "close", "()V"); RETURN_ERROR_IF_EXC(env); table_get_scanner_id_ = env->GetMethodID(table_cl_, "getScanner", "(Lorg/apache/hadoop/hbase/client/Scan;)" "Lorg/apache/hadoop/hbase/client/ResultScanner;"); RETURN_ERROR_IF_EXC(env); table_put_id_ = env->GetMethodID(table_cl_, "put", "(Ljava/util/List;)V"); RETURN_ERROR_IF_EXC(env); // Connection RETURN_IF_ERROR( JniUtil::GetGlobalClassRef(env, "org/apache/hadoop/hbase/client/Connection", &connection_cl_)); connection_get_table_id_= env->GetMethodID(connection_cl_, "getTable", "(Lorg/apache/hadoop/hbase/TableName;)" "Lorg/apache/hadoop/hbase/client/Table;"); RETURN_ERROR_IF_EXC(env); return Status::OK(); } Status HBaseTable::GetResultScanner(const jobject& scan, jobject* result_scanner) { JNIEnv* env = getJNIEnv(); if (env == NULL) return Status("Error creating JNIEnv"); (*result_scanner) = env->CallObjectMethod(table_, table_get_scanner_id_, scan); RETURN_ERROR_IF_EXC(env); return Status::OK(); } Status HBaseTable::Put(const jobject& puts_list) { JNIEnv* env = getJNIEnv(); if (env == NULL) return Status("Error creating JNIEnv"); env->CallObjectMethod(table_, table_put_id_, puts_list); RETURN_ERROR_IF_EXC(env); // TODO(eclark): FlushCommits return Status::OK(); } } // namespace impala
31.378882
84
0.717933
[ "object" ]
84d571b1f65ee8b0dc3a85223349421a3a5f4bf8
5,975
cpp
C++
util/test/demos/d3d12/d3d12_simple_dispatch.cpp
BNieuwenhuizen/renderdoc
4ca0376420d471511f832b4385e96399eabbe803
[ "MIT" ]
20
2020-10-03T18:03:34.000Z
2021-01-15T02:53:29.000Z
util/test/demos/d3d12/d3d12_simple_dispatch.cpp
kevin-mccullough/renderdoc
89af50a76c1cf98f800a6ff8ece5c31f3ff5504c
[ "MIT" ]
null
null
null
util/test/demos/d3d12/d3d12_simple_dispatch.cpp
kevin-mccullough/renderdoc
89af50a76c1cf98f800a6ff8ece5c31f3ff5504c
[ "MIT" ]
5
2020-10-03T18:13:37.000Z
2021-01-15T02:53:35.000Z
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2020 Baldur Karlsson * * 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 "d3d12_test.h" RD_TEST(D3D12_Simple_Dispatch, D3D12GraphicsTest) { static constexpr const char *Description = "Test that just does a dispatch and some copies, for checking basic compute stuff"; std::string compute = R"EOSHADER( Texture2D<uint> texin : register(t0); RWTexture2D<uint> texout : register(u0); [numthreads(1,1,1)] void main() { texout[uint2(3,4)] = texin[uint2(4,3)]; texout[uint2(4,4)] = texin[uint2(3,3)]; texout[uint2(4,3)] = texin[uint2(3,4)]; texout[uint2(3,3)] = texin[uint2(4,4)]; texout[uint2(0,0)] = texin[uint2(0,0)] + 3; } )EOSHADER"; int main() { // initialise, create window, create device, etc if(!Init()) return 3; ID3DBlobPtr csblob = Compile(compute, "main", "cs_5_0"); ID3D12RootSignaturePtr sig = MakeSig({ tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0, 1, 0), tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 0, 1, 1), }); ID3D12PipelineStatePtr pso = MakePSO().RootSig(sig).CS(csblob); ID3D12ResourcePtr texin = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8) .InitialState(D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) .UAV(); ID3D12ResourcePtr texout = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8) .InitialState(D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) .UAV(); D3D12_TEXTURE_COPY_LOCATION dstLocation; dstLocation.pResource = texin; dstLocation.SubresourceIndex = 0; dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; MakeSRV(texin).CreateGPU(0); MakeUAV(texout).CreateGPU(1); D3D12_TEXTURE_COPY_LOCATION srcLocation; srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; D3D12_RESOURCE_DESC srcDesc = texin->GetDesc(); dev->GetCopyableFootprints(&srcDesc, 0, 1, 0, &srcLocation.PlacedFootprint, NULL, NULL, NULL); UINT dataSize = srcLocation.PlacedFootprint.Footprint.RowPitch * srcLocation.PlacedFootprint.Footprint.Height; std::vector<uint32_t> data; data.reserve(dataSize); for(size_t i = 0; i < dataSize; i++) { data.push_back(5 + rand() % 100); } ID3D12ResourcePtr copybuffer = MakeBuffer().Data(data).Upload(); srcLocation.pResource = copybuffer; D3D12_RESOURCE_BARRIER toDestState[2] = {}; toDestState[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; toDestState[0].Transition.pResource = texin; toDestState[0].Transition.Subresource = 0; toDestState[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; toDestState[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; toDestState[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; toDestState[1].Transition.pResource = texout; toDestState[1].Transition.Subresource = 0; toDestState[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; toDestState[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; D3D12_RESOURCE_BARRIER toUseState[2] = {}; toUseState[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; toUseState[0].Transition.pResource = texin; toUseState[0].Transition.Subresource = 0; toUseState[0].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; toUseState[0].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; toUseState[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; toUseState[1].Transition.pResource = texout; toUseState[1].Transition.Subresource = 0; toUseState[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; toUseState[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; while(Running()) { ID3D12GraphicsCommandListPtr cmd = GetCommandBuffer(); Reset(cmd); { cmd->ResourceBarrier(2, toDestState); cmd->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL); dstLocation.pResource = texout; cmd->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL); cmd->ResourceBarrier(2, toUseState); } cmd->SetComputeRootSignature(sig); cmd->SetPipelineState(pso); cmd->SetDescriptorHeaps(1, &m_CBVUAVSRV.GetInterfacePtr()); cmd->SetComputeRootDescriptorTable(0, m_CBVUAVSRV->GetGPUDescriptorHandleForHeapStart()); cmd->SetComputeRootDescriptorTable(1, m_CBVUAVSRV->GetGPUDescriptorHandleForHeapStart()); cmd->Dispatch(1, 1, 1); cmd->Close(); Submit({cmd}); Present(); } return 0; } }; REGISTER_TEST();
40.646259
98
0.697238
[ "vector" ]
84d7966cc15d55b16d68cf0b523858b67564fbb0
4,970
cpp
C++
geos-3.7.0beta1/src/algorithm/RobustDeterminant.cpp
litbangbungamayang/SIMTR
23435e829f6c766ec8483c88005daac654de4057
[ "MIT" ]
null
null
null
geos-3.7.0beta1/src/algorithm/RobustDeterminant.cpp
litbangbungamayang/SIMTR
23435e829f6c766ec8483c88005daac654de4057
[ "MIT" ]
null
null
null
geos-3.7.0beta1/src/algorithm/RobustDeterminant.cpp
litbangbungamayang/SIMTR
23435e829f6c766ec8483c88005daac654de4057
[ "MIT" ]
null
null
null
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (c) 1995 Olivier Devillers <Olivier.Devillers@sophia.inria.fr> * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * RobustDeterminant implements an algorithm to compute the * sign of a 2x2 determinant for double precision values robustly. * It is a direct translation of code developed by Olivier Devillers. * * The original code carries the following copyright notice: * * Author : Olivier Devillers * Olivier.Devillers@sophia.inria.fr * http://www-sop.inria.fr/prisme/logiciel/determinant.html * * Olivier Devillers has allowed the code to be distributed under * the LGPL (2012-02-16) saying "It is ok for LGPL distribution." * ************************************************************************** * * Last port: algorithm/RobustDeterminant.java 1.15 (JTS-1.10) * **********************************************************************/ #include <geos/algorithm/RobustDeterminant.h> #include <geos/util/IllegalArgumentException.h> #include <cmath> #include <geos/platform.h> // for ISNAN, FINITE #ifdef _MSC_VER #pragma warning(disable : 4127) #endif using namespace std; // for isfinite.. namespace geos { namespace algorithm { // geos.algorithm int RobustDeterminant::signOfDet2x2(double x1,double y1,double x2,double y2) { // returns -1 if the determinant is negative, // returns 1 if the determinant is positive, // retunrs 0 if the determinant is null. int sign=1; double swap; double k; // Protect against non-finite numbers if ( !FINITE(x1) || !FINITE(y1) || !FINITE(x2) || !FINITE(y2) ) { throw util::IllegalArgumentException("RobustDeterminant encountered non-finite numbers "); } /* * testing null entries */ if ((x1==0.0) || (y2==0.0)) { if ((y1==0.0) || (x2==0.0)) { return 0; } else if (y1>0) { if (x2>0) { return -sign; } else { return sign; } } else { if (x2>0) { return sign; } else { return -sign; } } } if ((y1==0.0) || (x2==0.0)) { if (y2>0) { if (x1>0) { return sign; } else { return -sign; } } else { if (x1>0) { return -sign; } else { return sign; } } } /* * making y coordinates positive and permuting the entries * so that y2 is the biggest one */ if (0.0<y1) { if (0.0<y2) { if (y1<=y2) { ; } else { sign=-sign; swap=x1; x1=x2; x2=swap; swap=y1; y1=y2; y2=swap; } } else { if (y1<=-y2) { sign=-sign; x2=-x2; y2=-y2; } else { swap=x1; x1=-x2; x2=swap; swap=y1; y1=-y2; y2=swap; } } } else { if (0.0<y2) { if (-y1<=y2) { sign=-sign; x1=-x1; y1=-y1; } else { swap=-x1; x1=x2; x2=swap; swap=-y1; y1=y2; y2=swap; } } else { if (y1>=y2) { x1=-x1; y1=-y1; x2=-x2; y2=-y2; } else { sign=-sign; swap=-x1; x1=-x2; x2=swap; swap=-y1; y1=-y2; y2=swap; } } } /* * making x coordinates positive */ /* * if |x2|<|x1| one can conclude */ if (0.0<x1) { if (0.0<x2) { if (x1 <= x2) { ; } else { return sign; } } else { return sign; } } else { if (0.0<x2) { return -sign; } else { if (x1 >= x2) { sign=-sign; x1=-x1; x2=-x2; } else { return -sign; } } } /* * all entries strictly positive x1 <= x2 and y1 <= y2 */ while (true) { k=std::floor(x2/x1); x2=x2-k*x1; y2=y2-k*y1; /* * testing if R (new U2) is in U1 rectangle */ if (y2<0.0) { return -sign; } if (y2>y1) { return sign; } /* * finding R' */ if (x1>x2+x2) { if (y1<y2+y2) { return sign; } } else { if (y1>y2+y2) { return -sign; } else { x2=x1-x2; y2=y1-y2; sign=-sign; } } if (y2==0.0) { if (x2==0.0) { return 0; } else { return -sign; } } if (x2==0.0) { return sign; } /* * exchange 1 and 2 role. */ k=std::floor(x1/x2); x1=x1-k*x2; y1=y1-k*y2; /* * testing if R (new U1) is in U2 rectangle */ if (y1<0.0) { return sign; } if (y1>y2) { return -sign; } /* * finding R' */ if (x2>x1+x1) { if (y2<y1+y1) { return -sign; } } else { if (y2>y1+y1) { return sign; } else { x1=x2-x1; y1=y2-y1; sign=-sign; } } if (y1==0.0) { if (x1==0.0) { return 0; } else { return sign; } } if (x1==0.0) { return -sign; } } } } // namespace geos.algorithm } // namespace geos
17.197232
94
0.517304
[ "geometry" ]
84e150758a0a05c23e045ce319eff4d8c622b111
2,379
hpp
C++
include/dafs/messages.hpp
dgkimura/dafs
20273ea13d71bbb9ca8f6e85045c0abb1cf45aba
[ "MIT" ]
2
2018-06-29T05:59:16.000Z
2018-07-01T05:58:14.000Z
include/dafs/messages.hpp
dgkimura/dafs
20273ea13d71bbb9ca8f6e85045c0abb1cf45aba
[ "MIT" ]
7
2018-06-04T16:26:37.000Z
2018-11-03T00:47:08.000Z
include/dafs/messages.hpp
dgkimura/dafs
20273ea13d71bbb9ca8f6e85045c0abb1cf45aba
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "dafs/metadata.hpp" namespace dafs { enum class MessageType { // // Reply indicating operation succeeded. // Success, // // Reply indicating operation failed. // Failure, // // Allocation request for a block. // AllocateBlock, // // Read from a known block. // ReadBlock, // // Write to a known block. // WriteBlock, // // Deletes a known block. // DeleteBlock, // // Get details of the node. // GetNodeDetails, // // Join cluster - message sent to a node to signal it to join a // cluster. // _JoinCluster, // // Request initation - message sent to a node requesting to initiate // into minus partition on given cluster node. // _RequestJoinCluster, // // Accepted inivitation - message sent to node to indicate that it // was accepted as the plus partition. // _AcceptJoinCluster, // // Exit cluster - message sent to a node to signal it to exit a // cluster. // ExitCluster, // // Propose exit cluster - message sent to either replicated partition // node suggesting to remove a non-responsive node. // _ProposeExitCluster, // // Plus exit cluster - message sent to node requesting to remove the // plus partition. // _PlusExitCluster, // // Minus exit cluster - message sent to node requesting to remove the // minus partition. // _MinusExitCluster }; struct Address { std::string ip; short port; Address() { } Address(std::string ip, short port) : ip(ip), port(port) { } }; struct EmptyAddress : public Address { EmptyAddress() : Address("invalid_ip", 1) { } }; static constexpr int MessageHeaderSize = 12; struct Message { dafs::MessageType type; std::vector<dafs::MetaData> metadata; }; }
18.732283
77
0.496847
[ "vector" ]
84e70cfba3edc62f47c4f4c97ce6ef80b368ba7c
61,399
inl
C++
CookieEngine/include/Core/Primitives.inl
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Primitives.inl
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Primitives.inl
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef __PRIMITIVES_INL__ #define __PRIMITIVES_INL__ namespace Cookie { namespace Core { namespace Primitives { inline std::unique_ptr<Resources::Mesh> CreateQuad() { std::vector<float> vertices = { -0.5, -0.5, 0, 0, 0, 0, 0, -1, 0.5, -0.5, 0, 1, 0, 0, 0, -1, 0.5, 0.5, 0, 1, 1, 0, 0, -1, -0.5, 0.5, 0, 0, 1, 0, 0, -1 }; std::vector<unsigned int> indices = { 1, 0, 3, 2, 1, 3 }; std::unique_ptr<Resources::Mesh> quad = std::make_unique<Resources::Mesh>("Quad", vertices, indices, 6); return quad; } inline std::vector<DebugVertex> CreateLine(const Math::Vec3& start, const Math::Vec3& end, uint32_t color1, uint32_t color2) { std::vector<DebugVertex> vertices = { {{start.x, start.y, start.z}, color1},{{ end.x, end.y, end.z}, color2} }; return vertices; } inline std::unique_ptr<Resources::Mesh> CreateTriangle() { std::vector<float> vertices = { -1, -1, 0, 0, 0, 0, 0, 1, 1, -1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0.5, 1, 0, 0, 1 }; std::vector<unsigned int> indices = { 0, 1, 2 }; std::unique_ptr<Resources::Mesh> triangle = std::make_unique<Resources::Mesh>("Triangle", vertices, indices, 3); return triangle; } inline std::unique_ptr<Resources::Mesh> CreateCube() { std::vector<float> vertices = { 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f,//1 -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,//2 -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f,//3 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,//4 -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,//5 -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f,//6 -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, -1.0f, 0.0f,//7 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,//8 -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,//9 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,//10 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f,//11 -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f,//12 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f }; std::vector<unsigned int> indices = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 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 }; std::unique_ptr<Cookie::Resources::Mesh> cube = std::make_unique<Cookie::Resources::Mesh>("Cube", vertices, indices, 36); return cube; } inline std::unique_ptr<Resources::Mesh> CreatePyramid() { std::vector<float> vertices = { 0.000000, -1.000000, 1.000000, 0.500000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, -1.000000, -0.000000, 0.750000, 0.250000, 0.000000, -1.000000, -0.000000, -0.000000, -1.000000, -1.000000, 0.500000, 0.500000, 0.000000, -1.000000, -0.000000, -1.000000, -1.000000, 0.000000, 0.250000, 0.250000, 0.000000, -1.000000, -0.000000, 0.000000, -1.000000, 1.000000, 0.250000, 0.500000, -0.666667, 0.333333, 0.666667, -1.000000, -1.000000, 0.000000, 0.375000, 0.500000, -0.666667, 0.333333, 0.666667, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.666667, 0.333333, 0.666667, -1.000000, -1.000000, 0.000000, 0.375000, 0.500000, -0.666667, 0.333333, -0.666667, -0.000000, -1.000000, -1.000000, 0.500000, 0.500000, -0.666667, 0.333333, -0.666667, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.666667, 0.333333, -0.666667, -0.000000, -1.000000, -1.000000, 0.500000, 0.500000, 0.666667, 0.333333, -0.666667, 1.000000, -1.000000, -0.000000, 0.625000, 0.500000, 0.666667, 0.333333, -0.666667, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, 0.666667, 0.333333, -0.666667, 1.000000, -1.000000, -0.000000, 0.625000, 0.500000, 0.666667, 0.333333, 0.666667, 0.000000, -1.000000, 1.000000, 0.750000, 0.500000, 0.666667, 0.333333, 0.666667, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, 0.666667, 0.333333, 0.666667, }; std::vector<unsigned int> indices = { 2,1,0, 3,2,0, 6,5,4, 9,8,7, 12,11,10, 15,14,13, }; std::unique_ptr<Cookie::Resources::Mesh> pyramid = std::make_unique<Cookie::Resources::Mesh>("Pyramid", vertices, indices, indices.size()); return pyramid; } inline std::unique_ptr<Resources::Mesh> CreateCylinder() { std::vector<float> vertices = { 0.951057, -1.000000, 0.309017, 0.375000, 0.312500, 0.951057, 0.000000, 0.309016, 0.809018, -1.000000, 0.587786, 0.387500, 0.312500, 0.809017, 0.000000, 0.587785, 0.809018, 1.000000, 0.587786, 0.387500, 0.688440, 0.809017, 0.000000, 0.587785, 0.951057, 1.000000, 0.309017, 0.375000, 0.688440, 0.951057, 0.000000, 0.309016, 0.587786, -1.000000, 0.809017, 0.400000, 0.312500, 0.587785, 0.000000, 0.809017, 0.587786, 1.000000, 0.809017, 0.400000, 0.688440, 0.587785, 0.000000, 0.809017, 0.309017, -1.000000, 0.951057, 0.412500, 0.312500, 0.309017, 0.000000, 0.951057, 0.309017, 1.000000, 0.951057, 0.412500, 0.688440, 0.309017, 0.000000, 0.951057, 0.000000, -1.000000, 1.000000, 0.425000, 0.312500, -0.000000, 0.000000, 1.000000, 0.000000, 1.000000, 1.000000, 0.425000, 0.688440, -0.000000, 0.000000, 1.000000, -0.309017, -1.000000, 0.951057, 0.437500, 0.312500, -0.309017, 0.000000, 0.951056, -0.309017, 1.000000, 0.951057, 0.437500, 0.688440, -0.309017, 0.000000, 0.951056, -0.587785, -1.000000, 0.809017, 0.450000, 0.312500, -0.587785, 0.000000, 0.809017, -0.587785, 1.000000, 0.809017, 0.450000, 0.688440, -0.587785, 0.000000, 0.809017, -0.809017, -1.000000, 0.587785, 0.462500, 0.312500, -0.809017, 0.000000, 0.587785, -0.809017, 1.000000, 0.587785, 0.462500, 0.688440, -0.809017, 0.000000, 0.587785, -0.951057, -1.000000, 0.309017, 0.475000, 0.312500, -0.951057, 0.000000, 0.309017, -0.951057, 1.000000, 0.309017, 0.475000, 0.688440, -0.951057, 0.000000, 0.309017, -1.000000, -1.000000, -0.000000, 0.487500, 0.312500, -1.000000, 0.000000, -0.000000, -1.000000, 1.000000, -0.000000, 0.487500, 0.688440, -1.000000, 0.000000, -0.000000, -0.951057, -1.000000, -0.309017, 0.500000, 0.312500, -0.951057, 0.000000, -0.309017, -0.951057, 1.000000, -0.309017, 0.500000, 0.688440, -0.951057, 0.000000, -0.309017, -0.809017, -1.000000, -0.587785, 0.512500, 0.312500, -0.809017, 0.000000, -0.587785, -0.809017, 1.000000, -0.587785, 0.512500, 0.688440, -0.809017, 0.000000, -0.587785, -0.587785, -1.000000, -0.809017, 0.525000, 0.312500, -0.587785, 0.000000, -0.809017, -0.587785, 1.000000, -0.809017, 0.525000, 0.688440, -0.587785, 0.000000, -0.809017, -0.309017, -1.000000, -0.951057, 0.537500, 0.312500, -0.309017, 0.000000, -0.951057, -0.309017, 1.000000, -0.951057, 0.537500, 0.688440, -0.309017, 0.000000, -0.951057, -0.000000, -1.000000, -1.000000, 0.550000, 0.312500, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, -1.000000, 0.550000, 0.688440, 0.000000, 0.000000, -1.000000, 0.309017, -1.000000, -0.951057, 0.562500, 0.312500, 0.309017, 0.000000, -0.951057, 0.309017, 1.000000, -0.951057, 0.562500, 0.688440, 0.309017, 0.000000, -0.951057, 0.587785, -1.000000, -0.809017, 0.575000, 0.312500, 0.587785, 0.000000, -0.809017, 0.587785, 1.000000, -0.809017, 0.575000, 0.688440, 0.587785, 0.000000, -0.809017, 0.809017, -1.000000, -0.587785, 0.587500, 0.312500, 0.809017, 0.000000, -0.587785, 0.809017, 1.000000, -0.587785, 0.587500, 0.688440, 0.809017, 0.000000, -0.587785, 0.951057, -1.000000, -0.309017, 0.600000, 0.312500, 0.951057, 0.000000, -0.309017, 0.951057, 1.000000, -0.309017, 0.600000, 0.688440, 0.951057, 0.000000, -0.309017, 1.000000, -1.000000, -0.000000, 0.612500, 0.312500, 1.000000, 0.000000, -0.000001, 1.000000, 1.000000, -0.000000, 0.612500, 0.688440, 1.000000, 0.000000, -0.000001, 0.951057, -1.000000, 0.309017, 0.625000, 0.312500, 0.951057, 0.000000, 0.309016, 0.951057, 1.000000, 0.309017, 0.625000, 0.688440, 0.951057, 0.000000, 0.309016, 0.809018, -1.000000, 0.587786, 0.626409, 0.064408, 0.000000, -1.000000, -0.000000, 0.951057, -1.000000, 0.309017, 0.648603, 0.107966, 0.000000, -1.000000, -0.000000, 0.000000, -1.000000, -0.000000, 0.500000, 0.150000, 0.000000, -1.000000, -0.000000, 0.587786, -1.000000, 0.809017, 0.591842, 0.029841, 0.000000, -1.000000, -0.000000, 0.309017, -1.000000, 0.951057, 0.548284, 0.007647, 0.000000, -1.000000, -0.000000, 0.000000, -1.000000, 1.000000, 0.500000, 0.000000, 0.000000, -1.000000, -0.000000, -0.309017, -1.000000, 0.951057, 0.451716, 0.007647, 0.000000, -1.000000, -0.000000, -0.587785, -1.000000, 0.809017, 0.408159, 0.029841, 0.000000, -1.000000, -0.000000, -0.809017, -1.000000, 0.587785, 0.373591, 0.064409, 0.000000, -1.000000, -0.000000, -0.951057, -1.000000, 0.309017, 0.351397, 0.107966, 0.000000, -1.000000, -0.000000, -1.000000, -1.000000, -0.000000, 0.343750, 0.156250, 0.000000, -1.000000, -0.000000, -0.951057, -1.000000, -0.309017, 0.351397, 0.204534, 0.000000, -1.000000, -0.000000, -0.809017, -1.000000, -0.587785, 0.373591, 0.248091, 0.000000, -1.000000, -0.000000, -0.587785, -1.000000, -0.809017, 0.408159, 0.282659, 0.000000, -1.000000, -0.000000, -0.309017, -1.000000, -0.951057, 0.451716, 0.304853, 0.000000, -1.000000, -0.000000, -0.000000, -1.000000, -1.000000, 0.500000, 0.312500, 0.000000, -1.000000, -0.000000, 0.309017, -1.000000, -0.951057, 0.548284, 0.304853, 0.000000, -1.000000, -0.000000, 0.587785, -1.000000, -0.809017, 0.591841, 0.282659, 0.000000, -1.000000, -0.000000, 0.809017, -1.000000, -0.587785, 0.626409, 0.248091, 0.000000, -1.000000, -0.000000, 0.951057, -1.000000, -0.309017, 0.648603, 0.204534, 0.000000, -1.000000, -0.000000, 1.000000, -1.000000, -0.000000, 0.656250, 0.156250, 0.000000, -1.000000, -0.000000, 0.951057, 1.000000, 0.309017, 0.648603, 0.892034, 0.000000, 1.000000, -0.000000, 0.809018, 1.000000, 0.587786, 0.626409, 0.935591, 0.000000, 1.000000, -0.000000, 0.000000, 1.000000, -0.000000, 0.500000, 0.837500, 0.000000, 1.000000, -0.000000, 0.587786, 1.000000, 0.809017, 0.591841, 0.970159, 0.000000, 1.000000, -0.000000, 0.309017, 1.000000, 0.951057, 0.548284, 0.992353, 0.000000, 1.000000, -0.000000, 0.000000, 1.000000, 1.000000, 0.500000, 1.000000, 0.000000, 1.000000, -0.000000, -0.309017, 1.000000, 0.951057, 0.451716, 0.992353, 0.000000, 1.000000, -0.000000, -0.587785, 1.000000, 0.809017, 0.408159, 0.970159, 0.000000, 1.000000, -0.000000, -0.809017, 1.000000, 0.587785, 0.373591, 0.935591, 0.000000, 1.000000, -0.000000, -0.951057, 1.000000, 0.309017, 0.351397, 0.892034, 0.000000, 1.000000, -0.000000, -1.000000, 1.000000, -0.000000, 0.343750, 0.843750, 0.000000, 1.000000, -0.000000, -0.951057, 1.000000, -0.309017, 0.351397, 0.795466, 0.000000, 1.000000, -0.000000, -0.809017, 1.000000, -0.587785, 0.373591, 0.751909, 0.000000, 1.000000, -0.000000, -0.587785, 1.000000, -0.809017, 0.408159, 0.717341, 0.000000, 1.000000, -0.000000, -0.309017, 1.000000, -0.951057, 0.451716, 0.695147, 0.000000, 1.000000, -0.000000, -0.000000, 1.000000, -1.000000, 0.500000, 0.687500, 0.000000, 1.000000, -0.000000, 0.309017, 1.000000, -0.951057, 0.548284, 0.695147, 0.000000, 1.000000, -0.000000, 0.587785, 1.000000, -0.809017, 0.591842, 0.717341, 0.000000, 1.000000, -0.000000, 0.809017, 1.000000, -0.587785, 0.626409, 0.751908, 0.000000, 1.000000, -0.000000, 0.951057, 1.000000, -0.309017, 0.648603, 0.795466, 0.000000, 1.000000, -0.000000, 1.000000, 1.000000, -0.000000, 0.656250, 0.843750, 0.000000, 1.000000, -0.000000, }; std::vector<unsigned int> indices = { 2,1,0, 3,2,0, 5,4,1, 2,5,1, 7,6,4, 5,7,4, 9,8,6, 7,9,6, 11,10,8, 9,11,8, 13,12,10, 11,13,10, 15,14,12, 13,15,12, 17,16,14, 15,17,14, 19,18,16, 17,19,16, 21,20,18, 19,21,18, 23,22,20, 21,23,20, 25,24,22, 23,25,22, 27,26,24, 25,27,24, 29,28,26, 27,29,26, 31,30,28, 29,31,28, 33,32,30, 31,33,30, 35,34,32, 33,35,32, 37,36,34, 35,37,34, 39,38,36, 37,39,36, 41,40,38, 39,41,38, 44,43,42, 44,42,45, 44,45,46, 44,46,47, 44,47,48, 44,48,49, 44,49,50, 44,50,51, 44,51,52, 44,52,53, 44,53,54, 44,54,55, 44,55,56, 44,56,57, 44,57,58, 44,58,59, 44,59,60, 44,60,61, 44,61,62, 44,62,43, 65,64,63, 65,66,64, 65,67,66, 65,68,67, 65,69,68, 65,70,69, 65,71,70, 65,72,71, 65,73,72, 65,74,73, 65,75,74, 65,76,75, 65,77,76, 65,78,77, 65,79,78, 65,80,79, 65,81,80, 65,82,81, 65,83,82, 65,63,83, }; std::unique_ptr<Cookie::Resources::Mesh> cylinder = std::make_unique<Cookie::Resources::Mesh>("Cylinder", vertices, indices, indices.size()); return cylinder; } inline std::unique_ptr<Resources::Mesh> CreateCone() { std::vector<float> vertices = { 0.951057, -1.000000, 0.309017, 0.737764, 0.172746, 0.000000, -1.000000, 0.000000, 1.000000, -1.000000, -0.000000, 0.750000, 0.250000, 0.000000, -1.000000, 0.000000, 0.951057, -1.000000, -0.309017, 0.737764, 0.327254, 0.000000, -1.000000, 0.000000, 0.809017, -1.000000, -0.587785, 0.702254, 0.396946, 0.000000, -1.000000, 0.000000, 0.587785, -1.000000, -0.809017, 0.646946, 0.452254, 0.000000, -1.000000, 0.000000, 0.309017, -1.000000, -0.951057, 0.577254, 0.487764, 0.000000, -1.000000, 0.000000, -0.000000, -1.000000, -1.000000, 0.500000, 0.500000, 0.000000, -1.000000, 0.000000, -0.309017, -1.000000, -0.951057, 0.422746, 0.487764, 0.000000, -1.000000, 0.000000, -0.587785, -1.000000, -0.809017, 0.353054, 0.452254, 0.000000, -1.000000, 0.000000, -0.809017, -1.000000, -0.587785, 0.297746, 0.396946, 0.000000, -1.000000, 0.000000, -0.951057, -1.000000, -0.309017, 0.262236, 0.327254, 0.000000, -1.000000, 0.000000, -1.000000, -1.000000, -0.000000, 0.250000, 0.250000, 0.000000, -1.000000, 0.000000, -0.951057, -1.000000, 0.309017, 0.262236, 0.172746, 0.000000, -1.000000, 0.000000, -0.809017, -1.000000, 0.587785, 0.297746, 0.103054, 0.000000, -1.000000, 0.000000, -0.587785, -1.000000, 0.809017, 0.353054, 0.047746, 0.000000, -1.000000, 0.000000, -0.309017, -1.000000, 0.951057, 0.422746, 0.012236, 0.000000, -1.000000, 0.000000, 0.000000, -1.000000, 1.000000, 0.500000, 0.000000, 0.000000, -1.000000, 0.000000, 0.309017, -1.000000, 0.951057, 0.577254, 0.012236, 0.000000, -1.000000, 0.000000, 0.587786, -1.000000, 0.809017, 0.646946, 0.047746, 0.000000, -1.000000, 0.000000, 0.809018, -1.000000, 0.587786, 0.702254, 0.103054, 0.000000, -1.000000, 0.000000, 0.951057, -1.000000, 0.309017, 0.250000, 0.500000, 0.850651, 0.447214, 0.276392, 0.809018, -1.000000, 0.587786, 0.275000, 0.500000, 0.723607, 0.447214, 0.525731, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, 0.587786, -1.000000, 0.809017, 0.300000, 0.500000, 0.525731, 0.447214, 0.723607, 0.309017, -1.000000, 0.951057, 0.325000, 0.500000, 0.276393, 0.447214, 0.850651, 0.000000, -1.000000, 1.000000, 0.350000, 0.500000, -0.000000, 0.447214, 0.894427, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, -0.309017, -1.000000, 0.951057, 0.375000, 0.500000, -0.276393, 0.447214, 0.850651, -0.587785, -1.000000, 0.809017, 0.400000, 0.500000, -0.525731, 0.447214, 0.723607, -0.809017, -1.000000, 0.587785, 0.425000, 0.500000, -0.723607, 0.447214, 0.525731, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, -0.951057, -1.000000, 0.309017, 0.450000, 0.500000, -0.850651, 0.447214, 0.276393, -1.000000, -1.000000, -0.000000, 0.475000, 0.500000, -0.894427, 0.447214, -0.000000, -0.951057, -1.000000, -0.309017, 0.500000, 0.500000, -0.850651, 0.447214, -0.276393, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, -0.809017, -1.000000, -0.587785, 0.525000, 0.500000, -0.723607, 0.447214, -0.525731, -0.587785, -1.000000, -0.809017, 0.550000, 0.500000, -0.525731, 0.447214, -0.723607, -0.309017, -1.000000, -0.951057, 0.575000, 0.500000, -0.276393, 0.447214, -0.850651, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, -0.000000, -1.000000, -1.000000, 0.600000, 0.500000, 0.000000, 0.447214, -0.894427, 0.309017, -1.000000, -0.951057, 0.625000, 0.500000, 0.276393, 0.447214, -0.850651, 0.587785, -1.000000, -0.809017, 0.650000, 0.500000, 0.525731, 0.447214, -0.723607, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, 0.809017, -1.000000, -0.587785, 0.675000, 0.500000, 0.723607, 0.447214, -0.525731, 0.951057, -1.000000, -0.309017, 0.700000, 0.500000, 0.850651, 0.447214, -0.276393, 1.000000, -1.000000, -0.000000, 0.725000, 0.500000, 0.894427, 0.447214, -0.000001, 0.000000, 1.000000, -0.000000, 0.500000, 1.000000, -0.000000, 1.000000, 0.000001, 0.951057, -1.000000, 0.309017, 0.750000, 0.500000, 0.850651, 0.447214, 0.276392, }; std::vector<unsigned int> indices = { 2,1,0, 3,2,0, 4,3,0, 5,4,0, 6,5,0, 7,6,0, 8,7,0, 9,8,0, 10,9,0, 11,10,0, 12,11,0, 13,12,0, 14,13,0, 15,14,0, 16,15,0, 17,16,0, 18,17,0, 19,18,0, 22,21,20, 22,23,21, 22,24,23, 26,25,24, 26,27,25, 26,28,27, 30,29,28, 30,31,29, 30,32,31, 34,33,32, 34,35,33, 34,36,35, 38,37,36, 38,39,37, 38,40,39, 42,41,40, 42,43,41, 42,44,43, 46,45,44, 46,47,45, }; std::unique_ptr<Cookie::Resources::Mesh> cone = std::make_unique<Cookie::Resources::Mesh>("Cone", vertices, indices, indices.size()); return cone; } inline std::unique_ptr<Resources::Mesh> CreateCircle() { std::vector<float> vertices = { -0.078459, 0.000000, -0.996917, 0.460649, 0.000000, 0.000000, 1.000000, -0.000000, 0.078459, 0.000000, -0.996917, 0.539351, 0.000000, 0.000000, 1.000000, -0.000000, -0.000000, 0.000000, -0.000000, 0.500000, 0.500000, 0.000000, 1.000000, -0.000000, 0.233445, 0.000000, -0.972370, 0.617084, 0.012312, 0.000000, 1.000000, -0.000000, 0.382683, 0.000000, -0.923880, 0.691933, 0.036632, 0.000000, 1.000000, -0.000000, 0.522499, 0.000000, -0.852640, 0.762057, 0.072362, 0.000000, 1.000000, -0.000000, 0.649448, 0.000000, -0.760406, 0.825728, 0.118621, 0.000000, 1.000000, -0.000000, 0.760406, 0.000000, -0.649448, 0.881379, 0.174272, 0.000000, 1.000000, -0.000000, 0.852640, 0.000000, -0.522499, 0.927638, 0.237943, 0.000000, 1.000000, -0.000000, 0.923880, 0.000000, -0.382683, 0.963368, 0.308067, 0.000000, 1.000000, -0.000000, 0.972370, 0.000000, -0.233445, 0.987688, 0.382916, 0.000000, 1.000000, -0.000000, 0.996917, 0.000000, -0.078459, 1.000000, 0.460649, 0.000000, 1.000000, -0.000000, 0.996917, 0.000000, 0.078459, 1.000000, 0.539351, 0.000000, 1.000000, -0.000000, 0.972370, 0.000000, 0.233445, 0.987688, 0.617084, 0.000000, 1.000000, -0.000000, 0.923879, 0.000000, 0.382684, 0.963368, 0.691933, 0.000000, 1.000000, -0.000000, 0.852640, 0.000000, 0.522499, 0.927638, 0.762057, 0.000000, 1.000000, -0.000000, 0.760406, 0.000000, 0.649448, 0.881379, 0.825728, 0.000000, 1.000000, -0.000000, 0.649448, 0.000000, 0.760406, 0.825728, 0.881379, 0.000000, 1.000000, -0.000000, 0.522498, 0.000000, 0.852640, 0.762057, 0.927638, 0.000000, 1.000000, -0.000000, 0.382683, 0.000000, 0.923880, 0.691933, 0.963368, 0.000000, 1.000000, -0.000000, 0.233445, 0.000000, 0.972370, 0.617084, 0.987688, 0.000000, 1.000000, -0.000000, 0.078459, 0.000000, 0.996917, 0.539351, 1.000000, 0.000000, 1.000000, -0.000000, -0.078459, 0.000000, 0.996917, 0.460649, 1.000000, 0.000000, 1.000000, -0.000000, -0.233445, 0.000000, 0.972370, 0.382916, 0.987688, 0.000000, 1.000000, -0.000000, -0.382684, 0.000000, 0.923880, 0.308067, 0.963368, 0.000000, 1.000000, -0.000000, -0.522499, 0.000000, 0.852640, 0.237943, 0.927638, 0.000000, 1.000000, -0.000000, -0.649448, 0.000000, 0.760406, 0.174272, 0.881379, 0.000000, 1.000000, -0.000000, -0.760406, 0.000000, 0.649448, 0.118621, 0.825728, 0.000000, 1.000000, -0.000000, -0.852640, 0.000000, 0.522498, 0.072362, 0.762057, 0.000000, 1.000000, -0.000000, -0.923880, 0.000000, 0.382683, 0.036632, 0.691933, 0.000000, 1.000000, -0.000000, -0.972370, 0.000000, 0.233445, 0.012312, 0.617084, 0.000000, 1.000000, -0.000000, -0.996917, 0.000000, 0.078459, 0.000000, 0.539351, 0.000000, 1.000000, -0.000000, -0.996917, 0.000000, -0.078459, 0.000000, 0.460649, 0.000000, 1.000000, -0.000000, -0.972370, 0.000000, -0.233446, 0.012312, 0.382916, 0.000000, 1.000000, -0.000000, -0.923879, 0.000000, -0.382684, 0.036632, 0.308066, 0.000000, 1.000000, -0.000000, -0.852640, 0.000000, -0.522499, 0.072362, 0.237943, 0.000000, 1.000000, -0.000000, -0.760406, 0.000000, -0.649448, 0.118621, 0.174272, 0.000000, 1.000000, -0.000000, -0.649448, 0.000000, -0.760406, 0.174272, 0.118621, 0.000000, 1.000000, -0.000000, -0.522499, 0.000000, -0.852640, 0.237943, 0.072362, 0.000000, 1.000000, -0.000000, -0.382684, 0.000000, -0.923880, 0.308067, 0.036632, 0.000000, 1.000000, -0.000000, -0.233445, 0.000000, -0.972370, 0.382916, 0.012312, 0.000000, 1.000000, -0.000000, }; std::vector<unsigned int> indices = { 2,1,0, 2,3,1, 2,4,3, 2,5,4, 2,6,5, 2,7,6, 2,8,7, 2,9,8, 2,10,9, 2,11,10, 2,12,11, 2,13,12, 2,14,13, 2,15,14, 2,16,15, 2,17,16, 2,18,17, 2,19,18, 2,20,19, 2,21,20, 2,22,21, 2,23,22, 2,24,23, 2,25,24, 2,26,25, 2,27,26, 2,28,27, 2,29,28, 2,30,29, 2,31,30, 2,32,31, 2,33,32, 2,34,33, 2,35,34, 2,36,35, 2,37,36, 2,38,37, 2,39,38, 2,40,39, 2,0,40, }; std::unique_ptr<Cookie::Resources::Mesh> circle = std::make_unique<Cookie::Resources::Mesh>("Circle", vertices, indices, indices.size()); return circle; } inline std::unique_ptr<Resources::Mesh> CreateCapsule() { std::vector<float> vertices = { 0.211630, -1.974928, 0.068763, 0.521229, 0.149352, 0.269980, -0.958862, 0.087722, 0.180023, -1.974928, 0.130795, 0.518058, 0.143130, 0.229659, -0.958862, 0.166856, 0.351019, -1.900969, 0.255030, 0.536117, 0.130010, 0.376829, -0.884897, 0.273782, 0.412648, -1.900969, 0.134077, 0.542458, 0.142455, 0.442989, -0.884897, 0.143936, 0.130795, -1.974928, 0.180023, 0.513120, 0.138192, 0.166857, -0.958862, 0.229659, 0.255030, -1.900969, 0.351019, 0.526240, 0.120133, 0.273782, -0.884897, 0.376829, 0.068763, -1.974928, 0.211630, 0.506898, 0.135021, 0.087722, -0.958862, 0.269980, 0.134077, -1.900969, 0.412648, 0.513795, 0.113792, 0.143936, -0.884897, 0.442989, -0.000000, -1.974928, 0.222521, 0.500000, 0.133929, -0.000000, -0.958862, 0.283874, -0.000000, -1.900969, 0.433884, 0.500000, 0.111607, -0.000000, -0.884897, 0.465786, -0.068763, -1.974928, 0.211630, 0.493102, 0.135021, -0.087722, -0.958862, 0.269980, -0.134077, -1.900969, 0.412648, 0.486205, 0.113792, -0.143936, -0.884897, 0.442989, -0.130795, -1.974928, 0.180023, 0.486880, 0.138192, -0.166857, -0.958862, 0.229659, -0.255030, -1.900969, 0.351019, 0.473760, 0.120133, -0.273782, -0.884897, 0.376829, -0.180023, -1.974928, 0.130795, 0.481942, 0.143130, -0.229659, -0.958862, 0.166857, -0.351019, -1.900969, 0.255030, 0.463883, 0.130010, -0.376829, -0.884897, 0.273783, -0.211630, -1.974928, 0.068763, 0.478771, 0.149352, -0.269980, -0.958862, 0.087722, -0.412648, -1.900969, 0.134077, 0.457542, 0.142455, -0.442989, -0.884897, 0.143936, -0.222521, -1.974928, -0.000000, 0.477679, 0.156250, -0.283874, -0.958862, -0.000000, -0.433884, -1.900969, -0.000000, 0.455357, 0.156250, -0.465786, -0.884897, -0.000000, -0.211630, -1.974928, -0.068763, 0.478771, 0.163148, -0.269980, -0.958862, -0.087722, -0.412648, -1.900969, -0.134077, 0.457542, 0.170045, -0.442989, -0.884897, -0.143936, -0.180023, -1.974928, -0.130795, 0.481942, 0.169370, -0.229659, -0.958862, -0.166856, -0.351019, -1.900969, -0.255030, 0.463883, 0.182490, -0.376829, -0.884897, -0.273782, -0.130795, -1.974928, -0.180023, 0.486880, 0.174308, -0.166857, -0.958862, -0.229659, -0.255030, -1.900969, -0.351019, 0.473760, 0.192367, -0.273782, -0.884897, -0.376829, -0.068763, -1.974928, -0.211630, 0.493102, 0.177479, -0.087722, -0.958862, -0.269980, -0.134077, -1.900969, -0.412648, 0.486205, 0.198708, -0.143936, -0.884897, -0.442989, 0.000000, -1.974928, -0.222521, 0.500000, 0.178571, 0.000000, -0.958862, -0.283874, 0.000000, -1.900969, -0.433884, 0.500000, 0.200893, 0.000000, -0.884897, -0.465786, 0.068763, -1.974928, -0.211630, 0.506898, 0.177479, 0.087722, -0.958862, -0.269980, 0.134077, -1.900969, -0.412648, 0.513795, 0.198708, 0.143936, -0.884897, -0.442989, 0.130795, -1.974928, -0.180023, 0.513120, 0.174308, 0.166857, -0.958862, -0.229659, 0.255030, -1.900969, -0.351019, 0.526240, 0.192367, 0.273782, -0.884897, -0.376829, 0.180023, -1.974928, -0.130795, 0.518058, 0.169370, 0.229659, -0.958862, -0.166857, 0.351019, -1.900969, -0.255030, 0.536117, 0.182490, 0.376829, -0.884897, -0.273783, 0.211630, -1.974928, -0.068763, 0.521229, 0.163148, 0.269980, -0.958862, -0.087722, 0.412648, -1.900969, -0.134077, 0.542458, 0.170045, 0.442989, -0.884897, -0.143936, 0.222521, -1.974928, -0.000000, 0.522321, 0.156250, 0.283874, -0.958862, -0.000000, 0.433884, -1.900969, -0.000000, 0.544643, 0.156250, 0.465786, -0.884897, -0.000000, 0.504414, -1.781832, 0.366478, 0.554175, 0.116889, 0.519724, -0.766358, 0.377602, 0.592974, -1.781832, 0.192669, 0.563687, 0.135557, 0.610972, -0.766358, 0.198517, 0.366478, -1.781832, 0.504414, 0.539361, 0.102075, 0.377602, -0.766358, 0.519724, 0.192669, -1.781832, 0.592974, 0.520693, 0.092563, 0.198517, -0.766358, 0.610972, -0.000000, -1.781832, 0.623490, 0.500000, 0.089286, 0.000000, -0.766358, 0.642414, -0.192669, -1.781832, 0.592974, 0.479307, 0.092563, -0.198517, -0.766358, 0.610972, -0.366478, -1.781832, 0.504414, 0.460639, 0.102075, -0.377602, -0.766358, 0.519724, -0.504414, -1.781832, 0.366478, 0.445825, 0.116889, -0.519724, -0.766358, 0.377602, -0.592974, -1.781832, 0.192669, 0.436313, 0.135557, -0.610972, -0.766358, 0.198517, -0.623490, -1.781832, -0.000000, 0.433036, 0.156250, -0.642414, -0.766358, -0.000000, -0.592974, -1.781832, -0.192669, 0.436313, 0.176943, -0.610972, -0.766358, -0.198517, -0.504414, -1.781832, -0.366478, 0.445825, 0.195611, -0.519724, -0.766358, -0.377602, -0.366478, -1.781832, -0.504414, 0.460639, 0.210425, -0.377602, -0.766358, -0.519724, -0.192669, -1.781832, -0.592974, 0.479307, 0.219937, -0.198517, -0.766358, -0.610972, 0.000000, -1.781832, -0.623490, 0.500000, 0.223214, 0.000000, -0.766358, -0.642414, 0.192669, -1.781832, -0.592974, 0.520693, 0.219937, 0.198517, -0.766358, -0.610972, 0.366478, -1.781832, -0.504414, 0.539361, 0.210425, 0.377602, -0.766358, -0.519724, 0.504414, -1.781832, -0.366478, 0.554175, 0.195611, 0.519724, -0.766358, -0.377602, 0.592974, -1.781832, -0.192669, 0.563687, 0.176943, 0.610972, -0.766358, -0.198517, 0.623490, -1.781832, -0.000000, 0.566964, 0.156250, 0.642414, -0.766358, 0.000000, 0.632515, -1.623490, 0.459549, 0.572234, 0.103769, 0.641024, -0.610068, 0.465731, 0.743566, -1.623490, 0.241599, 0.584916, 0.128659, 0.753569, -0.610068, 0.244849, 0.459549, -1.623490, 0.632515, 0.552481, 0.084016, 0.465731, -0.610068, 0.641024, 0.241599, -1.623490, 0.743566, 0.527591, 0.071334, 0.244849, -0.610068, 0.753569, -0.000000, -1.623490, 0.781832, 0.500000, 0.066964, -0.000000, -0.610068, 0.792349, -0.241599, -1.623490, 0.743566, 0.472409, 0.071334, -0.244849, -0.610068, 0.753569, -0.459549, -1.623490, 0.632515, 0.447519, 0.084016, -0.465731, -0.610068, 0.641024, -0.632515, -1.623490, 0.459549, 0.427766, 0.103769, -0.641024, -0.610068, 0.465731, -0.743566, -1.623490, 0.241599, 0.415084, 0.128659, -0.753569, -0.610068, 0.244850, -0.781832, -1.623490, -0.000000, 0.410714, 0.156250, -0.792349, -0.610068, -0.000000, -0.743566, -1.623490, -0.241599, 0.415084, 0.183841, -0.753569, -0.610068, -0.244849, -0.632515, -1.623490, -0.459549, 0.427766, 0.208731, -0.641024, -0.610068, -0.465731, -0.459549, -1.623490, -0.632515, 0.447519, 0.228484, -0.465731, -0.610068, -0.641024, -0.241599, -1.623490, -0.743566, 0.472409, 0.241166, -0.244849, -0.610068, -0.753569, 0.000000, -1.623490, -0.781832, 0.500000, 0.245536, 0.000000, -0.610068, -0.792349, 0.241599, -1.623490, -0.743566, 0.527591, 0.241166, 0.244849, -0.610068, -0.753569, 0.459549, -1.623490, -0.632515, 0.552481, 0.228484, 0.465731, -0.610068, -0.641024, 0.632515, -1.623490, -0.459549, 0.572234, 0.208731, 0.641024, -0.610068, -0.465731, 0.743566, -1.623490, -0.241599, 0.584916, 0.183841, 0.753569, -0.610068, -0.244850, 0.781832, -1.623490, -0.000000, 0.589286, 0.156250, 0.792349, -0.610068, 0.000000, 0.728899, -1.433884, 0.529576, 0.590292, 0.090649, 0.732709, -0.423966, 0.532344, 0.856872, -1.433884, 0.278415, 0.606145, 0.121761, 0.861351, -0.423966, 0.279870, 0.529576, -1.433884, 0.728899, 0.565601, 0.065958, 0.532344, -0.423966, 0.732709, 0.278415, -1.433884, 0.856872, 0.534488, 0.050105, 0.279870, -0.423966, 0.861351, -0.000000, -1.433884, 0.900969, 0.500000, 0.044643, -0.000000, -0.423966, 0.905678, -0.278415, -1.433884, 0.856872, 0.465511, 0.050105, -0.279870, -0.423966, 0.861351, -0.529576, -1.433884, 0.728899, 0.434399, 0.065958, -0.532344, -0.423966, 0.732709, -0.728899, -1.433884, 0.529576, 0.409708, 0.090649, -0.732709, -0.423966, 0.532344, -0.856872, -1.433884, 0.278415, 0.393855, 0.121762, -0.861351, -0.423966, 0.279870, -0.900969, -1.433884, -0.000000, 0.388393, 0.156250, -0.905678, -0.423966, -0.000000, -0.856872, -1.433884, -0.278415, 0.393855, 0.190738, -0.861351, -0.423966, -0.279870, -0.728899, -1.433884, -0.529576, 0.409708, 0.221851, -0.732709, -0.423966, -0.532344, -0.529576, -1.433884, -0.728899, 0.434399, 0.246542, -0.532344, -0.423966, -0.732709, -0.278415, -1.433884, -0.856872, 0.465512, 0.262395, -0.279870, -0.423966, -0.861351, 0.000000, -1.433884, -0.900969, 0.500000, 0.267857, 0.000000, -0.423966, -0.905678, 0.278415, -1.433884, -0.856872, 0.534488, 0.262395, 0.279870, -0.423966, -0.861351, 0.529576, -1.433884, -0.728899, 0.565601, 0.246542, 0.532344, -0.423966, -0.732709, 0.728899, -1.433884, -0.529576, 0.590292, 0.221851, 0.732709, -0.423966, -0.532344, 0.856872, -1.433884, -0.278415, 0.606145, 0.190738, 0.861351, -0.423966, -0.279870, 0.900969, -1.433884, -0.000000, 0.611607, 0.156250, 0.905678, -0.423966, 0.000000, 0.788733, -1.222521, 0.573048, 0.608351, 0.077529, 0.789694, -0.217251, 0.573747, 0.927212, -1.222521, 0.301269, 0.627374, 0.114864, 0.928341, -0.217251, 0.301636, 0.573048, -1.222521, 0.788733, 0.578721, 0.047899, 0.573747, -0.217251, 0.789694, 0.301269, -1.222521, 0.927212, 0.541386, 0.028876, 0.301636, -0.217251, 0.928341, -0.000000, -1.222521, 0.974928, 0.500000, 0.022321, -0.000000, -0.217250, 0.976116, -0.301269, -1.222521, 0.927212, 0.458614, 0.028876, -0.301636, -0.217250, 0.928341, -0.573048, -1.222521, 0.788733, 0.421279, 0.047899, -0.573747, -0.217250, 0.789694, -0.788733, -1.222521, 0.573048, 0.391649, 0.077529, -0.789694, -0.217250, 0.573747, -0.927212, -1.222521, 0.301269, 0.372626, 0.114864, -0.928342, -0.217250, 0.301636, -0.974928, -1.222521, -0.000000, 0.366071, 0.156250, -0.976116, -0.217250, -0.000000, -0.927212, -1.222521, -0.301269, 0.372626, 0.197636, -0.928342, -0.217250, -0.301636, -0.788733, -1.222521, -0.573048, 0.391649, 0.234971, -0.789694, -0.217250, -0.573747, -0.573048, -1.222521, -0.788733, 0.421279, 0.264601, -0.573747, -0.217250, -0.789694, -0.301269, -1.222521, -0.927212, 0.458614, 0.283624, -0.301636, -0.217250, -0.928342, 0.000000, -1.222521, -0.974928, 0.500000, 0.290179, 0.000000, -0.217250, -0.976116, 0.301269, -1.222521, -0.927212, 0.541386, 0.283624, 0.301636, -0.217250, -0.928342, 0.573048, -1.222521, -0.788733, 0.578721, 0.264601, 0.573747, -0.217250, -0.789695, 0.788733, -1.222521, -0.573048, 0.608351, 0.234971, 0.789695, -0.217250, -0.573747, 0.927212, -1.222521, -0.301269, 0.627374, 0.197636, 0.928342, -0.217249, -0.301636, 0.974928, -1.222521, -0.000000, 0.633929, 0.156250, 0.976116, -0.217250, -0.000000, 0.809018, -1.000000, 0.587786, 0.626409, 0.064408, 0.808968, -0.011041, 0.587749, 0.951057, -1.000000, 0.309017, 0.648603, 0.107966, 0.950999, -0.011041, 0.308997, 0.587786, -1.000000, 0.809017, 0.591842, 0.029841, 0.587749, -0.011041, 0.808968, 0.309017, -1.000000, 0.951057, 0.548284, 0.007647, 0.308998, -0.011041, 0.950999, 0.000000, -1.000000, 1.000000, 0.500000, 0.000000, -0.000000, -0.011041, 0.999939, -0.309017, -1.000000, 0.951057, 0.451716, 0.007647, -0.308998, -0.011041, 0.950998, -0.587785, -1.000000, 0.809017, 0.408159, 0.029841, -0.587750, -0.011041, 0.808968, -0.809017, -1.000000, 0.587785, 0.373591, 0.064408, -0.808968, -0.011041, 0.587749, -0.951057, -1.000000, 0.309017, 0.351397, 0.107966, -0.950999, -0.011041, 0.308998, -1.000000, -1.000000, -0.000000, 0.343750, 0.156250, -0.999939, -0.011041, -0.000000, -0.951057, -1.000000, -0.309017, 0.351397, 0.204534, -0.950999, -0.011041, -0.308998, -0.809017, -1.000000, -0.587785, 0.373591, 0.248091, -0.808968, -0.011041, -0.587750, -0.587785, -1.000000, -0.809017, 0.408159, 0.282659, -0.587749, -0.011041, -0.808968, -0.309017, -1.000000, -0.951057, 0.451716, 0.304853, -0.308998, -0.011041, -0.950999, -0.000000, -1.000000, -1.000000, 0.500000, 0.312500, 0.000000, -0.011041, -0.999939, 0.309017, -1.000000, -0.951057, 0.548284, 0.304853, 0.308998, -0.011041, -0.950999, 0.587785, -1.000000, -0.809017, 0.591841, 0.282659, 0.587749, -0.011041, -0.808968, 0.809017, -1.000000, -0.587785, 0.626409, 0.248091, 0.808968, -0.011041, -0.587749, 0.951057, -1.000000, -0.309017, 0.648603, 0.204534, 0.950999, -0.011041, -0.308998, 1.000000, -1.000000, -0.000000, 0.656250, 0.156250, 0.999939, -0.011041, -0.000001, 0.951057, -1.000000, 0.309017, 0.375000, 0.312500, 0.950999, -0.011041, 0.308997, 0.809018, -1.000000, 0.587786, 0.387500, 0.312500, 0.808968, -0.011041, 0.587749, 0.809018, 1.000000, 0.587786, 0.387500, 0.688440, 0.808968, 0.011041, 0.587749, 0.951057, 1.000000, 0.309017, 0.375000, 0.688440, 0.950999, 0.011041, 0.308997, 0.587786, -1.000000, 0.809017, 0.400000, 0.312500, 0.587749, -0.011041, 0.808968, 0.587786, 1.000000, 0.809017, 0.400000, 0.688440, 0.587749, 0.011041, 0.808968, 0.309017, -1.000000, 0.951057, 0.412500, 0.312500, 0.308998, -0.011041, 0.950999, 0.309017, 1.000000, 0.951057, 0.412500, 0.688440, 0.308998, 0.011041, 0.950999, 0.000000, -1.000000, 1.000000, 0.425000, 0.312500, -0.000000, -0.011041, 0.999939, 0.000000, 1.000000, 1.000000, 0.425000, 0.688440, -0.000000, 0.011041, 0.999939, -0.309017, -1.000000, 0.951057, 0.437500, 0.312500, -0.308998, -0.011041, 0.950998, -0.309017, 1.000000, 0.951057, 0.437500, 0.688440, -0.308998, 0.011041, 0.950999, -0.587785, -1.000000, 0.809017, 0.450000, 0.312500, -0.587750, -0.011041, 0.808968, -0.587785, 1.000000, 0.809017, 0.450000, 0.688440, -0.587750, 0.011041, 0.808968, -0.809017, -1.000000, 0.587785, 0.462500, 0.312500, -0.808968, -0.011041, 0.587749, -0.809017, 1.000000, 0.587785, 0.462500, 0.688440, -0.808968, 0.011041, 0.587749, -0.951057, -1.000000, 0.309017, 0.475000, 0.312500, -0.950999, -0.011041, 0.308998, -0.951057, 1.000000, 0.309017, 0.475000, 0.688440, -0.950999, 0.011041, 0.308998, -1.000000, -1.000000, -0.000000, 0.487500, 0.312500, -0.999939, -0.011041, -0.000000, -1.000000, 1.000000, -0.000000, 0.487500, 0.688440, -0.999939, 0.011041, -0.000000, -0.951057, -1.000000, -0.309017, 0.500000, 0.312500, -0.950999, -0.011041, -0.308998, -0.951057, 1.000000, -0.309017, 0.500000, 0.688440, -0.950999, 0.011041, -0.308998, -0.809017, -1.000000, -0.587785, 0.512500, 0.312500, -0.808968, -0.011041, -0.587750, -0.809017, 1.000000, -0.587785, 0.512500, 0.688440, -0.808968, 0.011041, -0.587750, -0.587785, -1.000000, -0.809017, 0.525000, 0.312500, -0.587749, -0.011041, -0.808968, -0.587785, 1.000000, -0.809017, 0.525000, 0.688440, -0.587749, 0.011041, -0.808968, -0.309017, -1.000000, -0.951057, 0.537500, 0.312500, -0.308998, -0.011041, -0.950999, -0.309017, 1.000000, -0.951057, 0.537500, 0.688440, -0.308998, 0.011041, -0.950999, -0.000000, -1.000000, -1.000000, 0.550000, 0.312500, 0.000000, -0.011041, -0.999939, -0.000000, 1.000000, -1.000000, 0.550000, 0.688440, 0.000000, 0.011041, -0.999939, 0.309017, -1.000000, -0.951057, 0.562500, 0.312500, 0.308998, -0.011041, -0.950999, 0.309017, 1.000000, -0.951057, 0.562500, 0.688440, 0.308998, 0.011041, -0.950999, 0.587785, -1.000000, -0.809017, 0.575000, 0.312500, 0.587749, -0.011041, -0.808968, 0.587785, 1.000000, -0.809017, 0.575000, 0.688440, 0.587749, 0.011041, -0.808968, 0.809017, -1.000000, -0.587785, 0.587500, 0.312500, 0.808968, -0.011041, -0.587749, 0.809017, 1.000000, -0.587785, 0.587500, 0.688440, 0.808968, 0.011041, -0.587749, 0.951057, -1.000000, -0.309017, 0.600000, 0.312500, 0.950999, -0.011041, -0.308998, 0.951057, 1.000000, -0.309017, 0.600000, 0.688440, 0.950999, 0.011041, -0.308998, 1.000000, -1.000000, -0.000000, 0.612500, 0.312500, 0.999939, -0.011041, -0.000001, 1.000000, 1.000000, -0.000000, 0.612500, 0.688440, 0.999939, 0.011041, -0.000001, 0.951057, -1.000000, 0.309017, 0.625000, 0.312500, 0.950999, -0.011041, 0.308997, 0.951057, 1.000000, 0.309017, 0.625000, 0.688440, 0.950999, 0.011041, 0.308997, 0.951057, 1.000000, 0.309017, 0.648603, 0.892034, 0.950999, 0.011041, 0.308997, 0.809018, 1.000000, 0.587786, 0.626409, 0.935591, 0.808968, 0.011041, 0.587749, 0.788733, 1.222521, 0.573048, 0.608351, 0.922471, 0.789694, 0.217251, 0.573747, 0.927212, 1.222521, 0.301269, 0.627374, 0.885136, 0.928341, 0.217251, 0.301636, 0.587786, 1.000000, 0.809017, 0.591841, 0.970159, 0.587749, 0.011041, 0.808968, 0.573048, 1.222521, 0.788733, 0.578721, 0.952101, 0.573747, 0.217251, 0.789694, 0.309017, 1.000000, 0.951057, 0.548284, 0.992353, 0.308998, 0.011041, 0.950999, 0.301269, 1.222521, 0.927212, 0.541386, 0.971124, 0.301636, 0.217251, 0.928341, 0.000000, 1.000000, 1.000000, 0.500000, 1.000000, -0.000000, 0.011041, 0.999939, -0.000000, 1.222521, 0.974928, 0.500000, 0.977679, -0.000000, 0.217250, 0.976116, -0.309017, 1.000000, 0.951057, 0.451716, 0.992353, -0.308998, 0.011041, 0.950999, -0.301269, 1.222521, 0.927212, 0.458614, 0.971124, -0.301636, 0.217250, 0.928341, -0.587785, 1.000000, 0.809017, 0.408159, 0.970159, -0.587750, 0.011041, 0.808968, -0.573048, 1.222521, 0.788733, 0.421279, 0.952101, -0.573747, 0.217250, 0.789694, -0.809017, 1.000000, 0.587785, 0.373591, 0.935591, -0.808968, 0.011041, 0.587749, -0.788733, 1.222521, 0.573048, 0.391649, 0.922471, -0.789694, 0.217250, 0.573747, -0.951057, 1.000000, 0.309017, 0.351397, 0.892034, -0.950999, 0.011041, 0.308998, -0.927212, 1.222521, 0.301269, 0.372626, 0.885136, -0.928342, 0.217250, 0.301636, -1.000000, 1.000000, -0.000000, 0.343750, 0.843750, -0.999939, 0.011041, -0.000000, -0.974928, 1.222521, -0.000000, 0.366071, 0.843750, -0.976116, 0.217250, -0.000000, -0.951057, 1.000000, -0.309017, 0.351397, 0.795466, -0.950999, 0.011041, -0.308998, -0.927212, 1.222521, -0.301269, 0.372626, 0.802364, -0.928342, 0.217250, -0.301636, -0.809017, 1.000000, -0.587785, 0.373591, 0.751908, -0.808968, 0.011041, -0.587750, -0.788733, 1.222521, -0.573048, 0.391649, 0.765029, -0.789694, 0.217250, -0.573747, -0.587785, 1.000000, -0.809017, 0.408159, 0.717341, -0.587749, 0.011041, -0.808968, -0.573048, 1.222521, -0.788733, 0.421279, 0.735399, -0.573747, 0.217250, -0.789694, -0.587785, 1.000000, -0.809017, 0.408159, 0.717341, -0.587749, 0.011041, -0.808968, -0.309017, 1.000000, -0.951057, 0.451716, 0.695147, -0.308998, 0.011041, -0.950999, -0.301269, 1.222521, -0.927212, 0.458614, 0.716376, -0.301636, 0.217250, -0.928342, -0.000000, 1.000000, -1.000000, 0.500000, 0.687500, 0.000000, 0.011041, -0.999939, 0.000000, 1.222521, -0.974928, 0.500000, 0.709821, 0.000000, 0.217250, -0.976116, 0.309017, 1.000000, -0.951057, 0.548284, 0.695147, 0.308998, 0.011041, -0.950999, 0.301269, 1.222521, -0.927212, 0.541386, 0.716376, 0.301636, 0.217250, -0.928342, 0.587785, 1.000000, -0.809017, 0.591842, 0.717341, 0.587749, 0.011041, -0.808968, 0.573048, 1.222521, -0.788733, 0.578721, 0.735399, 0.573747, 0.217250, -0.789694, 0.587785, 1.000000, -0.809017, 0.591842, 0.717341, 0.587749, 0.011041, -0.808968, 0.809017, 1.000000, -0.587785, 0.626409, 0.751908, 0.808968, 0.011041, -0.587749, 0.788733, 1.222521, -0.573048, 0.608351, 0.765029, 0.789694, 0.217250, -0.573747, 0.951057, 1.000000, -0.309017, 0.648603, 0.795466, 0.950999, 0.011041, -0.308998, 0.927212, 1.222521, -0.301269, 0.627374, 0.802364, 0.928342, 0.217249, -0.301636, 1.000000, 1.000000, -0.000000, 0.656250, 0.843750, 0.999939, 0.011041, -0.000001, 0.974928, 1.222521, -0.000000, 0.633929, 0.843750, 0.976116, 0.217250, -0.000000, 0.728899, 1.433884, 0.529576, 0.590292, 0.909351, 0.732709, 0.423966, 0.532344, 0.856872, 1.433884, 0.278415, 0.606145, 0.878238, 0.861351, 0.423966, 0.279870, 0.529576, 1.433884, 0.728899, 0.565601, 0.934042, 0.532344, 0.423966, 0.732709, 0.278415, 1.433884, 0.856872, 0.534488, 0.949895, 0.279870, 0.423966, 0.861351, -0.000000, 1.433884, 0.900969, 0.500000, 0.955357, -0.000000, 0.423966, 0.905678, -0.278415, 1.433884, 0.856872, 0.465512, 0.949895, -0.279870, 0.423966, 0.861351, -0.529576, 1.433884, 0.728899, 0.434399, 0.934042, -0.532344, 0.423966, 0.732709, -0.728899, 1.433884, 0.529576, 0.409708, 0.909351, -0.732709, 0.423966, 0.532344, -0.856872, 1.433884, 0.278415, 0.393855, 0.878238, -0.861351, 0.423966, 0.279870, -0.900969, 1.433884, -0.000000, 0.388393, 0.843750, -0.905678, 0.423966, -0.000000, -0.856872, 1.433884, -0.278415, 0.393855, 0.809262, -0.861351, 0.423966, -0.279870, -0.728899, 1.433884, -0.529576, 0.409708, 0.778149, -0.732709, 0.423966, -0.532344, -0.529576, 1.433884, -0.728899, 0.434399, 0.753458, -0.532344, 0.423966, -0.732709, -0.278415, 1.433884, -0.856872, 0.465511, 0.737605, -0.279870, 0.423966, -0.861351, 0.000000, 1.433884, -0.900969, 0.500000, 0.732143, 0.000000, 0.423966, -0.905678, 0.278415, 1.433884, -0.856872, 0.534488, 0.737605, 0.279870, 0.423966, -0.861351, 0.529576, 1.433884, -0.728899, 0.565601, 0.753458, 0.532344, 0.423966, -0.732709, 0.728899, 1.433884, -0.529576, 0.590292, 0.778149, 0.732709, 0.423966, -0.532344, 0.856872, 1.433884, -0.278415, 0.606145, 0.809261, 0.861351, 0.423966, -0.279870, 0.900969, 1.433884, -0.000000, 0.611607, 0.843750, 0.905678, 0.423966, 0.000000, 0.632515, 1.623490, 0.459549, 0.572234, 0.896231, 0.641024, 0.610068, 0.465731, 0.743566, 1.623490, 0.241599, 0.584916, 0.871341, 0.753569, 0.610068, 0.244850, 0.459549, 1.623490, 0.632515, 0.552481, 0.915984, 0.465731, 0.610068, 0.641024, 0.241599, 1.623490, 0.743566, 0.527591, 0.928666, 0.244849, 0.610068, 0.753569, -0.000000, 1.623490, 0.781832, 0.500000, 0.933036, -0.000000, 0.610068, 0.792349, -0.241599, 1.623490, 0.743566, 0.472409, 0.928666, -0.244849, 0.610068, 0.753569, -0.459549, 1.623490, 0.632515, 0.447519, 0.915984, -0.465731, 0.610068, 0.641024, -0.632515, 1.623490, 0.459549, 0.427766, 0.896231, -0.641024, 0.610068, 0.465731, -0.743566, 1.623490, 0.241599, 0.415084, 0.871341, -0.753569, 0.610068, 0.244849, -0.781832, 1.623490, -0.000000, 0.410714, 0.843750, -0.792349, 0.610068, -0.000000, -0.743566, 1.623490, -0.241599, 0.415084, 0.816159, -0.753569, 0.610068, -0.244850, -0.632515, 1.623490, -0.459549, 0.427766, 0.791269, -0.641024, 0.610068, -0.465731, -0.459549, 1.623490, -0.632515, 0.447519, 0.771516, -0.465731, 0.610068, -0.641024, -0.241599, 1.623490, -0.743566, 0.472409, 0.758834, -0.244849, 0.610068, -0.753569, 0.000000, 1.623490, -0.781832, 0.500000, 0.754464, 0.000000, 0.610068, -0.792349, 0.241599, 1.623490, -0.743566, 0.527591, 0.758834, 0.244849, 0.610068, -0.753569, 0.459549, 1.623490, -0.632515, 0.552481, 0.771516, 0.465731, 0.610068, -0.641024, 0.632515, 1.623490, -0.459549, 0.572234, 0.791269, 0.641024, 0.610068, -0.465731, 0.743566, 1.623490, -0.241599, 0.584916, 0.816159, 0.753569, 0.610068, -0.244849, 0.781832, 1.623490, -0.000000, 0.589286, 0.843750, 0.792349, 0.610068, 0.000000, 0.504414, 1.781832, 0.366478, 0.554175, 0.883111, 0.519724, 0.766358, 0.377602, 0.592974, 1.781832, 0.192669, 0.563687, 0.864443, 0.610972, 0.766358, 0.198517, 0.366478, 1.781832, 0.504414, 0.539361, 0.897925, 0.377602, 0.766358, 0.519724, 0.192669, 1.781832, 0.592974, 0.520693, 0.907437, 0.198517, 0.766358, 0.610972, -0.000000, 1.781832, 0.623490, 0.500000, 0.910714, 0.000000, 0.766358, 0.642414, -0.192669, 1.781832, 0.592974, 0.479307, 0.907437, -0.198517, 0.766358, 0.610972, -0.366478, 1.781832, 0.504414, 0.460639, 0.897925, -0.377602, 0.766358, 0.519724, -0.504414, 1.781832, 0.366478, 0.445825, 0.883111, -0.519724, 0.766358, 0.377602, -0.592974, 1.781832, 0.192669, 0.436313, 0.864443, -0.610972, 0.766358, 0.198517, -0.623490, 1.781832, -0.000000, 0.433036, 0.843750, -0.642414, 0.766358, -0.000000, -0.592974, 1.781832, -0.192669, 0.436313, 0.823057, -0.610972, 0.766358, -0.198517, -0.504414, 1.781832, -0.366478, 0.445825, 0.804389, -0.519724, 0.766358, -0.377602, -0.366478, 1.781832, -0.504414, 0.460639, 0.789575, -0.377602, 0.766358, -0.519724, -0.192669, 1.781832, -0.592974, 0.479307, 0.780063, -0.198517, 0.766358, -0.610972, 0.000000, 1.781832, -0.623490, 0.500000, 0.776786, 0.000000, 0.766358, -0.642414, 0.192669, 1.781832, -0.592974, 0.520693, 0.780063, 0.198517, 0.766358, -0.610972, 0.366478, 1.781832, -0.504414, 0.539361, 0.789575, 0.377602, 0.766358, -0.519724, 0.504414, 1.781832, -0.366478, 0.554175, 0.804389, 0.519724, 0.766358, -0.377602, 0.592974, 1.781832, -0.192669, 0.563687, 0.823057, 0.610972, 0.766358, -0.198517, 0.623490, 1.781832, -0.000000, 0.566964, 0.843750, 0.642414, 0.766358, 0.000000, 0.351019, 1.900969, 0.255030, 0.536117, 0.869990, 0.376829, 0.884897, 0.273783, 0.412648, 1.900969, 0.134077, 0.542458, 0.857545, 0.442989, 0.884897, 0.143936, 0.255030, 1.900969, 0.351019, 0.526240, 0.879867, 0.273782, 0.884897, 0.376829, 0.134077, 1.900969, 0.412648, 0.513795, 0.886208, 0.143936, 0.884897, 0.442989, -0.000000, 1.900969, 0.433884, 0.500000, 0.888393, 0.000000, 0.884897, 0.465786, -0.134077, 1.900969, 0.412648, 0.486205, 0.886208, -0.143936, 0.884897, 0.442989, -0.255030, 1.900969, 0.351019, 0.473760, 0.879867, -0.273782, 0.884897, 0.376829, -0.351019, 1.900969, 0.255030, 0.463883, 0.869990, -0.376829, 0.884897, 0.273782, -0.412648, 1.900969, 0.134077, 0.457542, 0.857545, -0.442989, 0.884897, 0.143936, -0.433884, 1.900969, -0.000000, 0.455357, 0.843750, -0.465786, 0.884897, -0.000000, -0.412648, 1.900969, -0.134077, 0.457542, 0.829955, -0.442989, 0.884897, -0.143936, -0.351019, 1.900969, -0.255030, 0.463883, 0.817510, -0.376829, 0.884897, -0.273783, -0.255030, 1.900969, -0.351019, 0.473760, 0.807633, -0.273782, 0.884897, -0.376829, -0.134077, 1.900969, -0.412648, 0.486205, 0.801292, -0.143936, 0.884897, -0.442989, 0.000000, 1.900969, -0.433884, 0.500000, 0.799107, 0.000000, 0.884897, -0.465786, 0.134077, 1.900969, -0.412648, 0.513795, 0.801292, 0.143936, 0.884897, -0.442989, 0.255030, 1.900969, -0.351019, 0.526240, 0.807633, 0.273782, 0.884897, -0.376829, 0.351019, 1.900969, -0.255030, 0.536117, 0.817510, 0.376829, 0.884897, -0.273782, 0.412648, 1.900969, -0.134077, 0.542458, 0.829955, 0.442989, 0.884897, -0.143936, 0.433884, 1.900969, -0.000000, 0.544643, 0.843750, 0.465786, 0.884897, -0.000000, 0.180023, 1.974928, 0.130795, 0.518058, 0.856870, 0.229659, 0.958862, 0.166857, 0.211630, 1.974928, 0.068763, 0.521229, 0.850648, 0.269980, 0.958862, 0.087722, 0.130795, 1.974928, 0.180023, 0.513120, 0.861808, 0.166857, 0.958862, 0.229659, 0.068763, 1.974928, 0.211630, 0.506898, 0.864979, 0.087722, 0.958862, 0.269980, -0.000000, 1.974928, 0.222521, 0.500000, 0.866071, 0.000000, 0.958862, 0.283874, -0.068763, 1.974928, 0.211630, 0.493102, 0.864979, -0.087722, 0.958862, 0.269980, -0.130795, 1.974928, 0.180023, 0.486880, 0.861808, -0.166857, 0.958862, 0.229659, -0.180023, 1.974928, 0.130795, 0.481942, 0.856870, -0.229659, 0.958862, 0.166857, -0.211630, 1.974928, 0.068763, 0.478771, 0.850648, -0.269980, 0.958862, 0.087722, -0.222521, 1.974928, -0.000000, 0.477679, 0.843750, -0.283874, 0.958862, -0.000000, -0.211630, 1.974928, -0.068763, 0.478771, 0.836852, -0.269980, 0.958862, -0.087722, -0.180023, 1.974928, -0.130795, 0.481942, 0.830630, -0.229659, 0.958862, -0.166857, -0.130795, 1.974928, -0.180023, 0.486880, 0.825692, -0.166857, 0.958862, -0.229659, -0.068763, 1.974928, -0.211630, 0.493102, 0.822521, -0.087722, 0.958862, -0.269980, 0.000000, 1.974928, -0.222521, 0.500000, 0.821429, 0.000000, 0.958862, -0.283874, 0.068763, 1.974928, -0.211630, 0.506898, 0.822521, 0.087722, 0.958862, -0.269980, 0.130795, 1.974928, -0.180023, 0.513120, 0.825692, 0.166857, 0.958862, -0.229659, 0.180023, 1.974928, -0.130795, 0.518058, 0.830630, 0.229659, 0.958862, -0.166857, 0.211630, 1.974928, -0.068763, 0.521229, 0.836852, 0.269980, 0.958862, -0.087722, 0.222521, 1.974928, -0.000000, 0.522321, 0.843750, 0.283874, 0.958862, -0.000000, 0.000000, -2.000000, -0.000000, 0.500000, 0.150000, 0.000000, -1.000000, 0.000000, 0.000000, 2.000000, -0.000000, 0.500000, 0.837500, 0.000000, 1.000000, 0.000000, }; std::vector<unsigned int> indices = { 2,1,0, 3,2,0, 5,4,1, 2,5,1, 7,6,4, 5,7,4, 9,8,6, 7,9,6, 11,10,8, 9,11,8, 13,12,10, 11,13,10, 15,14,12, 13,15,12, 17,16,14, 15,17,14, 19,18,16, 17,19,16, 21,20,18, 19,21,18, 23,22,20, 21,23,20, 25,24,22, 23,25,22, 27,26,24, 25,27,24, 29,28,26, 27,29,26, 31,30,28, 29,31,28, 33,32,30, 31,33,30, 35,34,32, 33,35,32, 37,36,34, 35,37,34, 39,38,36, 37,39,36, 3,0,38, 39,3,38, 40,2,3, 41,40,3, 42,5,2, 40,42,2, 43,7,5, 42,43,5, 44,9,7, 43,44,7, 45,11,9, 44,45,9, 46,13,11, 45,46,11, 47,15,13, 46,47,13, 48,17,15, 47,48,15, 49,19,17, 48,49,17, 50,21,19, 49,50,19, 51,23,21, 50,51,21, 52,25,23, 51,52,23, 53,27,25, 52,53,25, 54,29,27, 53,54,27, 55,31,29, 54,55,29, 56,33,31, 55,56,31, 57,35,33, 56,57,33, 58,37,35, 57,58,35, 59,39,37, 58,59,37, 41,3,39, 59,41,39, 60,40,41, 61,60,41, 62,42,40, 60,62,40, 63,43,42, 62,63,42, 64,44,43, 63,64,43, 65,45,44, 64,65,44, 66,46,45, 65,66,45, 67,47,46, 66,67,46, 68,48,47, 67,68,47, 69,49,48, 68,69,48, 70,50,49, 69,70,49, 71,51,50, 70,71,50, 72,52,51, 71,72,51, 73,53,52, 72,73,52, 74,54,53, 73,74,53, 75,55,54, 74,75,54, 76,56,55, 75,76,55, 77,57,56, 76,77,56, 78,58,57, 77,78,57, 79,59,58, 78,79,58, 61,41,59, 79,61,59, 80,60,61, 81,80,61, 82,62,60, 80,82,60, 83,63,62, 82,83,62, 84,64,63, 83,84,63, 85,65,64, 84,85,64, 86,66,65, 85,86,65, 87,67,66, 86,87,66, 88,68,67, 87,88,67, 89,69,68, 88,89,68, 90,70,69, 89,90,69, 91,71,70, 90,91,70, 92,72,71, 91,92,71, 93,73,72, 92,93,72, 94,74,73, 93,94,73, 95,75,74, 94,95,74, 96,76,75, 95,96,75, 97,77,76, 96,97,76, 98,78,77, 97,98,77, 99,79,78, 98,99,78, 81,61,79, 99,81,79, 100,80,81, 101,100,81, 102,82,80, 100,102,80, 103,83,82, 102,103,82, 104,84,83, 103,104,83, 105,85,84, 104,105,84, 106,86,85, 105,106,85, 107,87,86, 106,107,86, 108,88,87, 107,108,87, 109,89,88, 108,109,88, 110,90,89, 109,110,89, 111,91,90, 110,111,90, 112,92,91, 111,112,91, 113,93,92, 112,113,92, 114,94,93, 113,114,93, 115,95,94, 114,115,94, 116,96,95, 115,116,95, 117,97,96, 116,117,96, 118,98,97, 117,118,97, 119,99,98, 118,119,98, 101,81,99, 119,101,99, 120,100,101, 121,120,101, 122,102,100, 120,122,100, 123,103,102, 122,123,102, 124,104,103, 123,124,103, 125,105,104, 124,125,104, 126,106,105, 125,126,105, 127,107,106, 126,127,106, 128,108,107, 127,128,107, 129,109,108, 128,129,108, 130,110,109, 129,130,109, 131,111,110, 130,131,110, 132,112,111, 131,132,111, 133,113,112, 132,133,112, 134,114,113, 133,134,113, 135,115,114, 134,135,114, 136,116,115, 135,136,115, 137,117,116, 136,137,116, 138,118,117, 137,138,117, 139,119,118, 138,139,118, 121,101,119, 139,121,119, 142,141,140, 143,142,140, 145,144,141, 142,145,141, 147,146,144, 145,147,144, 149,148,146, 147,149,146, 151,150,148, 149,151,148, 153,152,150, 151,153,150, 155,154,152, 153,155,152, 157,156,154, 155,157,154, 159,158,156, 157,159,156, 161,160,158, 159,161,158, 163,162,160, 161,163,160, 165,164,162, 163,165,162, 167,166,164, 165,167,164, 169,168,166, 167,169,166, 171,170,168, 169,171,168, 173,172,170, 171,173,170, 175,174,172, 173,175,172, 177,176,174, 175,177,174, 179,178,176, 177,179,176, 181,180,178, 179,181,178, 184,183,182, 185,184,182, 187,186,183, 184,187,183, 189,188,186, 187,189,186, 191,190,188, 189,191,188, 193,192,190, 191,193,190, 195,194,192, 193,195,192, 197,196,194, 195,197,194, 199,198,196, 197,199,196, 201,200,198, 199,201,198, 203,202,200, 201,203,200, 205,204,202, 203,205,202, 207,206,204, 205,207,204, 210,209,208, 207,210,208, 212,211,209, 210,212,209, 214,213,211, 212,214,211, 216,215,213, 214,216,213, 219,218,217, 216,219,217, 221,220,218, 219,221,218, 223,222,220, 221,223,220, 185,182,222, 223,185,222, 224,184,185, 225,224,185, 226,187,184, 224,226,184, 227,189,187, 226,227,187, 228,191,189, 227,228,189, 229,193,191, 228,229,191, 230,195,193, 229,230,193, 231,197,195, 230,231,195, 232,199,197, 231,232,197, 233,201,199, 232,233,199, 234,203,201, 233,234,201, 235,205,203, 234,235,203, 236,207,205, 235,236,205, 237,210,207, 236,237,207, 238,212,210, 237,238,210, 239,214,212, 238,239,212, 240,216,214, 239,240,214, 241,219,216, 240,241,216, 242,221,219, 241,242,219, 243,223,221, 242,243,221, 225,185,223, 243,225,223, 244,224,225, 245,244,225, 246,226,224, 244,246,224, 247,227,226, 246,247,226, 248,228,227, 247,248,227, 249,229,228, 248,249,228, 250,230,229, 249,250,229, 251,231,230, 250,251,230, 252,232,231, 251,252,231, 253,233,232, 252,253,232, 254,234,233, 253,254,233, 255,235,234, 254,255,234, 256,236,235, 255,256,235, 257,237,236, 256,257,236, 258,238,237, 257,258,237, 259,239,238, 258,259,238, 260,240,239, 259,260,239, 261,241,240, 260,261,240, 262,242,241, 261,262,241, 263,243,242, 262,263,242, 245,225,243, 263,245,243, 264,244,245, 265,264,245, 266,246,244, 264,266,244, 267,247,246, 266,267,246, 268,248,247, 267,268,247, 269,249,248, 268,269,248, 270,250,249, 269,270,249, 271,251,250, 270,271,250, 272,252,251, 271,272,251, 273,253,252, 272,273,252, 274,254,253, 273,274,253, 275,255,254, 274,275,254, 276,256,255, 275,276,255, 277,257,256, 276,277,256, 278,258,257, 277,278,257, 279,259,258, 278,279,258, 280,260,259, 279,280,259, 281,261,260, 280,281,260, 282,262,261, 281,282,261, 283,263,262, 282,283,262, 265,245,263, 283,265,263, 284,264,265, 285,284,265, 286,266,264, 284,286,264, 287,267,266, 286,287,266, 288,268,267, 287,288,267, 289,269,268, 288,289,268, 290,270,269, 289,290,269, 291,271,270, 290,291,270, 292,272,271, 291,292,271, 293,273,272, 292,293,272, 294,274,273, 293,294,273, 295,275,274, 294,295,274, 296,276,275, 295,296,275, 297,277,276, 296,297,276, 298,278,277, 297,298,277, 299,279,278, 298,299,278, 300,280,279, 299,300,279, 301,281,280, 300,301,280, 302,282,281, 301,302,281, 303,283,282, 302,303,282, 285,265,283, 303,285,283, 304,284,285, 305,304,285, 306,286,284, 304,306,284, 307,287,286, 306,307,286, 308,288,287, 307,308,287, 309,289,288, 308,309,288, 310,290,289, 309,310,289, 311,291,290, 310,311,290, 312,292,291, 311,312,291, 313,293,292, 312,313,292, 314,294,293, 313,314,293, 315,295,294, 314,315,294, 316,296,295, 315,316,295, 317,297,296, 316,317,296, 318,298,297, 317,318,297, 319,299,298, 318,319,298, 320,300,299, 319,320,299, 321,301,300, 320,321,300, 322,302,301, 321,322,301, 323,303,302, 322,323,302, 305,285,303, 323,305,303, 324,0,1, 324,1,4, 324,4,6, 324,6,8, 324,8,10, 324,10,12, 324,12,14, 324,14,16, 324,16,18, 324,18,20, 324,20,22, 324,22,24, 324,24,26, 324,26,28, 324,28,30, 324,30,32, 324,32,34, 324,34,36, 324,36,38, 324,38,0, 325,304,305, 325,306,304, 325,307,306, 325,308,307, 325,309,308, 325,310,309, 325,311,310, 325,312,311, 325,313,312, 325,314,313, 325,315,314, 325,316,315, 325,317,316, 325,318,317, 325,319,318, 325,320,319, 325,321,320, 325,322,321, 325,323,322, 325,305,323, }; std::unique_ptr<Cookie::Resources::Mesh> capsule = std::make_unique<Cookie::Resources::Mesh>("Capsule", vertices, indices, indices.size()); return capsule; } } } } #endif
43.669275
145
0.602697
[ "mesh", "vector" ]
84eb8dbabccffd689fa772a837e19bd5ae5a4a96
8,663
cpp
C++
Oem/DWFTK/develop/global/src/dwf/package/Object.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/DWFTK/develop/global/src/dwf/package/Object.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/DWFTK/develop/global/src/dwf/package/Object.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (c) 2005-2006 by Autodesk, Inc. // // By using this code, you are agreeing to the terms and conditions of // the License Agreement included in the documentation for this code. // // AUTODESK MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AS TO THE CORRECTNESS // OF THIS CODE OR ANY DERIVATIVE WORKS WHICH INCORPORATE IT. AUTODESK // PROVIDES THE CODE ON AN "AS-IS" BASIS AND EXPLICITLY DISCLAIMS ANY // LIABILITY, INCLUDING CONSEQUENTIAL AND INCIDENTAL DAMAGES FOR ERRORS, // OMISSIONS, AND OTHER PROBLEMS IN THE CODE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer Software // Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) (Rights in Technical // Data and Computer Software), as applicable. // // $Header: //DWF/Development/Components/Internal/DWF Toolkit/v7.7/develop/global/src/dwf/package/Object.cpp#1 $ // $DateTime: 2011/02/14 01:16:30 $ // $Author: caos $ // $Change: 197964 $ // $Revision: #1 $ // #include "dwf/package/Object.h" #include "dwf/package/Entity.h" #include "dwf/package/Constants.h" #include "dwf/package/writer/PackageWriter.h" using namespace DWFToolkit; _DWFTK_API DWFObject::DWFObject( const DWFString& zID, DWFEntity* pEntity, DWFContent* pContent ) throw( DWFInvalidArgumentException ) : DWFRenderable( zID, pContent ) , _pEntity( pEntity ) , _pParent( NULL ) , _oChildren() , _oFeatures() { if (zID.chars() == 0) { _DWFCORE_THROW( DWFInvalidArgumentException, /*NOXLATE*/L"An new object ID was not provided" ); } if (pEntity == NULL) { _DWFCORE_THROW( DWFInvalidArgumentException, /*NOXLATE*/L"Objects cannot be created without a valid entity" ); } } _DWFTK_API DWFObject::DWFObject() throw() : DWFRenderable( /*NOXLATE*/L"" ) , _pEntity( NULL ) , _pParent( NULL ) , _oChildren() , _oFeatures() { } _DWFTK_API DWFObject::~DWFObject() throw() { } _DWFTK_API void DWFObject::parseAttributeList( const char** ppAttributeList, tUnresolvedList& rUnresolved ) throw( DWFException ) { if (ppAttributeList == NULL) { _DWFCORE_THROW( DWFInvalidArgumentException, /*NOXLATE*/L"No attributes provided" ); } DWFPropertySet::parseAttributeList( ppAttributeList, rUnresolved ); unsigned char nFound = 0; size_t iAttrib = 0; const char* pAttrib = NULL; for(; ppAttributeList[iAttrib]; iAttrib += 2) { pAttrib = &ppAttributeList[iAttrib][0]; // // get the entity reference // if (!(nFound & 0x01) && (DWFCORE_COMPARE_ASCII_STRINGS(pAttrib, DWFXML::kzAttribute_EntityRef) == 0)) { nFound |= 0x01; rUnresolved.push_back( tUnresolved(eEntityReference, DWFString(ppAttributeList[iAttrib+1])) ); } // // get the feature references // if (!(nFound & 0x02) && (DWFCORE_COMPARE_ASCII_STRINGS(pAttrib, DWFXML::kzAttribute_FeatureRefs) == 0)) { nFound |= 0x02; rUnresolved.push_back( tUnresolved(eFeatureReferences, DWFString(ppAttributeList[iAttrib+1])) ); } } } #ifndef DWFTK_READ_ONLY _DWFTK_API void DWFObject::_serializeAttributes( DWFXMLSerializer& rSerializer, unsigned int nFlags ) throw( DWFException ) { // // First let the base class serialize it attributes // DWFContentElement::_serializeAttributes( rSerializer, nFlags ); // // Serialize the entity reference. // if (_pEntity) { rSerializer.addAttribute( DWFXML::kzAttribute_EntityRef, _pEntity->id() ); } else { _DWFCORE_THROW( DWFNullPointerException, /*NOXLATE*/L"The entity reference in object should not be NULL" ); } // // Serialize any feature references. // if (_oFeatures.size() > 0) { DWFFeature::tIterator* piFeature = _oFeatures.iterator(); if (piFeature) { // // String together all the references // DWFString zReferences; DWFFeature* pReference = NULL; for (; piFeature->valid(); piFeature->next()) { pReference = piFeature->get(); zReferences.append( pReference->id() ); zReferences.append( /*NOXLATE*/L" " ); } if (zReferences.chars() > 0) { rSerializer.addAttribute( DWFXML::kzAttribute_FeatureRefs, zReferences ); } DWFCORE_FREE_OBJECT( piFeature ); } } } _DWFTK_API void DWFObject::_serializeXML( DWFXMLSerializer& rSerializer, unsigned int nFlags ) throw( DWFException ) { if (nFlags & DWFPackageWriter::eGlobalContent) { // // Open the object element // DWFString zNamespace( _oSerializer.namespaceXML( nFlags ) ); rSerializer.startElement( DWFXML::kzElement_Object, zNamespace ); // // Serialize attributes // _serializeAttributes( rSerializer, nFlags ); // // Serialize child elements // { // // Let baseclass know not to start a new XML element // bool bElementOpenFlag = false; if (nFlags & DWFXMLSerializer::eElementOpen) { bElementOpenFlag = true; } else { nFlags |= DWFXMLSerializer::eElementOpen; } DWFContentElement::_serializeXML( rSerializer, nFlags ); if (bElementOpenFlag == false) { // // Unset the element open bit to allow proper ending // nFlags &= ~DWFXMLSerializer::eElementOpen; } // // Serialize the child objects recursively as subnodes in the XML tree. // We can safely do this since objects can have only one parent. This // will speed up the load, since we can setup the relationships without // having to do a second pass. // if (_oChildren.size() > 0) { DWFObject::tIterator* piChild = _oChildren.iterator(); if (piChild) { for (; piChild->valid(); piChild->next()) { DWFObject* pChild = piChild->get(); pChild->getSerializable().serializeXML( rSerializer, nFlags ); } DWFCORE_FREE_OBJECT( piChild ); } } } rSerializer.endElement(); } } #endif _DWFTK_API void DWFObject::insertPropertyAncestors( DWFContentElement::tVector& rAncestorElements ) const throw() { rAncestorElements.push_back( _pEntity ); } _DWFTK_API void DWFObject::_addChild( DWFObject* pObject ) throw() { DWFObject* pPreviousParent = pObject->getParent(); // // Do something only if this isn't already the parent. // if (pPreviousParent != this) { // // Remove the existing parent-child relationship. // if (pPreviousParent != NULL) pPreviousParent->_removeChild( pObject ); // // Go ahead and setup the relationship pObject->_pParent = this; _oChildren.push_back( pObject ); } } _DWFTK_API bool DWFObject::_removeChild( DWFObject* pObject ) throw() { DWFOrderedVector<size_t> oIndices; size_t iLocation; if (_oChildren.findFirst( pObject, iLocation )) { // // Unset the parent informaton on the child before erasing. // _oChildren[ iLocation ]->_pParent = NULL; _oChildren.erase( pObject ); return true; } else { return false; } } _DWFTK_API void DWFObject::_removeChildren() throw() { // // Unset all parent information first. // for (size_t i=0; i<_oChildren.size(); ++i) { _oChildren[i]->_pParent = NULL; } _oChildren.clear(); }
27.589172
119
0.558698
[ "object" ]
84ecc7efbe171cd7cb70271c733dbdadbff5617c
1,630
hxx
C++
main/vcl/inc/vcl/taskpanelist.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/vcl/inc/vcl/taskpanelist.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/vcl/inc/vcl/taskpanelist.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SV_TASKPANELIST_HXX #define _SV_TASKPANELIST_HXX #include <vcl/dllapi.h> #include <vector> #include <vcl/window.hxx> class VCL_DLLPUBLIC TaskPaneList { ::std::vector<Window *> mTaskPanes; Window *FindNextPane( Window *pWindow, sal_Bool bForward = sal_True ); Window *FindNextFloat( Window *pWindow, sal_Bool bForward = sal_True ); Window *FindNextSplitter( Window *pWindow, sal_Bool bForward = sal_True ); //#if 0 // _SOLAR__PRIVATE public: sal_Bool IsInList( Window *pWindow ); //#endif public: TaskPaneList(); ~TaskPaneList(); void AddWindow( Window *pWindow ); void RemoveWindow( Window *pWindow ); sal_Bool HandleKeyEvent( KeyEvent aKeyEvent ); }; #endif
30.185185
75
0.687117
[ "vector" ]
84f4a0fe68bc442847e1f6a47d26701211b432f0
700
cpp
C++
atcoder/nomura2020_c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/nomura2020_c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/nomura2020_c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll=long long; void solve() { int n; cin >> n; vector<int> a(n + 1); for (auto& x: a) cin >> x; vector<ll> l(n+2), r(n+2); // lower/upper bound for (int i = n; i >= 0; i--) { l[i] = a[i] + (l[i+1]+1)/2; r[i] = a[i] + r[i+1]; if(i < 60) r[i] = min(r[i], 1ll<<i); // can (n*1e8 = 1e13) if (l[i] > r[i]) { cout << -1; return; } } ll res = 0; for (int i = 0; i <= n; i++) { res += r[i]; r[i+1] = min(r[i+1], (r[i]-a[i])*2ll); } cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
21.212121
66
0.417143
[ "vector" ]
84f605a7a9dc98f56f8cdfbdcfbe23881918629f
8,914
cpp
C++
src/navigation/path_planning/local_planner/src/dynamic_window_approach.cpp
venkisagunner93/beertender_robot
84de7442b815b02f90ff47f41d93157786c1a0a7
[ "MIT" ]
3
2021-08-05T03:43:08.000Z
2022-03-09T02:35:22.000Z
src/navigation/path_planning/local_planner/src/dynamic_window_approach.cpp
venkisagunner93/robot_navigation
84de7442b815b02f90ff47f41d93157786c1a0a7
[ "MIT" ]
21
2021-04-22T06:31:08.000Z
2022-03-21T04:34:01.000Z
src/navigation/path_planning/local_planner/src/dynamic_window_approach.cpp
venkisagunner93/robot_navigation
84de7442b815b02f90ff47f41d93157786c1a0a7
[ "MIT" ]
2
2021-08-05T03:43:35.000Z
2021-08-05T13:06:53.000Z
#include "local_planner/dynamic_window_approach.h" DWA::DWA(ros::NodeHandle* nh, std::string action_name) : as_(*nh, action_name, boost::bind(&DWA::performLocalPlanning, this, _1), false) , action_name_(action_name) , prev_time_(ros::Time::now()) { is_joystick_active_ = false; joy_subscriber_ = nh->subscribe("joy", 1, &DWA::joyCallback, this); trajectory_publisher_ = nh->advertise<nav_msgs::Path>("nav/local_trajectory", 1); cmd_vel_publisher_ = nh->advertise<ackermann_msgs::AckermannDrive>("cmd_vel", 1); // Load configurations loadDWAConfig(nh); reconfig_server_.reset(new dynamic_reconfigure::Server<local_planner::DWAConfig>()); dynamic_reconfigure::Server<local_planner::DWAConfig>::CallbackType f = boost::bind(&DWA::reconfigCallback, this, _1, _2); reconfig_server_->setCallback(f); zero_u_.speed = 0.0; zero_u_.steering_angle_velocity = 0.0; // Loading initial state of the robot nh->param<float>("robot_sim/init_state/x", state_.x, 0.0); nh->param<float>("robot_sim/init_state/y", state_.y, 0.0); nh->param<float>("robot_sim/init_state/theta", state_.theta, M_PI / 2); nh->param<float>("robot_sim/init_state/v", state_.v, 0.0); nh->param<float>("robot_sim/init_state/w", state_.w, 0.0); as_.start(); } void DWA::broadcastCurrentPose() { if (is_joystick_active_) { float y = joy_.axes[0]; float x = joy_.axes[1]; int turbo = joy_.buttons[7]; ackermann_msgs::AckermannDrive u; u.speed = x * (0.2 + turbo * 0.5); u.steering_angle_velocity = y * (0.2 + turbo * 0.4); updateStateAndPublish(u); } } void DWA::joyCallback(const sensor_msgs::JoyConstPtr& msg) { { std::lock_guard<std::mutex> lock(joy_mutex_); is_joystick_active_ = true; } joy_ = *msg; } void DWA::loadDWAConfig(ros::NodeHandle* nh) { // Loading all DWA configuration parameters nh->param<float>("local_planner/sim_time", config_.sim_time, 2.0); nh->param<float>("local_planner/dt", config_.dt, 0.05); nh->param<float>("local_planner/goal_region", config_.goal_region, 0.05); nh->param<int>("local_planner/window_size", config_.window_size, 5); nh->param<int>("local_planner/loop_rate", config_.loop_rate, 100); config_.sim_samples = static_cast<int>(config_.sim_time / config_.dt); // Loading all DWA gains nh->param<float>("local_planner/gains/distance_to_goal_gain", config_.gains.distance_to_goal_gain, 1.0); nh->param<int>("local_planner/gains/obstacle_gain", config_.gains.obstacle_gain, 1); nh->param<int>("local_planner/gains/max_velocity_gain", config_.gains.max_velocity_gain, 1); // Loading all DWA limits nh->param<float>("local_planner/limits/min_v", config_.limits.min_v, 0.025); nh->param<float>("local_planner/limits/max_v", config_.limits.max_v, 0.2); nh->param<float>("local_planner/limits/min_w", config_.limits.min_w, -0.7); nh->param<float>("local_planner/limits/max_w", config_.limits.max_w, 0.7); nh->param<float>("local_planner/limits/max_v_dot", config_.limits.max_v_dot, 0.01); nh->param<float>("local_planner/limits/max_w_dot", config_.limits.max_w_dot, 1.0); nh->param<float>("local_planner/limits/max_theta", config_.limits.max_theta, 0.5235); } void DWA::reconfigCallback(local_planner::DWAConfig& config, uint32_t level) { config_.limits.min_v = static_cast<float>(config.min_v); config_.limits.max_v = static_cast<float>(config.max_v); config_.limits.min_w = static_cast<float>(config.min_w); config_.limits.max_w = static_cast<float>(config.max_w); config_.limits.max_v_dot = static_cast<float>(config.max_v_dot); config_.limits.max_w_dot = static_cast<float>(config.max_w_dot); config_.limits.max_theta = static_cast<float>(config.max_theta); } std::vector<ackermann_msgs::AckermannDrive> DWA::generateVelocitySamples() { std::vector<ackermann_msgs::AckermannDrive> u_vec; float min_v = std::max((state_.v - config_.limits.max_v_dot * config_.dt), config_.limits.min_v); float max_v = std::min((state_.v + config_.limits.max_v_dot * config_.dt), config_.limits.max_v); float min_w = std::max((state_.w - config_.limits.max_w_dot * config_.dt), config_.limits.min_w); float max_w = std::min((state_.w + config_.limits.max_w_dot * config_.dt), config_.limits.max_w); float v_step = (max_v + abs(min_v)) / (config_.window_size - 1); float w_step = (max_w + abs(min_w)) / (config_.window_size - 1); float v_samples[config_.window_size]; float w_samples[config_.window_size]; for (int i = 0; i < config_.window_size; i++) { v_samples[i] = min_v + i * v_step; } for (int i = 0; i < config_.window_size; i++) { w_samples[i] = min_w + i * w_step; } for (int i = 0; i < config_.window_size; i++) { for (int j = 0; j < config_.window_size; j++) { ackermann_msgs::AckermannDrive u; u.speed = v_samples[i]; u.steering_angle_velocity = w_samples[j]; u_vec.push_back(u); } } return u_vec; } nav_msgs::Path DWA::simulateTrajectory(const ackermann_msgs::AckermannDrive& u) { nav_msgs::Path trajectory; trajectory.header.stamp = ros::Time::now(); trajectory.header.frame_id = PARENT_FRAME; robot_utils::State sim_state = state_; for (int i = 0; i < config_.sim_samples; i++) { geometry_msgs::PoseStamped pose; updateState(sim_state, u.speed, u.steering_angle_velocity, config_.dt); pose.pose.position.x = sim_state.x; pose.pose.position.y = sim_state.y; tf2::Quaternion q; q.setRPY(0, 0, sim_state.theta); pose.pose.orientation.x = q.x(); pose.pose.orientation.y = q.y(); pose.pose.orientation.z = q.z(); pose.pose.orientation.w = q.w(); trajectory.poses.push_back(pose); } return trajectory; } float DWA::calculateGoalDistanceCost(const nav_msgs::Path& trajectory, const geometry_msgs::PoseStamped& goal) { float cost = 1e5; if (!trajectory.poses.empty()) { geometry_msgs::PoseStamped simulated_trajectory_end = trajectory.poses.back(); cost = config_.gains.distance_to_goal_gain * sqrt(pow((simulated_trajectory_end.pose.position.x - goal.pose.position.x), 2) + pow((simulated_trajectory_end.pose.position.y - goal.pose.position.y), 2)); } return cost; } float DWA::calculateMaxVelocityCost(const ackermann_msgs::AckermannDrive& u) { return config_.gains.max_velocity_gain * (config_.limits.max_v - u.speed); } bool DWA::isInsideGoalRegion(const geometry_msgs::PoseStamped& goal) { float distance_to_goal = 1e5; geometry_msgs::PoseStamped current_pose; if (tf_helper_.getCurrentPoseFromTF(PARENT_FRAME, CHILD_FRAME, &current_pose)) { feedback_.current_pose = current_pose; as_.publishFeedback(feedback_); distance_to_goal = sqrt(pow((current_pose.pose.position.x - goal.pose.position.x), 2) + pow((current_pose.pose.position.y - goal.pose.position.y), 2)); } return distance_to_goal <= config_.goal_region; } void DWA::updateStateAndPublish(const ackermann_msgs::AckermannDrive& msg) { ros::Duration dt = ros::Time::now() - prev_time_; prev_time_ = ros::Time::now(); updateState(state_, msg.speed, msg.steering_angle_velocity, dt.toSec()); cmd_vel_publisher_.publish(msg); } void DWA::performLocalPlanning(const nav_utils::ReachGlobalPoseGoalConstPtr& goal) { result_.has_reached = false; ros::Rate rate(config_.loop_rate); while (ros::ok()) { { std::lock_guard<std::mutex> lock(joy_mutex_); if (is_joystick_active_) { is_joystick_active_ = false; as_.setAborted(result_); return; } } if (as_.isPreemptRequested()) { break; } if (!isInsideGoalRegion(goal->goal)) { float trajectory_cost = 0.0; float lowest_cost = 1e6; ackermann_msgs::AckermannDrive best_u; std::vector<ackermann_msgs::AckermannDrive> u_vec = generateVelocitySamples(); for (int i = 0; i < u_vec.size(); i++) { nav_msgs::Path trajectory = simulateTrajectory(u_vec[i]); float cost = calculateGoalDistanceCost(trajectory, goal->goal) + calculateMaxVelocityCost(u_vec[i]); if (cost < lowest_cost) { lowest_cost = cost; best_u = u_vec[i]; } trajectory_publisher_.publish(trajectory); } if (best_u.speed >= config_.limits.max_v) { best_u.speed = config_.limits.max_v; } if (best_u.steering_angle_velocity >= config_.limits.max_w) { best_u.steering_angle_velocity = config_.limits.max_w; } updateStateAndPublish(best_u); } else { result_.has_reached = true; updateStateAndPublish(zero_u_); as_.setSucceeded(result_); break; } rate.sleep(); } if (!result_.has_reached) { updateStateAndPublish(zero_u_); as_.setAborted(result_); } }
31.72242
100
0.685775
[ "vector" ]
84f8505b9576cfbe82eb82e15e1e09332eef4fbf
5,830
hpp
C++
include/bslam/utils/geometry/Line.hpp
JoachimClemens/Beta-SLAM
eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa
[ "BSD-3-Clause" ]
3
2019-01-17T21:47:05.000Z
2021-08-17T05:44:44.000Z
include/bslam/utils/geometry/Line.hpp
JoachimClemens/Beta-SLAM
eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa
[ "BSD-3-Clause" ]
null
null
null
include/bslam/utils/geometry/Line.hpp
JoachimClemens/Beta-SLAM
eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa
[ "BSD-3-Clause" ]
2
2019-02-16T01:37:14.000Z
2019-11-20T11:13:21.000Z
/* * Software License Agreement (BSD License) * * Beta-SLAM - Simultaneous localization and grid mapping with beta distributions * Copyright (c) 2013-2019, Joachim Clemens, Thomas Reineking, Tobias Kluth * 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 BSLAM 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. */ namespace bslam { // Declaration of specialized methods template<> inline void Line<2>::bresenham( const Point2m &start, const Point2m &end ); template<> inline void Line<3>::bresenham( const Point3m &start, const Point3m &end ); template<int N> Line<N>::Line( const Pointm<N> &start, const Pointm<N> &end ) { bresenham( start, end ); } template<int N> Line<N>::~Line() { // Nothing to do here } template<int N> void Line<N>::extend( const Pointm<N> &end ) { Pointm<N> start = this->back(); this->pop_back(); // do not add the last point twice bresenham( start, end ); } template<int N> inline void Line<N>::bresenham( const Pointm<N> &start, const Pointm<N> &end ) { static_assert( N != 2 && N != 3, "Specialization needed for this N." ); } template<> inline void Line<2>::bresenham( const Point2m &start, const Point2m &end ) { // 2D Bresenham's algorithm according to https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm int dx = abs( (int) end[0] - (int) start[0] ), dy = abs( (int) end[1] - (int) start[1] ), sx = (start[0] < end[0]) ? 1 : -1, sy = (start[1] < end[1]) ? 1 : -1, err = dx - dy, e2; Point2m cur = start; // reserve some memory reserve( size() + sqrt( (end - start).squaredNorm() ) + 2 ); // Eigen norm() doesn't work for integer types, so calc sqrt separately while( true ) { push_back( cur ); if( cur == end ) break; e2 = 2*err; if( e2 > -dy ) { err -= dy; cur[0] += sx; if( cur == end ) { push_back( cur ); break; } } if( e2 < dx ) { err += dx; cur[1] += sy; } } } template<> inline void Line<3>::bresenham( const Point3m &start, const Point3m &end ) { /* * 3D Bresenham's algorithm according to https://gist.githubusercontent.com/yamamushi/5823518/raw/6571ec0fa01d2e3378a9f5bdebdd9c41b176f4ed/bresenham3d * * A slightly modified version of the source found at * http://www.ict.griffith.edu.au/anthony/info/graphics/bresenham.procs * Provided by Anthony Thyssen, though he does not take credit for the original implementation * * It is highly likely that the original Author was Bob Pendelton, as referenced here * * ftp://ftp.isc.org/pub/usenet/comp.sources.unix/volume26/line3d * * line3d was dervied from DigitalLine.c published as "Digital Line Drawing" * by Paul Heckbert from "Graphics Gems", Academic Press, 1990 * * 3D modifications by Bob Pendleton. The original source code was in the public * domain, the author of the 3D version places his modifications in the * public domain as well. * * line3d uses Bresenham's algorithm to generate the 3 dimensional points on a * line from (x1, y1, z1) to (x2, y2, z2) */ int dx = end[0] - start[0], dy = end[1] - start[1], dz = end[2] - start[2], sx = (dx < 0) ? -1 : 1, sy = (dy < 0) ? -1 : 1, sz = (dz < 0) ? -1 : 1, l = abs( dx ), m = abs( dy ), n = abs( dz ), dx2 = l << 1, dy2 = m << 1, dz2 = n << 1, err1, err2, i; Point3m cur = start; // reserve some memory reserve( size() + sqrt( (end - start).squaredNorm() ) + 2 ); // Eigen norm() doesn't work for integer types, so calc sqrt separately if( (l >= m) && (l >= n) ) { err1 = dy2 - l; err2 = dz2 - l; for( i = 0; i < l; i++ ) { push_back( cur ); if( err1 > 0 ) { cur[1] += sy; err1 -= dx2; } if( err2 > 0 ) { cur[2] += sz; err2 -= dx2; } err1 += dy2; err2 += dz2; cur[0] += sx; } } else if( (m >= l) && (m >= n) ) { err1 = dx2 - m; err2 = dz2 - m; for( i = 0; i < m; i++ ) { push_back( cur ); if( err1 > 0 ) { cur[0] += sx; err1 -= dy2; } if( err2 > 0 ) { cur[2] += sz; err2 -= dy2; } err1 += dx2; err2 += dz2; cur[1] += sy; } } else { err1 = dy2 - n; err2 = dx2 - n; for( i = 0; i < n; i++ ) { push_back( cur ); if( err1 > 0 ) { cur[1] += sy; err1 -= dz2; } if( err2 > 0 ) { cur[0] += sx; err2 -= dz2; } err1 += dy2; err2 += dx2; cur[2] += sz; } } push_back( cur ); } } /* namespace bslam */
24.91453
151
0.62813
[ "3d" ]
ebce4e1228c334c61b43ee67f44c5b41cfcdfe14
4,817
cpp
C++
ZeroVulkan/src/Vulkan/Device.cpp
Greyrat7490/ZeroVulkan
446fde4f21749cbc5449023f691e942759b3cf97
[ "MIT" ]
null
null
null
ZeroVulkan/src/Vulkan/Device.cpp
Greyrat7490/ZeroVulkan
446fde4f21749cbc5449023f691e942759b3cf97
[ "MIT" ]
2
2021-09-26T16:20:00.000Z
2022-03-21T14:08:34.000Z
ZeroVulkan/src/Vulkan/Device.cpp
Greyrat7490/ZeroVulkan
446fde4f21749cbc5449023f691e942759b3cf97
[ "MIT" ]
null
null
null
#include "Device.h" #include "Surface.h" #include "Swapchain.h" #include "SyncObjects.h" namespace ZeroVulkan::ZDevice { // ------------------- // Device // ------------------- static VkDevice s_dev = nullptr; static VkInstance s_instance = nullptr; static VkPhysicalDevice* s_physicalDevices = nullptr; static VkQueue s_queue = nullptr; // ------------------- static ZCommandPool* s_commandPool = nullptr; //default commandPool ( used for graphics queue ) static VkSampler s_sampler = nullptr; // ------------------- // Device // ------------------- VkDevice getDevice() { return s_dev; } VkInstance getInstance() { return s_instance; } VkPhysicalDevice* getPhysicalDev() { return s_physicalDevices; } VkQueue& getQueue() { return s_queue; } // ------------------- VkSampler& getSampler() { return s_sampler; } ZCommandPool* getCommandPool() { return s_commandPool; } void clear() { vkDeviceWaitIdle(s_dev); SyncObjects::clear(); delete s_commandPool; vkDestroySampler(s_dev, s_sampler, nullptr); Swapchain::clear(); Surface::clear(); vkDestroyDevice(s_dev, nullptr); vkDestroyInstance(s_instance, nullptr); delete[] s_physicalDevices; } void createInstance(); void getPhysicalDevices(); void init() { createInstance(); getPhysicalDevices(); float queuePriority[] = { 1.0f, 1.0f, 1.0f, 1.0f }; VkDeviceQueueCreateInfo devQueueCreateInfo; devQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; devQueueCreateInfo.pNext = nullptr; devQueueCreateInfo.flags = 0; devQueueCreateInfo.queueFamilyIndex = 0; //TODO: choose proper index devQueueCreateInfo.queueCount = 1; //TODO: check how many queues are avaible devQueueCreateInfo.pQueuePriorities = queuePriority; VkPhysicalDeviceFeatures usedFeatures = {}; usedFeatures.samplerAnisotropy = true; usedFeatures.fillModeNonSolid = true; usedFeatures.wideLines = true; const std::vector<const char*> devExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; VkDeviceCreateInfo devCreateInfo; devCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; devCreateInfo.pNext = nullptr; devCreateInfo.flags = 0; devCreateInfo.queueCreateInfoCount = 1; devCreateInfo.pQueueCreateInfos = &devQueueCreateInfo; devCreateInfo.enabledLayerCount = 0; devCreateInfo.ppEnabledLayerNames = nullptr; devCreateInfo.enabledExtensionCount = static_cast<uint32_t>(devExtensions.size()); devCreateInfo.ppEnabledExtensionNames = devExtensions.data(); devCreateInfo.pEnabledFeatures = &usedFeatures; VkResult res = vkCreateDevice(s_physicalDevices[0], &devCreateInfo, nullptr, &s_dev); if (res != VK_SUCCESS) printf("create device ERROR: %d\n", res); //change later to a proper index vkGetDeviceQueue(s_dev, 0, 0, &s_queue); printf("created ZDevice\n"); s_commandPool = new ZCommandPool(); } void getPhysicalDevices() { uint32_t devCount; vkEnumeratePhysicalDevices(s_instance, &devCount, nullptr); s_physicalDevices = new VkPhysicalDevice[devCount]; vkEnumeratePhysicalDevices(s_instance, &devCount, s_physicalDevices); } void createInstance() { #ifdef Z_DEBUG const char* layerNames[1] = { "VK_LAYER_KHRONOS_validation" }; const uint32_t layerCount = 1; #else const char** layerNames = nullptr; const uint32_t layerCount = 0; #endif const char* KHRSurfaceExtension[2] = { "VK_KHR_surface", "VK_KHR_xlib_surface" }; VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "App"; appInfo.applicationVersion = VK_MAKE_VERSION( 0, 0, 1 ); appInfo.pEngineName = "ZeroVulkan"; appInfo.engineVersion = VK_MAKE_VERSION( 0, 0, 1 ); appInfo.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo instanceInfo = {}; instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceInfo.pApplicationInfo = &appInfo; instanceInfo.enabledLayerCount = layerCount; instanceInfo.ppEnabledLayerNames = layerNames; instanceInfo.enabledExtensionCount = 2; instanceInfo.ppEnabledExtensionNames = KHRSurfaceExtension; VkResult res = vkCreateInstance(&instanceInfo, nullptr, &s_instance); if (res != VK_SUCCESS ) printf("create instance ERROR: %d\n", res); } }
32.328859
99
0.646253
[ "vector" ]
ebd14c2c5023f73e63ef1897812d9b0ec8cfca04
2,849
cpp
C++
python/pyngraph/runtime/backend.cpp
csullivan/ngraph-1
1c4aa2257447cf8c9034d24fc1a1ef9ba468fdfb
[ "Apache-2.0" ]
null
null
null
python/pyngraph/runtime/backend.cpp
csullivan/ngraph-1
1c4aa2257447cf8c9034d24fc1a1ef9ba468fdfb
[ "Apache-2.0" ]
null
null
null
python/pyngraph/runtime/backend.cpp
csullivan/ngraph-1
1c4aa2257447cf8c9034d24fc1a1ef9ba468fdfb
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "ngraph/runtime/backend.hpp" #include "ngraph/runtime/tensor.hpp" #include "pyngraph/runtime/backend.hpp" namespace py = pybind11; void regclass_pyngraph_runtime_Backend(py::module m) { py::class_<ngraph::runtime::Backend, std::unique_ptr<ngraph::runtime::Backend>> backend( m, "Backend"); backend.doc() = "ngraph.impl.runtime.Backend wraps ngraph::runtime::Backend"; backend.def_static("create", &ngraph::runtime::Backend::create); backend.def_static("get_registered_devices", &ngraph::runtime::Backend::get_registered_devices); backend.def("create_tensor", (std::shared_ptr<ngraph::runtime::Tensor>(ngraph::runtime::Backend::*)( const ngraph::element::Type&, const ngraph::Shape&)) & ngraph::runtime::Backend::create_tensor); backend.def("compile", (void (ngraph::runtime::Backend::*)(std::shared_ptr<ngraph::Function>)) & ngraph::runtime::Backend::compile); backend.def("call", (void (ngraph::runtime::Backend::*)( std::shared_ptr<ngraph::Function>, const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>&, const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>&)) & ngraph::runtime::Backend::call); backend.def("remove_compiled_function", (void (ngraph::runtime::Backend::*)(std::shared_ptr<ngraph::Function>)) & ngraph::runtime::Backend::remove_compiled_function); backend.def("enable_performance_data", (void (ngraph::runtime::Backend::*)(std::shared_ptr<ngraph::Function>, bool)) & ngraph::runtime::Backend::enable_performance_data); backend.def("get_performance_data", (std::vector<ngraph::runtime::PerformanceCounter>(ngraph::runtime::Backend::*)( std::shared_ptr<ngraph::Function>)) & ngraph::runtime::Backend::get_performance_data); }
49.982456
100
0.614953
[ "shape", "vector" ]
ebd2b829a0c2753b5fa3775c19a58b893e2cc81e
690
hpp
C++
vac3_response_parser/VACStringArray.hpp
krystalgamer/vac_public
0f38fb384fd374226ff771255c3d1192ab3dca59
[ "WTFPL" ]
60
2017-05-09T20:09:35.000Z
2020-10-19T03:10:07.000Z
vac3_response_parser/VACStringArray.hpp
owerosu/vac_public
0f38fb384fd374226ff771255c3d1192ab3dca59
[ "WTFPL" ]
null
null
null
vac3_response_parser/VACStringArray.hpp
owerosu/vac_public
0f38fb384fd374226ff771255c3d1192ab3dca59
[ "WTFPL" ]
20
2017-05-09T20:09:39.000Z
2020-02-27T00:04:57.000Z
#pragma once #include <vector> class VACStringArray { public: VACStringArray(char *begin) noexcept; VACStringArray(const VACStringArray&) = default; // Copy constructor VACStringArray(VACStringArray&&) = default; // Move constructor VACStringArray& operator=(const VACStringArray&) & = default; // Copy assignment operator VACStringArray& operator=(VACStringArray&&) & = default; // Move assignment operator virtual ~VACStringArray() { } // Destructor unsigned int GetSize() const; char* Get(int index); void Remove(int index); private: void AnalyzeStrings(char* begin); private: std::vector<char*> m_strings; };
26.538462
91
0.67971
[ "vector" ]
ebd5c02ec5f84be4cb4a4cec9a945b70df26e7c5
1,191
cpp
C++
src/action_utils.cpp
ysl208/iRoPro
72a8b023755b6396239c24fabef79458bcdc3215
[ "MIT" ]
5
2020-11-11T10:51:53.000Z
2022-01-13T01:32:11.000Z
src/action_utils.cpp
ysl208/rapid_pbd
72a8b023755b6396239c24fabef79458bcdc3215
[ "MIT" ]
24
2018-05-02T17:33:04.000Z
2018-12-19T13:06:52.000Z
src/action_utils.cpp
ysl208/rapid_pbd
72a8b023755b6396239c24fabef79458bcdc3215
[ "MIT" ]
2
2018-05-03T07:02:09.000Z
2018-05-03T11:36:53.000Z
#include "rapid_pbd/action_utils.h" #include <string> #include <vector> #include "rapid_pbd_msgs/Action.h" namespace msgs = rapid_pbd_msgs; namespace rapid { namespace pbd { bool HasJointValues(const msgs::Action& action) { return action.joint_trajectory.points.size() > 0; } void GetJointPositions(const msgs::Action& action, std::vector<std::string>* joint_names, std::vector<double>* joint_positions) { if (!HasJointValues(action)) { return; } *joint_names = action.joint_trajectory.joint_names; const trajectory_msgs::JointTrajectoryPoint& pt = action.joint_trajectory.points[0]; *joint_positions = pt.positions; } void SetJointPositions(const std::vector<std::string>& joint_names, const std::vector<double>& joint_positions, msgs::Action* action) { action->joint_trajectory.joint_names = joint_names; if (action->joint_trajectory.points.size() == 0) { action->joint_trajectory.points.resize(1); } action->joint_trajectory.points[0].positions = joint_positions; } } // namespace pbd } // namespace rapid int main(int argc, char** argv) { return 0; }
28.357143
67
0.68178
[ "vector" ]
ebd986870fc09a9c44400774caae7067d002f590
410
cpp
C++
bia/bsl/os.cpp
bialang/bia
b54fff096b4fe91ddb0b1d509ea828daa11cee7e
[ "BSD-3-Clause" ]
2
2017-09-09T17:03:18.000Z
2018-03-02T20:02:02.000Z
bia/bsl/os.cpp
terrakuh/Bia
412b7e8aeb259f4925c3b588f6025760a43cd0b7
[ "BSD-3-Clause" ]
7
2018-10-11T18:14:19.000Z
2018-12-26T15:31:04.000Z
bia/bsl/os.cpp
terrakuh/Bia
412b7e8aeb259f4925c3b588f6025760a43cd0b7
[ "BSD-3-Clause" ]
null
null
null
#include "modules.hpp" #include <cstdlib> void bia::bsl::os(internal::Typed_object& object) { object.put_invokable(util::from_cstring("system"), [](const std::string& cmd) { return std::system(cmd.c_str()); }); object.put_invokable(util::from_cstring("getenv"), [](const std::string& key) { char* value = std::getenv(key.c_str()); return std::string{ value ? value : "" }; }); }
29.285714
87
0.631707
[ "object" ]
ebe66a0c513d40c839388e00ca1891bd1a7476a2
1,170
cc
C++
strongloop/node_modules/strong-supervisor/node_modules/strong-agent/src/strong-agent.cc
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
strongloop/node_modules/strong-supervisor/node_modules/strong-agent/src/strong-agent.cc
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
strongloop/node_modules/strong-supervisor/node_modules/strong-agent/src/strong-agent.cc
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
// Copyright (c) 2014, StrongLoop Inc. // // This software is covered by the StrongLoop License. See StrongLoop-LICENSE // in the top-level directory or visit http://strongloop.com/license. #include "strong-agent.h" #include "extras.h" #include "gcinfo.h" #include "heapdiff.h" #include "profiler.h" #include "uvmon.h" namespace strongloop { namespace agent { using v8::Isolate; using v8::Local; using v8::Object; void Initialize(Local<Object> binding) { Isolate* isolate = Isolate::GetCurrent(); extras::Initialize(isolate, binding); gcinfo::Initialize(isolate, binding); heapdiff::Initialize(isolate, binding); profiler::Initialize(isolate, binding); uvmon::Initialize(isolate, binding); } // See https://github.com/joyent/node/pull/7240. Need to make the module // definition externally visible when compiling with -fvisibility=hidden. // Doesn't apply to v0.11, it uses a constructor to register the module. #if defined(__GNUC__) && SL_NODE_VERSION == 10 extern "C" __attribute__((visibility("default"))) node::node_module_struct strong_agent_module; #endif NODE_MODULE(strong_agent, Initialize) } // namespace agent } // namespace strongloop
28.536585
78
0.747863
[ "object" ]
ebe8fd7940130d4f9a5ba92ccf4caab329548a1f
2,025
cc
C++
library/core/render/gl-texture.cc
ppofuk/engine
092b07647dda4b8ccd4a03237e174581b3493f39
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
library/core/render/gl-texture.cc
ppofuk/engine
092b07647dda4b8ccd4a03237e174581b3493f39
[ "BSD-2-Clause-FreeBSD" ]
1
2021-05-26T11:55:26.000Z
2021-05-26T18:24:30.000Z
library/core/render/gl-texture.cc
ppofuk/engine
092b07647dda4b8ccd4a03237e174581b3493f39
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "core/render/gl-texture.h" namespace render { bool GLTexture::Init(const DDSImage& image) { if (is_init()) { return false; } if (image.four_cc() == DDSImage::FourCC::kUknownType) { return false; } // Clear all errors before. while (glGetError() != GL_NO_ERROR) ; glGenTextures(1, &texture_); Bind(); GLenum err = glGetError(); if (err != GL_NO_ERROR) { util::Log << util::kLogDateTime << ": " << __FILE__ << ":" << __LINE__ << ": " << (const char*)gluErrorString(err) << "\n"; } u32 block_size = 0; if (image.four_cc() == DDSImage::FourCC::kDXT1) { format_ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; block_size = 8; } if (image.four_cc() == DDSImage::FourCC::kDXT3) { format_ = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; block_size = 16; } if (image.four_cc() == DDSImage::FourCC::kDXT5) { format_ = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; block_size = 16; } u32 width = image.width(); u32 height = image.height(); for (u32 level = 0, offset = 0; level < image.mip_map_count() && (width || height); ++level) { u32 size = std::max((u32)1, ((width + 3) / 4)) * std::max((u32)1, ((height + 3) / 4)) * block_size; glCompressedTexImage2D(GL_TEXTURE_2D, level, format_, std::max((u32)1, width), std::max((u32)1, height), 0, size, (char*)image.data() + offset); err = glGetError(); if (err != GL_NO_ERROR) { util::Log << util::kLogDateTime << ": " << __FILE__ << ":" << __LINE__ << ": " << (const char*)gluErrorString(err) << "\n"; } offset += size; width /= 2; height /= 2; } is_init_ = true; return true; } void GLTexture::Destroy() { if (is_init()) { pixel_buffer_object_.Destroy(); GLuint delete_texture[] = {texture_}; glDeleteTextures(1, delete_texture); is_init_ = false; } } void GLTexture::Bind() { glBindTexture(texture_type(), texture_); } } // namespace render
24.39759
80
0.57679
[ "render" ]
ebea74a7e4eabef2ba90b5da65732326c9e45707
4,806
cpp
C++
src/Container.cpp
metaverse-systems/libecs-cpp
508a7a091fc7a47560f9d3f551b8d36584471359
[ "MIT" ]
null
null
null
src/Container.cpp
metaverse-systems/libecs-cpp
508a7a091fc7a47560f9d3f551b8d36584471359
[ "MIT" ]
null
null
null
src/Container.cpp
metaverse-systems/libecs-cpp
508a7a091fc7a47560f9d3f551b8d36584471359
[ "MIT" ]
null
null
null
#include <libecs-cpp/ecs.hpp> #include <thread> #include <algorithm> #include <cstring> namespace ecs { Container::Container() { this->Handle = ecs::Uuid().Get(); } Container::Container(std::string Handle) { this->Handle = Handle; } void Container::Start() { this->ContainerThread = std::thread(&Container::ThreadFunc, this); this->ContainerThread.detach(); } void Container::Start(uint32_t interval) { this->sleep_interval = interval; this->ContainerThread = std::thread(&Container::ThreadFunc, this); this->ContainerThread.detach(); } Json::Value Container::Export() { Json::Value data; data["Handle"] = this->Handle; for(auto &[name, entity] : this->Entities) { data["Entities"][name] = entity->Export(); } for(auto &[name, system] : this->Systems) { data["Systems"][name] = system->Export(); } return data; } void Container::ManagerSet(ecs::Manager *Manager) { this->Manager = Manager; } ecs::Manager *Container::ManagerGet() { return this->Manager; } std::string Container::HandleGet() { return this->Handle; } ecs::System *Container::System(ecs::System *system) { system->ContainerSet(this); this->Systems[system->HandleGet()] = system; return system; } std::vector<std::string> Container::SystemsGet() { std::vector<std::string> Handles; for(auto &system : this->Systems) Handles.push_back(system.first); return Handles; } std::shared_ptr<ecs::Component> Container::Component(std::shared_ptr<ecs::Component> c) { this->Components[c->Type][c->EntityHandle] = c; return c; } ecs::TypeEntityComponentList Container::ComponentsGet() { return this->Components; } ecs::TypeEntityComponentList Container::ComponentsGet(std::vector<std::string> Types) { ecs::TypeEntityComponentList c; for(auto &t : Types) c[t] = this->Components[t]; return c; } ecs::Entity *Container::Entity(std::string uuid) { return this->EntityCreate(uuid); } ecs::Entity *Container::Entity() { return this->EntityCreate(""); } ecs::Entity *Container::EntityCreate(std::string uuid) { ecs::Entity *e; if(uuid.size() == 0) { e = new ecs::Entity(); this->Entities[e->HandleGet()] = e; } else { if(this->Entities.count(uuid) == 0) { e = new ecs::Entity(uuid); this->Entities[uuid] = e; } else { e = this->Entities[uuid]; } } e->ContainerSet(this); return e; } void Container::SystemsInit() { for(auto &Handle : this->SystemsGet()) { this->Systems[Handle]->Init(); } } void Container::ThreadFunc() { this->SystemsInit(); #ifdef WITHGPERFTOOLS ProfilerStart("container_update.log"); #endif while(this->ThreadRunning) { usleep(this->sleep_interval); this->Update(); } #ifdef WITHGPERFTOOLS ProfilerStop(); #endif } void Container::Update() { for(auto &Handle : this->SystemsGet()) { this->Systems[Handle]->Update(); } } void Container::MessageSubmit(Json::Value message) { auto dest_system = message["destination"]["system"].asString(); if(!this->Systems[dest_system]) { auto err = "ecs::Container(\"" + message["destination"]["container"].asString() + "\")::MessageSubmit(): System " + dest_system + " not found."; throw std::runtime_error(err); } this->Systems[dest_system]->MessageSubmit(message); } void Container::EntityDestroy(std::string uuid) { for(auto &t : this->Components) { t.second.erase(uuid); } this->Entities.erase(uuid); } void Container::ResourceAdd(std::string name, ecs::Resource r) { this->resources[name] = r; } ecs::Resource Container::ResourceGet(std::string name) { if(this->resources.count(name) == 0) { auto err = "Attempted to access non-existent resource: " + name; throw std::runtime_error(err); } return this->resources[name]; } void Container::ComponentDestroy(std::string entity, std::string Type) { this->Components[Type].erase(entity); } }
22.777251
156
0.539118
[ "vector" ]
ebed4d86769ef325cf5028584eeb0853be6c6ad2
1,470
cpp
C++
07-creating-tile-maps/PauseState.cpp
caiotava/SDLBook
a689003e0667baf1491e93b33b2e3f50666f366e
[ "BSD-2-Clause" ]
6
2015-06-04T19:48:28.000Z
2021-12-11T21:39:40.000Z
07-creating-tile-maps/PauseState.cpp
caiotava/SDLBook
a689003e0667baf1491e93b33b2e3f50666f366e
[ "BSD-2-Clause" ]
null
null
null
07-creating-tile-maps/PauseState.cpp
caiotava/SDLBook
a689003e0667baf1491e93b33b2e3f50666f366e
[ "BSD-2-Clause" ]
2
2020-06-30T03:54:15.000Z
2022-02-06T02:18:55.000Z
// // Created by caiotava on 4/21/21. // #include "Game.h" #include "MenuButton.h" #include "MainMenuState.h" #include "PauseState.h" #include "StateParser.h" const std::string PauseState::pauseID = "pause"; void PauseState::pauseToMain() { Game::Instance()->getStateMachine()->changeState(new MainMenuState()); } void PauseState::resumePlay() { Game::Instance()->getStateMachine()->popState(); } void PauseState::update() { for (auto& o : objects) { o->update(); } } void PauseState::render() { for (auto& o : objects) { o->draw(); } } bool PauseState::onEnter() { StateParser stateParser; stateParser.parseState("assets/test.xml", pauseID, &objects, &textureIDs); callbacks.push_back(0); callbacks.push_back(pauseToMain); callbacks.push_back(resumePlay); setCallbacks(callbacks); std::cout << "entering pause-state" << std::endl; return true; } bool PauseState::onExit() { for (auto& o : objects) { o->clean(); } objects.clear(); for (auto& t : textureIDs) { TextureManager::Instance()->clearFromTextureMap(t); } return true; } void PauseState::setCallbacks(const std::vector<Callback> &callbacks) { for (auto& o : objects) { if (!dynamic_cast<MenuButton*>(o)) { continue; } MenuButton* button = dynamic_cast<MenuButton*>(o); button->setCallback(callbacks[button->getCallbackID()]); } }
20.416667
78
0.62585
[ "render", "vector" ]
ebee3e89a28c699673ad955a3a690d925e5e182e
5,881
cpp
C++
engine/source/engine/physics/OOBB.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
engine/source/engine/physics/OOBB.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
engine/source/engine/physics/OOBB.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
#include "engine-precompiled-header.h" #include "OOBB.h" #include "engine/renderer/Renderer3D.h" longmarch::OOBB::OOBB() : Shape(SHAPE_TYPE::OOBB) { ResetOriginal(); Reset(); } longmarch::OOBB::OOBB(const Vec3f& min, const Vec3f& max) : Shape(SHAPE_TYPE::OOBB) { o_min = Min = min; o_max = Max = max; } longmarch::OOBB::OOBB(const std::shared_ptr<MeshData>& mesh) : Shape(SHAPE_TYPE::OOBB) { ResetOriginal(); InitWithMeshData(mesh->vertices, mesh->indices); } longmarch::OOBB::OOBB(const LongMarch_Vector<std::shared_ptr<MeshData>>& meshs) : Shape(SHAPE_TYPE::OOBB) { ResetOriginal(); for (const auto& mesh : meshs) { InitWithMeshData(mesh->vertices, mesh->indices); } } void longmarch::OOBB::InitWithMeshData(const MeshData::VertexList& vertex_data, const MeshData::IndexList& index_data) { LOCK_GUARD_NC(); if (vertex_data.empty()) { throw EngineException(_CRT_WIDE(__FILE__), __LINE__, L"Mesh data does not exist! Either the mesh data has been destroied after sending to GPU or the mesh data has not be loaded yet!"); } // Check if submesh is indexed if (!index_data.empty()) { // Update bounding box for each indexed vertex for (const auto& tri : index_data) { #if MESH_VERTEX_DATA_FORMAT == 4 const auto& pnt1 = Geommath::UnPackVec4ToHVec4(vertex_data[tri[0]].pnt); const auto& pnt2 = Geommath::UnPackVec4ToHVec4(vertex_data[tri[1]].pnt); const auto& pnt3 = Geommath::UnPackVec4ToHVec4(vertex_data[tri[2]].pnt); UpdateOriginal(pnt1 * pnt1.w); UpdateOriginal(pnt2 * pnt2.w); UpdateOriginal(pnt3 * pnt3.w); #else UpdateOriginal(vertex_data[tri[0]].pnt); UpdateOriginal(vertex_data[tri[1]].pnt); UpdateOriginal(vertex_data[tri[2]].pnt); #endif } } else { // Update bounding box for each vertex for (const auto& vertex3d : vertex_data) { #if MESH_VERTEX_DATA_FORMAT == 4 const auto& pnt1 = Geommath::UnPackVec4ToHVec4(vertex3d.pnt); UpdateOriginal(pnt1 * pnt1.w); #else UpdateOriginal(vertex3d.pnt); #endif } } } void longmarch::OOBB::ResetOriginal() { o_min = Vec3f((std::numeric_limits<float>::max)()); o_max = Vec3f((std::numeric_limits<float>::lowest)()); } void longmarch::OOBB::UpdateOriginal(const Vec3f& point) { o_min = (glm::min)(o_min, point); o_max = (glm::max)(o_max, point); } const LongMarch_Vector<Vec3f> longmarch::OOBB::GetAllVertex() { LOCK_GUARD_NC(); LongMarch_Vector<Vec3f> ret = GetAllVertexOriginal(); for (auto& v : ret) { v = Geommath::ToVec3(m_ObjectTr * Geommath::ToVec4(v)); } return ret; } const LongMarch_Vector<Vec3f> longmarch::OOBB::GetAllVertexOriginal() { LongMarch_Vector<Vec3f> ret(8); { Vec3f _min = o_min, _max = o_max; Vec4f abc = Vec4f(_max - _min, 0); ret[0] = _min; ret[1] = _min + abc.xww; ret[2] = _min + abc.xyw; ret[3] = _min + abc.wyw; ret[4] = _min + abc.wwz; ret[5] = _min + abc.xwz; ret[6] = _min + abc.xyz; ret[7] = _min + abc.wyz; } return ret; } Vec3f longmarch::OOBB::GetDiag() { return Max - Min; } inline float longmarch::OOBB::GetRadius() { return glm::length(GetDiag() * 0.5f); } Vec3f longmarch::OOBB::GetCenter() { return (Max + Min) * 0.5f; } void longmarch::OOBB::SetModelTrAndUpdate(const Mat4& transform) { LOCK_GUARD_NC(); m_ObjectTr = transform; Min = std::move(Geommath::Mat4ProdVec3(transform, o_min)); Max = std::move(Geommath::Mat4ProdVec3(transform, o_max)); } bool longmarch::OOBB::VFCTest(const ViewFrustum& VF, const Mat4& worldSpaceToViewFrustumSpace) { LOCK_GUARD_NC(); /* Reference: https://old.cescg.org/CESCG-2002/DSykoraJJelinek/ Reference: http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-testing-boxes-ii/ */ const auto& _min = o_min; const auto& _max = o_max; // Original: const auto& plane_tr = Geommath::SmartInverseTranspose(Geommath::SmartInverse(worldSpaceToViewFrustumSpace * m_ObjectTr)); // Simplified as: glm::transpose(worldSpaceToViewFrustumSpace * m_ObjectTr); // Could be event more simplified as worldSpaceToViewFrustumSpace * m_ObjectTr to take advantage of row vector operation const auto& plane_tr = worldSpaceToViewFrustumSpace * m_ObjectTr; for (const auto& plane : VF.planes) { const auto& pl = Geommath::Plane::Normalize(plane * plane_tr); // vec * mat would treat the vector as a row vector, this is equivalent to trans(mat) * vec // N-P vertex test Vec3f p; for (int i = 0; i < 3; ++i) { p[i] = (pl[i] > 0) ? _max[i] : _min[i]; } if (Geommath::Plane::Distance(pl, p) < 0) { m_isCulled = true; return m_isCulled; } } m_isCulled = false; return m_isCulled; } bool longmarch::OOBB::DistanceTest(const Vec3f& center, float Near, float Far) { LOCK_GUARD_NC(); auto r = GetRadius(); auto pos = GetCenter(); auto distance = glm::length(center - pos); { m_isCulled = (Far >= Near) && (distance < (Near - r) || distance >(Far + r)); return m_isCulled; } } void longmarch::OOBB::RenderShape() { LOCK_GUARD_NC(); Mat4 local_tr = Geommath::ToTranslateMatrix(GetOriginalCenter()) * Geommath::ToScaleMatrix(GetOriginalDiag()); Renderer3D::RenderBoundingBox(m_ObjectTr * local_tr); } const Vec3f& longmarch::OOBB::GetMin() const { return Min; } const Vec3f& longmarch::OOBB::GetMax() const { return Max; } Vec3f longmarch::OOBB::GetOriginalCenter() const { return (o_max + o_min) * 0.5f; } Vec3f longmarch::OOBB::GetOriginalDiag() const { return o_max - o_min; } void longmarch::OOBB::Reset() { Min = Vec3f((std::numeric_limits<float>::max)()); Max = Vec3f((std::numeric_limits<float>::lowest)()); } void longmarch::OOBB::Update(const Vec3f& point) { Min = (glm::min)(Min, point); Max = (glm::max)(Max, point); }
25.681223
187
0.670124
[ "mesh", "shape", "vector", "transform" ]
ebf17852d10337730c47ea2cf1796685390d43b9
5,795
hxx
C++
src/freertos_drivers/pic32mx/Pic32mxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
34
2015-05-23T03:57:56.000Z
2022-03-27T03:48:48.000Z
src/freertos_drivers/pic32mx/Pic32mxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
214
2015-07-05T05:06:55.000Z
2022-02-06T14:53:14.000Z
src/freertos_drivers/pic32mx/Pic32mxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
38
2015-08-28T05:32:07.000Z
2021-07-06T16:47:23.000Z
/** \copyright * Copyright (c) 2018, Balazs Racz * 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. * * 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. * * \file Pic32mxCan.hxx * * Declaration for the CAN device driver layer for the pic32mx. * * @author Balazs Racz * @date 21 Oct 2018 */ #ifndef _FREERTOS_DRIVERS_PIC32MX_PIC32MXCAN_HXX_ #define _FREERTOS_DRIVERS_PIC32MX_PIC32MXCAN_HXX_ #include "Devtab.hxx" #include "GenericTypeDefs.h" #include <xc.h> extern "C" { #include "peripheral/CAN.h" #include "peripheral/int.h" } /// CAN-bus device driver for the Pic32MX. /// /// This driver does not inherit from the shared Can driver, because the RX and /// RX buffering is different. The shared CAN driver has a DeviceBuffer for /// transmit and receive in the format of struct can_frame; whereas the PIC32 /// can write directly into the memory area of the CAN controller as the queues /// are long enough and the CAN controller is a bus master. class Pic32mxCan : public Node { public: /// Constructor. /// /// @param module defines which CAN hardware to use. (can0 or can1). /// @param dev filename of the device to create (e.g. "/dev/can0"); /// @param irq_vector fill with can1_interrupt_vector_number or /// can2_interrupt_vector_number. Pic32mxCan(CAN_MODULE module, const char *dev, unsigned irq_vector); ~Pic32mxCan(); /// Implementation of the interrupt handler. inline void isr() { int woken = 0; if ((CANGetModuleEvent(hw_) & CAN_RX_EVENT) != 0) // if(CANGetPendingEventCode(hw_) == CAN_CHANNEL1_EVENT) { /* This means that channel 1 caused the event. * The CAN_RX_CHANNEL_NOT_EMPTY event is persistent. You * could either read the channel in the ISR * to clear the event condition or as done * here, disable the event source, and set * an application flag to indicate that a message * has been received. The event can be * enabled by the application when it has processed * one message. * * Note that leaving the event enabled would * cause the CPU to keep executing the ISR since * the CAN_RX_CHANNEL_NOT_EMPTY event is persistent (unless * the not empty condition is cleared.) * */ CANEnableChannelEvent( hw_, CAN_CHANNEL1, CAN_RX_CHANNEL_NOT_EMPTY, FALSE); Device::select_wakeup_from_isr(&rxSelect_, &woken); } if ((CANGetModuleEvent(hw_) & CAN_TX_EVENT) != 0) // if(CANGetPendingEventCode(hw_) == CAN_CHANNEL0_EVENT) { /* Same with the TX event. */ CANEnableChannelEvent( hw_, CAN_CHANNEL0, CAN_TX_CHANNEL_NOT_FULL, FALSE); Device::select_wakeup_from_isr(&txSelect_, &woken); } INTClearFlag(can_int()); } private: void enable(); /**< function to enable device */ void disable(); /**< function to disable device */ void flush_buffers() OVERRIDE {} /**< function to disable device */ ssize_t read(File *file, void *buf, size_t count); ssize_t write(File *file, const void *buf, size_t count); /** Device select method. Default impementation returns true. * @param file reference to the file * @param mode FREAD for read active, FWRITE for write active, 0 for * exceptions * @return true if active, false if inactive */ bool select(File* file, int mode) OVERRIDE; /// @return the interrupt source as used by the internal tables of the /// peripheral library. INT_SOURCE can_int() { return (INT_SOURCE)(INT_SOURCE_CAN(hw_)); } /// @return the interrupt vector enum as used by the internal tables of the /// peripheral library. INT_VECTOR can_vector() { return (INT_VECTOR)(INT_VECTOR_CAN(hw_)); } /// Hardware (enumeration value). CAN_MODULE hw_; /// How many times did we drop a frame because we did not have enough /// hardware buffers. int overrunCount_; /// Hardware interrupt vector number. Do not delete! unsigned irqVector_; /// Points to the shared RAM area between the hardware and the driver. void *messageFifoArea_; // Select for the transmit buffers. SelectInfo txSelect_; // Select for the receive buffers. SelectInfo rxSelect_; DISALLOW_COPY_AND_ASSIGN(Pic32mxCan); }; #endif // _FREERTOS_DRIVERS_PIC32MX_PIC32MXCAN_HXX_
38.125
79
0.679551
[ "vector" ]
ebf1dee40f719f6564507605dda8868753d0403a
16,946
cpp
C++
Source/Urho3D/Navigation/DetourCrowdManager.cpp
asherkin/Urho3D
cf9e78e002ed6129d1c8b5b5e52f0b73181a5e01
[ "Apache-2.0" ]
null
null
null
Source/Urho3D/Navigation/DetourCrowdManager.cpp
asherkin/Urho3D
cf9e78e002ed6129d1c8b5b5e52f0b73181a5e01
[ "Apache-2.0" ]
null
null
null
Source/Urho3D/Navigation/DetourCrowdManager.cpp
asherkin/Urho3D
cf9e78e002ed6129d1c8b5b5e52f0b73181a5e01
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2008-2015 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Scene/Component.h" #include "../Core/Context.h" #include "../Navigation/CrowdAgent.h" #include "../Graphics/DebugRenderer.h" #include "../Navigation/DetourCrowdManager.h" #include "../Navigation/DynamicNavigationMesh.h" #include "../IO/Log.h" #include "../Navigation/NavigationEvents.h" #include "../Navigation/NavigationMesh.h" #include "../Scene/Node.h" #include "../Core/Profiler.h" #include "../Scene/Scene.h" #include "../Scene/SceneEvents.h" #include "../Container/Vector.h" #ifdef URHO3D_PHYSICS #include "../Physics/PhysicsEvents.h" #endif #include <DetourCrowd/DetourCrowd.h> #include <Recast/Recast.h> #include "../DebugNew.h" namespace Urho3D { extern const char* NAVIGATION_CATEGORY; static const unsigned DEFAULT_MAX_AGENTS = 512; DetourCrowdManager::DetourCrowdManager(Context* context) : Component(context), maxAgents_(DEFAULT_MAX_AGENTS), crowd_(0), navigationMesh_(0), agentDebug_(0) { agentBuffer_.Resize(maxAgents_); } DetourCrowdManager::~DetourCrowdManager() { dtFreeCrowd(crowd_); crowd_ = 0; delete agentDebug_; agentDebug_ = 0; } void DetourCrowdManager::RegisterObject(Context* context) { context->RegisterFactory<DetourCrowdManager>(NAVIGATION_CATEGORY); ACCESSOR_ATTRIBUTE("Max Agents", GetMaxAgents, SetMaxAgents, unsigned, DEFAULT_MAX_AGENTS, AM_DEFAULT); } void DetourCrowdManager::SetNavigationMesh(NavigationMesh* navMesh) { navigationMesh_ = WeakPtr<NavigationMesh>(navMesh); if (navigationMesh_ && !navigationMesh_->navMeshQuery_) navigationMesh_->InitializeQuery(); CreateCrowd(); MarkNetworkUpdate(); } void DetourCrowdManager::SetAreaCost(unsigned filterID, unsigned areaID, float weight) { dtQueryFilter* filter = crowd_->getEditableFilter(filterID); if (filter) filter->setAreaCost((int)areaID, weight); } void DetourCrowdManager::SetMaxAgents(unsigned agentCt) { maxAgents_ = agentCt; if (crowd_ && crowd_->getAgentCount() > 0) LOGERROR("DetourCrowdManager contains active agents, their state will be lost"); agentBuffer_.Resize(maxAgents_); CreateCrowd(); if (crowd_) { PODVector<CrowdAgent*> agents = agents_; // Reset the existing values in the agent for (unsigned i = 0; i < agents.Size(); ++i) { agents[i]->inCrowd_ = false; agents[i]->agentCrowdId_ = -1; } // Add the agents back in for (unsigned i = 0; i < agents.Size() && i < maxAgents_; ++i) agents[i]->AddAgentToCrowd(); if (agents.Size() > maxAgents_) LOGERROR("DetourCrowdManager: resize left " + String(agents.Size() - maxAgents_) + " agents orphaned"); } MarkNetworkUpdate(); } void DetourCrowdManager::SetCrowdTarget(const Vector3& position, int startId, int endId) { startId = Max(0, startId); endId = Clamp(endId, startId, agents_.Size() - 1); Vector3 moveTarget(position); for (int i = startId; i <= endId; ++i) { // Skip agent that does not have acceleration if (agents_[i]->GetMaxAccel() > 0.f) { agents_[i]->SetMoveTarget(moveTarget); // FIXME: Should reimplement this using event callback, i.e. it should be application-specific to decide what is the desired crowd formation when they reach the target if (navigationMesh_) moveTarget = navigationMesh_->FindNearestPoint(position + Vector3(Random(-4.5f, 4.5f), 0.0f, Random(-4.5f, 4.5f)), Vector3(1.0f, 1.0f, 1.0f)); } } } void DetourCrowdManager::ResetCrowdTarget(int startId, int endId) { startId = Max(0, startId); endId = Clamp(endId, startId, agents_.Size() - 1); for (int i = startId; i <= endId; ++i) { if (agents_[i]->GetMaxAccel() > 0.f) agents_[i]->ResetMoveTarget(); } } void DetourCrowdManager::SetCrowdVelocity(const Vector3& velocity, int startId, int endId) { startId = Max(0, startId); endId = Clamp(endId, startId, agents_.Size() - 1); for (int i = startId; i <= endId; ++i) { if (agents_[i]->GetMaxAccel() > 0.f) agents_[i]->SetMoveVelocity(velocity); } } float DetourCrowdManager::GetAreaCost(unsigned filterID, unsigned areaID) const { if (crowd_ && navigationMesh_) { const dtQueryFilter* filter = crowd_->getFilter((int)filterID); if (filter) return filter->getAreaCost((int)areaID); } return 0.0f; } unsigned DetourCrowdManager::GetAgentCount() const { return crowd_ ? crowd_->getAgentCount() : 0; } void DetourCrowdManager::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { if (debug && navigationMesh_.NotNull() && crowd_) { // Current position-to-target line for (int i = 0; i < crowd_->getAgentCount(); i++) { const dtCrowdAgent* ag = crowd_->getAgent(i); if (!ag->active) continue; // Draw CrowdAgent shape (from its radius & height) CrowdAgent* crowdAgent = static_cast<CrowdAgent*>(ag->params.userData); crowdAgent->DrawDebugGeometry(debug, depthTest); // Draw move target if any if (crowdAgent->GetTargetState() == CROWD_AGENT_TARGET_NONE) continue; Color color(0.6f, 0.2f, 0.2f, 1.0f); // Draw line to target Vector3 pos1(ag->npos[0], ag->npos[1], ag->npos[2]); Vector3 pos2; for (int i = 0; i < ag->ncorners; ++i) { pos2.x_ = ag->cornerVerts[i * 3]; pos2.y_ = ag->cornerVerts[i * 3 + 1]; pos2.z_ = ag->cornerVerts[i * 3 + 2]; debug->AddLine(pos1, pos2, color, depthTest); pos1 = pos2; } pos2.x_ = ag->targetPos[0]; pos2.y_ = ag->targetPos[1]; pos2.z_ = ag->targetPos[2]; debug->AddLine(pos1, pos2, color, depthTest); // Draw target circle debug->AddSphere(Sphere(pos2, 0.5f), color, depthTest); } } } void DetourCrowdManager::DrawDebugGeometry(bool depthTest) { Scene* scene = GetScene(); if (scene) { DebugRenderer* debug = scene->GetComponent<DebugRenderer>(); if (debug) DrawDebugGeometry(debug, depthTest); } } bool DetourCrowdManager::CreateCrowd() { if (!navigationMesh_ || !navigationMesh_->navMesh_) return false; if (crowd_) dtFreeCrowd(crowd_); crowd_ = dtAllocCrowd(); if (!agentDebug_) agentDebug_ = new dtCrowdAgentDebugInfo(); // Initialize the crowd if (!crowd_->init(maxAgents_, navigationMesh_->GetAgentRadius(), navigationMesh_->navMesh_)) { LOGERROR("Could not initialize DetourCrowd"); return false; } // Setup local avoidance params to different qualities. dtObstacleAvoidanceParams params; memcpy(&params, crowd_->getObstacleAvoidanceParams(0), sizeof(dtObstacleAvoidanceParams)); // Low (11) params.velBias = 0.5f; params.adaptiveDivs = 5; params.adaptiveRings = 2; params.adaptiveDepth = 1; crowd_->setObstacleAvoidanceParams(0, &params); // Medium (22) params.velBias = 0.5f; params.adaptiveDivs = 5; params.adaptiveRings = 2; params.adaptiveDepth = 2; crowd_->setObstacleAvoidanceParams(1, &params); // Good (45) params.velBias = 0.5f; params.adaptiveDivs = 7; params.adaptiveRings = 2; params.adaptiveDepth = 3; crowd_->setObstacleAvoidanceParams(2, &params); // High (66) params.velBias = 0.5f; params.adaptiveDivs = 7; params.adaptiveRings = 3; params.adaptiveDepth = 3; crowd_->setObstacleAvoidanceParams(3, &params); return true; } int DetourCrowdManager::AddAgent(CrowdAgent* agent, const Vector3& pos) { if (!crowd_ || navigationMesh_.Expired()) return -1; dtCrowdAgentParams params; params.userData = agent; if (agent->radius_ <= 0.0f) agent->radius_ = navigationMesh_->GetAgentRadius(); params.radius = agent->radius_; if (agent->height_ <= 0.0f) agent->height_ = navigationMesh_->GetAgentHeight(); params.height = agent->height_; params.queryFilterType = (unsigned char)agent->filterType_; params.maxAcceleration = agent->maxAccel_; params.maxSpeed = agent->maxSpeed_; params.collisionQueryRange = params.radius * 8.0f; params.pathOptimizationRange = params.radius * 30.0f; params.updateFlags = DT_CROWD_ANTICIPATE_TURNS | DT_CROWD_OPTIMIZE_VIS | DT_CROWD_OPTIMIZE_TOPO | DT_CROWD_OBSTACLE_AVOIDANCE; params.obstacleAvoidanceType = 3; params.separationWeight = 2.0f; params.queryFilterType = 0; dtPolyRef polyRef; float nearestPos[3]; rcVcopy(nearestPos, &pos.x_); dtStatus status = navigationMesh_->navMeshQuery_->findNearestPoly( pos.Data(), crowd_->getQueryExtents(), crowd_->getFilter(agent->filterType_), &polyRef, nearestPos); const int agentID = crowd_->addAgent(nearestPos, &params); if (agentID != -1) agents_.Push(agent); return agentID; } void DetourCrowdManager::RemoveAgent(CrowdAgent* agent) { if (!crowd_) return; // Clear user data dtCrowdAgent* agt = crowd_->getEditableAgent(agent->GetAgentCrowdId()); if (agt) agt->params.userData = 0; crowd_->removeAgent(agent->GetAgentCrowdId()); agents_.Remove(agent); } void DetourCrowdManager::UpdateAgentNavigationQuality(CrowdAgent* agent, NavigationQuality nq) { if (!crowd_) return; dtCrowdAgentParams params = crowd_->getAgent(agent->GetAgentCrowdId())->params; switch (nq) { case NAVIGATIONQUALITY_LOW: { params.updateFlags &= ~0 & ~DT_CROWD_ANTICIPATE_TURNS & ~DT_CROWD_OPTIMIZE_VIS & ~DT_CROWD_OPTIMIZE_TOPO & ~DT_CROWD_OBSTACLE_AVOIDANCE; } break; case NAVIGATIONQUALITY_MEDIUM: { params.updateFlags |= 0; params.updateFlags &= ~0 & ~DT_CROWD_OBSTACLE_AVOIDANCE & ~DT_CROWD_ANTICIPATE_TURNS & ~DT_CROWD_OPTIMIZE_VIS & ~DT_CROWD_OPTIMIZE_TOPO; } break; case NAVIGATIONQUALITY_HIGH: { params.obstacleAvoidanceType = 3; params.updateFlags |= 0 | DT_CROWD_ANTICIPATE_TURNS | DT_CROWD_OPTIMIZE_VIS | DT_CROWD_OPTIMIZE_TOPO | DT_CROWD_OBSTACLE_AVOIDANCE; } break; } crowd_->updateAgentParameters(agent->GetAgentCrowdId(), &params); } void DetourCrowdManager::UpdateAgentPushiness(CrowdAgent* agent, NavigationPushiness pushiness) { if (!crowd_) return; dtCrowdAgentParams params = crowd_->getAgent(agent->GetAgentCrowdId())->params; switch (pushiness) { case PUSHINESS_LOW: params.separationWeight = 4.0f; params.collisionQueryRange = params.radius * 16.0f; break; case PUSHINESS_MEDIUM: params.separationWeight = 2.0f; params.collisionQueryRange = params.radius * 8.0f; break; case PUSHINESS_HIGH: params.separationWeight = 0.5f; params.collisionQueryRange = params.radius * 1.0f; break; } crowd_->updateAgentParameters(agent->GetAgentCrowdId(), &params); } bool DetourCrowdManager::SetAgentTarget(CrowdAgent* agent, Vector3 target) { if (!crowd_) return false; dtPolyRef polyRef; float nearestPos[3]; dtStatus status = navigationMesh_->navMeshQuery_->findNearestPoly( target.Data(), crowd_->getQueryExtents(), crowd_->getFilter(agent->filterType_), &polyRef, nearestPos); return !dtStatusFailed(status) && crowd_->requestMoveTarget(agent->GetAgentCrowdId(), polyRef, nearestPos); } bool DetourCrowdManager::SetAgentTarget(CrowdAgent* agent, Vector3 target, unsigned int& targetRef) { if (crowd_ == 0) return false; float nearestPos[3]; dtStatus status = navigationMesh_->navMeshQuery_->findNearestPoly( target.Data(), crowd_->getQueryExtents(), crowd_->getFilter(agent->filterType_), &targetRef, nearestPos); // Return true if detour has determined it can do something with our move target return !dtStatusFailed(status) && crowd_->requestMoveTarget(agent->GetAgentCrowdId(), targetRef, nearestPos) && crowd_->getAgent(agent->GetAgentCrowdId())->targetState != DT_CROWDAGENT_TARGET_FAILED; } Vector3 DetourCrowdManager::GetClosestWalkablePosition(Vector3 pos) const { if (!crowd_) return Vector3::ZERO; float closest[3]; const static float extents[] = { 1.0f, 20.0f, 1.0f }; dtPolyRef closestPoly; dtQueryFilter filter; dtStatus status = navigationMesh_->navMeshQuery_->findNearestPoly( pos.Data(), crowd_->getQueryExtents(), &filter, &closestPoly, closest); return Vector3(closest); } void DetourCrowdManager::Update(float delta) { if (!crowd_) return; PROFILE(UpdateCrowd); crowd_->update(delta, agentDebug_); memset(&agentBuffer_[0], 0, maxAgents_ * sizeof(dtCrowdAgent*)); const int count = crowd_->getActiveAgents(&agentBuffer_[0], maxAgents_); { PROFILE(ApplyCrowdUpdates); for (int i = 0; i < count; i++) { dtCrowdAgent* agent = agentBuffer_[i]; if (agent) { CrowdAgent* crowdAgent = static_cast<CrowdAgent*>(agent->params.userData); if (crowdAgent) crowdAgent->OnCrowdAgentReposition(Vector3(agent->npos), Vector3(agent->vel)); } } } } const dtCrowdAgent* DetourCrowdManager::GetCrowdAgent(int agent) { return crowd_ ? crowd_->getAgent(agent) : 0; } void DetourCrowdManager::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData) { using namespace SceneSubsystemUpdate; if (IsEnabledEffective()) Update(eventData[P_TIMESTEP].GetFloat()); } void DetourCrowdManager::HandleNavMeshFullRebuild(StringHash eventType, VariantMap& eventData) { using namespace NavigationMeshRebuilt; // The mesh being rebuilt may not have existed before NavigationMesh* navMesh = static_cast<NavigationMesh*>(eventData[P_MESH].GetPtr()); if (!navigationMesh_ || !crowd_) { SetNavigationMesh(navMesh); // Scan for existing agents that are potentially important PODVector<Node*> agents; GetScene()->GetChildrenWithComponent<CrowdAgent>(agents, true); for (unsigned i = 0; i < agents.Size(); ++i) { CrowdAgent* agent = agents[i]->GetComponent<CrowdAgent>(); if (agent && agent->IsEnabledEffective()) agent->AddAgentToCrowd(); } } } void DetourCrowdManager::OnNodeSet(Node* node) { // Subscribe to the scene subsystem update, which will trigger the crowd update step, and grab a reference // to the scene's NavigationMesh if (node) { SubscribeToEvent(node, E_SCENESUBSYSTEMUPDATE, HANDLER(DetourCrowdManager, HandleSceneSubsystemUpdate)); SubscribeToEvent(node, E_NAVIGATION_MESH_REBUILT, HANDLER(DetourCrowdManager, HandleNavMeshFullRebuild)); NavigationMesh* mesh = GetScene()->GetComponent<NavigationMesh>(); if (!mesh) mesh = GetScene()->GetComponent<DynamicNavigationMesh>(); if (mesh) SetNavigationMesh(mesh); else LOGERROR("DetourCrowdManager requires an existing navigation mesh"); } } }
31.556797
179
0.650832
[ "mesh", "shape", "vector" ]
ebf224dc66056940da08d68b8031b1dde9ae74c8
1,884
hpp
C++
external/cppad/include/cppad/utility.hpp
l03ie/Gernby
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
5
2018-06-27T04:19:32.000Z
2018-08-01T19:16:28.000Z
external/cppad/include/cppad/utility.hpp
l03ie/Gernby
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
1
2018-07-31T16:52:31.000Z
2018-08-02T15:37:55.000Z
external/cppad/include/cppad/utility.hpp
l03ie/Gernby
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
3
2018-07-24T05:09:26.000Z
2018-08-01T16:03:31.000Z
# ifndef CPPAD_UTILITY_HPP # define CPPAD_UTILITY_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ # include <cppad/utility/check_numeric_type.hpp> # include <cppad/utility/check_simple_vector.hpp> # include <cppad/utility/elapsed_seconds.hpp> # include <cppad/utility/error_handler.hpp> # include <cppad/utility/index_sort.hpp> # include <cppad/utility/lu_factor.hpp> # include <cppad/utility/lu_invert.hpp> # include <cppad/utility/lu_solve.hpp> # include <cppad/utility/memory_leak.hpp> # include <cppad/utility/nan.hpp> # include <cppad/utility/near_equal.hpp> # include <cppad/utility/ode_err_control.hpp> # include <cppad/utility/ode_gear_control.hpp> # include <cppad/utility/ode_gear.hpp> # include <cppad/utility/omp_alloc.hpp> # include <cppad/utility/poly.hpp> # include <cppad/utility/pow_int.hpp> # include <cppad/utility/romberg_mul.hpp> # include <cppad/utility/romberg_one.hpp> # include <cppad/utility/rosen_34.hpp> # include <cppad/utility/runge_45.hpp> # include <cppad/utility/test_boolofvoid.hpp> # include <cppad/utility/set_union.hpp> # include <cppad/utility/speed_test.hpp> # include <cppad/utility/thread_alloc.hpp> # include <cppad/utility/time_test.hpp> # include <cppad/utility/to_string.hpp> # include <cppad/utility/track_new_del.hpp> # include <cppad/utility/vector.hpp> # include <cppad/utility/sparse_rc.hpp> # include <cppad/utility/sparse_rcv.hpp> # endif
41.866667
77
0.713376
[ "vector" ]
ebf26d819237cea1f47f92f4a9d710493f46becc
26,066
cpp
C++
OpenAutoItParser/src/Lexer.cpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
null
null
null
OpenAutoItParser/src/Lexer.cpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
6
2022-02-01T04:07:12.000Z
2022-03-01T04:43:49.000Z
OpenAutoItParser/src/Lexer.cpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
null
null
null
#include "OpenAutoIt/Lexer.hpp" #include "OpenAutoIt/Token.hpp" #include "OpenAutoIt/TokenKind.hpp" #include "OpenAutoIt/TokenStream.hpp" #include "phi/container/string_view.hpp" #include "phi/core/optional.hpp" #include <phi/container/array.hpp> #include <phi/core/assert.hpp> #include <phi/core/boolean.hpp> #include <algorithm> #include <array> #include <map> #include <string> template <typename KeyT, typename ValueT, std::size_t SizeT> class LookUpMap { public: constexpr LookUpMap(const std::array<std::pair<KeyT, ValueT>, SizeT>& data, ValueT default_value) noexcept : m_Data(data) , m_Default(default_value) {} [[nodiscard]] constexpr ValueT at(const KeyT& key) const { const auto itr = std::find_if(begin(m_Data), end(m_Data), [&key](const auto& v) { return v.first == key; }); if (itr != end(m_Data)) { return itr->second; } return m_Default; } private: std::array<std::pair<KeyT, ValueT>, SizeT> m_Data; ValueT m_Default; }; static constexpr std::array<std::pair<phi::string_view, OpenAutoIt::TokenKind>, 102u> MacroValues{{ {"@appdatacommondir", OpenAutoIt::TokenKind::MK_AppDataCommonDir}, {"@appdatadir", OpenAutoIt::TokenKind::MK_AppDataDir}, {"@autoitexe", OpenAutoIt::TokenKind::MK_AutoItExe}, {"@autoitpid", OpenAutoIt::TokenKind::MK_AutoItPID}, {"@autoitversion", OpenAutoIt::TokenKind::MK_AutoItVersion}, {"@autoitx64", OpenAutoIt::TokenKind::MK_AutoItX64}, {"@com_eventobj", OpenAutoIt::TokenKind::MK_COM_EventObj}, {"@commonfilesdir", OpenAutoIt::TokenKind::MK_CommonFilesDir}, {"@compiled", OpenAutoIt::TokenKind::MK_Compiled}, {"@computername", OpenAutoIt::TokenKind::MK_ComputerName}, {"@comspec", OpenAutoIt::TokenKind::MK_ComSpec}, {"@cpuarch", OpenAutoIt::TokenKind::MK_CPUArch}, {"@cr", OpenAutoIt::TokenKind::MK_CR}, {"@crlf", OpenAutoIt::TokenKind::MK_CRLF}, {"@desktopcommondir", OpenAutoIt::TokenKind::MK_DesktopCommonDir}, {"@desktopdepth", OpenAutoIt::TokenKind::MK_DesktopDepth}, {"@desktopdir", OpenAutoIt::TokenKind::MK_DesktopDir}, {"@desktopheight", OpenAutoIt::TokenKind::MK_DesktopHeight}, {"@desktoprefresh", OpenAutoIt::TokenKind::MK_DesktopRefresh}, {"@desktopwidth", OpenAutoIt::TokenKind::MK_DesktopWidth}, {"@documentscommondir", OpenAutoIt::TokenKind::MK_DocumentsCommonDir}, {"@error", OpenAutoIt::TokenKind::MK_error}, {"@exitcode", OpenAutoIt::TokenKind::MK_exitCode}, {"@exitmethod", OpenAutoIt::TokenKind::MK_exitMethod}, {"@extended", OpenAutoIt::TokenKind::MK_extended}, {"@favoritescommondir", OpenAutoIt::TokenKind::MK_FavoritesCommonDir}, {"@favoritesdir", OpenAutoIt::TokenKind::MK_FavoritesDir}, {"@gui_ctrlhandle", OpenAutoIt::TokenKind::MK_GUI_CtrlHandle}, {"@gui_ctrlid", OpenAutoIt::TokenKind::MK_GUI_CtrlId}, {"@gui_dragfile", OpenAutoIt::TokenKind::MK_GUI_DragFile}, {"@gui_dragid", OpenAutoIt::TokenKind::MK_GUI_DragId}, {"@gui_dropid", OpenAutoIt::TokenKind::MK_GUI_DropId}, {"@gui_winhandle", OpenAutoIt::TokenKind::MK_GUI_WinHandle}, {"@homedrive", OpenAutoIt::TokenKind::MK_HomeDrive}, {"@homepath", OpenAutoIt::TokenKind::MK_HomePath}, {"@homeshare", OpenAutoIt::TokenKind::MK_HomeShare}, {"@hotkeypressed", OpenAutoIt::TokenKind::MK_HotKeyPressed}, {"@hour", OpenAutoIt::TokenKind::MK_HOUR}, {"@ipaddress1", OpenAutoIt::TokenKind::MK_IPAddress1}, {"@ipaddress2", OpenAutoIt::TokenKind::MK_IPAddress2}, {"@ipaddress3", OpenAutoIt::TokenKind::MK_IPAddress3}, {"@ipaddress4", OpenAutoIt::TokenKind::MK_IPAddress4}, {"@kblayout", OpenAutoIt::TokenKind::MK_KBLayout}, {"@lf", OpenAutoIt::TokenKind::MK_LF}, {"@localappdatadir", OpenAutoIt::TokenKind::MK_LocalAppDataDir}, {"@logondnsdomain", OpenAutoIt::TokenKind::MK_LogonDNSDomain}, {"@logondomain", OpenAutoIt::TokenKind::MK_LogonDomain}, {"@logonserver", OpenAutoIt::TokenKind::MK_LogonServer}, {"@mday", OpenAutoIt::TokenKind::MK_MDAY}, {"@min", OpenAutoIt::TokenKind::MK_MIN}, {"@mon", OpenAutoIt::TokenKind::MK_MON}, {"@msec", OpenAutoIt::TokenKind::MK_MSEC}, {"@muilang", OpenAutoIt::TokenKind::MK_MUILang}, {"@mydocumentsdir", OpenAutoIt::TokenKind::MK_MyDocumentsDir}, {"@numparams", OpenAutoIt::TokenKind::MK_NumParams}, {"@osarch", OpenAutoIt::TokenKind::MK_OSArch}, {"@osbuild", OpenAutoIt::TokenKind::MK_OSBuild}, {"@oslang", OpenAutoIt::TokenKind::MK_OSLang}, {"@osservicepack", OpenAutoIt::TokenKind::MK_OSServicePack}, {"@ostype", OpenAutoIt::TokenKind::MK_OSType}, {"@osversion", OpenAutoIt::TokenKind::MK_OSVersion}, {"@programfilesdir", OpenAutoIt::TokenKind::MK_ProgramFilesDir}, {"@programscommondir", OpenAutoIt::TokenKind::MK_ProgramsCommonDir}, {"@programsdir", OpenAutoIt::TokenKind::MK_ProgramsDir}, {"@scriptdir", OpenAutoIt::TokenKind::MK_ScriptDir}, {"@scriptfullpath", OpenAutoIt::TokenKind::MK_ScriptFullPath}, {"@scriptlinenumber", OpenAutoIt::TokenKind::MK_ScriptLineNumber}, {"@scriptname", OpenAutoIt::TokenKind::MK_ScriptName}, {"@sec", OpenAutoIt::TokenKind::MK_SEC}, {"@startmenucommondir", OpenAutoIt::TokenKind::MK_StartMenuCommonDir}, {"@startmenudir", OpenAutoIt::TokenKind::MK_StartMenuDir}, {"@startupcommondir", OpenAutoIt::TokenKind::MK_StartupCommonDir}, {"@startupdir", OpenAutoIt::TokenKind::MK_StartupDir}, {"@sw_disable", OpenAutoIt::TokenKind::MK_SW_DISABLE}, {"@sw_enable", OpenAutoIt::TokenKind::MK_SW_ENABLE}, {"@sw_hide", OpenAutoIt::TokenKind::MK_SW_HIDE}, {"@sw_lock", OpenAutoIt::TokenKind::MK_SW_LOCK}, {"@sw_maximize", OpenAutoIt::TokenKind::MK_SW_MAXIMIZE}, {"@sw_minimize", OpenAutoIt::TokenKind::MK_SW_MINIMIZE}, {"@sw_restore", OpenAutoIt::TokenKind::MK_SW_RESTORE}, {"@sw_show", OpenAutoIt::TokenKind::MK_SW_SHOW}, {"@sw_showdefault", OpenAutoIt::TokenKind::MK_SW_SHOWDEFAULT}, {"@sw_showmaximized", OpenAutoIt::TokenKind::MK_SW_SHOWMAXIMIZED}, {"@sw_showminimized", OpenAutoIt::TokenKind::MK_SW_SHOWMINIMIZED}, {"@sw_showminnoactive", OpenAutoIt::TokenKind::MK_SW_SHOWMINNOACTIVE}, {"@sw_showna", OpenAutoIt::TokenKind::MK_SW_SHOWNA}, {"@sw_shownoactivate", OpenAutoIt::TokenKind::MK_SW_SHOWNOACTIVATE}, {"@sw_shownormal", OpenAutoIt::TokenKind::MK_SW_SHOWNORMAL}, {"@sw_unlock", OpenAutoIt::TokenKind::MK_SW_UNLOCK}, {"@systemdir", OpenAutoIt::TokenKind::MK_SystemDir}, {"@tab", OpenAutoIt::TokenKind::MK_TAB}, {"@tempdir", OpenAutoIt::TokenKind::MK_TempDir}, {"@tray_id", OpenAutoIt::TokenKind::MK_TRAY_ID}, {"@trayiconflashing", OpenAutoIt::TokenKind::MK_TrayIconFlashing}, {"@trayiconvisible", OpenAutoIt::TokenKind::MK_TrayIconVisible}, {"@username", OpenAutoIt::TokenKind::MK_UserName}, {"@userprofiledir", OpenAutoIt::TokenKind::MK_UserProfileDir}, {"@wday", OpenAutoIt::TokenKind::MK_WDAY}, {"@windowsdir", OpenAutoIt::TokenKind::MK_WindowsDir}, {"@workingdir", OpenAutoIt::TokenKind::MK_WorkingDir}, {"@yday", OpenAutoIt::TokenKind::MK_YDAY}, {"@year", OpenAutoIt::TokenKind::MK_YEAR}, }}; [[nodiscard]] OpenAutoIt::TokenKind lookup_macro(phi::string_view token) noexcept { static constexpr auto map = LookUpMap<phi::string_view, OpenAutoIt::TokenKind, MacroValues.size()>( MacroValues, OpenAutoIt::TokenKind::NotAToken); std::string str{token.begin(), token.end()}; std::transform(str.begin(), str.end(), str.begin(), ::tolower); return map.at({str}); } static constexpr std::array<std::pair<phi::string_view, OpenAutoIt::TokenKind>, 10u> PreProcessorValues{{ {"#comments-start", OpenAutoIt::TokenKind::PP_CommentsStart}, {"#comments-end", OpenAutoIt::TokenKind::PP_CommentsEnd}, {"#cs", OpenAutoIt::TokenKind::PP_CS}, {"#ce", OpenAutoIt::TokenKind::PP_CE}, {"#include", OpenAutoIt::TokenKind::PP_Include}, {"#include-once", OpenAutoIt::TokenKind::PP_IncludeOnce}, {"#notrayicon", OpenAutoIt::TokenKind::PP_NoTrayIcon}, {"#onautoitstartregister", OpenAutoIt::TokenKind::PP_OnAutoItStartRegister}, {"#pragma", OpenAutoIt::TokenKind::PP_Pragma}, {"#requireadmin", OpenAutoIt::TokenKind::PP_RequireAdmin}, }}; [[nodiscard]] OpenAutoIt::TokenKind lookup_pre_processor(phi::string_view token) noexcept { static constexpr auto map = LookUpMap<phi::string_view, OpenAutoIt::TokenKind, PreProcessorValues.size()>( PreProcessorValues, OpenAutoIt::TokenKind::NotAToken); std::string str{token.begin(), token.end()}; std::transform(str.begin(), str.end(), str.begin(), ::tolower); return map.at({str}); } static constexpr std::array<std::pair<phi::string_view, OpenAutoIt::TokenKind>, 43u> KeyWordsValues{ {{"false", OpenAutoIt::TokenKind::KW_False}, {"true", OpenAutoIt::TokenKind::KW_True}, {"continuecase", OpenAutoIt::TokenKind::KW_ContinueCase}, {"continueloop", OpenAutoIt::TokenKind::KW_ContinueLoop}, {"default", OpenAutoIt::TokenKind::KW_Default}, {"dim", OpenAutoIt::TokenKind::KW_Dim}, {"local", OpenAutoIt::TokenKind::KW_Local}, {"global", OpenAutoIt::TokenKind::KW_Global}, {"const", OpenAutoIt::TokenKind::KW_Const}, {"do", OpenAutoIt::TokenKind::KW_Do}, {"until", OpenAutoIt::TokenKind::KW_Until}, {"enum", OpenAutoIt::TokenKind::KW_Enum}, {"exit", OpenAutoIt::TokenKind::KW_Exit}, {"exitloop", OpenAutoIt::TokenKind::KW_ExitLoop}, {"for", OpenAutoIt::TokenKind::KW_For}, {"to", OpenAutoIt::TokenKind::KW_To}, {"step", OpenAutoIt::TokenKind::KW_Step}, {"next", OpenAutoIt::TokenKind::KW_Next}, {"in", OpenAutoIt::TokenKind::KW_In}, {"func", OpenAutoIt::TokenKind::KW_Func}, {"return", OpenAutoIt::TokenKind::KW_Return}, {"endfunc", OpenAutoIt::TokenKind::KW_EndFunc}, {"if", OpenAutoIt::TokenKind::KW_If}, {"then", OpenAutoIt::TokenKind::KW_Then}, {"endif", OpenAutoIt::TokenKind::KW_EndIf}, {"elseif", OpenAutoIt::TokenKind::KW_ElseIf}, {"else", OpenAutoIt::TokenKind::KW_Else}, {"null", OpenAutoIt::TokenKind::KW_Null}, {"redim", OpenAutoIt::TokenKind::KW_ReDim}, {"select", OpenAutoIt::TokenKind::KW_Select}, {"case", OpenAutoIt::TokenKind::KW_Case}, {"endselect", OpenAutoIt::TokenKind::KW_EndSelect}, {"static", OpenAutoIt::TokenKind::KW_Static}, {"switch", OpenAutoIt::TokenKind::KW_Switch}, {"endswitch", OpenAutoIt::TokenKind::KW_EndSwitch}, {"volatile", OpenAutoIt::TokenKind::KW_Volatile}, {"while", OpenAutoIt::TokenKind::KW_While}, {"wend", OpenAutoIt::TokenKind::KW_WEnd}, {"with", OpenAutoIt::TokenKind::KW_With}, {"endwith", OpenAutoIt::TokenKind::KW_EndWith}, {"and", OpenAutoIt::TokenKind::KW_And}, {"or", OpenAutoIt::TokenKind::KW_Or}, {"not", OpenAutoIt::TokenKind::KW_Not}}}; [[nodiscard]] OpenAutoIt::TokenKind lookup_identifier(phi::string_view token) noexcept { static constexpr auto map = LookUpMap<phi::string_view, OpenAutoIt::TokenKind, KeyWordsValues.size()>( KeyWordsValues, OpenAutoIt::TokenKind::FunctionIdentifier); std::string str{token.begin(), token.end()}; std::transform(str.begin(), str.end(), str.begin(), ::tolower); return map.at({str}); } static constexpr std::array<std::pair<phi::string_view, OpenAutoIt::TokenKind>, 20u> OperatorValues{ {{"=", OpenAutoIt::TokenKind::OP_Equals}, {"+=", OpenAutoIt::TokenKind::OP_PlusEquals}, {"-=", OpenAutoIt::TokenKind::OP_MinusEquals}, {"*=", OpenAutoIt::TokenKind::OP_MultiplyEquals}, {"/=", OpenAutoIt::TokenKind::OP_DivideEquals}, {"&", OpenAutoIt::TokenKind::OP_Concatenate}, {"&=", OpenAutoIt::TokenKind::OP_ConcatenateEquals}, {"+", OpenAutoIt::TokenKind::OP_Plus}, {"-", OpenAutoIt::TokenKind::OP_Minus}, {"*", OpenAutoIt::TokenKind::OP_Multiply}, {"/", OpenAutoIt::TokenKind::OP_Divide}, {"^", OpenAutoIt::TokenKind::OP_Raise}, {"==", OpenAutoIt::TokenKind::OP_EqualsEquals}, {"<>", OpenAutoIt::TokenKind::OP_NotEqual}, {">", OpenAutoIt::TokenKind::OP_GreaterThan}, {">=", OpenAutoIt::TokenKind::OP_GreaterThanEqual}, {"<", OpenAutoIt::TokenKind::OP_LessThan}, {"<=", OpenAutoIt::TokenKind::OP_LessThanEqual}, {"?", OpenAutoIt::TokenKind::OP_TernaryIf}, {":", OpenAutoIt::TokenKind::OP_TernaryElse}}}; [[nodiscard]] OpenAutoIt::TokenKind lookup_operator(phi::string_view token) noexcept { static constexpr auto map = LookUpMap<phi::string_view, OpenAutoIt::TokenKind, OperatorValues.size()>( OperatorValues, OpenAutoIt::TokenKind::NotAToken); return map.at(token); } [[nodiscard]] constexpr phi::boolean is_skip_character(const char c) noexcept { switch (c) { case ' ': case '\v': case '\t': return true; default: return false; } } [[nodiscard]] constexpr phi::boolean is_numeric(const char c) noexcept { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; default: return false; } } [[nodiscard]] constexpr phi::boolean is_alpha(const char c) noexcept { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } [[nodiscard]] constexpr phi::boolean is_alpha_numeric(const char c) noexcept { return is_numeric(c) || is_alpha(c); } [[nodiscard]] constexpr phi::boolean is_valid_identifier_char(const char c) noexcept { return is_alpha_numeric(c) || c == '_'; } [[nodiscard]] constexpr phi::boolean is_valid_pp_char(const char c) noexcept { return is_alpha_numeric(c) || c == '-'; } [[nodiscard]] constexpr phi::boolean is_two_part_operator(const char c) noexcept { switch (c) { case '=': case '+': case '-': case '*': case '/': case '&': case '<': case '>': return true; default: return false; } } [[nodiscard]] constexpr phi::boolean is_single_operator(const char c) noexcept { switch (c) { case '^': case '?': case ':': return true; default: return false; } } namespace OpenAutoIt { Lexer::Lexer() noexcept : m_Iterator{m_Source.begin()} {} Lexer::Lexer(phi::string_view source) noexcept : m_Source{source} , m_Iterator{source.begin()} {} void Lexer::SetInputSource(phi::string_view source) noexcept { m_Source = source; Reset(); } void Lexer::Reset() noexcept { m_Iterator = m_Source.begin(); m_LineNumber = 1u; m_Column = 1u; m_CurrentTokenBegin = 0u; } phi::boolean Lexer::IsFinished() const noexcept { return m_Iterator == m_Source.end(); } phi::boolean Lexer::HasInput() const noexcept { return !m_Source.is_empty(); } phi::optional<Token> Lexer::GetNextToken() noexcept { // TODO: #cs and #ce are not correctly parsed as comments while (!IsFinished()) { char current_character = *m_Iterator; /* Embeded null character */ if (current_character == '\0') { // TODO: Warn embeded null character SkipCurrentCharacter(); } /* Skip characters */ else if (is_skip_character(current_character)) { SkipCurrentCharacter(); } /* New Lines */ else if (current_character == '\n') { Token new_line_token = ConstructToken(TokenKind::NewLine); ConsumeCurrentCharacter(); AdvanceToNextLine(); return new_line_token; } /* Comment */ else if (current_character == ';') { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (current_character != '\n') { ConsumeCurrentCharacter(); continue; } break; } return ConstructToken(TokenKind::Comment, begin_of_token); } /* Macros */ else if (current_character == '@') { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (is_valid_identifier_char(current_character)) { ConsumeCurrentCharacter(); continue; } break; } // Emit token return ConstructToken(lookup_macro(TokenText(begin_of_token)), begin_of_token); } /* Variable identifier */ else if (current_character == '$') { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (is_valid_identifier_char(current_character)) { ConsumeCurrentCharacter(); continue; } break; } // Emit Token return ConstructToken(TokenKind::VariableIdentifier, begin_of_token); } /* PreProcessor directive */ else if (current_character == '#') { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (is_valid_pp_char(current_character)) { ConsumeCurrentCharacter(); continue; } break; } return ConstructToken(lookup_pre_processor(TokenText(begin_of_token)), begin_of_token); } /* SingleQuoteStringLiteral */ else if (current_character == '\'') { iterator begin_of_token = m_Iterator; phi::boolean did_terminate = false; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; ConsumeCurrentCharacter(); if (current_character == '\'') { did_terminate = true; break; } } if (did_terminate) { return ConstructToken(TokenKind::StringLiteral, begin_of_token); } // TODO: Warn unterminated string literal } /* DoubleQuoteStringLiteral */ else if (current_character == '\"') { iterator begin_of_token = m_Iterator; phi::boolean did_terminate = false; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; ConsumeCurrentCharacter(); if (current_character == '\"') { did_terminate = true; break; } } if (did_terminate) { return ConstructToken(TokenKind::StringLiteral, begin_of_token); } } /* Number Literals */ else if (is_numeric(current_character)) { // TODO: Support float literals // TODO: Suppport hex literals iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (is_numeric(current_character)) { ConsumeCurrentCharacter(); continue; } break; } return ConstructToken(TokenKind::IntegerLiteral, begin_of_token); } /* Operators */ else if (is_two_part_operator(current_character)) { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); if (!IsFinished()) { if (*m_Iterator == '=' || (*begin_of_token == '<' && *m_Iterator == '>')) { // We have an actual two part operator ConsumeCurrentCharacter(); } } return ConstructToken(lookup_operator(TokenText(begin_of_token)), begin_of_token); } else if (is_single_operator(current_character)) { Token token = ConstructToken(lookup_operator({m_Iterator})); ConsumeCurrentCharacter(); return token; } /* Punctioation */ else if (current_character == ',') { Token token = ConstructToken(TokenKind::Comma); ConsumeCurrentCharacter(); return token; } else if (current_character == '(') { Token token = ConstructToken(TokenKind::LParen); ConsumeCurrentCharacter(); return token; } else if (current_character == ')') { Token token = ConstructToken(TokenKind::RParen); ConsumeCurrentCharacter(); return token; } else if (current_character == '.') { Token token = ConstructToken(TokenKind::Dot); ConsumeCurrentCharacter(); return token; } else if (current_character == '[') { Token token = ConstructToken(TokenKind::LSquare); ConsumeCurrentCharacter(); return token; } else if (current_character == ']') { Token token = ConstructToken(TokenKind::RSquare); ConsumeCurrentCharacter(); return token; } /* Identifier */ else if (is_valid_identifier_char(current_character)) { iterator begin_of_token = m_Iterator; ConsumeCurrentCharacter(); while (!IsFinished()) { current_character = *m_Iterator; if (is_valid_identifier_char(current_character)) { ConsumeCurrentCharacter(); continue; } break; } return ConstructToken(lookup_identifier(TokenText(begin_of_token)), begin_of_token); } /* Unknown/Unexpected character */ else { // TODO: Warn unexpected character encountered SkipCurrentCharacter(); } } return {}; } TokenStream Lexer::ProcessAll() noexcept { TokenStream stream; while (!IsFinished()) { phi::optional<Token> maybe_token = GetNextToken(); if (maybe_token.has_value()) { stream.emplace_back(maybe_token.value()); } } stream.finalize(); return stream; } TokenStream Lexer::ProcessString(phi::string_view source) noexcept { SetInputSource(source); return ProcessAll(); } void Lexer::ConsumeCurrentCharacter() noexcept { ++m_Iterator; } void Lexer::AdvanceToNextLine() noexcept { ++m_LineNumber; m_Column = 1u; } void Lexer::SkipCurrentCharacter() noexcept { ConsumeCurrentCharacter(); ++m_Column; } } // namespace OpenAutoIt
33.940104
100
0.553441
[ "transform" ]
ebf579a26af66af1c8fdbc72bff9a3118212d42f
3,603
cc
C++
gpu/config/gpu_driver_bug_list.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
gpu/config/gpu_driver_bug_list.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
gpu/config/gpu_driver_bug_list.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/config/gpu_driver_bug_list.h" #include "base/check_op.h" #include "base/stl_util.h" #include "gpu/config/gpu_driver_bug_list_autogen.h" #include "gpu/config/gpu_driver_bug_workaround_type.h" #include "gpu/config/gpu_switches.h" #include "gpu/config/gpu_util.h" namespace gpu { namespace { struct GpuDriverBugWorkaroundInfo { GpuDriverBugWorkaroundType type; const char* name; }; const GpuDriverBugWorkaroundInfo kFeatureList[] = { #define GPU_OP(type, name) { type, #name }, GPU_DRIVER_BUG_WORKAROUNDS(GPU_OP) #undef GPU_OP }; } // namespace anonymous GpuDriverBugList::GpuDriverBugList(const GpuControlListData& data) : GpuControlList(data) {} GpuDriverBugList::~GpuDriverBugList() = default; // static std::unique_ptr<GpuDriverBugList> GpuDriverBugList::Create() { GpuControlListData data(kGpuDriverBugListEntryCount, kGpuDriverBugListEntries); return Create(data); } // static std::unique_ptr<GpuDriverBugList> GpuDriverBugList::Create( const GpuControlListData& data) { std::unique_ptr<GpuDriverBugList> list(new GpuDriverBugList(data)); DCHECK_EQ(static_cast<int>(base::size(kFeatureList)), NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES); for (int i = 0; i < NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES; ++i) { list->AddSupportedFeature(kFeatureList[i].name, kFeatureList[i].type); } return list; } std::string GpuDriverBugWorkaroundTypeToString( GpuDriverBugWorkaroundType type) { if (type < NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES) return kFeatureList[type].name; else return "unknown"; } // static void GpuDriverBugList::AppendWorkaroundsFromCommandLine( std::set<int>* workarounds, const base::CommandLine& command_line) { DCHECK(workarounds); for (int i = 0; i < NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES; i++) { if (command_line.HasSwitch(kFeatureList[i].name)) { // Check for disabling workaround flag. if (command_line.GetSwitchValueASCII(kFeatureList[i].name) == "0") { workarounds->erase(kFeatureList[i].type); continue; } // Removing conflicting workarounds. switch (kFeatureList[i].type) { case FORCE_HIGH_PERFORMANCE_GPU: workarounds->erase(FORCE_LOW_POWER_GPU); workarounds->insert(FORCE_HIGH_PERFORMANCE_GPU); break; case FORCE_LOW_POWER_GPU: workarounds->erase(FORCE_HIGH_PERFORMANCE_GPU); workarounds->insert(FORCE_LOW_POWER_GPU); break; default: workarounds->insert(kFeatureList[i].type); break; } } } } // static void GpuDriverBugList::AppendAllWorkarounds( std::vector<const char*>* workarounds) { static_assert(std::extent<decltype(kFeatureList)>::value == NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES, "Expected kFeatureList to include all gpu workarounds"); DCHECK(workarounds->empty()); workarounds->resize(NUMBER_OF_GPU_DRIVER_BUG_WORKAROUND_TYPES); size_t i = 0; for (const GpuDriverBugWorkaroundInfo& feature : kFeatureList) (*workarounds)[i++] = feature.name; } // static bool GpuDriverBugList::AreEntryIndicesValid( const std::vector<uint32_t>& entry_indices) { return GpuControlList::AreEntryIndicesValid(entry_indices, kGpuDriverBugListEntryCount); } } // namespace gpu
30.533898
75
0.706911
[ "vector" ]
ebfaff94f77c07d3658296a945b6bf3f6b5ad7cc
3,410
hpp
C++
src/utility/jb_launchargs.hpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
src/utility/jb_launchargs.hpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
8
2015-02-24T19:38:35.000Z
2016-05-25T02:33:48.000Z
src/utility/jb_launchargs.hpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
#ifndef JADEBASE_LAUNCHARGS_HPP #define JADEBASE_LAUNCHARGS_HPP /* * jb_launchargs.hpp * * Functions for parsing & accessing launch arguments and their values * * None of the getXYZ() functions are considered valid until parseLaunchArgs() * has been called, after which they will always return the same value. It is * assumed the program will only call parseLaunchArgs() once, on startup. * */ /* INCLUDES *******************************************************************//******************************************************************************/ #include <string> #include <vector> /******************************************************************************//******************************************************************************/ namespace jade { typedef bool (* launcharg_callback )( std::string ); // Argument parsing functions take a string and return a bool (whether the // parser should continue or should exit, for example after the version flag). void registerArgParser( launcharg_callback, // The function to be called when the flag is encountered char, // The single-character version of the flag, e.g. "d" (parsed after a "-") std::string, // The long version of the flag, e.g. "developer-mode" (parsed after a "--") bool, // Whether the flag requires an argument to follow std::string, // A string describing what type of argument to pass, e.g. "FILE" std::string ); // A help string describing the purpose and use of the flag // Note: registerArgParser() is not thread-safe bool parseLaunchArgs( int argc, char* argv[] ); // Returns true if the program should continue after parsing, false if exit void initFromLaunchArgs(); // Does any special stuff we may need to do only after platform code is called bool getDevMode(); // Get whether developer mode is enabled std::string getLogFileName(); // Get the path to the log file set at startup long getTaskThreadLimit(); // Get the max number of threads available to the task system (>=1 or -1) std::string getUserSettingsFileName(); // Get the path to the user settings file set at startup std::string getMainScriptFileName(); // Get the path to the main Lua script file float getGUIScaleOverride(); // Get the GUI scale override if any, or NaN if no override given } /******************************************************************************//******************************************************************************/ #endif
66.862745
160
0.431085
[ "vector" ]
ebfc02901dbe05da95fea41625993889a7dc9da4
4,646
cxx
C++
src/fsw/FswEfcSampler.cxx
fermi-lat/configData
3b824540d8173a24be12316a3821304e4ea20a1f
[ "BSD-3-Clause" ]
null
null
null
src/fsw/FswEfcSampler.cxx
fermi-lat/configData
3b824540d8173a24be12316a3821304e4ea20a1f
[ "BSD-3-Clause" ]
null
null
null
src/fsw/FswEfcSampler.cxx
fermi-lat/configData
3b824540d8173a24be12316a3821304e4ea20a1f
[ "BSD-3-Clause" ]
null
null
null
//--------------------------------------------------------------------------- // File and Version Information: // $Id: FswEfcSampler.cxx,v 1.2 2008/06/12 01:56:54 echarles Exp $ // // Description: // A GEM ROI register class // // Environment: // Software developed for GLAST. // // Author List: // Martin Kocian // // Copyright Information: // Copyright (C) 2005 Stanford Linear Accelerator Center // //--------------------------------------------------------------------------- #include "configData/fsw/FswEfcSampler.h" #include <iomanip> #include <algorithm> #include "xmlBase/Dom.h" #include "xmlBase/XmlParser.h" #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMDocument.hpp> #include "facilities/Util.h" FswEfcSampler* FswEfcSampler::makeFromXmlFile(const char* fileName) { static xmlBase::XmlParser parser(true); xmlBase::DOMDocument* doc(0); try { doc =parser.parse( fileName ); } catch (xmlBase::ParseException ex) { std::cerr << "caught exception with message " << std::endl; std::cerr << ex.getMsg() << std::endl; return 0; } xmlBase::DOMElement* elt = doc->getDocumentElement(); if ( elt == 0 ) return 0; std::vector<xmlBase::DOMElement*> enabledList; std::vector<xmlBase::DOMElement*> inputPSList; std::vector<xmlBase::DOMElement*> outputPSList; std::vector<xmlBase::DOMElement*> psList; xmlBase::Dom::getDescendantsByTagName(elt,"Enabled",enabledList); xmlBase::Dom::getDescendantsByTagName(elt,"Input_Prescale",inputPSList); xmlBase::Dom::getDescendantsByTagName(elt,"Output_Prescale",outputPSList); xmlBase::Dom::getDescendantsByTagName(elt,"Prescale",psList); if ( enabledList.size() != 1 || inputPSList.size() != 1 || outputPSList.size() != 1 || psList.size() != 32 ) return 0; std::string enabledSt = xmlBase::Dom::getTextContent( enabledList[0] ); std::string inputSt = xmlBase::Dom::getTextContent( inputPSList[0] ); std::string outputSt = xmlBase::Dom::getTextContent( outputPSList[0] ); FswEfcSampler* retVal(0); try { unsigned enabled = facilities::Util::stringToUnsigned( enabledSt ); unsigned input = facilities::Util::stringToUnsigned( inputSt ); unsigned output = facilities::Util::stringToUnsigned( outputSt ); unsigned ps[32]; for ( int i(0); i < 32; i++ ) { std::string psSt = xmlBase::Dom::getTextContent(psList[i]); int lineNum = xmlBase::Dom::getIntAttribute(psList[i],"line"); ps[lineNum] = facilities::Util::stringToUnsigned(psSt); } retVal = new FswEfcSampler; retVal->set(ps,input,output,enabled); } catch (...) { delete retVal; return 0; } return retVal; } unsigned FswEfcSampler::mapKey(unsigned lpaMode, unsigned handlerId) { return (lpaMode << 8) | handlerId; } FswEfcSampler::FswEfcSampler() :ConfigBranch("Prescales",'i',ChannelKey(32)){ clear(); } void FswEfcSampler::clear(){ for (int i=0;i<32;i++){ m_prescalers[i]=0; } m_inputPrescaler = 0; m_outputPrescaler = 0; m_enabled = 0; } void FswEfcSampler::set(unsigned prescalers[32], unsigned input, unsigned output, unsigned enabled){ for ( int i(0); i < 32; i++ ) { m_prescalers[i] = prescalers[i]; } m_inputPrescaler = input; m_outputPrescaler = output; m_enabled = enabled; } unsigned FswEfcSampler::prescaleFactor(enums::Lsf::RsdState rsdState, enums::Lsf::LeakedPrescaler leakedPrescaler) const { switch ( rsdState ) { case enums::Lsf::VETOED: return 0; case enums::Lsf::PASSED: return 1; case enums::Lsf::IGNORED: return m_inputPrescaler; case enums::Lsf::INVALID: return LSF_INVALID_UINT; case enums::Lsf::SUPPRESSED: case enums::Lsf::LEAKED: if ( leakedPrescaler >= 0 ) { return m_prescalers[leakedPrescaler]; } else if ( leakedPrescaler == enums::Lsf::OUTPUT ) { return m_outputPrescaler; } else if ( leakedPrescaler == enums::Lsf::INPUT ) { return m_inputPrescaler; } break; } return LSF_INVALID_UINT; } // Attach this value to a TTree void FswEfcSampler::makeBranch(TTree& /* tree */, const std::string& /* prefix */) const { return; } void FswEfcSampler::attach(TTree& tree, const std::string& prefix) const { return; } std::ostream& operator <<(std::ostream& os, const FswEfcSampler& tc){ os<<"Input Prescale: " << tc.inputPrescaler() <<std::endl; os<<"Output Prescale: " << tc.outputPrescaler() <<std::endl; os<<"Prescales: "<<std::endl; for (int i=0;i<32;i++){ os<< " line " << std::setw(2)<< i <<": " << tc.prescaler(i); os<< ( (tc.enabled() & (1 << i)) ? " On" : " Off") << std::endl; } return os; }
31.391892
122
0.644856
[ "vector" ]
ebfe741192482d2fd1dbfea1cb70000bdf61b62a
35,172
cpp
C++
Game/Source/ModulePlayer.cpp
mrmile/VideogameDevelopment
a69ddf91fcb9401078084e77f9377e8a59769b92
[ "MIT" ]
null
null
null
Game/Source/ModulePlayer.cpp
mrmile/VideogameDevelopment
a69ddf91fcb9401078084e77f9377e8a59769b92
[ "MIT" ]
null
null
null
Game/Source/ModulePlayer.cpp
mrmile/VideogameDevelopment
a69ddf91fcb9401078084e77f9377e8a59769b92
[ "MIT" ]
null
null
null
#include "ModulePlayer.h" #include "app.h" #include "Textures.h" #include "Input.h" #include "Render.h" #include "Enemies.h" #include "Enemy.h" //#include "ModuleParticles.h" #include "Audio.h" #include "ModuleFadeToBlack.h" #include "Window.h" //#include "ModuleFonts.h" #include "Log.h" #include "SceneForest.h" #include "SceneCastle.h" #include "Map.h" #include "ModulePhysics.h" #include "ModuleCollisions.h" #include "ModuleParticles.h" #include "Audio.h" #include "TitleScreen.h" #include "ModuleFonts.h" #include <stdio.h> #include <time.h> #include <SDL_mixer/include/SDL_mixer.h> #include <iostream> #include <Optick/include/optick.h> using namespace std; ModulePlayer::ModulePlayer(bool start_enabled) : Module(start_enabled) { name.Create("player"); // idle left idleLeftAnim.PushBack({ 0, 167, 28, 33 }); idleLeftAnim.PushBack({ 27, 167, 28, 33 }); idleLeftAnim.PushBack({ 54, 167, 28, 33 }); idleLeftAnim.PushBack({ 82, 167, 28, 33 }); idleLeftAnim.PushBack({ 109, 167, 27, 33 }); idleLeftAnim.PushBack({ 135, 167, 28, 33 }); idleLeftAnim.PushBack({ 162, 167, 28, 33 }); idleLeftAnim.PushBack({ 189, 167, 28, 33 }); idleLeftAnim.loop = true; idleLeftAnim.speed = 0.15f; // idle left idleRightAnim.PushBack({ 190, 207, 28, 33 }); idleRightAnim.PushBack({ 163, 207, 28, 33 }); idleRightAnim.PushBack({ 136, 207, 28, 33 }); idleRightAnim.PushBack({ 108, 207, 28, 33 }); idleRightAnim.PushBack({ 82, 207, 27, 33 }); idleRightAnim.PushBack({ 55, 207, 28, 33 }); idleRightAnim.PushBack({ 28, 207, 28, 33 }); idleRightAnim.PushBack({ 1, 207, 28, 33 }); idleRightAnim.loop = true; idleRightAnim.speed = 0.15f; // idle left 2 idleLeftAnim2.PushBack({ 0, 247, 27, 33 }); idleLeftAnim2.PushBack({ 27, 247, 27, 33 }); idleLeftAnim2.PushBack({ 53, 247, 27, 33 }); idleLeftAnim2.PushBack({ 79, 247, 27, 33 }); idleLeftAnim2.PushBack({ 105, 247, 27, 33 }); idleLeftAnim2.PushBack({ 131, 247, 27, 33 }); idleLeftAnim2.PushBack({ 157, 247, 27, 33 }); idleLeftAnim2.PushBack({ 131, 247, 27, 33 }); idleLeftAnim2.PushBack({ 157, 247, 27, 33 }); idleLeftAnim2.PushBack({ 184, 247, 27, 33 }); idleLeftAnim2.loop = true; idleLeftAnim2.speed = 0.15f; // idle right 2 idleRightAnim2.PushBack({ 184, 287, 27, 33 }); idleRightAnim2.PushBack({ 157, 287, 27, 33 }); idleRightAnim2.PushBack({ 131, 287, 27, 33 }); idleRightAnim2.PushBack({ 105, 287, 27, 33 }); idleRightAnim2.PushBack({ 79, 287, 27, 33 }); idleRightAnim2.PushBack({ 53, 287, 27, 33 }); idleRightAnim2.PushBack({ 27, 287, 27, 33 }); idleRightAnim2.PushBack({ 53, 287, 27, 33 }); idleRightAnim2.PushBack({ 27, 287, 27, 33 }); idleRightAnim2.PushBack({ 0, 287, 27, 33 }); idleRightAnim2.loop = true; idleRightAnim2.speed = 0.15f; // move left leftAnim.PushBack({ 1, 7, 28, 33 }); leftAnim.PushBack({ 28, 7, 28, 33 }); leftAnim.PushBack({ 55, 7, 28, 33 }); leftAnim.PushBack({ 82, 7, 28, 33 }); leftAnim.PushBack({ 109, 7, 28, 33 }); leftAnim.PushBack({ 136, 7, 28, 33 }); leftAnim.PushBack({ 163, 7, 28, 33 }); leftAnim.PushBack({ 190, 7, 28, 33 }); leftAnim.PushBack({ 217, 7, 28, 33 }); leftAnim.PushBack({ 244, 7, 28, 33 }); leftAnim.loop = true; leftAnim.speed = 0.3f; // Move right rightAnim.PushBack({ 244, 47, 28, 33 }); rightAnim.PushBack({ 217, 47, 28, 33 }); rightAnim.PushBack({ 190, 47, 28, 33 }); rightAnim.PushBack({ 163, 47, 28, 33 }); rightAnim.PushBack({ 136, 47, 28, 33 }); rightAnim.PushBack({ 109, 47, 28, 33 }); rightAnim.PushBack({ 82, 47, 28, 33 }); rightAnim.PushBack({ 55, 47, 28, 33 }); rightAnim.PushBack({ 28, 47, 28, 33 }); rightAnim.PushBack({ 1, 47, 28, 33 }); rightAnim.loop = true; rightAnim.speed = 0.3f; // Run left leftRunAnim.PushBack({ 308, 7, 35, 33 }); leftRunAnim.PushBack({ 343, 7, 36, 33 }); leftRunAnim.loop = true; leftRunAnim.speed = 0.3f; // Run right rightRunAnim.PushBack({ 344, 47, 36, 33 }); rightRunAnim.PushBack({ 308, 47, 36, 33 }); rightRunAnim.loop = true; rightRunAnim.speed = 0.3f; // Jump left jumpLeftAnim.PushBack({ 1, 130, 26, 33 }); jumpLeftAnim.loop = false; jumpLeftAnim.speed = 0.3f; // fall fallLeftAnim.PushBack({ 27, 130, 25, 33 }); fallLeftAnim.PushBack({ 51, 130, 25, 33 }); fallLeftAnim.loop = false; fallLeftAnim.speed = 0.3f; // Jump right jumpRightAnim.PushBack({ 52, 90, 28, 33 }); jumpRightAnim.loop = false; jumpRightAnim.speed = 0.3f; // fall fallRightAnim.PushBack({ 28, 90, 25, 33 }); fallRightAnim.PushBack({ 2, 90, 26, 33 }); fallRightAnim.loop = false; fallRightAnim.speed = 0.3f; // hover left hoverLeftAnim.PushBack({ 110, 92, 24, 34 }); hoverLeftAnim.PushBack({ 133, 92, 25, 34 }); hoverLeftAnim.PushBack({ 158, 92, 26, 34 }); hoverLeftAnim.loop = true; hoverLeftAnim.speed = 0.3f; // hover right hoverRightAnim.PushBack({ 158, 132, 24, 34 }); hoverRightAnim.PushBack({ 135, 132, 24, 34 }); hoverRightAnim.PushBack({ 109, 132, 26, 34 }); hoverRightAnim.loop = true; hoverRightAnim.speed = 0.3f; // die left dieLeft.PushBack({ 429, 9, 28, 40 }); dieLeft.PushBack({ 456, 9, 28, 40 }); dieLeft.loop = false; dieLeft.speed = 0.2f; //die right dieRight.PushBack({ 455, 59, 28, 40 }); dieRight.PushBack({ 428, 59, 28, 40 }); dieRight.loop = false; dieRight.speed = 0.2f; } ModulePlayer::~ModulePlayer() { } bool ModulePlayer::Awake() { return true; } bool ModulePlayer::Start() { LOG("Loading player textures"); bool ret = true; texture = app->tex->Load("Assets/textures/player.png"); ptsScore = app->tex->Load("Assets/textures/pts_score.png"); livesForScore = app->tex->Load("Assets/textures/lives_score.png"); gameOverScreen = app->tex->Load("Assets/textures/game_over.png"); yoshiIcon = app->tex->Load("Assets/textures/lives_score_e.png"); clockIcon = app->tex->Load("Assets/textures/clock.png"); currentAnimation = &idleRightAnim; jumpSound = app->audio->LoadFx("Assets/audio/fx/Jump.wav"); hoverSound = app->audio->LoadFx("Assets/audio/fx/Flutter_s.wav"); hoverSoundL = app->audio->LoadFx("Assets/audio/fx/Flutter_l.wav"); dead = app->audio->LoadFx("Assets/audio/fx/dead.wav"); damaged = app->audio->LoadFx("Assets/audio/fx/Whsiup.wav"); halfWayPoint = app->audio->LoadFx("Assets/audio/fx/Advice.wav"); coin = app->audio->LoadFx("Assets/audio/fx/Coin.wav"); recoverLifePowerUp = app->audio->LoadFx("Assets/audio/fx/itemGet.wav"); levelClear = app->audio->LoadFx("Assets/audio/fx/levelClear.wav"); firework = app->audio->LoadFx("Assets/audio/fx/fireworks.wav"); paused = app->audio->LoadFx("Assets/audio/fx/pause.wav"); gameOverfx = app->audio->LoadFx("Assets/audio/fx/GameOver.wav"); //laserFx = app->audio->LoadFx("Assets/Fx/laser.wav"); //explosionFx = app->audio->LoadFx("Assets/Fx/explosion.wav"); //position = app->map->MapToWorld(5, 21); // En el load objects b2VelocitySet.x = 0; b2VelocitySet.y = -0.5f; //position.x = 0; //position.y = 0; //scale = 1 // ofset x = 500 // ofset y = 50 //scale = 2 // ofset Px = 1 = Cx = 2 // ofset Py = 1 = Cy = 2 //app->render->camera.x = app->map->MapToWorld(32, 4100).x; //app->render->camera.y = app->map->MapToWorld(32, 4100).y; destroyed = false; deletePlayer = false; checkPointReached = false; collider = app->collisions->AddCollider({ position.x + 5, position.y + 3, 28, 23 }, Collider::Type::PLAYER, this); //{ position.x + 5, position.y + 3, 28, 33 colliderFeet = app->collisions->AddCollider({ position.x + 5, position.y + 23, 18, 10 }, Collider::Type::PLAYER_FEET, this); Player = app->physics->CreatePlayerBox(position.x, position.y, 28, 33); //app->physics->CreateRectangleSensor(position.x, position.y + 16, 28, 1); //Player = app->physics->CreatePlayerCircle(position.x, position.y, 20); //TestingGround = app->physics->CreateColliderRectangle(app->map->MapToWorld(5, 26).x, app->map->MapToWorld(5, 26).y, 1000, 100); // Tendria que estar en Scene.cpp //TestingGround = app->physics->CreateColliderRectangle(0, 50, 1000, 100); // TODO 0: Notice how a font is loaded and the meaning of all its arguments //char lookupTable[] = { "! ,_./0123456789$;<&?abcdefghijklmnopqrstuvwxyz" }; //scoreFont = app->fonts->Load("Assets/Fonts/rtype_font.png", "! @,_./0123456789$;<&?abcdefghijklmnopqrstuvwxyz", 1); //LOADING FONT FOR GAME char lookupTable[] = { "0123456789" }; scoreFont = app->fonts->Load("Assets/textures/numbersV3.png", lookupTable, 1); PlayerLookingPosition = 2; playerTimer = 0; playerIdleAnimationTimer = 0; hoverTimer = 0; destroyedDelay = 0; winDelay = 0; gameOverDelay = 0; TransationToTilteDelay = 0; jump = false; createPlayer = false; playerWin = false; layerZeroReveal = false; //srand(time(NULL)); uint winWidth, winHeight; app->win->GetWindowSize(winWidth, winHeight); playerHP = 100; invincibleDelay = 120; playerFPS = 0; sceneTimer = 450; pauseMenu = false; return ret; } bool ModulePlayer::Update(float dt) { if (pauseMenu==true) { iPoint NewPosition = position; collider->SetPos(NewPosition.x, NewPosition.y); colliderFeet->SetPos(NewPosition.x + 5, NewPosition.y + 23); return true; } if (pauseMenu == false) { playerFPS++; invincibleDelay++; //OPTICK_EVENT(); collider->SetPos(position.x, position.y); colliderFeet->SetPos(position.x + 5, position.y + 23); playerTimer++; //------------------------------------------------------------------------------------------------------------------------------------------ if (destroyed == false && playerWin == false && app->sceneCastle->godMode == false && app->sceneForest->godMode == false) { if ((playerFPS % 60) == 0) sceneTimer--; if (sceneTimer <= 0) { sceneTimer = 0; app->player->playerHP = 0; } if (app->input->GetKey(SDL_SCANCODE_LEFT) == KeyState::KEY_REPEAT || app->input->GetKey(SDL_SCANCODE_A) == KeyState::KEY_REPEAT) { if (run == false) { if (Player->body->GetLinearVelocity().x >= -2) Player->body->ApplyLinearImpulse({ -5.0f,0 }, { 0,0 }, true); if (currentAnimation != &leftAnim && hover == false) { leftAnim.Reset(); currentAnimation = &leftAnim; } } else if (run == true) { if (Player->body->GetLinearVelocity().x >= -4) Player->body->ApplyLinearImpulse({ -5.0f,0 }, { 0,0 }, true); if (currentAnimation != &leftRunAnim && hover == false) { leftRunAnim.Reset(); currentAnimation = &leftRunAnim; } } PlayerLookingPosition = 1; } if (app->input->GetKey(SDL_SCANCODE_RIGHT) == KeyState::KEY_REPEAT || app->input->GetKey(SDL_SCANCODE_D) == KeyState::KEY_REPEAT) { if (run == false) { if (Player->body->GetLinearVelocity().x <= 2) Player->body->ApplyLinearImpulse({ 5.0f,0 }, { 0,0 }, true); if (currentAnimation != &rightAnim && hover == false) { rightAnim.Reset(); currentAnimation = &rightAnim; } } else if (run == true) { if (Player->body->GetLinearVelocity().x <= 4) Player->body->ApplyLinearImpulse({ 5.0f,0 }, { 0,0 }, true); if (currentAnimation != &rightRunAnim && hover == false) { rightRunAnim.Reset(); currentAnimation = &rightRunAnim; } } PlayerLookingPosition = 2; } if ((app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_DOWN || app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_DOWN) && jump == false && inTheAir == false) { Player->body->ApplyLinearImpulse({ 0,-160 }, { 0,0 }, true); app->audio->PlayFx(jumpSound); //jump = true; } if (Player->body->GetLinearVelocity().y < 0 && (app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_DOWN || app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_DOWN)) { jump = true; } if (Player->body->GetLinearVelocity().y == 0 && app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_IDLE) { jump = false; inTheAir = false; hover = false; hoverTimer = 0; } if ((app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_REPEAT || app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_REPEAT) && Player->body->GetLinearVelocity().y > 0) // <-- { hover = true; run = false; if (hoverTimer < 75) { Player->body->ApplyForce({ 0,-1800 }, { 0,0 }, true); if (hoverTimer < 2 && hover == true) app->audio->PlayFx(hoverSound); if (hoverTimer > 30 && hoverTimer < 34 && hover == true) app->audio->PlayFx(hoverSound); } if (PlayerLookingPosition == 1) { if (Player->body->GetLinearVelocity().x < -1) Player->body->ApplyLinearImpulse({ 3.0f,0 }, { 0,0 }, true); if (currentAnimation != &hoverLeftAnim) { hoverLeftAnim.Reset(); currentAnimation = &hoverLeftAnim; } } if (PlayerLookingPosition == 2) { if (Player->body->GetLinearVelocity().x > 1) Player->body->ApplyLinearImpulse({ -3.0f,0 }, { 0,0 }, true); if (currentAnimation != &hoverRightAnim) { hoverRightAnim.Reset(); currentAnimation = &hoverRightAnim; } } } if (app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_UP && app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_UP) { hover = false; } if (hover == true) { hoverTimer++; } if (hoverTimer > 75) { hover = false; } if (PlayerLookingPosition == 1 && jump == true && hover == false) { if (Player->body->GetLinearVelocity().y < 0) { if (currentAnimation != &jumpLeftAnim) { jumpLeftAnim.Reset(); currentAnimation = &jumpLeftAnim; } } if (Player->body->GetLinearVelocity().y > 0) { if (currentAnimation != &fallLeftAnim) { fallLeftAnim.Reset(); currentAnimation = &fallLeftAnim; } } } if (PlayerLookingPosition == 2 && jump == true && hover == false) { if (Player->body->GetLinearVelocity().y < 0) { if (currentAnimation != &jumpRightAnim) { jumpRightAnim.Reset(); currentAnimation = &jumpRightAnim; } } if (Player->body->GetLinearVelocity().y > 0) { if (currentAnimation != &fallRightAnim) { fallRightAnim.Reset(); currentAnimation = &fallRightAnim; } } } if ((app->input->GetKey(SDL_SCANCODE_X) == KeyState::KEY_REPEAT) || (app->input->GetKey(SDL_SCANCODE_LSHIFT) == KeyState::KEY_REPEAT)) { if (hover == false) run = true; } else { run = false; } /* if (doubleJump == true) { if (app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_DOWN) { if (PlayerLookingPosition == 1) { Player->body->ApplyForce({ 0,-500 }, { 0,0 }, true); doubleJump = false; } if (PlayerLookingPosition == 2) { Player->body->ApplyForce({ 0,-500 }, { 0,0 }, true); doubleJump = false; } } } */ // If no up/down movement detected, set the current animation back to idle if (app->input->GetKey(SDL_SCANCODE_DOWN) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_UP) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_RIGHT) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_LEFT) == KeyState::KEY_IDLE && jump == false && Player->body->GetLinearVelocity().x == 0) { playerIdleAnimationTimer++; speed = 0; switch (PlayerLookingPosition) { case 1: if (playerIdleAnimationTimer <= 180) { if (currentAnimation != &idleLeftAnim) { idleLeftAnim.Reset(); currentAnimation = &idleLeftAnim; } } else if (playerIdleAnimationTimer > 180) // <-- Should be random { if (currentAnimation != &idleLeftAnim2) { idleLeftAnim2.Reset(); currentAnimation = &idleLeftAnim2; } if (playerIdleAnimationTimer >= 243) playerIdleAnimationTimer = 0; // <-- Should also be random } break; case 2: if (playerIdleAnimationTimer <= 180) { if (currentAnimation != &idleRightAnim) { idleRightAnim.Reset(); currentAnimation = &idleRightAnim; } } else if (playerIdleAnimationTimer > 180) // <-- Should be random { if (currentAnimation != &idleRightAnim2) { idleRightAnim2.Reset(); currentAnimation = &idleRightAnim2; } if (playerIdleAnimationTimer >= 243) playerIdleAnimationTimer = 0; // <-- Should also be random } break; } } } //------------------------------------------------------------------------------------------------------------------------------------------ if (destroyed == false && playerWin == false && (app->sceneCastle->godMode == true || app->sceneForest->godMode == true)) { if (app->input->GetKey(SDL_SCANCODE_LEFT) == KeyState::KEY_REPEAT || app->input->GetKey(SDL_SCANCODE_A)) { if (run == false) { if (Player->body->GetLinearVelocity().x >= -2) Player->body->ApplyLinearImpulse({ -5.0f,0 }, { 0,0 }, true); if (currentAnimation != &leftAnim && hover == false) { leftRunAnim.Reset(); currentAnimation = &leftAnim; } } else if (run == true) { if (Player->body->GetLinearVelocity().x >= -4) Player->body->ApplyLinearImpulse({ -5.0f,0 }, { 0,0 }, true); if (currentAnimation != &leftRunAnim && hover == false) { leftRunAnim.Reset(); currentAnimation = &leftRunAnim; } } PlayerLookingPosition = 1; } if (app->input->GetKey(SDL_SCANCODE_RIGHT) == KeyState::KEY_REPEAT || app->input->GetKey(SDL_SCANCODE_D)) { if (run == false) { if (Player->body->GetLinearVelocity().x <= 2) Player->body->ApplyLinearImpulse({ 5.0f,0 }, { 0,0 }, true); if (currentAnimation != &rightAnim && hover == false) { rightAnim.Reset(); currentAnimation = &rightAnim; } } else if (run == true) { if (Player->body->GetLinearVelocity().x <= 4) Player->body->ApplyLinearImpulse({ 5.0f,0 }, { 0,0 }, true); if (currentAnimation != &rightRunAnim && hover == false) { rightAnim.Reset(); currentAnimation = &rightRunAnim; } } PlayerLookingPosition = 2; } if ((app->input->GetKey(SDL_SCANCODE_Z) == KeyState::KEY_DOWN || app->input->GetKey(SDL_SCANCODE_SPACE) == KeyState::KEY_DOWN) && Player->body->GetLinearVelocity().y >= -2) { Player->body->ApplyLinearImpulse({ 0,-160 }, { 0,0 }, true); app->audio->PlayFx(jumpSound); } if (app->input->GetKey(SDL_SCANCODE_X) == KeyState::KEY_REPEAT) { if (hover == false) run = true; } else { run = false; } // If no up/down movement detected, set the current animation back to idle if (app->input->GetKey(SDL_SCANCODE_DOWN) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_UP) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_RIGHT) == KeyState::KEY_IDLE && app->input->GetKey(SDL_SCANCODE_LEFT) == KeyState::KEY_IDLE && jump == false && Player->body->GetLinearVelocity().x == 0) { playerIdleAnimationTimer++; speed = 0; switch (PlayerLookingPosition) { case 1: if (playerIdleAnimationTimer <= 180) { if (currentAnimation != &idleLeftAnim) { idleLeftAnim.Reset(); currentAnimation = &idleLeftAnim; } } else if (playerIdleAnimationTimer > 180) // <-- Should be random { if (currentAnimation != &idleLeftAnim2) { idleLeftAnim2.Reset(); currentAnimation = &idleLeftAnim2; } if (playerIdleAnimationTimer >= 243) playerIdleAnimationTimer = 0; // <-- Should also be random } break; case 2: if (playerIdleAnimationTimer <= 180) { if (currentAnimation != &idleRightAnim) { idleRightAnim.Reset(); currentAnimation = &idleRightAnim; } } else if (playerIdleAnimationTimer > 180) // <-- Should be random { if (currentAnimation != &idleRightAnim2) { idleRightAnim2.Reset(); currentAnimation = &idleRightAnim2; } if (playerIdleAnimationTimer >= 243) playerIdleAnimationTimer = 0; // <-- Should also be random } break; } } } //------------------------------------------------------------------------------------------------------------------------------------------ if (destroyed == true) { if (destroyedDelay < 1) { //Mix_PauseMusic(); app->audio->PlayFx(dead); lives--; } if (PlayerLookingPosition == 1) { if (destroyedDelay < 60) Player->body->SetLinearVelocity(b2VelocitySet); if (currentAnimation != &dieLeft) { dieLeft.Reset(); currentAnimation = &dieLeft; } } if (PlayerLookingPosition == 2) { if (destroyedDelay < 60) Player->body->SetLinearVelocity(b2VelocitySet); if (currentAnimation != &dieRight) { dieRight.Reset(); currentAnimation = &dieRight; } } } //------------------------------------------------------------------------------------------------------------------------------------------ if (playerWin == true) { if (winDelay < 1) { //Mix_PauseMusic(); app->audio->PlayFx(firework); } if (PlayerLookingPosition == 1) { } if (PlayerLookingPosition == 2) { } } /* if ((PlayerLookingPosition == 1) && (position.x < app->render->camera.x / app->win->GetScale() + 190)) { app->render->camera.x -= 5; } if ((PlayerLookingPosition == 2) && (position.x > app->render->camera.x / app->win->GetScale() + 140)) { app->render->camera.x += 5; } */ /* if (lives == 0) { //SDL_Delay(600); <-- Esto pausa el juego completo no hace que se espere algo. app->titleScreen->SavedGame = false; app->titleScreen->Enable(); app->CheckGameRequest(); app->titleScreen->MainMenu = true; app->map->Disable(); app->collisions->Disable(); app->particles->Disable(); app->sceneForest->Disable(); app->player->Disable(); app->enemies->Disable(); app->fonts->Disable(); } */ currentAnimation->Update(); Player->GetPosition(position.x, position.y); //cout << "PosX: " << position.x << " PosY: " << position.y << endl; } if ((app->input->GetKey(SDL_SCANCODE_P) == KEY_DOWN || app->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) && app->player->destroyed == false && app->player->playerWin == false) { app->audio->PlayFx(paused); pauseMenu = !pauseMenu; } //------------------------------------------------------------------------------------------------------------------------------------------ return true; } bool ModulePlayer::PostUpdate() { if (destroyed == true) { destroyedDelay++; } if (playerWin == true) { winDelay++; } if (invincibleDelay <= 120) { if ((playerFPS / 5) % 2 == 0) { SDL_Rect rect = currentAnimation->GetCurrentFrame(); app->render->DrawTexture(texture, position.x, position.y, &rect); } } else { SDL_Rect rect = currentAnimation->GetCurrentFrame(); app->render->DrawTexture(texture, position.x, position.y, &rect); } // Draw UI (score) -------------------------------------- sprintf_s(scoreText, 10, "%5d", score); sprintf_s(lifeText, 10, "%1d", lives); sprintf_s(timerText, 10, "%3d", sceneTimer); app->render->DrawTexture2(yoshiIcon, 5, 28, NULL, 0.0f); app->render->DrawTexture2(clockIcon, 400, 30, NULL, 0.0f); SDL_Rect quad; quad = { 5, 10, playerHP, 10 }; SDL_Rect quad2; quad2 = { 5, 10, 100, 10 }; SDL_Rect bgquad; bgquad = { 3, 8, 104, 14 }; app->render->DrawRectangle2(bgquad, 255, 255, 255, 255, 0.0f, true); app->render->DrawRectangle2(quad2, 200, 200, 200, 255, 0.0f, true); //app->render->DrawRectangle(bgquad, 255, 255, 255, 165, true, true); if (playerHP >= 100) { playerHP = 100; app->render->DrawRectangle2(quad, 0, 255, 0, 255, 0.0f, true); } else if (playerHP > 50) { app->render->DrawRectangle2(quad, 120, 255, 0, 255, 0.0f, true); } else if (playerHP > 20 && playerHP <= 50) { app->render->DrawRectangle2(quad, 255, 255, 0, 255, 0.0f, true); } else { if ((playerFPS / 5) % 2 == 0) { app->render->DrawRectangle2(quad, 255, 0, 0, 255, 0.0f, true); } else { app->render->DrawRectangle2(quad, 255, 150, 0, 255, 0.0f, true); } } if (app->sceneCastle->playerRestart == true) { //horizontalCB = true; app->sceneCastle->sceneTimer = 0; //if (checkPointReached == false) position = app->map->MapToWorld(32, 14); //if (checkPointReached == true) position = app->map->MapToWorld(32, 14); score = 0; app->player->Disable(); app->sceneCastle->Disable(); app->collisions->Disable(); app->map->Disable(); app->enemies->Disable(); app->particles->Disable(); app->fonts->Disable(); if (checkPointReached == false) position = app->map->playerStartPos; if (checkPointReached == true) position = app->map->playerCheckPointPos; app->player->Enable(); app->sceneCastle->Enable(); app->collisions->Enable(); app->map->Enable(); app->enemies->Enable(); app->particles->Enable(); app->fonts->Enable(); app->sceneCastle->playerRestart = false; } if (app->sceneForest->playerRestart == true) { //horizontalCB = true; app->sceneForest->sceneTimer = 0; //if (checkPointReached == false) position = app->map->MapToWorld(32, 14); //if (checkPointReached == true) position = app->map->MapToWorld(32, 14); app->player->Disable(); app->sceneForest->Disable(); app->collisions->Disable(); app->map->Disable(); app->enemies->Disable(); app->particles->Disable(); app->fonts->Disable(); if (checkPointReached == false) position = app->map->playerStartPos; if (checkPointReached == true) position = app->map->playerCheckPointPos; app->player->Enable(); app->sceneForest->Enable(); app->collisions->Enable(); app->map->Enable(); app->enemies->Enable(); app->particles->Enable(); app->fonts->Enable(); app->sceneForest->playerRestart = false; } if (app->titleScreen->toTitleScreen == true) { gameOverDelay++; app->render->DrawTexture2(gameOverScreen, 0, 0, NULL, 0.0f); if (gameOverDelay > 1 && gameOverDelay <= 2) app->audio->PlayFx(gameOverfx); if (gameOverDelay > 600 && gameOverDelay <= 601) { app->titleScreen->SavedGame = false; app->titleScreen->Enable(); app->CheckGameRequest(); app->map->Disable(); app->collisions->Disable(); app->particles->Disable(); app->sceneForest->Disable(); app->player->Disable(); app->enemies->Disable(); app->fonts->Disable(); app->titleScreen->toTitleScreen = false; } } // TODO 3: Blit the text of the score in at the bottom of the screen app->render->DrawTexture2(ptsScore, 400, 15, NULL); app->fonts->BlitText(320, 10, scoreFont, scoreText); app->fonts->BlitText(30, 30, scoreFont, lifeText); app->fonts->BlitText(350, 30, scoreFont, timerText); //app->fonts->BlitText(150, 248, scoreFont, "this is just a font test message"); return true; } bool ModulePlayer::CleanUp() { app->tex->UnLoad(texture); app->tex->UnLoad(ptsScore); app->tex->UnLoad(livesForScore); app->tex->UnLoad(gameOverScreen); app->tex->UnLoad(yoshiIcon); app->tex->UnLoad(clockIcon); //deletePlayer = true; app->player->Player->body->DestroyFixture(app->player->Player->body->GetFixtureList()); //app->collisions->RemoveCollider(app->player->collider); //app->collisions->RemoveCollider(app->player->colliderFeet); return true; } bool ModulePlayer::LoadState(pugi::xml_node& data) { position.x = data.child("position").attribute("x").as_int(); position.y = data.child("position").attribute("y").as_int(); score = data.child("atributes").attribute("score").as_int(); playerHP = data.child("atributes").attribute("hp").as_int(); lives = data.child("atributes").attribute("lives").as_int(); sceneTimer = data.child("atributes").attribute("timer").as_int(); if (app->player->IsEnabled() == true) { app->player->Player->body->DestroyFixture(app->player->Player->body->GetFixtureList()); Player = app->physics->CreatePlayerBox(position.x + 28 / 2, position.y + 33 / 2, 28, 33); } //b2Filter b; //b.categoryBits = 0x0001; //b.maskBits = 0x0001 | 0x0002; //Player->body->GetFixtureList()->SetFilterData(b); createPlayer = false; //if (app->player->horizontalCB == false && app->sceneCastle->sceneTimer > 1) app->render->camera.x = -(app->player->Player->body->GetPosition().x * 100) + 630; return true; } // L02: DONE 8: Create a method to save the state of the renderer // Save Game State bool ModulePlayer::SaveState(pugi::xml_node& data) const { pugi::xml_node playerpos = data.append_child("position"); pugi::xml_node playerAtributes = data.append_child("atributes"); playerpos.append_attribute("x") = position.x; playerpos.append_attribute("y") = position.y; playerAtributes.append_attribute("score") = score; playerAtributes.append_attribute("hp") = playerHP; playerAtributes.append_attribute("lives") = lives; playerAtributes.append_attribute("timer") = sceneTimer; return true; } void ModulePlayer::OnCollision(Collider* c1, Collider* c2) { if (app->sceneCastle->godMode == false && app->sceneForest->godMode == false && destroyed == false && playerWin == false) { if ((c1->type == Collider::Type::PLAYER && c2->type == Collider::Type::ENEMY) && destroyed == false && invincibleDelay >= 120) { playerHP -= 10; if (playerHP < 0) playerHP = 0; invincibleDelay = 0; if (playerHP != 0) app->audio->PlayFx(damaged); if (playerHP <= 0) { invincibleDelay = 121; playerHP = 0; //app->audio->PlayFx(dead); destroyed = true; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::H_CB) // HORIZONTAL_CAMERA_BOUND = H_CB { if (horizontalCB == false) { horizontalCB = true; } } else if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type != Collider::Type::H_CB) { if (horizontalCB == true) { horizontalCB = false; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::V_CB) // VERTICAL_CAMERA_BOUND = V_CB { if (verticalCB == false) { verticalCB = true; } } else if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type != Collider::Type::V_CB) { if (verticalCB == true) { verticalCB = false; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::B_CB) // BIDIMENSIONAL_CAMERA_BOUND = B_CB { if (bidimensionalCB == false) { bidimensionalCB = true; } } else if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type != Collider::Type::B_CB) { if (bidimensionalCB == true) { bidimensionalCB = false; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::LAYER_ZERO) { if (layerZeroReveal == false) { layerZeroReveal = true; } } else if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type != Collider::Type::LAYER_ZERO) { if (layerZeroReveal == true) { layerZeroReveal = false; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::LAVA) { playerHP -= 100; if (playerHP < 0) playerHP = 0; invincibleDelay = 0; if (playerHP != 0) app->audio->PlayFx(damaged); if (playerHP <= 0) { invincibleDelay = 121; playerHP = 0; //app->audio->PlayFx(dead); destroyed = true; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::INSTANT_DEATH) { playerHP -= 100; if (playerHP < 0) playerHP = 0; invincibleDelay = 0; if (playerHP != 0) app->audio->PlayFx(damaged); if (playerHP <= 0) { invincibleDelay = 121; playerHP = 0; //app->audio->PlayFx(dead); destroyed = true; } } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::RECOVER_LIFE_POWER_UP) { playerHP += 10; if (playerHP > 100) playerHP = 100; app->audio->PlayFx(recoverLifePowerUp); } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::COIN) { score += 5; //if (playerScore > 1000) playerScore = 1000; app->audio->PlayFx(coin); } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::CHECKPOINT) { score += 10; //if (playerScore > 1000) playerScore = 1000; app->audio->PlayFx(halfWayPoint); app->titleScreen->SavedGame = true; app->SaveGameRequest(); saved_game = true; checkPointReached = true; } if ((c1->type == Collider::Type::PLAYER || c1->type == Collider::Type::PLAYER_FEET) && c2->type == Collider::Type::GOAL_POINT) { //playerScore += 10; //if (playerScore > 1000) playerScore = 1000; app->audio->PlayFx(levelClear); app->titleScreen->SavedGame = false; app->SaveGameRequest(); playerWin = true; app->particles->AddParticle(app->particles->enemyDefeat, app->map->goalPoolPos.x, app->map->goalPoolPos.y - 5, Collider::NONE); app->particles->AddParticle(app->particles->firework1, app->map->goalPoolPos.x + 6, app->map->goalPoolPos.y - 8, Collider::NONE, 6); app->particles->AddParticle(app->particles->firework2, app->map->goalPoolPos.x - 10, app->map->goalPoolPos.y + 4, Collider::NONE, 12); app->particles->AddParticle(app->particles->firework3, app->map->goalPoolPos.x + 2, app->map->goalPoolPos.y - 6, Collider::NONE, 18); } } }
29.432636
185
0.594024
[ "render", "3d" ]
23014de92c1f682466c7203575c3178d89f0f465
2,882
hpp
C++
include/eve/function/shuffle.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
include/eve/function/shuffle.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
include/eve/function/shuffle.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
/* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/detail/overload.hpp> namespace eve { //================================================================================================ //! @addtogroup swar //! @{ //! @var shuffle //! //! @brief Callable object computing **TODO: FILL THIS BLANK**. //! //! **Required header:** `#include <eve/function/shuffle.hpp>` //! //! #### Members Functions //! //! | Member | Effect | //! |:-------------|:-----------------------------------------------------------| //! | `operator()` | **TODO: FILL THIS BLANK** | //! | `operator[]` | Construct a conditional version of current function object | //! //! --- //! //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} //! template<**TODO: FILL THIS BLANK**> //! auto operator()( **TODO: FILL THIS BLANK**) const noexcept; //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! **Parameters** //! //!`x`: **TODO: FILL THIS BLANK** //! //!OTHER PARAMETERS //!: **TODO: FILL THIS BLANK IF NEEDED BUT RESPECT THE : FORMATTING** //! //! **Return value** //! //!For **TODO: FILL THIS BLANK**: //! //!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++ //!auto r = shuffle(**TODO: FILL THIS BLANK**); //!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //!is semantically equivalent to: //! //!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++ //!Target r; //! //!if constexpr( scalar_value<T> ) //!{ //! **TODO: FILL THIS BLANK** //!} //!else if constexpr( simd_value<T> ) //!{ //! **TODO: FILL THIS BLANK** //!} //!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! --- //! //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} //! auto operator[]( conditional_expression auto cond ) const noexcept; //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! Higher-order function generating a masked version of eve::shuffle //! //! **Parameters** //! //! `cond` : conditional expression //! //! **Return value** //! //! A Callable object so that the expression `shuffle[cond](x, ...)` is equivalent to `if_else(cond,shuffle(x, ...),x)` //! //! --- //! //! #### Supported decorators //! //! no decorators are supported //! //! #### Example //! //! @godbolt{doc/core/shuffle.cpp} //! //! @} //================================================================================================ EVE_MAKE_CALLABLE(shuffle_, shuffle); } #include <eve/module/real/core/function/scalar/shuffle.hpp> //#include <eve/module/real/core/function/regular/simd/shuffle.hpp>
29.111111
122
0.396253
[ "object", "vector" ]
2307cd2d95348222e5740c68808d9f9975c5c6a6
1,463
cpp
C++
stats.cpp
bschiffthaler/assembly-stats
ffb3be14cc0cb881500cdaddc4eb8e5bca5d306b
[ "MIT" ]
1
2021-12-14T18:27:25.000Z
2021-12-14T18:27:25.000Z
stats.cpp
bschiffthaler/assembly-stats
ffb3be14cc0cb881500cdaddc4eb8e5bca5d306b
[ "MIT" ]
null
null
null
stats.cpp
bschiffthaler/assembly-stats
ffb3be14cc0cb881500cdaddc4eb8e5bca5d306b
[ "MIT" ]
null
null
null
#include<iostream> #include<fstream> #include<vector> #include<string> using std::cout; using std::string; using std::ifstream; class genome { public: string id; string seq; }ob[10]; class stats { public: int nos; int noa; int not1; int nog; int noc; int non; float a_percent; float t_percent; float g_percent; float c_percent; float n_percent; int total; }ob2; void getid(char buffer[81],int count) { ob[count].id+=buffer; } void getseq(char buffer[81], int count) { ob[count].seq+=buffer; } int main() { char buffer[81]; int i=0,n=0,q=0; int count=0; char array[10000]; ifstream fin("plantgenome.txt"); while(!fin.eof()) { fin.getline(buffer,81); if( buffer[0]=='<') { getid(buffer,count);count++; } else getseq(buffer,count); } --count; ob2.nos=count; for(int i=0;i<count;i++) { for(int j=0;j<ob[i].seq.length();j++) { if (ob[i].seq[j]=='A') ob2.noa++; if (ob[i].seq[j]=='T') ob2.not1++; if (ob[i].seq[j]=='G') ob2.nog++; if (ob[i].seq[j]=='C') ob2.noc++; if (ob[i].seq[j]=='N') ob2.non++; } } ob2.total=ob2.noa+ob2.not1+ob2.nog+ob2.c_percent+ob2.n_percent; ob2.a_percent=(ob2.noa/ob2.total)*100; ob2.t_percent=(ob2.not1/ob2.total)*100; ob2.g_percent=(ob2.nog/ob2.total)*100; ob2.c_percent=(ob2.noc/ob2.total)*100; ob2.n_percent=(ob2.non/ob2.total)*100; return 0; }
15.56383
63
0.583049
[ "vector" ]
230b22e498b65c284f22842e61c7fcfa3fafeedf
1,001
cpp
C++
C++/simplified-fractions.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/simplified-fractions.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/simplified-fractions.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n^2 * logn) // Space: O(n^2) class Solution { public: vector<string> simplifiedFractions(int n) { unordered_set<pair<int, int>, PairHash<int>> lookup; for (int b = 1; b <= n; ++b) { for (int a = 1; a < b; ++a) { const auto& g = gcd(a, b); lookup.emplace(a / g, b / g); } } vector<string> result; transform(cbegin(lookup), cend(lookup), back_inserter(result), [](const auto& kvp) { return to_string(kvp.first) + "/" + to_string(kvp.second); }); return result; } private: template <typename T> struct PairHash { size_t operator()(const pair<T, T>& p) const { size_t seed = 0; seed ^= std::hash<T>{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); seed ^= std::hash<T>{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); return seed; } }; };
30.333333
82
0.466533
[ "vector", "transform" ]
230bc76256da0fc4b32299278ba96131a93278a3
4,958
cc
C++
src/mem/cache/prefetch/signature_path_v2.cc
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/mem/cache/prefetch/signature_path_v2.cc
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
148
2018-07-20T00:58:36.000Z
2021-11-16T01:52:33.000Z
src/mem/cache/prefetch/signature_path_v2.cc
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
/** * Copyright (c) 2018 Metempsy Technology Consulting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mem/cache/prefetch/signature_path_v2.hh" #include <cassert> #include "debug/HWPrefetch.hh" #include "mem/cache/prefetch/associative_set_impl.hh" #include "params/SignaturePathPrefetcherV2.hh" namespace gem5 { GEM5_DEPRECATED_NAMESPACE(Prefetcher, prefetch); namespace prefetch { SignaturePathV2::SignaturePathV2(const SignaturePathPrefetcherV2Params &p) : SignaturePath(p), globalHistoryRegister(p.global_history_register_entries, p.global_history_register_entries, p.global_history_register_indexing_policy, p.global_history_register_replacement_policy, GlobalHistoryEntry()) { } void SignaturePathV2::handleSignatureTableMiss(stride_t current_block, signature_t &new_signature, double &new_conf, stride_t &new_stride) { bool found = false; // This should return all entries of the GHR, since it is a fully // associative table std::vector<GlobalHistoryEntry *> all_ghr_entries = globalHistoryRegister.getPossibleEntries(0 /* any value works */); for (auto gh_entry : all_ghr_entries) { if (gh_entry->lastBlock + gh_entry->delta == current_block) { new_signature = gh_entry->signature; new_conf = gh_entry->confidence; new_stride = gh_entry->delta; found = true; globalHistoryRegister.accessEntry(gh_entry); break; } } if (!found) { new_signature = current_block; new_conf = 1.0; new_stride = current_block; } } double SignaturePathV2::calculateLookaheadConfidence( PatternEntry const &sig, PatternStrideEntry const &lookahead) const { if (sig.counter == 0) return 0.0; return (((double) usefulPrefetches) / issuedPrefetches) * (((double) lookahead.counter) / sig.counter); } double SignaturePathV2::calculatePrefetchConfidence(PatternEntry const &sig, PatternStrideEntry const &entry) const { if (sig.counter == 0) return 0.0; return ((double) entry.counter) / sig.counter; } void SignaturePathV2::increasePatternEntryCounter( PatternEntry &pattern_entry, PatternStrideEntry &pstride_entry) { if (pattern_entry.counter.isSaturated()) { pattern_entry.counter >>= 1; for (auto &entry : pattern_entry.strideEntries) { entry.counter >>= 1; } } if (pstride_entry.counter.isSaturated()) { pattern_entry.counter >>= 1; for (auto &entry : pattern_entry.strideEntries) { entry.counter >>= 1; } } pattern_entry.counter++; pstride_entry.counter++; } void SignaturePathV2::handlePageCrossingLookahead(signature_t signature, stride_t last_offset, stride_t delta, double path_confidence) { // Always use the replacement policy to assign new entries, as all // of them are unique, there are never "hits" in the GHR GlobalHistoryEntry *gh_entry = globalHistoryRegister.findVictim(0); assert(gh_entry != nullptr); // Any address value works, as it is never used globalHistoryRegister.insertEntry(0, false, gh_entry); gh_entry->signature = signature; gh_entry->lastBlock = last_offset; gh_entry->delta = delta; gh_entry->confidence = path_confidence; } } // namespace prefetch } // namespace gem5
35.927536
79
0.709157
[ "vector" ]
230f940d7529e395c8e1c3828aa9ae24f63fa196
27,818
hpp
C++
dynadjust/include/functions/dnatemplatematrixfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
44
2018-08-30T04:18:27.000Z
2022-02-01T05:37:18.000Z
dynadjust/include/functions/dnatemplatematrixfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
112
2018-08-30T09:33:42.000Z
2022-03-30T00:32:29.000Z
dynadjust/include/functions/dnatemplatematrixfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
29
2018-08-30T09:07:36.000Z
2022-02-25T05:16:08.000Z
//============================================================================ // Name : dnatemplatematrixfuncs.hpp // Author : Roger Fraser // Contributors : // Version : 1.00 // Copyright : Copyright 2017 Geoscience Australia // // 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. // // Description : Common functions involving matrix_2d operations //============================================================================ #ifndef DNATEMPLATEMATRIXFUNCS_H_ #define DNATEMPLATEMATRIXFUNCS_H_ #if defined(_MSC_VER) #if defined(LIST_INCLUDES_ON_BUILD) #pragma message(" " __FILE__) #endif #endif #include <algorithm> #include <functional> #include <sstream> #include <string> #include <vector> #include <stdlib.h> #include <math.h> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <include/parameters/dnaellipsoid.hpp> #include <include/config/dnatypes.hpp> #include <include/math/dnamatrix_contiguous.hpp> #include <include/measurement_types/dnameasurement.hpp> using namespace std; using namespace boost; using namespace dynadjust::datum_parameters; using namespace dynadjust::math; // msr_t_Iterator = vector<measurement_t>::iterator template<typename msr_t_Iterator> // Fills upper triangle void GetDirectionsVarianceMatrix(msr_t_Iterator begin, matrix_2d* vmat) { msr_t_Iterator bmsRecord(begin); UINT32 a, angle_count(bmsRecord->vectorCount1 - 1); // number of directions excluding the RO vmat->zero(); vmat->redim(angle_count, angle_count); bmsRecord++; for (a=0; a<angle_count; ++a) { vmat->put(a, a, bmsRecord->scale2); // derived angle variance if (a+1 < angle_count) vmat->put(a, a+1, bmsRecord->scale3); // derived angle covariance bmsRecord++; } } // M = measurement_t, U = matrix_2d // Fills upper triangle template<typename msr_t_Iterator> void GetGPSVarianceMatrix(const msr_t_Iterator begin, matrix_2d* vmat) { msr_t_Iterator bmsRecord(begin); UINT32 variance_dim(bmsRecord->vectorCount1 * 3), covariance_dim, cov; vmat->zero(); vmat->redim(variance_dim, variance_dim); for (UINT32 var(0), cov_elem; var<variance_dim; var+=3) { covariance_dim = bmsRecord->vectorCount2 * 3; vmat->put(var, var, (bmsRecord++)->term2); // XX vmat->put(var, var+1, bmsRecord->term2); // XY vmat->put(var+1, var+1, (bmsRecord++)->term3); // YY vmat->put(var, var+2, bmsRecord->term2); // XZ vmat->put(var+1, var+2, bmsRecord->term3); // YZ vmat->put(var+2, var+2, (bmsRecord++)->term4); // ZZ for (cov_elem=0; cov_elem<covariance_dim; cov_elem+=3) { cov = var + 3 + cov_elem; vmat->put(var, cov, bmsRecord->term1); // m11 vmat->put(var, cov+1, bmsRecord->term2); // m12 vmat->put(var, cov+2, (bmsRecord++)->term3); // m13 vmat->put(var+1, cov, bmsRecord->term1); // m21 vmat->put(var+1, cov+1, bmsRecord->term2); // m22 vmat->put(var+1, cov+2, (bmsRecord++)->term3); // m23 vmat->put(var+2, cov, bmsRecord->term1); // m31 vmat->put(var+2, cov+1, bmsRecord->term2); // m32 vmat->put(var+2, cov+2, (bmsRecord++)->term3); // m33 } } } // msr_t_Iterator = vector<measurement_t>::iterator template<typename msr_t_Iterator> // Sets values based on upper triangle void SetDirectionsVarianceMatrix(msr_t_Iterator begin, const matrix_2d& vmat) { msr_t_Iterator bmsRecord(begin); UINT32 a, angle_count(bmsRecord->vectorCount1 - 1); // number of directions excluding the RO bmsRecord->scale2 = 0.; // variance (angle) bmsRecord->scale3 = 0.; // covariance (angle) bmsRecord++; for (a=0; a<angle_count; ++a) { bmsRecord->scale2 = vmat.get(a, a); // derived angle variance if (a+1 < angle_count) bmsRecord->scale3 = vmat.get(a, a+1); // derived angle covariance else bmsRecord->scale3 = 0.; // not necessary, but in the interest of // preventing confusion, set to zero bmsRecord++; } } // msr_t_Iterator = vector<measurement_t>::iterator template<typename msr_t_Iterator> // Sets values based on upper triangle void SetGPSVarianceMatrix(msr_t_Iterator begin, const matrix_2d& vmat) { msr_t_Iterator bmsRecord(begin); UINT32 variance_dim(bmsRecord->vectorCount1 * 3), covariance_dim, cov; for (UINT32 var(0), cov_elem; var<variance_dim; var+=3) { covariance_dim = bmsRecord->vectorCount2 * 3; (bmsRecord++)->term2 = vmat.get(var, var); // XX bmsRecord->term2 = vmat.get(var, var+1); // XY (bmsRecord++)->term3 = vmat.get(var+1, var+1); // YY bmsRecord->term2 = vmat.get(var, var+2); // XZ bmsRecord->term3 = vmat.get(var+1, var+2); // YZ (bmsRecord++)->term4 = vmat.get(var+2, var+2); // ZZ for (cov_elem=0; cov_elem<covariance_dim; cov_elem+=3) { cov = var + 3 + cov_elem; bmsRecord->term1 = vmat.get(var, cov); // m11 bmsRecord->term2 = vmat.get(var, cov+1); // m12 (bmsRecord++)->term3 = vmat.get(var, cov+2); // m13 bmsRecord->term1 = vmat.get(var+1, cov); // m21 bmsRecord->term2 = vmat.get(var+1, cov+1); // m22 (bmsRecord++)->term3 = vmat.get(var+1, cov+2); // m23 bmsRecord->term1 = vmat.get(var+2, cov); // m31 bmsRecord->term2 = vmat.get(var+2, cov+1); // m32 (bmsRecord++)->term3 = vmat.get(var+2, cov+2); // m33 } } } template <class T> void FormCarttoGeoRotationMatrix(const T& latitude, const T& longitude, const T& height, matrix_2d& mrotations, const CDnaEllipsoid* ellipsoid, bool CLUSTER=false, const UINT32& n=0) { if (!CLUSTER) mrotations.redim(3, 3); T coslat(cos(latitude)); T sinlat(sin(latitude)); T coslon(cos(longitude)); T sinlon(sin(longitude)); T term1_a(ellipsoid->GetSemiMajor() * ellipsoid->GetE1sqd()); T one_minus_esq(1. - ellipsoid->GetE1sqd()); T nu_plus_h(primeVertical(ellipsoid, latitude) + height); T nu_1minuse2_plus_h((primeVertical(ellipsoid, latitude) * (one_minus_esq) + height)); T term1_b(term1_a * sinlat * coslat); T term1_c(pow((1. - ellipsoid->GetE1sqd() * sinlat * sinlat), 1.5)); // set up Rotation matrix (geo to cart) mrotations.put(n, n, (term1_b * coslat * coslon / term1_c) - ((nu_plus_h) * sinlat * coslon)); mrotations.put(n, n+1, -(nu_plus_h) * coslat * sinlon); mrotations.put(n, n+2, coslat * coslon); mrotations.put(n+1, n, (term1_b * coslat * sinlon / term1_c) - ((nu_plus_h) * sinlat * sinlon)); mrotations.put(n+1, n+1, (nu_plus_h) * coslat * coslon); mrotations.put(n+1, n+2, coslat * sinlon); mrotations.put(n+2, n, (term1_b * one_minus_esq * sinlat / term1_c) + (nu_1minuse2_plus_h * coslat)); mrotations.put(n+2, n+1, 0.); mrotations.put(n+2, n+2, sinlat); } template <class T> void FormCarttoGeoRotationMatrix_Cluster(const matrix_2d& mpositions, matrix_2d& mrotations, const CDnaEllipsoid* ellipsoid) { mrotations.redim(mpositions.rows(), mpositions.rows()); for (UINT32 i(0); i<mpositions.rows(); i+=3) { FormCarttoGeoRotationMatrix<T>( mpositions.get(i, 0), mpositions.get(i+1, 0), mpositions.get(i+2, 0), mrotations, ellipsoid, true, i); } } // Assumes design elements for station 1 and station 2 are always // -1 and 1 respectively. template <class T> void Precision_Adjusted_GNSS_bsl(const matrix_2d& mvariances, const UINT32& stn1, const UINT32& stn2, matrix_2d* mvariances_mod, bool FILLLOWER=true) { matrix_2d tmp(3, 6); mvariances_mod->zero(); UINT32 i, j, k; // 1. Form A * V for (i=0, j=0; i<3; ++i, ++j) { // variance-covariance for (j=0; j<3; ++j) { // stn 11 variance tmp.elementadd(i, j, -mvariances.get(stn1+i, stn1+j)); // stn 21 covariance tmp.elementadd(i, j, mvariances.get(stn2+i, stn1+j)); } k=j; // variance-covariance for (j=0; j<3; ++j, ++k) { // stn 12 covariance tmp.elementadd(i, k, -mvariances.get(stn1+i, stn2+j)); // stn 22 variance tmp.elementadd(i, k, mvariances.get(stn2+i, stn2+j)); } } //tmp.trace("A x V", "%.16G "); // 2. Form AV * AT (upper triangular variance-covariance) for (i=0; i<3; ++i) for (j=i; j<3; ++j) // Sum the variances & covariances mvariances_mod->put(i, j, tmp.get(i, j+3) - tmp.get(i, j)); if (FILLLOWER) mvariances_mod->filllower(); //mvariances_mod->trace("AV X At", "%.16G "); } template <class T> void Prpagate_Variances_Geo_Cart(const matrix_2d& mvariances, matrix_2d mrotations, matrix_2d* mvariances_mod, bool FORWARD=true) { // the rotation matrix is in the direction geo to cart (forward) // so to go cart to geo, perform inverse if (!FORWARD) mrotations = mrotations.sweepinverse(); // allows negative diagonal terms matrix_2d mV(mrotations); //mV.multiply(mvariances); // original variance matrix mV.multiply_mkl("N", mvariances, "N"); // original variance matrix //mvariances_mod->multiply_square_t(mV, mrotations); mvariances_mod->multiply_mkl(mV, "N", mrotations, "T"); } template <class T> void PropagateVariances_GeoCart(const matrix_2d mvariances, matrix_2d* mvariances_mod, const T& latitude, const T& longitude, const T& height, matrix_2d& mrotations, const CDnaEllipsoid* ellipsoid, bool GEO_TO_CART, bool CALCULATE_ROTATIONS) { if (CALCULATE_ROTATIONS) FormCarttoGeoRotationMatrix<T>(latitude, longitude, height, mrotations, ellipsoid); Prpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART); } template <class T> void PropagateVariances_GeoCart(const matrix_2d mvariances, matrix_2d* mvariances_mod, const T& latitude, const T& longitude, const T& height, const CDnaEllipsoid* ellipsoid, bool GEO_TO_CART) { matrix_2d mrotations; PropagateVariances_GeoCart<T>(mvariances, mvariances_mod, latitude, longitude, height, mrotations, ellipsoid, GEO_TO_CART, true); // Calculate rotations } template <class T> void PropagateVariances_GeoCart_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, const matrix_2d& mpositions, matrix_2d& mrotations, const CDnaEllipsoid* ellipsoid, bool GEO_TO_CART, bool CALCULATE_ROTATIONS) { if (CALCULATE_ROTATIONS) FormCarttoGeoRotationMatrix_Cluster<T>(mpositions, mrotations, ellipsoid); Prpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART); } template <class T> void PropagateVariances_GeoCart_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, const matrix_2d& mpositions_rad, const CDnaEllipsoid* ellipsoid, bool GEO_TO_CART) { matrix_2d mrotations; FormCarttoGeoRotationMatrix_Cluster<T>(mpositions_rad, mrotations, ellipsoid); Prpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART); } template <class T> void ScaleMatrix(const matrix_2d mvariances, matrix_2d* mvariances_mod, const matrix_2d& scalars) { //matrix_2d mV(mvariances_mod->multiply(scalars, mvariances)); matrix_2d mV(mvariances_mod->multiply_mkl(scalars, "N", mvariances, "N")); //mvariances_mod->multiply_square_t(mV, scalars); mvariances_mod->multiply_mkl(mV, "N", scalars, "T"); } template <class T> void ScaleGPSVCV(const matrix_2d& mvariances, matrix_2d* mvariances_mod, const T& latitude, const T& longitude, const T& height, const CDnaEllipsoid* ellipsoid, const T& pScale, const T& lScale, const T& hScale) { matrix_2d mrotations(3, 3); PropagateVariances_GeoCart<T>(mvariances, mvariances_mod, latitude, longitude, height, mrotations, ellipsoid, false, // Geographic -> Cartesian ? true); // create the rotation matrix matrix_2d var_scalars(3, 3); var_scalars.put(0, 0, sqrt(pScale)); var_scalars.put(1, 1, sqrt(lScale)); var_scalars.put(2, 2, sqrt(hScale)); ScaleMatrix<T>(*mvariances_mod, mvariances_mod, var_scalars); PropagateVariances_GeoCart<T>(*mvariances_mod, mvariances_mod, latitude, longitude, height, mrotations, ellipsoid, true, // Geographic -> Cartesian ? false); // don't create a rotation matrix } template <class T> // coordType is passed so that ScaleGPSVCV_Cluster knows whether // mvariances needs to be propagated to geographic first. Hence, // if coordType == LLH_type_i, no propagation is undertaken void ScaleGPSVCV_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, const matrix_2d& mpositions, const CDnaEllipsoid* ellipsoid, const T& pScale, const T& lScale, const T& hScale, _COORD_TYPE_ coordType=XYZ_type_i) { matrix_2d mrotations; // form rotation matrix FormCarttoGeoRotationMatrix_Cluster<T>(mpositions, mrotations, ellipsoid); // Don't propagate if already in geographic if (coordType == XYZ_type_i) // propagate variances in cartesian system to geographic PropagateVariances_GeoCart_Cluster<T>(mvariances, mvariances_mod, mpositions, mrotations, ellipsoid, false, // Cartesian -> Geographic false); // don't create a rotation matrix // scale matrix matrix_2d var_scalars(mvariances.rows(), mvariances.columns()); for (UINT32 r(0); r<var_scalars.rows(); r+=3) { var_scalars.put(r, r, sqrt(pScale)); var_scalars.put(r+1, r+1, sqrt(lScale)); var_scalars.put(r+2, r+2, sqrt(hScale)); } // perform the scaling ScaleMatrix<T>(*mvariances_mod, mvariances_mod, var_scalars); // propagate variances in geographic system to cartesian PropagateVariances_GeoCart_Cluster<T>(*mvariances_mod, mvariances_mod, mpositions, mrotations, ellipsoid, true, // Geographic -> Cartesian false); // don't create a rotation matrix } template <class T> void FormLocaltoCartRotationMatrix(const T& latitude, const T& longitude, matrix_2d& mrotations, bool LOCAL_TO_CART=true) { mrotations.redim(3, 3); T coslat(cos(latitude)); T sinlat(sin(latitude)); T coslon(cos(longitude)); T sinlon(sin(longitude)); if (LOCAL_TO_CART) { // set up Rotation matrix for local to cart mrotations.put(0, 0, -sinlon); mrotations.put(0, 1, -sinlat*coslon); mrotations.put(0, 2, coslat*coslon); mrotations.put(1, 0, coslon); mrotations.put(1, 1, -sinlat*sinlon); mrotations.put(1, 2, coslat*sinlon); mrotations.put(2, 0, 0.); mrotations.put(2, 1, coslat); mrotations.put(2, 2, sinlat); } else { // set up Rotation matrix for cart to local, which is // transpose of local to cart! mrotations.put(0, 0, -sinlon); mrotations.put(0, 1, coslon); mrotations.put(0, 2, 0.); mrotations.put(1, 0, -sinlat*coslon); mrotations.put(1, 1, -sinlat*sinlon); mrotations.put(1, 2, coslat); mrotations.put(2, 0, coslat*coslon); mrotations.put(2, 1, coslat*sinlon); mrotations.put(2, 2, sinlat); } } template <class T> void FormLocaltoPolarRotationMatrix(const T& azimuth, const T& elevation, const T& distance, matrix_2d& mrotations, bool LOCAL_TO_POLAR=true) { mrotations.redim(3, 3); T cos_azimuth(cos(azimuth)); T sin_azimuth(sin(azimuth)); T cos_elevation(cos(elevation)); T sin_elevation(sin(elevation)); if (LOCAL_TO_POLAR) { // set up Jacobian matrix for local to polar mrotations.put(0, 0, cos_azimuth/distance); mrotations.put(0, 1, -sin_azimuth/distance); mrotations.put(0, 2, 0.); mrotations.put(1, 0, -sin_azimuth*sin_elevation/distance); mrotations.put(1, 1, -cos_azimuth*sin_elevation/distance); mrotations.put(1, 2, cos_elevation/distance); mrotations.put(2, 0, sin_azimuth*cos_elevation); mrotations.put(2, 1, cos_azimuth*cos_elevation); mrotations.put(2, 2, sin_elevation); } else { // Set up Jacobian matrix for polar to local, which is // transpose of local to polar! mrotations.put(0, 0, cos_azimuth/distance); mrotations.put(0, 1, -sin_azimuth*sin_elevation/distance); mrotations.put(0, 2, sin_azimuth*cos_elevation); mrotations.put(1, 0, -sin_azimuth/distance); mrotations.put(1, 1, -cos_azimuth*sin_elevation/distance); mrotations.put(1, 2, cos_azimuth*cos_elevation); mrotations.put(2, 0, 0.); mrotations.put(2, 1, cos_elevation/distance); mrotations.put(2, 2, sin_elevation); } } template <class T> void PropagateVariances_CartLocal_Diagonal(const matrix_2d& mvariances, matrix_2d& mvariances_mod, const T& latitude, const T& longitude, matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false) { if (CALCULATE_ROTATIONS) FormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations); //matrix_2d mrotations_T(mrotations.rows(), mrotations.columns()); matrix_2d rtv(mrotations.rows(), mrotations.columns()); //mrotations_T.transpose(mrotations); mvariances_mod.redim(3, 3); // RtV //rtv.multiply(mrotations_T, mvariances); rtv.multiply_mkl(mrotations, "T", mvariances, "N"); UINT32 row, col, i; // RtVR for (row=0; row<3; ++row) { for (col=0; col<3; ++col) { mvariances_mod.put(row, col, 0.0); // diagonals only if (row != col) continue; for (i=0; i<3; ++i) mvariances_mod.elementadd(row, col, rtv.get(row, i) * mrotations.get(i, col)); } } } template <class T> void PropagateVariances_LocalPolar_Diagonal(const matrix_2d& mvariances, matrix_2d& mvariances_mod, const T& azimuth, const T& elevation, const T& distance, matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false) { if (CALCULATE_ROTATIONS) FormLocaltoPolarRotationMatrix<T>(azimuth, elevation, distance, mrotations); matrix_2d mrotations_T(mrotations.rows(), mrotations.columns()); matrix_2d rtv(mrotations.rows(), mrotations.columns()); mrotations_T.transpose(mrotations); mvariances_mod.redim(3, 3); // RtV //rtv.multiply(mrotations, mvariances); rtv.multiply_mkl(mrotations, "N", mvariances, "N"); UINT32 row, col, i; // RtVR for (row=0; row<3; ++row) { for (col=0; col<3; ++col) { mvariances_mod.put(row, col, 0.0); // diagonals only if (row != col) continue; for (i=0; i<3; ++i) mvariances_mod.elementadd(row, col, rtv.get(row, i) * mrotations_T.get(i, col)); } } } template <class T> void PropagateVariances_LocalCart(const matrix_2d& mvariances, matrix_2d& mvariances_mod, const T& latitude, const T& longitude, bool LOCAL_TO_CART, matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false) { if (CALCULATE_ROTATIONS) FormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations); // form transpose, from either passed in matrix or newly formed matrix matrix_2d mrotations_T(mrotations.rows(), mrotations.columns()); mrotations_T.transpose(mrotations); // the rotation matrix is in the direction local to cart (forward) if (LOCAL_TO_CART) { // Vc = R * Vl * RT //matrix_2d mV(mvariances_mod.multiply(mrotations, mvariances)); matrix_2d mV(mvariances_mod.multiply_mkl(mrotations, "N", mvariances, "N")); //mvariances_mod.multiply_square(mV, mrotations_T); mvariances_mod.multiply_mkl(mV, "N", mrotations, "T"); } else { // Vc = R-1 * Vc * [R-1]T // = RT * Vc * R (since R is orthogonal) //matrix_2d mV(mvariances_mod.multiply(mrotations_T, mvariances)); matrix_2d mV(mvariances_mod.multiply_mkl(mrotations, "T", mvariances, "N")); //mvariances_mod.multiply_square(mV, mrotations); mvariances_mod.multiply_mkl(mV, "N", mrotations, "N"); } } template <class T> void PropagateVariances_LocalCart(const matrix_2d& mvariances, matrix_2d& mvariances_mod, const T& latitude, const T& longitude, bool LOCAL_TO_CART) { matrix_2d mrotations; PropagateVariances_LocalCart<T>(mvariances, mvariances_mod, latitude, longitude, LOCAL_TO_CART, mrotations, true); // calculate rotations } template <class T> void Rotate_LocalCart(const matrix_2d mvector, matrix_2d* mvector_mod, const T& latitude, const T& longitude) { matrix_2d mrotations(3, 3); FormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations); mvector_mod->redim(3, 1); //mvector_mod->multiply(mrotations, mvector); mvector_mod->multiply_mkl(mrotations, "N", mvector, "N"); } template <class T> void Rotate_CartLocal(const matrix_2d mvector, matrix_2d* mvector_mod, const T& latitude, const T& longitude) { // Helps T sin_lat(sin(latitude)); T cos_lat(cos(latitude)); T sin_long(sin(longitude)); T cos_long(cos(longitude)); mvector_mod->redim(3, 1); mvector_mod->put(0, 0, -sin_long * mvector.get(0,0) + cos_long * mvector.get(1,0)); mvector_mod->put(1, 0, -sin_lat * cos_long * mvector.get(0,0) - sin_lat * sin_long * mvector.get(1,0) + cos_lat * mvector.get(2,0)); mvector_mod->put(2, 0, cos_lat * cos_long * mvector.get(0,0) + cos_lat * sin_long * mvector.get(1,0) + sin_lat * mvector.get(2,0)); } template <class T> void Rotate_LocalPolar(const matrix_2d mvector, matrix_2d* mvector_mod, const T& azimuth, const T& elevation, const T& distance) { // Helps T sin_azimuth(sin(azimuth)); T cos_azimuth(cos(azimuth)); T sin_elevation(sin(elevation)); T cos_elevation(cos(elevation)); mvector_mod->redim(3, 1); mvector_mod->put(0, 0, -cos_azimuth * mvector.get(0,0) - sin_azimuth * mvector.get(1,0)); mvector_mod->put(1, 0, -sin_elevation * sin_azimuth * mvector.get(0,0) - sin_elevation * cos_azimuth * mvector.get(1,0) + cos_elevation * mvector.get(2,0)); mvector_mod->put(2, 0, cos_elevation * sin_azimuth * mvector.get(0,0) + cos_elevation * cos_azimuth * mvector.get(1,0) + sin_elevation * mvector.get(2,0)); } template <class T> // rotx is x rotation in radians // roty is y rotation in radians // rotz is z rotation in radians void FormHelmertRotationMatrix(const T& rotx, const T& roty, const T& rotz, matrix_2d& mrotations, bool RIGOROUS=false) { mrotations.redim(3, 3); // Which rotation matrix is required? // Convert to seconds for the test if (RIGOROUS) { // rigorous formula for large (> 10 seconds) rotations mrotations.put(0, 0, cos(roty) * cos(rotz)); mrotations.put(0, 1, cos(roty) * sin(rotz)); mrotations.put(0, 2, -sin(roty)); mrotations.put(1, 0, (sin(rotx) * sin(roty) * cos(rotz)) - (cos(rotx) * sin(rotz))); mrotations.put(1, 1, (sin(rotx) * sin(roty) * sin(rotz)) + (cos(rotx) * cos(rotz))); mrotations.put(1, 2, sin(rotx) * cos(roty)); mrotations.put(2, 0, (cos(rotx) * sin(roty) * cos(rotz)) + (sin(rotx) * sin(rotz))); mrotations.put(2, 1, (cos(rotx) * sin(roty) * sin(rotz)) - (sin(rotx) * cos(rotz))); mrotations.put(2, 2, cos(rotx) * cos(roty)); } else { mrotations.put(0, 0, 1.); mrotations.put(0, 1, rotz); mrotations.put(0, 2, -roty); mrotations.put(1, 0, -rotz); mrotations.put(1, 1, 1.); mrotations.put(1, 2, rotx); mrotations.put(2, 0, roty); mrotations.put(2, 1, -rotx); mrotations.put(2, 2, 1.); } } template <class T> void ReduceParameters(const T* parameters, T* reduced_parameters, const T& elapsedTime, bool DYNAMIC=true) { // translations (reduce to metres) reduced_parameters[0] = parameters[0] / 1000.; reduced_parameters[1] = parameters[1] / 1000.; reduced_parameters[2] = parameters[2] / 1000.; // scale reduced_parameters[3] = parameters[3] / 1E9; // rotations reduced_parameters[4] = parameters[4]; reduced_parameters[5] = parameters[5]; reduced_parameters[6] = parameters[6]; if (DYNAMIC) { // apply rates to translations reduced_parameters[0] += parameters[7] / 1000. * elapsedTime; reduced_parameters[1] += parameters[8] / 1000. * elapsedTime; reduced_parameters[2] += parameters[9] / 1000. * elapsedTime; // apply rate to scale reduced_parameters[3] += parameters[10] / 1E9 * elapsedTime; // apply rates to rotations reduced_parameters[4] += parameters[11] * elapsedTime; reduced_parameters[5] += parameters[12] * elapsedTime; reduced_parameters[6] += parameters[13] * elapsedTime; } // reduce rotations from milli-arc-seconds to radians reduced_parameters[4] = SecondstoRadians(reduced_parameters[4]) / 1000.; reduced_parameters[5] = SecondstoRadians(reduced_parameters[5]) / 1000.; reduced_parameters[6] = SecondstoRadians(reduced_parameters[6]) / 1000.; } template <class T> // No check or safe guard in place to test if mcoordinates_mod is a reference to mcoordinates void TransformCartesian(const matrix_2d& mcoordinates, matrix_2d& mcoordinates_mod, const matrix_2d& parameters, const matrix_2d& mrotations) { // Add rotation and scale contributions for (UINT16 i(0), j; i<3; ++i) { // Initialise 'to datum' matrix mcoordinates_mod.put(i, 0, 0.0); for (j=0; j<3; ++j) // For each column in the row mcoordinates_mod.elementadd(i, 0, mrotations.get(i, j) * mcoordinates.get(j, 0)); // Sum partial products // Apply scale mcoordinates_mod.elementmultiply(i, 0, 1.0 + parameters.get(3, 0)); // Add translations mcoordinates_mod.elementadd(i, 0, parameters.get(i, 0)); } } template <class T> void Transform_7parameter(const matrix_2d& mcoordinates, matrix_2d& mcoordinates_mod, const T parameters[]) { mcoordinates_mod.redim(3, 1); bool RIGOROUS(false); if (parameters[4] > 10. || parameters[5] > 10. || parameters[6] > 10.) RIGOROUS = true; // Form rotation matrix matrix_2d mrotations(3, 3); FormHelmertRotationMatrix<T>(parameters[4], parameters[5], parameters[6], mrotations, RIGOROUS); // Put translations and scale into reducedParameters matrix_2d mtrans_scale(4, 1, parameters, 4); // Transform TransformCartesian<T>(mcoordinates, mcoordinates_mod, mtrans_scale, mrotations); } template <typename T> void PositionalUncertainty(const T& semimajor, const T& semiminor, const T& azimuth, const T& sdHt, T& hzPosU_Radius, T& vtPosU_Radius) { hzPosU_Radius = vtPosU_Radius = -1.; if (semimajor < 0.0) return; if (semiminor < 0.0) return; // Horizontal T c(semiminor / semimajor); T K(HPOS_UNCERT_Q0 + (HPOS_UNCERT_Q1 * c) + (HPOS_UNCERT_Q2 * (c * c)) + (HPOS_UNCERT_Q3 * (c * c * c))); T R(semimajor * K); hzPosU_Radius = R; // Vertical vtPosU_Radius = sdHt * 1.96; } template <typename T> T PedalVariance(const matrix_2d& mvariance, const T& direction) { T cos_theta(cos(direction)); T sin_theta(sin(direction)); return mvariance.get(0, 0) * cos_theta * cos_theta + mvariance.get(1, 1) * sin_theta * sin_theta + 2. * mvariance.get(0, 1) * cos_theta * sin_theta; } template <typename T> void ErrorEllipseParameters(const matrix_2d& mvariance, T& semimajor, T& semiminor, T& azimuth) { semimajor = semiminor = azimuth = -1.; if (mvariance.rows() < 2) return; if (mvariance.columns() < 2) return; T e2(mvariance.get(0, 0)); T n2(mvariance.get(1, 1)); T en(mvariance.get(0, 1)); T e2_plus_n2(e2 + n2); T e2_minus_n2(e2 - n2); T n2_minus_e2(n2 - e2); T W((e2_minus_n2 * e2_minus_n2) + (4. * en * en)); if (W < 0.0) { if (fabs(W) > PRECISION_1E15) return; // temp term cannot be negative!!! else W = 0.0; } T a_sqd(0.5 * (e2_plus_n2 + sqrt(W))); // semi-major T b_sqd(0.5 * (e2_plus_n2 - sqrt(W))); // semi-minor if (a_sqd < 0.0) return; // lamda2 term cannot be negative!!! if (b_sqd < 0.0) return; // lamda2 term cannot be negative!!! semimajor = sqrt(a_sqd); semiminor = sqrt(b_sqd); // Compute the azimuth of the semi-major axis if (fabs(e2 - n2) < PRECISION_1E25) { if (en < PRECISION_1E25) azimuth = 0.; // ellipse is a circle else azimuth = PI / 4.; // azimuth = 45 } else { T x(en + en); azimuth = 0.5 * atan_2(x, n2_minus_e2); } } #endif /* DNATEMPLATEMATRIXFUNCS_H_ */
31.828375
129
0.690201
[ "vector", "transform" ]
231074fdfc8f55f2e747005f9d58795a275bb67d
19,784
cpp
C++
archsim/src/abi/memory/MemoryModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-14T22:09:30.000Z
2022-01-11T09:57:52.000Z
archsim/src/abi/memory/MemoryModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
6
2020-07-09T12:01:57.000Z
2021-04-27T10:23:58.000Z
archsim/src/abi/memory/MemoryModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-29T17:05:26.000Z
2021-12-04T14:57:15.000Z
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ /* * abi/memory/MemoryModel.cpp */ #include "define.h" #include "abi/memory/MemoryTranslationModel.h" #include "abi/memory/MemoryModel.h" #include "abi/memory/MemoryEventHandler.h" #include "util/LogContext.h" #include "util/ComponentManager.h" #include "abi/devices/MMU.h" #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <csignal> #include <cstddef> #include <iomanip> #include <sys/resource.h> #include <sys/mman.h> #include <sys/stat.h> DeclareLogContext(LogMemoryModel, "Memory"); #define HOST_PAGE_SIZE_BITS 12 // 4K Host Pages #define HOST_PAGE_SIZE (1 << HOST_PAGE_SIZE_BITS) #define HOST_PAGE_INDEX_MASK (~(HOST_PAGE_SIZE - 1)) #define HOST_PAGE_OFFSET_MASK (HOST_PAGE_SIZE - 1) #define GUEST_PAGE_SIZE_BITS 12 // 4K Guest Pages #define GUEST_PAGE_SIZE (1 << GUEST_PAGE_SIZE_BITS) #define GUEST_PAGE_INDEX_MASK (~(GUEST_PAGE_SIZE - 1)) #define GUEST_PAGE_OFFSET_MASK (GUEST_PAGE_SIZE - 1) #define GUEST_PAGE_INDEX(_addr) ((_addr &GUEST_PAGE_INDEX_MASK) >> GUEST_PAGE_SIZE_BITS) #define GUEST_PAGE_ADDRESS(_addr) (_addr &GUEST_PAGE_INDEX_MASK) #define GUEST_PAGE_OFFSET(_addr) (_addr &GUEST_PAGE_OFFSET_MASK) #include <unistd.h> using namespace archsim::abi::memory; DefineComponentType(MemoryModel); static ComponentDescriptor mem_model_descriptor("MemoryModel"); MappingManager::~MappingManager() {} MemoryModel::MemoryModel() : Component(mem_model_descriptor) {} MemoryModel::~MemoryModel() {} bool MemoryModel::InsertFile(guest_addr_t addr, std::string filename, uint32_t& size) { struct stat stat; // Open the supplied file for reading. int fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { LC_ERROR(LogMemoryModel) << "Unable to open file: " << filename; return false; } // Stat the file, so we know how big it is. fstat(fd, &stat); // Refuse to copy a file that's bigger than 'size' if (size && (stat.st_size > size)) { close(fd); return false; } // Map the file into memory. void *file_data = mmap(NULL, stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0); close(fd); // If the mapping failed, exit. if (file_data == MAP_FAILED) return false; // Copy the data from the mapping into guest memory. Write(addr, (uint8_t *)file_data, stat.st_size); // Release the file mapping. munmap(file_data, stat.st_size); size = stat.st_size; return true; } bool MemoryModel::RaiseEvent(MemoryEventType type, guest_addr_t addr, uint8_t size) { UNIMPLEMENTED; } bool MemoryModel::LockRegion(guest_addr_t guest_addr, guest_size_t guest_size, host_addr_t& host_addr) { return false; } bool MemoryModel::LockRegions(guest_addr_t guest_addr, guest_size_t guest_size, LockedMemoryRegion& regions) { return false; } bool MemoryModel::UnlockRegion(guest_addr_t guest_addr, guest_size_t guest_size, host_addr_t host_addr) { return false; } void MemoryModel::FlushCaches() { } void MemoryModel::EvictCacheEntry(Address virt_addr) { } uint32_t MemoryModel::PerformTranslation(Address virt_addr, Address &out_phys_addr, const struct abi::devices::AccessInfo &info) { out_phys_addr = virt_addr; return 0; } bool MemoryModel::GetMemoryUsage(MemoryUsageInfo& usage) { return false; } bool MemoryModel::HandleSegFault(host_const_addr_t host_addr) { return false; } MappingManager *MemoryModel::GetMappingManager() { return NULL; } uint32_t MemoryModel::Read8(guest_addr_t addr, uint8_t &data) { return Read(addr, &data, 1); } uint32_t MemoryModel::Read8_zx(guest_addr_t addr, uint32_t &data) { uint8_t local_data; uint32_t rc = Read8(addr, local_data); data = (uint32_t)local_data; return rc; } uint32_t MemoryModel::Read8_sx(guest_addr_t addr, uint32_t &data) { uint8_t local_data; uint32_t rc = Read8(addr, local_data); data = (uint32_t)(int32_t)(int8_t)local_data; return rc; } uint32_t MemoryModel::Read16(guest_addr_t addr, uint16_t &data) { return Read(addr, (uint8_t*)&data, 2); } uint32_t MemoryModel::Read16_zx(guest_addr_t addr, uint32_t &data) { uint16_t local_data; uint32_t rc = Read16(addr, local_data); data = (uint32_t)local_data; return rc; } uint32_t MemoryModel::Read16_sx(guest_addr_t addr, uint32_t &data) { uint16_t local_data; uint32_t rc = Read16(addr, local_data); data = (uint32_t)(int32_t)(int16_t)local_data; return rc; } uint32_t MemoryModel::Read32(guest_addr_t addr, uint32_t &data) { return Read(addr, (uint8_t*)&data, 4); } uint32_t MemoryModel::Read64(guest_addr_t addr, uint64_t &data) { return Read(addr, (uint8_t*)&data, 8); } uint32_t MemoryModel::Read128(guest_addr_t addr, uint128_t &data) { return Read(addr, (uint8_t*)&data, 16); } uint32_t MemoryModel::Fetch8(guest_addr_t addr, uint8_t &data) { return Fetch(addr, &data, 1); } uint32_t MemoryModel::Fetch16(guest_addr_t addr, uint16_t &data) { return Fetch(addr, (uint8_t*)&data, 2); } uint32_t MemoryModel::Fetch32(guest_addr_t addr, uint32_t &data) { return Fetch(addr, (uint8_t*)&data, 4); } uint32_t MemoryModel::Write8(guest_addr_t addr, uint8_t data) { uint32_t temp = Write(addr, &data, 1); return temp; } uint32_t MemoryModel::Write16(guest_addr_t addr, uint16_t data) { return Write(addr, (uint8_t*)&data, 2); } uint32_t MemoryModel::Write32(guest_addr_t addr, uint32_t data) { return Write(addr, (uint8_t*)&data, 4); } uint32_t MemoryModel::Write64(guest_addr_t addr, uint64_t data) { return Write(addr, (uint8_t*)&data, 8); } uint32_t MemoryModel::Write128(guest_addr_t addr, uint128_t data) { return Write(addr, (uint8_t*)&data, 16); } uint32_t MemoryModel::Read8User(guest_addr_t addr, uint32_t&data) { return Read8_zx(addr, data); } uint32_t MemoryModel::Read32User(guest_addr_t addr, uint32_t&data) { return Read32(addr, data); } uint32_t MemoryModel::Write8User(guest_addr_t addr, uint8_t data) { return Write8(addr, data); } uint32_t MemoryModel::Write32User(guest_addr_t addr, uint32_t data) { return Write32(addr, data); } uint32_t MemoryModel::ReadString(guest_addr_t addr, char *str, int size) { int offset = 0; uint8_t c; do { if (Read8(addr + offset, c)) return 1; *str++ = c; offset++; } while ((c != 0) && (offset < size)); return 0; } uint32_t MemoryModel::WriteString(guest_addr_t addr, const char *str) { return Write(addr, (uint8_t *)str, strlen(str) + 1); } uint32_t MemoryModel::ReadN(guest_addr_t addr, uint8_t *buffer, size_t size) { while(size) { uint32_t c = Read8(addr, *buffer); if(c) return c; buffer++; addr += 1; size--; } return 0; } uint32_t MemoryModel::WriteN(guest_addr_t addr, uint8_t *buffer, size_t size) { while(size) { uint32_t c = Write8(addr, *buffer); if(c) return c; buffer++; addr += 1; size--; } return 0; } uint32_t MemoryModel::Peek32(guest_addr_t addr, uint32_t &data) { return Peek(addr, (uint8_t*)&data, 4); } uint32_t MemoryModel::Peek32Unsafe(guest_addr_t addr) { uint32_t data; Peek32(addr, data); return data; } static struct GuestVMA null_vma = { 0, archsim::Address(0), 0, RegFlagNone, "NULL" }; RegionBasedMemoryModel::RegionBasedMemoryModel() : cached_vma(&null_vma) {} RegionBasedMemoryModel::~RegionBasedMemoryModel() { //Free guest VMA info for(auto v : guest_vmas) { delete(v.second); } } MappingManager *RegionBasedMemoryModel::GetMappingManager() { return this; } bool RegionBasedMemoryModel::GetMemoryUsage(MemoryUsageInfo& usage) { if (!MemoryModel::GetMemoryUsage(usage)) return false; usage.guest.total = 0; for (const auto& xvma : guest_vmas) { usage.guest.total += xvma.second->size; } return true; } bool RegionBasedMemoryModel::DeleteVMA(guest_addr_t addr) { for (GuestVMAMap::const_iterator VI = guest_vmas.begin(), VE = guest_vmas.end(); VI != VE; ++VI) { if (addr >= VI->second->base && addr < (VI->second->base + VI->second->size)) { if(VI->second == cached_vma) cached_vma = &null_vma; guest_vmas.erase(VI); return true; } } return false; } GuestVMA *RegionBasedMemoryModel::LookupVMA(guest_addr_t addr) { if(guest_vmas.empty()) { return nullptr; } GuestVMAMap::const_iterator iter = guest_vmas.upper_bound(addr); iter--; GuestVMA *vma = iter->second; if ((addr >= vma->base) && (addr < (vma->base + vma->size))) { cached_vma = vma; return vma; } return NULL; } bool RegionBasedMemoryModel::AllocateRegion(archsim::Address addr, uint64_t size) { if(allocated_regions_.count(addr)) { throw std::logic_error("Attempting to reallocate a region"); } LC_DEBUG1(LogMemoryModel) << "Allocating a region " << addr << " (" << std::hex << size << ")"; allocated_regions_[addr] = size; MergeAllocatedRegions(); return true; } bool RegionBasedMemoryModel::DeallocateRegion(archsim::Address addr, uint64_t size) { auto iterator = allocated_regions_.lower_bound(addr); LC_DEBUG1(LogMemoryModel) << "Deallocating a region " << addr << " (" << std::hex << size << ")"; // iterator points to either a region which has an address >= addr // therefore (addr, addr+size) might overlap it. if(addr + size > (iterator->first + iterator->second)) { UNIMPLEMENTED; } else { // we didn't find a region which was allocated } MergeAllocatedRegions(); return true; } bool RegionBasedMemoryModel::MergeAllocatedRegions() { std::vector<archsim::Address> removed_regions; if(allocated_regions_.empty()) { return true; } LC_DEBUG1(LogMemoryModel) << "Merging regions: "; for(auto i : allocated_regions_) { LC_DEBUG1(LogMemoryModel) << " - " << i.first << " (" << std::hex << i.second << ")"; } auto iterator = allocated_regions_.begin(); while(iterator != allocated_regions_.end()) { auto cur = iterator; auto next = iterator; next++; while(next != allocated_regions_.end() && cur->first + cur->second >= next->first) { LC_DEBUG1(LogMemoryModel) << "Merging region " << next->first << " into " << cur->first; auto next_end = (next->first + next->second).Get(); cur->second = next_end - cur->first.Get(); removed_regions.push_back(next->first); LC_DEBUG1(LogMemoryModel) << " - Final region: " << cur->first << " (" << std::hex << cur->second << ")"; next++; } iterator = next; } for(auto i : removed_regions) { allocated_regions_.erase(i); } LC_DEBUG1(LogMemoryModel) << "Merged regions: "; for(auto i : allocated_regions_) { LC_DEBUG1(LogMemoryModel) << " - " << i.first << " (" << std::hex << i.second << ")"; } return true; } bool RegionBasedMemoryModel::HasIntersectingRegions(guest_addr_t addr, guest_size_t size) { guest_addr_t start1 = addr; guest_addr_t end1 = addr + size; for (auto region : allocated_regions_) { guest_addr_t start2 = region.first; guest_addr_t end2 = region.first + region.second; //(Start1 <= End2) and (Start2 <= End1) if (start1 < end2 && start2 < end1) { return true; } } return false; } bool RegionBasedMemoryModel::VMAIntersects(GuestVMA& vma, guest_size_t size) { guest_addr_t start1 = vma.base; guest_addr_t end1 = start1 + vma.size; for (auto region : guest_vmas) { if (region.second == &vma) continue; guest_addr_t start2 = region.second->base; guest_addr_t end2 = start2 + region.second->size; //(Start1 <= End2) and (Start2 <= End1) if (start1 < end2 && start2 < end1) { return true; } } return false; } bool RegionBasedMemoryModel::MapAll(RegionFlags prot) { assert(guest_vmas.empty()); LC_DEBUG1(LogMemoryModel) << "Map All"; GuestVMA *vma = new GuestVMA(); vma->base = Address(0); vma->size = 0xffffffff; vma->protection = prot; vma->name = "all"; if (!AllocateVMA(*vma)) { delete vma; return false; } guest_vmas[Address(0)] = vma; return true; } bool RegionBasedMemoryModel::MapRegion(guest_addr_t addr, guest_size_t size, RegionFlags prot, std::string name) { size = AlignUp(Address(size)).Get(); LC_DEBUG1(LogMemoryModel) << "Map Region: addr = " << std::hex << addr << ", size = " << std::hex << size << ", prot = " << prot << ", name = " << name; if (HasIntersectingRegions(addr, size)) { LC_DEBUG1(LogMemoryModel) << " - Overlap detected"; UnmapSubregion(addr, size); } GuestVMA *vma = new GuestVMA(); vma->base = addr; vma->size = size; vma->protection = prot; vma->name = name; if (!AllocateVMA(*vma)) { delete vma; return false; } guest_vmas[addr] = vma; AllocateRegion(addr, size); return true; } guest_addr_t RegionBasedMemoryModel::MapAnonymousRegion(guest_size_t size, RegionFlags prot) { // Force size alignment. size = AlignUp(Address(size)).Get(); LC_DEBUG1(LogMemoryModel) << "Map anonymous region: size = " << std::hex << size << ", prot = " << prot; // Start from a (random?) base address, and find the first address that doesn't // contain an intersecting region. guest_addr_t addr = Address(0x40000000); while (HasIntersectingRegions(addr, size)) { addr += 4096; } // Attempt to map it. if (MapRegion(addr, size, prot, "")) { return addr; } else { LC_ERROR(LogMemoryModel) << "Failed to map anonymous region!"; return Address(-1); } } bool RegionBasedMemoryModel::RemapRegion(guest_addr_t addr, guest_size_t size) { GuestVMA *vma = LookupVMA(addr); if (vma == NULL) { LC_ERROR(LogMemoryModel) << "Attempt to remap non-mapped region"; return false; } // Force size alignment. size = AlignUp(Address(size)).Get(); // Check for overlapping regions. if (VMAIntersects(*vma, size)) { return false; } DeallocateRegion(addr,vma->size); AllocateRegion(addr, size); LC_DEBUG1(LogMemoryModel) << "Remap Region: addr = " << std::hex << vma->base << ", real addr = " << std::hex << vma->host_base << ", old size = " << std::hex << vma->size << ", new size = " << std::hex << size; return ResizeVMA(*vma, size); } bool RegionBasedMemoryModel::UnmapRegion(guest_addr_t addr, guest_size_t size) { GuestVMA *vma = LookupVMA(addr); if (vma == NULL) { LC_ERROR(LogMemoryModel) << "Attempt to unmap non-mapped region."; return false; } // Force size alignment. size = AlignUp(Address(size)).Get(); LC_DEBUG1(LogMemoryModel) << "Unmap Region: addr = " << std::hex << vma->base << ", real addr = " << std::hex << vma->host_base << ", size = " << std::hex << vma->size; if (!DeallocateVMA(*vma)) return false; DeallocateRegion(addr, size); DeleteVMA(addr); return true; } bool RegionBasedMemoryModel::UnmapSubregion(guest_addr_t addr, guest_size_t size) { Address u_start = addr; Address u_end = addr + size; LC_DEBUG1(LogMemoryModel) << "Subregion " << u_start << " to " << u_end; for(auto &i : guest_vmas) { auto i_start = Address(i.second->base); auto i_end = Address(i.second->base + i.second->size); LC_DEBUG2(LogMemoryModel) << "Checking against " << i_start << " to " << i_end; // 6 possible situations: // 1. i is completely before the unmapped subregion // - do nothing // 2. i is completely covered by the unmapped subregion // - unmap i // 3. i overlaps the start of the unmapped subregion // - move the start of i to the end of the unmapped subregion // 4. i overlaps the middle of the unmapped subregion // - resize i to end at the start of the unmapped region // - create a new guest vma after the end of the unmapped region // 5. i overlaps the end of the unmapped subregion // - move the start of i to the end of the unmapped region // 6. i is completely after the unmapped subregion // - do nothing // 2: if(i_start >= u_start && u_end >= i_end) { LC_DEBUG1(LogMemoryModel) << "Unmapping entire region and recursing"; UnmapRegion(addr, size); return UnmapSubregion(addr, size); } // 3: if(i_start < u_start && i_end > u_start && i_end < u_end) { LC_DEBUG1(LogMemoryModel) << "Shifting start of region"; i.second->base = u_end; } // 4: if(u_start > i_start && u_end < i_end) { LC_DEBUG1(LogMemoryModel) << "Splitting existing vma and recursing"; // shift the end of the current vma and also create a new one, then recurse auto new_size = u_start - i_start; i.second->size = new_size.Get(); MapRegion(u_end, (i_end - u_end).Get(), i.second->protection, i.second->name); return UnmapSubregion(addr, size); } // 5: if(i_start > u_start && i_start < u_end) { UNIMPLEMENTED; } } return true; } bool RegionBasedMemoryModel::ProtectRegion(guest_addr_t addr, guest_size_t size, RegionFlags prot) { // Force size alignment. size = AlignUp(Address(size)).Get(); LC_DEBUG1(LogMemoryModel) << "Protect Region: addr = " << std::hex << addr << ", size = " << std::hex << size << ", prot = " << prot; // Locate the enclosing VMA, and update protections. auto vma = guest_vmas.find(addr); if (vma == guest_vmas.end()) return false; vma->second->protection = prot; return SynchroniseVMAProtection(*vma->second); } bool RegionBasedMemoryModel::GetRegionProtection(guest_addr_t addr, RegionFlags& prot) { // Locate the enclosing VMA, and retrieve protections. GuestVMA *vma = LookupVMA(addr); if (vma == NULL) return false; prot = vma->protection; return true; } void RegionBasedMemoryModel::DumpRegions() { fprintf(stderr, "Memory Regions:\n"); // Enumerate each region, and print out region metadata. for (auto region : guest_vmas) { char pfr = '-'; char pfw = '-'; char pfx = '-'; char pfp = '-'; if (region.second->protection & RegFlagRead) pfr = 'r'; if (region.second->protection & RegFlagWrite) pfw = 'w'; if (region.second->protection & RegFlagExecute) pfx = 'x'; fprintf(stderr, "%016lx %08x-%08x (%08x) %c%c%c%c %s\n", (unsigned long)region.second->host_base, region.second->base, region.second->base + region.second->size, region.second->size, pfr, pfw, pfx, pfp, region.second->name.c_str()); } } bool RegionBasedMemoryModel::ResolveGuestAddress(host_const_addr_t host_addr, guest_addr_t &guest_addr) { for (auto region : guest_vmas) { if (host_addr >= (host_const_addr_t)region.second->host_base && host_addr < (host_const_addr_t)((unsigned long)region.second->host_base + region.second->size)) { guest_addr = (guest_addr_t)((unsigned long)host_addr - (unsigned long)region.second->host_base); return true; } } return false; } #if CONFIG_LLVM class NullMemoryTranslationModel : public MemoryTranslationModel { public: NullMemoryTranslationModel() {} ~NullMemoryTranslationModel() {} }; #endif NullMemoryModel::NullMemoryModel() { #if CONFIG_LLVM translation_model = new NullMemoryTranslationModel(); #else translation_model = nullptr; #endif } NullMemoryModel::~NullMemoryModel() { } bool NullMemoryModel::Initialise() { return true; } void NullMemoryModel::Destroy() { } uint32_t NullMemoryModel::Read(guest_addr_t addr, uint8_t *data, int size) { #ifdef CONFIG_MEMORY_EVENTS RaiseEvent(MemoryModel::MemEventRead, addr, size); #endif return 1; } uint32_t NullMemoryModel::Fetch(guest_addr_t addr, uint8_t *data, int size) { #ifdef CONFIG_MEMORY_EVENTS RaiseEvent(MemoryModel::MemEventFetch, addr, size); #endif return 1; } uint32_t NullMemoryModel::Write(guest_addr_t addr, uint8_t *data, int size) { #ifdef CONFIG_MEMORY_EVENTS RaiseEvent(MemoryModel::MemEventWrite, addr, size); #endif return 1; } uint32_t NullMemoryModel::Peek(guest_addr_t addr, uint8_t *data, int size) { return 1; } uint32_t NullMemoryModel::Poke(guest_addr_t addr, uint8_t *data, int size) { return 1; } bool NullMemoryModel::ResolveGuestAddress(host_const_addr_t host_addr, guest_addr_t &guest_addr) { return false; } bool NullMemoryModel::HandleSegFault(host_const_addr_t host_addr) { return false; } MemoryTranslationModel &NullMemoryModel::GetTranslationModel() { return *translation_model; } uint32_t NullMemoryModel::PerformTranslation(Address virt_addr, Address &out_phys_addr, const struct archsim::abi::devices::AccessInfo &info) { out_phys_addr = virt_addr; return 0; }
24.097442
234
0.706581
[ "vector" ]
23118998e67bcccba3a9331d76ab632100f7f883
23,426
cpp
C++
core/FluffiTester/TGTestcaseManagerTester.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
core/FluffiTester/TGTestcaseManagerTester.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
core/FluffiTester/TGTestcaseManagerTester.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
/* Copyright 2017-2019 Siemens AG 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. Author(s): Michael Kraus, Thomas Riedmaier, Pascal Eckmann, Abian Blome */ #include "stdafx.h" #include "CppUnitTest.h" #include "Util.h" #include "TGTestcaseManager.h" #include "GarbageCollectorWorker.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace FluffiTester { TEST_CLASS(TGTestcaseManagerTest) { public: TGTestcaseManager* testcaseManager = nullptr; GarbageCollectorWorker* garbageCollector = nullptr; TEST_METHOD_INITIALIZE(ModuleInitialize) { Util::setDefaultLogOptions("logs" + Util::pathSeperator + "Test.log"); garbageCollector = new GarbageCollectorWorker(200); testcaseManager = new TGTestcaseManager(garbageCollector); } TEST_METHOD_CLEANUP(ModuleCleanup) { //Freeing the testcase Queue delete testcaseManager; testcaseManager = nullptr; // Freeing the garbageCollector delete garbageCollector; garbageCollector = nullptr; } TEST_METHOD(TGTestcaseManager_pushNewGeneratedTestcase_getQueueSize) { Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error initializing pendingTestcaseQueue (pushNewGeneratedTestcase)"); const FluffiServiceDescriptor sd = FluffiServiceDescriptor("testServiceDescriptor", "testGuiID"); FluffiTestcaseID id = FluffiTestcaseID(sd, 190); FluffiTestcaseID parentId = FluffiTestcaseID(sd, 111); std::string pathAndFileName = "testpath"; TestcaseDescriptor testcase = TestcaseDescriptor(id, parentId, pathAndFileName, true); // Test Method testcaseManager->pushNewGeneratedTestcase(testcase); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)1, L"Error pushing Testcase into pendingTestcaseQueue: (pushNewGeneratedTestcase)"); } TEST_METHOD(TGTestcaseManager_pushNewGeneratedTestcases) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcases.push_back(testcase1); testcases.push_back(testcase2); // Test Method testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error pushing TestcaseS into pendingTestcaseQueue: (pushNewGeneratedTestcases)"); int oldNumOfProcessingAttempts = testcase1.getNumOfProcessingAttempts(); TestcaseDescriptor poppedTestcase1 = testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(poppedTestcase1.getId().m_localID, id1.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase1.getparentId().m_localID, parentId1.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase1.getparentId().m_localID, parentId1.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase1.getNumOfProcessingAttempts(), oldNumOfProcessingAttempts + 1, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); int oldNumOfProcessingAttempts2 = testcase2.getNumOfProcessingAttempts(); TestcaseDescriptor poppedTestcase2 = testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(poppedTestcase2.getId().m_localID, id2.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase2.getparentId().m_localID, parentId2.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase2.getparentId().m_localID, parentId2.m_localID, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); Assert::AreEqual(poppedTestcase2.getNumOfProcessingAttempts(), oldNumOfProcessingAttempts2 + 1, L"Error testcases in pendingTestcaseQueue corrupted: (pushNewGeneratedTestcases)"); // Proove Exception if Queue is empty TGTestcaseManager* testcaseManagerLocal = testcaseManager; auto f = [testcaseManagerLocal] { testcaseManagerLocal->popPendingTCForProcessing(); }; Assert::ExpectException<std::runtime_error>(f); } TEST_METHOD(TGTestcaseManager_popPendingTCForProcessing) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcases.push_back(testcase1); testcases.push_back(testcase2); testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error pushing TestcaseS into pendingTestcaseQueue: (pushNewGeneratedTestcases)"); int oldNumOfProcessingAttempts = testcase1.getNumOfProcessingAttempts(); // Test Method TestcaseDescriptor poppedTestcase1 = testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(poppedTestcase1.getId().m_localID, id1.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase1.getparentId().m_localID, parentId1.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase1.getparentId().m_localID, parentId1.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase1.getNumOfProcessingAttempts(), oldNumOfProcessingAttempts + 1, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); int oldNumOfProcessingAttempts2 = testcase2.getNumOfProcessingAttempts(); // Test Method TestcaseDescriptor poppedTestcase2 = testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(poppedTestcase2.getId().m_localID, id2.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase2.getparentId().m_localID, parentId2.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase2.getparentId().m_localID, parentId2.m_localID, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); Assert::AreEqual(poppedTestcase2.getNumOfProcessingAttempts(), oldNumOfProcessingAttempts2 + 1, L"Error popping testcases from pendingTestcaseQueue: (popPendingTCForProcessing)"); // Proove Exception if Queue is empty TGTestcaseManager* testcaseManagerLocal = testcaseManager; auto f = [testcaseManagerLocal] { testcaseManagerLocal->popPendingTCForProcessing(); }; Assert::ExpectException<std::runtime_error>(f); } TEST_METHOD(TGTestcaseManager_removeEvaluatedTestcases) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcases.push_back(testcase1); testcases.push_back(testcase2); testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error pushing TestcaseS into pendingTestcaseQueue: (removeEvaluatedTestcases)"); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (removeEvaluatedTestcases)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)2, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (removeEvaluatedTestcases)"); google::protobuf::RepeatedPtrField< TestcaseID > evaluatedTestcases = google::protobuf::RepeatedPtrField< TestcaseID >(); TestcaseID* tmp1 = new TestcaseID(); tmp1->CopyFrom(id1.getProtobuf()); evaluatedTestcases.AddAllocated(tmp1); TestcaseID* tmp2 = new TestcaseID(); tmp2->CopyFrom(id2.getProtobuf()); evaluatedTestcases.AddAllocated(tmp2); // Test Method testcaseManager->removeEvaluatedTestcases(evaluatedTestcases); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)0, L"Error removing evaluated TestcaseS from sentButNotEvaluatedTestcaseSet: (removeEvaluatedTestcases)"); } TEST_METHOD(TGTestcaseManager_getPendingTestcaseQueueSize) { Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error initializing pendingTestcaseQueue (pushNewGeneratedTestcase)"); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); testcaseManager->pushNewGeneratedTestcase(testcase1); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcaseManager->pushNewGeneratedTestcase(testcase2); // Test Method Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error getting Queue size of pendingTestcaseQueue: (getPendingTestcaseQueueSize)"); } TEST_METHOD(TGTestcaseManager_getSentButNotEvaluatedTestcaseSetSize) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); const FluffiServiceDescriptor sd3 = FluffiServiceDescriptor("testServiceDescriptor3", "testGuiID3"); FluffiTestcaseID id3 = FluffiTestcaseID(sd3, 666); FluffiTestcaseID parentId3 = FluffiTestcaseID(sd3, 777); std::string pathAndFileName3 = "testpath"; TestcaseDescriptor testcase3 = TestcaseDescriptor(id3, parentId3, pathAndFileName3, true); testcases.push_back(testcase1); testcases.push_back(testcase2); testcases.push_back(testcase3); testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)3, L"Error pushing TestcaseS into pendingTestcaseQueue: (getSentButNotEvaluatedTestcaseSetSize)"); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (getSentButNotEvaluatedTestcaseSetSize)"); // Test Method Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)3, L"Error calculating size of sentButNotEvaluatedTestcaseSet: (getSentButNotEvaluatedTestcaseSetSize)"); google::protobuf::RepeatedPtrField< TestcaseID > evaluatedTestcases = google::protobuf::RepeatedPtrField< TestcaseID >(); TestcaseID* tmp2 = new TestcaseID(); tmp2->CopyFrom(id2.getProtobuf()); evaluatedTestcases.AddAllocated(tmp2); Assert::AreEqual(evaluatedTestcases.size(), 1, L"Error calculating size of evaluatedTestcases: (getSentButNotEvaluatedTestcaseSetSize)"); testcaseManager->removeEvaluatedTestcases(evaluatedTestcases); // Test Method Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)2, L"Error calculating size of sentButNotEvaluatedTestcaseSet or Error in removeEvaluatedTestcases: (getSentButNotEvaluatedTestcaseSetSize)"); } TEST_METHOD(TGTestcaseManager_reinsertTestcasesHavingNoAnswerSince) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcases.push_back(testcase1); testcases.push_back(testcase2); testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error pushing TestcaseS into pendingTestcaseQueue: (reinsertTestcasesHavingNoAnswerSince)"); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (reinsertTestcasesHavingNoAnswerSince)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)2, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (reinsertTestcasesHavingNoAnswerSince)"); std::chrono::time_point<std::chrono::steady_clock> timeBeforeWhichShouldBeReinserted = std::chrono::steady_clock::now() + std::chrono::milliseconds(100); // Test Method testcaseManager->reinsertTestcasesHavingNoAnswerSince(timeBeforeWhichShouldBeReinserted); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error reinserting TestcaseS from sentButNotEvaluatedSet due to no answer since..: (reinsertTestcasesHavingNoAnswerSince)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)0, L"Error reinserting TestcaseS from sentButNotEvaluatedSet due to no answer since..: (reinsertTestcasesHavingNoAnswerSince)"); } TEST_METHOD(TGTestcaseManager_handMeAllTestcasesWithTooManyRetries) { std::deque<TestcaseDescriptor> testcases = std::deque<TestcaseDescriptor>(); const FluffiServiceDescriptor sd1 = FluffiServiceDescriptor("testServiceDescriptor1", "testGuiID1"); FluffiTestcaseID id1 = FluffiTestcaseID(sd1, 222); FluffiTestcaseID parentId1 = FluffiTestcaseID(sd1, 333); std::string pathAndFileName1 = "testpath"; TestcaseDescriptor testcase1 = TestcaseDescriptor(id1, parentId1, pathAndFileName1, true); const FluffiServiceDescriptor sd2 = FluffiServiceDescriptor("testServiceDescriptor2", "testGuiID2"); FluffiTestcaseID id2 = FluffiTestcaseID(sd2, 444); FluffiTestcaseID parentId2 = FluffiTestcaseID(sd2, 555); std::string pathAndFileName2 = "testpath"; TestcaseDescriptor testcase2 = TestcaseDescriptor(id2, parentId2, pathAndFileName2, true); testcases.push_back(testcase1); testcases.push_back(testcase2); testcaseManager->pushNewGeneratedTestcases(testcases); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error pushing TestcaseS into pendingTestcaseQueue: (handMeAllTestcasesWithTooManyRetries)"); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)2, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (handMeAllTestcasesWithTooManyRetries)"); std::chrono::time_point<std::chrono::steady_clock> timeBeforeWhichShouldBeReinserted = std::chrono::steady_clock::now() + std::chrono::milliseconds(100); testcaseManager->reinsertTestcasesHavingNoAnswerSince(timeBeforeWhichShouldBeReinserted); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)2, L"Error reinserting TestcaseS from sentButNotEvaluatedSet due to no answer since..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)0, L"Error reinserting TestcaseS from sentButNotEvaluatedSet due to no answer since..: (handMeAllTestcasesWithTooManyRetries)"); testcaseManager->popPendingTCForProcessing(); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)1, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)1, L"Error popping TestcaseS from pendingTestcaseQueue into sentButNotEvaluatedSet: (handMeAllTestcasesWithTooManyRetries)"); timeBeforeWhichShouldBeReinserted = std::chrono::steady_clock::now() + std::chrono::milliseconds(1000); testcaseManager->reinsertTestcasesHavingNoAnswerSince(timeBeforeWhichShouldBeReinserted); testcaseManager->popPendingTCForProcessing(); testcaseManager->popPendingTCForProcessing(); // Test Method std::vector<TestcaseDescriptor> testcasesThatNeedToBeReported = testcaseManager->handMeAllTestcasesWithTooManyRetries(4); Assert::AreEqual(testcasesThatNeedToBeReported.size(), (size_t)0, L"Error calculating size of handed out vector of testcases with too many retires..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)2, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); // Test Method std::vector<TestcaseDescriptor> testcasesThatNeedToBeReported2 = testcaseManager->handMeAllTestcasesWithTooManyRetries(3); Assert::AreEqual(testcasesThatNeedToBeReported2.size(), (size_t)1, L"Error calculating size of handed out vector of testcases with too many retires..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)1, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); // Test Method std::vector<TestcaseDescriptor> testcasesThatNeedToBeReported3 = testcaseManager->handMeAllTestcasesWithTooManyRetries(2); Assert::AreEqual(testcasesThatNeedToBeReported3.size(), (size_t)1, L"Error calculating size of handed out vector of testcases with too many retires..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getSentButNotEvaluatedTestcaseSetSize(), (size_t)0, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); Assert::AreEqual(testcaseManager->getPendingTestcaseQueueSize(), (size_t)0, L"Error handing out all testcases that need to be reported due to too many send retries..: (handMeAllTestcasesWithTooManyRetries)"); } }; }
61.647368
460
0.80607
[ "vector" ]
231331ad543b38eae87067ca5392290719067dd9
1,942
cpp
C++
448_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
448_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
448_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int INF = 0x3f3f3f3f; int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif string a,b; cin>>a>>b; //for automaton check if b is a subsequence of 'a' int la=0; int lb=0; while(la<a.size() && lb<b.size()) { if(a[la]==b[lb]) { la++; lb++; } else la++; } if(lb==b.size()) { cout<<"automaton"; return 0; } //for array strigns should be anagrams sort(a.begin(),a.end()); sort(b.begin(),b.end()); if(a==b) { cout<<"array"; return 0; } vector<int>freq(26,0); for(int i=0;i<a.size();i++) freq[a[i]-'a']++; bool ok=true; for(int i=0;i<b.size();i++) { if(freq[b[i]-'a']==0) { ok=false; break; } freq[b[i]-'a']--; } if(ok) cout<<"both"; else cout<<"need tree"; }
22.321839
106
0.560247
[ "vector" ]
23152160aff1fa936b4f0aed815922df25c9c580
17,140
cpp
C++
ClangAstDumper/ClangAstDumper.cpp
JulesHervault/clava
61a72bee627d48976392de0b46ac0681ed7f86de
[ "Apache-2.0" ]
null
null
null
ClangAstDumper/ClangAstDumper.cpp
JulesHervault/clava
61a72bee627d48976392de0b46ac0681ed7f86de
[ "Apache-2.0" ]
null
null
null
ClangAstDumper/ClangAstDumper.cpp
JulesHervault/clava
61a72bee627d48976392de0b46ac0681ed7f86de
[ "Apache-2.0" ]
null
null
null
// // Created by JoaoBispo on 20/01/2017. // #include "ClangAstDumper.h" #include "ClangAstDumperConstants.h" #include "ClangNodes.h" #include "ClangEnums.h" #include "clang/AST/AST.h" #include "clang/Lex/Lexer.h" #include <iostream> #include <sstream> #include <assert.h> //#define DEBUG //#define VISIT_CHECK using namespace clang; //ClangAstDumper::ClangAstDumper(ASTContext *Context, const ASTContext& constContext, int id, int systemHeaderThreshold) : Context(Context), constContext(constContext), id(id), ClangAstDumper::ClangAstDumper(ASTContext *Context, int id, int systemHeaderThreshold) : Context(Context), id(id), systemHeaderThreshold(systemHeaderThreshold), dataDumper(Context, id) {}; // This method is equivalent to a VisitQualType() in ClangAstDumperTypes.cpp void ClangAstDumper::VisitTypeTop(const QualType& T) { if(T.isNull()) { return; } /* auto singleStepDesugar = T.getSingleStepDesugaredType(*Context); if(singleStepDesugar != T) { VisitTypeTop(singleStepDesugar); } */ // Check if QualType is the same as the underlying type if((void*) T.getTypePtr() == T.getAsOpaquePtr()) { #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(T.getTypePtr(), id)); #endif /* if(dumpType(T.getTypePtr())) { return; } */ // TODO: AST dump method relies on visiting the nodes multiple times // For now, detect it to avoid visiting children more than once if(seenTypes.count(T.getTypePtr()) == 0) { /* if(dumpType(T.getTypePtr())) { return; } visitChildrenAndData(T.getTypePtr()); */ TypeVisitor::Visit(T.getTypePtr()); } //llvm::errs() << "BRANCH 1 FOR " << T.getTypePtr() << "\n"; //visitChildren(T.getTypePtr()); //dataDumper.dump(T.getTypePtr()); //dumpIdToClassMap(T.getTypePtr(), clava::getClassName(T.getTypePtr())); dumpType(T.getTypePtr()); #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(T.getTypePtr(), id)); #endif return; } // Dump QualType /* if(dumpType(T)) { return; } */ // Visit children // TODO: AST dump method relies on visiting the nodes multiple times // For now, detect it to avoid visiting children more than once /* if(seenTypes.count(T.getAsOpaquePtr()) == 0) { visitChildren(T); } */ //dumpType(T); if(dumpType(T)) { return; } #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(T, id)); #endif //llvm::errs() << "BRANCH 2 FOR " << T.getAsOpaquePtr() << "\n"; visitChildren(T); dataDumper.dump(T); dumpIdToClassMap(T.getAsOpaquePtr(), "QualType"); #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(T, id)); #endif // Dump data //dataDumper.dump(clava::TypeNode::TYPE, T); // Visit underlying (unqualified) type //TypeVisitor::Visit(T.getTypePtr()); //llvm::errs() << "Opaque PTR: " << T.getAsOpaquePtr() << "\n"; //llvm::errs() << "Underlying PTR: " << T.getTypePtr() << "\n"; //dumpType(T); // auto typeAddr = T.getTypePtrOrNull(); // if(typeAddr == nullptr) { // return; // } } void ClangAstDumper::VisitTypeTop(const Type *T) { //std::cout << "HELLO\n"; if(T == nullptr) { return; } /* auto desugar = T->getUnqualifiedDesugaredType(); if(desugar != T) { VisitTypeTop(desugar); } */ // llvm::errs() << "TYPE TOP:" << T << "\n"; // llvm::errs() << "TYPE TOP CLASS:" << T->getTypeClass() << "\n"; // llvm::errs() << "TYPE TOP 2\n"; #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(T, id)); #endif TypeVisitor::Visit(T); // llvm::errs() << "TYPE TOP 3\n"; #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(T, id)); #endif } void ClangAstDumper::VisitStmtTop(const Stmt *Node) { //VisitStmt(Node); if(Node == nullptr) { return; } #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(Node, id)); #endif /* if(dumpStmt(Node)) { return; } visitChildrenAndData(Node); */ ConstStmtVisitor::Visit(Node); #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(Node, id)); #endif } void ClangAstDumper::VisitDeclTop(const Decl *Node) { if(Node == nullptr) { return; } #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(Node, id)); #endif /* if(dumpDecl(Node)) { return; } visitChildrenAndData(Node); */ // Do not visit if in system header // If is in system header /* FullSourceLoc fullLocation = Context->getFullLoc(Node->getLocStart()); if (fullLocation.isValid() && fullLocation.isInSystemHeader()) { return; } */ ConstDeclVisitor::Visit(Node); #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(Node, id)); #endif } void ClangAstDumper::VisitAttrTop(const Attr *Node) { if(Node == nullptr) { return; } #ifdef VISIT_CHECK clava::dump(TOP_VISIT_START); clava::dump(clava::getId(Node, id)); #endif VisitAttr(Node); #ifdef VISIT_CHECK clava::dump(TOP_VISIT_END); clava::dump(clava::getId(Node, id)); #endif } //void ClangAstDumper::log(const char* name, const void* addr) { void ClangAstDumper::log(std::string name, const void* addr) { #ifdef DEBUG llvm::errs() << name << " " << addr << "\n"; #endif // clava::dump(VISIT_START); // clava::dump(clava::getId(addr, id)); } void ClangAstDumper::log(const Decl* D) { log(clava::getClassName(D), D); } void ClangAstDumper::log(const Stmt* S) { log(clava::getClassName(S), S); } void ClangAstDumper::log(const Type* T) { log(clava::getClassName(T), T); } void ClangAstDumper::log(const Attr* A) { log(clava::getClassName(A), A); } std::string ClangAstDumper::loc2str(SourceLocation locStart, SourceLocation locEnd) { clang::SourceManager *sm = &Context->getSourceManager(); clang::LangOptions lopt = Context->getLangOpts(); clang::SourceLocation b(locStart), _e(locEnd); clang::SourceLocation e(clang::Lexer::getLocForEndOfToken(_e, 0, *sm, lopt)); std::string bChars(sm->getCharacterData(b)); std::string eChars(sm->getCharacterData(e)); if(bChars == "<<<<INVALID BUFFER>>>>") { return ""; } if(eChars == "<<<<INVALID BUFFER>>>>") { return ""; } return std::string(sm->getCharacterData(b), sm->getCharacterData(e)-sm->getCharacterData(b)); } void ClangAstDumper::dumpSourceRange(std::string id, SourceLocation startLoc, SourceLocation endLoc) { llvm::errs() << "<SourceRange Dump>\n"; llvm::errs() << id << "\n"; // All components of the source range will be dumped const SourceManager& SM = Context->getSourceManager(); SourceLocation startSpellingLoc = SM.getSpellingLoc(startLoc); PresumedLoc startPLoc = SM.getPresumedLoc(startSpellingLoc); if (startPLoc.isInvalid()) { llvm::errs() << "<invalid>\n"; /* llvm::errs() << "startLoc:\n"; startLoc.dump(SM); llvm::errs() << "endLoc:\n"; endLoc.dump(SM); assert(startLoc == endLoc); */ return; } // Dump start location llvm::errs() << startPLoc.getFilename() << "\n"; llvm::errs() << startPLoc.getLine() << "\n"; llvm::errs() << startPLoc.getColumn() << "\n"; if(startLoc == endLoc) { llvm::errs() << "<end>\n"; return; } SourceLocation endSpellingLoc = SM.getSpellingLoc(endLoc); PresumedLoc endPLoc = SM.getPresumedLoc(endSpellingLoc); if(endPLoc.isInvalid()) { llvm::errs() << "<end>\n"; return; } const char* endFilename = endPLoc.getFilename(); if(!endFilename) { endFilename = startPLoc.getFilename(); } unsigned int endLine = endPLoc.getLine(); if(!endLine) { endLine = startPLoc.getLine(); } unsigned int endCol = endPLoc.getColumn(); if(!endCol) { endCol = startPLoc.getColumn(); } // Dump end location llvm::errs() << endFilename << "\n"; llvm::errs() << endLine << "\n"; llvm::errs() << endCol << "\n"; } /* std::string ClangAstDumper::getId(const void* addr) { std::stringstream ss; ss << addr << "_" << id; return ss.str(); } */ /* std::string ClangAstDumper::getId(const Decl* addr) { } std::string ClangAstDumper::getId(const Stmt* addr) { } std::string ClangAstDumper::getId(const Expr* addr) { } std::string ClangAstDumper::getId(const Type* addr) { } std::string ClangAstDumper::getId(const Attr* addr) { } */ std::string ClangAstDumper::toBoolString(int value) { return value ? "true" : "false"; } const Type* getTypePtr(QualType T, std::string source) { assert(!T.isNull() && "Cannot retrieve a NULL type pointer"); return T.getTypePtr(); } void ClangAstDumper::dumpVisitedChildren(const void *pointer, std::vector<std::string> children) { llvm::errs() << VISITED_CHILDREN << "\n"; // If node has children, pointer will not be null llvm::errs() << clava::getId(pointer, id) << "\n"; llvm::errs() << children.size() << "\n"; for(auto child : children) { llvm::errs() << child << "\n"; } } void ClangAstDumper::dumpIdToClassMap(const void* pointer, std::string className) { llvm::errs() << ID_TO_CLASS_MAP << "\n"; llvm::errs() << clava::getId(pointer, id) << "\n"; llvm::errs() << className << "\n"; } void ClangAstDumper::dumpTopLevelType(const QualType &type) { llvm::errs() << TOP_LEVEL_TYPES << "\n"; clava::dump(type, id); } void ClangAstDumper::dumpTopLevelAttr(const Attr *attr) { llvm::errs() << TOP_LEVEL_ATTRIBUTES << "\n"; llvm::errs() << clava::getId(attr, id) << "\n"; } void ClangAstDumper::emptyChildren(const void *pointer) { std::vector<std::string> noChildren; dumpVisitedChildren(pointer, noChildren); } const void ClangAstDumper::addChild(const Decl *addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_START); clava::dump(clavaId); } #endif VisitDeclTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_END); clava::dump(clavaId); } #endif }; /* const void ClangAstDumper::addChildren(DeclContext::decl_range decls, std::vector<std::string> &children) { return addChildren(decls, children, true); } */ //const void ClangAstDumper::addChildren(DeclContext::decl_range decls, std::vector<std::string> &children, bool ignoreClassDefinitions) { const void ClangAstDumper::addChildren(DeclContext::decl_range decls, std::vector<std::string> &children) { for (auto decl = decls.begin(), endDecl = decls.end(); decl != endDecl; ++decl) { // Ignore decls that are not in the source code if(decl->isImplicit()) { continue; } if (*decl == nullptr) { continue; } addChild(*decl, children); } }; const void ClangAstDumper::addChild(const Stmt *addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_START); clava::dump(clavaId); } #endif VisitStmtTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_END); clava::dump(clavaId); } #endif }; const void ClangAstDumper::addChild(const Expr *addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_START); clava::dump(clavaId); } #endif VisitStmtTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_END); clava::dump(clavaId); } #endif }; const void ClangAstDumper::addChild(const Type *addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_START); clava::dump(clavaId); } #endif VisitTypeTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_END); clava::dump(clavaId); } #endif }; const void ClangAstDumper::addChild(const QualType &addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK clava::dump(VISIT_START); clava::dump(clavaId); #endif VisitTypeTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK clava::dump(VISIT_END); clava::dump(clavaId); #endif }; const void ClangAstDumper::addChild(const Attr *addr, std::vector<std::string> &children) { // Do not add child if goes above system header threshold if(systemHeaderThreshold > 0 && currentSystemHeaderLevel > systemHeaderThreshold) { return; } std::string clavaId = clava::getId(addr, id); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_START); clava::dump(clavaId); } #endif VisitAttrTop(addr); children.push_back(clavaId); #ifdef VISIT_CHECK if(addr != nullptr) { clava::dump(VISIT_END); clava::dump(clavaId); } #endif }; void ClangAstDumper::VisitTemplateArgument(const TemplateArgument& templateArg) { switch(templateArg.getKind()) { case TemplateArgument::ArgKind::Type: VisitTypeTop(templateArg.getAsType()); break; case TemplateArgument::ArgKind::Expression: VisitStmtTop(templateArg.getAsExpr()); break; case TemplateArgument::ArgKind::Pack: // Do nothing break; case TemplateArgument::ArgKind::Integral: // Do nothing break; case TemplateArgument::ArgKind::Template: VisitTemplateName(templateArg.getAsTemplate()); break; /* { TemplateName templateName = templateArg.getAsTemplate(); switch(templateName.getKind()) { case TemplateName::NameKind::Template: VisitDeclTop(templateName.getAsTemplateDecl()); break; case TemplateName::NameKind::QualifiedTemplate: VisitDeclTop(templateName.getAsQualifiedTemplateName()->getTemplateDecl()); break; default: throw std::invalid_argument("ClangAstDumper::VisitTemplateArgument(): TemplateName case not implemented, '" + clava::TEMPLATE_NAME_KIND[templateName.getKind()] + "'"); } break; } */ default: throw std::invalid_argument("ClangAstDumper::VisitTemplateArgument(): Case not implemented, '"+clava::TEMPLATE_ARG_KIND[templateArg.getKind()]+"'"); } }; void ClangAstDumper::VisitTemplateName(const TemplateName& templateName) { switch(templateName.getKind()) { case TemplateName::NameKind::Template: VisitDeclTop(templateName.getAsTemplateDecl()); break; case TemplateName::NameKind::QualifiedTemplate: VisitDeclTop(templateName.getAsQualifiedTemplateName()->getTemplateDecl()); break; case TemplateName::NameKind::SubstTemplateTemplateParm: VisitDeclTop(templateName.getAsSubstTemplateTemplateParm()->getParameter()); VisitTemplateName(templateName.getAsSubstTemplateTemplateParm()->getReplacement()); default: throw std::invalid_argument("ClangAstDumper::VisitTemplateArgument(): TemplateName case not implemented, '" + clava::TEMPLATE_NAME_KIND[templateName.getKind()] + "'"); } };
24.346591
176
0.622345
[ "vector" ]
2318e1ba1cd6244cde4d4439d9a6e1e826ffc810
3,546
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoVertexAttributeElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoVertexAttributeElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoVertexAttributeElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ #include <Inventor/elements/SoVertexAttributeElement.h> #include "SbBasicP.h" #include "elements/SoVertexAttributeData.h" #include "misc/SbHash.h" struct AttribAppFunc : public SbHash<SoVertexAttributeData *,const char *>::ApplyFunctor<void *> { SoVertexAttributeElement::AttributeApplyFunc * func; void operator()(const char * & key, SoVertexAttributeData * & obj, void * closure) { func(key,obj,closure); } }; #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/fields/SoMFFloat.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/C/glue/gl.h> class SoVertexAttributeElementP { public: typedef SbHash<SoVertexAttributeData *, const char *> AttribDict; AttribDict attribdict; }; #define PRIVATE(obj) ((obj)->pimpl) SO_ELEMENT_SOURCE(SoVertexAttributeElement); void SoVertexAttributeElement::initClass(void) { SO_ELEMENT_INIT_CLASS(SoVertexAttributeElement, inherited); } void SoVertexAttributeElement::init(SoState * state) { inherited::init(state); this->clearNodeIds(); } SoVertexAttributeElement::~SoVertexAttributeElement() { } /*! Overridden to copy vertex attributes and node ids. */ void SoVertexAttributeElement::push(SoState * state) { inherited::push(state); const SoVertexAttributeElement * prev = coin_assert_cast<SoVertexAttributeElement *>(this->getNextInStack()); PRIVATE(this)->attribdict = PRIVATE(prev)->attribdict; this->copyNodeIds(prev); } void SoVertexAttributeElement::add(SoState * const state, SoVertexAttributeData * attribdata) { SoVertexAttributeElement * thisp = static_cast<SoVertexAttributeElement *>(SoElement::getElement(state, classStackIndex)); thisp->addElt(attribdata); thisp->addNodeId(attribdata->nodeid); } void SoVertexAttributeElement::addElt(SoVertexAttributeData * attribdata) { PRIVATE(this)->attribdict.put(attribdata->name.getString(), attribdata); } const SoVertexAttributeElement * SoVertexAttributeElement::getInstance(SoState * const state) { return coin_assert_cast<const SoVertexAttributeElement *> (getConstElement(state, classStackIndex)); } unsigned int SoVertexAttributeElement::getNumAttributes(void) const { return PRIVATE(this)->attribdict.getNumElements(); } void SoVertexAttributeElement::applyToAttributes(AttributeApplyFunc * func, void * closure) const { AttribAppFunc functor; functor.func = func; PRIVATE(this)->attribdict.apply(functor, closure); } #undef PRIVATE
28.368
98
0.723632
[ "3d" ]
231e19b00ee6149a905f25418c104543c73e10f5
7,044
cpp
C++
src/xr_3da/xrGame/ai/Zombie/ai_zombie.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
src/xr_3da/xrGame/ai/Zombie/ai_zombie.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrGame/ai/Zombie/ai_zombie.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//////////////////////////////////////////////////////////////////////////// // Module : ai_zombie.cpp // Created : 23.04.2002 // Modified : 07.11.2002 // Author : Dmitriy Iassenev // Description : AI Behaviour for monster "Zombie" //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ai_zombie.h" #include "../ai_monsters_misc.h" #include "../../xrserver_objects_alife_monsters.h" CAI_Zombie::CAI_Zombie() { m_hit_direction.set (0,0,1); m_tSavedEnemyPosition.set(0,0,0); m_hit_time = 0; m_tSavedEnemy = 0; m_tpSavedEnemyNode = 0; m_dwSavedEnemyNodeID = u32(-1); m_dwLostEnemyTime = 0; m_tpCurrentGlobalAnimation = 0; m_tpCurrentGlobalBlend = 0; m_bActionStarted = false; m_bFiring = false; m_dwLastVoiceTalk = 0; m_dwLastPursuitTalk = 0; m_tpSoundBeingPlayed = 0; m_dwLastSoundRefresh = 0; m_previous_query_time = 0; m_tCurrentDir.set (0,0,1); m_tHPB.set (0,0,0); m_fDHeading = 0; m_fGoalChangeTime = 0.f; m_tLastSound.tpEntity = 0; m_tLastSound.dwTime = 0; m_tLastSound.eSoundType = SOUND_TYPE_NO_SOUND; m_bNoWay = false; m_bActive = false; m_dwStartAttackTime = 0; m_fLookSpeed = PI; m_dwTimeToLie = 6000; m_dwToWaitBeforeDestroy = 10000; m_tAction = eZombieActionNone; inherited::Init (); } CAI_Zombie::~CAI_Zombie() { DELETE_SOUNDS(SND_ATTACK_COUNT, m_tpaSoundAttack ); DELETE_SOUNDS(SND_DEATH_COUNT, m_tpaSoundDeath ); DELETE_SOUNDS(SND_HIT_COUNT, m_tpaSoundHit ); DELETE_SOUNDS(SND_IDLE_COUNT, m_tpaSoundIdle ); DELETE_SOUNDS(SND_NOTICE_COUNT, m_tpaSoundNotice ); DELETE_SOUNDS(SND_PURSUIT_COUNT, m_tpaSoundPursuit ); DELETE_SOUNDS(SND_RESURRECT_COUNT, m_tpaSoundResurrect ); } void CAI_Zombie::Die() { inherited::Die( ); m_eCurrentState = aiZombieDie; ///Fvector dir; //direction(dir); //SelectAnimation(XFORM().k,dir,speed()); ::Sound->play_at_pos(m_tpaSoundDeath[Random.randI(SND_DEATH_COUNT)],this,Position()); CGroup &Group = Level().get_group(g_Team(),g_Squad(),g_Group()); vfRemoveActiveMember(); --(Group.m_dwAliveCount); m_eCurrentState = aiZombieDie; // Msg("%s : Death signal %d",*cName(),Level().timeServer()); } void CAI_Zombie::Load(LPCSTR section) { // load parameters from ".ini" file inherited::Load(section); // initialize start position Fvector P = Position(); P.x += ::Random.randF(); P.z += ::Random.randF(); vfLoadSounds(); // sounds m_fMinVoiceIinterval = pSettings->r_float (section,"MinVoiceInterval"); m_fMaxVoiceIinterval = pSettings->r_float (section,"MaxVoiceInterval"); m_fVoiceRefreshRate = pSettings->r_float (section,"VoiceRefreshRate"); m_fMinPursuitIinterval = pSettings->r_float (section,"MinPursuitInterval"); m_fMaxPursuitIinterval = pSettings->r_float (section,"MaxPursuitInterval"); m_fPursuitRefreshRate = pSettings->r_float (section,"PursuitRefreshRate"); // active\passive m_fChangeActiveStateProbability = pSettings->r_float (section,"ChangeActiveStateProbability"); m_dwPassiveScheduleMin = pSettings->r_s32 (section,"PassiveScheduleMin"); m_dwPassiveScheduleMax = pSettings->r_s32 (section,"PassiveScheduleMax"); m_dwActiveCountPercent = pSettings->r_s32 (section,"ActiveCountPercent"); // eye shift m_tEyeShift.y = pSettings->r_float (section,"EyeYShift"); // former constants m_dwLostMemoryTime = pSettings->r_s32 (section,"LostMemoryTime"); m_fAttackStraightDistance = pSettings->r_float (section,"AttackStraightDistance"); m_fStableDistance = pSettings->r_float (section,"StableDistance"); m_fWallMinTurnValue = pSettings->r_float (section,"WallMinTurnValue")/180.f*PI; m_fWallMaxTurnValue = pSettings->r_float (section,"WallMaxTurnValue")/180.f*PI; m_fAngleSpeed = pSettings->r_float (section,"AngleSpeed"); m_fSafeGoalChangeDelta = pSettings->r_float (section,"GoalChangeDelta"); m_tGoalVariation = pSettings->r_fvector3(section,"GoalVariation"); m_fSoundThreshold = pSettings->r_float (section,"SoundThreshold"); m_fMaxHealthValue = pSettings->r_float (section,"MaxHealthValue"); m_dwActiveScheduleMin = shedule.t_min; m_dwActiveScheduleMax = shedule.t_max; } BOOL CAI_Zombie::net_Spawn (LPVOID DC) { if (!inherited::net_Spawn(DC)) return FALSE; ////////////////////////////////////////////////////////////////////////// CSE_Abstract *e = (CSE_Abstract*)(DC); CSE_ALifeMonsterZombie *tpSE_Zombie = dynamic_cast<CSE_ALifeMonsterZombie*>(e); // model // personal characteristics m_body.current.yaw = m_body.target.yaw = -tpSE_Zombie->o_Angle.y; m_body.current.pitch = m_body.target.pitch = 0; eye_fov = tpSE_Zombie->fEyeFov; eye_range = tpSE_Zombie->fEyeRange; fEntityHealth = tpSE_Zombie->fHealth; m_fMinSpeed = tpSE_Zombie->fMinSpeed; m_fMaxSpeed = tpSE_Zombie->fMaxSpeed; m_fAttackSpeed = tpSE_Zombie->fAttackSpeed; m_fMaxPursuitRadius = tpSE_Zombie->fMaxPursuitRadius; m_fMaxHomeRadius = tpSE_Zombie->fMaxHomeRadius; // attack m_fHitPower = tpSE_Zombie->fHitPower; m_dwHitInterval = tpSE_Zombie->u16HitInterval; m_fAttackDistance = tpSE_Zombie->fAttackDistance; m_fAttackAngle = tpSE_Zombie->fAttackAngle/180.f*PI; ////////////////////////////////////////////////////////////////////////// m_fCurSpeed = m_fMaxSpeed; m_tOldPosition.set(Position()); m_tSpawnPosition.set(Level().get_squad(g_Team(),g_Squad()).Leader->Position()); m_tSafeSpawnPosition.set(m_tSpawnPosition); m_tStateStack.push(m_eCurrentState = aiZombieFreeHuntingActive); vfAddActiveMember(true); m_bStateChanged = true; m_tHPB.x = m_body.current.yaw; m_tHPB.y = m_body.current.pitch; m_tHPB.z = 0; vfLoadAnimations (); return TRUE; } void CAI_Zombie::net_Export(NET_Packet& P) { R_ASSERT (Local()); // export last known packet R_ASSERT (!NET.empty()); net_update& N = NET.back(); P.w_float_q16 (fEntityHealth,-500,1000); P.w_u32 (N.dwTimeStamp); P.w_u8 (0); P.w_vec3 (N.p_pos); P.w_angle8 (N.o_model); P.w_angle8 (N.o_torso.yaw); P.w_angle8 (N.o_torso.pitch); P.w_u8 (u8(g_Team())); P.w_u8 (u8(g_Squad())); P.w_u8 (u8(g_Group())); } void CAI_Zombie::net_Import(NET_Packet& P) { R_ASSERT (Remote()); net_update N; u8 flags; float health; P.r_float_q16 (health,-500,1000); fEntityHealth = health; P.r_u32 (N.dwTimeStamp); P.r_u8 (flags); P.r_vec3 (N.p_pos); P.r_angle8 (N.o_model); P.r_angle8 (N.o_torso.yaw); P.r_angle8 (N.o_torso.pitch); id_Team = P.r_u8(); id_Squad = P.r_u8(); id_Group = P.r_u8(); if (NET.empty() || (NET.back().dwTimeStamp<N.dwTimeStamp)) { NET.push_back (N); NET_WasInterpolating = TRUE; } setVisible (TRUE); setEnabled (TRUE); }
32.164384
96
0.661698
[ "model" ]
2322c5fc407133b2eb3bc03b165c427690ef5f3f
1,749
cpp
C++
src/+cv/RQDecomp3x3.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
571
2015-01-04T06:23:19.000Z
2022-03-31T07:37:19.000Z
src/+cv/RQDecomp3x3.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
362
2015-01-06T14:20:46.000Z
2022-01-20T08:10:46.000Z
src/+cv/RQDecomp3x3.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
300
2015-01-20T03:21:27.000Z
2022-03-31T07:36:37.000Z
/** * @file RQDecomp3x3.cpp * @brief mex interface for cv::RQDecomp3x3 * @ingroup calib3d * @author Kota Yamaguchi * @date 2011 */ #include "mexopencv.hpp" #include "opencv2/calib3d.hpp" using namespace std; using namespace cv; namespace { /** Create a new MxArray from decomposed matrix. * @param Qx Rotation matrix around x-axis. * @param Qy Rotation matrix around y-axis. * @param Qz Rotation matrix around z-axis. * @param eulerAngles Euler angles of rotation. * @return output MxArray struct object. */ MxArray toStruct(const Mat& Qx, const Mat& Qy, const Mat& Qz, const Vec3d& eulerAngles) { const char* fieldnames[] = {"Qx", "Qy", "Qz", "eulerAngles"}; MxArray s = MxArray::Struct(fieldnames, 4); s.set("Qx", Qx); s.set("Qy", Qy); s.set("Qz", Qz); s.set("eulerAngles", eulerAngles); return s; } } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk(nrhs==1 && nlhs<=3); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); // Process Mat M(rhs[0].toMat(rhs[0].isSingle() ? CV_32F : CV_64F)), R, Q, Qx, Qy, Qz; Vec3d eulerAngles = RQDecomp3x3(M, R, Q, (nlhs>2 ? Qx : noArray()), (nlhs>2 ? Qy : noArray()), (nlhs>2 ? Qz : noArray())); plhs[0] = MxArray(R); if (nlhs>1) plhs[1] = MxArray(Q); if (nlhs>2) plhs[2] = toStruct(Qx, Qy, Qz, eulerAngles); }
28.209677
76
0.6255
[ "object", "vector" ]
2325cdaf44579b7554583bf063ef82fbffabda67
55,015
cpp
C++
LeGO-LOAM/src/mapOptmization.cpp
tonglizi/LeGO-LOAM-BOR
602c4f2fc95583353674d40ae9d8168d1935d48c
[ "BSD-3-Clause" ]
null
null
null
LeGO-LOAM/src/mapOptmization.cpp
tonglizi/LeGO-LOAM-BOR
602c4f2fc95583353674d40ae9d8168d1935d48c
[ "BSD-3-Clause" ]
null
null
null
LeGO-LOAM/src/mapOptmization.cpp
tonglizi/LeGO-LOAM-BOR
602c4f2fc95583353674d40ae9d8168d1935d48c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2013, Ji Zhang, Carnegie Mellon University // Further contributions copyright (c) 2016, Southwest Research Institute // 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 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. // // This is an implementation of the algorithm described in the following paper: // J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time. // Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014. // T. Shan and B. Englot. LeGO-LOAM: Lightweight and Ground-Optimized Lidar // Odometry and Mapping on Variable Terrain // IEEE/RSJ International Conference on Intelligent Robots and Systems // (IROS). October 2018. #include "mapOptimization.h" #include <future> using namespace gtsam; MapOptimization::MapOptimization(ros::NodeHandle &node, Channel<AssociationOut> &input_channel) : nh(node), _input_channel(input_channel), _publish_global_signal(false), _loop_closure_signal(false) { ISAM2Params parameters; parameters.relinearizeThreshold = 0.01; parameters.relinearizeSkip = 1; isam = new ISAM2(parameters); pubKeyPoses = nh.advertise<sensor_msgs::PointCloud2>("/key_pose_origin", 2); pubLaserCloudSurround = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_surround", 2); pubOdomAftMapped = nh.advertise<nav_msgs::Odometry>("/aft_mapped_to_init", 5); pubHistoryKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("/history_cloud", 2); pubIcpKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("/corrected_cloud", 2); pubRecentKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("/recent_cloud", 2); downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2); downSizeFilterSurf.setLeafSize(0.4, 0.4, 0.4); downSizeFilterOutlier.setLeafSize(0.4, 0.4, 0.4); // for histor key frames of loop closure downSizeFilterHistoryKeyFrames.setLeafSize(0.4, 0.4, 0.4); // for surrounding key poses of scan-to-map optimization downSizeFilterSurroundingKeyPoses.setLeafSize(1.0, 1.0, 1.0); // for global map visualization downSizeFilterGlobalMapKeyPoses.setLeafSize(1.0, 1.0, 1.0); // for global map visualization downSizeFilterGlobalMapKeyFrames.setLeafSize(0.4, 0.4, 0.4); odomAftMapped.header.frame_id = "/camera_init"; odomAftMapped.child_frame_id = "/aft_mapped"; aftMappedTrans.frame_id_ = "/camera_init"; aftMappedTrans.child_frame_id_ = "/aft_mapped"; nh.getParam("/lego_loam/laser/scan_period", _scan_period); nh.getParam("/lego_loam/mapping/enable_loop_closure", _loop_closure_enabled); nh.getParam("/lego_loam/mapping/history_keyframe_search_radius", _history_keyframe_search_radius); nh.getParam("/lego_loam/mapping/history_keyframe_search_num", _history_keyframe_search_num); nh.getParam("/lego_loam/mapping/history_keyframe_fitness_score", _history_keyframe_fitness_score); nh.getParam("/lego_loam/mapping/surrounding_keyframe_search_radius", _surrounding_keyframe_search_radius); nh.getParam("/lego_loam/mapping/surrounding_keyframe_search_num", _surrounding_keyframe_search_num); nh.getParam("/lego_loam/mapping/global_map_visualization_search_radius", _global_map_visualization_search_radius); allocateMemory(); _publish_global_thread = std::thread(&MapOptimization::publishGlobalMapThread, this); _loop_closure_thread = std::thread(&MapOptimization::loopClosureThread, this); _run_thread = std::thread(&MapOptimization::run, this); } MapOptimization::~MapOptimization() { _input_channel.send({}); _run_thread.join(); _publish_global_signal.send(false); _publish_global_thread.join(); _loop_closure_signal.send(false); _loop_closure_thread.join(); } void MapOptimization::allocateMemory() { cloudKeyPoses3D.reset(new pcl::PointCloud<PointType>()); cloudKeyPoses6D.reset(new pcl::PointCloud<PointTypePose>()); surroundingKeyPoses.reset(new pcl::PointCloud<PointType>()); surroundingKeyPosesDS.reset(new pcl::PointCloud<PointType>()); laserCloudCornerLast.reset( new pcl::PointCloud<PointType>()); // corner feature set from // odoOptimization laserCloudSurfLast.reset( new pcl::PointCloud<PointType>()); // surf feature set from // odoOptimization laserCloudCornerLastDS.reset( new pcl::PointCloud<PointType>()); // downsampled corner featuer set // from odoOptimization laserCloudSurfLastDS.reset( new pcl::PointCloud<PointType>()); // downsampled surf featuer set from // odoOptimization laserCloudOutlierLast.reset( new pcl::PointCloud<PointType>()); // corner feature set from // odoOptimization laserCloudOutlierLastDS.reset( new pcl::PointCloud<PointType>()); // downsampled corner feature set // from odoOptimization laserCloudSurfTotalLast.reset( new pcl::PointCloud<PointType>()); // surf feature set from // odoOptimization laserCloudSurfTotalLastDS.reset( new pcl::PointCloud<PointType>()); // downsampled surf featuer set from // odoOptimization laserCloudOri.reset(new pcl::PointCloud<PointType>()); coeffSel.reset(new pcl::PointCloud<PointType>()); laserCloudCornerFromMap.reset(new pcl::PointCloud<PointType>()); laserCloudSurfFromMap.reset(new pcl::PointCloud<PointType>()); laserCloudCornerFromMapDS.reset(new pcl::PointCloud<PointType>()); laserCloudSurfFromMapDS.reset(new pcl::PointCloud<PointType>()); nearHistoryCornerKeyFrameCloud.reset(new pcl::PointCloud<PointType>()); nearHistoryCornerKeyFrameCloudDS.reset(new pcl::PointCloud<PointType>()); nearHistorySurfKeyFrameCloud.reset(new pcl::PointCloud<PointType>()); nearHistorySurfKeyFrameCloudDS.reset(new pcl::PointCloud<PointType>()); latestCornerKeyFrameCloud.reset(new pcl::PointCloud<PointType>()); latestSurfKeyFrameCloud.reset(new pcl::PointCloud<PointType>()); latestSurfKeyFrameCloudDS.reset(new pcl::PointCloud<PointType>()); globalMapKeyPoses.reset(new pcl::PointCloud<PointType>()); globalMapKeyPosesDS.reset(new pcl::PointCloud<PointType>()); globalMapKeyFrames.reset(new pcl::PointCloud<PointType>()); globalMapKeyFramesDS.reset(new pcl::PointCloud<PointType>()); timeLaserOdometry = 0; timeLastGloalMapPublish = 0; timeLastProcessing = -1; for (int i = 0; i < 6; ++i) { transformLast[i] = 0; transformSum[i] = 0; transformIncre[i] = 0; transformTobeMapped[i] = 0; transformBefMapped[i] = 0; transformAftMapped[i] = 0; } matA0.setZero(); matB0.fill(-1); matX0.setZero(); matA1.setZero(); matD1.setZero(); matV1.setZero(); isDegenerate = false; matP.setZero(); laserCloudCornerFromMapDSNum = 0; laserCloudSurfFromMapDSNum = 0; laserCloudCornerLastDSNum = 0; laserCloudSurfLastDSNum = 0; laserCloudOutlierLastDSNum = 0; laserCloudSurfTotalLastDSNum = 0; potentialLoopFlag = false; aLoopIsClosed = false; latestFrameID = 0; } void MapOptimization::publishGlobalMapThread() { while(ros::ok()) { bool ready; _publish_global_signal.receive(ready); if(ready){ publishGlobalMap(); } } } void MapOptimization::loopClosureThread() { while(ros::ok()) { bool ready; _loop_closure_signal.receive(ready); if(ready && _loop_closure_enabled){ performLoopClosure(); } } } void MapOptimization::transformAssociateToMap() { float x1 = cos(transformSum[1]) * (transformBefMapped[3] - transformSum[3]) - sin(transformSum[1]) * (transformBefMapped[5] - transformSum[5]); float y1 = transformBefMapped[4] - transformSum[4]; float z1 = sin(transformSum[1]) * (transformBefMapped[3] - transformSum[3]) + cos(transformSum[1]) * (transformBefMapped[5] - transformSum[5]); float x2 = x1; float y2 = cos(transformSum[0]) * y1 + sin(transformSum[0]) * z1; float z2 = -sin(transformSum[0]) * y1 + cos(transformSum[0]) * z1; transformIncre[3] = cos(transformSum[2]) * x2 + sin(transformSum[2]) * y2; transformIncre[4] = -sin(transformSum[2]) * x2 + cos(transformSum[2]) * y2; transformIncre[5] = z2; float sbcx = sin(transformSum[0]); float cbcx = cos(transformSum[0]); float sbcy = sin(transformSum[1]); float cbcy = cos(transformSum[1]); float sbcz = sin(transformSum[2]); float cbcz = cos(transformSum[2]); float sblx = sin(transformBefMapped[0]); float cblx = cos(transformBefMapped[0]); float sbly = sin(transformBefMapped[1]); float cbly = cos(transformBefMapped[1]); float sblz = sin(transformBefMapped[2]); float cblz = cos(transformBefMapped[2]); float salx = sin(transformAftMapped[0]); float calx = cos(transformAftMapped[0]); float saly = sin(transformAftMapped[1]); float caly = cos(transformAftMapped[1]); float salz = sin(transformAftMapped[2]); float calz = cos(transformAftMapped[2]); float srx = -sbcx * (salx * sblx + calx * cblx * salz * sblz + calx * calz * cblx * cblz) - cbcx * sbcy * (calx * calz * (cbly * sblz - cblz * sblx * sbly) - calx * salz * (cbly * cblz + sblx * sbly * sblz) + cblx * salx * sbly) - cbcx * cbcy * (calx * salz * (cblz * sbly - cbly * sblx * sblz) - calx * calz * (sbly * sblz + cbly * cblz * sblx) + cblx * cbly * salx); transformTobeMapped[0] = -asin(srx); float srycrx = sbcx * (cblx * cblz * (caly * salz - calz * salx * saly) - cblx * sblz * (caly * calz + salx * saly * salz) + calx * saly * sblx) - cbcx * cbcy * ((caly * calz + salx * saly * salz) * (cblz * sbly - cbly * sblx * sblz) + (caly * salz - calz * salx * saly) * (sbly * sblz + cbly * cblz * sblx) - calx * cblx * cbly * saly) + cbcx * sbcy * ((caly * calz + salx * saly * salz) * (cbly * cblz + sblx * sbly * sblz) + (caly * salz - calz * salx * saly) * (cbly * sblz - cblz * sblx * sbly) + calx * cblx * saly * sbly); float crycrx = sbcx * (cblx * sblz * (calz * saly - caly * salx * salz) - cblx * cblz * (saly * salz + caly * calz * salx) + calx * caly * sblx) + cbcx * cbcy * ((saly * salz + caly * calz * salx) * (sbly * sblz + cbly * cblz * sblx) + (calz * saly - caly * salx * salz) * (cblz * sbly - cbly * sblx * sblz) + calx * caly * cblx * cbly) - cbcx * sbcy * ((saly * salz + caly * calz * salx) * (cbly * sblz - cblz * sblx * sbly) + (calz * saly - caly * salx * salz) * (cbly * cblz + sblx * sbly * sblz) - calx * caly * cblx * sbly); transformTobeMapped[1] = atan2(srycrx / cos(transformTobeMapped[0]), crycrx / cos(transformTobeMapped[0])); float srzcrx = (cbcz * sbcy - cbcy * sbcx * sbcz) * (calx * salz * (cblz * sbly - cbly * sblx * sblz) - calx * calz * (sbly * sblz + cbly * cblz * sblx) + cblx * cbly * salx) - (cbcy * cbcz + sbcx * sbcy * sbcz) * (calx * calz * (cbly * sblz - cblz * sblx * sbly) - calx * salz * (cbly * cblz + sblx * sbly * sblz) + cblx * salx * sbly) + cbcx * sbcz * (salx * sblx + calx * cblx * salz * sblz + calx * calz * cblx * cblz); float crzcrx = (cbcy * sbcz - cbcz * sbcx * sbcy) * (calx * calz * (cbly * sblz - cblz * sblx * sbly) - calx * salz * (cbly * cblz + sblx * sbly * sblz) + cblx * salx * sbly) - (sbcy * sbcz + cbcy * cbcz * sbcx) * (calx * salz * (cblz * sbly - cbly * sblx * sblz) - calx * calz * (sbly * sblz + cbly * cblz * sblx) + cblx * cbly * salx) + cbcx * cbcz * (salx * sblx + calx * cblx * salz * sblz + calx * calz * cblx * cblz); transformTobeMapped[2] = atan2(srzcrx / cos(transformTobeMapped[0]), crzcrx / cos(transformTobeMapped[0])); x1 = cos(transformTobeMapped[2]) * transformIncre[3] - sin(transformTobeMapped[2]) * transformIncre[4]; y1 = sin(transformTobeMapped[2]) * transformIncre[3] + cos(transformTobeMapped[2]) * transformIncre[4]; z1 = transformIncre[5]; x2 = x1; y2 = cos(transformTobeMapped[0]) * y1 - sin(transformTobeMapped[0]) * z1; z2 = sin(transformTobeMapped[0]) * y1 + cos(transformTobeMapped[0]) * z1; transformTobeMapped[3] = transformAftMapped[3] - (cos(transformTobeMapped[1]) * x2 + sin(transformTobeMapped[1]) * z2); transformTobeMapped[4] = transformAftMapped[4] - y2; transformTobeMapped[5] = transformAftMapped[5] - (-sin(transformTobeMapped[1]) * x2 + cos(transformTobeMapped[1]) * z2); } void MapOptimization::transformUpdate() { for (int i = 0; i < 6; i++) { transformBefMapped[i] = transformSum[i]; transformAftMapped[i] = transformTobeMapped[i]; } } void MapOptimization::updatePointAssociateToMapSinCos() { cRoll = cos(transformTobeMapped[0]); sRoll = sin(transformTobeMapped[0]); cPitch = cos(transformTobeMapped[1]); sPitch = sin(transformTobeMapped[1]); cYaw = cos(transformTobeMapped[2]); sYaw = sin(transformTobeMapped[2]); tX = transformTobeMapped[3]; tY = transformTobeMapped[4]; tZ = transformTobeMapped[5]; } void MapOptimization::pointAssociateToMap(PointType const *const pi, PointType *const po) { float x1 = cYaw * pi->x - sYaw * pi->y; float y1 = sYaw * pi->x + cYaw * pi->y; float z1 = pi->z; float x2 = x1; float y2 = cRoll * y1 - sRoll * z1; float z2 = sRoll * y1 + cRoll * z1; po->x = cPitch * x2 + sPitch * z2 + tX; po->y = y2 + tY; po->z = -sPitch * x2 + cPitch * z2 + tZ; po->intensity = pi->intensity; } void MapOptimization::updateTransformPointCloudSinCos(PointTypePose *tIn) { ctRoll = cos(tIn->roll); stRoll = sin(tIn->roll); ctPitch = cos(tIn->pitch); stPitch = sin(tIn->pitch); ctYaw = cos(tIn->yaw); stYaw = sin(tIn->yaw); tInX = tIn->x; tInY = tIn->y; tInZ = tIn->z; } pcl::PointCloud<PointType>::Ptr MapOptimization::transformPointCloud( pcl::PointCloud<PointType>::Ptr cloudIn) { // !!! DO NOT use pcl for point cloud transformation, results are not // accurate Reason: unkown pcl::PointCloud<PointType>::Ptr cloudOut(new pcl::PointCloud<PointType>()); PointType *pointFrom; PointType pointTo; int cloudSize = cloudIn->points.size(); cloudOut->resize(cloudSize); for (int i = 0; i < cloudSize; ++i) { pointFrom = &cloudIn->points[i]; float x1 = ctYaw * pointFrom->x - stYaw * pointFrom->y; float y1 = stYaw * pointFrom->x + ctYaw * pointFrom->y; float z1 = pointFrom->z; float x2 = x1; float y2 = ctRoll * y1 - stRoll * z1; float z2 = stRoll * y1 + ctRoll * z1; pointTo.x = ctPitch * x2 + stPitch * z2 + tInX; pointTo.y = y2 + tInY; pointTo.z = -stPitch * x2 + ctPitch * z2 + tInZ; pointTo.intensity = pointFrom->intensity; cloudOut->points[i] = pointTo; } return cloudOut; } pcl::PointCloud<PointType>::Ptr MapOptimization::transformPointCloud( pcl::PointCloud<PointType>::Ptr cloudIn, PointTypePose *transformIn) { pcl::PointCloud<PointType>::Ptr cloudOut(new pcl::PointCloud<PointType>()); PointType *pointFrom; PointType pointTo; int cloudSize = cloudIn->points.size(); cloudOut->resize(cloudSize); for (int i = 0; i < cloudSize; ++i) { pointFrom = &cloudIn->points[i]; float x1 = cos(transformIn->yaw) * pointFrom->x - sin(transformIn->yaw) * pointFrom->y; float y1 = sin(transformIn->yaw) * pointFrom->x + cos(transformIn->yaw) * pointFrom->y; float z1 = pointFrom->z; float x2 = x1; float y2 = cos(transformIn->roll) * y1 - sin(transformIn->roll) * z1; float z2 = sin(transformIn->roll) * y1 + cos(transformIn->roll) * z1; pointTo.x = cos(transformIn->pitch) * x2 + sin(transformIn->pitch) * z2 + transformIn->x; pointTo.y = y2 + transformIn->y; pointTo.z = -sin(transformIn->pitch) * x2 + cos(transformIn->pitch) * z2 + transformIn->z; pointTo.intensity = pointFrom->intensity; cloudOut->points[i] = pointTo; } return cloudOut; } void MapOptimization::publishTF() { geometry_msgs::Quaternion geoQuat = tf::createQuaternionMsgFromRollPitchYaw( transformAftMapped[2], -transformAftMapped[0], -transformAftMapped[1]); odomAftMapped.header.stamp = ros::Time().fromSec(timeLaserOdometry); odomAftMapped.pose.pose.orientation.x = -geoQuat.y; odomAftMapped.pose.pose.orientation.y = -geoQuat.z; odomAftMapped.pose.pose.orientation.z = geoQuat.x; odomAftMapped.pose.pose.orientation.w = geoQuat.w; odomAftMapped.pose.pose.position.x = transformAftMapped[3]; odomAftMapped.pose.pose.position.y = transformAftMapped[4]; odomAftMapped.pose.pose.position.z = transformAftMapped[5]; odomAftMapped.twist.twist.angular.x = transformBefMapped[0]; odomAftMapped.twist.twist.angular.y = transformBefMapped[1]; odomAftMapped.twist.twist.angular.z = transformBefMapped[2]; odomAftMapped.twist.twist.linear.x = transformBefMapped[3]; odomAftMapped.twist.twist.linear.y = transformBefMapped[4]; odomAftMapped.twist.twist.linear.z = transformBefMapped[5]; pubOdomAftMapped.publish(odomAftMapped); aftMappedTrans.stamp_ = ros::Time().fromSec(timeLaserOdometry); aftMappedTrans.setRotation( tf::Quaternion(-geoQuat.y, -geoQuat.z, geoQuat.x, geoQuat.w)); aftMappedTrans.setOrigin(tf::Vector3( transformAftMapped[3], transformAftMapped[4], transformAftMapped[5])); tfBroadcaster.sendTransform(aftMappedTrans); } void MapOptimization::publishKeyPosesAndFrames() { if (pubKeyPoses.getNumSubscribers() != 0) { sensor_msgs::PointCloud2 cloudMsgTemp; pcl::toROSMsg(*cloudKeyPoses3D, cloudMsgTemp); cloudMsgTemp.header.stamp = ros::Time().fromSec(timeLaserOdometry); cloudMsgTemp.header.frame_id = "/camera_init"; pubKeyPoses.publish(cloudMsgTemp); } if (pubRecentKeyFrames.getNumSubscribers() != 0) { sensor_msgs::PointCloud2 cloudMsgTemp; pcl::toROSMsg(*laserCloudSurfFromMapDS, cloudMsgTemp); cloudMsgTemp.header.stamp = ros::Time().fromSec(timeLaserOdometry); cloudMsgTemp.header.frame_id = "/camera_init"; pubRecentKeyFrames.publish(cloudMsgTemp); } } void MapOptimization::publishGlobalMap() { if (pubLaserCloudSurround.getNumSubscribers() == 0) return; if (cloudKeyPoses3D->points.empty() == true) return; // kd-tree to find near key frames to visualize std::vector<int> pointSearchIndGlobalMap; std::vector<float> pointSearchSqDisGlobalMap; // search near key frames to visualize mtx.lock(); kdtreeGlobalMap.setInputCloud(cloudKeyPoses3D); kdtreeGlobalMap.radiusSearch( currentRobotPosPoint, _global_map_visualization_search_radius, pointSearchIndGlobalMap, pointSearchSqDisGlobalMap); mtx.unlock(); for (int i = 0; i < pointSearchIndGlobalMap.size(); ++i) globalMapKeyPoses->points.push_back( cloudKeyPoses3D->points[pointSearchIndGlobalMap[i]]); // downsample near selected key frames downSizeFilterGlobalMapKeyPoses.setInputCloud(globalMapKeyPoses); downSizeFilterGlobalMapKeyPoses.filter(*globalMapKeyPosesDS); // extract visualized and downsampled key frames for (int i = 0; i < globalMapKeyPosesDS->points.size(); ++i) { int thisKeyInd = (int)globalMapKeyPosesDS->points[i].intensity; *globalMapKeyFrames += *transformPointCloud( cornerCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]); *globalMapKeyFrames += *transformPointCloud( surfCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]); *globalMapKeyFrames += *transformPointCloud(outlierCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]); } // downsample visualized points downSizeFilterGlobalMapKeyFrames.setInputCloud(globalMapKeyFrames); downSizeFilterGlobalMapKeyFrames.filter(*globalMapKeyFramesDS); sensor_msgs::PointCloud2 cloudMsgTemp; pcl::toROSMsg(*globalMapKeyFramesDS, cloudMsgTemp); cloudMsgTemp.header.stamp = ros::Time().fromSec(timeLaserOdometry); cloudMsgTemp.header.frame_id = "/camera_init"; pubLaserCloudSurround.publish(cloudMsgTemp); globalMapKeyPoses->clear(); globalMapKeyPosesDS->clear(); globalMapKeyFrames->clear(); //globalMapKeyFramesDS->clear(); } bool MapOptimization::detectLoopClosure() { latestSurfKeyFrameCloud->clear(); nearHistorySurfKeyFrameCloud->clear(); nearHistorySurfKeyFrameCloudDS->clear(); std::lock_guard<std::mutex> lock(mtx); // find the closest history key frame std::vector<int> pointSearchIndLoop; std::vector<float> pointSearchSqDisLoop; kdtreeHistoryKeyPoses.setInputCloud(cloudKeyPoses3D); kdtreeHistoryKeyPoses.radiusSearch( currentRobotPosPoint, _history_keyframe_search_radius, pointSearchIndLoop, pointSearchSqDisLoop); closestHistoryFrameID = -1; for (int i = 0; i < pointSearchIndLoop.size(); ++i) { int id = pointSearchIndLoop[i]; if (abs(cloudKeyPoses6D->points[id].time - timeLaserOdometry) > 30.0) { closestHistoryFrameID = id; break; } } if (closestHistoryFrameID == -1) { return false; } // save latest key frames latestFrameIDLoopCloure = cloudKeyPoses3D->points.size() - 1; *latestSurfKeyFrameCloud += *transformPointCloud(cornerCloudKeyFrames[latestFrameIDLoopCloure], &cloudKeyPoses6D->points[latestFrameIDLoopCloure]); *latestSurfKeyFrameCloud += *transformPointCloud(surfCloudKeyFrames[latestFrameIDLoopCloure], &cloudKeyPoses6D->points[latestFrameIDLoopCloure]); pcl::PointCloud<PointType>::Ptr hahaCloud(new pcl::PointCloud<PointType>()); int cloudSize = latestSurfKeyFrameCloud->points.size(); for (int i = 0; i < cloudSize; ++i) { if ((int)latestSurfKeyFrameCloud->points[i].intensity >= 0) { hahaCloud->push_back(latestSurfKeyFrameCloud->points[i]); } } latestSurfKeyFrameCloud->clear(); *latestSurfKeyFrameCloud = *hahaCloud; // save history near key frames for (int j = - _history_keyframe_search_num; j <= _history_keyframe_search_num; ++j) { if (closestHistoryFrameID + j < 0 || closestHistoryFrameID + j > latestFrameIDLoopCloure) continue; *nearHistorySurfKeyFrameCloud += *transformPointCloud( cornerCloudKeyFrames[closestHistoryFrameID + j], &cloudKeyPoses6D->points[closestHistoryFrameID + j]); *nearHistorySurfKeyFrameCloud += *transformPointCloud( surfCloudKeyFrames[closestHistoryFrameID + j], &cloudKeyPoses6D->points[closestHistoryFrameID + j]); } downSizeFilterHistoryKeyFrames.setInputCloud(nearHistorySurfKeyFrameCloud); downSizeFilterHistoryKeyFrames.filter(*nearHistorySurfKeyFrameCloudDS); // publish history near key frames if (pubHistoryKeyFrames.getNumSubscribers() != 0) { sensor_msgs::PointCloud2 cloudMsgTemp; pcl::toROSMsg(*nearHistorySurfKeyFrameCloudDS, cloudMsgTemp); cloudMsgTemp.header.stamp = ros::Time().fromSec(timeLaserOdometry); cloudMsgTemp.header.frame_id = "/camera_init"; pubHistoryKeyFrames.publish(cloudMsgTemp); } return true; } void MapOptimization::performLoopClosure() { if (cloudKeyPoses3D->points.empty() == true) return; // try to find close key frame if there are any if (potentialLoopFlag == false) { if (detectLoopClosure() == true) { potentialLoopFlag = true; // find some key frames that is old enough or // close enough for loop closure timeSaveFirstCurrentScanForLoopClosure = timeLaserOdometry; } if (potentialLoopFlag == false) return; } // reset the flag first no matter icp successes or not potentialLoopFlag = false; // ICP Settings pcl::IterativeClosestPoint<PointType, PointType> icp; icp.setMaxCorrespondenceDistance(100); icp.setMaximumIterations(100); icp.setTransformationEpsilon(1e-6); icp.setEuclideanFitnessEpsilon(1e-6); icp.setRANSACIterations(0); // Align clouds icp.setInputSource(latestSurfKeyFrameCloud); icp.setInputTarget(nearHistorySurfKeyFrameCloudDS); pcl::PointCloud<PointType>::Ptr unused_result( new pcl::PointCloud<PointType>()); icp.align(*unused_result); if (icp.hasConverged() == false || icp.getFitnessScore() > _history_keyframe_fitness_score) return; // publish corrected cloud if (pubIcpKeyFrames.getNumSubscribers() != 0) { pcl::PointCloud<PointType>::Ptr closed_cloud( new pcl::PointCloud<PointType>()); pcl::transformPointCloud(*latestSurfKeyFrameCloud, *closed_cloud, icp.getFinalTransformation()); sensor_msgs::PointCloud2 cloudMsgTemp; pcl::toROSMsg(*closed_cloud, cloudMsgTemp); cloudMsgTemp.header.stamp = ros::Time().fromSec(timeLaserOdometry); cloudMsgTemp.header.frame_id = "/camera_init"; pubIcpKeyFrames.publish(cloudMsgTemp); } /* get pose constraint */ float x, y, z, roll, pitch, yaw; Eigen::Affine3f correctionCameraFrame; correctionCameraFrame = icp.getFinalTransformation(); // get transformation in camera frame // (because points are in camera frame) pcl::getTranslationAndEulerAngles(correctionCameraFrame, x, y, z, roll, pitch, yaw); Eigen::Affine3f correctionLidarFrame = pcl::getTransformation(z, x, y, yaw, roll, pitch); // transform from world origin to wrong pose Eigen::Affine3f tWrong = pclPointToAffine3fCameraToLidar( cloudKeyPoses6D->points[latestFrameIDLoopCloure]); // transform from world origin to corrected pose Eigen::Affine3f tCorrect = correctionLidarFrame * tWrong; // pre-multiplying -> successive rotation about a fixed frame pcl::getTranslationAndEulerAngles(tCorrect, x, y, z, roll, pitch, yaw); gtsam::Pose3 poseFrom = Pose3(Rot3::RzRyRx(roll, pitch, yaw), Point3(x, y, z)); gtsam::Pose3 poseTo = pclPointTogtsamPose3(cloudKeyPoses6D->points[closestHistoryFrameID]); gtsam::Vector Vector6(6); float noiseScore = icp.getFitnessScore(); Vector6 << noiseScore, noiseScore, noiseScore, noiseScore, noiseScore, noiseScore; auto constraintNoise = noiseModel::Diagonal::Variances(Vector6); /* add constraints */ std::lock_guard<std::mutex> lock(mtx); gtSAMgraph.add( BetweenFactor<Pose3>(latestFrameIDLoopCloure, closestHistoryFrameID, poseFrom.between(poseTo), constraintNoise)); isam->update(gtSAMgraph); isam->update(); gtSAMgraph.resize(0); aLoopIsClosed = true; } void MapOptimization::extractSurroundingKeyFrames() { if (cloudKeyPoses3D->points.empty() == true) return; if (_loop_closure_enabled == true) { // only use recent key poses for graph building if (recentCornerCloudKeyFrames.size() < _surrounding_keyframe_search_num) { // queue is not full (the beginning // of mapping or a loop is just // closed) // clear recent key frames queue recentCornerCloudKeyFrames.clear(); recentSurfCloudKeyFrames.clear(); recentOutlierCloudKeyFrames.clear(); int numPoses = cloudKeyPoses3D->points.size(); for (int i = numPoses - 1; i >= 0; --i) { int thisKeyInd = (int)cloudKeyPoses3D->points[i].intensity; PointTypePose thisTransformation = cloudKeyPoses6D->points[thisKeyInd]; updateTransformPointCloudSinCos(&thisTransformation); // extract surrounding map recentCornerCloudKeyFrames.push_front( transformPointCloud(cornerCloudKeyFrames[thisKeyInd])); recentSurfCloudKeyFrames.push_front( transformPointCloud(surfCloudKeyFrames[thisKeyInd])); recentOutlierCloudKeyFrames.push_front( transformPointCloud(outlierCloudKeyFrames[thisKeyInd])); if (recentCornerCloudKeyFrames.size() >= _surrounding_keyframe_search_num) break; } } else { // queue is full, pop the oldest key frame and push the latest // key frame if (latestFrameID != cloudKeyPoses3D->points.size()-1) { // if the robot is not moving, no need to // update recent frames recentCornerCloudKeyFrames.pop_front(); recentSurfCloudKeyFrames.pop_front(); recentOutlierCloudKeyFrames.pop_front(); // push latest scan to the end of queue latestFrameID = cloudKeyPoses3D->points.size() - 1; PointTypePose thisTransformation = cloudKeyPoses6D->points[latestFrameID]; updateTransformPointCloudSinCos(&thisTransformation); recentCornerCloudKeyFrames.push_back( transformPointCloud(cornerCloudKeyFrames[latestFrameID])); recentSurfCloudKeyFrames.push_back( transformPointCloud(surfCloudKeyFrames[latestFrameID])); recentOutlierCloudKeyFrames.push_back( transformPointCloud(outlierCloudKeyFrames[latestFrameID])); } } for (int i = 0; i < recentCornerCloudKeyFrames.size(); ++i) { *laserCloudCornerFromMap += *recentCornerCloudKeyFrames[i]; *laserCloudSurfFromMap += *recentSurfCloudKeyFrames[i]; *laserCloudSurfFromMap += *recentOutlierCloudKeyFrames[i]; } } else { surroundingKeyPoses->clear(); surroundingKeyPosesDS->clear(); // extract all the nearby key poses and downsample them kdtreeSurroundingKeyPoses.setInputCloud(cloudKeyPoses3D); kdtreeSurroundingKeyPoses.radiusSearch( currentRobotPosPoint, (double)_surrounding_keyframe_search_radius, pointSearchInd, pointSearchSqDis); for (int i = 0; i < pointSearchInd.size(); ++i){ surroundingKeyPoses->points.push_back( cloudKeyPoses3D->points[pointSearchInd[i]]); } downSizeFilterSurroundingKeyPoses.setInputCloud(surroundingKeyPoses); downSizeFilterSurroundingKeyPoses.filter(*surroundingKeyPosesDS); // delete key frames that are not in surrounding region int numSurroundingPosesDS = surroundingKeyPosesDS->points.size(); for (int i = 0; i < surroundingExistingKeyPosesID.size(); ++i) { bool existingFlag = false; for (int j = 0; j < numSurroundingPosesDS; ++j) { if (surroundingExistingKeyPosesID[i] == (int)surroundingKeyPosesDS->points[j].intensity) { existingFlag = true; break; } } if (existingFlag == false) { surroundingExistingKeyPosesID.erase( surroundingExistingKeyPosesID.begin() + i); surroundingCornerCloudKeyFrames.erase( surroundingCornerCloudKeyFrames.begin() + i); surroundingSurfCloudKeyFrames.erase( surroundingSurfCloudKeyFrames.begin() + i); surroundingOutlierCloudKeyFrames.erase( surroundingOutlierCloudKeyFrames.begin() + i); --i; } } // add new key frames that are not in calculated existing key frames for (int i = 0; i < numSurroundingPosesDS; ++i) { bool existingFlag = false; for (auto iter = surroundingExistingKeyPosesID.begin(); iter != surroundingExistingKeyPosesID.end(); ++iter) { if ((*iter) == (int)surroundingKeyPosesDS->points[i].intensity) { existingFlag = true; break; } } if (existingFlag == true) { continue; } else { int thisKeyInd = (int)surroundingKeyPosesDS->points[i].intensity; PointTypePose thisTransformation = cloudKeyPoses6D->points[thisKeyInd]; updateTransformPointCloudSinCos(&thisTransformation); surroundingExistingKeyPosesID.push_back(thisKeyInd); surroundingCornerCloudKeyFrames.push_back( transformPointCloud(cornerCloudKeyFrames[thisKeyInd])); surroundingSurfCloudKeyFrames.push_back( transformPointCloud(surfCloudKeyFrames[thisKeyInd])); surroundingOutlierCloudKeyFrames.push_back( transformPointCloud(outlierCloudKeyFrames[thisKeyInd])); } } for (int i = 0; i < surroundingExistingKeyPosesID.size(); ++i) { *laserCloudCornerFromMap += *surroundingCornerCloudKeyFrames[i]; *laserCloudSurfFromMap += *surroundingSurfCloudKeyFrames[i]; *laserCloudSurfFromMap += *surroundingOutlierCloudKeyFrames[i]; } } // Downsample the surrounding corner key frames (or map) downSizeFilterCorner.setInputCloud(laserCloudCornerFromMap); downSizeFilterCorner.filter(*laserCloudCornerFromMapDS); laserCloudCornerFromMapDSNum = laserCloudCornerFromMapDS->points.size(); // Downsample the surrounding surf key frames (or map) downSizeFilterSurf.setInputCloud(laserCloudSurfFromMap); downSizeFilterSurf.filter(*laserCloudSurfFromMapDS); laserCloudSurfFromMapDSNum = laserCloudSurfFromMapDS->points.size(); } void MapOptimization::downsampleCurrentScan() { laserCloudCornerLastDS->clear(); downSizeFilterCorner.setInputCloud(laserCloudCornerLast); downSizeFilterCorner.filter(*laserCloudCornerLastDS); laserCloudCornerLastDSNum = laserCloudCornerLastDS->points.size(); laserCloudSurfLastDS->clear(); downSizeFilterSurf.setInputCloud(laserCloudSurfLast); downSizeFilterSurf.filter(*laserCloudSurfLastDS); laserCloudSurfLastDSNum = laserCloudSurfLastDS->points.size(); laserCloudOutlierLastDS->clear(); downSizeFilterOutlier.setInputCloud(laserCloudOutlierLast); downSizeFilterOutlier.filter(*laserCloudOutlierLastDS); laserCloudOutlierLastDSNum = laserCloudOutlierLastDS->points.size(); laserCloudSurfTotalLast->clear(); laserCloudSurfTotalLastDS->clear(); *laserCloudSurfTotalLast += *laserCloudSurfLastDS; *laserCloudSurfTotalLast += *laserCloudOutlierLastDS; downSizeFilterSurf.setInputCloud(laserCloudSurfTotalLast); downSizeFilterSurf.filter(*laserCloudSurfTotalLastDS); laserCloudSurfTotalLastDSNum = laserCloudSurfTotalLastDS->points.size(); } void MapOptimization::cornerOptimization(int iterCount) { updatePointAssociateToMapSinCos(); for (int i = 0; i < laserCloudCornerLastDSNum; i++) { pointOri = laserCloudCornerLastDS->points[i]; pointAssociateToMap(&pointOri, &pointSel); kdtreeCornerFromMap.nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis); if (pointSearchSqDis[4] < 1.0) { float cx = 0, cy = 0, cz = 0; for (int j = 0; j < 5; j++) { cx += laserCloudCornerFromMapDS->points[pointSearchInd[j]].x; cy += laserCloudCornerFromMapDS->points[pointSearchInd[j]].y; cz += laserCloudCornerFromMapDS->points[pointSearchInd[j]].z; } cx /= 5; cy /= 5; cz /= 5; float a11 = 0, a12 = 0, a13 = 0, a22 = 0, a23 = 0, a33 = 0; for (int j = 0; j < 5; j++) { float ax = laserCloudCornerFromMapDS->points[pointSearchInd[j]].x - cx; float ay = laserCloudCornerFromMapDS->points[pointSearchInd[j]].y - cy; float az = laserCloudCornerFromMapDS->points[pointSearchInd[j]].z - cz; a11 += ax * ax; a12 += ax * ay; a13 += ax * az; a22 += ay * ay; a23 += ay * az; a33 += az * az; } a11 /= 5; a12 /= 5; a13 /= 5; a22 /= 5; a23 /= 5; a33 /= 5; matA1(0, 0) = a11; matA1(0, 1) = a12; matA1(0, 2) = a13; matA1(1, 0) = a12; matA1(1, 1) = a22; matA1(1, 2) = a23; matA1(2, 0) = a13; matA1(2, 1) = a23; matA1(2, 2) = a33; Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> esolver(matA1); matD1 = esolver.eigenvalues().real(); matV1 = esolver.eigenvectors().real(); if (matD1[2] > 3 * matD1[1]) { float x0 = pointSel.x; float y0 = pointSel.y; float z0 = pointSel.z; float x1 = cx + 0.1 * matV1(0, 0); float y1 = cy + 0.1 * matV1(0, 1); float z1 = cz + 0.1 * matV1(0, 2); float x2 = cx - 0.1 * matV1(0, 0); float y2 = cy - 0.1 * matV1(0, 1); float z2 = cz - 0.1 * matV1(0, 2); float a012 = sqrt(((x0 - x1) * (y0 - y2) - (x0 - x2) * (y0 - y1)) * ((x0 - x1) * (y0 - y2) - (x0 - x2) * (y0 - y1)) + ((x0 - x1) * (z0 - z2) - (x0 - x2) * (z0 - z1)) * ((x0 - x1) * (z0 - z2) - (x0 - x2) * (z0 - z1)) + ((y0 - y1) * (z0 - z2) - (y0 - y2) * (z0 - z1)) * ((y0 - y1) * (z0 - z2) - (y0 - y2) * (z0 - z1))); float l12 = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)); float la = ((y1 - y2) * ((x0 - x1) * (y0 - y2) - (x0 - x2) * (y0 - y1)) + (z1 - z2) * ((x0 - x1) * (z0 - z2) - (x0 - x2) * (z0 - z1))) / a012 / l12; float lb = -((x1 - x2) * ((x0 - x1) * (y0 - y2) - (x0 - x2) * (y0 - y1)) - (z1 - z2) * ((y0 - y1) * (z0 - z2) - (y0 - y2) * (z0 - z1))) / a012 / l12; float lc = -((x1 - x2) * ((x0 - x1) * (z0 - z2) - (x0 - x2) * (z0 - z1)) + (y1 - y2) * ((y0 - y1) * (z0 - z2) - (y0 - y2) * (z0 - z1))) / a012 / l12; float ld2 = a012 / l12; float s = 1 - 0.9 * fabs(ld2); coeff.x = s * la; coeff.y = s * lb; coeff.z = s * lc; coeff.intensity = s * ld2; if (s > 0.1) { laserCloudOri->push_back(pointOri); coeffSel->push_back(coeff); } } } } } void MapOptimization::surfOptimization(int iterCount) { updatePointAssociateToMapSinCos(); for (int i = 0; i < laserCloudSurfTotalLastDSNum; i++) { pointOri = laserCloudSurfTotalLastDS->points[i]; pointAssociateToMap(&pointOri, &pointSel); kdtreeSurfFromMap.nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis); if (pointSearchSqDis[4] < 1.0) { for (int j = 0; j < 5; j++) { matA0(j, 0) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].x; matA0(j, 1) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].y; matA0(j, 2) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].z; } matX0 = matA0.colPivHouseholderQr().solve(matB0); float pa = matX0(0, 0); float pb = matX0(1, 0); float pc = matX0(2, 0); float pd = 1; float ps = sqrt(pa * pa + pb * pb + pc * pc); pa /= ps; pb /= ps; pc /= ps; pd /= ps; bool planeValid = true; for (int j = 0; j < 5; j++) { if (fabs(pa * laserCloudSurfFromMapDS->points[pointSearchInd[j]].x + pb * laserCloudSurfFromMapDS->points[pointSearchInd[j]].y + pc * laserCloudSurfFromMapDS->points[pointSearchInd[j]].z + pd) > 0.2) { planeValid = false; break; } } if (planeValid) { float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd; float s = 1 - 0.9 * fabs(pd2) / sqrt(sqrt(pointSel.x * pointSel.x + pointSel.y * pointSel.y + pointSel.z * pointSel.z)); coeff.x = s * pa; coeff.y = s * pb; coeff.z = s * pc; coeff.intensity = s * pd2; if (s > 0.1) { laserCloudOri->push_back(pointOri); coeffSel->push_back(coeff); } } } } } bool MapOptimization::LMOptimization(int iterCount) { float srx = sin(transformTobeMapped[0]); float crx = cos(transformTobeMapped[0]); float sry = sin(transformTobeMapped[1]); float cry = cos(transformTobeMapped[1]); float srz = sin(transformTobeMapped[2]); float crz = cos(transformTobeMapped[2]); int laserCloudSelNum = laserCloudOri->points.size(); if (laserCloudSelNum < 50) { return false; } Eigen::Matrix<float,Eigen::Dynamic,6> matA(laserCloudSelNum, 6); Eigen::Matrix<float,6,Eigen::Dynamic> matAt(6,laserCloudSelNum); Eigen::Matrix<float,6,6> matAtA; Eigen::VectorXf matB(laserCloudSelNum); Eigen::Matrix<float,6,1> matAtB; Eigen::Matrix<float,6,1> matX; for (int i = 0; i < laserCloudSelNum; i++) { pointOri = laserCloudOri->points[i]; coeff = coeffSel->points[i]; float arx = (crx * sry * srz * pointOri.x + crx * crz * sry * pointOri.y - srx * sry * pointOri.z) * coeff.x + (-srx * srz * pointOri.x - crz * srx * pointOri.y - crx * pointOri.z) * coeff.y + (crx * cry * srz * pointOri.x + crx * cry * crz * pointOri.y - cry * srx * pointOri.z) * coeff.z; float ary = ((cry * srx * srz - crz * sry) * pointOri.x + (sry * srz + cry * crz * srx) * pointOri.y + crx * cry * pointOri.z) * coeff.x + ((-cry * crz - srx * sry * srz) * pointOri.x + (cry * srz - crz * srx * sry) * pointOri.y - crx * sry * pointOri.z) * coeff.z; float arz = ((crz * srx * sry - cry * srz) * pointOri.x + (-cry * crz - srx * sry * srz) * pointOri.y) * coeff.x + (crx * crz * pointOri.x - crx * srz * pointOri.y) * coeff.y + ((sry * srz + cry * crz * srx) * pointOri.x + (crz * sry - cry * srx * srz) * pointOri.y) * coeff.z; matA(i, 0) = arx; matA(i, 1) = ary; matA(i, 2) = arz; matA(i, 3) = coeff.x; matA(i, 4) = coeff.y; matA(i, 5) = coeff.z; matB(i, 0) = -coeff.intensity; } matAt = matA.transpose(); matAtA = matAt * matA; matAtB = matAt * matB; matX = matAtA.colPivHouseholderQr().solve(matAtB); if (iterCount == 0) { Eigen::Matrix<float,1,6> matE; Eigen::Matrix<float,6,6> matV; Eigen::Matrix<float,6,6> matV2; Eigen::SelfAdjointEigenSolver< Eigen::Matrix<float,6, 6> > esolver(matAtA); matE = esolver.eigenvalues().real(); matV = esolver.eigenvectors().real(); matV2 = matV; isDegenerate = false; float eignThre[6] = {100, 100, 100, 100, 100, 100}; for (int i = 5; i >= 0; i--) { if (matE(0, i) < eignThre[i]) { for (int j = 0; j < 6; j++) { matV2(i, j) = 0; } isDegenerate = true; } else { break; } } matP = matV.inverse() * matV2; } if (isDegenerate) { Eigen::Matrix<float,6, 1> matX2(matX); matX2 = matX; matX = matP * matX2; } transformTobeMapped[0] += matX(0, 0); transformTobeMapped[1] += matX(1, 0); transformTobeMapped[2] += matX(2, 0); transformTobeMapped[3] += matX(3, 0); transformTobeMapped[4] += matX(4, 0); transformTobeMapped[5] += matX(5, 0); float deltaR = sqrt(pow(pcl::rad2deg(matX(0, 0)), 2) + pow(pcl::rad2deg(matX(1, 0)), 2) + pow(pcl::rad2deg(matX(2, 0)), 2)); float deltaT = sqrt(pow(matX(3, 0) * 100, 2) + pow(matX(4, 0) * 100, 2) + pow(matX(5, 0) * 100, 2)); if (deltaR < 0.05 && deltaT < 0.05) { return true; } return false; } void MapOptimization::scan2MapOptimization() { if (laserCloudCornerFromMapDSNum > 10 && laserCloudSurfFromMapDSNum > 100) { kdtreeCornerFromMap.setInputCloud(laserCloudCornerFromMapDS); kdtreeSurfFromMap.setInputCloud(laserCloudSurfFromMapDS); for (int iterCount = 0; iterCount < 10; iterCount++) { laserCloudOri->clear(); coeffSel->clear(); cornerOptimization(iterCount); surfOptimization(iterCount); if (LMOptimization(iterCount) == true) break; } transformUpdate(); } } void MapOptimization::saveKeyFramesAndFactor() { currentRobotPosPoint.x = transformAftMapped[3]; currentRobotPosPoint.y = transformAftMapped[4]; currentRobotPosPoint.z = transformAftMapped[5]; gtsam::Vector Vector6(6); Vector6 << 1e-6, 1e-6, 1e-6, 1e-8, 1e-8, 1e-6; auto priorNoise = noiseModel::Diagonal::Variances(Vector6); auto odometryNoise = noiseModel::Diagonal::Variances(Vector6); bool saveThisKeyFrame = true; if (sqrt((previousRobotPosPoint.x - currentRobotPosPoint.x) * (previousRobotPosPoint.x - currentRobotPosPoint.x) + (previousRobotPosPoint.y - currentRobotPosPoint.y) * (previousRobotPosPoint.y - currentRobotPosPoint.y) + (previousRobotPosPoint.z - currentRobotPosPoint.z) * (previousRobotPosPoint.z - currentRobotPosPoint.z)) < 0.3) { saveThisKeyFrame = false; } if (saveThisKeyFrame == false && !cloudKeyPoses3D->points.empty()) return; previousRobotPosPoint = currentRobotPosPoint; /** * update grsam graph */ if (cloudKeyPoses3D->points.empty()) { gtSAMgraph.add(PriorFactor<Pose3>( 0, Pose3(Rot3::RzRyRx(transformTobeMapped[2], transformTobeMapped[0], transformTobeMapped[1]), Point3(transformTobeMapped[5], transformTobeMapped[3], transformTobeMapped[4])), priorNoise)); initialEstimate.insert( 0, Pose3(Rot3::RzRyRx(transformTobeMapped[2], transformTobeMapped[0], transformTobeMapped[1]), Point3(transformTobeMapped[5], transformTobeMapped[3], transformTobeMapped[4]))); for (int i = 0; i < 6; ++i) transformLast[i] = transformTobeMapped[i]; } else { gtsam::Pose3 poseFrom = Pose3( Rot3::RzRyRx(transformLast[2], transformLast[0], transformLast[1]), Point3(transformLast[5], transformLast[3], transformLast[4])); gtsam::Pose3 poseTo = Pose3(Rot3::RzRyRx(transformAftMapped[2], transformAftMapped[0], transformAftMapped[1]), Point3(transformAftMapped[5], transformAftMapped[3], transformAftMapped[4])); gtSAMgraph.add(BetweenFactor<Pose3>( cloudKeyPoses3D->points.size() - 1, cloudKeyPoses3D->points.size(), poseFrom.between(poseTo), odometryNoise)); initialEstimate.insert( cloudKeyPoses3D->points.size(), Pose3(Rot3::RzRyRx(transformAftMapped[2], transformAftMapped[0], transformAftMapped[1]), Point3(transformAftMapped[5], transformAftMapped[3], transformAftMapped[4]))); } /** * update iSAM */ isam->update(gtSAMgraph, initialEstimate); isam->update(); gtSAMgraph.resize(0); initialEstimate.clear(); /** * save key poses */ PointType thisPose3D; PointTypePose thisPose6D; Pose3 latestEstimate; isamCurrentEstimate = isam->calculateEstimate(); latestEstimate = isamCurrentEstimate.at<Pose3>(isamCurrentEstimate.size() - 1); thisPose3D.x = latestEstimate.translation().y(); thisPose3D.y = latestEstimate.translation().z(); thisPose3D.z = latestEstimate.translation().x(); thisPose3D.intensity = cloudKeyPoses3D->points.size(); // this can be used as index cloudKeyPoses3D->push_back(thisPose3D); thisPose6D.x = thisPose3D.x; thisPose6D.y = thisPose3D.y; thisPose6D.z = thisPose3D.z; thisPose6D.intensity = thisPose3D.intensity; // this can be used as index thisPose6D.roll = latestEstimate.rotation().pitch(); thisPose6D.pitch = latestEstimate.rotation().yaw(); thisPose6D.yaw = latestEstimate.rotation().roll(); // in camera frame thisPose6D.time = timeLaserOdometry; cloudKeyPoses6D->push_back(thisPose6D); /** * save updated transform */ if (cloudKeyPoses3D->points.size() > 1) { transformAftMapped[0] = latestEstimate.rotation().pitch(); transformAftMapped[1] = latestEstimate.rotation().yaw(); transformAftMapped[2] = latestEstimate.rotation().roll(); transformAftMapped[3] = latestEstimate.translation().y(); transformAftMapped[4] = latestEstimate.translation().z(); transformAftMapped[5] = latestEstimate.translation().x(); for (int i = 0; i < 6; ++i) { transformLast[i] = transformAftMapped[i]; transformTobeMapped[i] = transformAftMapped[i]; } } pcl::PointCloud<PointType>::Ptr thisCornerKeyFrame( new pcl::PointCloud<PointType>()); pcl::PointCloud<PointType>::Ptr thisSurfKeyFrame( new pcl::PointCloud<PointType>()); pcl::PointCloud<PointType>::Ptr thisOutlierKeyFrame( new pcl::PointCloud<PointType>()); pcl::copyPointCloud(*laserCloudCornerLastDS, *thisCornerKeyFrame); pcl::copyPointCloud(*laserCloudSurfLastDS, *thisSurfKeyFrame); pcl::copyPointCloud(*laserCloudOutlierLastDS, *thisOutlierKeyFrame); cornerCloudKeyFrames.push_back(thisCornerKeyFrame); surfCloudKeyFrames.push_back(thisSurfKeyFrame); outlierCloudKeyFrames.push_back(thisOutlierKeyFrame); } void MapOptimization::correctPoses() { if (aLoopIsClosed == true) { recentCornerCloudKeyFrames.clear(); recentSurfCloudKeyFrames.clear(); recentOutlierCloudKeyFrames.clear(); // update key poses int numPoses = isamCurrentEstimate.size(); for (int i = 0; i < numPoses; ++i) { cloudKeyPoses3D->points[i].x = isamCurrentEstimate.at<Pose3>(i).translation().y(); cloudKeyPoses3D->points[i].y = isamCurrentEstimate.at<Pose3>(i).translation().z(); cloudKeyPoses3D->points[i].z = isamCurrentEstimate.at<Pose3>(i).translation().x(); cloudKeyPoses6D->points[i].x = cloudKeyPoses3D->points[i].x; cloudKeyPoses6D->points[i].y = cloudKeyPoses3D->points[i].y; cloudKeyPoses6D->points[i].z = cloudKeyPoses3D->points[i].z; cloudKeyPoses6D->points[i].roll = isamCurrentEstimate.at<Pose3>(i).rotation().pitch(); cloudKeyPoses6D->points[i].pitch = isamCurrentEstimate.at<Pose3>(i).rotation().yaw(); cloudKeyPoses6D->points[i].yaw = isamCurrentEstimate.at<Pose3>(i).rotation().roll(); } aLoopIsClosed = false; } } void MapOptimization::clearCloud() { laserCloudCornerFromMap->clear(); laserCloudSurfFromMap->clear(); laserCloudCornerFromMapDS->clear(); laserCloudSurfFromMapDS->clear(); } void MapOptimization::run() { size_t cycle_count = 0; while (ros::ok()) { AssociationOut association; _input_channel.receive(association); if( !ros::ok() ) break; { std::lock_guard<std::mutex> lock(mtx); laserCloudCornerLast = association.cloud_corner_last; laserCloudSurfLast = association.cloud_surf_last; laserCloudOutlierLast = association.cloud_outlier_last; timeLaserOdometry = association.laser_odometry.header.stamp.toSec(); timeLastProcessing = timeLaserOdometry; OdometryToTransform(association.laser_odometry, transformSum); transformAssociateToMap(); extractSurroundingKeyFrames(); downsampleCurrentScan(); scan2MapOptimization(); saveKeyFramesAndFactor(); correctPoses(); publishTF(); publishKeyPosesAndFrames(); clearCloud(); } cycle_count++; if ((cycle_count % 3) == 0) { _loop_closure_signal.send(true); } if ((cycle_count % 10) == 0) { _publish_global_signal.send(true); } } }
38.552908
89
0.627047
[ "vector", "transform" ]
232659cef9a34dbeff616b39d6fc281107e40896
4,359
cpp
C++
clients/cpp-pistache-server/generated/model/GithubRepositorypermissions.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-pistache-server/generated/model/GithubRepositorypermissions.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-pistache-server/generated/model/GithubRepositorypermissions.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "GithubRepositorypermissions.h" #include "Helpers.h" #include <sstream> namespace org::openapitools::server::model { GithubRepositorypermissions::GithubRepositorypermissions() { m_Admin = false; m_AdminIsSet = false; m_Push = false; m_PushIsSet = false; m_Pull = false; m_PullIsSet = false; m__class = ""; m__classIsSet = false; } void GithubRepositorypermissions::validate() const { std::stringstream msg; if (!validate(msg)) { throw org::openapitools::server::helpers::ValidationException(msg.str()); } } bool GithubRepositorypermissions::validate(std::stringstream& msg) const { return validate(msg, ""); } bool GithubRepositorypermissions::validate(std::stringstream& msg, const std::string& pathPrefix) const { bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "GithubRepositorypermissions" : pathPrefix; return success; } bool GithubRepositorypermissions::operator==(const GithubRepositorypermissions& rhs) const { return ((!adminIsSet() && !rhs.adminIsSet()) || (adminIsSet() && rhs.adminIsSet() && isAdmin() == rhs.isAdmin())) && ((!pushIsSet() && !rhs.pushIsSet()) || (pushIsSet() && rhs.pushIsSet() && isPush() == rhs.isPush())) && ((!pullIsSet() && !rhs.pullIsSet()) || (pullIsSet() && rhs.pullIsSet() && isPull() == rhs.isPull())) && ((!r_classIsSet() && !rhs.r_classIsSet()) || (r_classIsSet() && rhs.r_classIsSet() && getClass() == rhs.getClass())) ; } bool GithubRepositorypermissions::operator!=(const GithubRepositorypermissions& rhs) const { return !(*this == rhs); } void to_json(nlohmann::json& j, const GithubRepositorypermissions& o) { j = nlohmann::json(); if(o.adminIsSet()) j["admin"] = o.m_Admin; if(o.pushIsSet()) j["push"] = o.m_Push; if(o.pullIsSet()) j["pull"] = o.m_Pull; if(o.r_classIsSet()) j["_class"] = o.m__class; } void from_json(const nlohmann::json& j, GithubRepositorypermissions& o) { if(j.find("admin") != j.end()) { j.at("admin").get_to(o.m_Admin); o.m_AdminIsSet = true; } if(j.find("push") != j.end()) { j.at("push").get_to(o.m_Push); o.m_PushIsSet = true; } if(j.find("pull") != j.end()) { j.at("pull").get_to(o.m_Pull); o.m_PullIsSet = true; } if(j.find("_class") != j.end()) { j.at("_class").get_to(o.m__class); o.m__classIsSet = true; } } bool GithubRepositorypermissions::isAdmin() const { return m_Admin; } void GithubRepositorypermissions::setAdmin(bool const value) { m_Admin = value; m_AdminIsSet = true; } bool GithubRepositorypermissions::adminIsSet() const { return m_AdminIsSet; } void GithubRepositorypermissions::unsetAdmin() { m_AdminIsSet = false; } bool GithubRepositorypermissions::isPush() const { return m_Push; } void GithubRepositorypermissions::setPush(bool const value) { m_Push = value; m_PushIsSet = true; } bool GithubRepositorypermissions::pushIsSet() const { return m_PushIsSet; } void GithubRepositorypermissions::unsetPush() { m_PushIsSet = false; } bool GithubRepositorypermissions::isPull() const { return m_Pull; } void GithubRepositorypermissions::setPull(bool const value) { m_Pull = value; m_PullIsSet = true; } bool GithubRepositorypermissions::pullIsSet() const { return m_PullIsSet; } void GithubRepositorypermissions::unsetPull() { m_PullIsSet = false; } std::string GithubRepositorypermissions::getClass() const { return m__class; } void GithubRepositorypermissions::setClass(std::string const& value) { m__class = value; m__classIsSet = true; } bool GithubRepositorypermissions::r_classIsSet() const { return m__classIsSet; } void GithubRepositorypermissions::unset_class() { m__classIsSet = false; } } // namespace org::openapitools::server::model
22.469072
120
0.657261
[ "model" ]
232b34f5f2fd1dbab199c8168aa969af2a96d2c7
7,471
cpp
C++
src/sprogc/source/gpc_delta_stoich.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
3
2020-09-08T14:06:33.000Z
2020-12-04T07:52:19.000Z
src/sprogc/source/gpc_delta_stoich.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
null
null
null
src/sprogc/source/gpc_delta_stoich.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
3
2021-11-15T05:18:26.000Z
2022-03-01T13:51:20.000Z
/* Author(s): Martin Martin (mm864) Project: sprog (gas-phase and surface chemical kinetics). Sourceforge: http://sourceforge.net/projects/mopssuite Copyright (C) 2012 Martin Martin. File purpose: Implementation of the Stoichiometry class declared in the gpc_Delta_stoich.h header file. Licence: This file is part of "sprog". sprog is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Contact: Dr Markus Kraft Dept of Chemical Engineering University of Cambridge New Museums Site Pembroke Street Cambridge CB2 3RA UK Email: mk306@cam.ac.uk Website: http://como.cheng.cam.ac.uk */ #include "gpc_delta_stoich.h" #include "gpc_reaction.h" #include "string_functions.h" #include <string> #include <cmath> #include <stdexcept> using namespace Strings; using namespace Sprog::Kinetics; using namespace std; // CONSTRUCTORS AND DESTRUCTORS. // Default constructor. DeltaStoich::DeltaStoich(void) { m_spName = ""; total_stoich_sp = 0.0; reac_stoich_sp = 0.0; prod_stoich_sp = 0.0; } // Copy constructor. DeltaStoich::DeltaStoich(const Sprog::Kinetics::DeltaStoich &delta_stoich) { m_spName = delta_stoich.m_spName; total_stoich_sp = delta_stoich.total_stoich_sp; reac_stoich_sp = delta_stoich.reac_stoich_sp; prod_stoich_sp = delta_stoich.prod_stoich_sp; } DeltaStoich::DeltaStoich(std::string &name) // Initialising constructor. { m_spName = name; total_stoich_sp = 0.0; reac_stoich_sp = 0.0; prod_stoich_sp = 0.0; } DeltaStoich::DeltaStoich(std::istream &in) // Stream in initilisation { Deserialize(in); } // Destructor. DeltaStoich::~DeltaStoich(void) { // There is nothing special to destruct here. } // OPERATOR OVERLOADING. // Assignment operator. DeltaStoich &DeltaStoich::operator=(const Sprog::Kinetics::DeltaStoich &delta_stoich) { // Check for self-assignment! if (this != &delta_stoich) { m_spName = delta_stoich.m_spName; total_stoich_sp = delta_stoich.total_stoich_sp; reac_stoich_sp = delta_stoich.reac_stoich_sp; prod_stoich_sp = delta_stoich.prod_stoich_sp; } return *this; } // Comparison operator: Compares a DeltaStoich object to a string. Returns // true if the DeltaStoich name is the same as the string. bool DeltaStoich::operator==(const std::string &name) const { return m_spName.compare(name)==0; } // Sets the species name. void Sprog::Kinetics::DeltaStoich::SetSpeciesName(const std::string &name) { m_spName = name; } // Sets/change the total stoichiometry change of this species. void Sprog::Kinetics::DeltaStoich::IncrementTotalStoich(const double &value) // value can be + or - { total_stoich_sp += value; } // Sets/change the reactant stoichiometry change of this species. void Sprog::Kinetics::DeltaStoich::IncrementReacStoich(const double &value) // value can be + or - { reac_stoich_sp += value; } // Sets/change the product stoichiometry change of this species. void Sprog::Kinetics::DeltaStoich::IncrementProdStoich(const double &value) // value can be + or - { prod_stoich_sp += value; } // Sets the parent reaction. void Sprog::Kinetics::DeltaStoich::SetReaction(Sprog::Kinetics::Reaction &rct) { m_react = &rct; } // Prints a diagnostic output file containing all the stoichiometry change for each phase. This is used to debug. void Sprog::Kinetics::DeltaStoich::WriteDiagnostics(std::ostream &out) const { string data = ""; double val = 0.0; if (out.good()) { // Species Name. data = m_spName + " "; out.write(data.c_str(), data.length()); // Total stoichiometry val = total_stoich_sp; data = cstr(val) + " "; out.write(data.c_str(), data.length()); // Reactant stoichiometry val = reac_stoich_sp; data = cstr(val) + " "; out.write(data.c_str(), data.length()); // Product stoichiometry val = prod_stoich_sp; data = cstr(val) + " "; out.write(data.c_str(), data.length()); } } // Writes the phase to a binary data stream. void Sprog::Kinetics::DeltaStoich::Serialize(std::ostream &out) const { if (out.good()) { // Write the serialisation version number to the stream. const unsigned int version = 0; out.write((char*)&version, sizeof(version)); // Write the length of the species name to the stream. unsigned int n = m_spName.length(); out.write((char*)&n, sizeof(n)); // Write the species name to the stream. out.write(m_spName.c_str(), n); // Write the total stoich to the stream. double totl = (double)total_stoich_sp; out.write((char*)&totl, sizeof(totl)); // Write the reactant stoich to the stream. double rea = (double)reac_stoich_sp; out.write((char*)&rea, sizeof(rea)); // Write the prod stoich to the stream. double pro = (double)prod_stoich_sp; out.write((char*)&pro, sizeof(pro)); } else { throw invalid_argument("Output stream not ready (Sprog, DeltaStoich::Serialize)."); } } void Sprog::Kinetics::DeltaStoich::Deserialize(std::istream &in) { // Clear the phase of all current data. m_spName = ""; total_stoich_sp = 0.0; reac_stoich_sp = 0.0; prod_stoich_sp = 0.0; m_react = NULL; if (in.good()) { // Read the serialized phase version number. unsigned int version = 0; in.read(reinterpret_cast<char*>(&version), sizeof(version)); unsigned int n = 0; // Need for reading name length. char *name = NULL; double totl= 0.0; double rea = 0.0; double pro = 0.0; switch (version) { case 0: // Read the length of the delta stoich name. in.read(reinterpret_cast<char*>(&n), sizeof(n)); // Read the delta stoich name. name = new char[n]; in.read(name, n); m_spName.assign(name, n); delete [] name; // Read the total stoich. in.read(reinterpret_cast<char*>(&totl), sizeof(totl)); total_stoich_sp = (double)totl; // Read the react stoich. in.read(reinterpret_cast<char*>(&rea), sizeof(rea)); reac_stoich_sp = (double)rea; // Read the prod stoich. in.read(reinterpret_cast<char*>(&pro), sizeof(pro)); prod_stoich_sp = (double)pro; break; default: throw runtime_error("DeltaStoich serialized version number " "is unsupported (Sprog, DeltaStoich::Deserialize)."); } } else { throw invalid_argument("Input stream not ready (Sprog, DeltaStoich::Deserialize)."); } }
27.876866
114
0.654531
[ "object" ]
232b7c4c0742427cd9982d162ba488170ad53ecd
3,789
cc
C++
paddle/fluid/framework/ir/delete_quant_dequant_op_pass.cc
JingChunzhen/Paddle
1bce7caabc1c5e55b1fa13edb19719c397803c43
[ "Apache-2.0" ]
2
2021-02-04T15:04:21.000Z
2021-02-07T14:20:00.000Z
paddle/fluid/framework/ir/delete_quant_dequant_op_pass.cc
JingChunzhen/Paddle
1bce7caabc1c5e55b1fa13edb19719c397803c43
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/ir/delete_quant_dequant_op_pass.cc
JingChunzhen/Paddle
1bce7caabc1c5e55b1fa13edb19719c397803c43
[ "Apache-2.0" ]
1
2021-12-09T06:56:27.000Z
2021-12-09T06:56:27.000Z
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/delete_quant_dequant_op_pass.h" #include <string> namespace paddle { namespace framework { namespace ir { #define GET_IR_NODE(node__) GET_IR_NODE_FROM_SUBGRAPH(node__, node__, pattern); #define GET_NODES \ GET_IR_NODE(any_op_out); \ GET_IR_NODE(quant_dequant_op_inscale); \ GET_IR_NODE(quant_dequant_op); \ GET_IR_NODE(quant_dequant_op_outscale); \ GET_IR_NODE(quant_dequant_op_out); \ GET_IR_NODE(any_op2); void DeleteQuantDequantOpPass::ApplyImpl(ir::Graph* graph) const { const std::string pattern_name = "delete_quantdequant_op_pattern"; FusePassBase::Init(pattern_name, graph); GraphPatternDetector gpd; patterns::DeleteQuantDequantOpPattern pattern(gpd.mutable_pattern(), pattern_name); pattern(); auto* scope = param_scope(); auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_NODES; IR_NODE_LINK_TO(any_op_out, any_op2); std::string any_op_out_name = any_op_out->Var()->Name(); std::string quant_dequant_op_out_name = quant_dequant_op_out->Var()->Name(); std::string input_scale_var_name = quant_dequant_op->Op()->Input("InScale").front(); const LoDTensor& input_scale_tensor = scope->GetVar(input_scale_var_name)->Get<LoDTensor>(); const float* input_scale_data = input_scale_tensor.data<float>(); float input_scale = input_scale_data[0] / 127.; auto* any_op2_desc = any_op2->Op(); // auto input_args_names = any_op2_desc->InputArgumentNames(); auto var_map = any_op2_desc->Inputs(); std::string arg_name = ""; for (auto& name_m : var_map) { if (std::find(name_m.second.begin(), name_m.second.end(), quant_dequant_op_out_name) != name_m.second.end()) { arg_name = name_m.first; } } CHECK(arg_name.size() > 0) << "can not find the input " << quant_dequant_op_out_name; any_op2_desc->SetAttr("enable_int8", true); any_op2_desc->SetAttr(arg_name + "_scale", input_scale); // modify the any_op2's inputs for (auto& name_m : var_map) { if (std::find(name_m.second.begin(), name_m.second.end(), quant_dequant_op_out_name) != name_m.second.end()) { std::vector<std::string> new_inputs; for (auto& i_n : name_m.second) { if (i_n != quant_dequant_op_out_name) { new_inputs.push_back(i_n); } } new_inputs.push_back(any_op_out_name); any_op2_desc->SetInput(name_m.first, new_inputs); any_op2_desc->Flush(); } } any_op2_desc->Flush(); // Delete the unneeded nodes. GraphSafeRemoveNodes(graph, {quant_dequant_op, quant_dequant_op_out, quant_dequant_op_inscale, quant_dequant_op_outscale}); }; gpd(graph, handler); } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(delete_quant_dequant_op_pass, paddle::framework::ir::DeleteQuantDequantOpPass);
37.147059
80
0.663764
[ "vector" ]
23352f6962eea4795c8cb3fd863e79b830f36425
1,692
cpp
C++
sgm/src/texture_cache.cpp
yodasoda1219/sge
d8e099842fd57e5f968083c87fccba2a5df51f19
[ "Apache-2.0" ]
4
2022-01-02T06:08:34.000Z
2022-02-20T06:28:01.000Z
sgm/src/texture_cache.cpp
yodasoda1219/sge
d8e099842fd57e5f968083c87fccba2a5df51f19
[ "Apache-2.0" ]
null
null
null
sgm/src/texture_cache.cpp
yodasoda1219/sge
d8e099842fd57e5f968083c87fccba2a5df51f19
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Nora Beda and SGE contributors 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 "sgmpch.h" #include "texture_cache.h" namespace sgm { struct cache_data_t { std::vector<std::unordered_set<ref<texture_2d>>> used_textures; }; std::unique_ptr<cache_data_t> cache_data; void texture_cache::init() { cache_data = std::make_unique<cache_data_t>(); swapchain& swap_chain = application::get().get_swapchain(); size_t image_count = swap_chain.get_image_count(); cache_data->used_textures.resize(image_count); } void texture_cache::shutdown() { cache_data.reset(); } void texture_cache::new_frame() { swapchain& swap_chain = application::get().get_swapchain(); size_t current_image = swap_chain.get_current_image_index(); cache_data->used_textures[current_image].clear(); } void texture_cache::add_texture(ref<texture_2d> texture) { swapchain& swap_chain = application::get().get_swapchain(); size_t current_image = swap_chain.get_current_image_index(); cache_data->used_textures[current_image].insert(texture); } } // namespace sgm
36
75
0.710993
[ "vector" ]
2335f49bc65ecc51ac830921ef885d4f42a05675
1,511
cpp
C++
2015/day9/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2015/day9/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2015/day9/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
#include <climits> #include "common/types.h" #include "utils/file.h" #include "utils/utils.h" #include "utils/graph.h" #define DEBUG_LEVEL 5 #include "common/debug.h" int main(int argc, char *argv[]) { std::map<std::string, std::map<std::string, int>> locations; { auto lines = File::readAllLines(argv[1]); for (auto line = lines.begin(); line != lines.end(); line++) { auto tokens = utils::strTok(*line, ' '); locations[tokens[0]][tokens[2]] = utils::toInt(tokens[4]); locations[tokens[2]][tokens[0]] = utils::toInt(tokens[4]); } } { std::vector<std::vector<std::string>> combinations; { std::vector<std::string> keys; for (auto p = locations.begin(); p != locations.end(); p++) { keys.push_back(p->first); } utils::genPermutation<std::string>(combinations, keys); PRINTF(("Nodes: %zd, %zd", locations.size(), combinations.size())); } int min = INT_MAX; int max = INT_MIN; for (auto c = combinations.begin(); c != combinations.end(); c++) { int sum = 0; int visited = 0; while (visited != locations.size() - 1) { auto src = locations.find(c->at(visited)); auto dst = src->second.find(c->at(visited + 1)); if (dst != src->second.end()) { sum += dst->second; visited++; } else { break; } } if (visited == (locations.size() - 1)) { if (min > sum) { min = sum; } if (max < sum) { max = sum; } } } PRINTF(("PART_A: %d", min)); PRINTF(("PART_B: %d", max)); } }
20.146667
70
0.571807
[ "vector" ]
233a680191667d53842e3c0641a9c2303d215839
3,749
cpp
C++
atcoder/HTTF2018/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
atcoder/HTTF2018/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
atcoder/HTTF2018/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } const int U = 0; const int R = 1; const int D = 2; const int L = 3; const int DIR[] = {U, R, D, L}; const int di[] = {-1, 0, +1, 0}; const int dj[] = {0, +1, 0, -1}; const int M = 29; struct G { char g[M][M]; G () { fill(&g[0][0], &g[M - 1][M - 1], '.'); for (int i = 0; i < M; ++i) { g[i][0] = g[0][i] = g[i][M - 1] = g[M - 1][i] = '#'; } } bool inside(int i, int j) const { unless (0 <= i && i < M) return false; unless (0 <= j && j < M) return false; return true; } bool valid(int i, int j) const { return this->g[i][j] != '#' && this->inside(i, j); } char& at(int i, int j) { return g[i][j]; } char& at(pair<int, int> p) { return this->at(p.first, p.second); } ostream& show(ostream& os) const { for (int i = 0; i < M; ++i) { for (int j = 0; j < M; ++j) { os << g[i][j]; } os << endl; } return os; } vector<pair<int, int>> run(string cmd) { int d = U; pair<int, int> p = make_pair(M / 2, M / 2); vector<pair<int, int>> path; each (c, cmd) { path.push_back(p); int x = 1; if (this->at(p) == 'D') x = 2; if (this->at(p) == 'T') x = 3; for (int k = 0; k < x; ++k) { if (c == 'S') { int ni = p.first + di[d]; int nj = p.second + dj[d]; if (this->valid(ni, nj)) { p = make_pair(ni, nj); } } else if (c == 'R' || this->at(p) == 'R') { d = (d + 1) % 4; } else if (c == 'L' || this->at(p) == 'L') { d = (d - 1 + 4) % 4; } } } path.push_back(p); return path; } }; int calc_score(int x) { if (x == 1) return 10; if (x == 2) return 3; if (x == 3) return 1; return 0; } int run(const vector<string>& cmds, G& g) { assert(cmds.size()); map<pair<int, int>, int> cnt; each (cmd, cmds) { vector<pair<int, int>> path = g.run(cmd); ++cnt[path.back()]; } int score = 0; each (i, cnt) { score += calc_score(i.second); } return score; } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, _l; while (cin >> n >> m >> _l) { vector<string> cmds(n); cin >> cmds; vector<pair<int, int>> v; for (int i = 1; i < M - 1; ++i) { for (int j = 1; j < M - 1; ++j) { v.push_back(make_pair(i, j)); } } G g; random_shuffle(v.begin(), v.end()); for (int i = 0; i < v.size() / 1; ++i) { g.at(v[i]) = 'R'; } random_shuffle(v.begin(), v.end()); int mx = run(cmds, g); each (p, v) { const char C = '#'; const char tmp = g.at(p); g.at(p) = C; int x = run(cmds, g); if (mx < x) { mx = x; } else { g.at(p) = tmp; } } g.show(cout); } return 0; }
22.183432
144
0.467591
[ "vector" ]
23433c99fba82193d1af780dc42a675c5f088f3d
15,455
cpp
C++
src/KinematicForest.cpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
src/KinematicForest.cpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
src/KinematicForest.cpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
#include "quickstep/KinematicForest.h" #include <iostream> #include <math.h> #include <assert.h> /* assert */ #include <functional> // reference_wrapper #include <cassert> #include "quickstep/utils.h" #include "quickstep/DisjointSet.h" using namespace std; using namespace quickstep; //std::vector<int> DOFIndex::get_atoms(const KinematicForest &forest) const { // std::vector<int> get_atoms(const KinematicForest &forest); { // std::vector<int> atoms(dof_type+1); // atoms[0] = atom_index; // int current_atom_index = atom_index; // for (int i=1; i<dof_type+1; ++i) { // current_atom_index = forest.parent(current_atom_index); // atoms[i] = current_atom_index; // } // return atoms; // } //} KinematicForest::KinematicForest(): n_atoms(0), topology(NULL) { // Eigen::Transform translation_A(Eigen::Translation<float,3>(Eigen::Vector3f(1,1,1))); Eigen::Translation<float,3> translation_A(Eigen::Vector3f(1,1, 1)); Eigen::Translation<float,3> translation_B(Eigen::Vector3f(1,1,-1)); Eigen::AngleAxis<float> aa(0.1, Eigen::Vector3f(1,0,0)); Eigen::Transform<float,3,Eigen::Affine> trans(translation_A); } KinematicForest::KinematicForest(quickstep::Topology &topology, const CoordinatesWrapper &coordinates): topology(&topology), positions(make_unique<CoordinatesWrapper>(coordinates)), stored_positions(coordinates.rows(), coordinates.cols()) // Stored positions is a matrix and must be initialized with two sizes { //Associate each atom with a unique index between 0 and the total number of atoms n_atoms = 0; unordered_map<int, int> atomIdxMap; for( const quickstep::Topology::Chain& chain: topology.get_chains() ){ for( const quickstep::Topology::Residue& res: chain.residues ){ //for( const quickstep::Topology::Atom& atom: res.atoms ){ for( unsigned int atom_idx: res.atom_indices){ // atomIdxMap[atom.index] = n_atoms; // id_atom_map[n_atoms] = &atom; atomIdxMap[atom_idx] = n_atoms; id_atom_map[n_atoms] = &topology.atoms[atom_idx]; n_atoms++; } } } //Allocate space for tree, positions and transformations adjacency_list.resize(n_atoms); transformations.resize(n_atoms); // transformations_queue.resize(n_atoms); //Kruskals algorithm for finding minimum spanning forest DisjointSet ds(n_atoms); for( auto bond: topology.get_bonds() ){ const quickstep::Topology::Atom& a1 = topology.atoms[bond.first]; const quickstep::Topology::Atom& a2 = topology.atoms[bond.second]; int a1Idx = atomIdxMap[a1.index]; int a2Idx = atomIdxMap[a2.index]; if(!ds.connected(a1Idx, a2Idx)){ adjacency_list[a1Idx].push_back( pair<int,int>(a1Idx, a2Idx) ); adjacency_list[a2Idx].push_back( pair<int,int>(a1Idx, a2Idx) ); ds.merge(a1Idx, a2Idx); } } //Root all trees roots.push_back(0); root_tree(0, -1); for(int v=1;v<n_atoms;v++){ bool vShouldBeRoot = true; for(int r=0;r<roots.size();r++){ if(ds.connected(roots[r], v)){ vShouldBeRoot = false; break; } } if(vShouldBeRoot){ roots.push_back(v); root_tree(v,-1); } } update_pseudo_roots(); //Reset transformations for(int i=0;i<n_atoms;i++){ transformations[i].setIdentity(); } } CoordinatesWrapper &KinematicForest::get_positions() { return *positions.get(); } int KinematicForest::get_num_roots() { return roots.size(); } int KinematicForest::get_root_atom(int chain_idx) { return roots[chain_idx]; } int KinematicForest::get_num_atoms() { return n_atoms; } units::Length KinematicForest::get_length(int atom) { assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); int a1 = parent(atom); Vector3d v = pos(atom)-pos(a1); return v.norm() * units::nm; } units::Angle KinematicForest::get_angle(int atom) { assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); int a1 = parent(atom); int a2 = parent(a1); // Note the use of ColXpr instead of standard references CoordinatesWrapper::ColXpr a0_pos = pos(atom); CoordinatesWrapper::ColXpr a1_pos = pos(a1); CoordinatesWrapper::ColXpr a2_pos = pos(a2); Vector3d v1 = a2_pos-a1_pos; Vector3d v2 = a0_pos-a1_pos; double v1_len = v1.norm(); double v2_len = v2.norm(); return acos(v1.dot(v2)/(v1_len*v2_len)) * units::radians; } units::Angle KinematicForest::get_torsion(int atom) const { assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); int a1 = parent(atom); int a2 = parent(a1); int a3 = parent(a2); Coordinate a0_pos = pos(atom); Coordinate a1_pos = pos(a1); Coordinate a2_pos = pos(a2); Coordinate a3_pos = pos(a3); Vector3d v01 = a1_pos - a0_pos; Vector3d v12 = a2_pos - a1_pos; Vector3d v23 = a3_pos - a2_pos; Vector3d cross1 {v01.cross(v12).normalized()}; Vector3d cross2 {v12.cross(v23).normalized()}; double product = cross1.dot(cross2); if (product > 1.) product = 1.; if (product < -1.) product = -1.; double torsion = acos(product); if (cross1.dot(v23) < 0.) torsion *= -1; return torsion * units::radians; }; void KinematicForest::change_length(int atom, units::Length value) { assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); // if(atom==0) return; int a1 = parent(atom); Vector3d d = (pos(atom)-pos(a1)).matrix().normalized() * value.value(); transformations[atom] = transformations[atom]*Eigen::Translation<double,3>(d); moved_subtrees.insert(atom); } void KinematicForest::change_angle(int atom, units::Angle value) { //std::cout<<"change_angle("<<atom<<", "<<value<<")"<<std::endl; assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); // if(atom==0) return; int a1 = parent(atom); int a2 = parent(a1); // Note the use of ColXpr instead of standard references CoordinatesWrapper::ColXpr pos_a = pos(atom); CoordinatesWrapper::ColXpr pos_a1 = pos(a1); CoordinatesWrapper::ColXpr pos_a2 = pos(a2); Vector3d v1 = pos_a2 - pos_a1; Vector3d v2 = pos_a - pos_a1; Vector3d axis = v1.cross(v2).normalized(); transformations[atom] = transformations[atom] * Eigen::Translation<double, 3>(pos_a1)* Eigen::AngleAxis<double>(value.value(), axis)* Eigen::Translation<double, 3>(-pos_a1); moved_subtrees.insert(atom); } void KinematicForest::change_torsion(int atom, units::Angle value) { //cout<<"KinematicForest::change_torsion("<<atom<<", "<<value<<")"<<endl; assert(atom>=0 && atom<n_atoms); // if(!pseudoRootsSet) update_pseudo_roots(); // if(atom==0) return; int a1 = parent(atom); int a2 = parent(a1); // Note the use of ColXpr instead of standard references CoordinatesWrapper::ColXpr pos_a1 = pos(a1); CoordinatesWrapper::ColXpr pos_a2 = pos(a2); Vector3d axis = (pos_a2 - pos_a1).matrix().normalized(); transformations[atom] = transformations[atom]* Eigen::Translation<double, 3>( pos_a1) * Eigen::AngleAxis<double>(-value.value(), axis) * Eigen::Translation<double, 3>(-pos_a1); moved_subtrees.insert(atom); } void KinematicForest::change_global(int chain, Eigen::Transform<double, 3, Eigen::Affine>& t) { // if(!pseudoRootsSet) update_pseudo_roots(); // int idx1 = parent(parent(roots[chain])); int idx1 = roots[chain]; transformations[idx1] = transformations[idx1] * t;//Eigen::Transform<units::Length, 3, Eigen::Affine>(t); moved_subtrees.insert(idx1); } void KinematicForest::update_positions() { // if(!pseudoRootsSet) update_pseudo_roots(); //forward_propagate_transformations(-1); //Ensure that moved_subtrees dont contain two vertices where one is an ancestor of the other unordered_set<int> to_remove; for(const int& r1: moved_subtrees){ for(const int& r2: moved_subtrees){ if(r1==r2) break; if(ancestor_of(r1,r2)) to_remove.insert(r2); else if(ancestor_of(r2,r1)) to_remove.insert(r1); } } for(const int& r: to_remove) { moved_subtrees.erase(r); //cout << "Removed " << r << " from subtrees to be moved"<<endl; } stored_indices.clear(); for(const int& subtree_root: moved_subtrees){ //cout<<"Moving subtree "<<subtree_root<<endl; forward_propagate_transformations(subtree_root); } moved_subtrees.clear(); } void KinematicForest::forward_propagate_transformations(int atom) { // std::cout<<"forwardPropagateTransformations "<<atom<<std::endl; if(atom<0){ for(size_t i=0;i<roots.size();i++){ forward_propagate_transformations(roots[i]); } }else{ int p = parent(atom); if(p>=0) transformations[atom] = transformations[p]*transformations[atom]; backup_pos(atom); stored_positions.col(atom) = positions->col(atom); positions->col(atom) = transformations[atom] * positions->col(atom).matrix(); stored_indices.insert(atom); for(int c=0;c<adjacency_list[atom].size();c++){ if(adjacency_list[atom][c].second!=atom) forward_propagate_transformations(adjacency_list[atom][c].second); } transformations[atom].setIdentity(); } } void KinematicForest::restore_positions() { for(auto &i: stored_indices){ positions->col(i) = stored_positions.col(i); } } CoordinatesWrapper::ColXpr KinematicForest::pos(int i) { // assert(i>-4 && i<n_atoms); if(i<0 && i>-4){ CoordinatesWrapper wrapper = CoordinatesWrapper( pseudo_root_positions.data(), 3, pseudo_root_positions.cols() ); return wrapper.col(i+3); } return positions->col(i); } Coordinate KinematicForest::pos(int i) const { // assert(i>-4 && i<n_atoms); if(i<0 && i>-4){ ConstCoordinatesWrapper wrapper = ConstCoordinatesWrapper( pseudo_root_positions.data(), 3, pseudo_root_positions.cols() ); return wrapper.col(i+3); } return positions->col(i); } void KinematicForest::backup_pos(int i) { assert(i>=0 && i<n_atoms); stored_positions.col(i) = positions->col(i); } //void KinematicForest::apply_transformation_at_pos(int i) //{ // assert( i>=0 && i<n_atoms ); // positions->col(i) = transformations[i] * positions->col(i).matrix(); // //// if(i>=n_atoms){ //// pseudo_root_positions.col(i-n_atoms) = transformations[i]*pseudo_root_positions.col(i-n_atoms).matrix(); //// }else{ //// positions->col(i) = transformations[i]*positions->col(i).matrix(); //// } //} void KinematicForest::root_tree(int v, int p) { for(int c=0;c<adjacency_list[v].size();c++){ if(adjacency_list[v][c].second==v && adjacency_list[v][c].first!=p){ //Switch direction of edge int v2 = adjacency_list[v][c].first; adjacency_list[v][c].first = v; adjacency_list[v][c].second = v2; for(int c2=0;c2<adjacency_list[v2].size();c2++){ if(adjacency_list[v2][c2].second==v){ adjacency_list[v2][c2].first = v; adjacency_list[v2][c2].second = v2; break; } } } if(adjacency_list[v][c].second != v) root_tree(adjacency_list[v][c].second, v); } } int KinematicForest::parent(int v) const { if(v<0) return v-1; for(int c=0;c<adjacency_list[v].size();c++){ if(adjacency_list[v][c].second==v) return adjacency_list[v][c].first; } return -1; } bool KinematicForest::ancestor_of(int v1, int v2) { int v = parent(v2); while(v>0){ if(v==v1) return true; v = parent(v); } return false; } void KinematicForest::print() { std::cout<<"KinematicForest:"<<std::endl; for(int v=0;v<adjacency_list.size();v++){ std::cout<<" adjacencies["<<v<<"]: "; for(int a=0;a<adjacency_list[v].size();a++){ if(adjacency_list[v][a].second!=v) std::cout<<" "<<adjacency_list[v][a].second; } std::cout<<std::endl; } } Topology* KinematicForest::get_topology() { return topology; } const Topology::Atom& KinematicForest::get_atom(int atom) { assert(atom>=0 && atom<n_atoms); return *id_atom_map[atom]; } bool KinematicForest::atom_matches_names(int atom, const std::vector<std::string>& dofNames) { int a = atom; bool matches = true; for (int p=0;p<dofNames.size();p++) { if(a<0 || a>=n_atoms || get_atom(a).name!=dofNames[p]) { matches = false; break; } a = parent(a); } if (matches) return matches; a = atom; matches = true; for (int p=dofNames.size()-1; p>=0; --p) { //if(a >= n_atoms || get_atom(a).name != dofNames[p]) { if(a < 0 || get_atom(a).name != dofNames[p]) { matches = false; break; } a = parent(a); } return matches; } void KinematicForest::update_pseudo_roots() { // // NOTE: resize of matrix requires two size arguments // pseudo_root_positions.resize(3, roots.size()*2); // stored_pseudo_root_positions.resize(3, roots.size()*2); pseudo_root_positions.resize(3,3); for(int r=0;r<roots.size();r++){ int idxr = roots[r]; // int idx0 = n_atoms; // int idx1 = idx0+1; // // units::Coordinate p0 = positions->col( idxr ) + units::Coordinate(0.1* units::nm, 0.0* units::nm, 0.0* units::nm) ; // units::Coordinate p1 = positions->col( idxr ) + units::Coordinate(0.1* units::nm, 0.1* units::nm, 0.0* units::nm); // pseudo_root_positions.col(r*2 ) = p0; // pseudo_root_positions.col(r*2+1) = p1; // // adjacency_list.push_back( std::vector< pair<int,int> >() ); // adjacency_list[idx0].push_back( std::make_pair( idx0, idxr ) ); // adjacency_list[idxr].push_back( std::make_pair( idx0, idxr ) ); adjacency_list[idxr].push_back( std::make_pair( -1, idxr )); // adjacency_list.push_back( std::vector< pair<int,int> >() ); // adjacency_list[idx1].push_back( std::make_pair( idx1, idx0 ) ); // adjacency_list[idx0].push_back( std::make_pair( idx1, idx0 ) ); // // transformations.push_back(QSTransform::Identity()); // transformations.push_back(QSTransform::Identity()); } // // pseudoRootsSet = true; } int KinematicForest::get_parent(int atom_index) { return parent(atom_index); } std::vector<int> KinematicForest::get_ancestors(int atom_index, Dof::Type dof_type) { std::vector<int> atoms(dof_type+1); atoms[0] = atom_index; int current_atom_index = atom_index; for (int i=1; i<dof_type+1; ++i) { current_atom_index = parent(current_atom_index); atoms[i] = current_atom_index; } return atoms; } // TODO: adjencency list should be reimplemented so that this function can just return a reference std::vector<int> KinematicForest::get_children(int parent_index) { std::vector<int> child_atom_indices; for(size_t i=0; i<adjacency_list[parent_index].size();++i) { if(adjacency_list[parent_index][i].first == parent_index) { child_atom_indices.push_back(adjacency_list[parent_index][i].second); } } return child_atom_indices; }
28.202555
129
0.637464
[ "vector", "transform" ]
234a86313e560b4bf35a04bebdde0970e01bc09e
52,125
cpp
C++
native/libs/gui/BufferQueueProducer.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
null
null
null
native/libs/gui/BufferQueueProducer.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
null
null
null
native/libs/gui/BufferQueueProducer.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
null
null
null
/* * Copyright 2014 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 <inttypes.h> #define LOG_TAG "BufferQueueProducer" #define ATRACE_TAG ATRACE_TAG_GRAPHICS //#define LOG_NDEBUG 0 #if DEBUG_ONLY_CODE #define VALIDATE_CONSISTENCY() do { mCore->validateConsistencyLocked(); } while (0) #else #define VALIDATE_CONSISTENCY() #endif #define EGL_EGLEXT_PROTOTYPES #include <gui/BufferItem.h> #include <gui/BufferQueueCore.h> #include <gui/BufferQueueProducer.h> #include <gui/GLConsumer.h> #include <gui/IConsumerListener.h> #include <gui/IGraphicBufferAlloc.h> #include <gui/IProducerListener.h> #include <utils/Log.h> #include <utils/Trace.h> namespace android { BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) : mCore(core), mSlots(core->mSlots), mConsumerName(), mStickyTransform(0), mLastQueueBufferFence(Fence::NO_FENCE), mCallbackMutex(), mNextCallbackTicket(0), mCurrentCallbackTicket(0), mCallbackCondition(), mDequeueTimeout(-1) {} BufferQueueProducer::~BufferQueueProducer() {} status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) { ATRACE_CALL(); BQ_LOGV("requestBuffer: slot %d", slot); Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("requestBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("requestBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) { BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)", slot, BufferQueueDefs::NUM_BUFFER_SLOTS); return BAD_VALUE; } else if (!mSlots[slot].mBufferState.isDequeued()) { BQ_LOGE("requestBuffer: slot %d is not owned by the producer " "(state = %s)", slot, mSlots[slot].mBufferState.string()); return BAD_VALUE; } mSlots[slot].mRequestBufferCalled = true; *buf = mSlots[slot].mGraphicBuffer; return NO_ERROR; } status_t BufferQueueProducer::setMaxDequeuedBufferCount( int maxDequeuedBuffers) { ATRACE_CALL(); BQ_LOGV("setMaxDequeuedBufferCount: maxDequeuedBuffers = %d", maxDequeuedBuffers); sp<IConsumerListener> listener; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mCore->waitWhileAllocatingLocked(); if (mCore->mIsAbandoned) { BQ_LOGE("setMaxDequeuedBufferCount: BufferQueue has been " "abandoned"); return NO_INIT; } if (maxDequeuedBuffers == mCore->mMaxDequeuedBufferCount) { return NO_ERROR; } // The new maxDequeuedBuffer count should not be violated by the number // of currently dequeued buffers int dequeuedCount = 0; for (int s : mCore->mActiveBuffers) { if (mSlots[s].mBufferState.isDequeued()) { dequeuedCount++; } } if (dequeuedCount > maxDequeuedBuffers) { BQ_LOGE("setMaxDequeuedBufferCount: the requested maxDequeuedBuffer" "count (%d) exceeds the current dequeued buffer count (%d)", maxDequeuedBuffers, dequeuedCount); return BAD_VALUE; } int bufferCount = mCore->getMinUndequeuedBufferCountLocked(); bufferCount += maxDequeuedBuffers; if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) { BQ_LOGE("setMaxDequeuedBufferCount: bufferCount %d too large " "(max %d)", bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS); return BAD_VALUE; } const int minBufferSlots = mCore->getMinMaxBufferCountLocked(); if (bufferCount < minBufferSlots) { BQ_LOGE("setMaxDequeuedBufferCount: requested buffer count %d is " "less than minimum %d", bufferCount, minBufferSlots); return BAD_VALUE; } if (bufferCount > mCore->mMaxBufferCount) { BQ_LOGE("setMaxDequeuedBufferCount: %d dequeued buffers would " "exceed the maxBufferCount (%d) (maxAcquired %d async %d " "mDequeuedBufferCannotBlock %d)", maxDequeuedBuffers, mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount, mCore->mAsyncMode, mCore->mDequeueBufferCannotBlock); return BAD_VALUE; } int delta = maxDequeuedBuffers - mCore->mMaxDequeuedBufferCount; if (!mCore->adjustAvailableSlotsLocked(delta)) { return BAD_VALUE; } mCore->mMaxDequeuedBufferCount = maxDequeuedBuffers; VALIDATE_CONSISTENCY(); if (delta < 0) { listener = mCore->mConsumerListener; } mCore->mDequeueCondition.broadcast(); } // Autolock scope // Call back without lock held if (listener != NULL) { listener->onBuffersReleased(); } return NO_ERROR; } status_t BufferQueueProducer::setAsyncMode(bool async) { ATRACE_CALL(); BQ_LOGV("setAsyncMode: async = %d", async); sp<IConsumerListener> listener; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mCore->waitWhileAllocatingLocked(); if (mCore->mIsAbandoned) { BQ_LOGE("setAsyncMode: BufferQueue has been abandoned"); return NO_INIT; } if (async == mCore->mAsyncMode) { return NO_ERROR; } if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount + (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) > mCore->mMaxBufferCount) { BQ_LOGE("setAsyncMode(%d): this call would cause the " "maxBufferCount (%d) to be exceeded (maxAcquired %d " "maxDequeued %d mDequeueBufferCannotBlock %d)", async, mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount, mCore->mMaxDequeuedBufferCount, mCore->mDequeueBufferCannotBlock); return BAD_VALUE; } int delta = mCore->getMaxBufferCountLocked(async, mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked(); if (!mCore->adjustAvailableSlotsLocked(delta)) { BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of " "available slots. Delta = %d", delta); return BAD_VALUE; } mCore->mAsyncMode = async; VALIDATE_CONSISTENCY(); mCore->mDequeueCondition.broadcast(); if (delta < 0) { listener = mCore->mConsumerListener; } } // Autolock scope // Call back without lock held if (listener != NULL) { listener->onBuffersReleased(); } return NO_ERROR; } int BufferQueueProducer::getFreeBufferLocked() const { if (mCore->mFreeBuffers.empty()) { return BufferQueueCore::INVALID_BUFFER_SLOT; } int slot = mCore->mFreeBuffers.front(); mCore->mFreeBuffers.pop_front(); return slot; } int BufferQueueProducer::getFreeSlotLocked() const { if (mCore->mFreeSlots.empty()) { return BufferQueueCore::INVALID_BUFFER_SLOT; } int slot = *(mCore->mFreeSlots.begin()); mCore->mFreeSlots.erase(slot); return slot; } status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller, int* found) const { auto callerString = (caller == FreeSlotCaller::Dequeue) ? "dequeueBuffer" : "attachBuffer"; bool tryAgain = true; while (tryAgain) { if (mCore->mIsAbandoned) { BQ_LOGE("%s: BufferQueue has been abandoned", callerString); return NO_INIT; } int dequeuedCount = 0; int acquiredCount = 0; for (int s : mCore->mActiveBuffers) { if (mSlots[s].mBufferState.isDequeued()) { ++dequeuedCount; } if (mSlots[s].mBufferState.isAcquired()) { ++acquiredCount; } } // Producers are not allowed to dequeue more than // mMaxDequeuedBufferCount buffers. // This check is only done if a buffer has already been queued if (mCore->mBufferHasBeenQueued && dequeuedCount >= mCore->mMaxDequeuedBufferCount) { BQ_LOGE("%s: attempting to exceed the max dequeued buffer count " "(%d)", callerString, mCore->mMaxDequeuedBufferCount); return INVALID_OPERATION; } *found = BufferQueueCore::INVALID_BUFFER_SLOT; // If we disconnect and reconnect quickly, we can be in a state where // our slots are empty but we have many buffers in the queue. This can // cause us to run out of memory if we outrun the consumer. Wait here if // it looks like we have too many buffers queued up. const int maxBufferCount = mCore->getMaxBufferCountLocked(); bool tooManyBuffers = mCore->mQueue.size() > static_cast<size_t>(maxBufferCount); if (tooManyBuffers) { BQ_LOGV("%s: queue size is %zu, waiting", callerString, mCore->mQueue.size()); } else { // If in shared buffer mode and a shared buffer exists, always // return it. if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot != BufferQueueCore::INVALID_BUFFER_SLOT) { *found = mCore->mSharedBufferSlot; } else { if (caller == FreeSlotCaller::Dequeue) { // If we're calling this from dequeue, prefer free buffers int slot = getFreeBufferLocked(); if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) { *found = slot; } else if (mCore->mAllowAllocation) { *found = getFreeSlotLocked(); } } else { // If we're calling this from attach, prefer free slots int slot = getFreeSlotLocked(); if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) { *found = slot; } else { *found = getFreeBufferLocked(); } } } } // If no buffer is found, or if the queue has too many buffers // outstanding, wait for a buffer to be acquired or released, or for the // max buffer count to change. tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) || tooManyBuffers; if (tryAgain) { // Return an error if we're in non-blocking mode (producer and // consumer are controlled by the application). // However, the consumer is allowed to briefly acquire an extra // buffer (which could cause us to have to wait here), which is // okay, since it is only used to implement an atomic acquire + // release (e.g., in GLConsumer::updateTexImage()) if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) && (acquiredCount <= mCore->mMaxAcquiredBufferCount)) { return WOULD_BLOCK; } if (mDequeueTimeout >= 0) { status_t result = mCore->mDequeueCondition.waitRelative( mCore->mMutex, mDequeueTimeout); if (result == TIMED_OUT) { return result; } } else { mCore->mDequeueCondition.wait(mCore->mMutex); } } } // while (tryAgain) return NO_ERROR; } status_t BufferQueueProducer::dequeueBuffer(int *outSlot, sp<android::Fence> *outFence, uint32_t width, uint32_t height, PixelFormat format, uint32_t usage) { ATRACE_CALL(); { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mConsumerName = mCore->mConsumerName; if (mCore->mIsAbandoned) { BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer"); return NO_INIT; } } // Autolock scope BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#x", width, height, format, usage); if ((width && !height) || (!width && height)) { BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height); return BAD_VALUE; } status_t returnFlags = NO_ERROR; EGLDisplay eglDisplay = EGL_NO_DISPLAY; EGLSyncKHR eglFence = EGL_NO_SYNC_KHR; bool attachedByConsumer = false; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mCore->waitWhileAllocatingLocked(); if (format == 0) { format = mCore->mDefaultBufferFormat; } // Enable the usage bits the consumer requested usage |= mCore->mConsumerUsageBits; const bool useDefaultSize = !width && !height; if (useDefaultSize) { width = mCore->mDefaultWidth; height = mCore->mDefaultHeight; } int found = BufferItem::INVALID_BUFFER_SLOT; while (found == BufferItem::INVALID_BUFFER_SLOT) { status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue, &found); if (status != NO_ERROR) { return status; } // This should not happen if (found == BufferQueueCore::INVALID_BUFFER_SLOT) { BQ_LOGE("dequeueBuffer: no available buffer slots"); return -EBUSY; } const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer); // If we are not allowed to allocate new buffers, // waitForFreeSlotThenRelock must have returned a slot containing a // buffer. If this buffer would require reallocation to meet the // requested attributes, we free it and attempt to get another one. if (!mCore->mAllowAllocation) { if (buffer->needsReallocation(width, height, format, usage)) { if (mCore->mSharedBufferSlot == found) { BQ_LOGE("dequeueBuffer: cannot re-allocate a shared" "buffer"); return BAD_VALUE; } mCore->mFreeSlots.insert(found); mCore->clearBufferSlotLocked(found); found = BufferItem::INVALID_BUFFER_SLOT; continue; } } } const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer); if (mCore->mSharedBufferSlot == found && buffer->needsReallocation(width, height, format, usage)) { BQ_LOGE("dequeueBuffer: cannot re-allocate a shared" "buffer"); return BAD_VALUE; } if (mCore->mSharedBufferSlot != found) { mCore->mActiveBuffers.insert(found); } *outSlot = found; ATRACE_BUFFER_INDEX(found); attachedByConsumer = mSlots[found].mNeedsReallocation; mSlots[found].mNeedsReallocation = false; mSlots[found].mBufferState.dequeue(); if ((buffer == NULL) || buffer->needsReallocation(width, height, format, usage)) { mSlots[found].mAcquireCalled = false; mSlots[found].mGraphicBuffer = NULL; mSlots[found].mRequestBufferCalled = false; mSlots[found].mEglDisplay = EGL_NO_DISPLAY; mSlots[found].mEglFence = EGL_NO_SYNC_KHR; mSlots[found].mFence = Fence::NO_FENCE; mCore->mBufferAge = 0; mCore->mIsAllocating = true; returnFlags |= BUFFER_NEEDS_REALLOCATION; } else { // We add 1 because that will be the frame number when this buffer // is queued mCore->mBufferAge = mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber; } BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64, mCore->mBufferAge); if (CC_UNLIKELY(mSlots[found].mFence == NULL)) { BQ_LOGE("dequeueBuffer: about to return a NULL fence - " "slot=%d w=%d h=%d format=%u", found, buffer->width, buffer->height, buffer->format); } eglDisplay = mSlots[found].mEglDisplay; eglFence = mSlots[found].mEglFence; // Don't return a fence in shared buffer mode, except for the first // frame. *outFence = (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == found) ? Fence::NO_FENCE : mSlots[found].mFence; mSlots[found].mEglFence = EGL_NO_SYNC_KHR; mSlots[found].mFence = Fence::NO_FENCE; // If shared buffer mode has just been enabled, cache the slot of the // first buffer that is dequeued and mark it as the shared buffer. if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == BufferQueueCore::INVALID_BUFFER_SLOT) { mCore->mSharedBufferSlot = found; mSlots[found].mBufferState.mShared = true; } } // Autolock scope if (returnFlags & BUFFER_NEEDS_REALLOCATION) { status_t error; BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot); sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer( width, height, format, usage, &error)); { // Autolock scope Mutex::Autolock lock(mCore->mMutex); if (graphicBuffer != NULL && !mCore->mIsAbandoned) { graphicBuffer->setGenerationNumber(mCore->mGenerationNumber); mSlots[*outSlot].mGraphicBuffer = graphicBuffer; } mCore->mIsAllocating = false; mCore->mIsAllocatingCondition.broadcast(); if (graphicBuffer == NULL) { BQ_LOGE("dequeueBuffer: createGraphicBuffer failed"); return error; } if (mCore->mIsAbandoned) { BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned"); return NO_INIT; } VALIDATE_CONSISTENCY(); } // Autolock scope } if (attachedByConsumer) { returnFlags |= BUFFER_NEEDS_REALLOCATION; } if (eglFence != EGL_NO_SYNC_KHR) { EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0, 1000000000); // If something goes wrong, log the error, but return the buffer without // synchronizing access to it. It's too late at this point to abort the // dequeue operation. if (result == EGL_FALSE) { BQ_LOGE("dequeueBuffer: error %#x waiting for fence", eglGetError()); } else if (result == EGL_TIMEOUT_EXPIRED_KHR) { BQ_LOGE("dequeueBuffer: timeout waiting for fence"); } eglDestroySyncKHR(eglDisplay, eglFence); } BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x", *outSlot, mSlots[*outSlot].mFrameNumber, mSlots[*outSlot].mGraphicBuffer->handle, returnFlags); return returnFlags; } status_t BufferQueueProducer::detachBuffer(int slot) { ATRACE_CALL(); ATRACE_BUFFER_INDEX(slot); BQ_LOGV("detachBuffer: slot %d", slot); sp<IConsumerListener> listener; { Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("detachBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("detachBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) { BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode"); return BAD_VALUE; } if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) { BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)", slot, BufferQueueDefs::NUM_BUFFER_SLOTS); return BAD_VALUE; } else if (!mSlots[slot].mBufferState.isDequeued()) { BQ_LOGE("detachBuffer: slot %d is not owned by the producer " "(state = %s)", slot, mSlots[slot].mBufferState.string()); return BAD_VALUE; } else if (!mSlots[slot].mRequestBufferCalled) { BQ_LOGE("detachBuffer: buffer in slot %d has not been requested", slot); return BAD_VALUE; } mSlots[slot].mBufferState.detachProducer(); mCore->mActiveBuffers.erase(slot); mCore->mFreeSlots.insert(slot); mCore->clearBufferSlotLocked(slot); mCore->mDequeueCondition.broadcast(); VALIDATE_CONSISTENCY(); listener = mCore->mConsumerListener; } if (listener != NULL) { listener->onBuffersReleased(); } return NO_ERROR; } status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence) { ATRACE_CALL(); if (outBuffer == NULL) { BQ_LOGE("detachNextBuffer: outBuffer must not be NULL"); return BAD_VALUE; } else if (outFence == NULL) { BQ_LOGE("detachNextBuffer: outFence must not be NULL"); return BAD_VALUE; } Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (mCore->mSharedBufferMode) { BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer " "mode"); return BAD_VALUE; } mCore->waitWhileAllocatingLocked(); if (mCore->mFreeBuffers.empty()) { return NO_MEMORY; } int found = mCore->mFreeBuffers.front(); mCore->mFreeBuffers.remove(found); mCore->mFreeSlots.insert(found); BQ_LOGV("detachNextBuffer detached slot %d", found); *outBuffer = mSlots[found].mGraphicBuffer; *outFence = mSlots[found].mFence; mCore->clearBufferSlotLocked(found); VALIDATE_CONSISTENCY(); return NO_ERROR; } status_t BufferQueueProducer::attachBuffer(int* outSlot, const sp<android::GraphicBuffer>& buffer) { ATRACE_CALL(); if (outSlot == NULL) { BQ_LOGE("attachBuffer: outSlot must not be NULL"); return BAD_VALUE; } else if (buffer == NULL) { BQ_LOGE("attachBuffer: cannot attach NULL buffer"); return BAD_VALUE; } Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("attachBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("attachBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (mCore->mSharedBufferMode) { BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode"); return BAD_VALUE; } if (buffer->getGenerationNumber() != mCore->mGenerationNumber) { BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] " "[queue %u]", buffer->getGenerationNumber(), mCore->mGenerationNumber); return BAD_VALUE; } mCore->waitWhileAllocatingLocked(); status_t returnFlags = NO_ERROR; int found; status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, &found); if (status != NO_ERROR) { return status; } // This should not happen if (found == BufferQueueCore::INVALID_BUFFER_SLOT) { BQ_LOGE("attachBuffer: no available buffer slots"); return -EBUSY; } *outSlot = found; ATRACE_BUFFER_INDEX(*outSlot); BQ_LOGV("attachBuffer: returning slot %d flags=%#x", *outSlot, returnFlags); mSlots[*outSlot].mGraphicBuffer = buffer; mSlots[*outSlot].mBufferState.attachProducer(); mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR; mSlots[*outSlot].mFence = Fence::NO_FENCE; mSlots[*outSlot].mRequestBufferCalled = true; mSlots[*outSlot].mAcquireCalled = false; mCore->mActiveBuffers.insert(found); VALIDATE_CONSISTENCY(); return returnFlags; } status_t BufferQueueProducer::queueBuffer(int slot, const QueueBufferInput &input, QueueBufferOutput *output) { ATRACE_CALL(); ATRACE_BUFFER_INDEX(slot); int64_t timestamp; bool isAutoTimestamp; android_dataspace dataSpace; Rect crop(Rect::EMPTY_RECT); int scalingMode; uint32_t transform; uint32_t stickyTransform; sp<Fence> fence; input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode, &transform, &fence, &stickyTransform); Region surfaceDamage = input.getSurfaceDamage(); if (fence == NULL) { BQ_LOGE("queueBuffer: fence is NULL"); return BAD_VALUE; } switch (scalingMode) { case NATIVE_WINDOW_SCALING_MODE_FREEZE: case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP: break; default: BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode); return BAD_VALUE; } sp<IConsumerListener> frameAvailableListener; sp<IConsumerListener> frameReplacedListener; int callbackTicket = 0; BufferItem item; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("queueBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("queueBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) { BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)", slot, BufferQueueDefs::NUM_BUFFER_SLOTS); return BAD_VALUE; } else if (!mSlots[slot].mBufferState.isDequeued()) { BQ_LOGE("queueBuffer: slot %d is not owned by the producer " "(state = %s)", slot, mSlots[slot].mBufferState.string()); return BAD_VALUE; } else if (!mSlots[slot].mRequestBufferCalled) { BQ_LOGE("queueBuffer: slot %d was queued without requesting " "a buffer", slot); return BAD_VALUE; } // If shared buffer mode has just been enabled, cache the slot of the // first buffer that is queued and mark it as the shared buffer. if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == BufferQueueCore::INVALID_BUFFER_SLOT) { mCore->mSharedBufferSlot = slot; mSlots[slot].mBufferState.mShared = true; } BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d" " crop=[%d,%d,%d,%d] transform=%#x scale=%s", slot, mCore->mFrameCounter + 1, timestamp, dataSpace, crop.left, crop.top, crop.right, crop.bottom, transform, BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode))); const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer); Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight()); Rect croppedRect(Rect::EMPTY_RECT); crop.intersect(bufferRect, &croppedRect); if (croppedRect != crop) { BQ_LOGE("queueBuffer: crop rect is not contained within the " "buffer in slot %d", slot); return BAD_VALUE; } // Override UNKNOWN dataspace with consumer default if (dataSpace == HAL_DATASPACE_UNKNOWN) { dataSpace = mCore->mDefaultBufferDataSpace; } mSlots[slot].mFence = fence; mSlots[slot].mBufferState.queue(); ++mCore->mFrameCounter; mSlots[slot].mFrameNumber = mCore->mFrameCounter; item.mAcquireCalled = mSlots[slot].mAcquireCalled; item.mGraphicBuffer = mSlots[slot].mGraphicBuffer; item.mCrop = crop; item.mTransform = transform & ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY); item.mTransformToDisplayInverse = (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0; item.mScalingMode = static_cast<uint32_t>(scalingMode); item.mTimestamp = timestamp; item.mIsAutoTimestamp = isAutoTimestamp; item.mDataSpace = dataSpace; item.mFrameNumber = mCore->mFrameCounter; item.mSlot = slot; item.mFence = fence; item.mIsDroppable = mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock || (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot); item.mSurfaceDamage = surfaceDamage; item.mQueuedBuffer = true; item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh; mStickyTransform = stickyTransform; // Cache the shared buffer data so that the BufferItem can be recreated. if (mCore->mSharedBufferMode) { mCore->mSharedBufferCache.crop = crop; mCore->mSharedBufferCache.transform = transform; mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>( scalingMode); mCore->mSharedBufferCache.dataspace = dataSpace; } if (mCore->mQueue.empty()) { // When the queue is empty, we can ignore mDequeueBufferCannotBlock // and simply queue this buffer mCore->mQueue.push_back(item); frameAvailableListener = mCore->mConsumerListener; } else { // When the queue is not empty, we need to look at the last buffer // in the queue to see if we need to replace it const BufferItem& last = mCore->mQueue.itemAt( mCore->mQueue.size() - 1); if (last.mIsDroppable) { if (!last.mIsStale) { mSlots[last.mSlot].mBufferState.freeQueued(); // After leaving shared buffer mode, the shared buffer will // still be around. Mark it as no longer shared if this // operation causes it to be free. if (!mCore->mSharedBufferMode && mSlots[last.mSlot].mBufferState.isFree()) { mSlots[last.mSlot].mBufferState.mShared = false; } // Don't put the shared buffer on the free list. if (!mSlots[last.mSlot].mBufferState.isShared()) { mCore->mActiveBuffers.erase(last.mSlot); mCore->mFreeBuffers.push_back(last.mSlot); } } // Overwrite the droppable buffer with the incoming one mCore->mQueue.editItemAt(mCore->mQueue.size() - 1) = item; frameReplacedListener = mCore->mConsumerListener; } else { mCore->mQueue.push_back(item); frameAvailableListener = mCore->mConsumerListener; } } mCore->mBufferHasBeenQueued = true; mCore->mDequeueCondition.broadcast(); mCore->mLastQueuedSlot = slot; output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight, mCore->mTransformHint, static_cast<uint32_t>(mCore->mQueue.size())); ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size()); // Take a ticket for the callback functions callbackTicket = mNextCallbackTicket++; VALIDATE_CONSISTENCY(); } // Autolock scope // Don't send the GraphicBuffer through the callback, and don't send // the slot number, since the consumer shouldn't need it item.mGraphicBuffer.clear(); item.mSlot = BufferItem::INVALID_BUFFER_SLOT; // Call back without the main BufferQueue lock held, but with the callback // lock held so we can ensure that callbacks occur in order { Mutex::Autolock lock(mCallbackMutex); while (callbackTicket != mCurrentCallbackTicket) { mCallbackCondition.wait(mCallbackMutex); } if (frameAvailableListener != NULL) { frameAvailableListener->onFrameAvailable(item); } else if (frameReplacedListener != NULL) { frameReplacedListener->onFrameReplaced(item); } ++mCurrentCallbackTicket; mCallbackCondition.broadcast(); } // Wait without lock held if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) { // Waiting here allows for two full buffers to be queued but not a // third. In the event that frames take varying time, this makes a // small trade-off in favor of latency rather than throughput. mLastQueueBufferFence->waitForever("Throttling EGL Production"); } mLastQueueBufferFence = fence; mLastQueuedCrop = item.mCrop; mLastQueuedTransform = item.mTransform; return NO_ERROR; } status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) { ATRACE_CALL(); BQ_LOGV("cancelBuffer: slot %d", slot); Mutex::Autolock lock(mCore->mMutex); if (mCore->mIsAbandoned) { BQ_LOGE("cancelBuffer: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("cancelBuffer: BufferQueue has no connected producer"); return NO_INIT; } if (mCore->mSharedBufferMode) { BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode"); return BAD_VALUE; } if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) { BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)", slot, BufferQueueDefs::NUM_BUFFER_SLOTS); return BAD_VALUE; } else if (!mSlots[slot].mBufferState.isDequeued()) { BQ_LOGE("cancelBuffer: slot %d is not owned by the producer " "(state = %s)", slot, mSlots[slot].mBufferState.string()); return BAD_VALUE; } else if (fence == NULL) { BQ_LOGE("cancelBuffer: fence is NULL"); return BAD_VALUE; } mSlots[slot].mBufferState.cancel(); // After leaving shared buffer mode, the shared buffer will still be around. // Mark it as no longer shared if this operation causes it to be free. if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) { mSlots[slot].mBufferState.mShared = false; } // Don't put the shared buffer on the free list. if (!mSlots[slot].mBufferState.isShared()) { mCore->mActiveBuffers.erase(slot); mCore->mFreeBuffers.push_back(slot); } mSlots[slot].mFence = fence; mCore->mDequeueCondition.broadcast(); VALIDATE_CONSISTENCY(); return NO_ERROR; } int BufferQueueProducer::query(int what, int *outValue) { ATRACE_CALL(); Mutex::Autolock lock(mCore->mMutex); if (outValue == NULL) { BQ_LOGE("query: outValue was NULL"); return BAD_VALUE; } if (mCore->mIsAbandoned) { BQ_LOGE("query: BufferQueue has been abandoned"); return NO_INIT; } int value; switch (what) { case NATIVE_WINDOW_WIDTH: value = static_cast<int32_t>(mCore->mDefaultWidth); break; case NATIVE_WINDOW_HEIGHT: value = static_cast<int32_t>(mCore->mDefaultHeight); break; case NATIVE_WINDOW_FORMAT: value = static_cast<int32_t>(mCore->mDefaultBufferFormat); break; case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS: value = mCore->getMinUndequeuedBufferCountLocked(); break; case NATIVE_WINDOW_STICKY_TRANSFORM: value = static_cast<int32_t>(mStickyTransform); break; case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: value = (mCore->mQueue.size() > 1); break; case NATIVE_WINDOW_CONSUMER_USAGE_BITS: value = static_cast<int32_t>(mCore->mConsumerUsageBits); break; case NATIVE_WINDOW_DEFAULT_DATASPACE: value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace); break; case NATIVE_WINDOW_BUFFER_AGE: if (mCore->mBufferAge > INT32_MAX) { value = 0; } else { value = static_cast<int32_t>(mCore->mBufferAge); } break; default: return BAD_VALUE; } BQ_LOGV("query: %d? %d", what, value); *outValue = value; return NO_ERROR; } status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp, QueueBufferOutput *output) { ATRACE_CALL(); Mutex::Autolock lock(mCore->mMutex); mConsumerName = mCore->mConsumerName; BQ_LOGV("connect: api=%d producerControlledByApp=%s", api, producerControlledByApp ? "true" : "false"); if (mCore->mIsAbandoned) { BQ_LOGE("connect: BufferQueue has been abandoned"); return NO_INIT; } if (mCore->mConsumerListener == NULL) { BQ_LOGE("connect: BufferQueue has no consumer"); return NO_INIT; } if (output == NULL) { BQ_LOGE("connect: output was NULL"); return BAD_VALUE; } if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("connect: already connected (cur=%d req=%d)", mCore->mConnectedApi, api); return BAD_VALUE; } int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, mDequeueTimeout < 0 ? mCore->mConsumerControlledByApp && producerControlledByApp : false, mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked(); if (!mCore->adjustAvailableSlotsLocked(delta)) { BQ_LOGE("connect: BufferQueue failed to adjust the number of available " "slots. Delta = %d", delta); return BAD_VALUE; } int status = NO_ERROR; switch (api) { case NATIVE_WINDOW_API_EGL: case NATIVE_WINDOW_API_CPU: case NATIVE_WINDOW_API_MEDIA: case NATIVE_WINDOW_API_CAMERA: mCore->mConnectedApi = api; output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight, mCore->mTransformHint, static_cast<uint32_t>(mCore->mQueue.size())); // Set up a death notification so that we can disconnect // automatically if the remote producer dies if (listener != NULL && IInterface::asBinder(listener)->remoteBinder() != NULL) { status = IInterface::asBinder(listener)->linkToDeath( static_cast<IBinder::DeathRecipient*>(this)); if (status != NO_ERROR) { BQ_LOGE("connect: linkToDeath failed: %s (%d)", strerror(-status), status); } } mCore->mConnectedProducerListener = listener; break; default: BQ_LOGE("connect: unknown API %d", api); status = BAD_VALUE; break; } mCore->mBufferHasBeenQueued = false; mCore->mDequeueBufferCannotBlock = false; if (mDequeueTimeout < 0) { mCore->mDequeueBufferCannotBlock = mCore->mConsumerControlledByApp && producerControlledByApp; } mCore->mAllowAllocation = true; VALIDATE_CONSISTENCY(); return status; } status_t BufferQueueProducer::disconnect(int api) { ATRACE_CALL(); BQ_LOGV("disconnect: api %d", api); int status = NO_ERROR; sp<IConsumerListener> listener; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mCore->waitWhileAllocatingLocked(); if (mCore->mIsAbandoned) { // It's not really an error to disconnect after the surface has // been abandoned; it should just be a no-op. return NO_ERROR; } if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) { api = mCore->mConnectedApi; // If we're asked to disconnect the currently connected api but // nobody is connected, it's not really an error. if (api == BufferQueueCore::NO_CONNECTED_API) { return NO_ERROR; } } switch (api) { case NATIVE_WINDOW_API_EGL: case NATIVE_WINDOW_API_CPU: case NATIVE_WINDOW_API_MEDIA: case NATIVE_WINDOW_API_CAMERA: if (mCore->mConnectedApi == api) { mCore->freeAllBuffersLocked(); // Remove our death notification callback if we have one if (mCore->mConnectedProducerListener != NULL) { sp<IBinder> token = IInterface::asBinder(mCore->mConnectedProducerListener); // This can fail if we're here because of the death // notification, but we just ignore it token->unlinkToDeath( static_cast<IBinder::DeathRecipient*>(this)); } mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT; mCore->mConnectedProducerListener = NULL; mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API; mCore->mSidebandStream.clear(); mCore->mDequeueCondition.broadcast(); listener = mCore->mConsumerListener; } else if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) { BQ_LOGE("disconnect: still connected to another API " "(cur=%d req=%d)", mCore->mConnectedApi, api); status = BAD_VALUE; } break; default: BQ_LOGE("disconnect: unknown API %d", api); status = BAD_VALUE; break; } } // Autolock scope // Call back without lock held if (listener != NULL) { listener->onBuffersReleased(); } return status; } status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) { sp<IConsumerListener> listener; { // Autolock scope Mutex::Autolock _l(mCore->mMutex); mCore->mSidebandStream = stream; listener = mCore->mConsumerListener; } // Autolock scope if (listener != NULL) { listener->onSidebandStreamChanged(); } return NO_ERROR; } void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height, PixelFormat format, uint32_t usage) { ATRACE_CALL(); while (true) { size_t newBufferCount = 0; uint32_t allocWidth = 0; uint32_t allocHeight = 0; PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN; uint32_t allocUsage = 0; { // Autolock scope Mutex::Autolock lock(mCore->mMutex); mCore->waitWhileAllocatingLocked(); if (!mCore->mAllowAllocation) { BQ_LOGE("allocateBuffers: allocation is not allowed for this " "BufferQueue"); return; } newBufferCount = mCore->mFreeSlots.size(); if (newBufferCount == 0) { return; } allocWidth = width > 0 ? width : mCore->mDefaultWidth; allocHeight = height > 0 ? height : mCore->mDefaultHeight; allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat; allocUsage = usage | mCore->mConsumerUsageBits; mCore->mIsAllocating = true; } // Autolock scope Vector<sp<GraphicBuffer>> buffers; for (size_t i = 0; i < newBufferCount; ++i) { status_t result = NO_ERROR; sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer( allocWidth, allocHeight, allocFormat, allocUsage, &result)); if (result != NO_ERROR) { BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format" " %u, usage %u)", width, height, format, usage); Mutex::Autolock lock(mCore->mMutex); mCore->mIsAllocating = false; mCore->mIsAllocatingCondition.broadcast(); return; } buffers.push_back(graphicBuffer); } { // Autolock scope Mutex::Autolock lock(mCore->mMutex); uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth; uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight; PixelFormat checkFormat = format != 0 ? format : mCore->mDefaultBufferFormat; uint32_t checkUsage = usage | mCore->mConsumerUsageBits; if (checkWidth != allocWidth || checkHeight != allocHeight || checkFormat != allocFormat || checkUsage != allocUsage) { // Something changed while we released the lock. Retry. BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying."); mCore->mIsAllocating = false; mCore->mIsAllocatingCondition.broadcast(); continue; } for (size_t i = 0; i < newBufferCount; ++i) { if (mCore->mFreeSlots.empty()) { BQ_LOGV("allocateBuffers: a slot was occupied while " "allocating. Dropping allocated buffer."); continue; } auto slot = mCore->mFreeSlots.begin(); mCore->clearBufferSlotLocked(*slot); // Clean up the slot first mSlots[*slot].mGraphicBuffer = buffers[i]; mSlots[*slot].mFence = Fence::NO_FENCE; // freeBufferLocked puts this slot on the free slots list. Since // we then attached a buffer, move the slot to free buffer list. mCore->mFreeBuffers.push_front(*slot); BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d", *slot); // Make sure the erase is done after all uses of the slot // iterator since it will be invalid after this point. mCore->mFreeSlots.erase(slot); } mCore->mIsAllocating = false; mCore->mIsAllocatingCondition.broadcast(); VALIDATE_CONSISTENCY(); } // Autolock scope } } status_t BufferQueueProducer::allowAllocation(bool allow) { ATRACE_CALL(); BQ_LOGV("allowAllocation: %s", allow ? "true" : "false"); Mutex::Autolock lock(mCore->mMutex); mCore->mAllowAllocation = allow; return NO_ERROR; } status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) { ATRACE_CALL(); BQ_LOGV("setGenerationNumber: %u", generationNumber); Mutex::Autolock lock(mCore->mMutex); mCore->mGenerationNumber = generationNumber; return NO_ERROR; } String8 BufferQueueProducer::getConsumerName() const { ATRACE_CALL(); BQ_LOGV("getConsumerName: %s", mConsumerName.string()); return mConsumerName; } uint64_t BufferQueueProducer::getNextFrameNumber() const { ATRACE_CALL(); Mutex::Autolock lock(mCore->mMutex); uint64_t nextFrameNumber = mCore->mFrameCounter + 1; return nextFrameNumber; } status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) { ATRACE_CALL(); BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode); Mutex::Autolock lock(mCore->mMutex); if (!sharedBufferMode) { mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT; } mCore->mSharedBufferMode = sharedBufferMode; return NO_ERROR; } status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) { ATRACE_CALL(); BQ_LOGV("setAutoRefresh: %d", autoRefresh); Mutex::Autolock lock(mCore->mMutex); mCore->mAutoRefresh = autoRefresh; return NO_ERROR; } status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) { ATRACE_CALL(); BQ_LOGV("setDequeueTimeout: %" PRId64, timeout); Mutex::Autolock lock(mCore->mMutex); int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, false, mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked(); if (!mCore->adjustAvailableSlotsLocked(delta)) { BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of " "available slots. Delta = %d", delta); return BAD_VALUE; } mDequeueTimeout = timeout; mCore->mDequeueBufferCannotBlock = false; VALIDATE_CONSISTENCY(); return NO_ERROR; } status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence, float outTransformMatrix[16]) { ATRACE_CALL(); BQ_LOGV("getLastQueuedBuffer"); Mutex::Autolock lock(mCore->mMutex); if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT) { *outBuffer = nullptr; *outFence = Fence::NO_FENCE; return NO_ERROR; } *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer; *outFence = mLastQueueBufferFence; // Currently only SurfaceFlinger internally ever changes // GLConsumer's filtering mode, so we just use 'true' here as // this is slightly specialized for the current client of this API, // which does want filtering. GLConsumer::computeTransformMatrix(outTransformMatrix, mSlots[mCore->mLastQueuedSlot].mGraphicBuffer, mLastQueuedCrop, mLastQueuedTransform, true /* filter */); return NO_ERROR; } void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) { // If we're here, it means that a producer we were connected to died. // We're guaranteed that we are still connected to it because we remove // this callback upon disconnect. It's therefore safe to read mConnectedApi // without synchronization here. int api = mCore->mConnectedApi; disconnect(api); } status_t BufferQueueProducer::getUniqueId(uint64_t* outId) const { BQ_LOGV("getUniqueId"); *outId = mCore->mUniqueId; return NO_ERROR; } } // namespace android
36.374738
98
0.604393
[ "vector", "transform" ]
054b3199e735a9590251eba87de245263d89059a
1,906
cpp
C++
core/util/SamplesGenerator.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
core/util/SamplesGenerator.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
core/util/SamplesGenerator.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
/** * Copyright(C) 2009-2012 * @author Jing HUANG * @file SamplesGenerator.cpp * @brief * @date 1/2/2011 */ #include "SamplesGenerator.h" #include <fstream> /** * @brief For tracking memory leaks under windows using the crtdbg */ #if ( defined( _DEBUG ) || defined( DEBUG ) ) && defined( _MSC_VER ) #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif namespace Etoile { SamplesGenerator::SamplesGenerator(const std::string& name): _name(name) { } SamplesGenerator::~SamplesGenerator() { } void SamplesGenerator::dumpPGM (const std::string & filename, unsigned int xSize, unsigned int ySize, unsigned int patternSize, unsigned int res ) { unsigned int width = res * patternSize; unsigned int size = width * width; std::vector<int> raster; raster.resize(size); ofstream out (filename.c_str ()); out << "P2" << std::endl << width << " " << width << std::endl << 255 << std::endl; for (unsigned int i = 0; i < width; i++){ for(unsigned int j = 0; j < width; j++){ if( (j) % res == 0 || i % res ==0 || i == width -1 || j == width - 1) raster[i * width +j] = 150; else raster[i * width +j] = 255; } } for(unsigned int l = 0; l < patternSize; ++l ) { for(unsigned int k = 0; k < patternSize; ++k ) { for(unsigned int j = 0; j < ySize; ++j) { for(unsigned int i = 0; i < xSize; ++i) { unsigned int index = l * patternSize * ySize * xSize + k * ySize * xSize + j * xSize + i; const Vec4d & s = samples[index]; unsigned int x = unsigned int(k * res + (s.x()/2.0+0.5) * res); unsigned int y = unsigned int(l * res + (s.y()/2.0+0.5) * res); int vidx = y*width+x; raster[vidx] = 0; } } } } for (unsigned int i = 0; i < size; i++) out << raster[i] << endl; out.close (); } }
25.413333
147
0.586569
[ "vector" ]
054da6d903c11e35adad5dd7e477fad37f27426c
12,522
cpp
C++
Editor/Editor.cpp
dayfox5317/SpartanEngine
b7d1efd676e464ea26f1b112cbcc3a73782d4b1b
[ "MIT" ]
null
null
null
Editor/Editor.cpp
dayfox5317/SpartanEngine
b7d1efd676e464ea26f1b112cbcc3a73782d4b1b
[ "MIT" ]
null
null
null
Editor/Editor.cpp
dayfox5317/SpartanEngine
b7d1efd676e464ea26f1b112cbcc3a73782d4b1b
[ "MIT" ]
1
2020-11-07T16:33:00.000Z
2020-11-07T16:33:00.000Z
/* Copyright(c) 2016-2019 Panos Karabelas 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. */ //= INCLUDES ===================================== #include "Editor.h" #include "Core/Engine.h" #include "Rendering/Model.h" #include "ImGui_Extension.h" #include "ImGui/Implementation/ImGui_RHI.h" #include "ImGui/Implementation/imgui_impl_win32.h" #include "Widgets/Widget_Assets.h" #include "Widgets/Widget_Console.h" #include "Widgets/Widget_MenuBar.h" #include "Widgets/Widget_ProgressDialog.h" #include "Widgets/Widget_Properties.h" #include "Widgets/Widget_Toolbar.h" #include "Widgets/Widget_Viewport.h" #include "Widgets/Widget_World.h" //================================================ //= NAMESPACES ========== using namespace std; using namespace Spartan; //======================= #define DOCKING_ENABLED ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable namespace _Editor { Widget* widget_menu_bar = nullptr; Widget* widget_toolbar = nullptr; Widget* widget_world = nullptr; const char* dockspace_name = "EditorDockspace"; } Editor::~Editor() { if (!m_initialized) return; m_widgets.clear(); m_widgets.shrink_to_fit(); // ImGui implementation - shutdown ImGui::RHI::Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); } void Editor::OnWindowMessage(WindowData& window_data) { if (!m_initialized) { // Create engine m_engine = make_unique<Engine>(window_data); // Acquire useful engine subsystems m_context = m_engine->GetContext(); m_renderer = m_context->GetSubsystem<Renderer>().get(); m_rhi_device = m_renderer->GetRhiDevice(); if (!m_renderer->IsInitialized()) { LOG_ERROR("The engine failed to initialize the renderer subsystem, aborting editor creation."); return; } // ImGui version validation IMGUI_CHECKVERSION(); m_context->GetSubsystem<Settings>()->m_versionImGui = IMGUI_VERSION; // ImGui context creation ImGui::CreateContext(); // ImGui configuration auto& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; io.ConfigWindowsResizeFromEdges = true; io.ConfigViewportsNoTaskBarIcon = true; ApplyStyle(); // ImGui backend setup ImGui_ImplWin32_Init(window_data.handle); ImGui::RHI::Initialize(m_context, static_cast<float>(window_data.width), static_cast<float>(window_data.height)); // Initialization of misc custom systems IconProvider::Get().Initialize(m_context); EditorHelper::Get().Initialize(m_context); // Create all ImGui widgets Widgets_Create(); m_initialized = true; } else { ImGui_ImplWin32_WndProcHandler( static_cast<HWND>(window_data.handle), static_cast<uint32_t>(window_data.message), static_cast<int64_t>(window_data.wparam), static_cast<uint64_t>(window_data.lparam) ); if (m_engine->GetWindowData().width != window_data.width || m_engine->GetWindowData().height != window_data.height) { ImGui::RHI::OnResize(window_data.width, window_data.height); } m_engine->SetWindowData(window_data); } } void Editor::OnTick() { if (!m_initialized) return; // Update engine (will simulate and render) m_engine->Tick(); // ImGui implementation - start frame ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); // Editor update Widgets_Tick(); // ImGui implementation - end frame ImGui::Render(); ImGui::RHI::RenderDrawData(ImGui::GetDrawData()); // Update and Render additional Platform Windows if (DOCKING_ENABLED) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } } void Editor::Widgets_Create() { m_widgets.emplace_back(make_unique<Widget_Console>(m_context)); m_widgets.emplace_back(make_unique<Widget_MenuBar>(m_context)); _Editor::widget_menu_bar = m_widgets.back().get(); m_widgets.emplace_back(make_unique<Widget_Toolbar>(m_context)); _Editor::widget_toolbar = m_widgets.back().get(); m_widgets.emplace_back(make_unique<Widget_Viewport>(m_context)); m_widgets.emplace_back(make_unique<Widget_Assets>(m_context)); m_widgets.emplace_back(make_unique<Widget_Properties>(m_context)); m_widgets.emplace_back(make_unique<Widget_World>(m_context)); _Editor::widget_world = m_widgets.back().get(); m_widgets.emplace_back(make_unique<Widget_ProgressDialog>(m_context)); } void Editor::Widgets_Tick() { if (DOCKING_ENABLED) { DockSpace_Begin(); } for (auto& widget : m_widgets) { widget->Begin(); widget->Tick(); widget->End(); } if (DOCKING_ENABLED) { DockSpace_End(); } } void Editor::DockSpace_Begin() { auto open = true; // Flags const auto window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; // Size, Pos float offset_y = 0; offset_y += _Editor::widget_menu_bar ? _Editor::widget_menu_bar->GetHeight() : 0; offset_y += _Editor::widget_toolbar ? _Editor::widget_toolbar->GetHeight() : 0; const auto viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + offset_y)); ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, viewport->Size.y - offset_y)); ImGui::SetNextWindowViewport(viewport->ID); // Style ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::SetNextWindowBgAlpha(0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin(_Editor::dockspace_name, &open, window_flags); ImGui::PopStyleVar(); ImGui::PopStyleVar(2); // Dock space const auto dockspace_id = ImGui::GetID(_Editor::dockspace_name); if (!ImGui::DockBuilderGetNode(dockspace_id)) { // Reset/clear current docking state ImGui::DockBuilderRemoveNode(dockspace_id); ImGui::DockBuilderAddNode(dockspace_id, ImGuiDockNodeFlags_None); // DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_dir, ImGuiID* out_id_other); auto dock_main_id = dockspace_id; auto dock_right_id = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.2f, nullptr, &dock_main_id); const auto dock_right_down_id = ImGui::DockBuilderSplitNode(dock_right_id, ImGuiDir_Down, 0.6f, nullptr, &dock_right_id); auto dock_down_id = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.2f, nullptr, &dock_main_id); const auto dock_down_right_id = ImGui::DockBuilderSplitNode(dock_down_id, ImGuiDir_Right, 0.6f, nullptr, &dock_down_id); // Dock windows ImGui::DockBuilderDockWindow("World", dock_right_id); ImGui::DockBuilderDockWindow("Properties", dock_right_down_id); ImGui::DockBuilderDockWindow("Console", dock_down_id); ImGui::DockBuilderDockWindow("Assets", dock_down_right_id); ImGui::DockBuilderDockWindow("Viewport", dock_main_id); ImGui::DockBuilderFinish(dock_main_id); } ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_PassthruCentralNode); } void Editor::DockSpace_End() { ImGui::End(); } void Editor::ApplyStyle() const { // Color settings const auto text = ImVec4(0.76f, 0.77f, 0.8f, 1.0f); const auto white = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); const auto black = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); const auto background_very_dark = ImVec4(0.08f, 0.086f, 0.094f, 1.00f); const auto background_dark = ImVec4(0.117f, 0.121f, 0.145f, 1.00f); const auto background_medium = ImVec4(0.26f, 0.26f, 0.27f, 1.0f); const auto background_light = ImVec4(0.37f, 0.38f, 0.39f, 1.0f); const auto highlight_blue = ImVec4(0.172f, 0.239f, 0.341f, 1.0f); const auto highlight_blue_hovered = ImVec4(0.29f, 0.42f, 0.65f, 1.0f); const auto highlight_blue_active = ImVec4(0.382f, 0.449f, 0.561f, 1.0f); const auto bar_background = ImVec4(0.078f, 0.082f, 0.09f, 1.0f); const auto bar = ImVec4(0.164f, 0.180f, 0.231f, 1.0f); const auto bar_hovered = ImVec4(0.411f, 0.411f, 0.411f, 1.0f); const auto bar_active = ImVec4(0.337f, 0.337f, 0.368f, 1.0f); // Spatial settings const auto font_size = 24.0f; const auto font_scale = 0.7f; const auto roundness = 2.0f; // Use default black style as a base ImGui::StyleColorsDark(); ImGuiStyle& style = ImGui::GetStyle(); auto& io = ImGui::GetIO(); // Spatial style.WindowBorderSize = 1.0f; style.FrameBorderSize = 0.0f; style.ScrollbarSize = 20.0f; style.FramePadding = ImVec2(5, 5); style.ItemSpacing = ImVec2(6, 5); style.WindowMenuButtonPosition = ImGuiDir_Right; style.WindowRounding = roundness; style.FrameRounding = roundness; style.PopupRounding = roundness; style.GrabRounding = roundness; style.ScrollbarRounding = roundness; style.Alpha = 1.0f; // Colors style.Colors[ImGuiCol_Text] = text; style.Colors[ImGuiCol_WindowBg] = background_dark; style.Colors[ImGuiCol_Border] = black; style.Colors[ImGuiCol_FrameBg] = bar; style.Colors[ImGuiCol_FrameBgHovered] = highlight_blue; style.Colors[ImGuiCol_FrameBgActive] = highlight_blue_hovered; style.Colors[ImGuiCol_TitleBg] = background_very_dark; style.Colors[ImGuiCol_TitleBgActive] = bar; style.Colors[ImGuiCol_MenuBarBg] = background_very_dark; style.Colors[ImGuiCol_ScrollbarBg] = bar_background; style.Colors[ImGuiCol_ScrollbarGrab] = bar; style.Colors[ImGuiCol_ScrollbarGrabHovered] = bar_hovered; style.Colors[ImGuiCol_ScrollbarGrabActive] = bar_active; style.Colors[ImGuiCol_CheckMark] = highlight_blue_hovered; style.Colors[ImGuiCol_SliderGrab] = highlight_blue_hovered; style.Colors[ImGuiCol_SliderGrabActive] = highlight_blue_active; style.Colors[ImGuiCol_Button] = bar_active; style.Colors[ImGuiCol_ButtonHovered] = highlight_blue; style.Colors[ImGuiCol_ButtonActive] = highlight_blue_active; style.Colors[ImGuiCol_Header] = highlight_blue; // selected items (tree, menu bar etc.) style.Colors[ImGuiCol_HeaderHovered] = highlight_blue_hovered; // hovered items (tree, menu bar etc.) style.Colors[ImGuiCol_HeaderActive] = highlight_blue_active; style.Colors[ImGuiCol_Separator] = background_light; style.Colors[ImGuiCol_ResizeGrip] = background_medium; style.Colors[ImGuiCol_ResizeGripHovered] = highlight_blue; style.Colors[ImGuiCol_ResizeGripActive] = highlight_blue_hovered; style.Colors[ImGuiCol_PlotLines] = ImVec4(0.0f, 0.7f, 0.77f, 1.0f); style.Colors[ImGuiCol_PlotHistogram] = highlight_blue; // Also used for progress bar style.Colors[ImGuiCol_PlotHistogramHovered] = highlight_blue_hovered; style.Colors[ImGuiCol_TextSelectedBg] = highlight_blue; style.Colors[ImGuiCol_PopupBg] = background_dark; style.Colors[ImGuiCol_DragDropTarget] = background_light; // Font string dir_fonts = m_context->GetSubsystem<ResourceCache>()->GetDataDirectory(Asset_Fonts); io.Fonts->AddFontFromFileTTF((dir_fonts + "CalibriBold.ttf").c_str(), font_size); io.FontGlobalScale = font_scale; }
37.716867
141
0.721291
[ "render", "model" ]
0550388342c00e678d52f9c862ac3e05d843e32e
15,440
cxx
C++
Remoting/ServerManager/vtkSMCollaborationManager.cxx
qiangwushuang/ParaView
f35ed90a6582e9d21924b66a905498f6a38ab4a3
[ "Apache-2.0", "BSD-3-Clause" ]
815
2015-01-03T02:14:04.000Z
2022-03-26T07:48:07.000Z
Remoting/ServerManager/vtkSMCollaborationManager.cxx
qiangwushuang/ParaView
f35ed90a6582e9d21924b66a905498f6a38ab4a3
[ "Apache-2.0", "BSD-3-Clause" ]
9
2015-04-28T20:10:37.000Z
2021-08-20T18:19:01.000Z
Remoting/ServerManager/vtkSMCollaborationManager.cxx
qiangwushuang/ParaView
f35ed90a6582e9d21924b66a905498f6a38ab4a3
[ "Apache-2.0", "BSD-3-Clause" ]
328
2015-01-22T23:11:46.000Z
2022-03-14T06:07:52.000Z
/*========================================================================= Program: ParaView Module: vtkSMCollaborationManager.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSMCollaborationManager.h" #include "vtkObjectFactory.h" #include "vtkPVMultiClientsInformation.h" #include "vtkPVServerInformation.h" #include "vtkProcessModule.h" #include "vtkReservedRemoteObjectIds.h" #include "vtkSMMessage.h" #include "vtkSMSession.h" #include "vtkSMSessionClient.h" #include "vtkSMProxy.h" #include "vtkSMProxyLocator.h" #include <map> #include <string> #include <vector> //**************************************************************************** // Internal class //**************************************************************************** class vtkSMCollaborationManager::vtkInternal { public: vtkInternal(vtkSMCollaborationManager* m) { this->Manager = m; this->ObserverTag = 0; this->Me = 0; this->UserToFollow = 0; this->DisableFurtherConnections = false; this->ConnectID = 0; this->Clear(); } ~vtkInternal() { this->Clear(); if (this->Manager && this->Manager->GetSession() && this->ObserverTag != 0) { this->Manager->GetSession()->RemoveObserver(this->ObserverTag); this->ObserverTag = 0; } } void Init() { // Check our current user Id and store it this->Me = this->Manager->GetSession()->GetServerInformation()->GetClientId(); this->ObserverTag = this->Manager->GetSession()->AddObserver(vtkPVSessionBase::ProcessingRemoteEnd, this, &vtkSMCollaborationManager::vtkInternal::StopProcessingRemoteNotificationCallback); } const char* GetUserName(int userId) { return this->UserNames[userId].c_str(); } bool UpdateMaster(int newMaster) { if (this->Master != newMaster) { this->Master = newMaster; // If no user to follow yet, then we follow master... this->UpdateState((this->UserToFollow == 0) ? newMaster : this->UserToFollow); this->Manager->InvokeEvent( (unsigned long)vtkSMCollaborationManager::UpdateMasterUser, (void*)&newMaster); return true; } return false; } bool UpdateUserName(int userId, const char* userName) { if (userName) { if (this->UserNames[userId] != userName) { this->UserNames[userId] = userName; this->UpdateState(this->UserToFollow); this->Manager->InvokeEvent( (unsigned long)vtkSMCollaborationManager::UpdateUserName, (void*)&userId); return true; } } else { this->UserNames.erase(userId); this->UpdateState(this->UserToFollow); } return false; } bool SetDisableFurtherConnections(bool disable) { if (disable != this->DisableFurtherConnections) { this->DisableFurtherConnections = disable; this->UpdateState(this->UserToFollow == 0 ? this->Master : this->UserToFollow); return true; } return false; } bool UpdateConnectID(int connectID) { if (this->ConnectID != connectID) { this->ConnectID = connectID; this->UpdateState(this->UserToFollow == 0 ? this->Master : this->UserToFollow); return true; } return false; } void Clear() { this->UserNames.clear(); this->Users.clear(); this->Master = 0; this->ConnectID = 0; this->DisableFurtherConnections = false; this->State.Clear(); this->PendingCameraUpdate.Clear(); this->LocalCameraStateCache.clear(); } void UpdateState(int followCamUserId) { this->UserToFollow = followCamUserId; this->State.ClearExtension(ClientsInformation::user); size_t size = this->Users.size(); for (size_t i = 0; i < size; ++i) { ClientsInformation_ClientInfo* user = this->State.AddExtension(ClientsInformation::user); user->set_user(this->Users[i]); user->set_name(this->GetUserName(this->Users[i])); if (this->Users[i] == this->Master) { user->set_is_master(true); } if (this->Users[i] == followCamUserId) { user->set_follow_cam(true); } user->set_disable_further_connections(this->DisableFurtherConnections); user->set_connect_id(this->ConnectID); } } bool LoadState(const vtkSMMessage* msg) { int size = msg->ExtensionSize(ClientsInformation::user); bool foundChanges = (size != static_cast<int>(this->Users.size())); // Update User list first this->Users.clear(); for (int i = 0; i < size; ++i) { const ClientsInformation_ClientInfo* user = &msg->GetExtension(ClientsInformation::user, i); int id = user->user(); this->Users.push_back(id); } // Update user name/master info int newFollow = 0; for (int i = 0; i < size; ++i) { const ClientsInformation_ClientInfo* user = &msg->GetExtension(ClientsInformation::user, i); int id = user->user(); foundChanges = this->UpdateUserName(id, user->name().c_str()) || foundChanges; if (user->is_master()) { foundChanges = this->UpdateMaster(id) || foundChanges; } foundChanges = this->SetDisableFurtherConnections(user->disable_further_connections()) || foundChanges; foundChanges = this->UpdateConnectID(user->connect_id()) || foundChanges; if (user->follow_cam()) { // Invoke event... newFollow = id; this->Manager->InvokeEvent( (unsigned long)vtkSMCollaborationManager::FollowUserCamera, (void*)&id); } } if (newFollow) { this->UserToFollow = newFollow; } return foundChanges || newFollow; } // Return the camera update message user origin otherwise // if not a camera update message we return -1; int StoreCameraByUser(const vtkSMMessage* msg) { if (msg->HasExtension(DefinitionHeader::client_class) && msg->GetExtension(DefinitionHeader::client_class) == "vtkSMCameraProxy") { int currentUserId = static_cast<int>(msg->client_id()); this->LocalCameraStateCache[currentUserId].CopyFrom(*msg); return currentUserId; } return -1; } void UpdateCamera(const vtkSMMessage* msg) { vtkTypeUInt32 cameraId = msg->global_id(); vtkSMProxyLocator* locator = this->Manager->GetSession()->GetProxyLocator(); vtkSMProxy* proxy = locator->LocateProxy(cameraId); // As camera do not synch its properties while IsProcessingRemoteNotification // there is no point of updating it when we are in that case. // So we just push back that request to later... if (proxy && !proxy->GetSession()->IsProcessingRemoteNotification()) { // Update Proxy proxy->EnableLocalPushOnly(); proxy->LoadState(msg, locator); proxy->UpdateVTKObjects(); proxy->DisableLocalPushOnly(); // Fire event so the Qt layer could trigger a render this->Manager->InvokeEvent(vtkSMCollaborationManager::CameraChanged); } else if (proxy->GetSession()->IsProcessingRemoteNotification()) { this->PendingCameraUpdate.CopyFrom(*msg); } } void StopProcessingRemoteNotificationCallback(vtkObject*, unsigned long, void*) { if (this->PendingCameraUpdate.has_global_id()) { this->UpdateCamera(&this->PendingCameraUpdate); this->PendingCameraUpdate.Clear(); } } vtkWeakPointer<vtkSMCollaborationManager> Manager; std::map<int, std::string> UserNames; std::vector<int> Users; int Me; int UserToFollow; int Master; int ConnectID; vtkSMMessage State; vtkSMMessage PendingCameraUpdate; std::map<int, vtkSMMessage> LocalCameraStateCache; unsigned long ObserverTag; bool DisableFurtherConnections; }; //**************************************************************************** vtkStandardNewMacro(vtkSMCollaborationManager); //---------------------------------------------------------------------------- vtkTypeUInt32 vtkSMCollaborationManager::GetReservedGlobalID() { return vtkReservedRemoteObjectIds::RESERVED_COLLABORATION_COMMUNICATOR_ID; } //---------------------------------------------------------------------------- vtkSMCollaborationManager::vtkSMCollaborationManager() { this->SetLocation(vtkPVSession::DATA_SERVER_ROOT); this->Internal = new vtkInternal(this); this->SetGlobalID(vtkSMCollaborationManager::GetReservedGlobalID()); } //---------------------------------------------------------------------------- vtkSMCollaborationManager::~vtkSMCollaborationManager() { delete this->Internal; this->Internal = nullptr; } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //--------------------------------------------------------------------------- void vtkSMCollaborationManager::LoadState( const vtkSMMessage* msg, vtkSMProxyLocator* vtkNotUsed(locator)) { // Check if it's a local state or if it's a state that use the // CollaborationManager as communication channel accros clients if (msg->ExtensionSize(ClientsInformation::user) > 0) { // For me if (this->Internal->LoadState(msg)) { this->InvokeEvent(UpdateUserList); } } else { // Handle camera synchro if (this->Internal->UserToFollow == this->Internal->StoreCameraByUser(msg) && this->Internal->UserToFollow != -1) { this->Internal->UpdateCamera(msg); } // For Observers vtkSMMessage* msgCopy = new vtkSMMessage(); msgCopy->CopyFrom(*msg); this->InvokeEvent(CollaborationNotification, msgCopy); } } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::DisableFurtherConnections(bool disable) { this->Internal->SetDisableFurtherConnections(disable); this->UpdateUserInformations(); } //----------------------------------------------------------------------------- void vtkSMCollaborationManager::SetConnectID(int connectID) { this->Internal->UpdateConnectID(connectID); this->UpdateUserInformations(); } //---------------------------------------------------------------------------- vtkTypeUInt32 vtkSMCollaborationManager::GetGlobalID() { if (!this->HasGlobalID()) { this->SetGlobalID(vtkSMCollaborationManager::GetReservedGlobalID()); } return this->Superclass::GetGlobalID(); } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::SendToOtherClients(vtkSMMessage* msg) { this->PushState(msg); } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::PromoteToMaster(int clientId) { this->Internal->UpdateMaster(clientId); this->UpdateUserInformations(); } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetFollowedUser() { return this->Internal->UserToFollow; } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::FollowUser(int clientId) { if (this->Internal->UserToFollow == clientId) { return; } if (this->IsMaster()) { this->Internal->UpdateState(clientId); this->UpdateUserInformations(); } else // Follow someone else on my own { this->Internal->UserToFollow = clientId; } // Update the camera if (clientId != -1 && this->Internal->LocalCameraStateCache.find(clientId) != this->Internal->LocalCameraStateCache.end()) { this->Internal->UpdateCamera(&this->Internal->LocalCameraStateCache[clientId]); } } //---------------------------------------------------------------------------- bool vtkSMCollaborationManager::IsMaster() { return (this->Internal->Me == this->Internal->Master); } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetMasterId() { return this->Internal->Master; } //---------------------------------------------------------------------------- bool vtkSMCollaborationManager::GetDisableFurtherConnections() { return this->Internal->DisableFurtherConnections; } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetUserId() { return this->Internal->Me; } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetUserId(int index) { return this->Internal->Users[index]; } //---------------------------------------------------------------------------- const char* vtkSMCollaborationManager::GetUserLabel(int userID) { return this->Internal->GetUserName(userID); } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::SetUserLabel(const char* userName) { this->SetUserLabel(this->Internal->Me, userName); } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::SetUserLabel(int userId, const char* userName) { if (this->Internal->UpdateUserName(userId, userName)) { this->UpdateUserInformations(); } } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetNumberOfConnectedClients() { return static_cast<int>(this->Internal->Users.size()); } //---------------------------------------------------------------------------- const vtkSMMessage* vtkSMCollaborationManager::GetFullState() { this->Internal->State.set_location(vtkPVSession::DATA_SERVER_ROOT); this->Internal->State.set_global_id(vtkSMCollaborationManager::GetReservedGlobalID()); this->Internal->State.SetExtension(DefinitionHeader::client_class, "vtkSMCollaborationManager"); this->Internal->State.SetExtension(DefinitionHeader::server_class, "vtkSICollaborationManager"); return &this->Internal->State; } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::UpdateUserInformations() { // Make sure to add declaration to state message this->GetFullState(); this->PushState(&this->Internal->State); // If we are the only client fetch the data of ourself if (this->GetNumberOfConnectedClients() == 0) { vtkSMMessage msg; msg.CopyFrom(*this->GetFullState()); this->PullState(&msg); this->LoadState(&msg, nullptr); } } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetServerConnectID() { return this->Internal->ConnectID; } //---------------------------------------------------------------------------- int vtkSMCollaborationManager::GetConnectID() { vtkSMSessionClient* session = vtkSMSessionClient::SafeDownCast(this->GetSession()); return session ? session->GetConnectID() : -1; } //---------------------------------------------------------------------------- void vtkSMCollaborationManager::SetSession(vtkSMSession* session) { this->Superclass::SetSession(session); this->Internal->Init(); }
31.255061
98
0.5875
[ "render", "vector" ]
055e1a06a2801c9f8e81887fa0579f37f378f964
3,952
cxx
C++
src/Cxx/VisualizationAlgorithms/CutWithCutFunction.cxx
jhlegarreta/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/VisualizationAlgorithms/CutWithCutFunction.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/VisualizationAlgorithms/CutWithCutFunction.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkSmartPointer.h> #include <vtkXMLPolyDataReader.h> #include <vtkPolyDataMapper.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkPlane.h> #include <vtkProperty.h> #include <vtkActor.h> #include <vtkCamera.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkNamedColors.h> #include <vtkCutter.h> int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " inputFilename(.vtp) [numberOfCuts]" << std::endl; std::cout << "where: inputFilename is Torso.vtp and"; std::cout << " numberOfCuts is 10." << std::endl; return EXIT_FAILURE; } std::string inputFilename = argv[1]; int numberOfCuts = 10; if (argc > 2) { numberOfCuts = atoi(argv[2]); } vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); vtkSmartPointer<vtkXMLPolyDataReader> reader = vtkSmartPointer<vtkXMLPolyDataReader>::New(); reader->SetFileName(inputFilename.c_str()); reader->Update(); double bounds[6]; reader->GetOutput()->GetBounds(bounds); std::cout << "Bounds: " << bounds[0] << ", " << bounds[1] << " " << bounds[2] << ", " << bounds[3] << " " << bounds[4] << ", " << bounds[5] << std::endl; vtkSmartPointer<vtkPlane> plane = vtkSmartPointer<vtkPlane>::New(); plane->SetOrigin((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[4]); plane->SetNormal(0,0,1); // Create cutter double high = plane->EvaluateFunction((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[5]); vtkSmartPointer<vtkCutter> cutter = vtkSmartPointer<vtkCutter>::New(); cutter->SetInputConnection(reader->GetOutputPort()); cutter->SetCutFunction(plane); cutter->GenerateValues( numberOfCuts, .99, .99 * high); vtkSmartPointer<vtkPolyDataMapper> cutterMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); cutterMapper->SetInputConnection( cutter->GetOutputPort()); cutterMapper->ScalarVisibilityOff(); // Create cut actor vtkSmartPointer<vtkActor> cutterActor = vtkSmartPointer<vtkActor>::New(); cutterActor->GetProperty()->SetColor(colors->GetColor3d("Banana").GetData()); cutterActor->GetProperty()->SetLineWidth(2); cutterActor->SetMapper(cutterMapper); // Create model actor vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); modelMapper->SetInputConnection( reader->GetOutputPort()); modelMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New(); modelActor->GetProperty()->SetColor(colors->GetColor3d("Flesh").GetData()); modelActor->SetMapper(modelMapper); // Create renderers and add actors of plane and model vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); renderer->AddActor(cutterActor); renderer->AddActor(modelActor); // Add renderer to renderwindow and render vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); renderWindow->SetSize(600, 600); vtkSmartPointer<vtkRenderWindowInteractor> interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); interactor->SetRenderWindow(renderWindow); renderer->SetBackground(colors->GetColor3d("Burlywood").GetData()); renderer->GetActiveCamera()->SetPosition(0, -1, 0); renderer->GetActiveCamera()->SetFocalPoint(0, 0, 0); renderer->GetActiveCamera()->SetViewUp(0, 0, 1); renderer->GetActiveCamera()->Azimuth(30); renderer->GetActiveCamera()->Elevation(30); renderer->ResetCamera(); renderWindow->Render(); renderWindow->SetWindowName("CutWithCutFunction"); interactor->Start(); return EXIT_SUCCESS; }
31.365079
79
0.677632
[ "render", "model" ]
055ebe3a53b77224ac111fd848abad6aa8a246b0
40,999
cpp
C++
Dependencies/xr/Source/OpenXR/XR.cpp
elix22/BabylonNative
107d6cbb3dc5d5f8ad92ca03e71603eae2cf62d1
[ "MIT" ]
null
null
null
Dependencies/xr/Source/OpenXR/XR.cpp
elix22/BabylonNative
107d6cbb3dc5d5f8ad92ca03e71603eae2cf62d1
[ "MIT" ]
null
null
null
Dependencies/xr/Source/OpenXR/XR.cpp
elix22/BabylonNative
107d6cbb3dc5d5f8ad92ca03e71603eae2cf62d1
[ "MIT" ]
null
null
null
#include <XR.h> #include <XrPlatform.h> #include <assert.h> #include <optional> namespace xr { namespace { struct SupportedExtensions { SupportedExtensions() : Names{} { uint32_t extensionCount{}; XrCheck(xrEnumerateInstanceExtensionProperties(nullptr, 0, &extensionCount, nullptr)); std::vector<XrExtensionProperties> extensionProperties(extensionCount, { XR_TYPE_EXTENSION_PROPERTIES }); XrCheck(xrEnumerateInstanceExtensionProperties(nullptr, extensionCount, &extensionCount, extensionProperties.data())); // D3D11 extension is required for this sample, so check if it's supported. for (const char* extensionName : REQUIRED_EXTENSIONS) { if (!TryEnableExtension(extensionName, extensionProperties)) { throw std::runtime_error{ "Required extension not supported" }; } } // Additional optional extensions for enhanced functionality. Track whether enabled in m_optionalExtensions. DepthExtensionSupported = TryEnableExtension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME, extensionProperties); UnboundedRefSpaceSupported = TryEnableExtension(XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME, extensionProperties); SpatialAnchorSupported = TryEnableExtension(XR_MSFT_SPATIAL_ANCHOR_EXTENSION_NAME, extensionProperties); } std::vector<const char*> Names{}; bool DepthExtensionSupported{ false }; bool UnboundedRefSpaceSupported{ false }; bool SpatialAnchorSupported{ false }; private: bool TryEnableExtension( const char* extensionName, const std::vector<XrExtensionProperties>& extensionProperties) { for (const auto& extensionProperty : extensionProperties) { if (strcmp(extensionProperty.extensionName, extensionName) == 0) { Names.push_back(extensionName); return true; } } return false; }; }; uint32_t AquireAndWaitForSwapchainImage(XrSwapchain handle) { uint32_t swapchainImageIndex; XrSwapchainImageAcquireInfo acquireInfo{ XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO }; XrCheck(xrAcquireSwapchainImage(handle, &acquireInfo, &swapchainImageIndex)); XrSwapchainImageWaitInfo waitInfo{ XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO }; waitInfo.timeout = XR_INFINITE_DURATION; XrCheck(xrWaitSwapchainImage(handle, &waitInfo)); return swapchainImageIndex; }; } class System::Impl { public: static constexpr XrFormFactor FORM_FACTOR{ XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY }; static constexpr XrViewConfigurationType VIEW_CONFIGURATION_TYPE{ XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO }; static constexpr uint32_t STEREO_VIEW_COUNT{ 2 }; // PRIMARY_STEREO view configuration always has 2 views XrInstance Instance{ XR_NULL_HANDLE }; XrSystemId SystemId{ XR_NULL_SYSTEM_ID }; std::unique_ptr<SupportedExtensions> Extensions{}; XrEnvironmentBlendMode EnvironmentBlendMode{}; std::string ApplicationName{}; Impl(const std::string& applicationName) : ApplicationName{ applicationName } {} bool IsInitialized() const { return Instance != XR_NULL_HANDLE && SystemId != XR_NULL_SYSTEM_ID; } bool TryInitialize() { assert(!IsInitialized()); if (Instance == XR_NULL_HANDLE) { Extensions = std::make_unique<SupportedExtensions>(); InitializeXrInstance(); } assert(Extensions != nullptr); assert(SystemId == XR_NULL_SYSTEM_ID); return TryInitializeXrSystemIdAndBlendMode(); } private: // Phase one of initialization. Cannot fail without crashing. void InitializeXrInstance() { XrInstanceCreateInfo createInfo{ XR_TYPE_INSTANCE_CREATE_INFO }; createInfo.enabledExtensionCount = static_cast<uint32_t>(Extensions->Names.size()); createInfo.enabledExtensionNames = Extensions->Names.data(); createInfo.applicationInfo = { "", 1, "OpenXR Sample", 1, XR_CURRENT_API_VERSION }; strcpy_s(createInfo.applicationInfo.applicationName, ApplicationName.c_str()); XrCheck(xrCreateInstance(&createInfo, &Instance)); } // Phase two of initialization. Can fail and be retried without crashing. bool TryInitializeXrSystemIdAndBlendMode() { XrSystemGetInfo systemInfo{ XR_TYPE_SYSTEM_GET_INFO }; systemInfo.formFactor = FORM_FACTOR; XrResult result = xrGetSystem(Instance, &systemInfo, &SystemId); if (result == XR_ERROR_FORM_FACTOR_UNAVAILABLE) { SystemId = XR_NULL_SYSTEM_ID; return false; } else if(!XR_SUCCEEDED(result)) { throw std::runtime_error{ "SystemId initialization failed with unexpected result type." }; } // Find the available environment blend modes. uint32_t count; XrCheck(xrEnumerateEnvironmentBlendModes(Instance, SystemId, VIEW_CONFIGURATION_TYPE, 0, &count, nullptr)); std::vector<XrEnvironmentBlendMode> environmentBlendModes(count); XrCheck(xrEnumerateEnvironmentBlendModes(Instance, SystemId, VIEW_CONFIGURATION_TYPE, count, &count, environmentBlendModes.data())); // Automatically choose the system's preferred blend mode, since specifying the app's // preferred blend mode is currently not supported. assert(environmentBlendModes.size() > 0); EnvironmentBlendMode = environmentBlendModes[0]; return true; } }; class System::Session::Impl { public: const System::Impl& HmdImpl; XrSession Session{ XR_NULL_HANDLE }; XrSpace SceneSpace{ XR_NULL_HANDLE }; XrReferenceSpaceType SceneSpaceType{}; static constexpr uint32_t LeftSide = 0; static constexpr uint32_t RightSide = 1; struct Swapchain { XrSwapchain Handle{}; SwapchainFormat Format{}; int32_t Width{ 0 }; int32_t Height{ 0 }; uint32_t ArraySize{ 0 }; std::vector<SwapchainImage> Images{}; }; struct { std::vector<XrView> Views{}; std::vector<XrViewConfigurationView> ConfigViews{}; std::vector<Swapchain> ColorSwapchains{}; std::vector<Swapchain> DepthSwapchains{}; std::vector<XrCompositionLayerProjectionView> ProjectionLayerViews{}; std::vector<XrCompositionLayerDepthInfoKHR> DepthInfoViews{}; std::vector<Frame::View> ActiveFrameViews{}; } RenderResources{}; struct { static constexpr char* DEFAULT_XR_ACTION_SET_NAME{ "default_xr_action_set" }; static constexpr char* DEFAULT_XR_ACTION_SET_LOCALIZED_NAME{ "Default XR Action Set" }; XrActionSet ActionSet{}; static constexpr std::array<const char*, 2> CONTROLLER_SUBACTION_PATH_PREFIXES { "/user/hand/left", "/user/hand/right" }; std::array<XrPath, CONTROLLER_SUBACTION_PATH_PREFIXES.size()> ControllerSubactionPaths{}; static constexpr char* CONTROLLER_GET_GRIP_POSE_ACTION_NAME{ "controller_get_pose_action" }; static constexpr char* CONTROLLER_GET_GRIP_POSE_ACTION_LOCALIZED_NAME{ "Controller Pose" }; static constexpr char* CONTROLLER_GET_GRIP_POSE_PATH_SUFFIX{ "/input/grip/pose" }; XrAction ControllerGetGripPoseAction{}; std::array<XrSpace, CONTROLLER_SUBACTION_PATH_PREFIXES.size()> ControllerGripPoseSpaces{}; static constexpr char* CONTROLLER_GET_AIM_POSE_ACTION_NAME{ "controller_get_aim_action" }; static constexpr char* CONTROLLER_GET_AIM_POSE_ACTION_LOCALIZED_NAME{ "Controller Aim" }; static constexpr char* CONTROLLER_GET_AIM_POSE_PATH_SUFFIX{ "/input/aim/pose" }; XrAction ControllerGetAimPoseAction{}; std::array<XrSpace, CONTROLLER_SUBACTION_PATH_PREFIXES.size()> ControllerAimPoseSpaces{}; static constexpr char* DEFAULT_XR_INTERACTION_PROFILE{ "/interaction_profiles/khr/simple_controller" }; std::vector<Frame::InputSource> ActiveInputSources{}; } ActionResources{}; float DepthNearZ{ DEFAULT_DEPTH_NEAR_Z }; float DepthFarZ{ DEFAULT_DEPTH_FAR_Z }; XrSessionState SessionState{ XR_SESSION_STATE_UNKNOWN }; Impl(System::Impl& hmdImpl, void* graphicsContext) : HmdImpl{ hmdImpl } { assert(HmdImpl.IsInitialized()); auto instance = HmdImpl.Instance; auto systemId = HmdImpl.SystemId; // Create the session auto graphicsBinding = CreateGraphicsBinding(instance, systemId, graphicsContext); XrSessionCreateInfo createInfo{ XR_TYPE_SESSION_CREATE_INFO }; createInfo.next = &graphicsBinding; createInfo.systemId = systemId; XrCheck(xrCreateSession(instance, &createInfo, &Session)); // Initialize scene space if (HmdImpl.Extensions->UnboundedRefSpaceSupported) { SceneSpaceType = XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT; } else { SceneSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL; } XrReferenceSpaceCreateInfo spaceCreateInfo{ XR_TYPE_REFERENCE_SPACE_CREATE_INFO }; spaceCreateInfo.referenceSpaceType = SceneSpaceType; spaceCreateInfo.poseInReferenceSpace = IDENTITY_TRANSFORM; XrCheck(xrCreateReferenceSpace(Session, &spaceCreateInfo, &SceneSpace)); InitializeRenderResources(instance, systemId); InitializeActionResources(instance); } std::unique_ptr<System::Session::Frame> GetNextFrame(bool& shouldEndSession, bool& shouldRestartSession) { ProcessEvents(shouldEndSession, shouldRestartSession); if (!shouldEndSession) { return std::make_unique<Frame>(*this); } else { return nullptr; } } void RequestEndSession() { xrRequestExitSession(Session); } Size GetWidthAndHeightForViewIndex(size_t viewIndex) const { const auto& swapchain = RenderResources.ColorSwapchains[viewIndex]; return{ static_cast<size_t>(swapchain.Width), static_cast<size_t>(swapchain.Height) }; } private: static constexpr XrPosef IDENTITY_TRANSFORM{ XrQuaternionf{ 0.f, 0.f, 0.f, 1.f }, XrVector3f{ 0.f, 0.f, 0.f } }; void InitializeRenderResources(XrInstance instance, XrSystemId systemId) { // Read graphics properties for preferred swapchain length and logging. XrSystemProperties systemProperties{ XR_TYPE_SYSTEM_PROPERTIES }; XrCheck(xrGetSystemProperties(instance, systemId, &systemProperties)); // Select color and depth swapchain pixel formats SwapchainFormat colorSwapchainFormat; SwapchainFormat depthSwapchainFormat; SelectSwapchainPixelFormats(colorSwapchainFormat, depthSwapchainFormat); // Query and cache view configuration views. Two-call idiom. uint32_t viewCount; XrCheck(xrEnumerateViewConfigurationViews(instance, systemId, HmdImpl.VIEW_CONFIGURATION_TYPE, 0, &viewCount, nullptr)); assert(viewCount == HmdImpl.STEREO_VIEW_COUNT); RenderResources.ConfigViews.resize(viewCount, { XR_TYPE_VIEW_CONFIGURATION_VIEW }); XrCheck(xrEnumerateViewConfigurationViews(instance, systemId, HmdImpl.VIEW_CONFIGURATION_TYPE, viewCount, &viewCount, RenderResources.ConfigViews.data())); // Create all the swapchains. for (uint32_t idx = 0; idx < viewCount; ++idx) { const XrViewConfigurationView& view = RenderResources.ConfigViews[idx]; RenderResources.ColorSwapchains.push_back( CreateSwapchain(Session, colorSwapchainFormat, view.recommendedImageRectWidth, view.recommendedImageRectHeight, 1, view.recommendedSwapchainSampleCount, 0, XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT)); RenderResources.DepthSwapchains.push_back( CreateSwapchain(Session, depthSwapchainFormat, view.recommendedImageRectWidth, view.recommendedImageRectHeight, 1, view.recommendedSwapchainSampleCount, 0, XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)); } // Pre-allocate the views, since we know how many there will be. RenderResources.Views.resize(viewCount, { XR_TYPE_VIEW }); } void InitializeActionResources(XrInstance instance) { // Create action set XrActionSetCreateInfo actionSetInfo{ XR_TYPE_ACTION_SET_CREATE_INFO }; std::strcpy(actionSetInfo.actionSetName, ActionResources.DEFAULT_XR_ACTION_SET_NAME); std::strcpy(actionSetInfo.localizedActionSetName, ActionResources.DEFAULT_XR_ACTION_SET_LOCALIZED_NAME); XrCheck(xrCreateActionSet(instance, &actionSetInfo, &ActionResources.ActionSet)); // Cache paths for subactions for (size_t idx = 0; idx < ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES.size(); ++idx) { XrCheck(xrStringToPath(instance, ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES[idx], &ActionResources.ControllerSubactionPaths[idx])); } std::vector<XrActionSuggestedBinding> bindings{}; // Create controller get grip pose action, suggested bindings, and spaces { XrActionCreateInfo actionInfo{ XR_TYPE_ACTION_CREATE_INFO }; actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT; strcpy_s(actionInfo.actionName, ActionResources.CONTROLLER_GET_GRIP_POSE_ACTION_NAME); strcpy_s(actionInfo.localizedActionName, ActionResources.CONTROLLER_GET_GRIP_POSE_ACTION_LOCALIZED_NAME); actionInfo.countSubactionPaths = ActionResources.ControllerSubactionPaths.size(); actionInfo.subactionPaths = ActionResources.ControllerSubactionPaths.data(); XrCheck(xrCreateAction(ActionResources.ActionSet, &actionInfo, &ActionResources.ControllerGetGripPoseAction)); // For each controller subaction for (size_t idx = 0; idx < ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES.size(); ++idx) { // Create suggested binding std::string path{ ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES[idx] }; path.append(ActionResources.CONTROLLER_GET_GRIP_POSE_PATH_SUFFIX); bindings.push_back({ ActionResources.ControllerGetGripPoseAction }); XrCheck(xrStringToPath(instance, path.data(), &bindings.back().binding)); // Create subaction space XrActionSpaceCreateInfo actionSpaceCreateInfo{ XR_TYPE_ACTION_SPACE_CREATE_INFO }; actionSpaceCreateInfo.action = ActionResources.ControllerGetGripPoseAction; actionSpaceCreateInfo.poseInActionSpace = IDENTITY_TRANSFORM; actionSpaceCreateInfo.subactionPath = ActionResources.ControllerSubactionPaths[idx]; XrCheck(xrCreateActionSpace(Session, &actionSpaceCreateInfo, &ActionResources.ControllerGripPoseSpaces[idx])); } } // Create controller controller get aim pose action, suggested bindings, and spaces { XrActionCreateInfo actionInfo{ XR_TYPE_ACTION_CREATE_INFO }; actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT; strcpy_s(actionInfo.actionName, ActionResources.CONTROLLER_GET_AIM_POSE_ACTION_NAME); strcpy_s(actionInfo.localizedActionName, ActionResources.CONTROLLER_GET_AIM_POSE_ACTION_LOCALIZED_NAME); actionInfo.countSubactionPaths = ActionResources.ControllerSubactionPaths.size(); actionInfo.subactionPaths = ActionResources.ControllerSubactionPaths.data(); XrCheck(xrCreateAction(ActionResources.ActionSet, &actionInfo, &ActionResources.ControllerGetAimPoseAction)); // For each controller subaction for (size_t idx = 0; idx < ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES.size(); ++idx) { // Create suggested binding std::string path{ ActionResources.CONTROLLER_SUBACTION_PATH_PREFIXES[idx] }; path.append(ActionResources.CONTROLLER_GET_AIM_POSE_PATH_SUFFIX); bindings.push_back({ ActionResources.ControllerGetAimPoseAction }); XrCheck(xrStringToPath(instance, path.data(), &bindings.back().binding)); // Create subaction space XrActionSpaceCreateInfo actionSpaceCreateInfo{ XR_TYPE_ACTION_SPACE_CREATE_INFO }; actionSpaceCreateInfo.action = ActionResources.ControllerGetAimPoseAction; actionSpaceCreateInfo.poseInActionSpace = IDENTITY_TRANSFORM; actionSpaceCreateInfo.subactionPath = ActionResources.ControllerSubactionPaths[idx]; XrCheck(xrCreateActionSpace(Session, &actionSpaceCreateInfo, &ActionResources.ControllerAimPoseSpaces[idx])); } } // Provide suggested bindings to instance XrInteractionProfileSuggestedBinding suggestedBindings{ XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING }; XrCheck(xrStringToPath(instance, ActionResources.DEFAULT_XR_INTERACTION_PROFILE, &suggestedBindings.interactionProfile)); suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); XrCheck(xrSuggestInteractionProfileBindings(instance, &suggestedBindings)); XrSessionActionSetsAttachInfo attachInfo{ XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO }; attachInfo.countActionSets = 1; attachInfo.actionSets = &ActionResources.ActionSet; XrCheck(xrAttachSessionActionSets(Session, &attachInfo)); } Swapchain CreateSwapchain(XrSession session, SwapchainFormat format, int32_t width, int32_t height, uint32_t arraySize, uint32_t sampleCount, XrSwapchainCreateFlags createFlags, XrSwapchainUsageFlags usageFlags) { Swapchain swapchain; swapchain.Format = format; swapchain.Width = width; swapchain.Height = height; swapchain.ArraySize = arraySize; XrSwapchainCreateInfo swapchainCreateInfo{ XR_TYPE_SWAPCHAIN_CREATE_INFO }; swapchainCreateInfo.arraySize = arraySize; swapchainCreateInfo.format = format; swapchainCreateInfo.width = width; swapchainCreateInfo.height = height; swapchainCreateInfo.mipCount = 1; swapchainCreateInfo.faceCount = 1; swapchainCreateInfo.sampleCount = sampleCount; swapchainCreateInfo.createFlags = createFlags; swapchainCreateInfo.usageFlags = usageFlags; XrCheck(xrCreateSwapchain(session, &swapchainCreateInfo, &swapchain.Handle)); uint32_t chainLength; XrCheck(xrEnumerateSwapchainImages(swapchain.Handle, 0, &chainLength, nullptr)); swapchain.Images.resize(chainLength, { SWAPCHAIN_IMAGE_TYPE_ENUM }); XrCheck(xrEnumerateSwapchainImages(swapchain.Handle, static_cast<uint32_t>(swapchain.Images.size()), &chainLength, reinterpret_cast<XrSwapchainImageBaseHeader*>(swapchain.Images.data()))); return swapchain; } void SelectSwapchainPixelFormats(SwapchainFormat& colorFormat, SwapchainFormat& depthFormat) { // Query runtime preferred swapchain formats. Two-call idiom. uint32_t swapchainFormatCount; XrCheck(xrEnumerateSwapchainFormats(Session, 0, &swapchainFormatCount, nullptr)); std::vector<int64_t> swapchainFormats(swapchainFormatCount); XrCheck(xrEnumerateSwapchainFormats(Session, static_cast<uint32_t>(swapchainFormats.size()), &swapchainFormatCount, swapchainFormats.data())); auto colorFormatPtr = std::find_first_of( std::begin(swapchainFormats), std::end(swapchainFormats), std::begin(SUPPORTED_COLOR_FORMATS), std::end(SUPPORTED_COLOR_FORMATS)); if (colorFormatPtr == std::end(swapchainFormats)) { throw std::runtime_error{ "No runtime swapchain format is supported for color." }; } auto depthFormatPtr = std::find_first_of( std::begin(swapchainFormats), std::end(swapchainFormats), std::begin(SUPPORTED_DEPTH_FORMATS), std::end(SUPPORTED_DEPTH_FORMATS)); if (depthFormatPtr == std::end(swapchainFormats)) { throw std::runtime_error{ "No runtime swapchain format is supported for depth." }; } colorFormat = static_cast<SwapchainFormat>(*colorFormatPtr); depthFormat = static_cast<SwapchainFormat>(*depthFormatPtr); } bool TryReadNextEvent(XrEventDataBuffer& buffer) const { // Reset buffer header for every xrPollEvent function call. buffer = { XR_TYPE_EVENT_DATA_BUFFER }; const XrResult xr = xrPollEvent(HmdImpl.Instance, &buffer); return xr != XR_EVENT_UNAVAILABLE; } void ProcessSessionState(bool& exitRenderLoop, bool& requestRestart) { switch (SessionState) { case XR_SESSION_STATE_READY: { assert(Session != XR_NULL_HANDLE); XrSessionBeginInfo sessionBeginInfo{ XR_TYPE_SESSION_BEGIN_INFO }; sessionBeginInfo.primaryViewConfigurationType = HmdImpl.VIEW_CONFIGURATION_TYPE; XrCheck(xrBeginSession(Session, &sessionBeginInfo)); break; } case XR_SESSION_STATE_STOPPING: XrCheck(xrEndSession(Session)); break; case XR_SESSION_STATE_EXITING: // Do not attempt to restart because user closed this session. exitRenderLoop = true; requestRestart = false; break; case XR_SESSION_STATE_LOSS_PENDING: // Poll for a new systemId exitRenderLoop = true; requestRestart = true; break; } } void ProcessEvents(bool& exitRenderLoop, bool& requestRestart) { exitRenderLoop = false; requestRestart = false; XrEventDataBuffer buffer{ XR_TYPE_EVENT_DATA_BUFFER }; XrEventDataBaseHeader* header = reinterpret_cast<XrEventDataBaseHeader*>(&buffer); // Process all pending messages. while (TryReadNextEvent(buffer)) { switch (header->type) { case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: exitRenderLoop = true; requestRestart = false; return; case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: const auto stateEvent = *reinterpret_cast<const XrEventDataSessionStateChanged*>(header); assert(Session != XR_NULL_HANDLE && Session == stateEvent.session); SessionState = stateEvent.state; ProcessSessionState(exitRenderLoop, requestRestart); break; case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: default: // DEBUG_PRINT("Ignoring event type %d", header->type); break; } } } }; struct System::Session::Frame::Impl { Impl(Session::Impl& sessionImpl) : sessionImpl{sessionImpl} { } Session::Impl& sessionImpl; bool shouldRender{}; int64_t displayTime{}; }; System::Session::Frame::Frame(Session::Impl& sessionImpl) : Views{ sessionImpl.RenderResources.ActiveFrameViews } , InputSources{ sessionImpl.ActionResources.ActiveInputSources } , m_impl{ std::make_unique<System::Session::Frame::Impl>(sessionImpl) } { auto session = m_impl->sessionImpl.Session; XrFrameWaitInfo frameWaitInfo{ XR_TYPE_FRAME_WAIT_INFO }; XrFrameState frameState{ XR_TYPE_FRAME_STATE }; XrCheck(xrWaitFrame(session, &frameWaitInfo, &frameState)); m_impl->shouldRender = frameState.shouldRender; m_impl->displayTime = frameState.predictedDisplayTime; XrFrameBeginInfo frameBeginInfo{ XR_TYPE_FRAME_BEGIN_INFO }; XrCheck(xrBeginFrame(session, &frameBeginInfo)); auto& renderResources = m_impl->sessionImpl.RenderResources; // Only render when session is visible. otherwise submit zero layers if (m_impl->shouldRender) { uint32_t viewCapacityInput = static_cast<uint32_t>(renderResources.Views.size()); uint32_t viewCountOutput; XrViewState viewState{ XR_TYPE_VIEW_STATE }; XrViewLocateInfo viewLocateInfo{ XR_TYPE_VIEW_LOCATE_INFO }; viewLocateInfo.viewConfigurationType = System::Impl::VIEW_CONFIGURATION_TYPE; viewLocateInfo.displayTime = m_impl->displayTime; viewLocateInfo.space = m_impl->sessionImpl.SceneSpace; XrCheck(xrLocateViews(session, &viewLocateInfo, &viewState, viewCapacityInput, &viewCountOutput, renderResources.Views.data())); assert(viewCountOutput == viewCapacityInput); assert(viewCountOutput == renderResources.ConfigViews.size()); assert(viewCountOutput == renderResources.ColorSwapchains.size()); assert(viewCountOutput == renderResources.DepthSwapchains.size()); renderResources.ProjectionLayerViews.resize(viewCountOutput); if (m_impl->sessionImpl.HmdImpl.Extensions->DepthExtensionSupported) { renderResources.DepthInfoViews.resize(viewCountOutput); } Views.resize(viewCountOutput); // Prepare rendering parameters of each view for swapchain texture arrays for (uint32_t idx = 0; idx < viewCountOutput; ++idx) { const auto& colorSwapchain = renderResources.ColorSwapchains[idx]; const auto& depthSwapchain = renderResources.DepthSwapchains[idx]; // Use the full range of recommended image size to achieve optimum resolution const XrRect2Di imageRect = { {0, 0}, { colorSwapchain.Width, colorSwapchain.Height } }; assert(colorSwapchain.Width == depthSwapchain.Width); assert(colorSwapchain.Height == depthSwapchain.Height); const uint32_t colorSwapchainImageIndex = AquireAndWaitForSwapchainImage(colorSwapchain.Handle); const uint32_t depthSwapchainImageIndex = AquireAndWaitForSwapchainImage(depthSwapchain.Handle); // Populate the struct that consuming code will use for rendering. auto& view = Views[idx]; view.Space.Pose.Position.X = renderResources.Views[idx].pose.position.x; view.Space.Pose.Position.Y = renderResources.Views[idx].pose.position.y; view.Space.Pose.Position.Z = renderResources.Views[idx].pose.position.z; view.Space.Pose.Orientation.X = renderResources.Views[idx].pose.orientation.x; view.Space.Pose.Orientation.Y = renderResources.Views[idx].pose.orientation.y; view.Space.Pose.Orientation.Z = renderResources.Views[idx].pose.orientation.z; view.Space.Pose.Orientation.W = renderResources.Views[idx].pose.orientation.w; view.FieldOfView.AngleUp = renderResources.Views[idx].fov.angleUp; view.FieldOfView.AngleDown = renderResources.Views[idx].fov.angleDown; view.FieldOfView.AngleLeft = renderResources.Views[idx].fov.angleLeft; view.FieldOfView.AngleRight = renderResources.Views[idx].fov.angleRight; view.ColorTextureFormat = SwapchainFormatToTextureFormat(colorSwapchain.Format); view.ColorTexturePointer = colorSwapchain.Images[colorSwapchainImageIndex].texture; view.ColorTextureSize.Width = colorSwapchain.Width; view.ColorTextureSize.Height = colorSwapchain.Height; view.DepthTextureFormat = SwapchainFormatToTextureFormat(depthSwapchain.Format); view.DepthTexturePointer = depthSwapchain.Images[depthSwapchainImageIndex].texture; view.DepthTextureSize.Width = depthSwapchain.Width; view.DepthTextureSize.Height = depthSwapchain.Height; view.DepthNearZ = sessionImpl.DepthNearZ; view.DepthFarZ = sessionImpl.DepthFarZ; renderResources.ProjectionLayerViews[idx] = { XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW }; renderResources.ProjectionLayerViews[idx].pose = renderResources.Views[idx].pose; renderResources.ProjectionLayerViews[idx].fov = renderResources.Views[idx].fov; renderResources.ProjectionLayerViews[idx].subImage.swapchain = colorSwapchain.Handle; renderResources.ProjectionLayerViews[idx].subImage.imageRect = imageRect; renderResources.ProjectionLayerViews[idx].subImage.imageArrayIndex = 0; if (sessionImpl.HmdImpl.Extensions->DepthExtensionSupported) { renderResources.DepthInfoViews[idx] = { XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR }; renderResources.DepthInfoViews[idx].minDepth = 0; renderResources.DepthInfoViews[idx].maxDepth = 1; renderResources.DepthInfoViews[idx].nearZ = sessionImpl.DepthNearZ; renderResources.DepthInfoViews[idx].farZ = sessionImpl.DepthFarZ; renderResources.DepthInfoViews[idx].subImage.swapchain = depthSwapchain.Handle; renderResources.DepthInfoViews[idx].subImage.imageRect = imageRect; renderResources.DepthInfoViews[idx].subImage.imageArrayIndex = 0; // Chain depth info struct to the corresponding projection layer views's next renderResources.ProjectionLayerViews[idx].next = &renderResources.DepthInfoViews[idx]; } } // Locate all the things. auto& actionResources = m_impl->sessionImpl.ActionResources; std::vector<XrActiveActionSet> activeActionSets = { { actionResources.ActionSet, XR_NULL_PATH } }; XrActionsSyncInfo syncInfo{ XR_TYPE_ACTIONS_SYNC_INFO }; syncInfo.countActiveActionSets = (uint32_t)activeActionSets.size(); syncInfo.activeActionSets = activeActionSets.data(); XrCheck(xrSyncActions(m_impl->sessionImpl.Session, &syncInfo)); InputSources.resize(actionResources.CONTROLLER_SUBACTION_PATH_PREFIXES.size()); for (size_t idx = 0; idx < InputSources.size(); ++idx) { // Get grip space { XrSpace space = actionResources.ControllerGripPoseSpaces[idx]; XrSpaceLocation location{ XR_TYPE_SPACE_LOCATION }; XrCheck(xrLocateSpace(space, m_impl->sessionImpl.SceneSpace, m_impl->displayTime, &location)); constexpr XrSpaceLocationFlags RequiredFlags = XR_SPACE_LOCATION_POSITION_VALID_BIT | XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT; auto& inputSource = InputSources[idx]; inputSource.TrackedThisFrame = (location.locationFlags & RequiredFlags) == RequiredFlags; if (inputSource.TrackedThisFrame) { inputSource.Handedness = static_cast<InputSource::HandednessEnum>(idx); inputSource.GripSpace.Pose.Position.X = location.pose.position.x; inputSource.GripSpace.Pose.Position.Y = location.pose.position.y; inputSource.GripSpace.Pose.Position.Z = location.pose.position.z; inputSource.GripSpace.Pose.Orientation.X = location.pose.orientation.x; inputSource.GripSpace.Pose.Orientation.Y = location.pose.orientation.y; inputSource.GripSpace.Pose.Orientation.Z = location.pose.orientation.z; inputSource.GripSpace.Pose.Orientation.W = location.pose.orientation.w; } } // Get aim space { XrSpace space = actionResources.ControllerAimPoseSpaces[idx]; XrSpaceLocation location{ XR_TYPE_SPACE_LOCATION }; XrCheck(xrLocateSpace(space, m_impl->sessionImpl.SceneSpace, m_impl->displayTime, &location)); constexpr XrSpaceLocationFlags RequiredFlags = XR_SPACE_LOCATION_POSITION_VALID_BIT | XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT; auto& inputSource = InputSources[idx]; inputSource.TrackedThisFrame = (location.locationFlags & RequiredFlags) == RequiredFlags; if (inputSource.TrackedThisFrame) { inputSource.Handedness = static_cast<InputSource::HandednessEnum>(idx); inputSource.AimSpace.Pose.Position.X = location.pose.position.x; inputSource.AimSpace.Pose.Position.Y = location.pose.position.y; inputSource.AimSpace.Pose.Position.Z = location.pose.position.z; inputSource.AimSpace.Pose.Orientation.X = location.pose.orientation.x; inputSource.AimSpace.Pose.Orientation.Y = location.pose.orientation.y; inputSource.AimSpace.Pose.Orientation.Z = location.pose.orientation.z; inputSource.AimSpace.Pose.Orientation.W = location.pose.orientation.w; } } } } } void System::Session::Frame::GetHitTestResults(std::vector<Pose>& filteredResults, Ray) const { // Stubbed out for now, should be implemented if we want to support OpenXR based passthrough AR devices. } System::Session::Frame::~Frame() { // EndFrame can submit mutiple layers, but we only support one at the moment. XrCompositionLayerBaseHeader* layersPtr{}; // The projection layer consists of projection layer views. // This must be declared out here because layers is a vector of pointer, so the layer struct // must not go out of scope before xrEndFrame() is called. XrCompositionLayerProjection layer{ XR_TYPE_COMPOSITION_LAYER_PROJECTION }; if (m_impl->shouldRender) { auto& renderResources = m_impl->sessionImpl.RenderResources; XrSwapchainImageReleaseInfo releaseInfo{ XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO }; for (auto& swapchain : renderResources.ColorSwapchains) { XrAssert(xrReleaseSwapchainImage(swapchain.Handle, &releaseInfo)); } for (auto& swapchain : renderResources.DepthSwapchains) { XrAssert(xrReleaseSwapchainImage(swapchain.Handle, &releaseInfo)); } // Inform the runtime to consider alpha channel during composition // The primary display on Hololens has additive environment blend mode. It will ignore alpha channel. // But mixed reality capture has alpha blend mode display and use alpha channel to blend content to environment. layer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT; layer.space = m_impl->sessionImpl.SceneSpace; layer.viewCount = static_cast<uint32_t>(renderResources.ProjectionLayerViews.size()); layer.views = renderResources.ProjectionLayerViews.data(); layersPtr = reinterpret_cast<XrCompositionLayerBaseHeader*>(&layer); } #ifdef _DEBUG if (!Views.empty()) { // 'SetPrivateData' is intercepted by the special fork of RenderDoc in order to detect that // a frame is being presented. This can be done to any swapchain image texture returned // by xrEnumerateSwapchainImages. This should be done after all rendering is complete for the // frame (and not for each eye backbuffer). ID3D11Texture2D* texture = reinterpret_cast<ID3D11Texture2D*>(Views.front().ColorTexturePointer); int dummy; texture->SetPrivateData({0xD4544440, 0x90B9, 0x4815, 0x8B, 0x99, 0x18, 0xC0, 0x23, 0xA5, 0x73, 0xF1}, sizeof(dummy), &dummy); } #endif // Submit the composition layers for the predicted display time. XrFrameEndInfo frameEndInfo{ XR_TYPE_FRAME_END_INFO }; frameEndInfo.displayTime = m_impl->displayTime; frameEndInfo.environmentBlendMode = m_impl->sessionImpl.HmdImpl.EnvironmentBlendMode; frameEndInfo.layerCount = m_impl->shouldRender ? 1 : 0; frameEndInfo.layers = &layersPtr; XrAssert(xrEndFrame(m_impl->sessionImpl.Session, &frameEndInfo)); } System::System(const char* appName) : m_impl{ std::make_unique<System::Impl>(appName) } {} System::~System() {} bool System::IsInitialized() const { return m_impl->IsInitialized(); } bool System::TryInitialize() { return m_impl->TryInitialize(); } System::Session::Session(System& headMountedDisplay, void* graphicsDevice) : m_impl{ std::make_unique<System::Session::Impl>(*headMountedDisplay.m_impl, graphicsDevice) } {} System::Session::~Session() {} std::unique_ptr<System::Session::Frame> System::Session::GetNextFrame(bool& shouldEndSession, bool& shouldRestartSession) { return m_impl->GetNextFrame(shouldEndSession, shouldRestartSession); } void System::Session::RequestEndSession() { m_impl->RequestEndSession(); } Size System::Session::GetWidthAndHeightForViewIndex(size_t viewIndex) const { return m_impl->GetWidthAndHeightForViewIndex(viewIndex); } void System::Session::SetDepthsNearFar(float depthNear, float depthFar) { m_impl->DepthNearZ = depthNear; m_impl->DepthFarZ = depthFar; } }
48.519527
167
0.63782
[ "render", "vector" ]
05627c179f54f6db5fdc70590b74bb0d4ebbf3d5
2,982
hpp
C++
core/id_mapper.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
29
2019-11-18T14:25:05.000Z
2022-02-10T07:21:48.000Z
core/id_mapper.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
2
2021-03-17T03:17:38.000Z
2021-04-11T04:06:23.000Z
core/id_mapper.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
6
2019-11-21T18:04:15.000Z
2022-03-01T02:48:50.000Z
/* Copyright 2019 Husky Data Lab, CUHK Authors: Hongzhi Chen (hzchen@cse.cuhk.edu.hk) */ #ifndef IDMAPPER_HPP_ #define IDMAPPER_HPP_ #include <vector> #include "core/abstract_id_mapper.hpp" #include "utils/config.hpp" #include "utils/unit.hpp" #include "utils/mymath.hpp" #include "base/type.hpp" #include "base/node.hpp" #include "glog/logging.h" static uint64_t _VIDFLAG = 0xFFFFFFFFFFFFFFFF >> (64-VID_BITS); static uint64_t _PIDLFLAG = 0xFFFFFFFFFFFFFFFF >> (64- 2*VID_BITS); class NaiveIdMapper : public AbstractIdMapper { public: NaiveIdMapper(Node & node) : my_node_(node) { config_ = Config::GetInstance(); } bool IsVertex(uint64_t v_id) { bool has_v = v_id & _VIDFLAG; return has_v; } bool IsEdge(uint64_t e_id) { bool has_out_v = e_id & _VIDFLAG; e_id >>= VID_BITS; bool has_in_v = e_id & _VIDFLAG; return has_out_v && has_in_v; } bool IsVProperty(uint64_t vp_id) { bool has_p = vp_id & _PIDLFLAG; vp_id >>= PID_BITS; vp_id >>= VID_BITS; bool has_v = vp_id & _VIDFLAG; return has_p && has_v; } bool IsEProperty(uint64_t ep_id) { bool has_p = ep_id & _PIDLFLAG; ep_id >>= PID_BITS; bool has_out_v = ep_id & _VIDFLAG; ep_id >>= VID_BITS; bool has_in_v = ep_id & _VIDFLAG; return has_p && has_out_v && has_in_v; } // judge if vertex/edge/property local bool IsVertexLocal(const vid_t v_id) { return GetMachineIdForVertex(v_id) == my_node_.get_local_rank(); } bool IsEdgeLocal(const eid_t e_id) { return GetMachineIdForEdge(e_id) == my_node_.get_local_rank(); } bool IsVPropertyLocal(const vpid_t vp_id) { return GetMachineIdForVProperty(vp_id) == my_node_.get_local_rank(); } bool IsEPropertyLocal(const epid_t ep_id) { return GetMachineIdForEProperty(ep_id) == my_node_.get_local_rank(); } // vertex/edge/property -> machine index mapping int GetMachineIdForVertex(vid_t v_id) { return mymath::hash_mod(v_id.hash(), my_node_.get_local_size()); } int GetMachineIdForEdge(eid_t e_id) { return mymath::hash_mod(e_id.hash(), my_node_.get_local_size()); } // #define BY_EV_ID #ifdef BY_EV_ID int GetMachineIdForVProperty(vpid_t vp_id) { vid_t v(vp_id.vid); return mymath::hash_mod(v.hash(), my_node_.get_local_size()); } int GetMachineIdForEProperty(epid_t ep_id) { eid_t e(ep_id.in_vid, ep_id.out_vid); return mymath::hash_mod(e.hash(), my_node_.get_local_size()); } #else int GetMachineIdForVProperty(vpid_t vp_id) { return mymath::hash_mod(vp_id.hash(), my_node_.get_local_size()); } int GetMachineIdForEProperty(epid_t ep_id) { return mymath::hash_mod(ep_id.hash(), my_node_.get_local_size()); } #endif private: Config * config_; Node my_node_; }; #endif /* IDMAPPER_HPP_ */
26.864865
76
0.657277
[ "vector" ]
0564baa167da35561c9c7db1ea2322b3a09eb529
684
hpp
C++
include/xul/xio/io_session_listener.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/xio/io_session_listener.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/xio/io_session_listener.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <stddef.h> namespace xul { class io_session; class io_session_listener; class decoder_message_base; class message_decoder; class io_session_listener { public: virtual void on_session_open(io_session* session) { } virtual void on_session_close(io_session* session) { } virtual void on_session_error(io_session* session, int errcode) { } virtual void on_session_receive(io_session* session, xul::decoder_message_base* msg) { } virtual void on_session_send(io_session* session, size_t bytes) { } virtual message_decoder* create_message_decoder() = 0; }; class io_session_handler : public object, public io_session_listener { }; }
20.727273
92
0.763158
[ "object" ]
0566bb7416a4e71dce50c1827d83218c0c0eae64
4,085
cpp
C++
gtests/src/integration/tests/test_dc_aware_policy.cpp
polsm91/cpp-driver
fd9b73d4acfd85293ab304be64e2e1e2109e521d
[ "Apache-2.0" ]
null
null
null
gtests/src/integration/tests/test_dc_aware_policy.cpp
polsm91/cpp-driver
fd9b73d4acfd85293ab304be64e2e1e2109e521d
[ "Apache-2.0" ]
null
null
null
gtests/src/integration/tests/test_dc_aware_policy.cpp
polsm91/cpp-driver
fd9b73d4acfd85293ab304be64e2e1e2109e521d
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) DataStax, 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 "integration.hpp" #include "cassandra.h" #include <algorithm> #include <iterator> class DcAwarePolicyTest : public Integration { public: void SetUp() { // Create a cluster with 2 DCs with 2 nodes in each number_dc1_nodes_ = 2; number_dc2_nodes_ = 2; is_session_requested_ = false; Integration::SetUp(); } void initialize() { session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "text")); session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "1", "'one'")); session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "2", "'two'")); } std::vector<std::string> validate() { std::vector<std::string> attempted_hosts, temp; Result result; result = session_.execute(select_statement("1")); temp = result.attempted_hosts(); std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts)); EXPECT_EQ(result.first_row().next().as<Varchar>(), Varchar("one")); result = session_.execute(select_statement("2")); temp = result.attempted_hosts(); std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts)); EXPECT_EQ(result.first_row().next().as<Varchar>(), Varchar("two")); return attempted_hosts; } Statement select_statement(const std::string& key) { Statement statement(format_string(CASSANDRA_SELECT_VALUE_FORMAT, table_name_.c_str(), key.c_str())); statement.set_consistency(CASS_CONSISTENCY_ONE); statement.set_record_attempted_hosts(true); return statement; } bool contains(const std::string& host, const std::vector<std::string>& attempted_hosts) { return std::count(attempted_hosts.begin(), attempted_hosts.end(), host) > 0; } }; /** * Verify that the "used hosts per remote DC" setting allows queries to use the * remote DC nodes when the local DC nodes are unavailable. * * This ensures that the DC aware policy correctly uses remote hosts when * "used hosts per remote DC" has a value greater than 0. * * @since 2.8.1 * @jira_ticket CPP-572 * @test_category load_balancing_policy:dc_aware */ CASSANDRA_INTEGRATION_TEST_F(DcAwarePolicyTest, UsedHostsRemoteDc) { CHECK_FAILURE // Use up to one of the remote DC nodes if no local nodes are available. cluster_ = default_cluster(); cluster_.with_load_balance_dc_aware("dc1", 1, false); connect(cluster_); // Create a test table and add test data to it initialize(); { // Run queries using the local DC std::vector<std::string> attempted_hosts = validate(); // Verify that local DC hosts were used EXPECT_TRUE(contains(ccm_->get_ip_prefix() + "1", attempted_hosts) || contains(ccm_->get_ip_prefix() + "2", attempted_hosts)); // Verify that no remote DC hosts were used EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + "3", attempted_hosts) && !contains(ccm_->get_ip_prefix() + "4", attempted_hosts)); } // Stop the whole local DC ccm_->stop_node(1, true); ccm_->stop_node(2, true); { // Run queries using the remote DC std::vector<std::string> attempted_hosts = validate(); // Verify that remote DC hosts were used EXPECT_TRUE(contains(ccm_->get_ip_prefix() + "3", attempted_hosts) || contains(ccm_->get_ip_prefix() + "4", attempted_hosts)); // Verify that no local DC hosts where used EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + "1", attempted_hosts) && !contains(ccm_->get_ip_prefix() + "2", attempted_hosts)); } }
35.833333
132
0.715545
[ "vector" ]
0566e14801fe65c3ca83031bd4425b5ec63ce773
8,786
cpp
C++
inference-engine/tests/unit/shape_infer/reshaper_test.cpp
cpriebe/dldt
8631dc583e506adcd06498095919b5dd42323e1e
[ "Apache-2.0" ]
3
2020-02-09T23:25:37.000Z
2021-01-19T09:44:12.000Z
inference-engine/tests/unit/shape_infer/reshaper_test.cpp
cpriebe/dldt
8631dc583e506adcd06498095919b5dd42323e1e
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/unit/shape_infer/reshaper_test.cpp
cpriebe/dldt
8631dc583e506adcd06498095919b5dd42323e1e
[ "Apache-2.0" ]
2
2020-04-18T16:24:39.000Z
2021-01-19T09:42:19.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include <shape_infer/mock_ishape_infer_impl.hpp> #include <shape_infer/mock_shape_infer_extension.hpp> #include <mock_icnn_network.hpp> #include <../graph_tools/graph_test_base.hpp> #include <shape_infer/mock_reshaper_launcher.hpp> #include <shape_infer/ie_reshaper.hpp> using namespace InferenceEngine; using namespace InferenceEngine::details; using namespace ShapeInfer; using namespace ::testing; using namespace ::GraphTest; class ReshaperTest : public GraphTestsBase { protected: class TestLauncherCreator : public LauncherCreator { public: struct Mocks { MockReshapeLauncher::Ptr launcher; MockInputController* iController; MockOutputController* oController; MockIShapeInferImpl::Ptr shapeInferImpl; Mocks(const MockReshapeLauncher::Ptr& _launcher, MockInputController* _iController, MockOutputController* _oController, const MockIShapeInferImpl::Ptr& _shapeInferImpl) : launcher(_launcher), iController(_iController), oController(_oController), shapeInferImpl(_shapeInferImpl) {} }; ReshapeLauncher::Ptr createNotInputLauncher(const CNNLayer* layer, const std::vector<IShapeInferExtensionPtr>& extensions) override { return createLauncher(layer); } ReshapeLauncher::Ptr createInputLauncher(const CNNLayer* layer, const std::vector<IShapeInferExtensionPtr>& extensions) override { return createLauncher(layer); } std::vector<Mocks> getMocks() { return _mocks; } private: ReshapeLauncher::Ptr createLauncher(const CNNLayer* layer) { auto initializer = std::make_shared<MockReshapeLauncher::TestLauncherInitializer>(); auto shapeInferImpl = std::make_shared<MockIShapeInferImpl>(); auto mockLauncher = std::make_shared<MockReshapeLauncher>(initializer, layer, shapeInferImpl); _mocks.emplace_back(mockLauncher, initializer->getInputController(), initializer->getOutputController(), shapeInferImpl); return mockLauncher; } private: std::vector<Mocks> _mocks; }; class TestEmptyLauncherCreator : public LauncherCreator { public: ReshapeLauncher::Ptr createNotInputLauncher(const CNNLayer* layer, const std::vector<IShapeInferExtensionPtr>& extensions) override { return std::make_shared<FakeReshapeLauncher>(layer, std::make_shared<MockIShapeInferImpl>());; } ReshapeLauncher::Ptr createInputLauncher(const CNNLayer* layer, const std::vector<IShapeInferExtensionPtr>& extensions) override { return std::make_shared<InputReshapeLauncher>(layer, std::make_shared<MockIShapeInferImpl>()); } }; void prepareInputs(InputsDataMap& inputsMap, int batchSize = 1) override { GraphTestsBase::prepareInputs(inputsMap); for (auto layer = lhsLayers.begin(); layer != lhsLayers.end(); layer++) { if ((*layer)->insData.empty()) { (*layer)->type = "Input"; } } } void SetUp() override { GraphTestsBase::SetUp(); impl = std::make_shared<MockIShapeInferImpl>(); CONNECT(0, 1); }; public: StatusCode sts = GENERAL_ERROR; ResponseDesc resp; static const std::string TEST_NAME; MockIShapeInferImpl::Ptr impl; ReshaperPtr reshaper; }; const std::string ReshaperTest::TEST_NAME = "TEST_NAME"; TEST_F(ReshaperTest, canCreateReshaper) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); Reshaper reshaper(mockNet); } TEST_F(ReshaperTest, throwOnAddNullExtension) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); Reshaper reshaper(mockNet); MockShapeInferExtension::Ptr extension; ASSERT_THROW(reshaper.AddExtension(extension), InferenceEngineException); } TEST_F(ReshaperTest, canAddExtensionWithNotRegistered) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); Reshaper reshaper(mockNet); auto extension = std::make_shared<MockShapeInferExtension>(); EXPECT_CALL(*extension.get(), getShapeInferTypes(_, _, _)).WillOnce(DoAll( WithArg<0>(Invoke([&](char**& type) { type = new char*[1]; type[0] = new char[TEST_NAME.size() + 1]; std::copy(TEST_NAME.begin(), TEST_NAME.end(), type[0]); type[0][TEST_NAME.size()] = '\0'; })), WithArg<1>(Invoke([&](unsigned int& size) { size = 1; })), Return(OK))); reshaper.AddExtension(extension); } TEST_F(ReshaperTest, throwOnExtensionWithAlreadyRegisteredImpl) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); Reshaper reshaper(mockNet); auto extension = std::make_shared<MockShapeInferExtension>(); std::string conv_name = "Convolution"; EXPECT_CALL(*extension.get(), getShapeInferTypes(_, _, _)).WillOnce(DoAll( WithArg<0>(Invoke([&](char**& type) { type = new char*[2]; type[0] = new char[TEST_NAME.size() + 1]; std::copy(TEST_NAME.begin(), TEST_NAME.end(), type[0]); type[0][TEST_NAME.size()] = '\0'; type[1] = new char[conv_name.size() + 1]; std::copy(conv_name.begin(), conv_name.end(), type[1]); type[1][conv_name.size()] = '\0'; })), WithArg<1>(Invoke([&](unsigned int& size) { size = 2; })), Return(OK))); ASSERT_THROW(reshaper.AddExtension(extension), InferenceEngineException); } TEST_F(ReshaperTest, canResetOnReshape) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); auto testCreator = std::make_shared<TestLauncherCreator>(); Reshaper reshaper(mockNet, testCreator); auto mocks = testCreator->getMocks(); auto inputMock = mocks[0]; EXPECT_CALL(*(inputMock.launcher).get(), setShapeByName(_, _)); for (auto it:mocks) { EXPECT_CALL(*(it.launcher).get(), getLayerName()).WillRepeatedly(Return(it.launcher->realGetLayerName())); EXPECT_CALL(*(it.launcher).get(), reset()); EXPECT_CALL(*(it.launcher).get(), reshape(_)); EXPECT_CALL(*(it.launcher).get(), applyChanges(_)); } auto extension = std::make_shared<MockShapeInferExtension>(); EXPECT_CALL(*extension.get(), getShapeInferTypes(_, _, _)).WillOnce(DoAll( WithArg<0>(Invoke([&](char**& type) { type = new char*[1]; type[0] = new char[TEST_NAME.size() + 1]; std::copy(TEST_NAME.begin(), TEST_NAME.end(), type[0]); type[0][TEST_NAME.size()] = '\0'; })), WithArg<1>(Invoke([&](unsigned int& size) { size = 1; })), Return(OK))); reshaper.AddExtension(extension); reshaper.run({{"0", {2}}}); } TEST_F(ReshaperTest, canUpdateFakeImpl) { EXPECT_CALL(mockNet, getInputsInfo(_)).WillRepeatedly(WithArg<0>(Invoke([&](InputsDataMap& maps) { prepareInputs(maps); }))); auto testCreator = std::make_shared<TestEmptyLauncherCreator>(); Reshaper reshaper(mockNet, testCreator); auto newImpl = std::make_shared<MockIShapeInferImpl>(); const char* registered[] = {""}; auto extension = std::make_shared<MockShapeInferExtension>(); EXPECT_CALL(*extension.get(), getShapeInferTypes(_, _, _)).WillOnce(DoAll( WithArg<0>(Invoke([&](char**& type) { type = new char*[1]; type[0] = new char[1]; type[0][0] = '\0'; })), WithArg<1>(Invoke([&](unsigned int& size) { size = 1; })), Return(OK))); EXPECT_CALL(*extension.get(), getShapeInferImpl(_, _, _)).WillOnce(DoAll( WithArg<0>(Invoke([&](IShapeInferImpl::Ptr& impl) { impl = newImpl; })), Return(OK))); reshaper.AddExtension(extension); EXPECT_CALL(*newImpl.get(), inferShapes(_, _, _, _, _)). WillOnce(DoAll( WithArg<3>(Invoke([&](std::vector<SizeVector>& outShape) { outShape.push_back({1, 2}); })), Return(OK))); reshaper.run({{"0", {1, 2}}}); }
40.302752
120
0.633394
[ "vector" ]
05711b26b1e782c892ec06a60500ace1a4144722
9,587
cc
C++
DQM/HLTEvF/plugins/LumiMonitor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/HLTEvF/plugins/LumiMonitor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/HLTEvF/plugins/LumiMonitor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "DQM/HLTEvF/plugins/LumiMonitor.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DQM/TrackingMonitor/interface/GetLumi.h" // ----------------------------- // constructors and destructor // ----------------------------- LumiMonitor::LumiMonitor( const edm::ParameterSet& iConfig ) : folderName_ ( iConfig.getParameter<std::string>("FolderName") ) , lumiScalersToken_ ( consumes<LumiScalersCollection>(iConfig.getParameter<edm::InputTag>("scalers") ) ) , lumi_binning_ ( getHistoPSet (iConfig.getParameter<edm::ParameterSet>("histoPSet").getParameter<edm::ParameterSet>("lumiPSet")) ) , ls_binning_ ( getHistoLSPSet(iConfig.getParameter<edm::ParameterSet>("histoPSet").getParameter<edm::ParameterSet>("lsPSet")) ) , doPixelLumi_ ( iConfig.getParameter<bool>("doPixelLumi") ) , pixelClustersToken_ ( doPixelLumi_ ? consumes<edmNew::DetSetVector<SiPixelCluster> >(iConfig.getParameter<edm::InputTag>("pixelClusters") ) : edm::EDGetTokenT<edmNew::DetSetVector<SiPixelCluster>> () ) , useBPixLayer1_ ( doPixelLumi_ ? iConfig.getParameter<bool> ("useBPixLayer1") : false ) , minNumberOfPixelsPerCluster_ ( doPixelLumi_ ? iConfig.getParameter<int> ("minNumberOfPixelsPerCluster") : -1 ) , minPixelClusterCharge_ ( doPixelLumi_ ? iConfig.getParameter<double> ("minPixelClusterCharge") : -1. ) , pixelCluster_binning_ ( doPixelLumi_ ? getHistoPSet (iConfig.getParameter<edm::ParameterSet>("histoPSet").getParameter<edm::ParameterSet>("pixelClusterPSet")) : MEbinning {} ) , pixellumi_binning_ ( doPixelLumi_ ? getHistoPSet (iConfig.getParameter<edm::ParameterSet>("histoPSet").getParameter<edm::ParameterSet>("pixellumiPSet")) : MEbinning {} ) { numberOfPixelClustersVsLS_ = nullptr; numberOfPixelClustersVsLumi_ = nullptr; lumiVsLS_ = nullptr; pixelLumiVsLS_ = nullptr; pixelLumiVsLumi_ = nullptr; if(useBPixLayer1_) lumi_factor_per_bx_ = GetLumi::FREQ_ORBIT * GetLumi::SECONDS_PER_LS / GetLumi::XSEC_PIXEL_CLUSTER ; else lumi_factor_per_bx_ = GetLumi::FREQ_ORBIT * GetLumi::SECONDS_PER_LS / GetLumi::rXSEC_PIXEL_CLUSTER ; } MEbinning LumiMonitor::getHistoPSet(edm::ParameterSet pset) { return MEbinning{ pset.getParameter<int32_t>("nbins"), pset.getParameter<double>("xmin"), pset.getParameter<double>("xmax"), }; } MEbinning LumiMonitor::getHistoLSPSet(edm::ParameterSet pset) { return MEbinning{ pset.getParameter<int32_t>("nbins"), 0., double(pset.getParameter<int32_t>("nbins")) }; } void LumiMonitor::bookHistograms(DQMStore::IBooker & ibooker, edm::Run const & iRun, edm::EventSetup const & iSetup) { std::string histname, histtitle; std::string currentFolder = folderName_ ; ibooker.setCurrentFolder(currentFolder.c_str()); if ( doPixelLumi_ ) { histname = "numberOfPixelClustersVsLS"; histtitle = "number of pixel clusters vs LS"; numberOfPixelClustersVsLS_ = ibooker.book1D(histname, histtitle, ls_binning_.nbins, ls_binning_.xmin, ls_binning_.xmax); // numberOfPixelClustersVsLS_->getTH1()->SetCanExtend(TH1::kAllAxes); numberOfPixelClustersVsLS_->setAxisTitle("LS",1); numberOfPixelClustersVsLS_->setAxisTitle("number of pixel clusters",2); histname = "numberOfPixelClustersVsLumi"; histtitle = "number of pixel clusters vs scal lumi"; numberOfPixelClustersVsLumi_ = ibooker.bookProfile(histname, histtitle, lumi_binning_.nbins, lumi_binning_.xmin, lumi_binning_.xmax, pixelCluster_binning_.xmin,pixelCluster_binning_.xmax); numberOfPixelClustersVsLumi_->setAxisTitle("scal inst lumi E30 [Hz cm^{-2}]",1); numberOfPixelClustersVsLumi_->setAxisTitle("number of pixel clusters",2); histname = "pixelLumiVsLS"; histtitle = "pixel-lumi vs LS"; pixelLumiVsLS_ = ibooker.bookProfile(histname, histtitle, ls_binning_.nbins, ls_binning_.xmin, ls_binning_.xmax, pixellumi_binning_.xmin,pixellumi_binning_.xmax); // pixelLumiVsLS_->getTH1()->SetCanExtend(TH1::kAllAxes); pixelLumiVsLS_->setAxisTitle("LS",1); pixelLumiVsLS_->setAxisTitle("pixel-based inst lumi E30 [Hz cm^{-2}]",2); histname = "pixelLumiVsLumi"; histtitle = "pixel-lumi vs scal lumi"; pixelLumiVsLumi_ = ibooker.bookProfile(histname, histtitle, lumi_binning_.nbins,lumi_binning_.xmin,lumi_binning_.xmax, pixellumi_binning_.xmin,lumi_binning_.xmax); pixelLumiVsLumi_->setAxisTitle("scal inst lumi E30 [Hz cm^{-2}]",1); pixelLumiVsLumi_->setAxisTitle("pixel-based inst lumi E30 [Hz cm^{-2}]",2); } histname = "lumiVsLS"; histtitle = "scal lumi vs LS"; lumiVsLS_ = ibooker.bookProfile(histname, histtitle, ls_binning_.nbins, ls_binning_.xmin, ls_binning_.xmax, lumi_binning_.xmin, lumi_binning_.xmax); // lumiVsLS_->getTH1()->SetCanExtend(TH1::kAllAxes); lumiVsLS_->setAxisTitle("LS",1); lumiVsLS_->setAxisTitle("scal inst lumi E30 [Hz cm^{-2}]",2); } #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" void LumiMonitor::analyze(edm::Event const& iEvent, edm::EventSetup const& iSetup) { // int bx = iEvent.bunchCrossing(); int ls = iEvent.id().luminosityBlock(); float scal_lumi = -1.; edm::Handle<LumiScalersCollection> lumiScalers; iEvent.getByToken(lumiScalersToken_, lumiScalers); if ( lumiScalers.isValid() && lumiScalers->size() ) { LumiScalersCollection::const_iterator scalit = lumiScalers->begin(); scal_lumi = scalit->instantLumi(); } else { scal_lumi = -1.; } lumiVsLS_ -> Fill(ls, scal_lumi); if ( doPixelLumi_ ) { size_t pixel_clusters = 0; float pixel_lumi = -1.; edm::Handle< edmNew::DetSetVector<SiPixelCluster> > pixelClusters; iEvent.getByToken(pixelClustersToken_, pixelClusters); if ( pixelClusters.isValid() ) { edm::ESHandle<TrackerTopology> tTopoHandle; iSetup.get<TrackerTopologyRcd>().get(tTopoHandle); const TrackerTopology* const tTopo = tTopoHandle.product(); // Count the number of clusters with at least a minimum // number of pixels per cluster and at least a minimum charge. size_t tot = 0; edmNew::DetSetVector<SiPixelCluster>::const_iterator pixCluDet = pixelClusters->begin(); for ( ; pixCluDet!=pixelClusters->end(); ++pixCluDet) { DetId detid = pixCluDet->detId(); size_t subdetid = detid.subdetId(); if ( subdetid == (int) PixelSubdetector::PixelBarrel ) if ( tTopo->layer(detid)==1 ) continue; edmNew::DetSet<SiPixelCluster>::const_iterator pixClu = pixCluDet->begin(); for ( ; pixClu != pixCluDet->end(); ++pixClu ) { ++tot; if ( (pixClu->size() >= minNumberOfPixelsPerCluster_) && (pixClu->charge() >= minPixelClusterCharge_ ) ) { ++pixel_clusters; } } } pixel_lumi = lumi_factor_per_bx_ * pixel_clusters / GetLumi::CM2_TO_NANOBARN ; // ?!?! } else pixel_lumi = -1.; numberOfPixelClustersVsLS_ -> Fill(ls, pixel_clusters); numberOfPixelClustersVsLumi_ -> Fill(scal_lumi,pixel_clusters); pixelLumiVsLS_ -> Fill(ls, pixel_lumi); pixelLumiVsLumi_ -> Fill(scal_lumi,pixel_lumi); } } void LumiMonitor::fillHistoPSetDescription(edm::ParameterSetDescription & pset) { pset.add<int> ( "nbins"); pset.add<double>( "xmin" ); pset.add<double>( "xmax" ); } void LumiMonitor::fillHistoLSPSetDescription(edm::ParameterSetDescription & pset) { pset.add<int> ( "nbins", 2500); } void LumiMonitor::fillDescriptions(edm::ConfigurationDescriptions & descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>( "pixelClusters", edm::InputTag("hltSiPixelClusters") ); desc.add<edm::InputTag>( "scalers", edm::InputTag("hltScalersRawToDigi")); desc.add<std::string> ( "FolderName", "HLT/LumiMonitoring" ); desc.add<bool> ( "doPixelLumi", false ); desc.add<bool> ( "useBPixLayer1", false ); desc.add<int> ( "minNumberOfPixelsPerCluster", 2 ); // from DQM/PixelLumi/python/PixelLumiDQM_cfi.py desc.add<double> ( "minPixelClusterCharge", 15000. ); edm::ParameterSetDescription histoPSet; edm::ParameterSetDescription pixelClusterPSet; LumiMonitor::fillHistoPSetDescription(pixelClusterPSet); histoPSet.add("pixelClusterPSet", pixelClusterPSet); edm::ParameterSetDescription lumiPSet; fillHistoPSetDescription(lumiPSet); histoPSet.add<edm::ParameterSetDescription>("lumiPSet", lumiPSet); edm::ParameterSetDescription pixellumiPSet; fillHistoPSetDescription(pixellumiPSet); histoPSet.add<edm::ParameterSetDescription>("pixellumiPSet", pixellumiPSet); edm::ParameterSetDescription lsPSet; fillHistoLSPSetDescription(lsPSet); histoPSet.add<edm::ParameterSetDescription>("lsPSet", lsPSet); desc.add<edm::ParameterSetDescription>("histoPSet",histoPSet); descriptions.add("lumiMonitor", desc); } // Define this as a plug-in #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(LumiMonitor);
43.577273
215
0.686346
[ "geometry" ]
057c1b5e82e75b3298a0cb31ebcf39bd6d981f5b
558
hpp
C++
coding-interviews/jump_floor_ii_9.hpp
lonelyhentai/nowcoder-collection
db795a5349b59f8cbb69e974adbb90ad30912558
[ "WTFPL" ]
1
2020-03-08T13:54:54.000Z
2020-03-08T13:54:54.000Z
coding-interviews/jump_floor_ii_9.hpp
lonelyhentai/nowcoder-collection
db795a5349b59f8cbb69e974adbb90ad30912558
[ "WTFPL" ]
null
null
null
coding-interviews/jump_floor_ii_9.hpp
lonelyhentai/nowcoder-collection
db795a5349b59f8cbb69e974adbb90ad30912558
[ "WTFPL" ]
null
null
null
// [变态跳台阶](https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387) #pragma once #include <vector> #define let const auto namespace task9 { using namespace std; class Solution { public: int jumpFloorII(int number) { auto dp = vector<int>(number+1, 0); dp[0] = 1; for(auto i=0;i<number;i++) { let now = dp[i]; for(auto j=1;j<=number-i;j++) { dp[i+j] += now; } } return dp[number]; } }; }
25.363636
78
0.483871
[ "vector" ]
0585804e9feff63b7d3d5ee66433b3c37355ec3d
1,758
hh
C++
graph/graph.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
6
2020-03-19T04:16:02.000Z
2022-03-30T15:41:39.000Z
graph/graph.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
1
2020-05-20T12:05:49.000Z
2021-11-14T13:39:23.000Z
graph/graph.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
null
null
null
#ifndef GRAPH_HH #define GRAPH_HH #include "display.hh" #include "cairo_objects.hh" class Graph { Display display_; Cairo cairo_; Pango pango_; Pango::Font tick_font_; Pango::Font label_font_; struct YLabel { int height; Pango::Text text; float intensity; }; std::deque<std::pair<int, Pango::Text>> x_tick_labels_; std::vector<YLabel> y_tick_labels_; std::vector<std::tuple<float, float, float, float>> colors_; std::vector<std::deque<std::pair<float, float>>> data_points_; Pango::Text x_label_; Pango::Text y_label_; std::string info_string_; Pango::Text info_; float bottom_, top_; float project_height( const float x ) const { return ( x - bottom_ ) / ( top_ - bottom_ ); } float chart_height( const float x, const unsigned int window_height ) const { return (window_height - 40) * (.825*(1-project_height( x ))+.025) + (.825 * 40); } Cairo::Pattern horizontal_fadeout_; public: Graph( const unsigned int num_lines, const unsigned int initial_width, const unsigned int initial_height, const std::string & title, const float min_y, const float max_y ); void set_window( const float t, const float logical_width ); void add_data_point( const unsigned int num, const float t, const float y ) { if ( not data_points_.at( num ).empty() ) { if ( y == data_points_.at( num ).back().second ) { return; } } data_points_.at( num ).emplace_back( t, y ); } void set_color( const unsigned int num, const float red, const float green, const float blue, const float alpha ); bool blocking_draw( const float t, const float logical_width, const float min_y, const float max_y ); void set_info( const std::string & info ); }; #endif /* GRAPH_HH */
25.478261
103
0.684869
[ "vector" ]
058a9f91babd854bb1c61e8e7d7cdf8983f73ada
5,225
cpp
C++
modules/task_2/voronin_a_vertical_gaussian_method/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
1
2020-10-30T13:49:58.000Z
2020-10-30T13:49:58.000Z
modules/task_2/voronin_a_vertical_gaussian_method/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/voronin_a_vertical_gaussian_method/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 Voronin Aleksey #include <gtest-mpi-listener.hpp> #include <gtest/gtest.h> #include <cmath> #include <vector> #include "./vertical_gaussian_method.h" TEST(Parallel_Operations_MPI, can_get_random_linear_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = 3; ASSERT_NO_THROW(getRandomMatrixLinear(rows)); } } TEST(Parallel_Operations_MPI, can_get_result_with_random_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = 5; std::vector<double> sample_matrix = getRandomMatrixLinear(rows); ASSERT_NO_THROW(sequentialGaussianMethod(sample_matrix, rows)); } } TEST(Parallel_Operations_MPI, can_get_result_with_sequential_version_three_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = 3; std::vector<double> sample_matrix = {2, 1, 1, 2, 1, -1, 0, -2, 3, -1, 2, 2}; std::vector<double> result = sequentialGaussianMethod(sample_matrix, rows); std::vector<double> expectedResult = {-1, 1, 3}; ASSERT_EQ(result, expectedResult); } } TEST(Parallel_Operations_MPI, can_get_result_with_sequential_version_two_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = 2; std::vector<double> sample_matrix = {1, -1, -5, 2, 1, -7}; std::vector<double> result = sequentialGaussianMethod(sample_matrix, rows); std::vector<double> expectedResult = {-4, 1}; ASSERT_EQ(result, expectedResult); } } TEST(Parallel_Operations_MPI, cant_get_result_with_wrong_input) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = 4; std::vector<double> sample_matrix = {1, -1, -5, 2, 1, -7}; std::vector<double> result = sequentialGaussianMethod(sample_matrix, rows); ASSERT_EQ(result.size(), (unsigned int) 0); } } TEST(Parallel_Operations_MPI, cant_get_result_with_negative_input) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { const int rows = -1; std::vector<double> sample_matrix = {1, -1, -5, 2, 1, -7}; std::vector<double> result = sequentialGaussianMethod(sample_matrix, rows); ASSERT_EQ(result.size(), (unsigned int) 0); } } TEST(Parallel_Operations_MPI, can_get_result_with_parallel_version_two_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int rows = 2; std::vector<double> sample_matrix = {1, -1, -5, 2, 1, -7}; std::vector<double> values = parallelGaussianMethod(sample_matrix, rows); if (rank == 0) { std::vector<double> expectedResult = {-4, 1}; ASSERT_EQ(values, expectedResult); } } TEST(Parallel_Operations_MPI, can_get_result_with_parallel_version_three_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int rows = 3; std::vector<double> sample_matrix = {2, 1, 1, 2, 1, -1, 0, -2, 3, -1, 2, 2}; std::vector<double> result = parallelGaussianMethod(sample_matrix, rows); if (rank == 0) { std::vector<double> expectedResult = {-1, 1, 3}; for (size_t i = 0; i < 3; i++) { ASSERT_NEAR(result[i], expectedResult[i], 0.1); } } } TEST(Parallel_Operations_MPI, can_get_result_with_parallel_version_random_matrix_three_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int rows = 3; std::vector<double> sample_matrix = getRandomMatrixLinear(rows); ASSERT_NO_THROW(parallelGaussianMethod(sample_matrix, rows)); } TEST(Parallel_Operations_MPI, can_compare_result_with_parallel_version_random_matrix_three_unknowns) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int rows = 3; std::vector<double> sample_matrix = getRandomMatrixLinear(rows); std::vector<double> values = parallelGaussianMethod(sample_matrix, rows); if (rank == 0) { std::vector<double> expectedResult = calculateResults(sample_matrix, rows, values); for (size_t i = 0; i < rows; i++) { if (std::isnan(expectedResult[i])) { break; } ASSERT_NEAR(sample_matrix[(rows+1)*i+rows], expectedResult[i], 0.1); } } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
33.709677
102
0.621244
[ "vector" ]
058bcc8155802ddd94b1fe16606f686c45d87991
2,852
cpp
C++
drlDLL/drlDLL/graphnn/src/nn/binary_logloss.cpp
songwenas12/csp-drl
dcc2320b08c397a9561242de4e24b569b71752fa
[ "Apache-2.0" ]
3
2021-12-11T12:30:09.000Z
2021-12-30T09:49:45.000Z
drlDLL/drlDLL/graphnn/src/nn/binary_logloss.cpp
songwenas12/csp-drl
dcc2320b08c397a9561242de4e24b569b71752fa
[ "Apache-2.0" ]
null
null
null
drlDLL/drlDLL/graphnn/src/nn/binary_logloss.cpp
songwenas12/csp-drl
dcc2320b08c397a9561242de4e24b569b71752fa
[ "Apache-2.0" ]
null
null
null
#include "nn/binary_logloss.h" #include <cmath> namespace gnn { template<typename Dtype> void CalcBinaryLogLoss(DTensor<CPU, Dtype>& prob, DTensor<CPU, Dtype>& label, DTensor<CPU, Dtype>& out) { //ASSERT(prob.cols() == label.cols(), "# columns should match"); out.Reshape({prob.rows(), prob.cols()}); for (size_t i = 0; i < prob.rows(); ++i) { for (size_t j = 0; j < prob.cols(); ++j) { auto& y = label.data->ptr[i * prob.cols() + j]; auto& p = prob.data->ptr[i * prob.cols() + j]; out.data->ptr[i * prob.cols() + j] = -y * log(p + 1e-9) - (1 - y) * log(1 - p + 1e-9); } } } template<typename mode, typename Dtype> BinaryLogLoss<mode, Dtype>::BinaryLogLoss(std::string _name, bool _need_sigmoid, PropErr _properr) : Factor(_name, _properr), need_sigmoid(_need_sigmoid) { } template<typename mode, typename Dtype> void BinaryLogLoss<mode, Dtype>::Forward(std::vector< std::shared_ptr<Variable> >& operands, std::vector< std::shared_ptr<Variable> >& outputs, Phase phase) { //ASSERT(operands.size() == 2, "unexpected input size for " << StrType()); //ASSERT(outputs.size() == 1, "unexpected output size for " << StrType()); auto& output = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->value; auto& raw_pred = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[0].get())->value; auto& label = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[1].get())->value; auto& probs = need_sigmoid ? tmp_probs : raw_pred; if (need_sigmoid) { probs.CopyFrom(raw_pred); probs.Sigmoid(); } CalcBinaryLogLoss(probs, label, output); } template<typename mode, typename Dtype> void BinaryLogLoss<mode, Dtype>::Backward(std::vector< std::shared_ptr<Variable> >& operands, std::vector< bool >& isConst, std::vector< std::shared_ptr<Variable> >& outputs) { //ASSERT(operands.size() == 2, "unexpected input size for " << StrType()); //ASSERT(outputs.size() == 1, "unexpected output size for " << StrType()); if (isConst[0]) return; auto& raw_pred = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[0].get())->value; auto& label = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[1].get())->value; auto& probs = need_sigmoid ? tmp_probs : raw_pred; auto grad_out = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->grad.Full(); auto grad_lhs = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[0].get())->grad.Full(); if (need_sigmoid) { probs.Axpy(-1.0, label); probs.ElewiseMul(grad_out); grad_lhs.Axpy(1.0, probs); } else { DTensor<mode, Dtype> tmp; tmp.CopyFrom(probs); tmp.Axpy(-1.0, label); tmp.ElewiseDiv(probs); probs.Scale(-1.0); probs.Add(1.0); tmp.ElewiseDiv(probs); tmp.ElewiseMul(grad_out); grad_lhs.Axpy(1.0, tmp); } } INSTANTIATE_CLASS(BinaryLogLoss) }
31.688889
103
0.648317
[ "vector" ]
058dd6907f90e9e0067372b5f84879166c2d8e9a
4,205
cc
C++
src/solvers/EigenvalueManager.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/solvers/EigenvalueManager.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/solvers/EigenvalueManager.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*----------------------------------// /** * @file EigenvalueManager.cc * @brief EigenvalueManager class definition * @note Copyright(C) 2012-2013 Jeremy Roberts */ //---------------------------------------------------------------------------// #include "EigenvalueManager.hh" #include "angle/QuadratureFactory.hh" #include "boundary/BoundaryDiffusion.hh" #include "boundary/BoundaryMOC.hh" #include "boundary/BoundarySN.hh" #include "geometry/Tracker.hh" // Eigenvalue solvers #include "solvers/eigen/EigenPI.hh" #include "solvers/eigen/EigenDiffusion.hh" #include "solvers/eigen/EigenArnoldi.hh" #include "solvers/eigen/EigenGD.hh" #include "solvers/eigen/EigenCMFD.hh" #include <string> namespace detran { using std::cout; using std::endl; //---------------------------------------------------------------------------// template <class D> EigenvalueManager<D>::EigenvalueManager(int argc, char *argv[], SP_input input, SP_material material, SP_mesh mesh) : TransportManager(argc, argv) , d_adjoint(false) , d_discretization(0) , d_is_setup(false) { Require(input); Require(material); Require(mesh); /// Create the fixed source manager d_mg_solver = new FixedSourceManager<D>(input, material, mesh, false, true); d_mg_solver->setup(); d_mg_solver->set_solver(); d_discretization = d_mg_solver->discretization(); Ensure(d_mg_solver); } //---------------------------------------------------------------------------// template <class D> EigenvalueManager<D>::EigenvalueManager(SP_input input, SP_material material, SP_mesh mesh) : d_adjoint(false) , d_discretization(0) , d_is_setup(false) { Require(input); Require(material); Require(mesh); /// Create the fixed source manager d_mg_solver = new FixedSourceManager<D>(input, material, mesh, false, true); d_mg_solver->setup(); d_mg_solver->set_solver(); d_discretization = d_mg_solver->discretization(); Ensure(d_mg_solver); } //---------------------------------------------------------------------------// template <class D> bool EigenvalueManager<D>::solve() { std::cout << "Solving eigenvalue problem..." << std::endl; std::string eigen_solver = "PI"; if (d_mg_solver->input()->check("eigen_solver")) { eigen_solver = d_mg_solver->input()->template get<std::string>("eigen_solver"); } if (eigen_solver == "PI") { d_solver = new EigenPI<D>(d_mg_solver); } else if (eigen_solver == "diffusion") { if (d_discretization != Fixed_T::DIFF) { std::cout << "Diffusion eigensolver requires diffusion discretization." << std::endl; return false; } d_solver = new EigenDiffusion<D>(d_mg_solver); } else if (eigen_solver == "arnoldi") { d_solver = new EigenArnoldi<D>(d_mg_solver); } else if (eigen_solver == "cmfd") { d_solver = new EigenCMFD<D>(d_mg_solver); } else if (eigen_solver == "GD") { std::cout << " GD-----> " << std::endl; if (d_discretization == Fixed_T::DIFF) { cout << "GD not applicable for diffusion. Use the diffusion" << endl; cout << "eigensolver and select gd from callow to use the " << endl; cout << "built-in implementation or use the SLEPc version. " << endl; return false; } d_solver = new EigenGD<D>(d_mg_solver); } else { std::cout << "Unsupported outer_solver type selected:" << eigen_solver << std::endl; return false; } // Solve the eigenvalue problem d_solver->solve(); return true; } //---------------------------------------------------------------------------// // Explicit instantiations //---------------------------------------------------------------------------// SOLVERS_INSTANTIATE_EXPORT(EigenvalueManager<_1D>) SOLVERS_INSTANTIATE_EXPORT(EigenvalueManager<_2D>) SOLVERS_INSTANTIATE_EXPORT(EigenvalueManager<_3D>) } // end namespace detran
28.605442
79
0.552438
[ "mesh", "geometry" ]
05914a4f3ebcbcddcc3894aa3f05ab5baadc0fe9
4,640
cpp
C++
src/cpp/src/Capture.cpp
vmlaker/wabbit
49d7e2ae6d476c809131aab8cc4df21a91ebed06
[ "MIT" ]
2
2015-04-23T05:40:53.000Z
2017-09-27T17:34:04.000Z
src/cpp/src/Capture.cpp
vmlaker/wabbit
49d7e2ae6d476c809131aab8cc4df21a91ebed06
[ "MIT" ]
null
null
null
src/cpp/src/Capture.cpp
vmlaker/wabbit
49d7e2ae6d476c809131aab8cc4df21a91ebed06
[ "MIT" ]
null
null
null
/** * Capture.cpp */ #include <iomanip> #include <stdexcept> // std::invalid_argument #include <bites.hpp> #include <boost/filesystem.hpp> #include "Capture.hpp" namespace wabbit { Capture::Capture( bites::Config& config, const int& duration, std::ostream* output_stream ) : Node( output_stream ), m_config( config ), m_duration( duration ), m_video_capture(), m_rate_ticker({1, 5, 10}) { // Attempt to open device given as integer. // If that fails, attempt to resolve the device as a path. int device = -1; try{ device = stod( m_config["device"] ); } catch( std::invalid_argument){ boost::filesystem::path path( m_config["device"] ); // Resolve symbolic link. auto target = boost::filesystem::canonical(path).string(); // Extract the number ABC from string /dev/videoABC auto length = std::string( "/dev/video" ).length(); auto number = target.substr( length ); device = std::stod( number ); } vout() << "device: " << device << std::endl; // Setup the OpenCV VideoCapture object. m_video_capture.open( device ); vout() << "is opened: " << m_video_capture.isOpened() << std::endl; m_video_capture.set( 3, stod( m_config["width"] )); m_video_capture.set( 4, stod( m_config["height"] )); // Compute interval needed to observe maximum FPS limit. float max_fps = stof( m_config["max_fps"] ); max_fps = max_fps >= 0 ? max_fps : std::numeric_limits<float>::max(); float interval_seconds = 1 / max_fps; int interval_ms = interval_seconds * 1000000; m_min_interval = std::chrono::microseconds( interval_ms ); // Set the minimum read time for detecting camera disconnect. m_min_read = stof( m_config["min_read"] ); m_prev_time = std::chrono::system_clock::now(); m_end_time = m_prev_time + std::chrono::seconds( m_duration ); } Capture::Capture( const Capture& capture ) : Node( capture ), m_config( capture.m_config ), m_duration( capture.m_duration ), m_video_capture( capture.m_video_capture ), m_rate_ticker( capture.m_rate_ticker ), m_prev_time( capture.m_prev_time ), m_end_time( capture.m_end_time ), m_min_interval( capture.m_min_interval ), m_min_read( capture.m_min_read ) {} std::vector <float> Capture::getFramerate () { return m_framerate.get(); } bool Capture::operator()( wabbit::ImageAndTime& image_and_time ) { if( !m_video_capture.isOpened() ){ return false; } if( m_end_time <= std::chrono::system_clock::now() and m_duration >= 0 ){ return false; } // Insert delay to observe maximum framerate limit. auto elapsed = std::chrono::system_clock::now() - m_prev_time; auto elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); auto sleep_ms = m_min_interval - elapsed_ms; sleep_ms = sleep_ms.count() < 0 ? std::chrono::microseconds(0) : sleep_ms; usleep( sleep_ms.count()); // Take a snapshot. // The only way I could detect camera disconnect was by // thresholding the length of time to call read() method. // For some reason return value of read() is always True, // even after disconnecting the camera. m_prev_time = std::chrono::system_clock::now(); m_video_capture >> image_and_time.image; // Read the image. elapsed = std::chrono::system_clock::now() - m_prev_time; image_and_time.time = m_prev_time; image_and_time.sequence++; elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); if( elapsed_ms.count()/1000000. < m_min_read ) { // TODO: Write error to log instead of stdout. std::cout << "Error: Read time failed to meet threshold: " << std::endl; std::cout << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count() / 1000000. << " (readtime) < " << m_min_read << " (threshold)" << std::endl; std::cout << "Probably disconnected camera." << std::endl; return false; } // Set the framerate. auto fps = m_rate_ticker.tick(); m_framerate.set( fps ); image_and_time.framerate = fps; // Verbose-output the current framerate. vout() << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count()/1000000.; for(auto ii=begin( fps ); ii!=end( fps ); ++ii){ vout() << std::fixed << std::setw( 7 ) << std::setprecision( 2 ) << *ii; } vout() << std::endl; return true; } } // namespace wabbit.
34.37037
101
0.628017
[ "object", "vector" ]
059715b018c6ac74e8d17e2707accdb566b25fd6
4,895
hpp
C++
src/graphlab/parallel/atomic.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-08-01T06:32:58.000Z
2018-08-01T06:32:58.000Z
src/graphlab/parallel/atomic.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/parallel/atomic.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_ATOMIC_HPP #define GRAPHLAB_ATOMIC_HPP #include <stdint.h> namespace graphlab { /** * \brief atomic object toolkit * \ingroup util * A templated class for creating atomic numbers. */ template<typename T> class atomic{ public: /// The current value of the atomic number volatile T value; /// Creates an atomic number with value "value" atomic(const T& value = 0) : value(value) { } /// Performs an atomic increment by 1, returning the new value T inc() { return __sync_add_and_fetch(&value, 1); } /// Performs an atomic decrement by 1, returning the new value T dec() { return __sync_sub_and_fetch(&value, 1); } /// Performs an atomic increment by 'val', returning the new value T inc(T val) { return __sync_add_and_fetch(&value, val); } /// Performs an atomic decrement by 'val', returning the new value T dec(T val) { return __sync_sub_and_fetch(&value, val); } /// Performs an atomic increment by 1, returning the old value T inc_ret_last() { return __sync_fetch_and_add(&value, 1); } /// Performs an atomic decrement by 1, returning the old value T dec_ret_last() { return __sync_fetch_and_sub(&value, 1); } /// Performs an atomic increment by 'val', returning the old value T inc_ret_last(T val) { return __sync_fetch_and_add(&value, val); } /// Performs an atomic decrement by 'val', returning the new value T dec_ret_last(T val) { return __sync_fetch_and_sub(&value, val); } }; /** * \ingroup util atomic instruction that is equivalent to the following: \code if (a==oldval) { a = newval; return true; } else { return false; } \endcode */ template<typename T> bool atomic_compare_and_swap(T& a, const T &oldval, const T &newval) { return __sync_bool_compare_and_swap(&a, oldval, newval); }; /** * \ingroup util atomic instruction that is equivalent to the following: \code if (a==oldval) { a = newval; return true; } else { return false; } \endcode */ template<typename T> bool atomic_compare_and_swap(volatile T& a, const T &oldval, const T &newval) { return __sync_bool_compare_and_swap(&a, oldval, newval); }; /** * \ingroup util atomic instruction that is equivalent to the following: \code if (a==oldval) { a = newval; return true; } else { return false; } \endcode */ template <> inline bool atomic_compare_and_swap(double& a, const double &oldval, const double &newval) { return __sync_bool_compare_and_swap(reinterpret_cast<uint64_t*>(&a), *reinterpret_cast<const uint64_t*>(&oldval), *reinterpret_cast<const uint64_t*>(&newval)); }; /** * \ingroup util atomic instruction that is equivalent to the following: \code if (a==oldval) { a = newval; return true; } else { return false; } \endcode */ template <> inline bool atomic_compare_and_swap(float& a, const float &oldval, const float &newval) { return __sync_bool_compare_and_swap(reinterpret_cast<uint32_t*>(&a), *reinterpret_cast<const uint32_t*>(&oldval), *reinterpret_cast<const uint32_t*>(&newval)); }; /** * \ingroup util * \brief Atomically exchanges the values of a and b. */ template<typename T> void atomic_exchange(T& a, T& b) { b =__sync_lock_test_and_set(&a, b); }; /** * \ingroup util * \brief Atomically sets a to the newval, returning the old value */ template<typename T> T fetch_and_store(T& a, const T& newval) { return __sync_lock_test_and_set(&a, newval); }; } #endif
29.487952
91
0.598774
[ "object" ]
0598f02888843cbadde9649f529c7efd1e73c68e
10,922
cpp
C++
example/probe-demo/probe-demo.cpp
bcumming/arbor
3cc73f1eea296332e1308567e1b8a7ed41128355
[ "BSD-3-Clause" ]
null
null
null
example/probe-demo/probe-demo.cpp
bcumming/arbor
3cc73f1eea296332e1308567e1b8a7ed41128355
[ "BSD-3-Clause" ]
null
null
null
example/probe-demo/probe-demo.cpp
bcumming/arbor
3cc73f1eea296332e1308567e1b8a7ed41128355
[ "BSD-3-Clause" ]
null
null
null
#include <functional> #include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <tuple> #include <utility> #include <vector> #include <arbor/load_balance.hpp> #include <arbor/cable_cell.hpp> #include <arbor/morph/morphology.hpp> #include <arbor/morph/region.hpp> #include <arbor/simulation.hpp> #include <arbor/sampling.hpp> #include <arbor/util/any.hpp> #include <arbor/util/any_ptr.hpp> #include <tinyopt/smolopt.h> // Simulate a cell modelled as a simple cable with HH dynamics, // emitting the results of a user specified probe over time. using arb::util::any; using arb::util::any_cast; using arb::util::any_ptr; const char* help_msg = "[OPTION]... PROBE\n" "\n" " --dt=TIME set simulation dt to TIME [ms]\n" " --until=TIME simulate until TIME [ms]\n" " -n, --n-cv=N discretize with N CVs\n" " -t, --sample=TIME take a sample every TIME [ms]\n" " -x, --at=X take sample at relative position X along cable\n" " --exact use exact time sampling\n" " -h, --help print extended usage information and exit\n" "\n" "Simulate a simple 1 mm cable with HH dynamics, taking samples according\n" "to PROBE (see below). Unless otherwise specified, the simulation will\n" "use 10 CVs and run for 100 ms with a time step of 0.025 ms.\n" "\n" "Samples are by default taken every 1 ms; for probes that test a specific\n" "point on the cell, that point is 0.5 along the cable (i.e. 500 µm) unless\n" "specified with the --at option.\n" "\n" "PROBE is one of:\n" "\n" " v membrane potential [mV] at X\n" " i_axial axial (distal) current [nA] at X\n" " j_ion total ionic membrane current density [A/m²] at X\n" " j_na sodium ion membrane current density [A/m²] at X\n" " j_k potassium ion membrane current density [A/m²] at X\n" " c_na internal sodium concentration [mmol/L] at X\n" " c_k internal potassium concentration [mmol/L] at X\n" " hh_m HH state variable m at X\n" " hh_h HH state variable h at X\n" " hh_n HH state variable n at X\n" "\n" "where X is the relative position along the cable as described above, or else:\n" "\n" " all_v membrane potential [mV] in each CV\n" " all_i_ion total ionic membrane current [nA] in each CV\n" " all_i_na sodium ion membrane current [nA] in each CV\n" " all_i_k potassium ion membrane current [nA] in each CV\n" " all_i total membrane current [nA] in each CV\n" " all_c_na internal sodium concentration [mmol/L] in each CV\n" " all_c_k internal potassium concentration [mmol/L] in each CV\n" " all_hh_m HH state variable m in each CV\n" " all_hh_h HH state variable h in each CV\n" " all_hh_n HH state variable n in each CV\n"; struct options { double sim_end = 100.0; // [ms] double sim_dt = 0.025; // [ms] double sample_dt = 1.0; // [ms] unsigned n_cv = 10; bool exact = false; bool scalar_probe = true; any probe_addr; std::string value_name; }; const char* argv0 = ""; bool parse_options(options&, int& argc, char** argv); void vector_sampler(arb::probe_metadata, std::size_t, const arb::sample_record*); void scalar_sampler(arb::probe_metadata, std::size_t, const arb::sample_record*); struct cable_recipe: public arb::recipe { arb::cable_cell_global_properties gprop; any probe_addr; explicit cable_recipe(any probe_addr, unsigned n_cv): probe_addr(std::move(probe_addr)) { gprop.default_parameters = arb::neuron_parameter_defaults; gprop.default_parameters.discretization = arb::cv_policy_fixed_per_branch(n_cv); } arb::cell_size_type num_cells() const override { return 1; } arb::cell_size_type num_targets(arb::cell_gid_type) const override { return 0; } std::vector<arb::probe_info> get_probes(arb::cell_gid_type) const override { return {probe_addr}; // (use default tag value 0) } arb::cell_kind get_cell_kind(arb::cell_gid_type) const override { return arb::cell_kind::cable; } arb::util::any get_global_properties(arb::cell_kind) const override { return gprop; } arb::util::unique_any get_cell_description(arb::cell_gid_type) const override { using namespace arb; const double length = 1000; // [µm] const double diam = 1; // [µm] segment_tree tree; tree.append(arb::mnpos, {0, 0, 0, 0.5*diam}, {length, 0, 0, 0.5*diam}, 1); cable_cell c(tree); c.paint(reg::all(), "hh"); // HH mechanism over whole cell. c.place(mlocation{0, 0.}, i_clamp{0., INFINITY, 1.}); // Inject a 1 nA current indefinitely. return c; } }; int main(int argc, char** argv) { argv0 = argv[0]; try { options opt; if (!parse_options(opt, argc, argv)) { return 0; } cable_recipe R(opt.probe_addr, opt.n_cv); auto context = arb::make_context(); arb::simulation sim(R, arb::partition_load_balance(R, context), context); sim.add_sampler(arb::all_probes, arb::regular_schedule(opt.sample_dt), opt.scalar_probe? scalar_sampler: vector_sampler, opt.exact? arb::sampling_policy::exact: arb::sampling_policy::lax); // CSV header for sample output: std::cout << "t, " << (opt.scalar_probe? "x, ": "x0, x1, ") << opt.value_name << '\n'; sim.run(opt.sim_end, opt.sim_dt); } catch (to::option_error& e) { to::usage(argv0, "[OPTIONS]... PROBE\nTry '--help' for more information.", e.what()); return 1; } catch (std::exception& e) { std::cerr << "caught exception: " << e.what() << "\n"; return 2; } } void scalar_sampler(arb::probe_metadata pm, std::size_t n, const arb::sample_record* samples) { auto* loc = any_cast<const arb::mlocation*>(pm.meta); assert(loc); std::cout << std::fixed << std::setprecision(4); for (std::size_t i = 0; i<n; ++i) { auto* value = any_cast<const double*>(samples[i].data); assert(value); std::cout << samples[i].time << ", " << loc->pos << ", " << *value << '\n'; } } void vector_sampler(arb::probe_metadata pm, std::size_t n, const arb::sample_record* samples) { auto* cables_ptr = any_cast<const arb::mcable_list*>(pm.meta); assert(cables_ptr); unsigned n_cable = cables_ptr->size(); std::cout << std::fixed << std::setprecision(4); for (std::size_t i = 0; i<n; ++i) { auto* value_range = any_cast<const arb::cable_sample_range*>(samples[i].data); assert(value_range); assert(n_cable==value_range->second-value_range->first); for (unsigned j = 0; j<n_cable; ++j) { arb::mcable where = (*cables_ptr)[j]; std::cout << samples[i].time << ", " << where.prox_pos << ", " << where.dist_pos << ", " << value_range->first[j] << '\n'; } } } bool parse_options(options& opt, int& argc, char** argv) { using std::get; using namespace to; auto do_help = [&]() { usage(argv0, help_msg); }; using L = arb::mlocation; // Map probe argument to output variable name, scalarity, and a lambda that makes specific probe address from a location. std::pair<const char*, std::tuple<const char*, bool, std::function<any (double)>>> probe_tbl[] { // located probes {"v", {"v", true, [](double x) { return arb::cable_probe_membrane_voltage{L{0, x}}; }}}, {"i_axial", {"i_axial", true, [](double x) { return arb::cable_probe_axial_current{L{0, x}}; }}}, {"j_ion", {"j_ion", true, [](double x) { return arb::cable_probe_total_ion_current_density{L{0, x}}; }}}, {"j_na", {"j_na", true, [](double x) { return arb::cable_probe_ion_current_density{L{0, x}, "na"}; }}}, {"j_k", {"j_k", true, [](double x) { return arb::cable_probe_ion_current_density{L{0, x}, "k"}; }}}, {"c_na", {"c_na", true, [](double x) { return arb::cable_probe_ion_int_concentration{L{0, x}, "na"}; }}}, {"c_k", {"c_k", true, [](double x) { return arb::cable_probe_ion_int_concentration{L{0, x}, "k"}; }}}, {"hh_m", {"hh_m", true, [](double x) { return arb::cable_probe_density_state{L{0, x}, "hh", "m"}; }}}, {"hh_h", {"hh_h", true, [](double x) { return arb::cable_probe_density_state{L{0, x}, "hh", "h"}; }}}, {"hh_n", {"hh_n", true, [](double x) { return arb::cable_probe_density_state{L{0, x}, "hh", "n"}; }}}, // all-of-cell probes {"all_v", {"v", false, [](double) { return arb::cable_probe_membrane_voltage_cell{}; }}}, {"all_i_ion", {"i_ion", false, [](double) { return arb::cable_probe_total_ion_current_cell{}; }}}, {"all_i_na", {"i_na", false, [](double) { return arb::cable_probe_ion_current_cell{"na"}; }}}, {"all_i_k", {"i_k", false, [](double) { return arb::cable_probe_ion_current_cell{"k"}; }}}, {"all_i", {"i", false, [](double) { return arb::cable_probe_total_current_cell{}; }}}, {"all_c_na", {"c_na", false, [](double) { return arb::cable_probe_ion_int_concentration_cell{"na"}; }}}, {"all_c_k", {"c_k", false, [](double) { return arb::cable_probe_ion_int_concentration_cell{"k"}; }}}, {"all_hh_m", {"hh_m", false, [](double) { return arb::cable_probe_density_state_cell{"hh", "m"}; }}}, {"all_hh_h", {"hh_h", false, [](double) { return arb::cable_probe_density_state_cell{"hh", "h"}; }}}, {"all_hh_n", {"hh_n", false, [](double) { return arb::cable_probe_density_state_cell{"hh", "n"}; }}} }; std::tuple<const char*, bool, std::function<any (double)>> probe_spec; double probe_pos = 0.5; to::option cli_opts[] = { { to::action(do_help), to::flag, to::exit, "-h", "--help" }, { {probe_spec, to::keywords(probe_tbl)}, to::single }, { opt.sim_dt, "--dt" }, { opt.sim_end, "--until" }, { opt.sample_dt, "-t", "--sample" }, { probe_pos, "-x", "--at" }, { opt.n_cv, "-n", "--n-cv" }, { to::set(opt.exact), to::flag, "--exact" } }; if (!to::run(cli_opts, argc, argv+1)) return false; if (!get<2>(probe_spec)) throw to::user_option_error("missing PROBE"); if (argv[1]) throw to::user_option_error("unrecognized option"); opt.value_name = get<0>(probe_spec); opt.scalar_probe = get<1>(probe_spec); opt.probe_addr = get<2>(probe_spec)(probe_pos); return true; }
42.831373
125
0.590734
[ "vector" ]
059a393845c183a7649246c6a299c04f91820666
1,335
cpp
C++
uva/634 - Polygon_2.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
uva/634 - Polygon_2.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
uva/634 - Polygon_2.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct Point { double x; double y; }; vector<Point> polygon; bool insidePolygon(Point p) { int i,j; int vertexNum = polygon.size(); j = vertexNum-1; bool result = false; for(i = 0 ; i < vertexNum ; i++) { if(((p.y < polygon[i].y) && (p.y >= polygon[j].y)) || ((p.y >= polygon[i].y) && (p.y < polygon[j].y))) { if(polygon[i].x == polygon[j].x) { if(polygon[i].x < p.x) result = !result; } else { if(polygon[i].x + (polygon[j].x - polygon[i].x)/(polygon[j].y - polygon[i].y)*(p.y-polygon[i].y) < p.x) { result = !result; } } } j=i; } return result; } int main() { int setNum; int i,j; Point temp; while(cin >> setNum) { if(setNum == 0) break; i = 0; polygon.clear(); while(i < setNum) { cin >> temp.x >> temp.y; polygon.push_back(temp); i++; } cin >> temp.x >> temp.y; if(insidePolygon(temp)) cout << 'T' << endl; else cout << 'F' << endl; } }
20.227273
120
0.4
[ "vector" ]
05a301a02b1db4e285e5a26a24cd5eb062e87b4d
2,475
hpp
C++
core/src/Navigation/NavigationMeshContainer.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Navigation/NavigationMeshContainer.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Navigation/NavigationMeshContainer.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 CRIMILD_NAVIGATION_MESH_CONTAINER_ #define CRIMILD_NAVIGATION_MESH_CONTAINER_ #include "NavigationMesh.hpp" #include "Components/NodeComponent.hpp" namespace crimild { namespace navigation { class NavigationMeshContainer : public NodeComponent { CRIMILD_IMPLEMENT_RTTI( crimild::navigation::NavigationMeshContainer ) public: NavigationMeshContainer( void ); explicit NavigationMeshContainer( NavigationMeshPtr const &mesh ); virtual ~NavigationMeshContainer( void ); inline NavigationMesh *getNavigationMesh( void ) { return crimild::get_ptr( _navigationMesh ); } private: NavigationMeshPtr _navigationMesh; public: virtual void renderDebugInfo( Renderer *renderer, Camera *camera ) override; public: virtual void encode( coding::Encoder &encoder ) override; virtual void decode( coding::Decoder &decoder ) override; }; } } #endif
37.5
99
0.758384
[ "mesh" ]
05a457ab6ed789a18316a9c198d6c1cc0af7cb80
8,424
cc
C++
src/model/operation/pooling.cc
agnesnatasya/singa
e4082c600e7730b795e55ff3dd3b9df5b282389c
[ "Apache-2.0" ]
1
2020-04-28T01:42:33.000Z
2020-04-28T01:42:33.000Z
src/model/operation/pooling.cc
yshuailiu/singa
50d3092e8f489994becf84ee7e22c69a935a1f13
[ "Apache-2.0" ]
null
null
null
src/model/operation/pooling.cc
yshuailiu/singa
50d3092e8f489994becf84ee7e22c69a935a1f13
[ "Apache-2.0" ]
2
2021-08-06T23:43:42.000Z
2021-08-06T23:45:55.000Z
/********************************************************* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ************************************************************/ #include "pooling.h" #include <cmath> namespace singa { PoolingHandle::PoolingHandle(const Tensor &input, const std::vector<int> &kernel_size, const std::vector<int> &stride, const std::vector<int> &padding, const bool is_max) { kernel_h = kernel_size[0]; kernel_w = kernel_size[1]; pad_h = padding[0]; pad_w = padding[1]; stride_h = stride[0]; stride_w = stride[1]; batchsize = input.shape(0); channels = input.shape(1); height = input.shape(2); width = input.shape(3); pooled_height = 1; if (stride_h > 0) pooled_height = std::floor(((height + 2 * pad_h - kernel_h) / stride_h)) + 1; pooled_width = std::floor(((width + 2 * pad_w - kernel_w) / stride_w)) + 1; is_max_pooling = is_max; #ifdef USE_DNNL if (input.device()->lang() == kCpp) { auto x_dims = dnnl::memory::dims(input.shape().begin(), input.shape().end()); auto y_dims = dnnl::memory::dims({batchsize, channels, pooled_height, pooled_width}); auto s_dims = dnnl::memory::dims(stride.begin(), stride.end()); auto k_dims = dnnl::memory::dims(kernel_size.begin(), kernel_size.end()); auto p_dims = dnnl::memory::dims(padding.begin(), padding.end()); auto dtype_ = dnnl::memory::data_type::f32; auto format_tag_ = get_dnnl_format_tag(input); x_md = dnnl::memory::desc({x_dims}, dtype_, format_tag_); y_md = dnnl::memory::desc({y_dims}, dtype_, format_tag_); // allow max or avg (follow cudnn implementation convention) auto pooling_algo = dnnl::algorithm::pooling_avg_exclude_padding; if (is_max_pooling) pooling_algo = dnnl::algorithm::pooling_max; auto pool_fwd_d = dnnl::pooling_forward::desc( dnnl::prop_kind::forward_training, pooling_algo, x_md, y_md, s_dims, k_dims, p_dims, p_dims); auto pool_bwd_d = dnnl::pooling_backward::desc( pooling_algo, x_md, y_md, s_dims, k_dims, p_dims, p_dims); auto eng = input.device()->context(0)->dnnl_engine; pool_fwd_pd = dnnl::pooling_forward::primitive_desc(pool_fwd_d, eng); pool_bwd_pd = dnnl::pooling_backward::primitive_desc(pool_bwd_d, eng, pool_fwd_pd); auto ws_md = pool_fwd_pd.workspace_desc(); ws_mem = dnnl::memory(ws_md, eng); } #endif // USE_DNNL } PoolingHandle::~PoolingHandle() {} #ifdef USE_DNNL Tensor CpuPoolingForward(const PoolingHandle &ph, const Tensor &x) { CHECK_EQ(x.device()->lang(), kCpp); Tensor y({(unsigned long)ph.batchsize, (unsigned long)ph.channels, (unsigned long)ph.pooled_height, (unsigned long)ph.pooled_width}, x.device(), x.data_type()); y.device()->Exec( [y, x, &ph](Context *ctx) mutable { auto eng = ctx->dnnl_engine; using namespace dnnl; memory x_mem(ph.x_md, eng, x.block()->mutable_data()); memory y_mem(ph.y_md, eng, y.block()->mutable_data()); pooling_forward(ph.pool_fwd_pd) .execute(ctx->dnnl_stream, {{DNNL_ARG_SRC, x_mem}, {DNNL_ARG_DST, y_mem}, {DNNL_ARG_WORKSPACE, ph.ws_mem}}); ctx->dnnl_stream.wait(); }, {x.block()}, {y.block()}); return y; } Tensor CpuPoolingBackward(const PoolingHandle &ph, const Tensor &grad, const Tensor &x, const Tensor &y) { CHECK_EQ(x.device()->lang(), kCpp); CHECK_EQ(grad.device()->lang(), kCpp); CHECK_EQ(y.device()->lang(), kCpp); Tensor in_grad; in_grad.ResetLike(x); in_grad.device()->Exec( [x, y, in_grad, grad, &ph](Context *ctx) mutable { auto eng = ctx->dnnl_engine; using namespace dnnl; memory dx_mem(ph.x_md, eng, in_grad.block()->mutable_data()); memory dy_mem(ph.y_md, eng, grad.block()->mutable_data()); pooling_backward(ph.pool_bwd_pd) .execute(ctx->dnnl_stream, {{DNNL_ARG_DIFF_DST, dy_mem}, {DNNL_ARG_DIFF_SRC, dx_mem}, {DNNL_ARG_WORKSPACE, ph.ws_mem}}); ctx->dnnl_stream.wait(); }, {x.block(), y.block(), grad.block()}, {in_grad.block()}); return in_grad; } #endif // USE_DNNL #ifdef USE_CUDNN CudnnPoolingHandle::CudnnPoolingHandle(const Tensor &input, const std::vector<int> &kernel_size, const std::vector<int> &stride, const std::vector<int> &padding, const bool is_max) : PoolingHandle(input, kernel_size, stride, padding, is_max) { // nan_prop = CUDNN_NOT_PROPAGATE_NAN; DataType dtype = input.data_type(); CUDNN_CHECK(cudnnCreateTensorDescriptor(&x_desc)); CUDNN_CHECK(cudnnCreateTensorDescriptor(&y_desc)); CUDNN_CHECK(cudnnCreatePoolingDescriptor(&pool_desc)); CUDNN_CHECK(cudnnSetTensor4dDescriptor(x_desc, CUDNN_TENSOR_NCHW, GetCudnnDataType(dtype), batchsize, channels, height, width)); // LOG(ERROR) << batchsize << " " << channels << " " << pooled_height << " " // << pooled_width; CUDNN_CHECK(cudnnSetTensor4dDescriptor( y_desc, CUDNN_TENSOR_NCHW, GetCudnnDataType(dtype), batchsize, channels, pooled_height, pooled_width)); auto pool_method = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING; if (is_max) pool_method = CUDNN_POOLING_MAX; CUDNN_CHECK(cudnnSetPooling2dDescriptor(pool_desc, pool_method, nan_prop, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w)); }; CudnnPoolingHandle::~CudnnPoolingHandle() { if (pool_desc != nullptr) CUDNN_CHECK(cudnnDestroyPoolingDescriptor(pool_desc)); if (x_desc != nullptr) CUDNN_CHECK(cudnnDestroyTensorDescriptor(x_desc)); if (y_desc != nullptr) CUDNN_CHECK(cudnnDestroyTensorDescriptor(y_desc)); } Tensor GpuPoolingForward(const CudnnPoolingHandle &cph, const Tensor &x) { CHECK_EQ(x.device()->lang(), kCuda); CHECK_EQ(x.nDim(), 4u); Tensor output = Tensor( Shape({cph.batchsize, cph.channels, cph.pooled_height, cph.pooled_width}), x.device(), x.data_type()); output.device()->Exec( [output, x, &cph](Context *ctx) mutable { float alpha = 1.0f, beta = 0.0f; cudnnPoolingForward(ctx->cudnn_handle, cph.pool_desc, &alpha, cph.x_desc, x.block()->data(), &beta, cph.y_desc, output.block()->mutable_data()); }, {x.block()}, {output.block()}); return output; } Tensor GpuPoolingBackward(const CudnnPoolingHandle &cph, const Tensor &dy, const Tensor &x, const Tensor &y) { CHECK_EQ(dy.device()->lang(), kCuda); CHECK_EQ(dy.nDim(), 4u); Tensor dx; dx.ResetLike(x); dx.device()->Exec( [dx, dy, x, y, &cph](Context *ctx) mutable { float alpha = 1.0f, beta = 0.0f; cudnnPoolingBackward(ctx->cudnn_handle, cph.pool_desc, &alpha, cph.y_desc, y.block()->data(), cph.y_desc, dy.block()->data(), cph.x_desc, x.block()->data(), &beta, cph.x_desc, dx.block()->mutable_data()); }, {dy.block(), y.block(), x.block()}, {dx.block()}); return dx; }; #endif // USE_CUDNN } // namespace singa
36.626087
80
0.607787
[ "shape", "vector" ]
05ac05afa937bc62bd9d7fa3a334906c757acf5a
1,983
cpp
C++
src/space/triangulation_view.cpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/space/triangulation_view.cpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/space/triangulation_view.cpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
#include "triangulation_view.hpp" namespace space { TriangulationView::TriangulationView(std::vector<Vertex *> &&vertices) : V(vertices.size()), J(vertices.back()->level()), vertices_(std::move(vertices)), on_boundary_(V), godparents_(V, {0, 0}), vertices_per_level(J + 2, 0) { assert(V >= 3); // First, we mark all vertices. std::vector<uint> indices(V); for (uint i = 0; i < V; ++i) { const auto &vtx = vertices_[i]; on_boundary_[i] = vtx->on_domain_boundary; indices[i] = i; vtx->set_data(&indices[i]); // Find the first vertex on this level. auto lvl = vtx->level(); if (lvl > 0 && vertices_per_level[lvl] == 0) vertices_per_level[lvl] = i; assert((lvl < 0 || i >= vertices_per_level[lvl])); // Store link to the Godparents. if (vtx->godparents.size()) for (int gp = 0; gp < 2; gp++) godparents_[i][gp] = *vtx->godparents[gp]->template data<uint>(); } // Store number of vertices on last level as well, for convenience. assert(vertices_per_level[J + 1] == 0); vertices_per_level[J + 1] = V; // Figure out all the element leaves. Element2D *elem_meta_root = vertices_[0]->patch[0]->parents()[0]; assert(elem_meta_root->is_metaroot()); std::queue<Element2D *> queue; element_leaves_.reserve(V * 2); for (auto root : elem_meta_root->children()) queue.emplace(root); while (!queue.empty()) { auto elem = queue.front(); queue.pop(); bool is_leaf = true; for (const auto &child : elem->children()) if (child->newest_vertex()->has_data()) { queue.emplace(child); is_leaf = false; } if (is_leaf) { std::array<uint, 3> Vids; for (uint i = 0; i < 3; ++i) Vids[i] = *elem->vertices()[i]->template data<uint>(); element_leaves_.emplace_back(elem, std::move(Vids)); } } // Unset the data stored in the vertices. for (auto nv : vertices_) nv->reset_data(); } } // namespace space
30.045455
77
0.609682
[ "vector" ]
05b66b80cbdbc0344d4d7a50a8018d154f4988ad
16,272
cpp
C++
src/FresponzeWasapiSpatialEndpoint.cpp
Vertver/Fresponze
ca45738a2c06474fb6f45b627f8b1c8b85e69cd1
[ "Apache-2.0" ]
6
2019-10-09T11:43:42.000Z
2021-08-19T01:31:02.000Z
src/FresponzeWasapiSpatialEndpoint.cpp
Vertver/Fresponze
ca45738a2c06474fb6f45b627f8b1c8b85e69cd1
[ "Apache-2.0" ]
null
null
null
src/FresponzeWasapiSpatialEndpoint.cpp
Vertver/Fresponze
ca45738a2c06474fb6f45b627f8b1c8b85e69cd1
[ "Apache-2.0" ]
null
null
null
/********************************************************************* * Copyright (C) Anton Kovalev (vertver), 2020. All rights reserved. * Fresponze - fast, simple and modern multimedia sound library * Apache-2 License ********************************************************************** * 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 "FresponzeWasapi.h" #ifdef WASAPI_USE_SPATIAL_AUDIO #include <process.h> #include <avrt.h> #ifndef GUID_SECT #define GUID_SECT #endif #define __FRDEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #define __FRDEFINE_IID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const IID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #define __FRDEFINE_CLSID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const CLSID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #define FRDEFINE_CLSID(className, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ __FRDEFINE_CLSID(FR_CLSID_##className, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8) #define FRDEFINE_IID(interfaceName, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ __FRDEFINE_IID(FR_IID_##interfaceName, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8) FRDEFINE_IID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 00000003, 0000, 0010, 80, 00, 00, aa, 00, 38, 9b, 71); FRDEFINE_IID(KSDATAFORMAT_SUBTYPE_PCM, 00000001, 0000, 0010, 80, 00, 00, aa, 00, 38, 9b, 71); #define maxmin(a, minimum, maximum) min(max(a, minimum), maximum) PROPERTYKEY FFRPKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 }; const AudioObjectType ChannelMask_Mono = AudioObjectType_FrontCenter; const AudioObjectType ChannelMask_Stereo = (AudioObjectType)(AudioObjectType_FrontLeft | AudioObjectType_FrontRight); const AudioObjectType ChannelMask_2_1 = (AudioObjectType)(ChannelMask_Stereo | AudioObjectType_LowFrequency); const AudioObjectType ChannelMask_Quad = (AudioObjectType)(AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_BackLeft | AudioObjectType_BackRight); const AudioObjectType ChannelMask_4_1 = (AudioObjectType)(ChannelMask_Quad | AudioObjectType_LowFrequency); const AudioObjectType ChannelMask_5_1 = (AudioObjectType)(AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft | AudioObjectType_SideRight); const AudioObjectType ChannelMask_7_1 = (AudioObjectType)(ChannelMask_5_1 | AudioObjectType_BackLeft | AudioObjectType_BackRight); const UINT32 MaxStaticObjectCount_7_1_4 = 12; const AudioObjectType ChannelMask_7_1_4 = (AudioObjectType)(ChannelMask_7_1 | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft | AudioObjectType_TopBackRight); const UINT32 MaxStaticObjectCount_7_1_4_4 = 16; const AudioObjectType ChannelMask_7_1_4_4 = (AudioObjectType)(ChannelMask_7_1_4 | AudioObjectType_BottomFrontLeft | AudioObjectType_BottomFrontRight | AudioObjectType_BottomBackLeft | AudioObjectType_BottomBackRight); const UINT32 MaxStaticObjectCount_8_1_4_4 = 17; const AudioObjectType ChannelMask_8_1_4_4 = (AudioObjectType)(ChannelMask_7_1_4_4 | AudioObjectType_BackCenter); inline DWORD GetSleepTime( DWORD Frames, DWORD SampleRate ) { float fRet = 0.f; if (!SampleRate) return 0; fRet = ((((float)Frames / (float)SampleRate) * 1000.f) / 4.f); return (DWORD)fRet; } inline void CopyDataToBuffer( float* FileData, void* OutData, size_t FramesCount, bool IsFloat, int Bits, int Channels ) { size_t sizeToRead = FramesCount * Channels; if (IsFloat) { memcpy(OutData, FileData, sizeToRead * sizeof(fr_f32)); } else { short* pShortData = (short*)FileData; switch (Bits) { case 16: for (size_t i = 0; i < sizeToRead; i++) { pShortData[i] = maxmin(((short)(FileData[i] * 32768.0f)), -32768, 32767); } break; default: break; } } } inline void CopyDataFromBuffer( void* FileData, float* OutData, size_t FramesCount, bool IsFloat, int Bits, int Channels ) { size_t sizeToRead = FramesCount * Channels; if (IsFloat) { memcpy(OutData, FileData, sizeToRead * sizeof(fr_f32)); } else { short* pShortData = (short*)FileData; switch (Bits) { case 16: for (size_t i = 0; i < sizeToRead; i++) { OutData[i] = (float)pShortData[i] < 0 ? pShortData[i] / 32768.0f : pShortData[i] / 32767.0f; } break; default: break; } } } void CWASAPISpatialAudioEnpoint::GetDevicePointer( void*& pDevice ) { pDevice = pCurrentDevice; } void WINAPIV WASAPISpatialThreadProc( void* pData ) { CoInitialize(nullptr); CWASAPISpatialAudioEnpoint* pThis = (CWASAPISpatialAudioEnpoint*)pData; pThis->ThreadProc(); CoUninitialize(); } void CWASAPISpatialAudioEnpoint::ThreadProc() { if (!InitializeToPlay(DelayCustom)) return; PcmFormat fmtToPush = {}; bool isFloat = EndpointInfo.EndpointFormat.IsFloat; fr_err errCode = 0; UINT32 CurrentFrames = 0; UINT32 SampleRate = EndpointInfo.EndpointFormat.SampleRate; UINT32 Bits = EndpointInfo.EndpointFormat.Bits; UINT32 FramesInBuffer = EndpointInfo.EndpointFormat.Frames; UINT32 CurrentChannels = EndpointInfo.EndpointFormat.Channels; DWORD dwTask = 0; DWORD dwFlags = 0; DWORD dwFlushTime = GetSleepTime(FramesInBuffer, (DWORD)SampleRate); HRESULT hr = 0; HANDLE hMMCSS = nullptr; switch (EndpointInfo.Type) { case ProxyType: case RenderType: { hMMCSS = AvSetMmThreadCharacteristicsA("Pro Audio", &dwTask); if (IsInvalidHandle(hMMCSS)) { TypeToLog("WASAPI: AvSetMmThreadCharacteristicsA() failed"); return; } } break; case CaptureType: { hMMCSS = AvSetMmThreadCharacteristicsA("Capture", &dwTask); if (IsInvalidHandle(hMMCSS)) { TypeToLog("WASAPI: AvSetMmThreadCharacteristicsA() failed"); return; } } break; default: { hMMCSS = AvSetMmThreadCharacteristicsA("Audio", &dwTask); if (IsInvalidHandle(hMMCSS)) { TypeToLog("WASAPI: AvSetMmThreadCharacteristicsA() failed"); return; } } break; } if (!AvSetMmThreadPriority(hMMCSS, AVRT_PRIORITY_CRITICAL)) { TypeToLog("WASAPI: AvSetMmThreadPriority() failed"); goto EndOfThread; } pSyncEvent->Raise(); pStartEvent->Wait(); pThreadEvent->Reset(); if (pAudioCallback) { pAudioCallback->FlushCallback(); pAudioCallback->FormatCallback(&fmtToPush); } pObjectAudioStream->Start(); while (!pThreadEvent->Wait(dwFlushTime)) { if (WaitForSingleObject(hCompleteEvent, 100) != WAIT_OBJECT_0) { hr = pObjectAudioStream->Reset(); if (FAILED(hr)) { goto EndOfThread; } } if (!pAudioCallback) continue; UINT32 availableDynamicObjectCount = 0; UINT32 frameCount = 0; hr = pObjectAudioStream->BeginUpdatingAudioObjects(&availableDynamicObjectCount, &frameCount); BYTE* buffer = nullptr; UINT32 bufferLength = 0; if (pStaticObject == nullptr) { hr = pObjectAudioStream->ActivateSpatialAudioObject(ChannelMask_Mono, &pStaticObject); if (hr != S_OK) break; } // Get the buffer to write audio data hr = pStaticObject->GetBuffer(&buffer, &bufferLength); if (SUCCEEDED(hr)) { /* Process and copy data to main buffer */ if (!buffer) continue; errCode = pAudioCallback->EndpointCallback((fr_f32*)buffer, frameCount, 1, (fr_i32)SampleRate, RenderType); if (FAILED(errCode)) { TypeToLog("WASAPI: Putting empty buffer to output"); } } else { /* Don't try to destroy device if the buffer is unavailable */ if (hr == AUDCLNT_E_BUFFER_TOO_LARGE) { TypeToLog("WASAPI: Buffer is too large for endpoint buffer"); continue; } TypeToLog("WASAPI: pRenderClient->GetBuffer() failed (render callback)"); goto EndOfThread; } hr = pObjectAudioStream->EndUpdatingAudioObjects(); } EndOfThread: /* This functions must be called in thread, where you create service */ _RELEASE(pObjectAudioStream); _RELEASE(pAudioClient); TypeToLog("WASAPI: Shutdowning thread"); if (pThreadEvent->IsRaised()) pThreadEvent->Reset(); if (pSyncEvent->IsRaised()) pSyncEvent->Reset(); if (!IsInvalidHandle(hMMCSS)) AvRevertMmThreadCharacteristics(hMMCSS); } bool CWASAPISpatialAudioEnpoint::CreateWasapiThread() { DWORD dwThreadId = 0; if (pThreadEvent->IsRaised()) pThreadEvent->Reset(); #ifndef XBOX_BUILD hThread = (HANDLE)_beginthread(WASAPISpatialThreadProc, 0, this); #else hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)WASAPIThreadProc, this, 0, &dwThreadId); #endif if (!IsInvalidHandle(hThread)) { TypeToLog("WASAPI: Waiting for event"); if (!pSyncEvent->Wait(2000)) { /* Terminate our thread if it was timeouted */ if (WaitForSingleObject(hThread, 0) != WAIT_OBJECT_0) { TypeToLog("WASAPI: Failed to init thread"); TerminateThread(hThread, (DWORD)-1); } return false; } } else return false; TypeToLog("WASAPI: Event triggered. Thread started"); return true; } void CWASAPISpatialAudioEnpoint::SetDeviceInfo(EndpointInformation& DeviceInfo) { memcpy(&EndpointInfo, &DeviceInfo, sizeof(EndpointInformation)); } void CWASAPISpatialAudioEnpoint::GetDeviceInfo(EndpointInformation& DeviceInfo) { memcpy(&DeviceInfo, &EndpointInfo, sizeof(EndpointInformation)); } void CWASAPISpatialAudioEnpoint::SetCallback(IAudioCallback* pCallback) { pCallback->Clone((void**)&pAudioCallback); } bool CWASAPISpatialAudioEnpoint::GetEndpointDeviceInfo() { LPWSTR lpwDeviceId = nullptr; IPropertyStore* pPropertyStore = nullptr; PROPVARIANT value = { 0 }; if (!pCurrentDevice) return false; #ifndef XBOX_BUILD if (FAILED(pCurrentDevice->OpenPropertyStore(STGM_READ, &pPropertyStore))) { TypeToLog("WASAPI: pCurrentDevice->OpenPropertyStore() failed (endpoint)"); return false; } /* Get friendly name of current device */ PropVariantInit(&value); if (SUCCEEDED(pPropertyStore->GetValue(FFRPKEY_Device_FriendlyName, &value))) { if (value.vt == VT_LPWSTR) { /* Get size of new UTF-8 string */ int StringSize = WideCharToMultiByte(CP_UTF8, 0, value.pwszVal, -1, NULL, 0, NULL, NULL); char lpNewString[260] = {}; /* Translate UTF-16 string to normalized UTF-8 string */ if (StringSize && StringSize < 259) { if (WideCharToMultiByte(CP_UTF8, 0, value.pwszVal, -1, lpNewString, 260, NULL, NULL)) { strcpy_s(EndpointInfo.EndpointName, lpNewString); } } else { strcpy_s(EndpointInfo.EndpointName, "Unknown Device Name"); } } } else { TypeToLog("WASAPI: Failed to get friendly name"); strcpy_s(EndpointInfo.EndpointName, "Unknown Device Name"); } PropVariantClear(&value); /* Get UUID of current device */ if (SUCCEEDED(pCurrentDevice->GetId(&lpwDeviceId))) { /* Get size of new UTF-8 string */ int StringSize = WideCharToMultiByte(CP_UTF8, 0, lpwDeviceId, -1, NULL, 0, NULL, NULL); char lpNewString[260] = {}; /* Translate UTF-16 string to normalized UTF-8 string */ if (StringSize && StringSize < 259) { if (WideCharToMultiByte(CP_UTF8, 0, lpwDeviceId, -1, lpNewString, 260, NULL, NULL)) { strcpy_s(EndpointInfo.EndpointUUID, lpNewString); } else { strcpy_s(EndpointInfo.EndpointUUID, "Unknown Device UUID"); } } } else { TypeToLog("WASAPI: Failed to get device UUID"); strcpy_s(EndpointInfo.EndpointUUID, "Unknown Device UUID"); } _RELEASE(pPropertyStore); #endif return true; } bool CWASAPISpatialAudioEnpoint::InitializeToPlay(fr_f32 Delay) { DWORD dwStreamFlags = (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY); UINT32 BufferFrames = 0; HRESULT hr = 0; REFERENCE_TIME refTimeDefault = 0; REFERENCE_TIME refTimeMin = 0; REFERENCE_TIME refTimeAccepted = REFERENCE_TIME(Delay * 10000.f); WAVEFORMATEX* pWaveFormat = nullptr; WAVEFORMATEX waveFormat = {}; IPropertyStore* pPropertyStore = nullptr; IAudioFormatEnumerator* pFormatEnumerator = nullptr; PROPVARIANT value = { 0 }; if (!pCurrentDevice) return false; hr = pCurrentDevice->Activate(__uuidof(ISpatialAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&pAudioClient); if (FAILED(hr)) return false; if (!GetEndpointDeviceInfo()) { _RELEASE(pAudioClient); return false; } hr = pAudioClient->GetSupportedAudioObjectFormatEnumerator(&pFormatEnumerator); if (FAILED(hr)) { _RELEASE(pAudioClient); return false; } /* Check for needy format to activate device with it (default sample rate requested - 48000)*/ UINT32 FormatsCount = 0; pFormatEnumerator->GetCount(&FormatsCount); for (UINT32 i = 0; i < FormatsCount; i++) { hr = pFormatEnumerator->GetFormat(i, &pWaveFormat); if (FAILED(hr)) { _RELEASE(pFormatEnumerator); _RELEASE(pAudioClient); return false; } /* We've got it! Continue to client execution*/ if (pWaveFormat->nSamplesPerSec == RENDER_SAMPLE_RATE && pWaveFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { memcpy(&waveFormat, pWaveFormat, sizeof(WAVEFORMATEX)); break; } } /* We don't find needy format, abort */ if (waveFormat.nSamplesPerSec == 0) { _RELEASE(pFormatEnumerator); _RELEASE(pAudioClient); return false; } hr = pAudioClient->IsAudioObjectFormatSupported(&waveFormat); if (FAILED(hr)) { if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT) { TypeToLogFormated("WASAPI: Unsupported format to device: 0x%x", hr); } return false; } /* Create the event that will be used to signal the client for more data */ hCompleteEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); /* Get current object type for set channels mask */ hr = pAudioClient->GetNativeStaticObjectTypeMask(&typeOfObject); if (FAILED(hr)) { _RELEASE(pAudioClient); CloseHandle(hCompleteEvent); return false; } streamParams.ObjectFormat = &waveFormat; streamParams.StaticObjectTypeMask = ChannelMask_Mono; streamParams.MinDynamicObjectCount = 0; streamParams.MaxDynamicObjectCount = 0; streamParams.Category = AudioCategory_SoundEffects; streamParams.EventHandle = hCompleteEvent; streamParams.NotifyObject = nullptr; hr = pAudioClient->GetMaxFrameCount(&waveFormat, &BufferFrames); if (FAILED(hr)) { _RELEASE(pAudioClient); CloseHandle(hCompleteEvent); return false; } PropVariantInit(&activationParams); activationParams.vt = VT_BLOB; activationParams.blob.cbSize = sizeof(streamParams); activationParams.blob.pBlobData = reinterpret_cast<BYTE*>(&streamParams); hr = pAudioClient->ActivateSpatialAudioStream(&activationParams, __uuidof(pObjectAudioStream), (void**)&pObjectAudioStream); if (FAILED(hr)) { CloseHandle(hCompleteEvent); return false; } EndpointInfo.EndpointFormat.Frames = (fr_i32)BufferFrames; TypeToLogFormated("WASAPI: Device initialized (Shared, Sample rate: %i, Channels: %i, Latency: %i)", EndpointInfo.EndpointFormat.SampleRate, EndpointInfo.EndpointFormat.Channels, EndpointInfo.EndpointFormat.Frames); TypeToLogFormated("WASAPI: Device name: %s", EndpointInfo.EndpointName); TypeToLogFormated("WASAPI: Device GUID: %s", EndpointInfo.EndpointUUID); pTempBuffer = (fr_f32*)FastMemAlloc(sizeof(fr_f32) * EndpointInfo.EndpointFormat.Frames * EndpointInfo.EndpointFormat.Channels); CoTaskMemFree(pWaveFormat); return true; } bool CWASAPISpatialAudioEnpoint::Open(fr_f32 Delay) { DelayCustom = Delay; if (!Start()) return false; return true; } bool CWASAPISpatialAudioEnpoint::Close() { Stop(); return true; } bool CWASAPISpatialAudioEnpoint::Start() { CreateWasapiThread(); pStartEvent->Raise(); return true; } bool CWASAPISpatialAudioEnpoint::Stop() { if (!IsInvalidHandle(hThread)) { pThreadEvent->Raise(); pStartEvent->Reset(); if (WaitForSingleObject(hThread, 1000) == WAIT_TIMEOUT) { TerminateThread(hThread, (DWORD)-1); } if (pTempBuffer) { FreeFastMemory(pTempBuffer); pTempBuffer = nullptr; } return true; } return false; } #endif
31.053435
230
0.734329
[ "render", "object" ]
05bd2d8f7b1b9fa1f70829310b4eb5c3d515a383
1,144
cpp
C++
test/findpaths_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
test/findpaths_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
test/findpaths_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
#include "bct_test.h" DEFUN_DLD(findpaths_cpp, args, , "Wrapper for C++ function.") { if (args.length() != 3) { return octave_value_list(); } Matrix CIJ = args(0).matrix_value(); Matrix sources = args(1).matrix_value(); int qmax = args(2).int_value(); if (!error_state) { gsl_matrix* CIJ_gsl = bct_test::to_gslm(CIJ); gsl_vector* sources_gsl = bct_test::to_gslv(sources); gsl_vector_add_constant(sources_gsl, -1.0); gsl_vector* plq; int qstop; gsl_matrix* allpths; gsl_matrix* util; std::vector<gsl_matrix*> Pq = bct::findpaths(CIJ_gsl, sources_gsl, qmax, &plq, &qstop, &allpths, &util); gsl_matrix_add_constant(allpths, 1.0); octave_value_list ret; ret(0) = octave_value(bct_test::from_gsl(Pq, 1)); ret(1) = octave_value(bct_test::from_gsl(plq, 1)); ret(2) = octave_value(qstop); ret(3) = octave_value(bct_test::from_gsl(allpths)); ret(4) = octave_value(bct_test::from_gsl(util, 0, 1)); gsl_matrix_free(CIJ_gsl); gsl_vector_free(sources_gsl); gsl_vector_free(plq); gsl_matrix_free(allpths); gsl_matrix_free(util); bct::gsl_free(Pq); return ret; } else { return octave_value_list(); } }
30.918919
106
0.702797
[ "vector" ]
05bde3ddbc6427fbb55bd6f9d97c88b31613b146
9,390
cpp
C++
code/src/resources/othermanagers/colorspacesimpl.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
54
2015-02-16T14:25:16.000Z
2022-03-16T07:54:25.000Z
code/src/resources/othermanagers/colorspacesimpl.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
null
null
null
code/src/resources/othermanagers/colorspacesimpl.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
30
2015-03-05T08:52:25.000Z
2022-02-17T13:49:15.000Z
// Copyright (c) 2005-2009 Jaroslav Gresula // // Distributed under the MIT license (See accompanying file // LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) // #include "precompiled.h" #include <resources/othermanagers/colorspacesimpl.h> #include <resources/resourcebox/colorspacehelpers.h> #include <core/generic/floatpointtools.h> #include <core/generic/containerhelpers.h> #include <core/generic/refcountedimpl.h> #include <core/generic/null_deleter.h> #include <core/errlib/errlib.h> #include <core/jstd/file_stream.h> #include <core/jstd/fileso.h> #include <msg_resources.h> #include <string.h> using namespace jag::jstd; namespace jag { namespace resources { /////////////////////////////////////////////////////////////////////////// // PaletteImpl /////////////////////////////////////////////////////////////////////////// PaletteImpl::PaletteImpl() {} void PaletteImpl::check_validity() const { if (!is_valid(m_color_space)) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; } void PaletteImpl::set(ColorSpace cs, Byte const* palette, UInt byte_size) { if (!byte_size) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_color_space = handle_from_id<RESOURCE_COLOR_SPACE>(cs); UInt cs_type = resources::color_space_type(m_color_space); if (cs_type == CS_INDEXED || is_pattern_color_space(m_color_space)) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_palette.resize(byte_size); memcpy(&m_palette[0], palette, byte_size); } Byte const* PaletteImpl::data() const { JAG_PRECONDITION(length()); return address_of(m_palette); } size_t PaletteImpl::length() const { return m_palette.size(); } /// Upon finishing execution of this method the object becomes a zombie. void PaletteImpl::drop_data() { std::vector<Byte>().swap(m_palette); } boost::intrusive_ptr<IColorSpace> PaletteImpl::clone() const { boost::intrusive_ptr<PaletteImpl> cloned(new RefCountImpl<PaletteImpl>()); cloned->m_color_space = m_color_space; cloned->m_palette = m_palette; return cloned; } /////////////////////////////////////////////////////////////////////////// // class CIELabImpl /////////////////////////////////////////////////////////////////////////// CIEBase::CIEBase() { // white point in pdf spec (D65) - x=0.9505, y=1.0890 set_invalid_double(m_white_xz[0]); set_invalid_double(m_black_xyz[0]); } void CIEBase::check_validity() const { if (is_invalid_double(m_white_xz[0])) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; } void CIEBase::white_point(Double xw, Double zw) { if (xw < 1e-8 || zw < 1e-8) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_white_xz[0] = xw; m_white_xz[1] = zw; } void CIEBase::black_point (Double xb, Double yb, Double zb) { if (xb<0 || yb<0 || zb<0) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_black_xyz[0] = xb; m_black_xyz[1] = yb; m_black_xyz[2] = zb; } CIEBase::black_point_ref_t CIEBase::black_point() const { JAG_PRECONDITION(is_black_point_valid()); return m_black_xyz; } bool CIEBase::is_black_point_valid() const { return !is_invalid_double(m_black_xyz[0]); } /////////////////////////////////////////////////////////////////////////// // CIECalGrayImpl /////////////////////////////////////////////////////////////////////////// CIECalGrayImpl::CIECalGrayImpl() { set_invalid_double(m_gamma); } void CIECalGrayImpl::gamma(Double val) { if (val < 1e-8) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_gamma = val; } bool CIECalGrayImpl::is_gamma_valid() const { return !is_invalid_double(m_gamma); } Double CIECalGrayImpl::gamma() const { JAG_PRECONDITION(is_gamma_valid()); return m_gamma; } boost::intrusive_ptr<IColorSpace> CIECalGrayImpl::clone() const { boost::intrusive_ptr<CIECalGrayImpl> cloned(new RefCountImpl<CIECalGrayImpl>()); cloned->m_gamma = m_gamma; cloned->m_cie_base = m_cie_base; return cloned; } /////////////////////////////////////////////////////////////////////////// // CIECalRGBImpl /////////////////////////////////////////////////////////////////////////// CIECalRGBImpl::CIECalRGBImpl() { set_invalid_double(m_gamma[0]); set_invalid_double(m_matrix[0]); } void CIECalRGBImpl::gamma(Double gr, Double gg, Double gb) { if (gr < 1e-8 || gg < 1e-8 || gb < 1e-8) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_gamma[0] = gr; m_gamma[1] = gg; m_gamma[2] = gb; } void CIECalRGBImpl::matrix( Double xa, Double ya, Double za, Double xb, Double yb, Double zb, Double xc, Double yc, Double zc) { m_matrix[0] = xa; m_matrix[1] = ya; m_matrix[2] = za; m_matrix[3] = xb; m_matrix[4] = yb; m_matrix[5] = zb; m_matrix[6] = xc; m_matrix[7] = yc; m_matrix[8] = zc; } CIECalRGBImpl::gamma_ref_t CIECalRGBImpl::gamma() const { JAG_ASSERT(is_gamma_valid()); return m_gamma; } CIECalRGBImpl::matrix_ref_t CIECalRGBImpl::matrix() const { JAG_ASSERT(is_matrix_valid()); return m_matrix; } bool CIECalRGBImpl::is_gamma_valid() const { return !is_invalid_double(m_gamma[0]); } bool CIECalRGBImpl::is_matrix_valid() const { return !is_invalid_double(m_matrix[0]); } boost::intrusive_ptr<IColorSpace> CIECalRGBImpl::clone() const { boost::intrusive_ptr<CIECalRGBImpl> cloned(new RefCountImpl<CIECalRGBImpl>()); cloned->m_cie_base = m_cie_base; cloned->m_gamma = m_gamma; cloned->m_matrix = m_matrix; return cloned; } /////////////////////////////////////////////////////////////////////////// // CIELabImpl /////////////////////////////////////////////////////////////////////////// CIELabImpl::CIELabImpl() { set_invalid_double(m_range_ab[0]); } void CIELabImpl::range(Double amin, Double amax, Double bmin, Double bmax) { if (amin>amax || bmin>bmax) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_range_ab[0] = amin; m_range_ab[1] = amax; m_range_ab[2] = bmin; m_range_ab[3] = bmax; } CIELabImpl::range_ref_t CIELabImpl::range() const { JAG_PRECONDITION(is_range_valid()); return m_range_ab; } bool CIELabImpl::is_range_valid() const { return !is_invalid_double(m_range_ab[0]); } boost::intrusive_ptr<IColorSpace> CIELabImpl::clone() const { boost::intrusive_ptr<CIELabImpl> cloned(new RefCountImpl<CIELabImpl>()); cloned->m_cie_base = m_cie_base; cloned->m_range_ab = m_range_ab; return cloned; } ////////////////////////////////////////////// // ICCBasedImpl ////////////////////////////////////////////// ICCBasedImpl::ICCBasedImpl() : m_num_components(-1) #ifdef _DEBUG , m_stream_retrieved(false) #endif { } void ICCBasedImpl::check_validity() const { if (m_num_components==-1 || (!is_file(m_file_path.c_str()) && !m_stream.get())) { throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; } if (is_valid(m_alternate)) { // ?number of components of the alternate cs does not match // we do not have color space manager pointer here so we can only // verify color spaces that has fixed number of components int nc = resources::num_components(m_alternate, 0, true); if (nc && nc != m_num_components) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; } } void ICCBasedImpl::num_components(Int val) { if (val<=0 || val>4 || val==2) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_num_components = val; } void ICCBasedImpl::icc_profile(Char const* file_path) { if (!is_file(file_path)) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_stream.reset(); m_file_path.assign(file_path); } void ICCBasedImpl::alternate(ColorSpace cs) { ColorSpaceHandle csh(handle_from_id<RESOURCE_COLOR_SPACE>(cs)); if (!is_valid(csh) || is_pattern_color_space(csh)) throw exception_invalid_value(msg_invalid_argument()) << JAGLOC; m_alternate = csh; } boost::intrusive_ptr<IColorSpace> ICCBasedImpl::clone() const { boost::intrusive_ptr<ICCBasedImpl> cloned(new RefCountImpl<ICCBasedImpl>()); cloned->m_num_components = m_num_components; cloned->m_alternate = m_alternate; cloned->m_file_path = m_file_path; cloned->m_stream = m_stream; return cloned; } /** * @brief Provides stream containing the profile. * * @todo return a stream proxy instead of the member * @return icc profile stream */ boost::shared_ptr<ISeqStreamInput> ICCBasedImpl::icc_profile() const { if (m_stream.get()) { #ifdef _DEBUG JAG_ASSERT(!m_stream_retrieved && "stream retrieved more than once"); m_stream_retrieved = 1; #endif return boost::shared_ptr<ISeqStreamInput>(m_stream.get(), null_deleter); } return boost::shared_ptr<ISeqStreamInput>( new FileStreamInput(m_file_path.c_str())); } void ICCBasedImpl::icc_profile_stream(std::auto_ptr<ISeqStreamInput> stream) { m_stream = stream; m_file_path.clear(); } }} // namespace jag::resources /** EOF @file */
21.487414
84
0.628647
[ "object", "vector" ]
05c417895c7117944a92ad4647a579e4d7c7ea9f
13,601
cpp
C++
clipdiff/FormMain.cpp
ambiesoft/clipdiff
856b4ca0ee9b089ab2b3b249dd82579936183819
[ "BSD-2-Clause" ]
null
null
null
clipdiff/FormMain.cpp
ambiesoft/clipdiff
856b4ca0ee9b089ab2b3b249dd82579936183819
[ "BSD-2-Clause" ]
2
2019-06-23T16:38:59.000Z
2019-06-23T16:39:32.000Z
clipdiff/FormMain.cpp
ambiesoft/clipdiff
856b4ca0ee9b089ab2b3b249dd82579936183819
[ "BSD-2-Clause" ]
null
null
null
//Copyright (C) 2017 Ambiesoft All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions //are met: //1. Redistributions of source code must retain the above copyright //notice, this list of conditions and the following disclaimer. //2. Redistributions in binary form must reproduce the above copyright //notice, this list of conditions and the following disclaimer in the //documentation and/or other materials provided with the distribution. // //THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. // clipdiff.cpp : main project file. #include "stdafx.h" #include "../../lsMisc/GetChildWindowBy.h" #include "FormMain.h" //#include "difflist.h" #include "ListViewForScroll.h" #include "LVInfo.h" #include "../Common/defines.h" namespace clipdiff { using namespace Ambiesoft; using namespace System::Text; using namespace System::IO; using namespace System::Collections::Generic; void FormMain::addColumn() { int index = !tlpMain ? 1 : tlpMain->ColumnCount+1; ListViewForScroll^ lv = gcnew ListViewForScroll(this); ColumnHeader^ chLine = (gcnew System::Windows::Forms::ColumnHeader()); chLine->Text = L"Line"; chLine->Name = L"chLine"; ColumnHeader^ chText = (gcnew System::Windows::Forms::ColumnHeader()); chText->Text = L"Text"; chText->Name = L"chText"; chText->Width = 213; lv->Columns->AddRange(gcnew cli::array< System::Windows::Forms::ColumnHeader^ > {chLine, chText}); lv->Dock = System::Windows::Forms::DockStyle::Fill; lv->FullRowSelect = true; lv->HeaderStyle = IsHeaderVisible ? ColumnHeaderStyle::Nonclickable : ColumnHeaderStyle::None; lv->HideSelection = false; lv->MultiSelect = !false; lv->Location = System::Drawing::Point(0, 0); lv->Name = L"lv" + index; lv->Size = System::Drawing::Size(138, 255); lv->TabIndex = index; lv->UseCompatibleStateImageBehavior = false; lv->View = System::Windows::Forms::View::Details; lv->ContextMenuStrip = ctxMenuList; lv->ShowItemToolTips = IsShowToolTip; lv->VirtualMode = true; lv->RetrieveVirtualItem += gcnew RetrieveVirtualItemEventHandler(this, &FormMain::onRetrieveItem); lv->Tag = gcnew LVInfo(); lv->DoubleClick += gcnew System::EventHandler(this, &FormMain::lv_doubleClick); if(FontLV) { lv->Font=FontLV; } // flowLayoutPanel1->Controls->Add(lv); if(!tlpMain) { tlpMain = gcnew System::Windows::Forms::TableLayoutPanel(); this->tlpMain->Dock = System::Windows::Forms::DockStyle::Fill; this->tlpMain->Location = System::Drawing::Point(0, 24); this->tlpMain->Name = L"tlpMain"; this->tlpMain->RowCount = 1; this->tlpMain->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 100))); this->tlpMain->Size = System::Drawing::Size(622, 387); this->tlpMain->TabIndex = 3; this->tlpMain->SizeChanged += gcnew System::EventHandler(this, &FormMain::tlpMain_SizeChanged); this->panelClient->Controls->Add(this->tlpMain); } for each(Control^ control in tlpMain->Controls) { Panel^ otherPanel = (Panel^)control; ListViewForScroll^ other = (ListViewForScroll^)otherPanel->Tag; lv->others_.Add(other); other->others_.Add(lv); } Panel^ listPanel = gcnew Panel(); listPanel->Tag=lv; listPanel->Dock= DockStyle::Fill; listPanel->Controls->Add(lv); StatusStrip^ ss = gcnew StatusStrip(); ss->Dock=DockStyle::Top; ss->SizingGrip = false; { ToolStripStatusLabel^ sslabelDate = gcnew ToolStripStatusLabel(); sslabelDate->Spring = true; sslabelDate->TextAlign = System::Drawing::ContentAlignment::MiddleLeft; ss->Items->Add(sslabelDate); } { ToolStripStatusLabel^ sslabelNewOld = gcnew ToolStripStatusLabel(); sslabelNewOld->TextAlign = System::Drawing::ContentAlignment::MiddleRight; ss->Items->Add(sslabelNewOld); } ss->TabIndex = 1; ss->Name = L"ListStatus"; listPanel->Controls->Add(ss); tlpMain->ColumnCount++; tlpMain->Controls->Add(listPanel, tlpMain->ColumnCount-1, 0); tlpMain->ColumnStyles->Clear(); for(int i=0 ; i < tlpMain->ColumnCount; ++i) { tlpMain->ColumnStyles->Add((gcnew ColumnStyle(SizeType::Percent, 100.0F/tlpMain->ColumnCount))); } } void FormMain::removeColumn() { if(tlpMain->ColumnCount <= 2) return; tlpMain->Controls->RemoveAt(tlpMain->Controls->Count-1); tlpMain->ColumnCount--; tlpMain->RowCount=1; // tlpMain->Controls->R Add(lv, tlpMain->ColumnCount-1, 0); tlpMain->ColumnStyles->Clear(); for(int i=0 ; i < tlpMain->ColumnCount; ++i) tlpMain->ColumnStyles->Add((gcnew ColumnStyle(SizeType::Percent, 100.0F/tlpMain->ColumnCount))); } void FormMain::updateTitle(int addCount, int replaceCount, int deleteCount, int nochangeCount) { System::Text::StringBuilder title; System::Text::StringBuilder msg; if(addCount==0 && replaceCount==0 && deleteCount==0) { title.Append(I18N(L"Identical")); msg.Append(I18N(L"Identical")); } else { title.Append(addCount); title.Append(L":"); msg.Append(I18N(L"Added") + L":" + addCount.ToString()); msg.Append(L" "); title.Append(replaceCount); title.Append(L":"); msg.Append(I18N(L"Replaced") + L":" + replaceCount.ToString()); msg.Append(L" "); title.Append(deleteCount); title.Append(L":"); msg.Append(I18N(L"Deleted") + L":" + deleteCount.ToString()); msg.Append(L" "); title.Append(nochangeCount); msg.Append(I18N(L"Nochange") + L":" + nochangeCount.ToString()); } slChange->Text = msg.ToString(); title.Append(L" | "); title.Append(Application::ProductName); Text = title.ToString(); } void FormMain::updateTitle() { updateTitle(0,0,0,0); } bool FormMain::IsIdling::get() { return isIdling_; } void FormMain::IsIdling::set(bool value) { isIdling_ = value; if(value) Application::Idle += gcnew EventHandler(this, &FormMain::onIdle); else Application::Idle -= gcnew EventHandler(this, &FormMain::onIdle); } void FormMain::onIdle(Object^ sender, EventArgs^ e) { tsbTopMost->Checked = this->TopMost; } System::Void FormMain::tlpMain_SizeChanged(System::Object^ sender, System::EventArgs^ e) { //lv1->AutoResizeColumns(ColumnHeaderAutoResizeStyle::ColumnContent); //lv2->AutoResizeColumns(ColumnHeaderAutoResizeStyle::ColumnContent); //int width = Math::Max(chText1->Width, chText2->Width); //lv1->AutoResizeColumns(ColumnHeaderAutoResizeStyle::None); //lv2->AutoResizeColumns(ColumnHeaderAutoResizeStyle::None); //chText1->Width = width; //chText2->Width = width; //lv2->Columns["Text"]->Width = width; //int hPad = lv1->Padding.Left + lv1->Padding.Right; //int i = lv1->Columns->IndexOfKey("Text"); // lv1->Columns[i]; } List<StreamWriter^>^ FormMain::GetsaveAsFiles(int filecount, String^ filenamepre, List<String^>^ filenames) { List<StreamWriter^>^ ret = gcnew List<StreamWriter^>(); try { for(int i=0 ; i < filecount; ++i) { String^ filename = filenamepre + (i+1).ToString() + L".txt"; if(System::IO::File::Exists(filename)) { return nullptr; } filenames->Add(filename); StreamWriter^ sw = gcnew StreamWriter(filename, false, System::Text::Encoding::UTF8); ret->Add(sw); } return ret; } catch(System::Exception^) {} return nullptr; } HWND FormMain::GetChildMainFormWindow() { if (WAIT_TIMEOUT != WaitForSingleObject(childProcess_,0)) return NULL; if (::IsWindow(childHwnd_)) { DWORD dwProcessIDChild; GetWindowThreadProcessId(childHwnd_, &dwProcessIDChild); if (dwProcessIDChild == GetProcessId(childProcess_)) { return childHwnd_; } } HWND parentHwnd = (HWND)spRoot->Panel2->Handle.ToPointer(); return childHwnd_ = GetChildWindowByText(parentHwnd, L"clipdiffbrowser"); } System::Void FormMain::spRoot_Panel2_Resize(System::Object^ sender, System::EventArgs^ e) { HWND h = GetChildMainFormWindow(); if (!h) return; SendNotifyMessage(h, WM_APP_RESIZE, 0, 0); } System::Void FormMain::tsmDonate_Click(System::Object^ sender, System::EventArgs^ e) { try { System::Diagnostics::Process::Start(L"https://ambiesoft.github.io/webjumper/?target=donate"); } catch (Exception^ex) { Alert(ex); } } System::Void FormMain::TsmFind_Click(System::Object^ sender, System::EventArgs^ e) { cmbFind->Focus(); } System::Void FormMain::CmbFind_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) { if (e->KeyCode == Keys::Enter) findNext(cmbFind->Text); } System::Void FormMain::TsbFindUp_Click(System::Object^ sender, System::EventArgs^ e) { findPrev(cmbFind->Text); } System::Void FormMain::TsbFindDown_Click(System::Object^ sender, System::EventArgs^ e) { findNext(cmbFind->Text); } bool hasItemText(ListViewItem^ item, String^ text) { if (item->Text->IndexOf(text) >= 0) return true; for (int i = 0; i < item->SubItems->Count; ++i) { if (item->SubItems[i]->Text->IndexOf(text) >= 0) return true; } return false; } List<ListViewForScroll^>^ FormMain::GetAllLV(bool bReverse) { List<ListViewForScroll^>^ allLVs = gcnew List<ListViewForScroll^>(); for (int i = 0; i < tlpMain->Controls->Count; ++i) { allLVs->Add(GetList(i)); } if (bReverse) allLVs->Reverse(); return allLVs; } List<ListViewForScroll^>^ FormMain::GetAllLV() { return GetAllLV(false); } void FormMain::findPrev(String^ findWord) { findCommon(false, findWord); } void FormMain::findNext(String^ findWord) { findCommon(true, findWord); } int FormMain::GetLVIndex(ListViewForScroll^ lv) { for (int i = 0; i < tlpMain->Controls->Count; ++i) { if (lv == GetList(i)) return i; } return -1; } void FormMain::findCommon(bool bNext, String^ findWord) { // Create table arrya in which the focused table gets first List<ListViewForScroll^>^ allLVs = GetAllLV(!bNext); int focusIndex = -1; for (int i = 0; i < allLVs->Count; ++i) { ListViewForScroll^ lv = allLVs[i]; if (lv->Focused) { focusIndex = i; break; } } if (focusIndex >= 0) { // Table has focus List<ListViewForScroll^> toAppends; List<ListViewForScroll^>^ allLVtmp = GetAllLV(!bNext); for (int i = 0; i < allLVtmp->Count; ++i) { ListViewForScroll^ lv = allLVtmp[i]; DTRACE("LVIndex=" + GetLVIndex(lv)); if (i >= focusIndex) break; allLVs->Remove(lv); toAppends.Add(lv); } allLVs->AddRange(toAppends.ToArray()); } #ifdef _DEBUG String^ message = ""; for each(ListViewForScroll^ lv in allLVs) { message += GetLVIndex(lv); message += ":"; } DTRACE("Find Order=" + message); #endif bool first = true; for each(ListViewForScroll^ lv in allLVs) { DTRACE("LVIndex=" + GetLVIndex(lv)); int startIndex = !bNext ? lv->Items->Count - 1 : 0; if (lv->SelectedIndices->Count == 0) { if (first) continue; } else { if (first) startIndex = lv->SelectedIndices[0] + (!bNext ? -1 : 1); } List<int> indexOrder; if (!bNext) { for (int i = startIndex; i >= 0; --i) { indexOrder.Add(i); } } else { for (int i = startIndex; i < lv->Items->Count; ++i) { indexOrder.Add(i); } } for each(int i in indexOrder) { if (hasItemText(lv->Items[i],findWord)) { // found //lv->Items[i]->Selected = true; //lv->Items[i]->Focused = true; //lv->Items[i]->EnsureVisible(); SelectItemAndAync(lv, lv->Items[i]); lv->Focus(); return; } } first = false; } // not found, start from beginning for each(ListViewForScroll^ lv in GetAllLV(!bNext)) { List<int> indexOrder; if (!bNext) { for (int i = lv->Items->Count -1 ; i >= 0; --i) { indexOrder.Add(i); } } else { for (int i = 0; i < lv->Items->Count; ++i) { indexOrder.Add(i); } } for each(int i in indexOrder) { if (hasItemText(lv->Items[i], findWord)) { // found //lv->Items[i]->Selected = true; //lv->Items[i]->Focused = true; //lv->Items[i]->EnsureVisible(); SelectItemAndAync(lv, lv->Items[i]); lv->Focus(); return; } } } // not found at all MessageBeep(MB_ICONINFORMATION); } }
25.327747
124
0.637894
[ "object" ]
05c93fa76c7546e8dabfa8919cefd15decef6ea5
16,194
cpp
C++
samples/sfml/SimpleStreamViewer-SFML/main.cpp
mucks/astra-sdk
810fc9ad62167baee6326de2549c583d0d54d424
[ "Apache-2.0" ]
1
2019-11-22T05:36:21.000Z
2019-11-22T05:36:21.000Z
samples/sfml/SimpleStreamViewer-SFML/main.cpp
mucks/astra-sdk
810fc9ad62167baee6326de2549c583d0d54d424
[ "Apache-2.0" ]
null
null
null
samples/sfml/SimpleStreamViewer-SFML/main.cpp
mucks/astra-sdk
810fc9ad62167baee6326de2549c583d0d54d424
[ "Apache-2.0" ]
1
2021-02-04T05:18:23.000Z
2021-02-04T05:18:23.000Z
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015-2017 Orbbec 3D // // 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. // // Be excellent to each other. #include <SFML/Graphics.hpp> #include <astra_core/astra_core.hpp> #include <astra/astra.hpp> #include "LitDepthVisualizer.hpp" #include <chrono> #include <iostream> #include <iomanip> #include <key_handler.h> enum ColorMode { MODE_COLOR, MODE_IR_16, MODE_IR_RGB, }; class MultiFrameListener : public astra::FrameListener { public: using BufferPtr = std::unique_ptr<uint8_t[]>; struct StreamView { sf::Sprite sprite_; sf::Texture texture_; BufferPtr buffer_; int width_{0}; int height_{0}; }; MultiFrameListener() { prev_ = ClockType::now(); } void init_texture(int width, int height, StreamView& view) { if (view.buffer_ == nullptr || width != view.width_ || height != view.height_) { view.width_ = width; view.height_ = height; // texture is RGBA const int byteLength = width * height * 4; view.buffer_ = BufferPtr(new uint8_t[byteLength]); clear_view(view); view.texture_.create(width, height); view.sprite_.setTexture(view.texture_, true); view.sprite_.setPosition(0, 0); } } void clear_view(StreamView& view) { const int byteLength = view.width_ * view.height_ * 4; std::fill(&view.buffer_[0], &view.buffer_[0] + byteLength, 0); } void check_fps() { const float frameWeight = .2f; const ClockType::time_point now = ClockType::now(); const float elapsedMillis = std::chrono::duration_cast<DurationType>(now - prev_).count(); elapsedMillis_ = elapsedMillis * frameWeight + elapsedMillis_ * (1.f - frameWeight); prev_ = now; const float fps = 1000.f / elapsedMillis; const auto precision = std::cout.precision(); std::cout << std::fixed << std::setprecision(1) << fps << " fps (" << std::setprecision(1) << elapsedMillis_ << " ms)" << std::setprecision(precision) << std::endl; } void update_depth(astra::Frame& frame) { const astra::PointFrame pointFrame = frame.get<astra::PointFrame>(); if (!pointFrame.is_valid()) { clear_view(depthView_); depthView_.texture_.update(&depthView_.buffer_[0]); return; } const int depthWidth = pointFrame.width(); const int depthHeight = pointFrame.height(); init_texture(depthWidth, depthHeight, depthView_); if (isPaused_) { return; } visualizer_.update(pointFrame); astra::RgbPixel* vizBuffer = visualizer_.get_output(); uint8_t* buffer = &depthView_.buffer_[0]; for (int i = 0; i < depthWidth * depthHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = vizBuffer[i].r; buffer[rgbaOffset + 1] = vizBuffer[i].g; buffer[rgbaOffset + 2] = vizBuffer[i].b; buffer[rgbaOffset + 3] = 255; } depthView_.texture_.update(&depthView_.buffer_[0]); } void update_color(astra::Frame& frame) { const astra::ColorFrame colorFrame = frame.get<astra::ColorFrame>(); if (!colorFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } const int colorWidth = colorFrame.width(); const int colorHeight = colorFrame.height(); init_texture(colorWidth, colorHeight, colorView_); if (isPaused_) { return; } const astra::RgbPixel* color = colorFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for(int i = 0; i < colorWidth * colorHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = color[i].r; buffer[rgbaOffset + 1] = color[i].g; buffer[rgbaOffset + 2] = color[i].b; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } void update_ir_16(astra::Frame& frame) { const astra::InfraredFrame16 irFrame = frame.get<astra::InfraredFrame16>(); if (!irFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } const int irWidth = irFrame.width(); const int irHeight = irFrame.height(); init_texture(irWidth, irHeight, colorView_); if (isPaused_) { return; } const uint16_t* ir_values = irFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for (int i = 0; i < irWidth * irHeight; i++) { const int rgbaOffset = i * 4; const uint16_t value = ir_values[i]; const uint8_t red = static_cast<uint8_t>(value >> 2); const uint8_t blue = 0x66 - red / 2; buffer[rgbaOffset] = red; buffer[rgbaOffset + 1] = 0; buffer[rgbaOffset + 2] = blue; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } void update_ir_rgb(astra::Frame& frame) { const astra::InfraredFrameRgb irFrame = frame.get<astra::InfraredFrameRgb>(); if (!irFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } int irWidth = irFrame.width(); int irHeight = irFrame.height(); init_texture(irWidth, irHeight, colorView_); if (isPaused_) { return; } const astra::RgbPixel* irRGB = irFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for (int i = 0; i < irWidth * irHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = irRGB[i].r; buffer[rgbaOffset + 1] = irRGB[i].g; buffer[rgbaOffset + 2] = irRGB[i].b; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } virtual void on_frame_ready(astra::StreamReader& reader, astra::Frame& frame) override { update_depth(frame); switch (colorMode_) { case MODE_COLOR: update_color(frame); break; case MODE_IR_16: update_ir_16(frame); break; case MODE_IR_RGB: update_ir_rgb(frame); break; } check_fps(); } void draw_to(sf::RenderWindow& window, sf::Vector2f origin, sf::Vector2f size) { const int viewSize = (int)(size.x / 2.0f); const sf::Vector2f windowSize = window.getView().getSize(); if (depthView_.buffer_ != nullptr) { const float depthScale = viewSize / (float)depthView_.width_; const int horzCenter = origin.y * windowSize.y; depthView_.sprite_.setScale(depthScale, depthScale); depthView_.sprite_.setPosition(origin.x * windowSize.x, horzCenter); window.draw(depthView_.sprite_); } if (colorView_.buffer_ != nullptr) { const float colorScale = viewSize / (float)colorView_.width_; const int horzCenter = origin.y * windowSize.y; colorView_.sprite_.setScale(colorScale, colorScale); if (overlayDepth_) { colorView_.sprite_.setPosition(origin.x * windowSize.x, horzCenter); colorView_.sprite_.setColor(sf::Color(255, 255, 255, 128)); } else { colorView_.sprite_.setPosition(origin.x * windowSize.x + viewSize, horzCenter); colorView_.sprite_.setColor(sf::Color(255, 255, 255, 255)); } window.draw(colorView_.sprite_); } } void toggle_depth_overlay() { overlayDepth_ = !overlayDepth_; } bool get_overlay_depth() const { return overlayDepth_; } void toggle_paused() { isPaused_ = !isPaused_; } bool is_paused() const { return isPaused_; } ColorMode get_mode() const { return colorMode_; } void set_mode(ColorMode mode) { colorMode_ = mode; } private: samples::common::LitDepthVisualizer visualizer_; using DurationType = std::chrono::milliseconds; using ClockType = std::chrono::high_resolution_clock; ClockType::time_point prev_; float elapsedMillis_{.0f}; StreamView depthView_; StreamView colorView_; ColorMode colorMode_; bool overlayDepth_{ false }; bool isPaused_{ false }; }; astra::DepthStream configure_depth(astra::StreamReader& reader) { auto depthStream = reader.stream<astra::DepthStream>(); auto oldMode = depthStream.mode(); //We don't have to set the mode to start the stream, but if you want to here is how: astra::ImageStreamMode depthMode; depthMode.set_width(640); depthMode.set_height(480); depthMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_DEPTH_MM); depthMode.set_fps(30); depthStream.set_mode(depthMode); auto newMode = depthStream.mode(); printf("Changed depth mode: %dx%d @ %d -> %dx%d @ %d\n", oldMode.width(), oldMode.height(), oldMode.fps(), newMode.width(), newMode.height(), newMode.fps()); return depthStream; } astra::InfraredStream configure_ir(astra::StreamReader& reader, bool useRGB) { auto irStream = reader.stream<astra::InfraredStream>(); auto oldMode = irStream.mode(); astra::ImageStreamMode irMode; irMode.set_width(640); irMode.set_height(480); if (useRGB) { irMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_RGB888); } else { irMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_GRAY16); } irMode.set_fps(30); irStream.set_mode(irMode); auto newMode = irStream.mode(); printf("Changed IR mode: %dx%d @ %d -> %dx%d @ %d\n", oldMode.width(), oldMode.height(), oldMode.fps(), newMode.width(), newMode.height(), newMode.fps()); return irStream; } astra::ColorStream configure_color(astra::StreamReader& reader) { auto colorStream = reader.stream<astra::ColorStream>(); auto oldMode = colorStream.mode(); astra::ImageStreamMode colorMode; colorMode.set_width(640); colorMode.set_height(480); colorMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_RGB888); colorMode.set_fps(30); colorStream.set_mode(colorMode); auto newMode = colorStream.mode(); printf("Changed color mode: %dx%d @ %d -> %dx%d @ %d\n", oldMode.width(), oldMode.height(), oldMode.fps(), newMode.width(), newMode.height(), newMode.fps()); return colorStream; } int main(int argc, char** argv) { astra::initialize(); set_key_handler(); #ifdef _WIN32 auto fullscreenStyle = sf::Style::None; #else auto fullscreenStyle = sf::Style::Fullscreen; #endif const sf::VideoMode fullScreenMode = sf::VideoMode::getFullscreenModes()[0]; const sf::VideoMode windowedMode(1800, 675); bool isFullScreen = false; sf::RenderWindow window(windowedMode, "Stream Viewer"); astra::StreamSet streamSet; astra::StreamReader reader = streamSet.create_reader(); reader.stream<astra::PointStream>().start(); auto depthStream = configure_depth(reader); depthStream.start(); auto colorStream = configure_color(reader); colorStream.start(); auto irStream = configure_ir(reader, false); MultiFrameListener listener; listener.set_mode(MODE_COLOR); reader.add_listener(listener); while (window.isOpen()) { astra_update(); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: { switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::F: if (isFullScreen) { isFullScreen = false; window.create(windowedMode, "Stream Viewer", sf::Style::Default); } else { isFullScreen = true; window.create(fullScreenMode, "Stream Viewer", fullscreenStyle); } break; case sf::Keyboard::R: depthStream.enable_registration(!depthStream.registration_enabled()); break; case sf::Keyboard::M: { const bool newMirroring = !depthStream.mirroring_enabled(); depthStream.enable_mirroring(newMirroring); colorStream.enable_mirroring(newMirroring); irStream.enable_mirroring(newMirroring); } break; case sf::Keyboard::G: colorStream.stop(); configure_ir(reader, false); listener.set_mode(MODE_IR_16); irStream.start(); break; case sf::Keyboard::I: colorStream.stop(); configure_ir(reader, true); listener.set_mode(MODE_IR_RGB); irStream.start(); break; case sf::Keyboard::O: listener.toggle_depth_overlay(); if (listener.get_overlay_depth()) { depthStream.enable_registration(true); } break; case sf::Keyboard::P: listener.toggle_paused(); break; case sf::Keyboard::C: if (event.key.control) { window.close(); } else { irStream.stop(); listener.set_mode(MODE_COLOR); colorStream.start(); } break; default: break; } break; } default: break; } } // clear the window with black color window.clear(sf::Color::Black); listener.draw_to(window, sf::Vector2f(0.f, 0.f), sf::Vector2f(window.getSize().x, window.getSize().y)); window.display(); if (!shouldContinue) { window.close(); } } astra::terminate(); return 0; }
29.768382
111
0.550821
[ "3d" ]
fe4ca8b18d138bbb241c7da39f81d9d0043d59fe
8,623
cc
C++
Geometry/MTDCommonData/test/DD4hep_TestMTDNumbering.cc
RosmarieSchoefbeck/cmssw
66b151a27eef46ff965508064071091ecb21395c
[ "Apache-2.0" ]
1
2020-04-09T19:05:23.000Z
2020-04-09T19:05:23.000Z
Geometry/MTDCommonData/test/DD4hep_TestMTDNumbering.cc
RosmarieSchoefbeck/cmssw
66b151a27eef46ff965508064071091ecb21395c
[ "Apache-2.0" ]
null
null
null
Geometry/MTDCommonData/test/DD4hep_TestMTDNumbering.cc
RosmarieSchoefbeck/cmssw
66b151a27eef46ff965508064071091ecb21395c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <utility> #include <vector> #include <algorithm> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESTransientHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/Exception.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/Records/interface/DDSpecParRegistryRcd.h" #include "DetectorDescription/DDCMS/interface/DDDetector.h" #include "DetectorDescription/DDCMS/interface/DDFilteredView.h" #include "DetectorDescription/DDCMS/interface/DDSpecParRegistry.h" #include "Geometry/MTDCommonData/interface/MTDBaseNumber.h" #include "Geometry/MTDCommonData/interface/BTLNumberingScheme.h" #include "Geometry/MTDCommonData/interface/ETLNumberingScheme.h" #include "DataFormats/ForwardDetId/interface/BTLDetId.h" #include "DataFormats/ForwardDetId/interface/ETLDetId.h" //#define EDM_ML_DEBUG using namespace cms; class DD4hep_TestMTDNumbering : public edm::one::EDAnalyzer<> { public: explicit DD4hep_TestMTDNumbering(const edm::ParameterSet&); ~DD4hep_TestMTDNumbering() = default; void beginJob() override {} void analyze(edm::Event const&, edm::EventSetup const&) override; void endJob() override {} void theBaseNumber(const std::vector<std::pair<std::string_view, uint32_t>>& gh); private: const edm::ESInputTag tag_; std::string fname_; std::string ddTopNodeName_; uint32_t theLayout_; MTDBaseNumber thisN_; BTLNumberingScheme btlNS_; ETLNumberingScheme etlNS_; edm::ESGetToken<DDDetector, IdealGeometryRecord> dddetToken_; edm::ESGetToken<DDSpecParRegistry, DDSpecParRegistryRcd> dspecToken_; }; DD4hep_TestMTDNumbering::DD4hep_TestMTDNumbering(const edm::ParameterSet& iConfig) : tag_(iConfig.getParameter<edm::ESInputTag>("DDDetector")), fname_(iConfig.getUntrackedParameter<std::string>("outFileName", "GeoHistory")), ddTopNodeName_(iConfig.getUntrackedParameter<std::string>("ddTopNodeName", "BarrelTimingLayer")), theLayout_(iConfig.getUntrackedParameter<uint32_t>("theLayout", 1)), thisN_(), btlNS_(), etlNS_() { dddetToken_ = esConsumes<DDDetector, IdealGeometryRecord>(tag_); dspecToken_ = esConsumes<DDSpecParRegistry, DDSpecParRegistryRcd>(tag_); } void DD4hep_TestMTDNumbering::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { auto pDD = iSetup.getTransientHandle(dddetToken_); auto pSP = iSetup.getTransientHandle(dspecToken_); if (ddTopNodeName_ != "BarrelTimingLayer" && ddTopNodeName_ != "EndcapTimingLayer") { edm::LogWarning("DD4hep_TestMTDNumbering") << ddTopNodeName_ << "Not valid top MTD volume"; return; } if (!pDD.isValid()) { edm::LogError("DD4hep_TestMTDNumbering") << "ESTransientHandle<DDCompactView> pDD is not valid!"; return; } if (pDD.description()) { edm::LogInfo("DD4hep_TestMTDNumbering") << pDD.description()->type_ << " label: " << pDD.description()->label_; } else { edm::LogWarning("DD4hep_TestMTDNumbering") << "NO label found pDD.description() returned false."; } if (!pSP.isValid()) { edm::LogError("DD4hep_TestMTDNumbering") << "ESTransientHandle<DDSpecParRegistry> pSP is not valid!"; return; } const std::string fname = "dump" + fname_; DDFilteredView fv(pDD.product(), pDD.product()->description()->worldVolume()); fv.next(0); edm::LogInfo("DD4hep_TestMTDNumbering") << fv.name(); DDSpecParRefs specs; std::string attribute("ReadOutName"), name; if (ddTopNodeName_ == "BarrelTimingLayer") { name = "FastTimerHitsBarrel"; } else if (ddTopNodeName_ == "EndcapTimingLayer") { name = "FastTimerHitsEndcap"; } if (name.empty()) { edm::LogError("DD4hep_TestMTDNumbering") << "No sensitive detector provided, abort"; return; } pSP.product()->filter(specs, attribute, name); edm::LogVerbatim("Geometry").log([&specs](auto& log) { log << "Filtered DD SpecPar Registry size: " << specs.size() << "\n"; for (const auto& t : specs) { log << "\nRegExps { "; for (const auto& ki : t->paths) log << ki << " "; log << "};\n "; for (const auto& kl : t->spars) { log << kl.first << " = "; for (const auto& kil : kl.second) { log << kil << " "; } log << "\n "; } } }); std::ofstream dump(fname.c_str()); bool write = false; bool isBarrel = true; uint32_t level(0); std::vector<std::pair<std::string_view, uint32_t>> geoHistory; do { uint32_t clevel = fv.navPos().size(); uint32_t ccopy = (clevel > 1 ? fv.copyNum() : 0); geoHistory.resize(clevel); geoHistory[clevel - 1] = std::pair<std::string_view, uint32_t>(fv.name(), ccopy); if (fv.name() == "BarrelTimingLayer") { isBarrel = true; edm::LogInfo("DD4hep_TestMTDNumbering") << "isBarrel = " << isBarrel; } else if (fv.name() == "EndcapTimingLayer") { isBarrel = false; edm::LogInfo("DD4hep_TestMTDNumbering") << "isBarrel = " << isBarrel; } auto print_path = [&](std::vector<std::pair<std::string_view, uint32_t>>& theHistory) { dump << " - "; for (const auto& t : theHistory) { dump << t.first; dump << "["; dump << t.second; dump << "]/"; } dump << "\n"; }; #ifdef EDM_ML_DEBUG edm::LogInfo("DD4hep_TestMTDNumbering") << level << " " << clevel << " " << fv.name() << " " << ccopy; edm::LogVerbatim("DD4hep_TestMTDNumbering").log([&geoHistory](auto& log) { for (const auto& t : geoHistory) { log << t.first; log << "["; log << t.second; log << "]/"; } }); #endif if (level > 0 && fv.navPos().size() < level) { level = 0; write = false; } if (fv.name() == ddTopNodeName_) { write = true; level = fv.navPos().size(); } // Actions for MTD volumes: searchg for sensitive detectors if (write) { print_path(geoHistory); bool isSens = false; for (auto const& t : specs) { for (auto const& it : t->paths) { if (dd::compareEqual(fv.name(), dd::realTopName(it))) { isSens = true; break; } } } // Check of numbering scheme for sensitive detectors if (isSens) { theBaseNumber(geoHistory); if (isBarrel) { BTLDetId::CrysLayout lay = static_cast<BTLDetId::CrysLayout>(theLayout_); BTLDetId theId(btlNS_.getUnitID(thisN_)); int hIndex = theId.hashedIndex(lay); BTLDetId theNewId(theId.getUnhashedIndex(hIndex, lay)); dump << theId; dump << "\n layout type = " << static_cast<int>(lay); dump << "\n ieta = " << theId.ieta(lay); dump << "\n iphi = " << theId.iphi(lay); dump << "\n hashedIndex = " << theId.hashedIndex(lay); dump << "\n BTLDetId hI = " << theNewId; if (theId.mtdSide() != theNewId.mtdSide()) { dump << "\n DIFFERENCE IN SIDE"; } if (theId.mtdRR() != theNewId.mtdRR()) { dump << "\n DIFFERENCE IN ROD"; } if (theId.module() != theNewId.module()) { dump << "\n DIFFERENCE IN MODULE"; } if (theId.modType() != theNewId.modType()) { dump << "\n DIFFERENCE IN MODTYPE"; } if (theId.crystal() != theNewId.crystal()) { dump << "\n DIFFERENCE IN CRYSTAL"; } dump << "\n"; } else { ETLDetId theId(etlNS_.getUnitID(thisN_)); dump << theId; #ifdef EDM_ML_DEBUG edm::LogInfo("DD4hep_TestMTDNumbering") << " ETLDetId = " << theId << "\n geographicalId = " << theId.geographicalId(); #endif } dump << "\n"; } } } while (fv.next(0)); dump << std::flush; dump.close(); } void DD4hep_TestMTDNumbering::theBaseNumber(const std::vector<std::pair<std::string_view, uint32_t>>& gh) { thisN_.reset(); thisN_.setSize(gh.size()); for (auto t = gh.rbegin(); t != gh.rend(); ++t) { std::string name; name.assign(t->first); int copyN(t->second); thisN_.addLevel(name, copyN); #ifdef EDM_ML_DEBUG edm::LogVerbatim("DD4hep_TestMTDNumbering") << name << " " << copyN; #endif } } DEFINE_FWK_MODULE(DD4hep_TestMTDNumbering);
32.539623
115
0.630871
[ "geometry", "vector" ]
fe5b51105061e9188b1b6f3d059b18f88edf54f1
2,303
cpp
C++
core_cs/oops/function_overriding.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
23
2021-10-30T04:11:52.000Z
2021-11-27T09:16:18.000Z
core_cs/oops/function_overriding.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
null
null
null
core_cs/oops/function_overriding.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
4
2021-10-30T03:26:05.000Z
2021-11-14T12:15:04.000Z
/** * If derived class defines same function as defined in its base class, * it is known as function overriding in C++. * It is used to achieve runtime polymorphism. * It enables you to provide specific implementation of the function which is already provided by its base class. * */ #include<bits/stdc++.h> using namespace std; class OldCar { public : void ShiftGear () { cout << "Manual Transmission in Old Cars" << endl; } virtual void SteeringType () { cout << "Bearing Based Steering Wheel in Old Cars" << endl; } void Radio () { cout << "Radio present in Old Cars" << endl; } }; class SportsCar : public OldCar { public : void ShiftGear () { cout << "Automatic Transmission in Sports Car" << endl; } void SteeringType () { cout << "Power Steering Wheel in Sports Car" << endl; } }; int main () { SportsCar sportsCar; cout << "Early Binding demonstration based on caller object type done by compiler" << endl; sportsCar.SteeringType(); sportsCar.ShiftGear(); // Compiler looks for ShiftGear() in caller object's class first, if it finds it there then OK // Otherwise it will look in Parent class for the same function, just like in the next example sportsCar.Radio(); // Since this method doesn't exist in caller obj's class it looks for it in Parent class. cout << endl << "Demonstration of the need for Late Binding" << endl; OldCar *pointer; // Base Class pointer object pointer = &sportsCar; // Holds the address of Child class pointer->ShiftGear(); // It selects ShiftGear() from class of pointer object becaus of early binding // To fix this issue the compiler needs to look into the type of data who's address is stored in pointer // This can be achieved at Runtime only, because only then pointer is assigned its value // So we use virtual keyword with overrided functions to let the compiler know that it need to look // at it's type during the runtime cout << endl << "Late Binding demonstration based on type of data held by the base class pointer done by compiler" << endl; pointer->SteeringType(); }
34.373134
127
0.64568
[ "object" ]
fe5c68db9eadbf82aa3373a970e6e84c2f0f6fdb
6,588
cpp
C++
tests/TracingTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
tests/TracingTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
tests/TracingTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 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/SkImageInfo.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "src/core/SkLeanWindows.h" #include "src/core/SkTraceEvent.h" #include "tests/Test.h" #include "tools/flags/CommandLineFlags.h" static DEFINE_bool( slowTracingTest, false, "Artificially slow down tracing test to produce nicer JSON"); namespace { /** * Helper types for demonstrating usage of TRACE_EVENT_OBJECT_XXX macros. */ struct TracingShape { TracingShape() { TRACE_EVENT_OBJECT_CREATED_WITH_ID("skia.objects", this->typeName(), this); } virtual ~TracingShape() { TRACE_EVENT_OBJECT_DELETED_WITH_ID("skia.objects", this->typeName(), this); } void traceSnapshot() { // The state of an object can be specified at any point with the OBJECT_SNAPSHOT macro. // This takes the "name" (actually the type name), the ID of the object (typically a // pointer), and a single (unnnamed) argument, which is the "snapshot" of that object. // // Tracing viewer requires that all object macros use the same name and id for creation, // deletion, and snapshots. However: It's convenient to put creation and deletion in the // base-class constructor/destructor where the actual type name isn't known yet. That's // what we're doing here. The JSON for snapshots can therefore include the actual type // name, and a special tag that refers to the type name originally used at creation time. // Skia's JSON tracer handles this automatically, so SNAPSHOT macros can simply use the // derived type name, and the JSON will be formatted correctly to link the events. TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID( "skia.objects", this->typeName(), this, TRACE_STR_COPY(this->toString().c_str())); } virtual const char* typeName() { return "TracingShape"; } virtual SkString toString() { return SkString("Shape()"); } }; struct TracingCircle : public TracingShape { TracingCircle(SkPoint center, SkScalar radius) : fCenter(center), fRadius(radius) {} const char* typeName() override { return "TracingCircle"; } SkString toString() override { return SkStringPrintf("Circle(%f, %f, %f)", fCenter.fX, fCenter.fY, fRadius); } SkPoint fCenter; SkScalar fRadius; }; struct TracingRect : public TracingShape { TracingRect(SkRect rect) : fRect(rect) {} const char* typeName() override { return "TracingRect"; } SkString toString() override { return SkStringPrintf( "Rect(%f, %f, %f, %f)", fRect.fLeft, fRect.fTop, fRect.fRight, fRect.fBottom); } SkRect fRect; }; } // namespace static SkScalar gTracingTestWorkSink = 1.0f; static void do_work(int howMuchWork) { // Do busy work so the trace marker durations are large enough to be readable in trace viewer if (FLAGS_slowTracingTest) { for (int i = 0; i < howMuchWork * 100; ++i) { gTracingTestWorkSink += SkScalarSin(i); } } } static void test_trace_simple() { // Simple event that lasts until the end of the current scope. TRACE_FUNC is an easy way // to insert the current function name. TRACE_EVENT0("skia", TRACE_FUNC); { // There are versions of the macro that take 1 or 2 named arguments. The arguments // can be any simple type. Strings need to be static/literal - we just copy pointers. // Argument names & values are shown when the event is selected in the viewer. TRACE_EVENT1("skia", "Nested work", "isBGRA", kN32_SkColorType == kBGRA_8888_SkColorType); do_work(500); } { // If you must copy a string as an argument value, use the TRACE_STR_COPY macro. // This will instruct the tracing system (if one is active) to make a copy. SkString message = SkStringPrintf("%s %s", "Hello", "World"); TRACE_EVENT1("skia", "Dynamic String", "message", TRACE_STR_COPY(message.c_str())); do_work(500); } } static void test_trace_counters() { TRACE_EVENT0("skia", TRACE_FUNC); { TRACE_EVENT0("skia", "Single Counter"); // Counter macros allow recording a named value (which must be a 32-bit integer). // The value will be graphed in the viewer. for (int i = 0; i < 180; ++i) { SkScalar rad = SkDegreesToRadians(SkIntToScalar(i)); TRACE_COUNTER1("skia", "sin", SkScalarSin(rad) * 1000.0f + 1000.0f); do_work(10); } } { TRACE_EVENT0("skia", "Independent Counters"); // Recording multiple counters with separate COUNTER1 macros will make separate graphs. for (int i = 0; i < 180; ++i) { SkScalar rad = SkDegreesToRadians(SkIntToScalar(i)); TRACE_COUNTER1("skia", "sin", SkScalarSin(rad) * 1000.0f + 1000.0f); TRACE_COUNTER1("skia", "cos", SkScalarCos(rad) * 1000.0f + 1000.0f); do_work(10); } } { TRACE_EVENT0("skia", "Stacked Counters"); // Two counters can be recorded together with COUNTER2. They will be graphed together, // as a stacked bar graph. The combined graph needs a name, as does each data series. for (int i = 0; i < 180; ++i) { SkScalar rad = SkDegreesToRadians(SkIntToScalar(i)); TRACE_COUNTER2( "skia", "trig", "sin", SkScalarSin(rad) * 1000.0f + 1000.0f, "cos", SkScalarCos(rad) * 1000.0f + 1000.0f); do_work(10); } } } static void test_trace_objects() { TRACE_EVENT0("skia", TRACE_FUNC); // Objects can be tracked through time with the TRACE_EVENT_OBJECT_ macros. // The macros in use (and their idiosyncracies) are commented in the TracingShape class above. TracingCircle* circle = new TracingCircle(SkPoint::Make(20, 20), 15); circle->traceSnapshot(); do_work(100); // Make another object. Objects with the same base type are shown in the same row in the viewer. TracingRect* rect = new TracingRect(SkRect::MakeWH(100, 50)); rect->traceSnapshot(); do_work(100); // We can create multiple snapshots of objects to reflect their state over time. circle->fCenter.offset(10, 10); circle->traceSnapshot(); { // Other events (duration or instant) can refer directly to objects. For Skia's JSON // tracer, having an argument whose name starts with '#' will trigger the creation of JSON // that links the event to the object (with a direct link to the most recent snapshot). TRACE_EVENT1("skia", "Processing Shape", "#shape", circle); do_work(100); } delete circle; delete rect; } DEF_TEST(Tracing, reporter) { test_trace_simple(); test_trace_counters(); test_trace_objects(); }
35.804348
98
0.693534
[ "object", "shape" ]
fe5d9e4608b98bd16ba1dc721217fc2ad606bb60
303
cc
C++
leetcode/unique-binary-search-tree.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
leetcode/unique-binary-search-tree.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
leetcode/unique-binary-search-tree.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
// Unique Binary Search Tree class Solution { public: int numTrees(int n) { vector<int> nums(n+1, 0); nums[0] = 1; nums[1] = 1; for (int i=2; i<=n; i++) for (int k=1; k<=i; k++) nums[i] += nums[k-1] * nums[i-k]; return nums[n]; } };
21.642857
49
0.442244
[ "vector" ]
fe60f3e92b49b85e976cb2b456a07ec8d2489367
4,486
hxx
C++
opencascade/ShapeFix_Root.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/ShapeFix_Root.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/ShapeFix_Root.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1999-08-09 // Created by: Galina KULIKOVA // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeFix_Root_HeaderFile #define _ShapeFix_Root_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Real.hxx> #include <TopoDS_Shape.hxx> #include <Standard_Transient.hxx> #include <Message_Gravity.hxx> #include <Standard_Boolean.hxx> #include <Standard_Integer.hxx> #include <ShapeExtend_BasicMsgRegistrator.hxx> class ShapeBuild_ReShape; class ShapeExtend_BasicMsgRegistrator; class TopoDS_Shape; class Message_Msg; class ShapeFix_Root; DEFINE_STANDARD_HANDLE(ShapeFix_Root, Standard_Transient) //! Root class for fixing operations //! Provides context for recording changes (optional), //! basic precision value and limit (minimal and //! maximal) values for tolerances, //! and message registrator class ShapeFix_Root : public Standard_Transient { public: //! Empty Constructor (no context is created) Standard_EXPORT ShapeFix_Root(); //! Copy all fields from another Root object Standard_EXPORT virtual void Set (const Handle(ShapeFix_Root)& Root); //! Sets context Standard_EXPORT virtual void SetContext (const Handle(ShapeBuild_ReShape)& context); //! Returns context Handle(ShapeBuild_ReShape) Context() const; //! Sets message registrator Standard_EXPORT virtual void SetMsgRegistrator (const Handle(ShapeExtend_BasicMsgRegistrator)& msgreg); //! Returns message registrator Handle(ShapeExtend_BasicMsgRegistrator) MsgRegistrator() const; //! Sets basic precision value Standard_EXPORT virtual void SetPrecision (const Standard_Real preci); //! Returns basic precision value Standard_Real Precision() const; //! Sets minimal allowed tolerance Standard_EXPORT virtual void SetMinTolerance (const Standard_Real mintol); //! Returns minimal allowed tolerance Standard_Real MinTolerance() const; //! Sets maximal allowed tolerance Standard_EXPORT virtual void SetMaxTolerance (const Standard_Real maxtol); //! Returns maximal allowed tolerance Standard_Real MaxTolerance() const; //! Returns tolerance limited by [myMinTol,myMaxTol] Standard_Real LimitTolerance (const Standard_Real toler) const; //! Sends a message to be attached to the shape. //! Calls corresponding message of message registrator. Standard_EXPORT void SendMsg (const TopoDS_Shape& shape, const Message_Msg& message, const Message_Gravity gravity = Message_Info) const; //! Sends a message to be attached to myShape. //! Calls previous method. void SendMsg (const Message_Msg& message, const Message_Gravity gravity = Message_Info) const; //! Sends a warning to be attached to the shape. //! Calls SendMsg with gravity set to Message_Warning. void SendWarning (const TopoDS_Shape& shape, const Message_Msg& message) const; //! Calls previous method for myShape. void SendWarning (const Message_Msg& message) const; //! Sends a fail to be attached to the shape. //! Calls SendMsg with gravity set to Message_Fail. void SendFail (const TopoDS_Shape& shape, const Message_Msg& message) const; //! Calls previous method for myShape. void SendFail (const Message_Msg& message) const; DEFINE_STANDARD_RTTIEXT(ShapeFix_Root,Standard_Transient) protected: //! Auxiliary method for work with three-position //! (on/off/default) flags (modes) in ShapeFix. static Standard_Boolean NeedFix (const Standard_Integer flag, const Standard_Boolean def = Standard_True); TopoDS_Shape myShape; private: Handle(ShapeBuild_ReShape) myContext; Handle(ShapeExtend_BasicMsgRegistrator) myMsgReg; Standard_Real myPrecision; Standard_Real myMinTol; Standard_Real myMaxTol; }; #include <ShapeFix_Root.lxx> #endif // _ShapeFix_Root_HeaderFile
30.310811
139
0.766161
[ "object", "shape" ]
fe61ac5596d7ec3843930286f33e1707c0f0ff7c
50,667
cpp
C++
android-opencv/opencv/modules/video/src/blobtrackanalysishist.cpp
agunksetiajaty/viewercv
539d9f60bc61c3a2761157aa4e44e5d00048dbf1
[ "Apache-2.0" ]
1
2015-11-06T02:07:38.000Z
2015-11-06T02:07:38.000Z
android-opencv/opencv/modules/video/src/blobtrackanalysishist.cpp
agunksetiajaty/viewercv
539d9f60bc61c3a2761157aa4e44e5d00048dbf1
[ "Apache-2.0" ]
null
null
null
android-opencv/opencv/modules/video/src/blobtrackanalysishist.cpp
agunksetiajaty/viewercv
539d9f60bc61c3a2761157aa4e44e5d00048dbf1
[ "Apache-2.0" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "precomp.hpp" #define MAX_FV_SIZE 5 #define BLOB_NUM 5 typedef struct DefBlobFVN { CvBlob blob; CvBlob BlobSeq[BLOB_NUM]; int state; int LastFrame; int FrameNum; } DefBlobFVN; class CvBlobTrackFVGenN: public CvBlobTrackFVGen { private: CvBlobSeq m_BlobList; CvMemStorage* m_pMem; CvSeq* m_pFVSeq; float m_FVMax[MAX_FV_SIZE]; float m_FVMin[MAX_FV_SIZE]; float m_FVVar[MAX_FV_SIZE]; int m_Dim; CvBlob m_BlobSeq[BLOB_NUM]; int m_Frame; int m_State; int m_LastFrame; int m_ClearFlag; void Clear() { if (m_pMem) { cvClearMemStorage(m_pMem); m_pFVSeq = cvCreateSeq(0, sizeof(CvSeq), sizeof(float) * (m_Dim + 1), m_pMem); m_ClearFlag = 1; } } public: CvBlobTrackFVGenN(int dim = 2): m_BlobList(sizeof(DefBlobFVN)) { int i; assert(dim <= MAX_FV_SIZE); m_Dim = dim; for (i = 0; i < m_Dim; ++i) { m_FVVar[i] = 0.01f; m_FVMax[i] = 1; m_FVMin[i] = 0; } m_Frame = 0; m_State = 0; m_pMem = cvCreateMemStorage(); m_pFVSeq = NULL; Clear(); switch (dim) { case 2: SetModuleName("P"); break; case 4: SetModuleName("PV"); break; case 5: SetModuleName("PVS"); break; } }; ~CvBlobTrackFVGenN() { if (m_pMem) { cvReleaseMemStorage(&m_pMem); } }; void AddBlob(CvBlob* pBlob) { float FV[MAX_FV_SIZE+1]; int i; DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob)); if (!m_ClearFlag) { Clear(); } if (pFVBlob == NULL) { DefBlobFVN BlobNew; BlobNew.blob = pBlob[0]; BlobNew.LastFrame = m_Frame; BlobNew.state = 0;; BlobNew.FrameNum = 0; m_BlobList.AddBlob((CvBlob*)&BlobNew); pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob)); } /* Add new record if necessary. */ pFVBlob->blob = pBlob[0]; /* Shift: */ for (i = (BLOB_NUM - 1); i > 0; --i) { pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1]; } pFVBlob->BlobSeq[0] = pBlob[0]; if (m_Dim > 0) { /* Calculate FV position: */ FV[0] = CV_BLOB_X(pBlob); FV[1] = CV_BLOB_Y(pBlob); } if (m_Dim <= 2) { /* Add new FV if position is enough: */ *(int*)(FV + m_Dim) = CV_BLOB_ID(pBlob); cvSeqPush(m_pFVSeq, FV); } else if (pFVBlob->FrameNum > BLOB_NUM) { /* Calculate velocity for more complex FV: */ float AverVx = 0; float AverVy = 0; { /* Average velocity: */ CvBlob* pBlobSeq = pFVBlob->BlobSeq; int i; for (i = 1; i < BLOB_NUM; ++i) { AverVx += CV_BLOB_X(pBlobSeq + i - 1) - CV_BLOB_X(pBlobSeq + i); AverVy += CV_BLOB_Y(pBlobSeq + i - 1) - CV_BLOB_Y(pBlobSeq + i); } AverVx /= BLOB_NUM - 1; AverVy /= BLOB_NUM - 1; FV[2] = AverVx; FV[3] = AverVy; } if (m_Dim > 4) { /* State duration: */ float T = (CV_BLOB_WX(pBlob) + CV_BLOB_WY(pBlob)) * 0.01f; if (fabs(AverVx) < T && fabs(AverVy) < T) { pFVBlob->state++; } else { pFVBlob->state = 0; } FV[4] = (float)pFVBlob->state; } /* State duration. */ /* Add new FV: */ *(int*)(FV + m_Dim) = CV_BLOB_ID(pBlob); cvSeqPush(m_pFVSeq, FV); } /* If velocity is calculated. */ pFVBlob->FrameNum++; pFVBlob->LastFrame = m_Frame; }; /* AddBlob */ void Process(IplImage* pImg, IplImage* /*pFG*/) { int i; if (!m_ClearFlag) { Clear(); } for (i = m_BlobList.GetBlobNum(); i > 0; --i) { /* Delete unused blob: */ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i - 1); if (pFVBlob->LastFrame < m_Frame) { m_BlobList.DelBlob(i - 1); } } /* Check next blob in list. */ m_FVMin[0] = 0; m_FVMin[1] = 0; m_FVMax[0] = (float)(pImg->width - 1); m_FVMax[1] = (float)(pImg->height - 1); m_FVVar[0] = m_FVMax[0] * 0.01f; m_FVVar[1] = m_FVMax[1] * 0.01f; m_FVVar[2] = (float)(pImg->width - 1) / 1440.0f; m_FVMax[2] = (float)(pImg->width - 1) * 0.02f; m_FVMin[2] = -m_FVMax[2]; m_FVVar[3] = (float)(pImg->width - 1) / 1440.0f; m_FVMax[3] = (float)(pImg->height - 1) * 0.02f; m_FVMin[3] = -m_FVMax[3]; m_FVMax[4] = 25 * 32.0f; /* max state is 32 sec */ m_FVMin[4] = 0; m_FVVar[4] = 10; m_Frame++; m_ClearFlag = 0; }; virtual void Release() {delete this;}; virtual int GetFVSize() {return m_Dim;}; virtual int GetFVNum() { return m_pFVSeq->total; }; virtual float* GetFV(int index, int* pFVID) { float* pFV = (float*)cvGetSeqElem(m_pFVSeq, index); if (pFVID) { pFVID[0] = *(int*)(pFV + m_Dim); } return pFV; }; virtual float* GetFVMin() {return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */ virtual float* GetFVMax() {return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */ virtual float* GetFVVar() {return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */ };/* CvBlobTrackFVGenN */ CvBlobTrackFVGen* cvCreateFVGenP() {return (CvBlobTrackFVGen*)new CvBlobTrackFVGenN(2);} CvBlobTrackFVGen* cvCreateFVGenPV() {return (CvBlobTrackFVGen*)new CvBlobTrackFVGenN(4);} CvBlobTrackFVGen* cvCreateFVGenPVS() {return (CvBlobTrackFVGen*)new CvBlobTrackFVGenN(5);} #undef MAX_FV_SIZE #define MAX_FV_SIZE 4 class CvBlobTrackFVGenSS: public CvBlobTrackFVGen { private: CvBlobSeq m_BlobList; CvMemStorage* m_pMem; CvSeq* m_pFVSeq; float m_FVMax[MAX_FV_SIZE]; float m_FVMin[MAX_FV_SIZE]; float m_FVVar[MAX_FV_SIZE]; int m_Dim; CvBlob m_BlobSeq[BLOB_NUM]; int m_Frame; int m_State; int m_LastFrame; int m_ClearFlag; void Clear() { cvClearMemStorage(m_pMem); m_pFVSeq = cvCreateSeq(0, sizeof(CvSeq), sizeof(float) * (m_Dim + 1), m_pMem); m_ClearFlag = 1; } public: CvBlobTrackFVGenSS(int dim = 2): m_BlobList(sizeof(DefBlobFVN)) { int i; assert(dim <= MAX_FV_SIZE); m_Dim = dim; for (i = 0; i < m_Dim; ++i) { m_FVVar[i] = 0.01f; m_FVMax[i] = 1; m_FVMin[i] = 0; } m_Frame = 0; m_State = 0; m_pMem = cvCreateMemStorage(); m_pFVSeq = NULL; SetModuleName("SS"); }; ~CvBlobTrackFVGenSS() { if (m_pMem) { cvReleaseMemStorage(&m_pMem); } }; void AddBlob(CvBlob* pBlob) { //float FV[MAX_FV_SIZE+1]; int i; DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob)); if (!m_ClearFlag) { Clear(); } if (pFVBlob == NULL) { DefBlobFVN BlobNew; BlobNew.blob = pBlob[0]; BlobNew.LastFrame = m_Frame; BlobNew.state = 0;; BlobNew.FrameNum = 0; m_BlobList.AddBlob((CvBlob*)&BlobNew); pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob)); } /* Add new record if necessary. */ /* Shift: */ for (i = (BLOB_NUM - 1); i > 0; --i) { pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1]; } pFVBlob->BlobSeq[0] = pBlob[0]; if (pFVBlob->FrameNum > BLOB_NUM) { /* Average velocity: */ CvBlob* pBlobSeq = pFVBlob->BlobSeq; float T = (CV_BLOB_WX(pBlob) + CV_BLOB_WY(pBlob)) * 0.01f; float AverVx = 0; float AverVy = 0; int i; for (i = 1; i < BLOB_NUM; ++i) { AverVx += CV_BLOB_X(pBlobSeq + i - 1) - CV_BLOB_X(pBlobSeq + i); AverVy += CV_BLOB_Y(pBlobSeq + i - 1) - CV_BLOB_Y(pBlobSeq + i); } AverVx /= BLOB_NUM - 1; AverVy /= BLOB_NUM - 1; if (fabs(AverVx) < T && fabs(AverVy) < T) { pFVBlob->state++; } else { pFVBlob->state = 0; } } if (pFVBlob->state == 5) { /* Object is stopped: */ float FV[MAX_FV_SIZE]; FV[0] = pFVBlob->blob.x; FV[1] = pFVBlob->blob.y; FV[2] = pFVBlob->BlobSeq[0].x; FV[3] = pFVBlob->BlobSeq[0].y; *(int*)(FV + m_Dim) = CV_BLOB_ID(pBlob); cvSeqPush(m_pFVSeq, FV); } /* Object is stopped. */ pFVBlob->FrameNum++; pFVBlob->LastFrame = m_Frame; }; /* AddBlob */ void Process(IplImage* pImg, IplImage* /*pFG*/) { int i; if (!m_ClearFlag) { Clear(); } for (i = m_BlobList.GetBlobNum(); i > 0; --i) { /* Delete unused blob: */ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i - 1); if (pFVBlob->LastFrame < m_Frame) { float FV[MAX_FV_SIZE+1]; FV[0] = pFVBlob->blob.x; FV[1] = pFVBlob->blob.y; FV[2] = pFVBlob->BlobSeq[0].x; FV[3] = pFVBlob->BlobSeq[0].y; *(int*)(FV + m_Dim) = CV_BLOB_ID(pFVBlob); cvSeqPush(m_pFVSeq, FV); m_BlobList.DelBlob(i - 1); } } /* Check next blob in list. */ /* Set max min range: */ m_FVMin[0] = 0; m_FVMin[1] = 0; m_FVMin[2] = 0; m_FVMin[3] = 0; m_FVMax[0] = (float)(pImg->width - 1); m_FVMax[1] = (float)(pImg->height - 1); m_FVMax[2] = (float)(pImg->width - 1); m_FVMax[3] = (float)(pImg->height - 1); m_FVVar[0] = m_FVMax[0] * 0.01f; m_FVVar[1] = m_FVMax[1] * 0.01f; m_FVVar[2] = m_FVMax[2] * 0.01f; m_FVVar[3] = m_FVMax[3] * 0.01f; m_Frame++; m_ClearFlag = 0; }; virtual void Release() {delete this;}; virtual int GetFVSize() {return m_Dim;}; virtual int GetFVNum() { return m_pFVSeq->total; }; virtual float* GetFV(int index, int* pFVID) { float* pFV = (float*)cvGetSeqElem(m_pFVSeq, index); if (pFVID) { pFVID[0] = *(int*)(pFV + m_Dim); } return pFV; }; virtual float* GetFVMin() {return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */ virtual float* GetFVMax() {return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */ virtual float* GetFVVar() {return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */ };/* CvBlobTrackFVGenSS */ CvBlobTrackFVGen* cvCreateFVGenSS() {return (CvBlobTrackFVGen*)new CvBlobTrackFVGenSS;} /*======================= TRAJECTORY ANALYZER MODULES =====================*/ /* Trajectory Analyser module */ #define SPARSE 0 #define ND 1 #define BYSIZE -1 class DefMat { private: CvSparseMatIterator m_SparseIterator; CvSparseNode* m_pSparseNode; int* m_IDXs; int m_Dim; public: CvSparseMat* m_pSparse; CvMatND* m_pND; int m_Volume; int m_Max; DefMat(int dim = 0, int* sizes = NULL, int type = SPARSE) { /* Create sparse or ND matrix but not both: */ m_pSparseNode = NULL; m_pSparse = NULL; m_pND = NULL; m_Volume = 0; m_Max = 0; m_IDXs = NULL; m_Dim = 0; if (dim > 0 && sizes != 0) { Realloc(dim, sizes, type); } } ~DefMat() { if (m_pSparse) { cvReleaseSparseMat(&m_pSparse); } if (m_pND) { cvReleaseMatND(&m_pND); } if (m_IDXs) { cvFree(&m_IDXs); } } void Realloc(int dim, int* sizes, int type = SPARSE) { if (m_pSparse) { cvReleaseSparseMat(&m_pSparse); } if (m_pND) { cvReleaseMatND(&m_pND); } if (type == BYSIZE) { int size = 0; int i; for (size = 1, i = 0; i < dim; ++i) { size *= sizes[i]; } size *= sizeof(int); if (size > (2 << 20)) { /* if size > 1M */ type = SPARSE; } else { type = ND; } } /* Define matrix type. */ if (type == SPARSE) { m_pSparse = cvCreateSparseMat(dim, sizes, CV_32SC1); m_Dim = dim; } if (type == ND) { m_pND = cvCreateMatND(dim, sizes, CV_32SC1); cvZero(m_pND); m_IDXs = (int*)cvAlloc(sizeof(int) * dim); m_Dim = dim; } m_Volume = 0; m_Max = 0; } void Save(const char* File) { if (m_pSparse) { cvSave(File, m_pSparse); } if (m_pND) { cvSave(File, m_pND); } } void Save(CvFileStorage* fs, const char* name) { if (m_pSparse) { cvWrite(fs, name, m_pSparse); } else if (m_pND) { cvWrite(fs, name, m_pND); } } void Load(const char* File) { CvFileStorage* fs = cvOpenFileStorage(File, NULL, CV_STORAGE_READ); if (fs) { void* ptr; if (m_pSparse) { cvReleaseSparseMat(&m_pSparse); } if (m_pND) { cvReleaseMatND(&m_pND); } m_Volume = 0; m_Max = 0; ptr = cvLoad(File); if (ptr && CV_IS_MATND_HDR(ptr)) { m_pND = (CvMatND*)ptr; } if (ptr && CV_IS_SPARSE_MAT_HDR(ptr)) { m_pSparse = (CvSparseMat*)ptr; } cvReleaseFileStorage(&fs); } AfterLoad(); } /* Load. */ void Load(CvFileStorage* fs, CvFileNode* node, const char* name) { CvFileNode* n = cvGetFileNodeByName(fs, node, name); void* ptr = n ? cvRead(fs, n) : NULL; if (ptr) { if (m_pSparse) { cvReleaseSparseMat(&m_pSparse); } if (m_pND) { cvReleaseMatND(&m_pND); } m_Volume = 0; m_Max = 0; if (CV_IS_MATND_HDR(ptr)) { m_pND = (CvMatND*)ptr; } if (CV_IS_SPARSE_MAT_HDR(ptr)) { m_pSparse = (CvSparseMat*)ptr; } } else { printf("WARNING!!! Can't load %s matrix\n", name); } AfterLoad(); } /* Load. */ void AfterLoad() { m_Volume = 0; m_Max = 0; if (m_pSparse) { /* Calculate Volume of loaded hist: */ CvSparseMatIterator mat_iterator; CvSparseNode* node = cvInitSparseMatIterator(m_pSparse, &mat_iterator); for (; node != 0; node = cvGetNextSparseNode(&mat_iterator)) { int val = *(int*)CV_NODE_VAL(m_pSparse, node); /* get value of the element (assume that the type is CV_32SC1) */ m_Volume += val; if (m_Max < val) { m_Max = val; } } } /* Calculate Volume of loaded hist. */ if (m_pND) { /* Calculate Volume of loaded hist: */ CvMat mat; double max_val; double vol; cvGetMat(m_pND, &mat, NULL, 1); vol = cvSum(&mat).val[0]; m_Volume = cvRound(vol); cvMinMaxLoc(&mat, NULL, &max_val); m_Max = cvRound(max_val); /* MUST BE WRITTEN LATER */ } /* Calculate Volume of loaded hist. */ } /* AfterLoad. */ int* GetPtr(int* indx) { if (m_pSparse) { return (int*)cvPtrND(m_pSparse, indx, NULL, 1, NULL); } if (m_pND) { return (int*)cvPtrND(m_pND, indx, NULL, 1, NULL); } return NULL; } /* GetPtr. */ int GetVal(int* indx) { int* p = GetPtr(indx); if (p) { return p[0]; } return -1; } /* GetVal. */ int Add(int* indx, int val) { int NewVal; int* pVal = GetPtr(indx); if (pVal == NULL) { return -1; } pVal[0] += val; NewVal = pVal[0]; m_Volume += val; if (m_Max < NewVal) { m_Max = NewVal; } return NewVal; } /* Add. */ void Add(DefMat* pMatAdd) { int* pIDXS = NULL; int Val = 0; for (Val = pMatAdd->GetNext(&pIDXS, 1); pIDXS; Val = pMatAdd->GetNext(&pIDXS, 0)) { Add(pIDXS, Val); } } /* Add. */ int SetMax(int* indx, int val) { int NewVal; int* pVal = GetPtr(indx); if (pVal == NULL) { return -1; } if (val > pVal[0]) { m_Volume += val - pVal[0]; pVal[0] = val; } NewVal = pVal[0]; if (m_Max < NewVal) { m_Max = NewVal; } return NewVal; } /* Add. */ int GetNext(int** pIDXS, int init = 0) { int Val = 0; pIDXS[0] = NULL; if (m_pSparse) { m_pSparseNode = (init || m_pSparseNode == NULL) ? cvInitSparseMatIterator(m_pSparse, &m_SparseIterator) : cvGetNextSparseNode(&m_SparseIterator); if (m_pSparseNode) { int* pVal = (int*)CV_NODE_VAL(m_pSparse, m_pSparseNode); if (pVal) { Val = pVal[0]; } pIDXS[0] = CV_NODE_IDX(m_pSparse, m_pSparseNode); } }/* Sparse matrix. */ if (m_pND) { int i; if (init) { for (i = 0; i < m_Dim; ++i) { m_IDXs[i] = cvGetDimSize(m_pND, i) - 1; } pIDXS[0] = m_IDXs; Val = GetVal(m_IDXs); } else { for (i = 0; i < m_Dim; ++i) { if ((m_IDXs[i]--) > 0) { break; } m_IDXs[i] = cvGetDimSize(m_pND, i) - 1; } if (i == m_Dim) { pIDXS[0] = NULL; } else { pIDXS[0] = m_IDXs; Val = GetVal(m_IDXs); } } /* Get next ND. */ } /* Sparse matrix. */ return Val; }; /* GetNext. */ }; #define FV_NUM 10 #define FV_SIZE 10 typedef struct DefTrackFG { CvBlob blob; // CvBlobTrackFVGen* pFVGen; int LastFrame; float state; DefMat* pHist; } DefTrackFG; class CvBlobTrackAnalysisHist : public CvBlobTrackAnalysis { /*---------------- Internal functions: --------------------*/ private: int m_BinNumParam; int m_SmoothRadius; const char* m_SmoothKernel; float m_AbnormalThreshold; int m_TrackNum; int m_Frame; int m_BinNum; char m_DataFileName[1024]; int m_Dim; int* m_Sizes; DefMat m_HistMat; int m_HistVolumeSaved; int* m_pFVi; int* m_pFViVar; int* m_pFViVarRes; CvBlobSeq m_TrackFGList; //CvBlobTrackFVGen* (*m_CreateFVGen)(); CvBlobTrackFVGen* m_pFVGen; void SaveHist() { if (m_DataFileName[0]) { m_HistMat.Save(m_DataFileName); m_HistVolumeSaved = m_HistMat.m_Volume; } }; void LoadHist() { if (m_DataFileName[0]) { m_HistMat.Load(m_DataFileName); } m_HistVolumeSaved = m_HistMat.m_Volume; } void AllocData() { /* AllocData: */ m_pFVi = (int*)cvAlloc(sizeof(int) * m_Dim); m_pFViVar = (int*)cvAlloc(sizeof(int) * m_Dim); m_pFViVarRes = (int*)cvAlloc(sizeof(int) * m_Dim); m_Sizes = (int*)cvAlloc(sizeof(int) * m_Dim); { /* Create init sparce matrix: */ int i; for (i = 0; i < m_Dim; ++i) { m_Sizes[i] = m_BinNum; } m_HistMat.Realloc(m_Dim, m_Sizes, SPARSE); m_HistVolumeSaved = 0; } /* Create init sparce matrix. */ } /* AllocData. */ void FreeData() { /* FreeData. */ int i; for (i = m_TrackFGList.GetBlobNum(); i > 0; --i) { //DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1); // pF->pFVGen->Release(); m_TrackFGList.DelBlob(i - 1); } cvFree(&m_pFVi); cvFree(&m_pFViVar); cvFree(&m_pFViVarRes); cvFree(&m_Sizes); } /* FreeData. */ virtual void ParamUpdate() { if (m_BinNum != m_BinNumParam) { FreeData(); m_BinNum = m_BinNumParam; AllocData(); } } public: CvBlobTrackAnalysisHist(CvBlobTrackFVGen*(*createFVGen)()): m_TrackFGList(sizeof(DefTrackFG)) { m_pFVGen = createFVGen(); m_Dim = m_pFVGen->GetFVSize(); m_Frame = 0; m_pFVi = 0; m_TrackNum = 0; m_BinNum = 32; m_DataFileName[0] = 0; m_AbnormalThreshold = 0.02f; AddParam("AbnormalThreshold", &m_AbnormalThreshold); CommentParam("AbnormalThreshold", "If trajectory histogram value is lesst then <AbnormalThreshold*DataBaseTrackNum> then trajectory is abnormal"); m_SmoothRadius = 1; AddParam("SmoothRadius", &m_SmoothRadius); CommentParam("AbnormalThreshold", "Radius (in bins) for histogram smoothing"); m_SmoothKernel = "L"; AddParam("SmoothKernel", &m_SmoothKernel); CommentParam("SmoothKernel", "L - Linear, G - Gaussian"); m_BinNumParam = m_BinNum; AddParam("BinNum", &m_BinNumParam); CommentParam("BinNum", "Number of bin for each dimention of feature vector"); AllocData(); SetModuleName("Hist"); } /* Constructor. */ ~CvBlobTrackAnalysisHist() { SaveHist(); FreeData(); m_pFVGen->Release(); } /* Destructor. */ /*----------------- Interface: --------------------*/ virtual void AddBlob(CvBlob* pBlob) { DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob)); if (pF == NULL) { /* create new filter */ DefTrackFG F; F.state = 0; F.blob = pBlob[0]; F.LastFrame = m_Frame; // F.pFVGen = m_CreateFVGen(); F.pHist = new DefMat(m_Dim, m_Sizes, SPARSE); m_TrackFGList.AddBlob((CvBlob*)&F); pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob)); } assert(pF); pF->blob = pBlob[0]; pF->LastFrame = m_Frame; m_pFVGen->AddBlob(pBlob); }; virtual void Process(IplImage* pImg, IplImage* pFG) { int i; m_pFVGen->Process(pImg, pFG); int SK = m_SmoothKernel[0]; for (i = 0; i < m_pFVGen->GetFVNum(); ++i) { int BlobID = 0; float* pFV = m_pFVGen->GetFV(i, &BlobID); float* pFVMax = m_pFVGen->GetFVMax(); float* pFVMin = m_pFVGen->GetFVMin(); DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID); int HistVal = 1; if (pFV == NULL) { break; } pF->LastFrame = m_Frame; { /* Binarize FV: */ int j; for (j = 0; j < m_Dim; ++j) { int index; float f0 = pFVMin ? pFVMin[j] : 0; float f1 = pFVMax ? pFVMax[j] : 1; assert(f1 > f0); index = cvRound((m_BinNum - 1) * (pFV[j] - f0) / (f1 - f0)); if (index < 0) { index = 0; } if (index >= m_BinNum) { index = m_BinNum - 1; } m_pFVi[j] = index; } } HistVal = m_HistMat.GetVal(m_pFVi);/* get bin value*/ pF->state = 0; { /* Calculate state: */ float T = m_HistMat.m_Max * m_AbnormalThreshold; /* calc threshold */ if (m_TrackNum > 0) { T = 256.0f * m_TrackNum * m_AbnormalThreshold; } if (T > 0) { pF->state = (T - HistVal) / (T * 0.2f) + 0.5f; } if (pF->state < 0) { pF->state = 0; } if (pF->state > 1) { pF->state = 1; } } { /* If it is a new FV then add it to trajectory histogram: */ int i, flag = 1; int r = m_SmoothRadius; // printf("BLob %3d NEW FV [", CV_BLOB_ID(pF)); // for(i=0;i<m_Dim;++i) printf("%d,", m_pFVi[i]); // printf("]"); for (i = 0; i < m_Dim; ++i) { m_pFViVar[i] = -r; } while (flag) { float dist = 0; int HistAdd = 0; int i; int good = 1; for (i = 0; i < m_Dim; ++i) { m_pFViVarRes[i] = m_pFVi[i] + m_pFViVar[i]; if (m_pFViVarRes[i] < 0) { good = 0; } if (m_pFViVarRes[i] >= m_BinNum) { good = 0; } dist += m_pFViVar[i] * m_pFViVar[i]; }/* Calculate next dimension. */ if (SK == 'G' || SK == 'g') { double dist2 = dist / (r * r); HistAdd = cvRound(256 * exp(-dist2)); /* Hist Add for (dist=1) = 25.6*/ } else if (SK == 'L' || SK == 'l') { dist = (float)(sqrt(dist) / (r + 1)); HistAdd = cvRound(256 * (1 - dist)); } else { HistAdd = 255; /* Flat smoothing. */ } if (good && HistAdd > 0) { /* Update histogram: */ assert(pF->pHist); pF->pHist->SetMax(m_pFViVarRes, HistAdd); } /* Update histogram. */ for (i = 0; i < m_Dim; ++i) { /* Next config: */ if ((m_pFViVar[i]++) < r) { break; } m_pFViVar[i] = -r; } /* Increase next dimension variable. */ if (i == m_Dim) { break; } } /* Next variation. */ } /* If new FV. */ } /* Next FV. */ { /* Check all blobs on list: */ int i; for (i = m_TrackFGList.GetBlobNum(); i > 0; --i) { /* Add histogram and delete blob from list: */ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i - 1); if (pF->LastFrame + 3 < m_Frame && pF->pHist) { m_HistMat.Add(pF->pHist); delete pF->pHist; m_TrackNum++; m_TrackFGList.DelBlob(i - 1); } }/* next blob */ } m_Frame++; if (m_Wnd) { /* Debug output: */ int* idxs = NULL; int Val = 0; IplImage* pI = cvCloneImage(pImg); cvZero(pI); for (Val = m_HistMat.GetNext(&idxs, 1); idxs; Val = m_HistMat.GetNext(&idxs, 0)) { /* Draw all elements: */ float vf; int x, y; if (!idxs) { break; } if (Val == 0) { continue; } vf = (float)Val / (m_HistMat.m_Max ? m_HistMat.m_Max : 1); x = cvRound((float)(pI->width - 1) * (float)idxs[0] / (float)m_BinNum); y = cvRound((float)(pI->height - 1) * (float)idxs[1] / (float)m_BinNum); cvCircle(pI, cvPoint(x, y), cvRound(vf * pI->height / (m_BinNum * 2)), CV_RGB(255, 0, 0), CV_FILLED); if (m_Dim > 3) { int dx = -2 * (idxs[2] - m_BinNum / 2); int dy = -2 * (idxs[3] - m_BinNum / 2); cvLine(pI, cvPoint(x, y), cvPoint(x + dx, y + dy), CV_RGB(0, cvRound(vf * 255), 1)); } if (m_Dim == 4 && m_pFVGen->GetFVMax()[0] == m_pFVGen->GetFVMax()[2] && m_pFVGen->GetFVMax()[1] == m_pFVGen->GetFVMax()[3]) { int x = cvRound((float)(pI->width - 1) * (float)idxs[2] / (float)m_BinNum); int y = cvRound((float)(pI->height - 1) * (float)idxs[3] / (float)m_BinNum); cvCircle(pI, cvPoint(x, y), cvRound(vf * pI->height / (m_BinNum * 2)), CV_RGB(0, 0, 255), CV_FILLED); } } /* Draw all elements. */ for (i = m_TrackFGList.GetBlobNum(); i > 0; --i) { DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i - 1); DefMat* pHist = pF ? pF->pHist : NULL; if (pHist == NULL) { continue; } for (Val = pHist->GetNext(&idxs, 1); idxs; Val = pHist->GetNext(&idxs, 0)) { /* Draw all elements: */ float vf; int x, y; if (!idxs) { break; } if (Val == 0) { continue; } vf = (float)Val / (pHist->m_Max ? pHist->m_Max : 1); x = cvRound((float)(pI->width - 1) * (float)idxs[0] / (float)m_BinNum); y = cvRound((float)(pI->height - 1) * (float)idxs[1] / (float)m_BinNum); cvCircle(pI, cvPoint(x, y), cvRound(2 * vf), CV_RGB(0, 0, cvRound(255 * vf)), CV_FILLED); if (m_Dim > 3) { int dx = -2 * (idxs[2] - m_BinNum / 2); int dy = -2 * (idxs[3] - m_BinNum / 2); cvLine(pI, cvPoint(x, y), cvPoint(x + dx, y + dy), CV_RGB(0, 0, 255)); } if (m_Dim == 4 && m_pFVGen->GetFVMax()[0] == m_pFVGen->GetFVMax()[2] && m_pFVGen->GetFVMax()[1] == m_pFVGen->GetFVMax()[3]) { /* if SS feature vector */ int x = cvRound((float)(pI->width - 1) * (float)idxs[2] / (float)m_BinNum); int y = cvRound((float)(pI->height - 1) * (float)idxs[3] / (float)m_BinNum); cvCircle(pI, cvPoint(x, y), cvRound(vf * pI->height / (m_BinNum * 2)), CV_RGB(0, 0, 255), CV_FILLED); } } /* Draw all elements. */ } /* Next track. */ //cvNamedWindow("Hist",0); //cvShowImage("Hist", pI); cvReleaseImage(&pI); } }; float GetState(int BlobID) { DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID); return pF ? pF->state : 0.0f; }; /* Return 0 if trajectory is normal; rreturn >0 if trajectory abnormal. */ virtual const char* GetStateDesc(int BlobID) { if (GetState(BlobID) > 0.5) { return "abnormal"; } return NULL; } virtual void SetFileName(const char* DataBaseName) { if (m_HistMat.m_Volume != m_HistVolumeSaved) { SaveHist(); } m_DataFileName[0] = 0; if (DataBaseName) { strncpy(m_DataFileName, DataBaseName, 1000); strcat(m_DataFileName, ".yml"); } LoadHist(); }; virtual void SaveState(CvFileStorage* fs) { int b, bN = m_TrackFGList.GetBlobNum(); cvWriteInt(fs, "BlobNum", bN); cvStartWriteStruct(fs, "BlobList", CV_NODE_SEQ); for (b = 0; b < bN; ++b) { DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(b); cvStartWriteStruct(fs, NULL, CV_NODE_MAP); cvWriteStruct(fs, "Blob", &(pF->blob), "ffffi"); cvWriteInt(fs, "LastFrame", pF->LastFrame); cvWriteReal(fs, "State", pF->state); pF->pHist->Save(fs, "Hist"); cvEndWriteStruct(fs); } cvEndWriteStruct(fs); m_HistMat.Save(fs, "Hist"); }; virtual void LoadState(CvFileStorage* fs, CvFileNode* node) { CvFileNode* pBLN = cvGetFileNodeByName(fs, node, "BlobList"); if (pBLN && CV_NODE_IS_SEQ(pBLN->tag)) { int b, bN = pBLN->data.seq->total; for (b = 0; b < bN; ++b) { DefTrackFG* pF = NULL; CvBlob Blob; CvFileNode* pBN = (CvFileNode*)cvGetSeqElem(pBLN->data.seq, b); assert(pBN); cvReadStructByName(fs, pBN, "Blob", &Blob, "ffffi"); AddBlob(&Blob); pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(Blob.ID); if (pF == NULL) { continue; } assert(pF); pF->state = (float)cvReadIntByName(fs, pBN, "State", cvRound(pF->state)); assert(pF->pHist); pF->pHist->Load(fs, pBN, "Hist"); } } m_HistMat.Load(fs, node, "Hist"); }; /* LoadState */ virtual void Release() { delete this; }; }; CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisHistP() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisHist(cvCreateFVGenP);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisHistPV() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisHist(cvCreateFVGenPV);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisHistPVS() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisHist(cvCreateFVGenPVS);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisHistSS() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisHist(cvCreateFVGenSS);} typedef struct DefTrackSVM { CvBlob blob; // CvBlobTrackFVGen* pFVGen; int LastFrame; float state; CvBlob BlobLast; CvSeq* pFVSeq; CvMemStorage* pMem; } DefTrackSVM; class CvBlobTrackAnalysisSVM : public CvBlobTrackAnalysis { /*---------------- Internal functions: --------------------*/ private: CvMemStorage* m_pMem; int m_TrackNum; int m_Frame; char m_DataFileName[1024]; int m_Dim; float* m_pFV; //CvStatModel* m_pStatModel; void* m_pStatModel; CvBlobSeq m_Tracks; CvMat* m_pTrainData; int m_LastTrainDataSize; // CvBlobTrackFVGen* (*m_CreateFVGen)(); CvBlobTrackFVGen* m_pFVGen; float m_NU; float m_RBFWidth; IplImage* m_pStatImg; /* for debug purpose */ CvSize m_ImgSize; void RetrainStatModel() { ///////// !!!!! TODO !!!!! Repair ///////////// #if 0 float nu = 0; CvSVMModelParams SVMParams = {0}; CvStatModel* pM = NULL; memset(&SVMParams, 0, sizeof(SVMParams)); SVMParams.svm_type = CV_SVM_ONE_CLASS; SVMParams.kernel_type = CV_SVM_RBF; SVMParams.gamma = 2.0 / (m_RBFWidth * m_RBFWidth); SVMParams.nu = m_NU; SVMParams.degree = 3; SVMParams.criteria = cvTermCriteria(CV_TERMCRIT_EPS, 100, 1e-3); SVMParams.C = 1; SVMParams.p = 0.1; if (m_pTrainData == NULL) { return; } { int64 TickCount = cvGetTickCount(); printf("Frame: %d\n Retrain SVM\nData Size = %d\n", m_Frame, m_pTrainData->rows); pM = cvTrainSVM(m_pTrainData, CV_ROW_SAMPLE, NULL, (CvStatModelParams*)&SVMParams, NULL, NULL); TickCount = cvGetTickCount() - TickCount ; printf("SV Count = %d\n", ((CvSVMModel*)pM)->sv_total); printf("Processing Time = %.1f(ms)\n", TickCount / (1000 * cvGetTickFrequency())); } if (pM == NULL) { return; } if (m_pStatModel) { cvReleaseStatModel(&m_pStatModel); } m_pStatModel = pM; if (m_pTrainData && m_Wnd) { float MaxVal = 0; IplImage* pW = cvCreateImage(m_ImgSize, IPL_DEPTH_32F, 1); IplImage* pI = cvCreateImage(m_ImgSize, IPL_DEPTH_8U, 1); float* pFVVar = m_pFVGen->GetFVVar(); int i; cvZero(pW); for (i = 0; i < m_pTrainData->rows; ++i) { /* Draw all elements: */ float* pFV = (float*)(m_pTrainData->data.ptr + m_pTrainData->step * i); int x = cvRound(pFV[0] * pFVVar[0]); int y = cvRound(pFV[1] * pFVVar[1]); float r; if (x < 0) { x = 0; } if (x >= pW->width) { x = pW->width - 1; } if (y < 0) { y = 0; } if (y >= pW->height) { y = pW->height - 1; } r = ((float*)(pW->imageData + y * pW->widthStep))[x]; r++; ((float*)(pW->imageData + y * pW->widthStep))[x] = r; if (r > MaxVal) { MaxVal = r; } } /* Next point. */ if (MaxVal > 0) { cvConvertScale(pW, pI, 255 / MaxVal, 0); } cvNamedWindow("SVMData", 0); cvShowImage("SVMData", pI); cvSaveImage("SVMData.bmp", pI); cvReleaseImage(&pW); cvReleaseImage(&pI); } /* Prepare for debug. */ if (m_pStatModel && m_Wnd && m_Dim == 2) { float* pFVVar = m_pFVGen->GetFVVar(); int x, y; if (m_pStatImg == NULL) { m_pStatImg = cvCreateImage(m_ImgSize, IPL_DEPTH_8U, 1); } cvZero(m_pStatImg); for (y = 0; y < m_pStatImg->height; y += 1) for (x = 0; x < m_pStatImg->width; x += 1) { /* Draw all elements: */ float res; uchar* pData = (uchar*)m_pStatImg->imageData + x + y * m_pStatImg->widthStep; CvMat FVmat; float xy[2] = {x / pFVVar[0], y / pFVVar[1]}; cvInitMatHeader(&FVmat, 1, 2, CV_32F, xy); res = cvStatModelPredict(m_pStatModel, &FVmat, NULL); pData[0] = ((res > 0.5) ? 255 : 0); } /* Next point. */ cvNamedWindow("SVMMask", 0); cvShowImage("SVMMask", m_pStatImg); cvSaveImage("SVMMask.bmp", m_pStatImg); } /* Prepare for debug. */ #endif }; void SaveStatModel() { if (m_DataFileName[0]) { if (m_pTrainData) { cvSave(m_DataFileName, m_pTrainData); } } }; void LoadStatModel() { if (m_DataFileName[0]) { CvMat* pTrainData = (CvMat*)cvLoad(m_DataFileName); if (CV_IS_MAT(pTrainData) && pTrainData->width == m_Dim) { if (m_pTrainData) { cvReleaseMat(&m_pTrainData); } m_pTrainData = pTrainData; RetrainStatModel(); } } } public: CvBlobTrackAnalysisSVM(CvBlobTrackFVGen*(*createFVGen)()): m_Tracks(sizeof(DefTrackSVM)) { m_pFVGen = createFVGen(); m_Dim = m_pFVGen->GetFVSize(); m_pFV = (float*)cvAlloc(sizeof(float) * m_Dim); m_Frame = 0; m_TrackNum = 0; m_pTrainData = NULL; m_pStatModel = NULL; m_DataFileName[0] = 0; m_pStatImg = NULL; m_LastTrainDataSize = 0; m_NU = 0.2f; AddParam("Nu", &m_NU); CommentParam("Nu", "Parameters that tunes SVM border elastic"); m_RBFWidth = 1; AddParam("RBFWidth", &m_RBFWidth); CommentParam("RBFWidth", "Parameters that tunes RBF kernel function width."); SetModuleName("SVM"); } /* Constructor. */ ~CvBlobTrackAnalysisSVM() { int i; SaveStatModel(); for (i = m_Tracks.GetBlobNum(); i > 0; --i) { DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i - 1); if (pF->pMem) { cvReleaseMemStorage(&pF->pMem); } //pF->pFVGen->Release(); } if (m_pStatImg) { cvReleaseImage(&m_pStatImg); } cvFree(&m_pFV); } /* Destructor. */ /*----------------- Interface: --------------------*/ virtual void AddBlob(CvBlob* pBlob) { DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob)); m_pFVGen->AddBlob(pBlob); if (pF == NULL) { /* Create new record: */ DefTrackSVM F; F.state = 0; F.blob = pBlob[0]; F.LastFrame = m_Frame; //F.pFVGen = m_CreateFVGen(); F.pMem = cvCreateMemStorage(); F.pFVSeq = cvCreateSeq(0, sizeof(CvSeq), sizeof(float) * m_Dim, F.pMem); F.BlobLast.x = -1; F.BlobLast.y = -1; F.BlobLast.w = -1; F.BlobLast.h = -1; m_Tracks.AddBlob((CvBlob*)&F); pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob)); } assert(pF); pF->blob = pBlob[0]; pF->LastFrame = m_Frame; }; virtual void Process(IplImage* pImg, IplImage* pFG) { int i; float* pFVVar = m_pFVGen->GetFVVar(); m_pFVGen->Process(pImg, pFG); m_ImgSize = cvSize(pImg->width, pImg->height); for (i = m_pFVGen->GetFVNum(); i > 0; --i) { int BlobID = 0; float* pFV = m_pFVGen->GetFV(i, &BlobID); DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID); if (pF && pFV) { /* Process: */ float dx, dy; CvMat FVmat; pF->state = 0; if (m_pStatModel) { int j; for (j = 0; j < m_Dim; ++j) { m_pFV[j] = pFV[j] / pFVVar[j]; } cvInitMatHeader(&FVmat, 1, m_Dim, CV_32F, m_pFV); //pF->state = cvStatModelPredict( m_pStatModel, &FVmat, NULL )<0.5; pF->state = 1.f; } dx = (pF->blob.x - pF->BlobLast.x); dy = (pF->blob.y - pF->BlobLast.y); if (pF->BlobLast.x < 0 || (dx * dx + dy * dy) >= 2 * 2) { /* Add feature vector to train data base: */ pF->BlobLast = pF->blob; cvSeqPush(pF->pFVSeq, pFV); } } /* Process one blob. */ } /* Next FV. */ for (i = m_Tracks.GetBlobNum(); i > 0; --i) { /* Check each blob record: */ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i - 1); if (pF->LastFrame + 3 < m_Frame) { /* Retrain stat model and delete blob filter: */ int mult = 1 + m_Dim; int old_height = m_pTrainData ? m_pTrainData->height : 0; int height = old_height + pF->pFVSeq->total * mult; CvMat* pTrainData = cvCreateMat(height, m_Dim, CV_32F); int j; if (m_pTrainData && pTrainData) { /* Create new train data matrix: */ int h = pTrainData->height; pTrainData->height = MIN(pTrainData->height, m_pTrainData->height); cvCopy(m_pTrainData, pTrainData); pTrainData->height = h; } for (j = 0; j < pF->pFVSeq->total; ++j) { /* Copy new data to train data: */ float* pFVVar = m_pFVGen->GetFVVar(); float* pFV = (float*)cvGetSeqElem(pF->pFVSeq, j); int k; for (k = 0; k < mult; ++k) { int t; float* pTD = (float*)CV_MAT_ELEM_PTR(pTrainData[0], old_height + j * mult + k, 0); memcpy(pTD, pFV, sizeof(float)*m_Dim); if (pFVVar)for (t = 0; t < m_Dim; ++t) { /* Scale FV: */ pTD[t] /= pFVVar[t]; } if (k > 0) { /* Variate: */ for (t = 0; t < m_Dim; ++t) { pTD[t] += m_RBFWidth * 0.5f * (1 - 2.0f * rand() / (float)RAND_MAX); } } } } /* Next new datum. */ if (m_pTrainData) { cvReleaseMat(&m_pTrainData); } m_pTrainData = pTrainData; /* delete track record */ cvReleaseMemStorage(&pF->pMem); m_TrackNum++; m_Tracks.DelBlob(i - 1); } /* End delete. */ } /* Next track. */ /* Retrain data each 1 minute if new data exist: */ if (m_Frame % (25 * 60) == 0 && m_pTrainData && m_pTrainData->rows > m_LastTrainDataSize) { RetrainStatModel(); } m_Frame++; if (m_Wnd && m_Dim == 2) { /* Debug output: */ int x, y; IplImage* pI = cvCloneImage(pImg); if (m_pStatModel && m_pStatImg) for (y = 0; y < pI->height; y += 2) { uchar* pStatData = (uchar*)m_pStatImg->imageData + y * m_pStatImg->widthStep; uchar* pData = (uchar*)pI->imageData + y * pI->widthStep; for (x = 0; x < pI->width; x += 2) { /* Draw all elements: */ int d = pStatData[x]; d = (d << 8) | (d ^ 0xff); *(ushort*)(pData + x * 3) = (ushort)d; } } /* Next line. */ //cvNamedWindow("SVMMap",0); //cvShowImage("SVMMap", pI); cvReleaseImage(&pI); } /* Debug output. */ }; float GetState(int BlobID) { DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID); return pF ? pF->state : 0.0f; }; /* Return 0 if trajectory is normal; return >0 if trajectory abnormal. */ virtual const char* GetStateDesc(int BlobID) { if (GetState(BlobID) > 0.5) { return "abnormal"; } return NULL; } virtual void SetFileName(char* DataBaseName) { if (m_pTrainData) { SaveStatModel(); } m_DataFileName[0] = 0; if (DataBaseName) { strncpy(m_DataFileName, DataBaseName, 1000); strcat(m_DataFileName, ".yml"); } LoadStatModel(); }; virtual void Release() { delete this; }; }; /* CvBlobTrackAnalysisSVM. */ CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisSVMP() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisSVM(cvCreateFVGenP);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisSVMPV() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisSVM(cvCreateFVGenPV);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisSVMPVS() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisSVM(cvCreateFVGenPVS);} CvBlobTrackAnalysis* cvCreateModuleBlobTrackAnalysisSVMSS() {return (CvBlobTrackAnalysis*) new CvBlobTrackAnalysisSVM(cvCreateFVGenSS);}
36.164882
154
0.484832
[ "object", "vector", "model", "3d" ]
fe6a7159529c61b048840515b84615f94b43a05f
30,927
cc
C++
src/cxx/mrs/libmrs/MRS_Sparse.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/mrs/libmrs/MRS_Sparse.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/mrs/libmrs/MRS_Sparse.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
/****************************************************************************** ** Copyright (C) 2008 by CEA ******************************************************************************* ** ** UNIT ** ** Version: 1.0 ** ** Author: Jean-Luc Starck / Florent Sureau Modified ** ** Date: 25/10/08 / 04/10/11 ** ** File: MRS_Sparse.cc ** ******************************************************************************* ** ** DESCRIPTION: Code for sparse representation ** ------------------- ** ******************************************************************************/ #include"MRS_Sparse.h" #include"WT1D_FFT.h" //FCS MODIFIED: adding C_UWT2D transforms for lGMCA inversion void C_UWT2D_ATROUS::alloc(int NsideIn, int NScale, bool nested, type_border TBorder, int lnb_thr) { nest = nested; Nside = NsideIn; if (NScale >= 2) NbrScale=NScale; else NbrScale = (int) (log((double) NsideIn) / log(2.)+1); UWT2D->Bord=TBorder; WTTrans=new Hmap<REAL> [NbrScale]; for (int p=0;p<NbrScale;p++) (WTTrans[p]).alloc(Nside, nest); AllocMem=1; nb_thr=lnb_thr; } void C_UWT2D_ATROUS::transform(Hmap<REAL> & DataIn) { int f,p; fltarray Face,FaceW; Ifloat IFace, *TabTrans; TabTrans=new Ifloat[NbrScale]; Face.alloc(Nside,Nside); IFace.alloc(Face.buffer(), Face.ny(), Face.nx()); for (p=0;p<NbrScale;p++) TabTrans[p].alloc(Face.ny(), Face.nx()); //#pragma omp parallel for default(none) private(f,p,Face,IFace,TabTrans,FaceW) for (f=0; f < 12; f++){ DataIn.get_one_face(Face, f); UWT2D->transform(IFace,TabTrans,NbrScale,nb_thr); for (p=0;p<NbrScale;p++) { FaceW.alloc(TabTrans[p].buffer(),TabTrans[p].ny(),TabTrans[p].nx()); (WTTrans[p]).put_one_face(FaceW, f); } } delete [] TabTrans; } void C_UWT2D_ATROUS::recons(Hmap<REAL> & DataOut) { fltarray *Face,FaceR; Ifloat *IFace, TabTrans; int p,f; Face= new fltarray[NbrScale]; for (p=0;p<NbrScale;p++) (Face[p]).alloc(nside(),nside()); IFace= new Ifloat[NbrScale]; for (p=0;p<NbrScale;p++) (IFace[p]).alloc((Face[p]).buffer(),(Face[p]).ny(),(Face[p]).nx()); //map same region as Face, but Ifloat vs fltarray FaceR.alloc(TabTrans.buffer(),TabTrans.ny(),TabTrans.nx()); //#pragma omp parallel for default(none) private(f,p) shared (NbrScale) for (int f=0; f < 12; f++) { for (p=0;p<NbrScale;p++) (WTTrans[p]).get_one_face(Face[p], f); //For each wavelet scale, get the face UWT2D->recons(IFace,TabTrans,NbrScale,nb_thr); //perform reconstruction DataOut.put_one_face(FaceR, f); //put the result in DataOut } delete [] Face; delete [] IFace; } //End FCSMODIFIED C_UWT2D void C_OWT::alloc(int NsideIn, int NScale, bool nested) { int x=0; nest = nested; Nside = NsideIn; WTTrans.alloc(NsideIn, nested); T_FilterBank = F_MALLAT_7_9; FAS = new FilterAnaSynt; FAS->alloc(T_FilterBank); SBF = new SubBandFilter(*FAS, NORM_L2); SBF->setBorder(I_MIRROR); if (NScale >= 2) NbrScale=NScale; else NbrScale = (int) (log((double) NsideIn) / log(2.)+1); OWT2D = new Ortho_2D_WT(*SBF); } void C_OWT::transform(Hmap<REAL> & DataIn) { fltarray Face; Ifloat IF; Face.alloc(Nside,Nside); IF.alloc(Face.buffer(), Face.ny(), Face.nx()); //cout << "Transform " << endl; for (int f=0; f < 12; f++) { DataIn.get_one_face(Face, f); //cout << " get " << NbrScale << endl; OWT2D->transform(IF,NbrScale); //cout << " put " << endl; WTTrans.put_one_face(Face, f); //cout << " ok " << endl; } //cout << "transform ok " << endl; } void C_OWT::recons(Hmap<REAL> & DataOut) { fltarray Face; Ifloat IF; Face.alloc(nside(),nside()); IF.alloc(Face.buffer(), Face.ny(), Face.nx()); for (int f=0; f < 12; f++) { WTTrans.get_one_face(Face, f); OWT2D->recons(IF,NbrScale); DataOut.put_one_face(Face, f); } } /*ooooooooooooooooooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooooooooooooooooooooooo*/ //Undecimated transforms /****************************************************************************/ //General functions void wp_trans(Hdmap & Map, dblarray & TabCoef, fltarray & WP_W, fltarray & WP_H, int NbrWP_Band, int Lmax,bool BandLimit, bool SqrtFilter, int NScale, int ALM_iter) //FCS Added { int Nside = Map.Nside(); Hdmap Band,Result; Band.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); Result.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); if(BandLimit==false) Result=Map; //FCS Added First wavelet scale: difference between input image and first approximation scale CAlmR ALM,ALM_Band; ALM.alloc(Nside, Lmax); ALM_Band.alloc(Nside, Lmax); ALM.Norm = ALM_Band.Norm = False; ALM.UseBeamEff = ALM_Band.UseBeamEff = False; ALM.set_beam_eff(Lmax, Lmax); ALM_Band.set_beam_eff(Lmax, Lmax); if((NScale==0)||(NScale>NbrWP_Band)) NScale=NbrWP_Band; TabCoef.resize(Map.Npix(),NScale+1); ALM.Niter=ALM_iter;//Nb iterations in ALM transform ALM.alm_trans(Map); for (int b=0; b <= NScale; b++) { // int LMin = (b != NbrWP_Band) ? WP_W(NbrWP_Band-1-b,0): WP_W(0,0); int LMax; if (b == NScale) LMax=(int)WP_W(NbrWP_Band-b,1); else if (b ==0) LMax=Lmax; else LMax=(int)WP_W(NbrWP_Band-b,1); // if (Verbose == True) cout << " WP:Band " << b+1 << ", Lmax = " << LMax << endl; if ((b == NScale) && (SqrtFilter == false)) Band = Result; else { ALM_Band.Set(LMax, LMax); ALM_Band.SetToZero(); // Compute the solution at a given resolution (convolution with H) int FL = MIN(ALM_Band.Lmax(),WP_H.nx()-1); if (FL > ALM.Lmax()) FL = ALM.Lmax(); if (SqrtFilter == false) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) WP_H(l, NbrWP_Band-1-b); ALM_Band.alm_rec(Band); if((b==0)&&(BandLimit==true)) ALM.alm_rec(Result);//FCS Modified: First band is now difference between band-limited Image at Lmax and Lowpass // Compute the coefficients and standard deviations in and out the mask for (int p=0; p < Band.Npix(); p++) { double Val = Band[p]; Band[p] = Result[p] - Val; Result[p] = Val; } } else { //FCS Added: Sqrt filters if(b == NScale) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(WP_H(l,NbrWP_Band-NScale)); } else if (b == 0) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(1.-WP_H(l, NbrWP_Band-1)); } else { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(WP_H(l, NbrWP_Band-b)-WP_H(l, NbrWP_Band-1-b)); } ALM_Band.alm_rec(Band); if((b==0)&&(BandLimit==false)) {//FCS Modified: add Info at multipoles > lmax ALM.alm_rec(Result,true); for (int p=0; p < Band.Npix(); p++){ Result[p]=Map[p]-Result[p]; Band[p]+= Result[p]; } } } } // endelse if (b == NbrWP_Band) for (int p=0; p < Band.Npix(); p++) TabCoef(p, b) = Band[p]; } // fits_write_fltarr("xxcoef.fits", TabCoef); } //FCS ADDED: Pyramidal wavelet transform void wp_trans(Hdmap & Map, dblarray **TabCoef,intarray &NsideBand, fltarray & WP_W, fltarray & WP_H, int NbrWP_Band, int Lmax,bool BandLimit, bool SqrtFilter, int NScale, int ALM_iter) //FCS Added { int Nside = Map.Nside(); long Npix; Hdmap Band,Result; if(BandLimit==false) Result=Map; //FCS Added First wavelet scale: difference between input image and first approximation scale CAlmR ALM; ALM.alloc(Nside, Lmax); ALM.Norm = False; ALM.UseBeamEff = False; ALM.set_beam_eff(Lmax, Lmax); if((NScale==0)||(NScale>NbrWP_Band)) NScale=NbrWP_Band; *TabCoef=new dblarray[NScale+1]; ALM.Niter=ALM_iter;//Nb iterations in ALM transform ALM.alm_trans(Map); for (int b=0; b <= NScale; b++) { printf("Process band %d\n",b); // int LMin = (b != NbrWP_Band) ? WP_W(NbrWP_Band-1-b,0): WP_W(0,0); CAlmR ALM_Band; int LMax; if (b == NScale) LMax=(int)WP_W(NbrWP_Band-b,1); else if (b ==0) LMax=Lmax; else LMax=(int)WP_W(NbrWP_Band-b,1); Npix=(unsigned long) NsideBand(b) * NsideBand(b) * 12ul; (*TabCoef)[b].alloc(Npix); ALM_Band.alloc(NsideBand(b), LMax);//Beware, using ring weighting implies that the ALM are correctly initialized ALM_Band.SetToZero(); ALM_Band.Norm = False; ALM_Band.UseBeamEff = False; ALM_Band.set_beam_eff(LMax, LMax); // Compute the solution at a given resolution (convolution with H) int FL = MIN(ALM_Band.Lmax(),WP_H.nx()-1); if (FL > ALM.Lmax()) FL = ALM.Lmax(); if (SqrtFilter == false) { if((b==0)&&(BandLimit==false)) { Result.SetNside ((int) NsideBand(b), (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); ALM.alm_rec(Result,true,NsideBand(b)); } //Modified such that we can use pyramidal transform : substraction in ALM SPACE //Note that using filter banks results in lower precision for coarsest (and more energetic) scales if(b == NScale) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) WP_H(l, NbrWP_Band-NScale); } else if (b==0) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) (1L - (double) WP_H(l, NbrWP_Band-1)); } else { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) (WP_H(l, NbrWP_Band-b)-WP_H(l, NbrWP_Band-1-b)); } ALM_Band.alm_rec(Band,false,NsideBand(b)); if((b==0)&&(BandLimit==false)) for (int p=0; p < Band.Npix(); p++) Band[p]+=Map[p]-Result[p];//FCS Modified: First band is now difference between band-limited Image at Lmax and Lowpass } else { //FCS Added: Sqrt filters if(b == NScale) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(WP_H(l,NbrWP_Band-NScale)); } else if (b == 0) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(1.-WP_H(l, NbrWP_Band-1)); } else { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) sqrt(WP_H(l, NbrWP_Band-b)-WP_H(l, NbrWP_Band-1-b)); } ALM_Band.alm_rec(Band,false,NsideBand(b)); if((b==0)&&(BandLimit==false)) {//FCS Modified: add Info at multipoles > lmax Result.SetNside ((int) NsideBand(b), (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); ALM.alm_rec(Result,true); for (int p=0; p < Band.Npix(); p++){ Result[p]=Map[p]-Result[p]; Band[p]+= Result[p]; } } } // endelse if (b == NbrWP_Band) for (int p=0; p < Band.Npix(); p++) ((*TabCoef)[b])(p) = Band[p]; } // fits_write_fltarr("xxcoef.fits", TabCoef); } inline void wp_trans(Hdmap & Map, dblarray & TabCoef, fltarray & WP_W, fltarray & WP_H, int NbrWP_Band, int Lmax){wp_trans(Map,TabCoef,WP_W,WP_H,NbrWP_Band,Lmax,false,false,0,0);} //FCS Added inline void wp_trans(Hdmap & Map, dblarray **TabCoef,intarray &NsideBand, fltarray & WP_W, fltarray & WP_H, int NbrWP_Band, int Lmax){wp_trans(Map,TabCoef,NsideBand,WP_W,WP_H,NbrWP_Band,Lmax,false,false,0,0);} //FCS Added /****************************************************************************/ void get_wt_bspline_filter(int nside, fltarray &TabH, fltarray &TabG, fltarray &Win, fltarray & WP_WPFilter, int Lmax, int NbrBand) { WT1D_FFT W; // enum type_wt_filter {WT_PHI,WT_PSI,WT_H,WT_H_TILDE,WT_G,WT_G_TILDE}; type_wt_filter Filter; int LM = Lmax+1; WP_WPFilter.alloc(LM, NbrBand); int Nstep = NbrBand - 1; fltarray TabHH; TabH.alloc(LM, Nstep); TabHH.alloc(LM, Nstep); TabG.alloc(LM, Nstep); Win.alloc(Nstep,2); int b,p,Np = 2*LM; for (b=0; b < Nstep; b++) { // cout << Np << endl; for (p=0; p < LM; p++) { TabH(p, Nstep-1-b) = W.filter(WT_H, p, Np); TabG(p, Nstep-1-b) = W.filter(WT_G, p, Np); if (b > 0) TabHH(p, b) = TabH(p, Nstep-1-b) * TabHH(p,b-1); else TabHH(p, 0) = TabH(p, Nstep-1-b) ; } Np /= 2; } Np = LM; for (b=0; b < Nstep; b++) { Win(Nstep-1-b,0) = 0; Win(Nstep-1-b,1) = Np; Np /= 2; } for (int l=0; l < LM; l++) WP_WPFilter(l,0) = 1. - TabH(l,NbrBand-2); for (int b=1; b < Nstep; b++) for (int l=0; l < LM; l++) WP_WPFilter(l,b) = TabHH(l,b-1) * TabG(l,Nstep-b-1); b = Nstep; for (int l=0; l < LM; l++) WP_WPFilter(l,b) = TabHH(l,b-1); /* fits_write_fltarr("xxhh2.fits", TabHH); cout << " Win = " << Lmax << " " << NbrBand << endl; fits_write_fltarr("xxh2.fits", TabH); fits_write_fltarr("xxg2.fits", TabG); fits_write_fltarr("xxw2.fits", Win); fits_write_fltarr("xxf2.fits", WP_WPFilter);/* // exit(-1); */ } /****************************************************************************/ void mrs_wt_trans(Hdmap & Map, dblarray & TabCoef, fltarray & TabFilter, int Lmax, int NScale, int ALM_iter) { int Nside = Map.Nside(); Hdmap Band,SmoothMap; // cout << "mrs_wt_transL Lmax = " << Lmax << ", Nside = " << Nside << ", Nscale = " << NScale << endl; Band.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); SmoothMap.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); SmoothMap=Map; CAlmR ALM; ALM.alloc(Nside, Lmax); ALM.Norm = False; ALM.UseBeamEff = False; ALM.set_beam_eff(Lmax, Lmax); TabCoef.resize(Map.Npix(),NScale); ALM.Niter=ALM_iter;//Nb iterations in ALM transform int Nstep = NScale - 1; for (int p=0; p < Band.Npix(); p++) Band[p] = Map[p]; // cout << "ALM = "<< endl; ALM.alm_trans(Map); // Map.info((char*) "Input MAP"); // fits_write_fltarr("xxf3.fits", TabFilter); for (int b=0; b < Nstep; b++) { CAlmR ALM_Band; // cout << "AllocBand = "<< b+1 << endl; ALM_Band.alloc(Nside, Lmax); // cout << "BandAlloc ok "<< b+1 << endl; ALM_Band.SetToZero(); // cout << " SetToZero = "<< b+1 << endl; ALM_Band.Norm = False; ALM_Band.UseBeamEff = False; ALM_Band.set_beam_eff(Lmax, Lmax); // cout << " WP:Band " << b+1 << " " << NScale-2-b << ", Lmax = " << Lmax << " TabFilter.nx = " << TabFilter.nx() << endl; // Compute the solution at a given resolution (convolution with H) for (int l=0; l <= Lmax; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) = ALM(l,m) * (REAL) TabFilter(l, Nstep-1-b); ALM_Band.alm_rec(SmoothMap); // SmoothMap.info((char*) "SmoothMap "); for (int p=0; p < Band.Npix(); p++) Band[p] = Band[p] - SmoothMap[p]; // Band.info((char*) "Band "); for (int p=0; p < Band.Npix(); p++) { TabCoef(p, b) = Band[p]; Band[p] = SmoothMap[p]; } } int b = Nstep; for (int p=0; p < Band.Npix(); p++) TabCoef(p, b) = SmoothMap[p]; // fits_write_fltarr("xxcoef.fits", TabCoef); } /****************************************************************************/ //Undecimated class void C_UWT::wt_alloc(int NsideIn, int NScale, int LM, bool nested) { nest = nested; Nside = NsideIn; Lmax=LM; T_Fil = F_ALM_SPLINE; MeyerWT = false; if (T_Fil == F_ALM_MEYER) { wp_alloc(NsideIn, LM, nested); } else // SPLINE Filter { if (NScale >= 2) NbrScale=NScale; else NbrScale = (int) (log((double) NsideIn) / log(2.)-1); NpixPerBand = NsideIn*NsideIn*12; // WTTrans = new Hmap<REAL> [NbrScale]; // for (int b=0; b < NbrScale; b++) (WTTrans[b].alloc)(NsideIn, nested); WTTrans.alloc(NpixPerBand, NbrScale); get_wt_bspline_filter(Nside, WP_H, WP_G, WP_W, WP_WPFilter, Lmax, NbrScale); double EnerBand; TabNorm.alloc(NbrScale); TabMad.alloc(NbrScale); for (int b=0; b < NbrScale; b++) { EnerBand = 0.; for (int l=0; l <= MIN(Lmax, WP_WPFilter.nx()-1); l++) { EnerBand += (2.*l+1)* WP_WPFilter(l, b)* WP_WPFilter(l, b); } TabNorm(b) = sqrt( EnerBand / (double) NpixPerBand); // cout << "Band " << b+1 << ", Norm = " << TabNorm(b) << endl; } } } /****************************************************************************/ void C_UWT::hard_thresholding(int b, float NSigma, float & SigmaNoise, bool UseMad) { float Level = SigmaNoise * NSigma; if (UseMad == true) { fltarray Tab; Tab.alloc(WTTrans.nx()); for (int i=0; i < Tab.nx(); i++) Tab(i) = WTTrans(i,b); SigmaNoise = get_sigma_mad(Tab.buffer(), Tab.n_elem() ); Level = SigmaNoise * NSigma; TabMad(b) = SigmaNoise; } else Level = SigmaNoise * NSigma * TabNorm(b); for (int i=0; i < WTTrans.nx(); i++) { if (ABS(WTTrans(i,b)) < Level) WTTrans(i,b) = 0; } } /****************************************************************************/ void C_UWT::set_band(int b, float Value) { for (int i=0; i < WTTrans.nx(); i++) WTTrans(i,b) = Value; } /****************************************************************************/ void C_UWT::hard_thresholding(Hmap<REAL> & DataIn, float NSigma, float & SigmaNoise, bool UseMad, bool KillLastScale) { transform(DataIn); for (int b=0; b < NbrScale-1; b++) hard_thresholding(b, NSigma, SigmaNoise, UseMad); if (KillLastScale == true) set_band(NbrScale-1, 0.); // fits_write_dblarr("xx_wt.fits", WTTrans ); recons(DataIn); } /****************************************************************************/ void C_UWT::wp_alloc(int NsideIn, int LM, bool nested) { nest = nested; Nside = NsideIn; Lmax=LM; MeyerWT = true; if (All_WP_Band == False) get_wp_meyer_filter(Nside, WP_H, WP_G, WP_W, WP_WPFilter, Lmax); else get_planck_wp_meyer_filter(WP_H, WP_G, WP_W, WP_WPFilter, Lmax, Lmax); NbrScale = WP_H.ny(); // cout << " NN = " << NbrScale << " Lmax = " << Lmax << ", WP_WPFilter: " << WP_WPFilter.nx() << " " << WP_WPFilter.ny() << endl; NpixPerBand = NsideIn*NsideIn*12; WTTrans.alloc(NpixPerBand, NbrScale); // WTTrans = new Hmap<REAL> [NbrScale]; // for (int b=0; b < NbrScale; b++) (WTTrans[b].alloc)(NsideIn, nested); // double CoefN = 1.; double EnerBand; TabNorm.alloc(NbrScale); TabMad.alloc(NbrScale); for (int b=0; b < NbrScale; b++) { EnerBand = 0.; for (int l=0; l <= MIN(Lmax, WP_WPFilter.nx()-1); l++) { EnerBand += (2.*l+1)* WP_WPFilter(l, b)* WP_WPFilter(l, b); } TabNorm(b) = sqrt( EnerBand / (double) NpixPerBand); // cout << "Band " << b+1 << ", Norm = " << TabNorm(b) << endl; } } /****************************************************************************/ void C_UWT::transform(Hmap<REAL> & DataIn) { if (MeyerWT == false) mrs_wt_trans(DataIn, WTTrans, WP_H, Lmax, NbrScale, ALM_iter); else wp_trans(DataIn, WTTrans, WP_W, WP_H, NbrScale, Lmax); } /****************************************************************************/ void C_UWT::transform(Hmap<REAL> & DataIn, bool BandLimit, bool SqrtFilter, int NScale) { // cout << "TRANS" << WP_W.nx() << " " << WP_H.nx() << endl; if (MeyerWT == false) mrs_wt_trans(DataIn, WTTrans, WP_H, Lmax, NbrScale, ALM_iter); else wp_trans(DataIn, WTTrans, WP_W, WP_H, NbrScale, Lmax,BandLimit,SqrtFilter,NScale,ALM_iter); } /****************************************************************************/ void C_UWT::recons(Hmap<REAL> & DataOut) { // for (int b=0; b < NbrScale; b++) DataOut.fill(0.); NbrScale=WTTrans.ny();//FCS added for (int b=0; b < NbrScale; b++) for (int p=0; p < NpixPerBand; p++) DataOut[p] += WTTrans(p, b); } /****************************************************************************/ void C_UWT::recons(Hmap<REAL> & DataOut, bool BandLimit, bool SqrtFilter, int NScale) //FCS added { DataOut.fill(0.); if(SqrtFilter==false) recons(DataOut); else { if(NScale==0) NScale=WTTrans.ny()-1; int Nside = sqrt(WTTrans.nx()/12l); unsigned long Npix=WTTrans.nx(); Hdmap Band,Rec; Band.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); DataOut.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); DataOut.fill(0.); CAlmR ALM,ALM_Band; ALM_Band.alloc(Nside, Lmax); ALM.Norm = ALM_Band.Norm = False; ALM.UseBeamEff = ALM_Band.UseBeamEff = False; ALM_Band.set_beam_eff(Lmax, Lmax); ALM_Band.Set(Lmax, Lmax); ALM_Band.SetToZero(); for (int b=0; b <= NScale; b++) {//NbrWP_Band for(unsigned long p=0;p<Npix;p++) Band[p]=WTTrans(p,b); int LMax; if(b==NScale) LMax=(int) WP_W(NbrScale-NScale,1); else if (b==0) LMax=Lmax; else LMax=(int) WP_W(NbrScale-b,1); ALM.alloc(Nside, LMax); ALM.set_beam_eff(LMax, LMax); ALM.SetToZero(); ALM.Niter=ALM_iter;//Nb iterations in ALM transform ALM.alm_trans(Band); int FL = MIN(ALM.Lmax(),WP_H.nx()-1); if (FL > ALM.Lmax()) FL = ALM.Lmax(); if(b==NScale) {//Low pass filter for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) += (ALM(l,m) * (REAL) sqrt(WP_H(l,NbrScale-NScale))); } else { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) += (ALM(l,m) * (REAL) sqrt(WP_WPFilter(l,b))); } if((b==0)&&(BandLimit==false)) {//FCS Modified: add Info at multipoles > lmax ALM.alm_rec(Rec); for (int p=0; p < Band.Npix(); p++) Rec[p]= Band[p] - Rec[p]; } } ALM_Band.alm_rec(DataOut); if(BandLimit==false) for (int p=0; p < DataOut.Npix(); p++) DataOut[p]+=Rec[p]; } // fits_write_fltarr("xxcoef.fits", TabCoef); } /*ooooooooooooooooooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooooooooooooooooooooooo*/ //Pyramidal transforms /****************************************************************************/ void C_PWT::wp_alloc(int NsideIn, int LM, bool nested) { int LMax,b; nest = nested; Nside = NsideIn; Lmax=LM; if (All_WP_Band == False) get_wp_meyer_filter(Nside, WP_H, WP_G, WP_W, WP_WPFilter, Lmax); else get_planck_wp_meyer_filter(WP_H, WP_G, WP_W, WP_WPFilter, Lmax, Lmax); NbrScale = WP_H.ny(); NsidePerBand.alloc(NbrScale+1); NpixPerBand.alloc(NbrScale+1); for(b=0;b<=NbrScale;b++) { if (b == NbrScale) LMax=(int)WP_W(0,1); else if (b ==0) LMax=Lmax; else LMax=(int)WP_W(NbrScale-b,1); NsidePerBand(b)=max((int) pow(2.,ceil(log( (double) LMax)/log(2.))-1.),64);//Compute the Nside parameter (power of two such that 2*Nside > Lmax) NpixPerBand(b)=(unsigned long) NsidePerBand(b) * NsidePerBand(b) * 12ul; } } /****************************************************************************/ void C_PWT::transform(Hmap<REAL> & DataIn, bool BandLimit, bool SqrtFilter, int NScale) { wp_trans(DataIn, &PWTTrans,NsidePerBand, WP_W, WP_H, NbrScale, Lmax,BandLimit,SqrtFilter,NScale,ALM_iter); WTalloc=true; } /****************************************************************************/ void C_PWT::recons(Hmap<REAL> & DataOut, bool BandLimit, bool SqrtFilter, int NScale) //FCS added { if(NScale==0) { printf("Should specify the number of scales for Pyramidal wavelet transform\n"); exit(-1); } Hdmap Band,Rec; DataOut.SetNside ((int) Nside, (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); DataOut.fill(0.); CAlmR ALM,ALM_Band; ALM_Band.alloc(Nside, Lmax);//Beware of ring weighting (Nside and not NsidePerBand(b)) ALM.Norm = ALM_Band.Norm = False; ALM.UseBeamEff = ALM_Band.UseBeamEff = False; ALM_Band.set_beam_eff(Lmax, Lmax); ALM_Band.Set(Lmax, Lmax); ALM_Band.SetToZero(); for (int b=0; b <= NScale; b++) {//NbrWP_Band Band.SetNside ((int) NsidePerBand(b), (Healpix_Ordering_Scheme) DEF_MRS_ORDERING); for(long p=0;p<Band.Npix();p++) Band[p]=(PWTTrans[b])(p); int LMax; if(b==NScale) LMax=(int) WP_W(NbrScale-NScale,1); else if (b==0) LMax=Lmax; else LMax=(int) WP_W(NbrScale-b,1); ALM.alloc( NsidePerBand(b), LMax);//Beware of ring weighting (NsidePerBand(b) and not Nside) ALM.set_beam_eff(LMax, LMax); ALM.SetToZero(); ALM.Niter=ALM_iter;//Nb iterations in ALM transform ALM.alm_trans(Band); int FL = MIN(ALM.Lmax(),WP_H.nx()-1); if (FL > ALM.Lmax()) FL = ALM.Lmax(); if(SqrtFilter==false) { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) += ALM(l,m) ; } else { if(b==NScale) {//Low pass filter for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) += (ALM(l,m) * (REAL) sqrt(WP_H(l,NbrScale-NScale))); } else { for (int l=0; l <= FL; l++) for (int m=0; m <= l; m++) ALM_Band(l,m) += (ALM(l,m) * (REAL) sqrt(WP_WPFilter(l,b))); } } if((b==0)&&(BandLimit==false)) {//FCS Modified: add Info at multipoles > lmax printf("NO BAND LIMIT\n"); ALM.alm_rec(Rec); for (int p=0; p < Band.Npix(); p++) Rec[p]= Band[p] - Rec[p]; } } ALM_Band.alm_rec(DataOut); if(BandLimit==false) for (int p=0; p < DataOut.Npix(); p++) DataOut[p]+=Rec[p]; } /****************************************************************************/ void C_PWT::read_scales(char *Name_Imag_In, int &LM,int &NScale, bool order) { char prefix_inv[512],NameIn[512],suffix_inv[512],TempInv[512], * pos_substr, * pos_substr2; int len_substr,offset_str; if (strstr(Name_Imag_In, ".fit") != NULL) strcpy(NameIn, Name_Imag_In); else sprintf(NameIn, "%s.%s", Name_Imag_In, "fits"); if (strstr(Name_Imag_In, "_scale0_") == NULL) { printf("Wavelet scales do not follow proper string formatting (should contain _scale0_)\n"); exit(-1); } pos_substr=strstr(NameIn,"_scale"); len_substr=pos_substr-NameIn; strncpy(prefix_inv,NameIn,len_substr); prefix_inv[len_substr]='\0'; if ((pos_substr=strstr(NameIn,"_over")) == NULL) { printf("Wavelet scales do not follow proper string formatting (should contain _over)\n"); exit(-1); } pos_substr2=strstr(NameIn,".fits"); offset_str=(pos_substr-NameIn); len_substr=pos_substr2-pos_substr; memcpy(suffix_inv,&(NameIn[offset_str]),len_substr); suffix_inv[len_substr]='\0'; if(order == RING) nest=false; else nest=true; //How many scales? Check according to the name ifstream infile; int kb=0; sprintf(TempInv,"%s_scale%d%s.fits",prefix_inv,kb,suffix_inv); infile.open(TempInv); while(infile.is_open()) { infile.close(); kb++; sprintf(TempInv,"%s_scale%d%s.fits",prefix_inv,kb,suffix_inv); infile.open(TempInv); } NScale=kb-1; printf("NScale=%d\n",NScale); PWTTrans = new dblarray[NScale+1]; WTalloc=true; for(int kb=0;kb<=NScale;kb++) { sprintf(TempInv,"%s_scale%d%s.fits",prefix_inv,kb,suffix_inv); printf("Process file %s\n",TempInv); fits_read_dblarr(TempInv,(PWTTrans)[kb]); } Nside=sqrt((PWTTrans[0]).nx()/ 12ul); if(LM == 0) LM=min(2*Nside,ALM_MAX_L);//default value for Lmax wp_alloc(Nside, LM, DEF_MRS_ORDERING);//Ring Format (quicker spherical harmonic transform) } /****************************************************************************/ void C_PWT::write_scales(char *Name_Imag_Out, int NScale) { char prefix_inv[512],NameOut[512],TempInv[512], * pos_substr; int len_substr; if (strstr(Name_Imag_Out, ".fit") != NULL) strcpy(NameOut, Name_Imag_Out); else sprintf(NameOut, "%s.%s", Name_Imag_Out, "fits"); pos_substr=strstr(NameOut,".fits"); len_substr=pos_substr-NameOut; strncpy(prefix_inv,NameOut,len_substr); prefix_inv[len_substr]='\0'; for(int kb=0;kb<=NScale;kb++) { sprintf(TempInv,"%s_scale%d_over%d.fits",prefix_inv,kb,NScale); fits_write_dblarr(TempInv,(PWTTrans)[kb]); } } /****************************************************************************/ /* void MRS_GMCA::transform_sources(fltarray &Data, fltarray &DataOut, bool reverse) { for (int c=0; c < Data.ny(); c++) { for (int f=0; f < 12; f++) { fltarray Face; Ifloat IF; Face.alloc(nside(),nside()); IF.alloc(Face.buffer(), Face.ny(), Face.nx()); for (int x=0; x < nside(); x++) for (int y=0; y < nside(); y++) Face(y,x) = Data( WTTrans.xyf2ind(x,y,f), c); if (reverse == false) OWT2D->transform(IF,nscale()); else OWT2D->recons(IF,nscale()); for (int x=0; x < nside(); x++) for (int y=0; y < nside(); y++) DataOut( WTTrans.xyf2ind(x,y,f), c) = Face(y,x); } } } */ /****************************************************************************/ /*********************************************************************/
36.686833
221
0.532253
[ "transform" ]
fe6cecabe16d0ce06574ef40262980bad668f56a
11,712
cpp
C++
GTE/Samples/Mathematics/FitConeByEllipseAndPoints/FitConeByEllipseAndPointsWindow3.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
null
null
null
GTE/Samples/Mathematics/FitConeByEllipseAndPoints/FitConeByEllipseAndPointsWindow3.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
1
2022-03-18T00:34:13.000Z
2022-03-18T00:34:13.000Z
GTE/Samples/Mathematics/FitConeByEllipseAndPoints/FitConeByEllipseAndPointsWindow3.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
1
2022-03-17T21:54:55.000Z
2022-03-17T21:54:55.000Z
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.02.25 #include "FitConeByEllipseAndPointsWindow3.h" #include <Graphics/MeshFactory.h> #include <Graphics/ConstantColorEffect.h> #include <Mathematics/ApprCone3EllipseAndPoints.h> #include <random> std::array<std::string, 4> FitConeByEllipseAndPointsWindow3::msFile = { "CircleAndVertex.txt", "OneCircleOneEllipse.txt", "TwoEllipses.txt", "TwoPartialEllipses.txt" }; FitConeByEllipseAndPointsWindow3::FitConeByEllipseAndPointsWindow3(Parameters& parameters) : Window3(parameters), mFileSelection(0), mBlendState(), mNoCullState(), mNoCullWireState(), mPoints{}, mPointMesh{}, mBoxMesh{}, mEllipseMesh{}, mConeMesh{}, mDrawPointMesh(false), mDrawBoxMesh(false), mDrawEllipseMesh(true), mDrawConeMesh(true) { if (!SetEnvironment()) { parameters.created = false; return; } mBlendState = std::make_shared<BlendState>(); mBlendState->target[0].enable = true; mBlendState->target[0].srcColor = BlendState::Mode::SRC_ALPHA; mBlendState->target[0].dstColor = BlendState::Mode::INV_SRC_ALPHA; mBlendState->target[0].srcAlpha = BlendState::Mode::SRC_ALPHA; mBlendState->target[0].dstAlpha = BlendState::Mode::INV_SRC_ALPHA; mNoCullState = std::make_shared<RasterizerState>(); mNoCullState->cull = RasterizerState::Cull::NONE; mNoCullWireState = std::make_shared<RasterizerState>(); mNoCullWireState->cull = RasterizerState::Cull::NONE; mNoCullWireState->fill = RasterizerState::Fill::WIREFRAME; mEngine->SetRasterizerState(mNoCullState); InitializeCamera(60.0f, GetAspectRatio(), 0.001f, 100.0f, 0.0001f, 0.0001f, { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }); CreateScene(); } void FitConeByEllipseAndPointsWindow3::OnIdle() { mTimer.Measure(); if (mCameraRig.Move()) { mPVWMatrices.Update(); } mEngine->ClearBuffers(); if (mDrawPointMesh) { mEngine->Draw(mPointMesh); } if (mDrawBoxMesh) { for (auto const& mesh : mBoxMesh) { mEngine->Draw(mesh); } } if (mDrawEllipseMesh) { mEngine->Draw(mEllipseMesh[0]); mEngine->Draw(mEllipseMesh[1]); } if (mDrawConeMesh) { mEngine->SetBlendState(mBlendState); mEngine->Draw(mConeMesh); mEngine->SetDefaultBlendState(); } mEngine->Draw(8, mYSize - 8, { 0.0f, 0.0f, 0.0f, 1.0f }, mTimer.GetFPS()); mEngine->DisplayColorBuffer(0); mTimer.UpdateFrameCount(); } bool FitConeByEllipseAndPointsWindow3::OnCharPress(uint8_t key, int32_t x, int32_t y) { switch (key) { case '0': if (mFileSelection != 0) { mFileSelection = 0; DeleteScene(); CreateScene(); } return true; case '1': if (mFileSelection != 1) { mFileSelection = 1; DeleteScene(); CreateScene(); } return true; case '2': if (mFileSelection != 2) { mFileSelection = 2; DeleteScene(); CreateScene(); } return true; case '3': if (mFileSelection != 3) { mFileSelection = 3; DeleteScene(); CreateScene(); } return true; case 'p': case 'P': mDrawPointMesh = !mDrawPointMesh; return true; case 'b': case 'B': mDrawBoxMesh = !mDrawBoxMesh; return true; case 'e': case 'E': mDrawEllipseMesh = !mDrawEllipseMesh; return true; case 'c': case 'C': mDrawConeMesh = !mDrawConeMesh; return true; case 'w': case 'W': if (mEngine->GetRasterizerState() == mNoCullWireState) { mEngine->SetRasterizerState(mNoCullState); } else { mEngine->SetRasterizerState(mNoCullWireState); } return true; } return Window3::OnCharPress(key, x, y); } bool FitConeByEllipseAndPointsWindow3::SetEnvironment() { std::string path = GetGTEPath(); if (path == "") { return false; } mEnvironment.Insert(path + "/Samples/Data/"); mEnvironment.Insert(path + "/Samples/Mathematics/FitConeByEllipseAndPoints/Data/"); for (auto const& input : msFile) { if (mEnvironment.GetPath(input) == "") { LogError("Cannot find file " + input); return false; } } return true; } void FitConeByEllipseAndPointsWindow3::CreateScene() { std::string path = mEnvironment.GetPath(msFile[mFileSelection]); std::ifstream input(path); // Subtract out the averages of the points so that you can rotate the // scene using the virtual trackball (move by left-mouse-click-and-drag). Vector3<double> average{ 0.0, 0.0, 0.0 }; for (;;) { Vector3<double> point{}; input >> point[0] >> point[1] >> point[2]; if (input.eof()) { break; } mPoints.push_back(point); average += point; } input.close(); average /= static_cast<double>(mPoints.size()); for (auto& p : mPoints) { p -= average; } // Extract ellipses from the points. ApprCone3ExtractEllipses<double> extractor{}; std::vector<Ellipse3<double>> ellipses{}; extractor.Extract(mPoints, 1e-06, 1e-06, ellipses); // Fit a cone to an ellipse and the points. ApprCone3EllipseAndPoints<double> fitter{}; auto cone = fitter.Fit(ellipses[0], mPoints); // Access the bounding boxes for visualization. auto const& boxes = extractor.GetBoxes(); VertexFormat vformat{}; vformat.Bind(VASemantic::POSITION, DF_R32G32B32_FLOAT, 0); uint32_t numVertices = static_cast<uint32_t>(mPoints.size()); auto vbuffer = std::make_shared<VertexBuffer>(vformat, numVertices); auto* vertices = vbuffer->Get<Vector3<float>>(); for (size_t i = 0; i < mPoints.size(); ++i) { for (int32_t j = 0; j < 3; ++j) { vertices[i][j] = static_cast<float>(mPoints[i][j]); } } auto ibuffer = std::make_shared<IndexBuffer>(IPType::IP_POLYPOINT, numVertices); auto effect = std::make_shared<ConstantColorEffect>(mProgramFactory, Vector4<float>{ 0.0f, 0.0f, 0.0f, 1.0f }); mPointMesh = std::make_shared<Visual>(vbuffer, ibuffer, effect); mPVWMatrices.Subscribe(mPointMesh); mTrackBall.Attach(mPointMesh); std::default_random_engine dre{}; std::uniform_real_distribution<float> urd(0.25f, 0.75f); MeshFactory mf{}; mf.SetVertexFormat(vformat); mBoxMesh.reserve(boxes.size()); for (size_t i = 0; i < boxes.size(); ++i) { auto const& box = boxes[i]; auto mesh = mf.CreateBox( static_cast<float>(box.extent[0]), static_cast<float>(box.extent[1]), static_cast<float>(box.extent[2])); Vector4<float> color{ urd(dre), urd(dre), urd(dre), 1.0f }; auto colorEffect = std::make_shared<ConstantColorEffect>(mProgramFactory, color); mesh->SetEffect(colorEffect); Vector3<float> translate { static_cast<float>(box.center[0]), static_cast<float>(box.center[1]), static_cast<float>(box.center[2]) }; mesh->localTransform.SetTranslation(translate); Matrix3x3<float> rotate{}; for (int32_t j = 0; j < 3; ++j) { Vector3<float> axis { static_cast<float>(box.axis[j][0]), static_cast<float>(box.axis[j][1]), static_cast<float>(box.axis[j][2]) }; rotate.SetCol(j, axis); } mesh->localTransform.SetRotation(rotate); mPVWMatrices.Subscribe(mesh); mTrackBall.Attach(mesh); mBoxMesh.push_back(mesh); } numVertices = 256; auto const& E0 = ellipses[0]; vbuffer = std::make_shared<VertexBuffer>(vformat, numVertices); vertices = vbuffer->Get<Vector3<float>>(); for (uint32_t i = 0; i < numVertices; ++i) { double t = GTE_C_TWO_PI * static_cast<double>(i) / 256.0; double cs = std::cos(t), sn = std::sin(t); Vector3<double> epoint = E0.center + E0.extent[0] * cs * E0.axis[0] + E0.extent[1] * sn * E0.axis[1]; for (int32_t j = 0; j < 3; ++j) { vertices[i][j] = static_cast<float>(epoint[j]); } } ibuffer = std::make_shared<IndexBuffer>(IPType::IP_POLYPOINT, numVertices); effect = std::make_shared<ConstantColorEffect>(mProgramFactory, Vector4<float>{ 0.0f, 1.0f, 0.0f, 1.0f }); mEllipseMesh[0] = std::make_shared<Visual>(vbuffer, ibuffer, effect); mPVWMatrices.Subscribe(mEllipseMesh[0]); mTrackBall.Attach(mEllipseMesh[0]); auto const& E1 = ellipses[1]; vbuffer = std::make_shared<VertexBuffer>(vformat, numVertices); vertices = vbuffer->Get<Vector3<float>>(); for (uint32_t i = 0; i < numVertices; ++i) { double t = GTE_C_TWO_PI * static_cast<double>(i) / 256.0; double cs = std::cos(t), sn = std::sin(t); Vector3<double> epoint = E1.center + E1.extent[0] * cs * E1.axis[0] + E1.extent[1] * sn * E1.axis[1]; for (int32_t j = 0; j < 3; ++j) { vertices[i][j] = static_cast<float>(epoint[j]); } } ibuffer = std::make_shared<IndexBuffer>(IPType::IP_POLYPOINT, numVertices); effect = std::make_shared<ConstantColorEffect>(mProgramFactory, Vector4<float>{ 1.0f, 0.0f, 0.0f, 1.0f }); mEllipseMesh[1] = std::make_shared<Visual>(vbuffer, ibuffer, effect); mPVWMatrices.Subscribe(mEllipseMesh[1]); mTrackBall.Attach(mEllipseMesh[1]); float const coneHeight = 2.0f; float const coneRadius = coneHeight * (float)cone.tanAngle; mConeMesh = mf.CreateDisk(64, 64, coneRadius); vbuffer = mConeMesh->GetVertexBuffer(); numVertices = vbuffer->GetNumElements(); vertices = vbuffer->Get<Vector3<float>>(); for (uint32_t i = 0; i < numVertices; ++i) { float radial = Length(vertices[i]); vertices[i][2] = coneHeight * radial / coneRadius; } std::array<Vector3<float>, 3> basis{}; basis[0] = { (float)cone.ray.direction[0], (float)cone.ray.direction[1], (float)cone.ray.direction[2] }; ComputeOrthogonalComplement(1, basis.data()); Matrix3x3<float> rotate{}; rotate.SetCol(0, basis[1]); rotate.SetCol(1, basis[2]); rotate.SetCol(2, basis[0]); Vector3<float> translate = { (float)cone.ray.origin[0], (float)cone.ray.origin[1], (float)cone.ray.origin[2] }; mConeMesh->localTransform.SetRotation(rotate); mConeMesh->localTransform.SetTranslation(translate); effect = std::make_shared<ConstantColorEffect>(mProgramFactory, Vector4<float>{ 0.0f, 0.0f, 1.0f, 0.5f }); mConeMesh->SetEffect(effect); mPVWMatrices.Subscribe(mConeMesh); mTrackBall.Attach(mConeMesh); mTrackBall.Update(); mPVWMatrices.Update(); } void FitConeByEllipseAndPointsWindow3::DeleteScene() { mPoints.clear(); mPointMesh.reset(); for (auto& mesh : mBoxMesh) { mesh.reset(); } for (auto& mesh : mEllipseMesh) { mesh.reset(); } mConeMesh.reset(); }
28.358354
90
0.602203
[ "mesh", "vector" ]
fe8095088a368e41c273e09986de7b4b514568c9
8,779
cc
C++
rperp_rpara_profiles/rperp_rpara_profiles.cc
ghadeeralsheshakly/VIDE
77b2a2d3090175aaae2ff206f2ede953a102c743
[ "MIT" ]
null
null
null
rperp_rpara_profiles/rperp_rpara_profiles.cc
ghadeeralsheshakly/VIDE
77b2a2d3090175aaae2ff206f2ede953a102c743
[ "MIT" ]
null
null
null
rperp_rpara_profiles/rperp_rpara_profiles.cc
ghadeeralsheshakly/VIDE
77b2a2d3090175aaae2ff206f2ede953a102c743
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cmath> #include <array> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace std; #include <mpi.h> // simulation constants const double l = 256.0; const long n = 2560; const long np = n*n*n; const double dx = l / n; std::vector<std::string> split_string(const std::string str, const char split_char) { // make return obj std::vector<std::string> result; // split and push each back to result. std::stringstream str_stream(str); std::string element; while(std::getline(str_stream, element, split_char)) { result.push_back(element); } return result; } std::vector< std::array<double, 3> > read_centers(const std::string path) { // Prep return value. std::vector< std::array<double, 3> > centers; // Open and check file. std::ifstream centers_file(path.c_str()); if (centers_file.is_open()) { // line obj to read into. std::string line; // read past headers std::getline(centers_file, line); // now read for centers and push onto return vec. while (std::getline(centers_file, line)) { std::vector<std::string> t = split_string(line, ','); // TODO // hard coding position indexes for now. std::array<double, 3> c = {stod(t[0]), stod(t[1]), stod(t[2])}; // DEBUG // just to be safe... if (c[0] < 0.0 || c[0] >= l || c[1] < 0.0 || c[1] >= l || c[2] < 0.0 || c[2] >= l) { std::cerr << "bad position: " << c[0] << " " << c[1] << " " << c[2] << std::endl; exit(1); } centers.push_back(c); } } else { std::cerr << "Could not read " << path << std::endl; exit(1); } return centers; } int main(int argc, char **argv) { // Initialize MPI stuff MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; int mpi_size, mpi_rank; MPI_Comm_size(comm, &mpi_size); MPI_Comm_rank(comm, &mpi_rank); int master_rank = 0; // command line const std::string centers_path = argv[1]; const std::string field_path = argv[2]; const std::string pre_path = argv[3]; // figure out decomp. if (n % mpi_size != 0) { printf("Bad mpi size %i for grid %li\n", mpi_size, n); } // // Read halo positions. // if (mpi_rank == 0) { printf("# Reading centers %s\n", centers_path.c_str()); } vector< array<double, 3> > centers = read_centers(centers_path); if (mpi_rank == 0) { printf("# Found %lu centers\n", centers.size()); } // // Read field values. // if (mpi_rank == 0) { printf("# Reading %s\n", field_path.c_str()); } const long n_local = n / mpi_size; const long np_local = n_local * n * n; const long local_ix0 = mpi_rank * n_local; double *f = new double[np_local]; FILE *field_file = fopen(field_path.c_str(), "r"); fseek(field_file, sizeof(double) * local_ix0 * n * n, SEEK_SET); fread(f, sizeof(double), np_local, field_file); fclose(field_file); // // Compute field mean and variance. // double f_sum_local = 0.0; double f2_sum_local = 0.0; for (long i = 0; i < np_local; ++i) { f_sum_local += f[i]; f2_sum_local += f[i]*f[i]; } double f_sum; MPI_Allreduce(&f_sum_local, &f_sum, 1, MPI_DOUBLE, MPI_SUM, comm); double f2_sum; MPI_Allreduce(&f2_sum_local, &f2_sum, 1, MPI_DOUBLE, MPI_SUM, comm); double f_mean = f_sum / np; double f2_mean = f2_sum / np; if (mpi_rank == master_rank) { char output_path[1000]; sprintf(output_path, "%sfield_var.txt", pre_path.c_str()); FILE *outfile = fopen(output_path, "w"); fprintf(outfile, "%e %e\n", f_mean, sqrt(f2_mean - f_mean * f_mean)); fclose(outfile); } // // start accumulating radial bins // if (mpi_rank == 0) { puts("# Finding local halos."); } // 10 Mpc/h in 256 Mpc/h const double r_max = 20.0; const int num_r_bins = 50; const double bin_dr = r_max / num_r_bins; const int num_bins = num_r_bins * num_r_bins; long *bin_counts_local = new long[num_bins]; long *bin_counts = new long[num_bins]; double *bin_rperp_sums_local = new double[num_bins]; double *bin_rperp_sums = new double[num_bins]; double *bin_rpara_sums_local = new double[num_bins]; double *bin_rpara_sums = new double[num_bins]; double *bin_f_sums_local = new double[num_bins]; double *bin_f_sums = new double[num_bins]; // iterate over groups for (size_t i_cent = 0; i_cent < centers.size(); ++i_cent) { // reset local stuff for (int i = 0; i < num_bins; ++i) { bin_counts_local[i] = 0; bin_rperp_sums_local[i] = 0.0; bin_rpara_sums_local[i] = 0.0; bin_f_sums_local[i] = 0.0; } // get pc position double cx = centers[i_cent][0]; double cy = centers[i_cent][1]; double cz = centers[i_cent][2]; long ix0 = floor( (cx - r_max) / dx ); long ix1 = ceil( (cx + r_max) / dx ); long iy0 = floor( (cy - r_max) / dx ); long iy1 = ceil( (cy + r_max) / dx ); long iz0 = floor( (cz - r_max) / dx ); long iz1 = ceil( (cz + r_max) / dx ); // iterate over points. for (long ix = ix0; ix <= ix1; ++ix) { // periodic fix long ixw = ix; if (ixw < 0) { ixw += n; } if (ixw >= n) { ixw -= n; } long ix_local = ixw - local_ix0; // check if this is even local before continuing. if (ix_local >= 0 && ix_local < n_local) { double x = dx * (ix + 0.5); double rx = x - cx; double rx2 = rx * rx; for (long iy = iy0; iy <= iy1; ++iy) { long iyw = iy; if (iyw < 0) { iyw += n; } if (iyw >= n) { iyw -= n; } double y = dx * (iy + 0.5); double ry = y - cy; double rperp = sqrt(rx2 + ry * ry); int ibin_rperp = rperp / bin_dr; if (ibin_rperp >= num_r_bins) { continue; } for (long iz = iz0; iz <= iz1; ++iz) { long izw = iz; if (izw < 0) { izw += n; } if (izw >= n) { izw -= n; } double z = dx * (iz + 0.5); double rz = z - cz; double rpara = sqrt(rz*rz); int ibin_rpara = rpara / bin_dr; if (ibin_rpara >= num_r_bins) { continue; } int ibin = ibin_rperp * num_r_bins + ibin_rpara; if (ibin < num_bins) { // got a bin point long ii = (ix_local * n + iyw) * n + izw; bin_counts_local[ibin] += 1; bin_rperp_sums_local[ibin] += rperp; bin_rpara_sums_local[ibin] += rpara; bin_f_sums_local[ibin] += f[ii]; } } } } } // done with binning for this PC. MPI_Allreduce(bin_counts_local, bin_counts, num_bins, MPI_LONG, MPI_SUM, comm); MPI_Allreduce(bin_rperp_sums_local, bin_rperp_sums, num_bins, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(bin_rpara_sums_local, bin_rpara_sums, num_bins, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(bin_f_sums_local, bin_f_sums, num_bins, MPI_DOUBLE, MPI_SUM, comm); // write this pc. // make sure file is empty if (mpi_rank == 0) { char output_path[1000]; sprintf(output_path, "%sprofile_%06d.txt", pre_path.c_str(), (int)i_cent); FILE *outfile = fopen(output_path, "w"); fprintf(outfile, "r_perp,r_para,field_value\n"); for (int i = 0; i < num_bins; ++i) { if (bin_counts[i] > 0) { fprintf(outfile, "%e,%e,%e\n", bin_rperp_sums[i] / bin_counts[i], bin_rpara_sums[i] / bin_counts[i], bin_f_sums[i] / bin_counts[i]); } else { fprintf(outfile, "0.0,0.0,0.0\n"); } } fclose(outfile); } // done with this center } MPI_Finalize(); return 0; }
29.759322
97
0.511562
[ "vector" ]
fe8151aae5944dac1348e2948ab329aaa8b99438
2,487
cc
C++
algos/string_search.cc
fcarreiro/crashingthecode
5a76be0aecfdbe4e913c2d790023c24fbabf80a1
[ "MIT" ]
1
2020-03-07T14:35:16.000Z
2020-03-07T14:35:16.000Z
algos/string_search.cc
fcarreiro/crashingthecode
5a76be0aecfdbe4e913c2d790023c24fbabf80a1
[ "MIT" ]
null
null
null
algos/string_search.cc
fcarreiro/crashingthecode
5a76be0aecfdbe4e913c2d790023c24fbabf80a1
[ "MIT" ]
null
null
null
#include <cstddef> #include <cassert> #include <iostream> #include <string> #include <vector> #include <queue> #include "../test_helpers.h" // #define LARGE_PRIME 1000000007 #define LARGE_PRIME 2147483647 // largest prime that fits in 32 bits #define BASE_PRIME 257 // prime related to the aphabet size inline uint64_t mpow(int base, int expo) { uint64_t ret = 1; for (int i=0; i < expo; ++i) { ret = (ret * base) % LARGE_PRIME; } return ret; } class RollingHash { public: RollingHash() : _hash(0), _length(0) { } void append(unsigned char n) { _hash = (_hash * BASE_PRIME + n) % LARGE_PRIME; _length++; } void append(const std::string& s) { for (auto& e : s) { append(e); } } void pop(unsigned char n) { assert(_length > 0); uint64_t out = (mpow(BASE_PRIME, _length - 1) * n) % LARGE_PRIME; _hash -= out; // % is remainder, not modulo if (_hash >= LARGE_PRIME) { _hash += LARGE_PRIME; } _length--; } void pop(const std::string& s) { for (auto& e : s) { pop(e); } } int length() const { return _length; } uint64_t hash() const { return _hash; } private: uint64_t _hash; int _length; }; template<class C> std::vector<int> rabin_karp(const std::string& pattern, const C& stream) { RollingHash phash; phash.append(pattern); RollingHash chash; std::deque<char> q; std::vector<int> places; int i = 0; for (const auto& e : stream) { chash.append(e); q.push_back(e); if (q.size() > pattern.size()) { const auto& front = q.front(); chash.pop(front); q.pop_front(); } i++; // las vegas method if (chash.hash() == phash.hash() && std::string(q.begin(), q.end()) == pattern) { places.push_back(i - pattern.size()); } } return places; } int main(int argc, char const *argv[]) { TestHelper th; { RollingHash rh; RollingHash f; f.append("alongtimeago"); rh.append("123456789012345678901234567890####****alongtimeago"); rh.pop("123456789012345678901234567890####****"); std::cout << "f.hash() : 0x" << std::hex << f.hash() << std::endl; std::cout << "rh.hash() : 0x" << std::hex << rh.hash() << std::endl; } { auto places = rabin_karp("ABABA", "456ABABABABABA123BA"); std::cout << "Rabin-Karp(ABABA, 456ABABABABABA123BA): "; for (const auto& e : places) { std::cout << e << ", "; } } th.summary(); return 0; }
19.738095
85
0.585042
[ "vector" ]
fe81bc0d22e80107042ee16f1fce5a0dd9086847
1,153
cpp
C++
test/snippet/range/container/aligned_allocator.cpp
marehr/nomchop
a88bfb6f5d4a291a71b6b3192eeac81fdc450d43
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-03-01T11:12:56.000Z
2021-03-01T11:12:56.000Z
test/snippet/range/container/aligned_allocator.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
2
2017-05-17T07:16:19.000Z
2020-02-13T16:10:10.000Z
test/snippet/range/container/aligned_allocator.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
#include <iostream> #include <vector> #include <seqan3/range/container/aligned_allocator.hpp> size_t memory_alignment(void * value, size_t alignment) { return (reinterpret_cast<size_t>(value) & (alignment - 1)); } int main() { // 128-byte memory aligned and 16bit = 2byte address width for each element std::vector<int16_t, seqan3::aligned_allocator<int16_t, 128u>> vec128{1,2,3,4,5}; // vector has no alignment and 16bit = 2byte address width for each element std::vector<int16_t> vec_unaligned{1,2,3,4,5}; // 256-byte memory aligned and 32bit = 4byte address width for each element std::vector<int32_t, seqan3::aligned_allocator<int32_t, 256u>> vec256{1,2,3,4,5}; for (auto && x: vec128) std::cout << "Item: " << x << " (" << &x << ", 128-byte aligned offset: " << memory_alignment(&x, 128u) << ")\n"; for (auto && x: vec_unaligned) std::cout << "Item: " << x << " (" << &x << ", unaligned start: " << memory_alignment(&x, 128u) << ")\n"; for (auto && x: vec256) std::cout << "Item: " << x << " (" << &x << ", 256-byte aligned offset: " << memory_alignment(&x, 256u) << ")\n"; }
36.03125
121
0.61752
[ "vector" ]
fe8d61803b2509b289d2848c7b226ec4efecbc48
1,698
hpp
C++
core/primitives/scheduled_change.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/primitives/scheduled_change.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/primitives/scheduled_change.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_PRIMITIVES_SCHEDULED_CHANGE_HPP #define KAGOME_CORE_PRIMITIVES_SCHEDULED_CHANGE_HPP #include <boost/optional.hpp> #include "primitives/authority.hpp" #include "primitives/common.hpp" #include "primitives/session_key.hpp" namespace kagome::primitives { /// @struct ScheduledChange is used by Grandpa api runtime struct ScheduledChange { std::vector<std::pair<AuthorityId, uint64_t>> next_authorities; BlockNumber delay = 0; }; /// @brief api function returns optional value using ScheduledChangeOptional = boost::optional<ScheduledChange>; /// @brief result type for grandpa forced_change function using ForcedChange = std::pair<BlockNumber, ScheduledChange>; /** * @brief outputs ScheduledChange instance to stream * @tparam Stream stream type * @param s reference to stream * @param v value to output * @return reference to stream */ template <class Stream, typename = std::enable_if_t<Stream::is_encoder_stream>> Stream &operator<<(Stream &s, const ScheduledChange &v) { return s << v.next_authorities << v.delay; } /** * @brief decodes ScheduledChange instance from stream * @tparam Stream stream type * @param s reference to stream * @param v value to decode * @return reference to stream */ template <class Stream, typename = std::enable_if_t<Stream::is_decoder_stream>> Stream &operator>>(Stream &s, ScheduledChange &v) { return s >> v.next_authorities >> v.delay; } } // namespace kagome::primitives #endif // KAGOME_CORE_PRIMITIVES_SCHEDULED_CHANGE_HPP
30.872727
67
0.722026
[ "vector" ]
fe8ec949a133f79cf96629cd1a48b8bd3fdda392
11,606
cpp
C++
compiler/src/ast/ast_fielddef_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
15
2017-08-15T20:46:44.000Z
2021-12-15T02:51:13.000Z
compiler/src/ast/ast_fielddef_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
null
null
null
compiler/src/ast/ast_fielddef_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
1
2017-09-28T14:48:15.000Z
2017-09-28T14:48:15.000Z
#include "ast_fielddef_node.hpp" #include "expr/ast_lambda_node.hpp" #include "symbol/qual_type.hpp" #include "llvm_generator.hpp" #include "parsercontext.hpp" using namespace llvm; Constant* TxFieldDefiningNode::code_gen_const_init_value( LlvmGenerationContext& context, bool genBody ) const { if (! this->cachedConstantInitializer) { ASSERT( this->initExpression && this->initExpression->is_statically_constant(), "Expected constant initializer in " << this ); if ( !genBody ) { if ( auto lambdaExpr = dynamic_cast<TxLambdaExprNode*>( this->initExpression->originalExpr ) ) { this->cachedConstantInitializer = lambdaExpr->code_gen_const_decl( context ); return this->cachedConstantInitializer; } } this->cachedConstantInitializer = this->initExpression->code_gen_const_value( context ); } else if ( genBody ) { if ( dynamic_cast<TxLambdaExprNode*>( this->initExpression->originalExpr ) ) this->initExpression->code_gen_const_value( context ); } return this->cachedConstantInitializer; } Value* TxLocalFieldDefNode::code_gen_field_decl( LlvmGenerationContext& context ) const { return this->field()->get_llvm_value(); } void TxLocalFieldDefNode::code_gen_field( LlvmGenerationContext& context, GenScope* scope ) const { TRACE_CODEGEN( this, context ); if ( this->typeExpression ) this->typeExpression->code_gen_type( context ); ASSERT( this->declaration, "NULL declaration in " << this ); ASSERT( this->declaration->get_storage() == TXS_STACK, "Local field gen can only apply to TX_STACK storage fields: " << this ); // If init expression performs a stack allocation (unbound) of this field's type (instance-equivalent type), // this field shall bind to that allocation. auto type = this->qtype().type(); Value* fieldPtrV; if ( this->initExpression ) { // (since we allow initialization of a longer array with a shorter one, we force explicit allocation if can't guarantee types to be exactly equal) bool maybeMismatchingArrayLen = type->get_type_class() == TXTC_ARRAY && bool( this->typeExpression ); if ( this->initExpression->get_storage() == TXS_UNBOUND_STACK && !maybeMismatchingArrayLen ) { fieldPtrV = this->initExpression->code_gen_addr( context, scope ); } else { // (if storage is TXS_STACK, we allocate new stack space for making copy of already bound stack value) fieldPtrV = type->gen_alloca( context, scope, this->declaration->get_symbol()->get_name() ); // create implicit assignment statement if ( type->get_type_class() == TXTC_ARRAY ) { ASSERT( !this->cachedConstantInitializer, "Constant initializer value already set when initializing array field " << this ); // how handle? Value* initializer = this->initExpression->code_gen_addr( context, scope ); auto lvalTypeIdC = ConstantInt::get( IntegerType::getInt32Ty( context.llvmContext ), type->get_runtime_type_id() ); TxAssignStmtNode::code_gen_array_copy( this, context, scope, type, lvalTypeIdC, fieldPtrV, initializer ); } else { Value* initializer = this->cachedConstantInitializer; if ( !initializer ) { initializer = this->initExpression->code_gen_expr( context, scope ); if ( auto constInit = dyn_cast<Constant>( initializer ) ) this->cachedConstantInitializer = constInit; } scope->builder->CreateStore( initializer, fieldPtrV ); } } } else { fieldPtrV = type->gen_alloca( context, scope, this->declaration->get_symbol()->get_name() ); // We don't automatically invoke default constructor (in future, a code flow validator should check that initialized before first use) } this->field()->set_llvm_value( fieldPtrV ); // Create a debug descriptor for the variable: auto pos = this->get_declaration()->get_definer()->ploc.begin; DILocalVariable *argVarD = context.debug_builder()->createAutoVariable( scope->debug_scope(), this->field()->get_unique_name(), this->get_parser_context()->debug_file(), pos.line, context.get_debug_type( this->qtype() ) ); context.debug_builder()->insertDeclare( fieldPtrV, argVarD, context.debug_builder()->createExpression(), DebugLoc::get( pos.line, pos.column, scope->debug_scope() ), scope->builder->GetInsertBlock() ); } Value* TxNonLocalFieldDefNode::code_gen_field_decl( LlvmGenerationContext& context ) const { if ( !this->field()->has_llvm_value() ) { this->inner_code_gen_field( context, false ); } return this->field()->get_llvm_value(); } void TxNonLocalFieldDefNode::code_gen_field( LlvmGenerationContext& context ) const { if ( !this->field()->has_llvm_value() ) { this->inner_code_gen_field( context, true ); } else if (this->initExpression ) { if ( dynamic_cast<TxLambdaExprNode*>( this->initExpression->originalExpr ) ) this->initExpression->code_gen_const_value( context ); } } static Value* make_constant_nonlocal_field( LlvmGenerationContext& context, Type* llvmType, Constant* constantInitializer, const std::string& name ) { // Also handles the case when there has been a "forward-declaration" of this field: // Note: If the global exists but has the wrong type: return the function with a constantexpr cast to the right type. Constant* maybe = context.llvmModule().getOrInsertGlobal( name, llvmType ); //std::cout << "maybe type: " << maybe->getType() << " value: " << maybe << " llvmType: " << llvmType << std::endl; auto globalV = cast<GlobalVariable>( maybe ); // bails if bitcast has been inserted, which means wrong type has been chosen globalV->setConstant( true ); globalV->setLinkage( GlobalValue::InternalLinkage ); ASSERT( !globalV->hasInitializer(), "global already has initializer: " << globalV ); globalV->setInitializer( constantInitializer ); return globalV; } void TxNonLocalFieldDefNode::inner_code_gen_field( LlvmGenerationContext& context, bool genBody ) const { TRACE_CODEGEN( this, context ); if ( this->typeExpression ) this->typeExpression->code_gen_type( context ); auto fieldDecl = this->get_declaration(); auto uniqueName = fieldDecl->get_unique_full_name(); auto txType = this->qtype(); switch ( fieldDecl->get_storage() ) { case TXS_INSTANCEMETHOD: if ( !( fieldDecl->get_decl_flags() & TXD_ABSTRACT ) ) { // constructors in generic types (that are not pure VALUE specializations) are suppressed as if abstract // (they are not abstract per se, but aren't code generated): auto enclosingType = static_cast<TxEntitySymbol*>( fieldDecl->get_symbol()->get_outer() ) ->get_type_decl()->get_definer()->qtype(); if ( !( ( fieldDecl->get_decl_flags() & ( TXD_CONSTRUCTOR | TXD_INITIALIZER ) ) && enclosingType->is_type_generic() ) ) { Value* fieldVal = nullptr; if ( static_cast<TxLambdaExprNode*>( this->initExpression->originalExpr )->is_suppressed_modifying_method() ) { // modifying instance methods in immutable specializations of generic types are suppressed (as if abstract) auto closureType = context.get_llvm_type( txType ); Type* fieldType = closureType->getStructElementType( 0 ); fieldVal = Constant::getNullValue( fieldType ); } else { ASSERT( this->initExpression, "instance method does not have an initializer/definition: " << fieldDecl->get_unique_full_name() ); auto initLambdaV = this->code_gen_const_init_value( context, genBody ); //fieldVal = initLambdaV; auto funcPtrV = initLambdaV->getAggregateElement( (unsigned) 0 ); fieldVal = funcPtrV; // the naked $func is stored (as opposed to a full lambda object) } this->field()->set_llvm_value( fieldVal ); } } return; case TXS_INSTANCE: if ( !( fieldDecl->get_decl_flags() & ( TXD_CONSTRUCTOR | TXD_INITIALIZER | TXD_GENPARAM | TXD_GENBINDING ) ) ) { // just a type definition; field storage isn't created until parent object is allocated return; } // no break case TXS_GLOBAL: if ( fieldDecl->get_decl_flags() & TXD_EXTERNC ) { // Note: External declaration, no initialization expression. std::string externalName( fieldDecl->get_unique_name() ); if ( txType->get_type_class() == TXTC_FUNCTION ) { // create the external C function declaration LOG_DEBUG( context.LOGGER(), "Codegen for extern-C function declaration '" << externalName << "': " << txType ); StructType* lambdaT = cast<StructType>( context.get_llvm_type( txType ) ); FunctionType* externFuncType = cast<FunctionType>( lambdaT->getElementType( 0 )->getPointerElementType() ); Function* extern_c_func = Function::Create( externFuncType, GlobalValue::ExternalLinkage, externalName, &context.llvmModule() ); extern_c_func->setCallingConv( CallingConv::C ); // construct the lambda object (a Tuplex object in Tuplex name space): auto nullClosureRefV = Constant::getNullValue( lambdaT->getStructElementType( 1 ) ); auto lambdaC = ConstantStruct::get( lambdaT, extern_c_func, nullClosureRefV ); this->field()->set_llvm_value( make_constant_nonlocal_field( context, lambdaT, lambdaC, uniqueName ) ); } else { // create the external C field declaration Type *externFieldT = txType->make_llvm_externc_type( context ); auto externDeclC = cast<GlobalVariable>( context.llvmModule().getOrInsertGlobal( externalName, externFieldT ) ); this->field()->set_llvm_value( externDeclC ); } return; } // no break case TXS_STATIC: case TXS_VIRTUAL: if ( !( fieldDecl->get_decl_flags() & ( TXD_ABSTRACT | TXD_INITIALIZER ) ) ) { if ( this->initExpression ) { if ( this->initExpression->is_statically_constant() ) { Constant* constantInitializer = this->code_gen_const_init_value( context, genBody ); this->field()->set_llvm_value( make_constant_nonlocal_field( context, context.get_llvm_type( txType ), constantInitializer, uniqueName ) ); return; } // FUTURE: support non-constant initializers for static and virtual fields } LOG( context.LOGGER(), WARN, "Skipping codegen for global/static/virtual field without constant initializer: " << fieldDecl ); } return; default: THROW_LOGIC( "TxFieldDeclNode can not apply to fields with storage " << fieldDecl->get_storage() << ": " << fieldDecl ); } }
53.981395
156
0.633465
[ "object" ]
fe907b7f31c062ad693a9a8256d2b4af5878ea52
37,696
cpp
C++
src/sodeclmgr.cpp
avramidis/sodecl
7bc2654293666a3a30766616d347e6347900e222
[ "BSD-3-Clause" ]
13
2018-01-19T14:08:33.000Z
2021-04-08T06:40:58.000Z
src/sodeclmgr.cpp
avramidis/odecl
7bc2654293666a3a30766616d347e6347900e222
[ "BSD-3-Clause" ]
11
2017-10-23T13:40:27.000Z
2020-08-02T07:50:08.000Z
src/sodeclmgr.cpp
avramidis/odecl
7bc2654293666a3a30766616d347e6347900e222
[ "BSD-3-Clause" ]
4
2018-05-15T15:07:26.000Z
2021-04-08T06:41:01.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2015 Eleftherios Avramidis <el.avramidis@gmail.com> // // Distributed under The MIT License (MIT) // See accompanying file LICENSE //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <string> #include <ctime> #include <random> #include <fstream> #include <sstream> #include <iterator> #include "sodeclmgr.hpp" #include "output_Type.hpp" #include "solver_Type.hpp" #include "clog.hpp" using namespace std; namespace sodecl { sodeclmgr::sodeclmgr(string kernel_path_str, char* sode_system_str, solver_Type solver, double dt, double int_time, int kernel_steps, int num_equat, int num_params, int num_noi, int list_size, output_Type output_type) { m_log = clog::getInstance(); // Set ODE Solver parameter values m_kernel_path_str = kernel_path_str; m_sode_system_string = sode_system_str; m_solver = solver; m_dt = dt; m_int_time = int_time; m_kernel_steps = kernel_steps; m_list_size = list_size; m_num_equat = num_equat; m_num_params = num_params; m_num_noi = num_noi; m_output_type = output_type; m_outputfile_str = "sodecloutput.bin"; if (m_num_noi>0) { double lower_bound = -100000000000; double upper_bound = 100000000000; std::uniform_real_distribution<double> unif(lower_bound, upper_bound); std::random_device rd; std::mt19937 gen(rd()); m_rcounter = new double[m_list_size]; for (int i = 0; i<m_list_size; i++) { m_rcounter[i] = unif(gen); } } m_outputPattern = new int[m_num_equat]; for (int i = 0; i<m_num_equat; i++) { //m_outputPattern[i] = i+1; m_outputPattern[i] = 1; } m_outputPattern[0] = 1; m_platform_count = get_platform_count(); if ((int) m_platform_count==-1) { cerr << "Error getting OpenCL planform number!" << endl; } create_platforms(); // Add default OpenCL build options //m_build_options.push_back(build_Option::FastRelaxedMath); //m_build_options.push_back(build_Option::stdCL20); //m_build_options.push_back(build_Option::stdCL21); m_local_group_size = 0; //m_log->toFile(); } /** * Destructor. Deletes all objects, arrays, pointers, etc. */ sodeclmgr::~sodeclmgr() { // delete m_sode_system_string; // delete m_output; // delete m_source_str; // delete[] m_sode_system_string; // This is a string literals. That means it has static storage duration (not dynamically allocated). ///////////////////////////////////////////////// // delete m_t0; // delete m_y0; // delete m_params; ////delete m_dts; if (m_num_noi>0) { delete[] m_rcounter; } delete[] m_outputPattern; // Clean OpenCL memory buffers. clReleaseMemObject(m_mem_t0); clReleaseMemObject(m_mem_y0); clReleaseMemObject(m_mem_params); if (m_num_noi>0) { clReleaseMemObject(m_mem_rcounter); } //clReleaseMemObject(m_mem_dt); // Clean OpenCL command queues. while (!m_command_queues.empty()) { clReleaseCommandQueue((cl_command_queue) (m_command_queues.back())); m_command_queues.pop_back(); } // Clean OpenCL kernels. while (!m_kernels.empty()) { clReleaseKernel((cl_kernel) (m_kernels.back())); m_kernels.pop_back(); } // Clean OpenCL programs. while (!m_programs.empty()) { clReleaseProgram((cl_program) (m_programs.back())); m_programs.pop_back(); } // Clean OpenCL contexts. while (!m_contexts.empty()) { clReleaseContext((cl_context) (m_contexts.back())); m_contexts.pop_back(); } for (auto i : m_platforms) { delete i; } m_platforms.clear(); // The executable exited normally m_log->writeExitStatusFile(0, "Normal."); delete m_log; } /****************************************************************************************** HARDWARE SECTION */ /** * Sets the sodecl object to use the selected OpenCL device for the integration of the ODE model. * * @param platform_num Index of selected OpenCL platform * @param device_type OpenCL device type * @param device_num Index of selected OpenCL device in the selected OpenCL platform * * @return output_type Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::choose_device(cl_uint platform_num, device_Type device_type, cl_uint device_num) { // Check if selected platform exist if (platform_num<0 || platform_num>m_platform_count) { //cerr << "Selected platform number is out of bounds." << std::endl; m_log->write("Selected platform number is out of bounds.\n"); return 0; } // Check if selected device exist if (device_num<0 || device_num>m_platforms[platform_num]->get_device_count()) { //cerr << "Selected device number is out of bounds." << std::endl; m_log->write("Selected device number is out of bounds.\n"); return 0; } // If selected device type is not ALL (OpenCL type) check if selected device type exist if ((cl_device_type) device_type!=(cl_device_type) device_Type::ALL) { if (m_platforms[platform_num]->m_devices[device_num]->type()!=(cl_device_type) device_type) { //cerr << "Selected device is not of the type selected." << std::endl; m_log->write("Selected device is not of the type selected.\n"); return 0; } } //std::cout << "Selected platform: " << m_platforms[platform_num]->name().c_str() << std::endl; //std::cout << "Device name: " << m_platforms[platform_num]->m_devices[device_num]->name().c_str() << std::endl; ////std::cout << "Device type: " << m_platforms[platform_num]->m_devices[device_num]->type() << std::endl; m_log->write("Selected platform name: "); m_log->write(m_platforms[platform_num]->name().c_str()); m_log->write("\n"); m_log->write("Selected device name: "); m_log->write(m_platforms[platform_num]->m_devices[device_num]->name().c_str()); m_log->write("\n"); m_log->write("Selected device OpenCL version: "); m_log->write(m_platforms[platform_num]->m_devices[device_num]->version().c_str()); m_log->write("\n"); m_selected_platform = platform_num; m_selected_device = device_num; m_selected_device_type = device_type; return 1; } void sodeclmgr::set_local_group_size(int local_group_size) { m_local_group_size = local_group_size; } void sodeclmgr::create_platforms() { cl_platform_id* cpPlatform = new cl_platform_id[m_platform_count]; // get all platforms cl_int err = clGetPlatformIDs(m_platform_count, cpPlatform, NULL); if (err!=CL_SUCCESS) { delete[] cpPlatform; } for (cl_uint i = 0; i<m_platform_count; i++) { m_platforms.push_back(new platform(cpPlatform[i])); } delete[] cpPlatform; } int sodeclmgr::get_platform_count() { cl_uint platform_count; // get platform count cl_int err = clGetPlatformIDs(platform_count, NULL, &platform_count); if (err!=CL_SUCCESS) { return -1; } return platform_count; } /****************************************************************************************** SOFTWARE SECTION */ /** * Create OpenCL context for the selected OpenCL platform and OpenCL device. * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::create_context() { cl_int err; cl_context context = clCreateContext(NULL, 1, &(m_platforms[m_selected_platform]->m_devices[m_selected_device]->m_device_id), NULL, NULL, &err); if (err!=(cl_int) CL_SUCCESS) { std::cout << "Error: Failed to create context! " << err << std::endl; return 0; } m_contexts.push_back(context); //std::cout << "Size of m_contexts : " << m_contexts.size() << std::endl; return 1; } /** * Create OpenCL command queue for the selected OpenCL platform and OpenCL device. * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::create_command_queue() { cl_context context = m_contexts[0]; cl_device_id device = m_platforms[m_selected_platform]->m_devices[m_selected_device]->m_device_id; cl_int err; cl_command_queue commands = clCreateCommandQueue(context, device, 0, &err); if (err!=CL_SUCCESS) { std::cout << "Error: Failed to create command queue!" << std::endl; return 0; } m_command_queues.push_back(commands); return 1; } /** * Reads an OpenCL function or kernel * * @param filename OpenCL file */ void sodeclmgr::read_kernel_file(char* filename) { std::ifstream t(filename); if (t.is_open()) { t.seekg(0, std::ios::end); size_t size = t.tellg(); std::string str(size, ' '); t.seekg(0); t.read(&str[0], size); t.close(); m_source_size = str.length(); for (int i = 0; i<m_source_size; i++) { m_kernel_sources.push_back(str[i]); } } else { // show message: std::cout << "Error opening file"; } } /** * Adds the string str to the vector which stores the kernel string (i.e. OpenCL kernel code) * * @param str The sting to be pushed in the OpenCL kernel code vector * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessfull */ int sodeclmgr::add_string_to_kernel_sources(string str) { // TODO: Add code to catch an exception in case the operation fails for (size_t i = 0; i<str.length(); i++) { m_kernel_sources.push_back(str[i]); } return 1; } /** * Convert a double to string. * * @param x Double number which will be coverted to string * * @return A string of the converted double number */ string sodeclmgr::double2string(double x) { // @todo Add code to catch an exception in the unlikely case of the conversion fails std::string s; { std::ostringstream ss; ss << x; s = ss.str(); } return s; } /** * Form the OpenCL kernel string. * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::create_kernel_string() { // Create the parameters section of the kernel string. These parameter values are defines if (m_num_noi>0) { add_string_to_kernel_sources("#define R123_USE_U01_DOUBLE 1"); add_string_to_kernel_sources("\n"); add_string_to_kernel_sources("#include <Random123/threefry.h>"); add_string_to_kernel_sources("\n"); add_string_to_kernel_sources("#include <Random123/u01.h>"); add_string_to_kernel_sources("\n"); } // Number of noise parameters add_string_to_kernel_sources("#define _numnoi_ "); add_string_to_kernel_sources(std::to_string(static_cast<long long>(m_num_noi))); add_string_to_kernel_sources("\n"); // List size add_string_to_kernel_sources("#define _listsize_ "); add_string_to_kernel_sources(std::to_string(static_cast<long long>(m_list_size))); add_string_to_kernel_sources("\n"); // Kernel steps add_string_to_kernel_sources("#define _numsteps_ "); add_string_to_kernel_sources(std::to_string(static_cast<long long>(m_kernel_steps))); add_string_to_kernel_sources("\n"); //cout << "Kernel steps done" << endl; // SODE solver time size add_string_to_kernel_sources("#define _m_dt_ "); //add_string_to_kernel_sources(std::to_string(static_cast<long double>(m_dt))); add_string_to_kernel_sources(double2string(m_dt)); add_string_to_kernel_sources("\n"); //cout << "SODE solver time size" << endl; // SODE system number of equations add_string_to_kernel_sources("#define _numeq_ "); add_string_to_kernel_sources(std::to_string(static_cast<long long>(m_num_equat))); add_string_to_kernel_sources("\n"); // SODE system number of parameters add_string_to_kernel_sources("#define _numpar_ "); add_string_to_kernel_sources(std::to_string(static_cast<long long>(m_num_params))); add_string_to_kernel_sources("\n"); if (m_solver==solver_Type::ImplicitEuler || m_solver==solver_Type::ImplicitMidpoint) { double epsilon1 = 1e-7; // Implicit StochasticEuler Newton-Raphson epsilon1 value add_string_to_kernel_sources("#define _epsilon1_ "); add_string_to_kernel_sources(double2string(epsilon1)); add_string_to_kernel_sources("\n"); } // Read the SODE system functions read_kernel_file(m_sode_system_string); add_string_to_kernel_sources("\n"); std::vector<char> kernelpath_char; string kernelpath = m_kernel_path_str; // Choose the solver. switch (m_solver) { case solver_Type::StochasticEuler:kernelpath.append("/stochastic_euler.cl"); // Stochastic Euler break; case solver_Type::Euler:kernelpath.append("/euler.cl"); // Euler break; case solver_Type::RungeKutta:kernelpath.append("/rk4.cl"); // Runge-Kutta break; case solver_Type::ImplicitEuler:kernelpath.append("/ie.cl"); // Implicit Euler break; case solver_Type::ImplicitMidpoint:kernelpath.append("/im.cl"); // Implicit midpoint break; default:std::cout << "No valid solver chosen!" << std::endl; } for (int i = 0; i<kernelpath.size(); i++) { kernelpath_char.push_back(kernelpath[i]); } kernelpath_char.push_back('\0'); m_log->write(&*kernelpath_char.begin()); m_log->write("\n"); kernelpath_char.shrink_to_fit(); read_kernel_file(&*kernelpath_char.begin()); add_string_to_kernel_sources("\n"); // Read the solver string kernelsolverpath_char = m_kernel_path_str; // Choose the solver. switch (m_solver) { case solver_Type::StochasticEuler:kernelsolverpath_char.append("/stochastic_solver_caller.cl"); break; case solver_Type::Euler:kernelsolverpath_char.append("/solver_caller.cl"); break; case solver_Type::RungeKutta:kernelsolverpath_char.append("/solver_caller.cl"); break; case solver_Type::ImplicitEuler:kernelsolverpath_char.append("/solver_caller.cl"); break; case solver_Type::ImplicitMidpoint:kernelsolverpath_char.append("/solver_caller.cl"); break; default:std::cout << "No valid solver chosen!" << std::endl; } //std::cout << kernelsolverpath_char << std::endl; read_kernel_file(&kernelsolverpath_char[0]); add_string_to_kernel_sources("\n"); // Print the string //cout << m_kernel_sources.data() << endl; m_kernel_sources.shrink_to_fit(); m_source_size = m_kernel_sources.size(); //cout << m_kernel_sources.data() << endl; // This is for debug purpose std::ofstream out("Generated_kernel.cl"); out << m_kernel_sources.data(); out.close(); return 1; } /** * Create OpenCL program for the selected OpenCL platform, OpenCL device and created OpenCL context. * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::create_program() { const char* srcptr[] = {m_kernel_sources.data()}; cl_int err; cl_program program = clCreateProgramWithSource(m_contexts.at(0), 1, srcptr, (const size_t*) &m_source_size, &err); if (err!=CL_SUCCESS) { return 0; } // Create OpenCL Program m_programs.push_back(program); return 1; } /** * Adds a selected OpenCL build option in the vector which stores these OpenCL build options. * * @param build_option build_Option which will be stored in the vector * * @todo This function should be expanded to perform all the operations for adding the OpenCL options in the char vector */ void sodeclmgr::add_option_to_build_options(build_Option build_option) { m_build_options.push_back(build_option); } /** * Adds the characters of a string in the vector which stores the OpenCL build options. * * @param str String with the OpenCL build option */ void sodeclmgr::add_string_to_build_options_str(string str) { for (size_t i = 0; i<str.length(); i++) { m_build_options_str.push_back(str[i]); } } /** * Builds OpenCL program for the selected OpenCL device. * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::build_program() { cl_device_id device_id = m_platforms[m_selected_platform]->m_devices[m_selected_device]->m_device_id; add_string_to_build_options_str("-I. "); for (build_Option option : m_build_options) { switch (option) { case build_Option::FastRelaxedMath:add_string_to_build_options_str("-cl-fast-relaxed-math "); break; case build_Option::stdCL20:add_string_to_build_options_str("-cl-std=CL2.0 "); break; case build_Option::stdCL21:add_string_to_build_options_str("-cl-std=CL2.1 "); break; } } const char* options = &m_build_options_str[0]; //cerr << "Build options string: " << options << endl; m_log->write("Build options string: "); m_log->write(options); m_log->write("\n"); //const char * options = "-D KHR_DP_EXTENSION -x clc++ -cl-mad-enable"; //const char * options = "-D KHR_DP_EXTENSION -cl-opt-disable -cl-mad-enable"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-unsafe-math-optimizations"; //const char * options = "-D KHR_DP_EXTENSION -cl-opt-disable"; //const char * options = "-D KHR_DP_EXTENSION -cl-std=CL2.0 -cl-uniform-work-group-size"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-no-signed-zeros -cl-finite-math-only"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-std=CL2.0"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math"; //const char * options = "-D KHR_DP_EXTENSION -cl-std=CL2.0"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-std=CL2.0"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-std=CL2.0"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-strict-aliasing -cl-single-precision-constant -cl-no-signed-zeros -cl-denorms-are-zero"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-nv-maxrregcount=200 -cl-nv-verbose -cl-mad-enable -cl-fast-relaxed-math -cl-no-signed-zeros -cl-strict-aliasing"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-nv-maxrregcount=200 -cl-nv-verbose -cl-mad-enable -cl-no-signed-zeros -cl-strict-aliasing"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-nv-maxrregcount=90"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-nv-opt-level=2"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math -cl-nv-allow-expensive-optimizations"; //const char * options = "-D KHR_DP_EXTENSION -cl-fast-relaxed-math"; //const char * options = ""; //const char * options = "-cl-fast-relaxed-math -cl-std=CL2.0"; cl_int err = clBuildProgram(m_programs[0], 1, &device_id, options, NULL, NULL); if (err!=CL_SUCCESS) { size_t len; char buffer[2048]; std::cout << "Error: " << err << std::endl; std::cout << "Error: Failed to build program executable!" << std::endl; clGetProgramBuildInfo(m_programs[0], device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); std::cout << buffer << std::endl; return 0; } return 1; } /// <summary> /// Create the OpenCL kernel. /// </summary> /// <param name="kernelname">Name of the OpenCL kernel.</param> /// <param name="program">OpenCL program.</param> /// <returns>Returns 1 if the operations were succcessfull or 0 if they were unsuccessfull.</returns> int sodeclmgr::create_kernel(string kernelname, cl_program program) { cl_int err; cl_kernel kernel = clCreateKernel(program, kernelname.c_str(), &err); if (!kernel || err!=CL_SUCCESS) { cerr << "Error: Failed to create compute kernel!" << std::endl; return 0; } m_kernels.push_back(kernel); return 1; } /** * Builds OpenCL program for the selected OpenCL device. * * @param context The context is the cl_context * @param list_size The list_size is the size of the buffers * @param equat_num The equat_num is number of equations * @param param_num The param_num is the number of parameters */ int sodeclmgr::create_buffers(cl_context context, int list_size, int equat_num, int param_num) { cl_int errcode; // Create OpenCL device memory buffers m_mem_t0 = clCreateBuffer(context, CL_MEM_READ_WRITE, list_size*sizeof(cl_double), NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } m_mem_y0 = clCreateBuffer(context, CL_MEM_READ_WRITE, list_size*sizeof(cl_double)*equat_num, NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } m_mem_detterm = clCreateBuffer(context, CL_MEM_READ_WRITE, list_size*sizeof(cl_double)*equat_num, NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } m_mem_params = clCreateBuffer(context, CL_MEM_READ_ONLY, list_size*sizeof(cl_double)*param_num, NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } if (m_num_noi>0) { m_mem_stoch = clCreateBuffer(context, CL_MEM_READ_WRITE, list_size*sizeof(cl_double)*equat_num, NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } m_mem_rcounter = clCreateBuffer(context, CL_MEM_READ_ONLY, list_size*sizeof(cl_double), NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } m_mem_noise = clCreateBuffer(context, CL_MEM_READ_ONLY, list_size*sizeof(cl_double)*m_num_noi, NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } } return 1; } /** * Create OpenCL device memory buffer for the dt. * * @param context OpenCL context * @param list_size Number of orbits which the ODE or SDE system will be integrated for * * @return param_num Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::create_dt_buffer(cl_context context, int list_size) { cl_int errcode; m_mem_dt = clCreateBuffer(context, CL_MEM_READ_WRITE, list_size*sizeof(cl_double), NULL, &errcode); if (errcode!=CL_SUCCESS) { return 0; } return 1; } /** * Write data in the OpenCL memory buffers. * * @param commands OpenCL command queue * @param list_size Number of data points to be written in the OpenCL memory buffers * @param equat_num Number of equations of the ODE or SDE system * @param param_num Number of parameters of the ODE or SDE system * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::write_buffers(cl_command_queue commands, int list_size, int equat_num, int param_num) { int err = 0; err |= clEnqueueWriteBuffer(commands, m_mem_t0, CL_TRUE, 0, list_size*sizeof(cl_double), m_t0, 0, NULL, NULL); cl_double* temp = new cl_double[m_list_size*m_num_equat]; for (int orbit = 0; orbit<list_size; orbit++) { int k = orbit*m_num_equat; for (int ieq = 0; ieq<m_num_equat; ieq++) { int i = k+ieq; temp[i] = m_y0[orbit*equat_num+ieq]; } } err |= clEnqueueWriteBuffer(commands, m_mem_y0, CL_TRUE, 0, list_size*sizeof(cl_double)*equat_num, temp, 0, NULL, NULL); delete[] temp; err |= clEnqueueWriteBuffer(commands, m_mem_params, CL_TRUE, 0, list_size*sizeof(cl_double)*param_num, m_params, 0, NULL, NULL); if (m_num_noi>0) { err |= clEnqueueWriteBuffer(commands, m_mem_rcounter, CL_TRUE, 0, list_size*sizeof(cl_double), m_rcounter, 0, NULL, NULL); } if (err!=CL_SUCCESS) { std::cout << "Error: Failed to write to source array!" << std::endl; return 0; } return 1; } /** * Sets OpenCL kernel arguments. * * @param commands OpenCL command queue * @param list_size Number of data points to be written in the OpenCL memory buffers * * @return Returns 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::set_kernel_args(cl_kernel kernel) { // Set the arguments to the compute kernel cl_int err = 0; err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &m_mem_t0); err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &m_mem_y0); //err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &m_mem_detterm); err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &m_mem_params); if (m_num_noi>0) { //err |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &m_mem_stoch); err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &m_mem_rcounter); //err |= clSetKernelArg(kernel, 6, sizeof(cl_mem), &m_mem_noise); } if (err!=CL_SUCCESS) { std::cout << "Error: Failed to set kernel arguments! " << err << std::endl; return 0; } return 1; } void sodeclmgr::set_t0(cl_double* t0) { m_t0 = t0; } /** * Sets the initial values for the variables of the ODE or SDE system. * * @param y0 Initial variables values for each orbit to be calculated */ void sodeclmgr::set_y0(cl_double* y0) { m_y0 = y0; } /** * Sets the parameter values for the variables of the ODE or SDE system. * * @param params Parameter variables values for each orbit to be calculated */ void sodeclmgr::set_params(cl_double* params) { m_params = params; } /** * Reads data from a binary file and saves the data in an array. * * @param filename Filename to read the data from * @param data Pointer to cl_double array to store the read data to * * @param params Returns 1 if the read of the data is successful or 0 if unsuccessful */ int sodeclmgr::read_binary_data_from_file(char* filename, cl_double* data) { ifstream ifs; ifs.open(filename, ios::in | ios::binary | ios::ate); if (ifs.good()) { streampos size = ifs.tellg(); ifs.seekg(0, ios::beg); vector<double> vectordata; vectordata.resize(size); ifs.read(reinterpret_cast<char*>(vectordata.data()), size); for (int i = 0; i<size/8; i++) { data[i] = vectordata.at(i); } ifs.close(); return 1; } else { cout << "ERROR: can't open " << filename << " file." << endl; return 0; } return 1; } /** * Reads data from a txt file and saves the data in an array. * * @param filename Filename to read the data from * @param data Pointer to cl_double array to store the read data to * * @param params Returns 1 if the read of the data is successful or 0 if unsuccessful */ int sodeclmgr::read_data_from_file(char* filename, cl_double* data) { // a string to store line of text string textLine; // try to open a file ifstream ifs(filename, ifstream::in); int j = 0; if (ifs.good()) { while (!ifs.eof()) { // read line of text getline(ifs, textLine); if (!textLine.empty()) { istringstream iss(textLine); vector<string> strs; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(strs)); for (std::vector<string>::size_type i = 0; i!=strs.size(); i++) { data[j] = atof(strs[i].c_str()); j++; } } } ifs.close(); return 1; } else { cout << "ERROR: can't open " << filename << " file." << endl; return 0; } return 1; } /** * Executes the ODE or SDE solver on the selected OpenCL device. * * @param params Returns 1 if the read of the data is successful or 0 if unsuccessful */ int sodeclmgr::run_sode_solver() { // Output binary files std::ofstream output_stream; if (m_output_type==sodecl::output_Type::File) { output_stream.open(m_outputfile_str, std::ios::binary | std::ios::app | std::ios::out); } cl_double* t_out = new cl_double[m_list_size]; cl_double* orbits_out = new cl_double[m_list_size*m_num_equat]; size_t global = size_t(m_list_size); size_t local; local = m_local_group_size; if (m_local_group_size>m_list_size) { local = m_local_group_size; } //cout << "The local group size is: " << local << endl; m_log->write("The local group size is: "); m_log->write((double) local); m_log->write("\n"); timer start_timer; // Run the initial values to the output file. //std::cout << "Running kernel.." << std::endl; cl_int err; for (int j = 0; j<(m_int_time/(m_dt*m_kernel_steps)); j++) { //std::cout << "Running kernel.." << std::endl; ////err = clEnqueueReadBuffer(m_command_queues[0], m_mem_t0, CL_TRUE, 0, m_list_size * sizeof(cl_double), t_out, 0, NULL, NULL); err = clEnqueueReadBuffer(m_command_queues[0], m_mem_y0, CL_TRUE, 0, m_list_size*sizeof(cl_double)*m_num_equat, orbits_out, 0, NULL, NULL); try { if (local!=0) { err = clEnqueueNDRangeKernel(m_command_queues[0], m_kernels[0], 1, NULL, &global, &local, 0, NULL, NULL); } else { err = clEnqueueNDRangeKernel(m_command_queues[0], m_kernels[0], 1, NULL, &global, NULL, 0, NULL, NULL); } } catch (const std::exception& e) { m_log->write("The call to the OpenCL device has failed."); m_log->write(e.what()); } if (err) { //cerr << "Error: Failed to execute kernel!" << std::endl; m_log->write("Error: Failed to execute kernel!"); return 0; } clFlush(m_command_queues[0]); // Save data to disk or to data array - all variables for (int jo = 0; jo<m_num_equat; jo++) { int e = m_outputPattern[jo]; if (e>0) { for (int ji = jo; ji<m_list_size*m_num_equat; ji = ji+m_num_equat) { switch (m_output_type) { case sodecl::output_Type::Array :m_output.push_back(orbits_out[ji]); break; case sodecl::output_Type::File : output_stream.write((char*) (&orbits_out[ji]), sizeof(cl_double)); break; case sodecl::output_Type::None :break; } } } } } // Save the data from the last kernel call. err = clEnqueueReadBuffer(m_command_queues[0], m_mem_y0, CL_TRUE, 0, m_list_size*sizeof(cl_double)*m_num_equat, orbits_out, 0, NULL, NULL); // Save data to disk or to data array - all variables for (int jo = 0; jo<m_num_equat; jo++) { int e = m_outputPattern[jo]; if (e>0) { for (int ji = jo; ji<m_list_size*m_num_equat; ji = ji+m_num_equat) { //m_output.push_back(orbits_out[ji]); switch (m_output_type) { case sodecl::output_Type::Array :m_output.push_back(orbits_out[ji]); break; case sodecl::output_Type::File :output_stream.write((char*) (&orbits_out[ji]), sizeof(cl_double)); break; case sodecl::output_Type::None :break; } } } } //m_output = output_data; double walltime = start_timer.stop_timer(); std::cout << "Compute results runtime: " << walltime << " sec.\n"; m_log->write("Compute results runtime: "); m_log->write(walltime); m_log->write("sec.\n"); if (m_output_type==sodecl::output_Type::File) { output_stream.close(); } m_log->toFile(); delete[] t_out; delete[] orbits_out; return 1; } /** * Setups the selected ODE or SDE solver OpenCL kernel source. * * @return 1 if the operations were succcessfull or 0 if they were unsuccessful */ int sodeclmgr::setup_sode_solver() { // To create a cl string with the program to run if (create_kernel_string()==0) { std::cout << "Kernel code creation failed." << std::endl; return 0; } //m_log->write("Kernel code creation successed.\n"); if (create_context()==0) { std::cout << "Context creation failed." << std::endl; return 0; } //m_log->write("Context created.\n"); if (create_program()==0) { std::cout << "Failed to create OpenCL program from source." << std::endl; return 0; } if (build_program()==0) { std::cout << "Failed to build kernel." << std::endl; return 0; } if (create_kernel("solver_caller", m_programs[0])==0) { std::cout << "Failed to create kernel." << std::endl; return 0; } if (create_command_queue()==0) { std::cout << "Failed to create command queue." << std::endl; return 0; } if (create_buffers(m_contexts[0], m_list_size, m_num_equat, m_num_params)==0) { std::cout << "Failed to create the OpenCL buffers." << std::endl; return 0; } if (write_buffers(m_command_queues[0], m_list_size, m_num_equat, m_num_params)==0) { std::cout << "Failed to write the data to the OpenCL buffers." << std::endl; return 0; } // assign the inputs to kernel if (set_kernel_args(m_kernels[0])==0) { std::cout << "Failed to set kernel arguments." << std::endl; return 0; } //m_log->toFile(); return 1; } }
34.269091
193
0.576533
[ "object", "vector", "model" ]
fe9319013e4dab1e0c5b0a91705cff6789255ec8
2,721
cpp
C++
VortexBaseRuntime/VortexBase/Controller.cpp
d0si/vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
2
2019-12-27T22:06:25.000Z
2020-01-13T18:43:29.000Z
VortexBaseRuntime/VortexBase/Controller.cpp
D0si/Vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
25
2020-01-29T23:04:23.000Z
2020-04-17T06:40:11.000Z
VortexBaseRuntime/VortexBase/Controller.cpp
D0si/Vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
1
2022-03-09T09:14:47.000Z
2022-03-09T09:14:47.000Z
#include <VortexBase/Controller.h> #include <Core/GlobalRuntime.h> #include <Core/Modules/DependencyInjection.h> using Vortex::Core::RuntimeInterface; using Vortex::Core::GlobalRuntime; namespace VortexBase { Controller::Controller(RuntimeInterface* runtime) : ControllerInterface(runtime) {} void Controller::init(const std::string& application_id, const std::string& name, const std::string& method) { if (_runtime->di()->plugin_manager()->on_controller_init_before(_runtime, application_id, name, method, &_controller)) return; std::string cache_key = "vortex.core.controller.value." + application_id + "." + name + "." + method; if (GlobalRuntime::instance().cache().exists(cache_key)) { _controller = Maze::Element::from_json(GlobalRuntime::instance().cache().get(cache_key)); } if (!_controller.has_children()) { Maze::Element or_query(Maze::Type::Array); or_query << Maze::Element({ "app_id" }, { Maze::Element(application_id) }) << Maze::Element({ "app_id" }, {Maze::Element::get_null_element()}); Maze::Element query(Maze::Type::Object); query.set("$or", or_query); query.set("name", name); query.set("method", method); _controller = _runtime->application()->find_object_in_application_storage("controllers", query); if (_controller.has_children()) { GlobalRuntime::instance().cache().set(cache_key, _controller.to_json(0)); } } if (_runtime->di()->plugin_manager()->on_controller_init_after(_runtime, application_id, name, method, &_controller)) return; if (!_controller.has_children()) { _runtime->view()->echo("Controller " + name + " not found."); _runtime->exit(); } } std::string Controller::id() { return _controller.get("_id").get("$oid").get_string(); } std::string Controller::name() { return _controller.get("name").get_string(); } Maze::Element Controller::app_ids() { if (_controller.is_array("app_ids")) { return _controller.get("app_ids"); } return Maze::Element(Maze::Type::Array); } std::string Controller::script() { return _controller.get("script").get_string(); } std::string Controller::post_script() { return _controller.get("post_script").get_string(); } std::string Controller::content_type() { return _controller.get("content_type").get_string(); } std::string Controller::method() { return _controller.get("method").get_string(); } }
33.592593
126
0.61301
[ "object" ]
fe97354da79ff6cb1734eaa59b58e53452a750e6
2,436
hpp
C++
include/caffe/layers/mhd_roi_data_layer.hpp
superxuang/caffe_triple-branch_FCN
e6b3ce2969dc95c55c25921194b93b05513f09ef
[ "MIT" ]
3
2021-01-01T13:04:18.000Z
2021-03-22T03:23:41.000Z
include/caffe/layers/mhd_roi_data_layer.hpp
superxuang/caffe_triple-branch_FCN
e6b3ce2969dc95c55c25921194b93b05513f09ef
[ "MIT" ]
null
null
null
include/caffe/layers/mhd_roi_data_layer.hpp
superxuang/caffe_triple-branch_FCN
e6b3ce2969dc95c55c25921194b93b05513f09ef
[ "MIT" ]
1
2021-03-22T03:23:42.000Z
2021-03-22T03:23:42.000Z
#ifndef CAFFE_MHD_ROI_DATA_LAYER_HPP_ #define CAFFE_MHD_ROI_DATA_LAYER_HPP_ #define USE_MULTI_CHANNEL #define NEAREST_INTERPOLATION 0 #define BILINEAR_INTERPOLATION 1 #define BICUBIC_INTERPOLATION 2 #define INTERPOLATION_ALGORITM BILINEAR_INTERPOLATION #define SOBEL_OPERATOR 0 #define LOG_OPERATOR 1 #define CANNY_OPERATOR 2 #define GRADIENT_OPERATOR SOBEL_OPERATOR #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/data_transformer.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/proto/caffe.pb.h" #include <itkImage.h> #include <itkSmartPointer.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> namespace caffe { /** * @brief Provides data to the Net from image files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class MHDRoiDataLayer : public RoiPrefetchingDataLayer<Dtype> { public: typedef itk::Image<Dtype, 3> ImageType; typedef itk::Image<char, 3> LabelType; struct ImageRecord { int origin_size_[3]; double origin_spacing_[3]; double origin_origin_[3]; int size_[3]; double spacing_[3]; double origin_[3]; int label_range_[3][2]; itk::SmartPointer<ImageType> image_; #ifdef USE_MULTI_CHANNEL itk::SmartPointer<ImageType> enhanced_image_; itk::SmartPointer<ImageType> edge_image_; #endif //itk::SmartPointer<LabelType> label_; std::string info_file_name_; std::vector<int> roi_label_; std::vector<int> roi_x0_, roi_x1_, roi_y0_, roi_y1_, roi_z0_, roi_z1_; }; explicit MHDRoiDataLayer(const LayerParameter& param) : RoiPrefetchingDataLayer<Dtype>(param) {} virtual ~MHDRoiDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MHDRoiData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 2; } virtual inline int MaxTopBlobs() const { return 5; } protected: shared_ptr<Caffe::RNG> prefetch_rng_; virtual void ShuffleImages(); virtual void load_batch(RoiBatch<Dtype>* batch); shared_ptr<Caffe::RNG> ind_rng_; shared_ptr<Caffe::RNG> trans_rng_; vector<ImageRecord*> lines_; int lines_id_; bool fixed_spacing_; }; } // namespace caffe #endif // CAFFE_MHD_ROI_DATA_LAYER_HPP_
26.769231
71
0.763957
[ "vector" ]
fe9a649d47abc5851eec92120a9627d4878a2f28
8,661
hpp
C++
src/graphics/gutils.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
7
2015-06-21T14:35:16.000Z
2021-08-30T12:00:52.000Z
src/graphics/gutils.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2017-02-28T14:09:43.000Z
2017-03-02T06:55:19.000Z
src/graphics/gutils.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2015-12-09T18:22:09.000Z
2015-12-09T18:22:09.000Z
/* Project: SSBRenderer File: gutils.hpp Copyright (c) 2015, Christoph "Youka" Spanknebel 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. */ #pragma once #include <type_traits> #ifdef _WIN32 #include <windef.h> #else #include <cairo.h> #include <pango/pango-layout.h> #endif #include <string> #include <exception> #include <vector> #include <algorithm> namespace GUtils{ // 4x4 double-precision floating point matrix for transformations class Matrix4x4d{ private: // Raw matrix data #ifdef __SSE2__ std::aligned_storage<sizeof(double)<<4, #ifdef __AVX__ sizeof(double)<<2 #else sizeof(float)<<2 #endif >::type storage; // MSVC doesn't support keyword 'alignas' #else double storage[16]; #endif double* const matrix = reinterpret_cast<decltype(this->matrix)>(&this->storage); public: // Ctors, dtor & assignments (rule-of-five) Matrix4x4d(); Matrix4x4d(const double* matrix); Matrix4x4d(double x11, double x12, double x13, double x14, double x21, double x22, double x23, double x24, double x31, double x32, double x33, double x34, double x41, double x42, double x43, double x44); Matrix4x4d(const Matrix4x4d& other); Matrix4x4d& operator=(const Matrix4x4d& other); Matrix4x4d(Matrix4x4d&& other) = delete; // No movable resources Matrix4x4d& operator=(Matrix4x4d&& other) = delete; ~Matrix4x4d() = default; // Raw data access double* data() const; double& operator[](unsigned index) const; // General transformations enum class Order{PREPEND, APPEND}; Matrix4x4d& multiply(const Matrix4x4d& other, Order order = Order::PREPEND); double* transform2d(double* vec); double* transform3d(double* vec); double* transform4d(double* vec); // Unary operations Matrix4x4d& identity(); bool invert(); // Binary operations Matrix4x4d& translate(double x, double y, double z, Order order = Order::PREPEND); Matrix4x4d& scale(double x, double y, double z, Order order = Order::PREPEND); Matrix4x4d& rotate_x(double rad, Order order = Order::PREPEND); Matrix4x4d& rotate_y(double rad, Order order = Order::PREPEND); Matrix4x4d& rotate_z(double rad, Order order = Order::PREPEND); Matrix4x4d& shear_x(double y, double z, Order order = Order::PREPEND); Matrix4x4d& shear_y(double x, double z, Order order = Order::PREPEND); Matrix4x4d& shear_z(double x, double y, Order order = Order::PREPEND); }; // Simple 2D image container template<typename Format = char> class Image2D{ private: // Image header unsigned width, height, stride; Format format; // Image data std::vector<unsigned char> data; public: // Ctors Image2D() : width(0), height(0), stride(0), format(Format()), data(0){} Image2D(unsigned width, unsigned height, unsigned stride, Format format = Format()) : width(width), height(height), stride(stride), format(format), data(this->height * this->stride){} Image2D(unsigned width, unsigned height, unsigned stride, Format format, const unsigned char* data) : width(width), height(height), stride(stride), format(format), data(data, data + this->height * this->stride){} // Getters unsigned get_width() const{return this->width;} unsigned get_height() const{return this->height;} unsigned get_stride() const{return this->stride;} Format get_format() const{return this->format;} unsigned char* get_data() const{return const_cast<unsigned char*>(this->data.data());} size_t get_size() const{return this->data.size();} // Setters void set_width(unsigned width){ this->width = width; } void set_height(unsigned height){ this->height = height, this->data.resize(height * this->stride); } void set_stride(unsigned stride){ decltype(this->data) new_data(this->height * stride); for(auto iter = this->data.begin(), new_iter = new_data.begin(); iter != this->data.end(); iter += this->stride, new_iter += stride) std::copy(iter, iter + stride, new_iter); this->stride = stride, this->data = std::move(new_data); } void set_format(Format format){ this->format = format; } void set_data(const unsigned char* data){ this->data.assign(data, data + this->data.size()); } }; // Flip image vertically void flip(unsigned char* data, const unsigned height, const unsigned stride); void flip(const unsigned char* src_data, const unsigned height, const unsigned stride, unsigned char* dst_data); // Blend one image anywhere on another with specific operation enum class BlendOp{SOURCE, OVER, ADD, SUB, MUL, SCR, DIFF}; bool blend(const unsigned char* src_data, unsigned src_width, unsigned src_height, const unsigned src_stride, const bool src_with_alpha, unsigned char* dst_data, const unsigned dst_width, const unsigned dst_height, const unsigned dst_stride, const bool dst_with_alpha, const int dst_x, const int dst_y, const BlendOp op); // Gaussian blur on image enum class ColorDepth{X1/* A */, X3/* RGB */, X4/* RGBA */}; void blur(unsigned char* data, const unsigned width, const unsigned height, const unsigned stride, const ColorDepth depth, const float strength_h, const float strength_v); // Path processing #pragma pack(push,1) // Ensure coordinates are aligned (for passing them as continuous memory) and memory usage is low struct PathSegment{ enum class Type{MOVE, LINE, CURVE/*Cubic bezier*/, CLOSE} type; double x, y; }; #pragma pack(pop) bool path_extents(const std::vector<PathSegment>& path, double* x0, double* y0, double* x1, double* y1); std::vector<PathSegment>& path_close(std::vector<PathSegment>& path); std::vector<PathSegment>& path_flatten(std::vector<PathSegment>& path, double tolerance); std::vector<PathSegment>& path_transform(std::vector<PathSegment>& path, Matrix4x4d& mat); std::vector<PathSegment> path_by_arc(double x, double y, double cx, double cy, double angle); // Exception for font problems (see Font class below) class FontException : public std::exception{ private: std::string message; public: FontException(const std::string& message) : message(message){} const char* what() const noexcept override{return this->message.c_str();} }; // Native font wrapper class Font{ private: #ifdef _WIN32 HDC dc; HFONT font; HGDIOBJ old_font; double spacing; #else cairo_surface_t* surface; cairo_t* context; PangoLayout* layout; #endif void copy(const Font& other); void move(Font&& other); public: // Rule-of-five Font(); Font(const std::string& family, float size = 12, bool bold = false, bool italic = false, bool underline = false, bool strikeout = false, double spacing = 0.0, bool rtl = false) throw(FontException); #ifdef _WIN32 Font(const std::wstring& family, float size = 12, bool bold = false, bool italic = false, bool underline = false, bool strikeout = false, double spacing = 0.0, bool rtl = false) throw(FontException); #endif ~Font(); Font(const Font& other); Font& operator=(const Font& other); Font(Font&& other); Font& operator=(Font&& other); // Check state operator bool() const; // Getters std::string get_family(); #ifdef _WIN32 std::wstring get_family_unicode(); #endif float get_size(); bool get_bold(); bool get_italic(); bool get_underline(); bool get_strikeout(); double get_spacing(); bool get_rtl(); // Font metrics struct Metrics{ double height, ascent, descent, internal_leading, external_leading; }; Metrics metrics(); // Text width by extents (height from metrics) double text_width(const std::string& text); #ifdef _WIN32 double text_width(const std::wstring& text); #endif // Text to graphical path std::vector<PathSegment> text_path(const std::string& text) throw(FontException); #ifdef _WIN32 std::vector<PathSegment> text_path(const std::wstring& text) throw(FontException); #endif }; }
38.838565
247
0.714583
[ "vector" ]
fe9a8a275c6e21b73517e76b2e6963dc422738ba
39,438
cc
C++
chrome/browser/autocomplete/autocomplete.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
chrome/browser/autocomplete/autocomplete.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/autocomplete/autocomplete.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autocomplete/autocomplete.h" #include <algorithm> #include "base/basictypes.h" #include "base/command_line.h" #include "base/i18n/number_formatting.h" #include "base/metrics/histogram.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_controller_delegate.h" #include "chrome/browser/autocomplete/autocomplete_match.h" #include "chrome/browser/autocomplete/builtin_provider.h" #include "chrome/browser/autocomplete/extension_app_provider.h" #include "chrome/browser/autocomplete/history_contents_provider.h" #include "chrome/browser/autocomplete/history_quick_provider.h" #include "chrome/browser/autocomplete/history_url_provider.h" #include "chrome/browser/autocomplete/keyword_provider.h" #include "chrome/browser/autocomplete/search_provider.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/external_protocol_handler.h" #include "chrome/browser/net/url_fixer_upper.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/history_ui.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/common/notification_service.h" #include "googleurl/src/gurl.h" #include "googleurl/src/url_canon_ip.h" #include "googleurl/src/url_util.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/net_util.h" #include "net/base/registry_controlled_domain.h" #include "net/url_request/url_request.h" #include "ui/base/l10n/l10n_util.h" using base::TimeDelta; // AutocompleteInput ---------------------------------------------------------- AutocompleteInput::AutocompleteInput() : type_(INVALID), initial_prevent_inline_autocomplete_(false), prevent_inline_autocomplete_(false), prefer_keyword_(false), allow_exact_keyword_match_(true), matches_requested_(ALL_MATCHES) { } AutocompleteInput::AutocompleteInput(const string16& text, const string16& desired_tld, bool prevent_inline_autocomplete, bool prefer_keyword, bool allow_exact_keyword_match, MatchesRequested matches_requested) : original_text_(text), desired_tld_(desired_tld), initial_prevent_inline_autocomplete_(prevent_inline_autocomplete), prevent_inline_autocomplete_(prevent_inline_autocomplete), prefer_keyword_(prefer_keyword), allow_exact_keyword_match_(allow_exact_keyword_match), matches_requested_(matches_requested) { // Trim whitespace from edges of input; don't inline autocomplete if there // was trailing whitespace. if (TrimWhitespace(text, TRIM_ALL, &text_) & TRIM_TRAILING) prevent_inline_autocomplete_ = true; GURL canonicalized_url; type_ = Parse(text_, desired_tld, &parts_, &scheme_, &canonicalized_url); if (type_ == INVALID) return; if (((type_ == UNKNOWN) || (type_ == REQUESTED_URL) || (type_ == URL)) && canonicalized_url.is_valid() && (!canonicalized_url.IsStandard() || canonicalized_url.SchemeIsFile() || !canonicalized_url.host().empty())) canonicalized_url_ = canonicalized_url; RemoveForcedQueryStringIfNecessary(type_, &text_); } AutocompleteInput::~AutocompleteInput() { } // static void AutocompleteInput::RemoveForcedQueryStringIfNecessary(Type type, string16* text) { if (type == FORCED_QUERY && !text->empty() && (*text)[0] == L'?') text->erase(0, 1); } // static std::string AutocompleteInput::TypeToString(Type type) { switch (type) { case INVALID: return "invalid"; case UNKNOWN: return "unknown"; case REQUESTED_URL: return "requested-url"; case URL: return "url"; case QUERY: return "query"; case FORCED_QUERY: return "forced-query"; default: NOTREACHED(); return std::string(); } } // static AutocompleteInput::Type AutocompleteInput::Parse( const string16& text, const string16& desired_tld, url_parse::Parsed* parts, string16* scheme, GURL* canonicalized_url) { const size_t first_non_white = text.find_first_not_of(kWhitespaceUTF16, 0); if (first_non_white == string16::npos) return INVALID; // All whitespace. if (text.at(first_non_white) == L'?') { // If the first non-whitespace character is a '?', we magically treat this // as a query. return FORCED_QUERY; } // Ask our parsing back-end to help us understand what the user typed. We // use the URLFixerUpper here because we want to be smart about what we // consider a scheme. For example, we shouldn't consider www.google.com:80 // to have a scheme. url_parse::Parsed local_parts; if (!parts) parts = &local_parts; const string16 parsed_scheme(URLFixerUpper::SegmentURL(text, parts)); if (scheme) *scheme = parsed_scheme; if (canonicalized_url) { *canonicalized_url = URLFixerUpper::FixupURL(UTF16ToUTF8(text), UTF16ToUTF8(desired_tld)); } if (LowerCaseEqualsASCII(parsed_scheme, chrome::kFileScheme)) { // A user might or might not type a scheme when entering a file URL. In // either case, |parsed_scheme| will tell us that this is a file URL, but // |parts->scheme| might be empty, e.g. if the user typed "C:\foo". return URL; } // If the user typed a scheme, and it's HTTP or HTTPS, we know how to parse it // well enough that we can fall through to the heuristics below. If it's // something else, we can just determine our action based on what we do with // any input of this scheme. In theory we could do better with some schemes // (e.g. "ftp" or "view-source") but I'll wait to spend the effort on that // until I run into some cases that really need it. if (parts->scheme.is_nonempty() && !LowerCaseEqualsASCII(parsed_scheme, chrome::kHttpScheme) && !LowerCaseEqualsASCII(parsed_scheme, chrome::kHttpsScheme)) { // See if we know how to handle the URL internally. if (net::URLRequest::IsHandledProtocol(UTF16ToUTF8(parsed_scheme))) return URL; // There are also some schemes that we convert to other things before they // reach the renderer or else the renderer handles internally without // reaching the net::URLRequest logic. We thus won't catch these above, but // we should still claim to handle them. if (LowerCaseEqualsASCII(parsed_scheme, chrome::kViewSourceScheme) || LowerCaseEqualsASCII(parsed_scheme, chrome::kJavaScriptScheme) || LowerCaseEqualsASCII(parsed_scheme, chrome::kDataScheme)) return URL; // Finally, check and see if the user has explicitly opened this scheme as // a URL before, or if the "scheme" is actually a username. We need to do // this last because some schemes (e.g. "javascript") may be treated as // "blocked" by the external protocol handler because we don't want pages to // open them, but users still can. // TODO(viettrungluu): get rid of conversion. ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(UTF16ToUTF8(parsed_scheme)); switch (block_state) { case ExternalProtocolHandler::DONT_BLOCK: return URL; case ExternalProtocolHandler::BLOCK: // If we don't want the user to open the URL, don't let it be navigated // to at all. return QUERY; default: { // We don't know about this scheme. It might be that the user typed a // URL of the form "username:password@foo.com". const string16 http_scheme_prefix = ASCIIToUTF16(std::string(chrome::kHttpScheme) + chrome::kStandardSchemeSeparator); url_parse::Parsed http_parts; string16 http_scheme; GURL http_canonicalized_url; Type http_type = Parse(http_scheme_prefix + text, desired_tld, &http_parts, &http_scheme, &http_canonicalized_url); DCHECK_EQ(std::string(chrome::kHttpScheme), UTF16ToUTF8(http_scheme)); if ((http_type == URL || http_type == REQUESTED_URL) && http_parts.username.is_nonempty() && http_parts.password.is_nonempty()) { // Manually re-jigger the parsed parts to match |text| (without the // http scheme added). http_parts.scheme.reset(); url_parse::Component* components[] = { &http_parts.username, &http_parts.password, &http_parts.host, &http_parts.port, &http_parts.path, &http_parts.query, &http_parts.ref, }; for (size_t i = 0; i < arraysize(components); ++i) { URLFixerUpper::OffsetComponent( -static_cast<int>(http_scheme_prefix.size()), components[i]); } *parts = http_parts; if (scheme) scheme->clear(); if (canonicalized_url) *canonicalized_url = http_canonicalized_url; return http_type; } // We don't know about this scheme and it doesn't look like the user // typed a username and password. It's likely to be a search operator // like "site:" or "link:". We classify it as UNKNOWN so the user has // the option of treating it as a URL if we're wrong. // Note that SegmentURL() is smart so we aren't tricked by "c:\foo" or // "www.example.com:81" in this case. return UNKNOWN; } } } // Either the user didn't type a scheme, in which case we need to distinguish // between an HTTP URL and a query, or the scheme is HTTP or HTTPS, in which // case we should reject invalid formulations. // If we have an empty host it can't be a URL. if (!parts->host.is_nonempty()) return QUERY; // Likewise, the RCDS can reject certain obviously-invalid hosts. (We also // use the registry length later below.) const string16 host(text.substr(parts->host.begin, parts->host.len)); const size_t registry_length = net::RegistryControlledDomainService::GetRegistryLength(UTF16ToUTF8(host), false); if (registry_length == std::string::npos) { // Try to append the desired_tld. if (!desired_tld.empty()) { string16 host_with_tld(host); if (host[host.length() - 1] != '.') host_with_tld += '.'; host_with_tld += desired_tld; if (net::RegistryControlledDomainService::GetRegistryLength( UTF16ToUTF8(host_with_tld), false) != std::string::npos) return REQUESTED_URL; // Something like "99999999999" that looks like a // bad IP address, but becomes valid on attaching // a TLD. } return QUERY; // Could be a broken IP address, etc. } // See if the hostname is valid. While IE and GURL allow hostnames to contain // many other characters (perhaps for weird intranet machines), it's extremely // unlikely that a user would be trying to type those in for anything other // than a search query. url_canon::CanonHostInfo host_info; const std::string canonicalized_host(net::CanonicalizeHost(UTF16ToUTF8(host), &host_info)); if ((host_info.family == url_canon::CanonHostInfo::NEUTRAL) && !net::IsCanonicalizedHostCompliant(canonicalized_host, UTF16ToUTF8(desired_tld))) { // Invalid hostname. There are several possible cases: // * Our checker is too strict and the user pasted in a real-world URL // that's "invalid" but resolves. To catch these, we return UNKNOWN when // the user explicitly typed a scheme, so we'll still search by default // but we'll show the accidental search infobar if necessary. // * The user is typing a multi-word query. If we see a space anywhere in // the hostname we assume this is a search and return QUERY. // * Our checker is too strict and the user is typing a real-world hostname // that's "invalid" but resolves. We return UNKNOWN if the TLD is known. // Note that we explicitly excluded hosts with spaces above so that // "toys at amazon.com" will be treated as a search. // * The user is typing some garbage string. Return QUERY. // // Thus we fall down in the following cases: // * Trying to navigate to a hostname with spaces // * Trying to navigate to a hostname with invalid characters and an unknown // TLD // These are rare, though probably possible in intranets. return (parts->scheme.is_nonempty() || ((registry_length != 0) && (host.find(' ') == string16::npos))) ? UNKNOWN : QUERY; } // A port number is a good indicator that this is a URL. However, it might // also be a query like "1.66:1" that looks kind of like an IP address and // port number. So here we only check for "port numbers" that are illegal and // thus mean this can't be navigated to (e.g. "1.2.3.4:garbage"), and we save // handling legal port numbers until after the "IP address" determination // below. if (parts->port.is_nonempty()) { int port; if (!base::StringToInt(text.substr(parts->port.begin, parts->port.len), &port) || (port < 0) || (port > 65535)) return QUERY; } // Now that we've ruled out all schemes other than http or https and done a // little more sanity checking, the presence of a scheme means this is likely // a URL. if (parts->scheme.is_nonempty()) return URL; // See if the host is an IP address. if (host_info.family == url_canon::CanonHostInfo::IPV4) { // If the user originally typed a host that looks like an IP address (a // dotted quad), they probably want to open it. If the original input was // something else (like a single number), they probably wanted to search for // it, unless they explicitly typed a scheme. This is true even if the URL // appears to have a path: "1.2/45" is more likely a search (for the answer // to a math problem) than a URL. if (host_info.num_ipv4_components == 4) return URL; return desired_tld.empty() ? UNKNOWN : REQUESTED_URL; } if (host_info.family == url_canon::CanonHostInfo::IPV6) return URL; // Now that we've ruled out invalid ports and queries that look like they have // a port, the presence of a port means this is likely a URL. if (parts->port.is_nonempty()) return URL; // Presence of a password means this is likely a URL. Note that unless the // user has typed an explicit "http://" or similar, we'll probably think that // the username is some unknown scheme, and bail out in the scheme-handling // code above. if (parts->password.is_nonempty()) return URL; // The host doesn't look like a number, so see if the user's given us a path. if (parts->path.is_nonempty()) { // Most inputs with paths are URLs, even ones without known registries (e.g. // intranet URLs). However, if there's no known registry and the path has // a space, this is more likely a query with a slash in the first term // (e.g. "ps/2 games") than a URL. We can still open URLs with spaces in // the path by escaping the space, and we will still inline autocomplete // them if users have typed them in the past, but we default to searching // since that's the common case. return ((registry_length == 0) && (text.substr(parts->path.begin, parts->path.len).find(' ') != string16::npos)) ? UNKNOWN : URL; } // If we reach here with a username, our input looks like "user@host". // Because there is no scheme explicitly specified, we think this is more // likely an email address than an HTTP auth attempt. Hence, we search by // default and let users correct us on a case-by-case basis. if (parts->username.is_nonempty()) return UNKNOWN; // We have a bare host string. If it has a known TLD, it's probably a URL. if (registry_length != 0) return URL; // No TLD that we know about. This could be: // * A string that the user wishes to add a desired_tld to to get a URL. If // we reach this point, we know there's no known TLD on the string, so the // fixup code will be willing to add one; thus this is a URL. // * A single word "foo"; possibly an intranet site, but more likely a search. // This is ideally an UNKNOWN, and we can let the Alternate Nav URL code // catch our mistakes. // * A URL with a valid TLD we don't know about yet. If e.g. a registrar adds // "xxx" as a TLD, then until we add it to our data file, Chrome won't know // "foo.xxx" is a real URL. So ideally this is a URL, but we can't really // distinguish this case from: // * A "URL-like" string that's not really a URL (like // "browser.tabs.closeButtons" or "java.awt.event.*"). This is ideally a // QUERY. Since the above case and this one are indistinguishable, and this // case is likely to be much more common, just say these are both UNKNOWN, // which should default to the right thing and let users correct us on a // case-by-case basis. return desired_tld.empty() ? UNKNOWN : REQUESTED_URL; } // static void AutocompleteInput::ParseForEmphasizeComponents( const string16& text, const string16& desired_tld, url_parse::Component* scheme, url_parse::Component* host) { url_parse::Parsed parts; string16 scheme_str; Parse(text, desired_tld, &parts, &scheme_str, NULL); *scheme = parts.scheme; *host = parts.host; int after_scheme_and_colon = parts.scheme.end() + 1; // For the view-source scheme, we should emphasize the scheme and host of the // URL qualified by the view-source prefix. if (LowerCaseEqualsASCII(scheme_str, chrome::kViewSourceScheme) && (static_cast<int>(text.length()) > after_scheme_and_colon)) { // Obtain the URL prefixed by view-source and parse it. string16 real_url(text.substr(after_scheme_and_colon)); url_parse::Parsed real_parts; AutocompleteInput::Parse(real_url, desired_tld, &real_parts, NULL, NULL); if (real_parts.scheme.is_nonempty() || real_parts.host.is_nonempty()) { if (real_parts.scheme.is_nonempty()) { *scheme = url_parse::Component( after_scheme_and_colon + real_parts.scheme.begin, real_parts.scheme.len); } else { scheme->reset(); } if (real_parts.host.is_nonempty()) { *host = url_parse::Component( after_scheme_and_colon + real_parts.host.begin, real_parts.host.len); } else { host->reset(); } } } } // static string16 AutocompleteInput::FormattedStringWithEquivalentMeaning( const GURL& url, const string16& formatted_url) { if (!net::CanStripTrailingSlash(url)) return formatted_url; const string16 url_with_path(formatted_url + char16('/')); return (AutocompleteInput::Parse(formatted_url, string16(), NULL, NULL, NULL) == AutocompleteInput::Parse(url_with_path, string16(), NULL, NULL, NULL)) ? formatted_url : url_with_path; } bool AutocompleteInput::Equals(const AutocompleteInput& other) const { return (text_ == other.text_) && (type_ == other.type_) && (desired_tld_ == other.desired_tld_) && (scheme_ == other.scheme_) && (prevent_inline_autocomplete_ == other.prevent_inline_autocomplete_) && (prefer_keyword_ == other.prefer_keyword_) && (matches_requested_ == other.matches_requested_); } void AutocompleteInput::Clear() { text_.clear(); type_ = INVALID; parts_ = url_parse::Parsed(); scheme_.clear(); desired_tld_.clear(); prevent_inline_autocomplete_ = false; prefer_keyword_ = false; } // AutocompleteProvider ------------------------------------------------------- // static const size_t AutocompleteProvider::kMaxMatches = 3; AutocompleteProvider::ACProviderListener::~ACProviderListener() { } AutocompleteProvider::AutocompleteProvider(ACProviderListener* listener, Profile* profile, const char* name) : profile_(profile), listener_(listener), done_(true), name_(name) { } void AutocompleteProvider::SetProfile(Profile* profile) { DCHECK(profile); DCHECK(done_); // The controller should have already stopped us. profile_ = profile; } void AutocompleteProvider::Stop() { done_ = true; } void AutocompleteProvider::DeleteMatch(const AutocompleteMatch& match) { } AutocompleteProvider::~AutocompleteProvider() { Stop(); } // static bool AutocompleteProvider::HasHTTPScheme(const string16& input) { std::string utf8_input(UTF16ToUTF8(input)); url_parse::Component scheme; if (url_util::FindAndCompareScheme(utf8_input, chrome::kViewSourceScheme, &scheme)) utf8_input.erase(0, scheme.end() + 1); return url_util::FindAndCompareScheme(utf8_input, chrome::kHttpScheme, NULL); } void AutocompleteProvider::UpdateStarredStateOfMatches() { if (matches_.empty()) return; if (!profile_) return; BookmarkModel* bookmark_model = profile_->GetBookmarkModel(); if (!bookmark_model || !bookmark_model->IsLoaded()) return; for (ACMatches::iterator i = matches_.begin(); i != matches_.end(); ++i) i->starred = bookmark_model->IsBookmarked(GURL(i->destination_url)); } string16 AutocompleteProvider::StringForURLDisplay(const GURL& url, bool check_accept_lang, bool trim_http) const { std::string languages = (check_accept_lang && profile_) ? profile_->GetPrefs()->GetString(prefs::kAcceptLanguages) : std::string(); return net::FormatUrl( url, languages, net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP), UnescapeRule::SPACES, NULL, NULL, NULL); } // AutocompleteResult --------------------------------------------------------- // static const size_t AutocompleteResult::kMaxMatches = 6; void AutocompleteResult::Selection::Clear() { destination_url = GURL(); provider_affinity = NULL; is_history_what_you_typed_match = false; } AutocompleteResult::AutocompleteResult() { // Reserve space for the max number of matches we'll show. matches_.reserve(kMaxMatches); // It's probably safe to do this in the initializer list, but there's little // penalty to doing it here and it ensures our object is fully constructed // before calling member functions. default_match_ = end(); } AutocompleteResult::~AutocompleteResult() {} void AutocompleteResult::CopyFrom(const AutocompleteResult& rhs) { if (this == &rhs) return; matches_ = rhs.matches_; // Careful! You can't just copy iterators from another container, you have to // reconstruct them. default_match_ = (rhs.default_match_ == rhs.end()) ? end() : (begin() + (rhs.default_match_ - rhs.begin())); alternate_nav_url_ = rhs.alternate_nav_url_; } void AutocompleteResult::CopyOldMatches(const AutocompleteInput& input, const AutocompleteResult& old_matches) { if (old_matches.empty()) return; if (empty()) { // If we've got no matches we can copy everything from the last result. CopyFrom(old_matches); for (ACMatches::iterator i = begin(); i != end(); ++i) i->from_previous = true; return; } // In hopes of providing a stable popup we try to keep the number of matches // per provider consistent. Other schemes (such as blindly copying the most // relevant matches) typically result in many successive 'What You Typed' // results filling all the matches, which looks awful. // // Instead of starting with the current matches and then adding old matches // until we hit our overall limit, we copy enough old matches so that each // provider has at least as many as before, and then use SortAndCull() to // clamp globally. This way, old high-relevance matches will starve new // low-relevance matches, under the assumption that the new matches will // ultimately be similar. If the assumption holds, this prevents seeing the // new low-relevance match appear and then quickly get pushed off the bottom; // if it doesn't, then once the providers are done and we expire the old // matches, the new ones will all become visible, so we won't have lost // anything permanently. ProviderToMatches matches_per_provider, old_matches_per_provider; BuildProviderToMatches(&matches_per_provider); old_matches.BuildProviderToMatches(&old_matches_per_provider); for (ProviderToMatches::const_iterator i = old_matches_per_provider.begin(); i != old_matches_per_provider.end(); ++i) { MergeMatchesByProvider(i->second, matches_per_provider[i->first]); } SortAndCull(input); } void AutocompleteResult::AppendMatches(const ACMatches& matches) { std::copy(matches.begin(), matches.end(), std::back_inserter(matches_)); default_match_ = end(); alternate_nav_url_ = GURL(); } void AutocompleteResult::AddMatch(const AutocompleteMatch& match) { DCHECK(default_match_ != end()); ACMatches::iterator insertion_point = std::upper_bound(begin(), end(), match, &AutocompleteMatch::MoreRelevant); ACMatches::iterator::difference_type default_offset = default_match_ - begin(); if ((insertion_point - begin()) <= default_offset) ++default_offset; matches_.insert(insertion_point, match); default_match_ = begin() + default_offset; } void AutocompleteResult::SortAndCull(const AutocompleteInput& input) { // Remove duplicates. std::sort(matches_.begin(), matches_.end(), &AutocompleteMatch::DestinationSortFunc); matches_.erase(std::unique(matches_.begin(), matches_.end(), &AutocompleteMatch::DestinationsEqual), matches_.end()); // Sort and trim to the most relevant kMaxMatches matches. const size_t num_matches = std::min(kMaxMatches, matches_.size()); std::partial_sort(matches_.begin(), matches_.begin() + num_matches, matches_.end(), &AutocompleteMatch::MoreRelevant); matches_.resize(num_matches); default_match_ = begin(); // Set the alternate nav URL. alternate_nav_url_ = GURL(); if (((input.type() == AutocompleteInput::UNKNOWN) || (input.type() == AutocompleteInput::REQUESTED_URL)) && (default_match_ != end()) && (default_match_->transition != PageTransition::TYPED) && (default_match_->transition != PageTransition::KEYWORD) && (input.canonicalized_url() != default_match_->destination_url)) alternate_nav_url_ = input.canonicalized_url(); } bool AutocompleteResult::HasCopiedMatches() const { for (ACMatches::const_iterator i = begin(); i != end(); ++i) { if (i->from_previous) return true; } return false; } size_t AutocompleteResult::size() const { return matches_.size(); } bool AutocompleteResult::empty() const { return matches_.empty(); } AutocompleteResult::const_iterator AutocompleteResult::begin() const { return matches_.begin(); } AutocompleteResult::iterator AutocompleteResult::begin() { return matches_.begin(); } AutocompleteResult::const_iterator AutocompleteResult::end() const { return matches_.end(); } AutocompleteResult::iterator AutocompleteResult::end() { return matches_.end(); } // Returns the match at the given index. const AutocompleteMatch& AutocompleteResult::match_at(size_t index) const { DCHECK(index < matches_.size()); return matches_[index]; } void AutocompleteResult::Reset() { matches_.clear(); default_match_ = end(); } void AutocompleteResult::Swap(AutocompleteResult* other) { const size_t default_match_offset = default_match_ - begin(); const size_t other_default_match_offset = other->default_match_ - other->begin(); matches_.swap(other->matches_); default_match_ = begin() + other_default_match_offset; other->default_match_ = other->begin() + default_match_offset; alternate_nav_url_.Swap(&(other->alternate_nav_url_)); } #ifndef NDEBUG void AutocompleteResult::Validate() const { for (const_iterator i(begin()); i != end(); ++i) i->Validate(); } #endif void AutocompleteResult::BuildProviderToMatches( ProviderToMatches* provider_to_matches) const { for (ACMatches::const_iterator i = begin(); i != end(); ++i) (*provider_to_matches)[i->provider].push_back(*i); } // static bool AutocompleteResult::HasMatchByDestination(const AutocompleteMatch& match, const ACMatches& matches) { for (ACMatches::const_iterator i = matches.begin(); i != matches.end(); ++i) { if (i->destination_url == match.destination_url) return true; } return false; } void AutocompleteResult::MergeMatchesByProvider(const ACMatches& old_matches, const ACMatches& new_matches) { if (new_matches.size() >= old_matches.size()) return; size_t delta = old_matches.size() - new_matches.size(); const int max_relevance = (new_matches.empty() ? matches_.front().relevance : new_matches[0].relevance) - 1; // Because the goal is a visibly-stable popup, rather than one that preserves // the highest-relevance matches, we copy in the lowest-relevance matches // first. This means that within each provider's "group" of matches, any // synchronous matches (which tend to have the highest scores) will // "overwrite" the initial matches from that provider's previous results, // minimally disturbing the rest of the matches. for (ACMatches::const_reverse_iterator i = old_matches.rbegin(); i != old_matches.rend() && delta > 0; ++i) { if (!HasMatchByDestination(*i, new_matches)) { AutocompleteMatch match = *i; match.relevance = std::min(max_relevance, match.relevance); match.from_previous = true; AddMatch(match); delta--; } } } // AutocompleteController ----------------------------------------------------- const int AutocompleteController::kNoItemSelected = -1; // Amount of time (in ms) between when the user stops typing and when we remove // any copied entries. We do this from the time the user stopped typing as some // providers (such as SearchProvider) wait for the user to stop typing before // they initiate a query. static const int kExpireTimeMS = 500; AutocompleteController::AutocompleteController( Profile* profile, AutocompleteControllerDelegate* delegate) : delegate_(delegate), done_(true), in_start_(false) { search_provider_ = new SearchProvider(this, profile); providers_.push_back(search_provider_); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableHistoryQuickProvider) && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHistoryQuickProvider)) providers_.push_back(new HistoryQuickProvider(this, profile)); if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHistoryURLProvider)) providers_.push_back(new HistoryURLProvider(this, profile)); providers_.push_back(new KeywordProvider(this, profile)); providers_.push_back(new HistoryContentsProvider(this, profile)); providers_.push_back(new BuiltinProvider(this, profile)); providers_.push_back(new ExtensionAppProvider(this, profile)); for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i) (*i)->AddRef(); } AutocompleteController::~AutocompleteController() { // The providers may have tasks outstanding that hold refs to them. We need // to ensure they won't call us back if they outlive us. (Practically, // calling Stop() should also cancel those tasks and make it so that we hold // the only refs.) We also don't want to bother notifying anyone of our // result changes here, because the notification observer is in the midst of // shutdown too, so we don't ask Stop() to clear |result_| (and notify). result_.Reset(); // Not really necessary. Stop(false); for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i) (*i)->Release(); providers_.clear(); // Not really necessary. } void AutocompleteController::SetProfile(Profile* profile) { Stop(true); for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i) (*i)->SetProfile(profile); input_.Clear(); // Ensure we don't try to do a "minimal_changes" query on a // different profile. } void AutocompleteController::Start( const string16& text, const string16& desired_tld, bool prevent_inline_autocomplete, bool prefer_keyword, bool allow_exact_keyword_match, AutocompleteInput::MatchesRequested matches_requested) { const string16 old_input_text(input_.text()); const AutocompleteInput::MatchesRequested old_matches_requested = input_.matches_requested(); input_ = AutocompleteInput(text, desired_tld, prevent_inline_autocomplete, prefer_keyword, allow_exact_keyword_match, matches_requested); // See if we can avoid rerunning autocomplete when the query hasn't changed // much. When the user presses or releases the ctrl key, the desired_tld // changes, and when the user finishes an IME composition, inline autocomplete // may no longer be prevented. In both these cases the text itself hasn't // changed since the last query, and some providers can do much less work (and // get matches back more quickly). Taking advantage of this reduces flicker. // // NOTE: This comes after constructing |input_| above since that construction // can change the text string (e.g. by stripping off a leading '?'). const bool minimal_changes = (input_.text() == old_input_text) && (input_.matches_requested() == old_matches_requested); expire_timer_.Stop(); // Start the new query. in_start_ = true; base::TimeTicks start_time = base::TimeTicks::Now(); for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i) { (*i)->Start(input_, minimal_changes); if (matches_requested != AutocompleteInput::ALL_MATCHES) DCHECK((*i)->done()); } if (matches_requested == AutocompleteInput::ALL_MATCHES && text.size() < 6) { base::TimeTicks end_time = base::TimeTicks::Now(); std::string name = "Omnibox.QueryTime." + base::IntToString(text.size()); base::Histogram* counter = base::Histogram::FactoryGet( name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag); counter->Add(static_cast<int>((end_time - start_time).InMilliseconds())); } in_start_ = false; CheckIfDone(); UpdateResult(true); if (!done_) StartExpireTimer(); } void AutocompleteController::Stop(bool clear_result) { for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end(); ++i) { (*i)->Stop(); } expire_timer_.Stop(); done_ = true; if (clear_result && !result_.empty()) { result_.Reset(); // NOTE: We pass in false since we're trying to only clear the popup, not // touch the edit... this is all a mess and should be cleaned up :( NotifyChanged(false); } } void AutocompleteController::DeleteMatch(const AutocompleteMatch& match) { DCHECK(match.deletable); match.provider->DeleteMatch(match); // This may synchronously call back to // OnProviderUpdate(). // If DeleteMatch resulted in a callback to OnProviderUpdate and we're // not done, we might attempt to redisplay the deleted match. Make sure // we aren't displaying it by removing any old entries. ExpireCopiedEntries(); } void AutocompleteController::ExpireCopiedEntries() { // Clear out the results. This ensures no results from the previous result set // are copied over. result_.Reset(); // We allow matches from the previous result set to starve out matches from // the new result set. This means in order to expire matches we have to query // the providers again. UpdateResult(false); } void AutocompleteController::OnProviderUpdate(bool updated_matches) { CheckIfDone(); // Multiple providers may provide synchronous results, so we only update the // results if we're not in Start(). if (!in_start_ && (updated_matches || done_)) UpdateResult(false); } void AutocompleteController::UpdateResult(bool is_synchronous_pass) { AutocompleteResult last_result; last_result.Swap(&result_); for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end(); ++i) result_.AppendMatches((*i)->matches()); // Sort the matches and trim to a small number of "best" matches. result_.SortAndCull(input_); // Need to validate before invoking CopyOldMatches as the old matches are not // valid against the current input. #ifndef NDEBUG result_.Validate(); #endif if (!done_) { // This conditional needs to match the conditional in Start that invokes // StartExpireTimer. result_.CopyOldMatches(input_, last_result); } bool notify_default_match = is_synchronous_pass; if (!is_synchronous_pass) { const bool last_default_was_valid = last_result.default_match() != last_result.end(); const bool default_is_valid = result_.default_match() != result_.end(); // We've gotten async results. Send notification that the default match // updated if fill_into_edit differs. We don't check the URL as that may // change for the default match even though the fill into edit hasn't // changed (see SearchProvider for one case of this). notify_default_match = (last_default_was_valid != default_is_valid) || (default_is_valid && (result_.default_match()->fill_into_edit != last_result.default_match()->fill_into_edit)); } NotifyChanged(notify_default_match); } void AutocompleteController::NotifyChanged(bool notify_default_match) { if (delegate_) delegate_->OnResultChanged(notify_default_match); if (done_) { NotificationService::current()->Notify( NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_READY, Source<AutocompleteController>(this), NotificationService::NoDetails()); } } void AutocompleteController::CheckIfDone() { for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end(); ++i) { if (!(*i)->done()) { done_ = false; return; } } done_ = true; } void AutocompleteController::StartExpireTimer() { if (result_.HasCopiedMatches()) expire_timer_.Start(base::TimeDelta::FromMilliseconds(kExpireTimeMS), this, &AutocompleteController::ExpireCopiedEntries); }
39.636181
80
0.680993
[ "object" ]
fe9c0647c5b00c59e6bb04b1a08996af1854da2d
352
cpp
C++
18. Greedy/gasStations.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
225
2021-10-01T03:09:01.000Z
2022-03-11T11:32:49.000Z
18. Greedy/gasStations.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
252
2021-10-01T03:45:20.000Z
2021-12-07T18:32:46.000Z
18. Greedy/gasStations.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
911
2021-10-01T02:55:19.000Z
2022-02-06T09:08:37.000Z
int Solution::canCompleteCircuit(const vector<int> &A, const vector<int> &B) { int total = 0; int current = 0; int ans =0; for(int i=0;i<A.size();i++){ total+=A[i]-B[i]; current+=A[i]-B[i]; if(current<0){ current =0; ans=i+1; } } if(total<0) return -1; return ans; }
22
78
0.477273
[ "vector" ]
fe9e5be9b4891d57d87e7cc81e7ca377a9d781f7
1,092
hpp
C++
src/EventLoop.hpp
senlinzhan/soke
e6767ea1fc88b35423c727e34bd46a9573f3775b
[ "MIT" ]
5
2017-01-21T12:59:51.000Z
2021-08-08T19:27:58.000Z
src/EventLoop.hpp
senlinzhan/soke
e6767ea1fc88b35423c727e34bd46a9573f3775b
[ "MIT" ]
null
null
null
src/EventLoop.hpp
senlinzhan/soke
e6767ea1fc88b35423c727e34bd46a9573f3775b
[ "MIT" ]
2
2017-07-23T04:49:55.000Z
2020-04-04T15:44:38.000Z
#ifndef EVENTLOOP_H #define EVENTLOOP_H #include "Epoll.hpp" #include <queue> #include <memory> #include <thread> #include <vector> #include <unordered_map> #include <unordered_set> namespace soke { class Channel; class EventLoop { public: using Task = std::function<void ()>; EventLoop(); ~EventLoop(); EventLoop(const EventLoop &) = delete; EventLoop &operator=(const EventLoop &) = delete; void updateChannel(Channel *channel); void removeChannel(Channel *channel); void loop(); void quit(); void queueInLoop(Task task); private: bool looping_; bool quit_; std::thread::id tid_; std::queue<Task> taskQueue_; Epoll epoll_; std::unordered_map<int, Channel *> channels_; std::unordered_set<int> unregisteredFds_; }; }; #endif /* EVENTLOOP_H */
22.75
60
0.509158
[ "vector" ]
fea43ea1ae8ce263f682cd73022d991557113aa9
34,995
cc
C++
remoting/host/plugin/host_script_object.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
remoting/host/plugin/host_script_object.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
remoting/host/plugin/host_script_object.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// 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 "remoting/host/plugin/host_script_object.h" #include "remoting/host/plugin/daemon_controller.h" #include "base/bind.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/message_loop.h" #include "base/message_loop_proxy.h" #include "base/sys_string_conversions.h" #include "base/threading/platform_thread.h" #include "base/threading/sequenced_worker_pool.h" #include "base/utf_string_conversions.h" #include "remoting/jingle_glue/xmpp_signal_strategy.h" #include "remoting/base/auth_token_util.h" #include "remoting/host/chromoting_host.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/desktop_environment.h" #include "remoting/host/host_key_pair.h" #include "remoting/host/host_secret.h" #include "remoting/host/it2me_host_user_interface.h" #include "remoting/host/plugin/host_log_handler.h" #include "remoting/host/policy_hack/nat_policy.h" #include "remoting/host/register_support_host_request.h" #include "remoting/protocol/it2me_host_authenticator_factory.h" namespace remoting { namespace { const char* kAttrNameAccessCode = "accessCode"; const char* kAttrNameAccessCodeLifetime = "accessCodeLifetime"; const char* kAttrNameClient = "client"; const char* kAttrNameDaemonState = "daemonState"; const char* kAttrNameState = "state"; const char* kAttrNameLogDebugInfo = "logDebugInfo"; const char* kAttrNameOnNatTraversalPolicyChanged = "onNatTraversalPolicyChanged"; const char* kAttrNameOnStateChanged = "onStateChanged"; const char* kFuncNameConnect = "connect"; const char* kFuncNameDisconnect = "disconnect"; const char* kFuncNameLocalize = "localize"; const char* kFuncNameGenerateKeyPair = "generateKeyPair"; const char* kFuncNameSetDaemonPin = "setDaemonPin"; const char* kFuncNameGetDaemonConfig = "getDaemonConfig"; const char* kFuncNameStartDaemon = "startDaemon"; const char* kFuncNameStopDaemon = "stopDaemon"; // States. const char* kAttrNameDisconnected = "DISCONNECTED"; const char* kAttrNameStarting = "STARTING"; const char* kAttrNameRequestedAccessCode = "REQUESTED_ACCESS_CODE"; const char* kAttrNameReceivedAccessCode = "RECEIVED_ACCESS_CODE"; const char* kAttrNameConnected = "CONNECTED"; const char* kAttrNameDisconnecting = "DISCONNECTING"; const char* kAttrNameError = "ERROR"; const int kMaxLoginAttempts = 5; // We may need to have more than one task running at the same time // (e.g. key generation and status update), yet unlikely to ever need // more than 2 threads. const int kMaxWorkerPoolThreads = 2; } // namespace HostNPScriptObject::HostNPScriptObject( NPP plugin, NPObject* parent, PluginMessageLoopProxy::Delegate* plugin_thread_delegate) : plugin_(plugin), parent_(parent), am_currently_logging_(false), state_(kDisconnected), np_thread_id_(base::PlatformThread::CurrentId()), plugin_message_loop_proxy_( new PluginMessageLoopProxy(plugin_thread_delegate)), failed_login_attempts_(0), disconnected_event_(true, false), nat_traversal_enabled_(false), policy_received_(false), daemon_controller_(DaemonController::Create()), worker_pool_(new base::SequencedWorkerPool(kMaxWorkerPoolThreads, "RemotingHostPlugin")) { } HostNPScriptObject::~HostNPScriptObject() { CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); // Shutdown It2MeHostUserInterface first so that it doesn't try to post // tasks on the UI thread while we are stopping the host. if (it2me_host_user_interface_.get()) { it2me_host_user_interface_->Shutdown(); } HostLogHandler::UnregisterLoggingScriptObject(this); plugin_message_loop_proxy_->Detach(); // Stop listening for policy updates. if (nat_policy_.get()) { base::WaitableEvent nat_policy_stopped_(true, false); nat_policy_->StopWatching(&nat_policy_stopped_); nat_policy_stopped_.Wait(); nat_policy_.reset(); } if (host_context_.get()) { // Disconnect synchronously. We cannot disconnect asynchronously // here because |host_context_| needs to be stopped on the plugin // thread, but the plugin thread may not exist after the instance // is destroyed. disconnected_event_.Reset(); DisconnectInternal(); disconnected_event_.Wait(); // Stops all threads. host_context_.reset(); } // Must shutdown worker pool threads so that they don't try to // access the host object. worker_pool_->Shutdown(); } bool HostNPScriptObject::Init() { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); VLOG(2) << "Init"; host_context_.reset(new ChromotingHostContext(NULL, plugin_message_loop_proxy_)); if (!host_context_->Start()) { host_context_.reset(); return false; } nat_policy_.reset( policy_hack::NatPolicy::Create(host_context_->network_message_loop())); nat_policy_->StartWatching( base::Bind(&HostNPScriptObject::OnNatPolicyUpdate, base::Unretained(this))); return true; } bool HostNPScriptObject::HasMethod(const std::string& method_name) { VLOG(2) << "HasMethod " << method_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); return (method_name == kFuncNameConnect || method_name == kFuncNameDisconnect || method_name == kFuncNameLocalize || method_name == kFuncNameGenerateKeyPair || method_name == kFuncNameSetDaemonPin || method_name == kFuncNameGetDaemonConfig || method_name == kFuncNameStartDaemon || method_name == kFuncNameStopDaemon); } bool HostNPScriptObject::InvokeDefault(const NPVariant* args, uint32_t arg_count, NPVariant* result) { VLOG(2) << "InvokeDefault"; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); SetException("exception during default invocation"); return false; } bool HostNPScriptObject::Invoke(const std::string& method_name, const NPVariant* args, uint32_t arg_count, NPVariant* result) { VLOG(2) << "Invoke " << method_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); if (method_name == kFuncNameConnect) { return Connect(args, arg_count, result); } else if (method_name == kFuncNameDisconnect) { return Disconnect(args, arg_count, result); } else if (method_name == kFuncNameLocalize) { return Localize(args, arg_count, result); } else if (method_name == kFuncNameGenerateKeyPair) { return GenerateKeyPair(args, arg_count, result); } else if (method_name == kFuncNameSetDaemonPin) { return SetDaemonPin(args, arg_count, result); } else if (method_name == kFuncNameGetDaemonConfig) { return GetDaemonConfig(args, arg_count, result); } else if (method_name == kFuncNameStartDaemon) { return StartDaemon(args, arg_count, result); } else if (method_name == kFuncNameStopDaemon) { return StopDaemon(args, arg_count, result); } else { SetException("Invoke: unknown method " + method_name); return false; } } bool HostNPScriptObject::HasProperty(const std::string& property_name) { VLOG(2) << "HasProperty " << property_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); return (property_name == kAttrNameAccessCode || property_name == kAttrNameAccessCodeLifetime || property_name == kAttrNameClient || property_name == kAttrNameDaemonState || property_name == kAttrNameState || property_name == kAttrNameLogDebugInfo || property_name == kAttrNameOnNatTraversalPolicyChanged || property_name == kAttrNameOnStateChanged || property_name == kAttrNameDisconnected || property_name == kAttrNameStarting || property_name == kAttrNameRequestedAccessCode || property_name == kAttrNameReceivedAccessCode || property_name == kAttrNameConnected || property_name == kAttrNameDisconnecting || property_name == kAttrNameError); } bool HostNPScriptObject::GetProperty(const std::string& property_name, NPVariant* result) { VLOG(2) << "GetProperty " << property_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); if (!result) { SetException("GetProperty: NULL result"); return false; } if (property_name == kAttrNameOnNatTraversalPolicyChanged) { OBJECT_TO_NPVARIANT(on_nat_traversal_policy_changed_func_.get(), *result); return true; } else if (property_name == kAttrNameOnStateChanged) { OBJECT_TO_NPVARIANT(on_state_changed_func_.get(), *result); return true; } else if (property_name == kAttrNameLogDebugInfo) { OBJECT_TO_NPVARIANT(log_debug_info_func_.get(), *result); return true; } else if (property_name == kAttrNameState) { INT32_TO_NPVARIANT(state_, *result); return true; } else if (property_name == kAttrNameAccessCode) { base::AutoLock auto_lock(access_code_lock_); *result = NPVariantFromString(access_code_); return true; } else if (property_name == kAttrNameAccessCodeLifetime) { base::AutoLock auto_lock(access_code_lock_); INT32_TO_NPVARIANT(access_code_lifetime_.InSeconds(), *result); return true; } else if (property_name == kAttrNameClient) { *result = NPVariantFromString(client_username_); return true; } else if (property_name == kAttrNameDaemonState) { INT32_TO_NPVARIANT(daemon_controller_->GetState(), *result); return true; } else if (property_name == kAttrNameDisconnected) { INT32_TO_NPVARIANT(kDisconnected, *result); return true; } else if (property_name == kAttrNameStarting) { INT32_TO_NPVARIANT(kStarting, *result); return true; } else if (property_name == kAttrNameRequestedAccessCode) { INT32_TO_NPVARIANT(kRequestedAccessCode, *result); return true; } else if (property_name == kAttrNameReceivedAccessCode) { INT32_TO_NPVARIANT(kReceivedAccessCode, *result); return true; } else if (property_name == kAttrNameConnected) { INT32_TO_NPVARIANT(kConnected, *result); return true; } else if (property_name == kAttrNameDisconnecting) { INT32_TO_NPVARIANT(kDisconnecting, *result); return true; } else if (property_name == kAttrNameError) { INT32_TO_NPVARIANT(kError, *result); return true; } else { SetException("GetProperty: unsupported property " + property_name); return false; } } bool HostNPScriptObject::SetProperty(const std::string& property_name, const NPVariant* value) { VLOG(2) << "SetProperty " << property_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); if (property_name == kAttrNameOnNatTraversalPolicyChanged) { if (NPVARIANT_IS_OBJECT(*value)) { on_nat_traversal_policy_changed_func_ = NPVARIANT_TO_OBJECT(*value); bool policy_received, nat_traversal_enabled; { base::AutoLock lock(nat_policy_lock_); policy_received = policy_received_; nat_traversal_enabled = nat_traversal_enabled_; } if (policy_received) { UpdateWebappNatPolicy(nat_traversal_enabled); } return true; } else { SetException("SetProperty: unexpected type for property " + property_name); } return false; } if (property_name == kAttrNameOnStateChanged) { if (NPVARIANT_IS_OBJECT(*value)) { on_state_changed_func_ = NPVARIANT_TO_OBJECT(*value); return true; } else { SetException("SetProperty: unexpected type for property " + property_name); } return false; } if (property_name == kAttrNameLogDebugInfo) { if (NPVARIANT_IS_OBJECT(*value)) { log_debug_info_func_ = NPVARIANT_TO_OBJECT(*value); HostLogHandler::RegisterLoggingScriptObject(this); return true; } else { SetException("SetProperty: unexpected type for property " + property_name); } return false; } return false; } bool HostNPScriptObject::RemoveProperty(const std::string& property_name) { VLOG(2) << "RemoveProperty " << property_name; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); return false; } bool HostNPScriptObject::Enumerate(std::vector<std::string>* values) { VLOG(2) << "Enumerate"; CHECK_EQ(base::PlatformThread::CurrentId(), np_thread_id_); const char* entries[] = { kAttrNameAccessCode, kAttrNameState, kAttrNameLogDebugInfo, kAttrNameOnStateChanged, kAttrNameDisconnected, kAttrNameStarting, kAttrNameRequestedAccessCode, kAttrNameReceivedAccessCode, kAttrNameConnected, kAttrNameDisconnecting, kAttrNameError, kFuncNameConnect, kFuncNameDisconnect, kFuncNameLocalize, kFuncNameGenerateKeyPair, kFuncNameSetDaemonPin, kFuncNameGetDaemonConfig, kFuncNameStartDaemon, kFuncNameStopDaemon }; for (size_t i = 0; i < arraysize(entries); ++i) { values->push_back(entries[i]); } return true; } void HostNPScriptObject::OnAccessDenied(const std::string& jid) { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); ++failed_login_attempts_; if (failed_login_attempts_ == kMaxLoginAttempts) { DisconnectInternal(); } } void HostNPScriptObject::OnClientAuthenticated(const std::string& jid) { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); if (state_ == kDisconnecting) { // Ignore the new connection if we are disconnecting. return; } client_username_ = jid; size_t pos = client_username_.find('/'); if (pos != std::string::npos) client_username_.replace(pos, std::string::npos, ""); LOG(INFO) << "Client " << client_username_ << " connected."; SetState(kConnected); } void HostNPScriptObject::OnClientDisconnected(const std::string& jid) { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); client_username_.clear(); DisconnectInternal(); } void HostNPScriptObject::OnShutdown() { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); register_request_.reset(); log_to_server_.reset(); signal_strategy_.reset(); host_->RemoveStatusObserver(this); host_ = NULL; if (state_ != kDisconnected) { SetState(kDisconnected); } } // string uid, string auth_token bool HostNPScriptObject::Connect(const NPVariant* args, uint32_t arg_count, NPVariant* result) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); LOG(INFO) << "Connecting..."; if (arg_count != 2) { SetException("connect: bad number of arguments"); return false; } if (state_ != kDisconnected) { SetException("connect: can be called only when disconnected"); return false; } std::string uid = StringFromNPVariant(args[0]); if (uid.empty()) { SetException("connect: bad uid argument"); return false; } std::string auth_service_with_token = StringFromNPVariant(args[1]); std::string auth_token; std::string auth_service; ParseAuthTokenWithService(auth_service_with_token, &auth_token, &auth_service); if (auth_token.empty()) { SetException("connect: auth_service_with_token argument has empty token"); return false; } ReadPolicyAndConnect(uid, auth_token, auth_service); return true; } void HostNPScriptObject::ReadPolicyAndConnect(const std::string& uid, const std::string& auth_token, const std::string& auth_service) { if (!host_context_->network_message_loop()->BelongsToCurrentThread()) { host_context_->network_message_loop()->PostTask( FROM_HERE, base::Bind( &HostNPScriptObject::ReadPolicyAndConnect, base::Unretained(this), uid, auth_token, auth_service)); return; } SetState(kStarting); // Only proceed to FinishConnect() if at least one policy update has been // received. if (policy_received_) { FinishConnectMainThread(uid, auth_token, auth_service); } else { // Otherwise, create the policy watcher, and thunk the connect. pending_connect_ = base::Bind(&HostNPScriptObject::FinishConnectMainThread, base::Unretained(this), uid, auth_token, auth_service); } } void HostNPScriptObject::FinishConnectMainThread( const std::string& uid, const std::string& auth_token, const std::string& auth_service) { if (host_context_->main_message_loop() != MessageLoop::current()) { host_context_->main_message_loop()->PostTask(FROM_HERE, base::Bind( &HostNPScriptObject::FinishConnectMainThread, base::Unretained(this), uid, auth_token, auth_service)); return; } // DesktopEnvironment must be initialized on the main thread. // // TODO(sergeyu): Fix DesktopEnvironment so that it can be created // on either the UI or the network thread so that we can avoid // jumping to the main thread here. desktop_environment_ = DesktopEnvironment::Create(host_context_.get()); FinishConnectNetworkThread(uid, auth_token, auth_service); } void HostNPScriptObject::FinishConnectNetworkThread( const std::string& uid, const std::string& auth_token, const std::string& auth_service) { if (!host_context_->network_message_loop()->BelongsToCurrentThread()) { host_context_->network_message_loop()->PostTask(FROM_HERE, base::Bind( &HostNPScriptObject::FinishConnectNetworkThread, base::Unretained(this), uid, auth_token, auth_service)); return; } if (state_ != kStarting) { // Host has been stopped while we were fetching policy. return; } // Verify that DesktopEnvironment has been created. if (desktop_environment_.get() == NULL) { SetState(kError); return; } // Generate a key pair for the Host to use. // TODO(wez): Move this to the worker thread. host_key_pair_.Generate(); // Create XMPP connection. scoped_ptr<SignalStrategy> signal_strategy( new XmppSignalStrategy(host_context_->jingle_thread(), uid, auth_token, auth_service)); // Request registration of the host for support. scoped_ptr<RegisterSupportHostRequest> register_request( new RegisterSupportHostRequest( signal_strategy.get(), &host_key_pair_, base::Bind(&HostNPScriptObject::OnReceivedSupportID, base::Unretained(this)))); // Beyond this point nothing can fail, so save the config and request. signal_strategy_.reset(signal_strategy.release()); register_request_.reset(register_request.release()); // Create the Host. LOG(INFO) << "NAT state: " << nat_traversal_enabled_; host_ = new ChromotingHost( host_context_.get(), signal_strategy_.get(), desktop_environment_.get(), protocol::NetworkSettings(nat_traversal_enabled_)); host_->AddStatusObserver(this); log_to_server_.reset( new LogToServer(host_, ServerLogEntry::IT2ME, signal_strategy_.get())); it2me_host_user_interface_.reset( new It2MeHostUserInterface(host_.get(), host_context_.get())); it2me_host_user_interface_->Init(); { base::AutoLock auto_lock(ui_strings_lock_); host_->SetUiStrings(ui_strings_); } signal_strategy_->Connect(); host_->Start(); SetState(kRequestedAccessCode); return; } bool HostNPScriptObject::Disconnect(const NPVariant* args, uint32_t arg_count, NPVariant* result) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); if (arg_count != 0) { SetException("disconnect: bad number of arguments"); return false; } DisconnectInternal(); return true; } bool HostNPScriptObject::Localize(const NPVariant* args, uint32_t arg_count, NPVariant* result) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); if (arg_count != 1) { SetException("localize: bad number of arguments"); return false; } if (NPVARIANT_IS_OBJECT(args[0])) { ScopedRefNPObject localize_func(NPVARIANT_TO_OBJECT(args[0])); LocalizeStrings(localize_func.get()); return true; } else { SetException("localize: unexpected type for argument 1"); return false; } } bool HostNPScriptObject::GenerateKeyPair(const NPVariant* args, uint32_t arg_count, NPVariant* result) { if (arg_count != 1) { SetException("generateKeyPair: bad number of arguments"); return false; } NPObject* callback_obj = ObjectFromNPVariant(args[0]); if (!callback_obj) { SetException("generateKeyPair: invalid callback parameter"); return false; } callback_obj = g_npnetscape_funcs->retainobject(callback_obj); worker_pool_->PostTask(FROM_HERE, base::Bind(&HostNPScriptObject::DoGenerateKeyPair, base::Unretained(this), callback_obj)); return true; } bool HostNPScriptObject::SetDaemonPin(const NPVariant* args, uint32_t arg_count, NPVariant* result) { if (arg_count != 1) { SetException("startDaemon: bad number of arguments"); return false; } if (NPVARIANT_IS_STRING(args[0])) { daemon_controller_->SetPin(StringFromNPVariant(args[0])); return true; } else { SetException("startDaemon: unexpected type for argument 1"); return false; } } bool HostNPScriptObject::GetDaemonConfig(const NPVariant* args, uint32_t arg_count, NPVariant* result) { if (arg_count != 1) { SetException("getDaemonConfig: bad number of arguments"); return false; } NPObject* callback_obj = ObjectFromNPVariant(args[0]); if (!callback_obj) { SetException("getDaemonConfig: invalid callback parameter"); return false; } callback_obj = g_npnetscape_funcs->retainobject(callback_obj); // We control lifetime of the |daemon_controller_| so it's safe to // use base::Unretained() here. daemon_controller_->GetConfig( base::Bind(&HostNPScriptObject::InvokeGetDaemonConfigCallback, base::Unretained(this), callback_obj)); return true; } bool HostNPScriptObject::StartDaemon(const NPVariant* args, uint32_t arg_count, NPVariant* result) { if (arg_count != 1) { SetException("startDaemon: bad number of arguments"); return false; } std::string config_str = StringFromNPVariant(args[0]); base::Value* config = base::JSONReader::Read(config_str, true); base::DictionaryValue* config_dict; if (config_str.empty() || !config || !config->GetAsDictionary(&config_dict)) { delete config; SetException("startDaemon: bad config parameter"); return false; } daemon_controller_->SetConfigAndStart( scoped_ptr<base::DictionaryValue>(config_dict)); return true; } bool HostNPScriptObject::StopDaemon(const NPVariant* args, uint32_t arg_count, NPVariant* result) { if (arg_count != 0) { SetException("startDaemon: bad number of arguments"); return false; } daemon_controller_->Stop(); return true; } void HostNPScriptObject::DisconnectInternal() { if (!host_context_->network_message_loop()->BelongsToCurrentThread()) { host_context_->network_message_loop()->PostTask( FROM_HERE, base::Bind(&HostNPScriptObject::DisconnectInternal, base::Unretained(this))); return; } switch (state_) { case kDisconnected: disconnected_event_.Signal(); return; case kStarting: SetState(kDisconnecting); SetState(kDisconnected); disconnected_event_.Signal(); return; case kDisconnecting: return; default: DCHECK(host_); SetState(kDisconnecting); // ChromotingHost::Shutdown() may destroy SignalStrategy // synchronously, bug SignalStrategy::Listener handlers are not // allowed to destroy SignalStrategy, so post task to call // Shutdown() later. host_context_->network_message_loop()->PostTask( FROM_HERE, base::Bind( &ChromotingHost::Shutdown, host_, base::Bind(&HostNPScriptObject::OnShutdownFinished, base::Unretained(this)))); } } void HostNPScriptObject::OnShutdownFinished() { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); disconnected_event_.Signal(); } void HostNPScriptObject::OnNatPolicyUpdate(bool nat_traversal_enabled) { if (!host_context_->network_message_loop()->BelongsToCurrentThread()) { host_context_->network_message_loop()->PostTask( FROM_HERE, base::Bind(&HostNPScriptObject::OnNatPolicyUpdate, base::Unretained(this), nat_traversal_enabled)); return; } VLOG(2) << "OnNatPolicyUpdate: " << nat_traversal_enabled; // When transitioning from enabled to disabled, force disconnect any // existing session. if (nat_traversal_enabled_ && !nat_traversal_enabled) { DisconnectInternal(); } { base::AutoLock lock(nat_policy_lock_); policy_received_ = true; nat_traversal_enabled_ = nat_traversal_enabled; } UpdateWebappNatPolicy(nat_traversal_enabled_); if (!pending_connect_.is_null()) { pending_connect_.Run(); pending_connect_.Reset(); } } void HostNPScriptObject::OnReceivedSupportID( bool success, const std::string& support_id, const base::TimeDelta& lifetime) { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); if (!success) { SetState(kError); DisconnectInternal(); return; } std::string host_secret = GenerateSupportHostSecret(); std::string access_code = support_id + host_secret; scoped_ptr<protocol::AuthenticatorFactory> factory( new protocol::It2MeHostAuthenticatorFactory( host_key_pair_.GenerateCertificate(), *host_key_pair_.private_key(), access_code)); host_->SetAuthenticatorFactory(factory.Pass()); { base::AutoLock lock(access_code_lock_); access_code_ = access_code; access_code_lifetime_ = lifetime; } SetState(kReceivedAccessCode); } void HostNPScriptObject::SetState(State state) { DCHECK(host_context_->network_message_loop()->BelongsToCurrentThread()); switch (state_) { case kDisconnected: DCHECK(state == kStarting || state == kError) << state; break; case kStarting: DCHECK(state == kRequestedAccessCode || state == kDisconnecting || state == kError) << state; break; case kRequestedAccessCode: DCHECK(state == kReceivedAccessCode || state == kDisconnecting || state == kError) << state; break; case kReceivedAccessCode: DCHECK(state == kConnected || state == kDisconnecting || state == kError) << state; break; case kConnected: DCHECK(state == kDisconnecting || state == kDisconnected || state == kError) << state; break; case kDisconnecting: DCHECK(state == kDisconnected) << state; break; case kError: DCHECK(state == kDisconnecting) << state; break; }; state_ = state; NotifyStateChanged(state); } void HostNPScriptObject::NotifyStateChanged(State state) { if (!plugin_message_loop_proxy_->BelongsToCurrentThread()) { plugin_message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&HostNPScriptObject::NotifyStateChanged, base::Unretained(this), state)); return; } if (on_state_changed_func_.get()) { VLOG(2) << "Calling state changed " << state; NPVariant state_var; INT32_TO_NPVARIANT(state, state_var); bool is_good = InvokeAndIgnoreResult(on_state_changed_func_.get(), &state_var, 1); LOG_IF(ERROR, !is_good) << "OnStateChanged failed"; } } void HostNPScriptObject::PostLogDebugInfo(const std::string& message) { if (plugin_message_loop_proxy_->BelongsToCurrentThread()) { // Make sure we're not currently processing a log message. // We only need to check this if we're on the plugin thread. if (am_currently_logging_) return; } // Always post (even if we're already on the correct thread) so that debug // log messages are shown in the correct order. plugin_message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&HostNPScriptObject::LogDebugInfo, base::Unretained(this), message)); } void HostNPScriptObject::LocalizeStrings(NPObject* localize_func) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); UiStrings ui_strings; string16 direction; LocalizeString(localize_func, "@@bidi_dir", &direction); ui_strings.direction = UTF16ToUTF8(direction) == "rtl" ? remoting::UiStrings::RTL : remoting::UiStrings::LTR; LocalizeString(localize_func, /*i18n-content*/"PRODUCT_NAME", &ui_strings.product_name); LocalizeString(localize_func, /*i18n-content*/"DISCONNECT_OTHER_BUTTON", &ui_strings.disconnect_button_text); LocalizeString(localize_func, #if defined(OS_WIN) /*i18n-content*/"DISCONNECT_BUTTON_PLUS_SHORTCUT_WINDOWS", #elif defined(OS_MACOSX) /*i18n-content*/"DISCONNECT_BUTTON_PLUS_SHORTCUT_MAC_OS_X", #else /*i18n-content*/"DISCONNECT_BUTTON_PLUS_SHORTCUT_LINUX", #endif &ui_strings.disconnect_button_text_plus_shortcut); LocalizeString(localize_func, /*i18n-content*/"CONTINUE_PROMPT", &ui_strings.continue_prompt); LocalizeString(localize_func, /*i18n-content*/"CONTINUE_BUTTON", &ui_strings.continue_button_text); LocalizeString(localize_func, /*i18n-content*/"STOP_SHARING_BUTTON", &ui_strings.stop_sharing_button_text); LocalizeString(localize_func, /*i18n-content*/"MESSAGE_SHARED", &ui_strings.disconnect_message); base::AutoLock auto_lock(ui_strings_lock_); ui_strings_ = ui_strings; } bool HostNPScriptObject::LocalizeString(NPObject* localize_func, const char* tag, string16* result) { NPVariant args[2]; STRINGZ_TO_NPVARIANT(tag, args[0]); NPVariant np_result; bool is_good = g_npnetscape_funcs->invokeDefault( plugin_, localize_func, &args[0], 1, &np_result); if (!is_good) { LOG(ERROR) << "Localization failed for " << tag; return false; } std::string translation = StringFromNPVariant(np_result); g_npnetscape_funcs->releasevariantvalue(&np_result); if (translation.empty()) { LOG(ERROR) << "Missing translation for " << tag; return false; } *result = UTF8ToUTF16(translation); return true; } void HostNPScriptObject::UpdateWebappNatPolicy(bool nat_traversal_enabled) { if (!plugin_message_loop_proxy_->BelongsToCurrentThread()) { plugin_message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&HostNPScriptObject::UpdateWebappNatPolicy, base::Unretained(this), nat_traversal_enabled)); return; } if (on_nat_traversal_policy_changed_func_.get()) { NPVariant policy; BOOLEAN_TO_NPVARIANT(nat_traversal_enabled, policy); InvokeAndIgnoreResult(on_nat_traversal_policy_changed_func_.get(), &policy, 1); } } void HostNPScriptObject::DoGenerateKeyPair(NPObject* callback) { HostKeyPair key_pair; key_pair.Generate(); InvokeGenerateKeyPairCallback(callback, key_pair.GetAsString()); } void HostNPScriptObject::InvokeGenerateKeyPairCallback( NPObject* callback, const std::string& result) { if (!plugin_message_loop_proxy_->BelongsToCurrentThread()) { plugin_message_loop_proxy_->PostTask( FROM_HERE, base::Bind( &HostNPScriptObject::InvokeGenerateKeyPairCallback, base::Unretained(this), callback, result)); return; } NPVariant result_val = NPVariantFromString(result); InvokeAndIgnoreResult(callback, &result_val, 1); g_npnetscape_funcs->releasevariantvalue(&result_val); g_npnetscape_funcs->releaseobject(callback); } void HostNPScriptObject::InvokeGetDaemonConfigCallback( NPObject* callback, scoped_ptr<base::DictionaryValue> config) { if (!plugin_message_loop_proxy_->BelongsToCurrentThread()) { plugin_message_loop_proxy_->PostTask( FROM_HERE, base::Bind( &HostNPScriptObject::InvokeGetDaemonConfigCallback, base::Unretained(this), callback, base::Passed(&config))); return; } // There is no easy way to create a dictionary from an NPAPI plugin // so we have to serialize the dictionary to pass it to JavaScript. std::string config_str; base::JSONWriter::Write(config.get(), &config_str); NPVariant config_val = NPVariantFromString(config_str); InvokeAndIgnoreResult(callback, &config_val, 1); g_npnetscape_funcs->releasevariantvalue(&config_val); g_npnetscape_funcs->releaseobject(callback); } void HostNPScriptObject::LogDebugInfo(const std::string& message) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); if (log_debug_info_func_.get()) { am_currently_logging_ = true; NPVariant log_message; STRINGZ_TO_NPVARIANT(message.c_str(), log_message); bool is_good = InvokeAndIgnoreResult(log_debug_info_func_.get(), &log_message, 1); if (!is_good) { LOG(ERROR) << "ERROR - LogDebugInfo failed\n"; } am_currently_logging_ = false; } } bool HostNPScriptObject::InvokeAndIgnoreResult(NPObject* func, const NPVariant* args, uint32_t arg_count) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); NPVariant np_result; bool is_good = g_npnetscape_funcs->invokeDefault(plugin_, func, args, arg_count, &np_result); if (is_good) g_npnetscape_funcs->releasevariantvalue(&np_result); return is_good; } void HostNPScriptObject::SetException(const std::string& exception_string) { DCHECK(plugin_message_loop_proxy_->BelongsToCurrentThread()); g_npnetscape_funcs->setexception(parent_, exception_string.c_str()); LOG(INFO) << exception_string; } } // namespace remoting
34.477833
80
0.68947
[ "object", "vector" ]
fea4b8262f50fad3eddaed20a727a864219fb572
3,515
cpp
C++
test/tools/test_surface_intersection.cpp
JanWehrmann/slam-maps
c03117e9d66ec312723ad700baabc0af04f36d70
[ "BSD-2-Clause" ]
15
2016-05-20T05:21:45.000Z
2021-07-21T02:34:18.000Z
test/tools/test_surface_intersection.cpp
JanWehrmann/slam-maps
c03117e9d66ec312723ad700baabc0af04f36d70
[ "BSD-2-Clause" ]
19
2016-06-22T18:43:36.000Z
2021-09-28T15:20:31.000Z
test/tools/test_surface_intersection.cpp
JanWehrmann/slam-maps
c03117e9d66ec312723ad700baabc0af04f36d70
[ "BSD-2-Clause" ]
12
2017-03-10T10:19:46.000Z
2021-06-04T05:50:10.000Z
// // Copyright (c) 2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH. // Copyright (c) 2017, University of Bremen // 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. // // 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. // #define BOOST_TEST_MODULE ToolsTest #include <boost/test/unit_test.hpp> #include <maps/tools/SurfaceIntersection.hpp> #include <iostream> #include <boost/test/results_collector.hpp> inline bool current_test_passing() { using namespace boost::unit_test; test_case::id_t id = framework::current_test_case().p_id; test_results rez = results_collector.results(id); return rez.passed(); } BOOST_AUTO_TEST_CASE(test_surface_intersection) { typedef Eigen::Vector3d Vec; typedef Eigen::AlignedBox3d Box; typedef Eigen::Hyperplane<double, 3> Plane; for(int i=0; i<100000; ++i) { // generate random box: Box box(Vec::Random()); box.extend(Vec::Random()); Vec inner = box.sample(); BOOST_CHECK_SMALL(box.squaredExteriorDistance(inner), 1e-4); Vec normal = Vec::Random().normalized(); BOOST_CHECK_CLOSE(normal.squaredNorm(), 1.0, 1e-6); Plane plane(normal, inner); std::vector<Vec> intersections; maps::tools::SurfaceIntersection::computeIntersections(plane, box, intersections); BOOST_CHECK_GE(intersections.size(), 3); BOOST_CHECK_LE(intersections.size(), 6); for(size_t j=0; j<intersections.size(); ++j) { const Vec &v = intersections[j]; BOOST_CHECK_SMALL(plane.signedDistance(v), 1e-4); // v must be on the plane BOOST_CHECK_SMALL(box.squaredExteriorDistance(v), 1e-4); // v must not be outside the box // next point: const Vec &next = intersections[(j+1)%intersections.size()]; BOOST_CHECK_SMALL((v-next).cwiseAbs().minCoeff(), 1e-6); // at least one coordinate must be equal to the next } // If anything failed, break and output input values: BOOST_REQUIRE_MESSAGE(current_test_passing(), "FAILED at i=" << i << " with box = [" << box.min().transpose() << " : " << box.max().transpose() << "], " "plane = (" << normal.transpose() << "; " << inner.transpose() << ')'); } }
42.349398
122
0.688762
[ "vector" ]
fea6360d231b58acb099aabd764aa54a5ce059a2
7,276
cpp
C++
inference-engine/tests/unit/cpu/shape_inference_test.cpp
SDxKeeper/dldt
a7dff0d0ec930c4c83690d41af6f6302b389f361
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/unit/cpu/shape_inference_test.cpp
SDxKeeper/dldt
a7dff0d0ec930c4c83690d41af6f6302b389f361
[ "Apache-2.0" ]
34
2020-11-20T15:19:18.000Z
2022-02-21T13:13:48.000Z
inference-engine/tests/unit/cpu/shape_inference_test.cpp
ababushk/openvino
80c707090ca691eedc16babf4369b89dd297858e
[ "Apache-2.0" ]
1
2019-09-03T08:35:20.000Z
2019-09-03T08:35:20.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "utils/shape_inference/static_shape.hpp" #include <convolution_shape_inference.hpp> #include <experimental_detectron_detection_output_shape_inference.hpp> #include <gtest/gtest.h> #include <openvino/core/coordinate_diff.hpp> #include <openvino/op/convolution.hpp> #include <openvino/op/ops.hpp> #include <openvino/op/parameter.hpp> using namespace ov; TEST(StaticShapeInferenceTest, ConvolutionTest) { Strides strides{1, 1}; CoordinateDiff pads_begin{0, 0}; CoordinateDiff pads_end{0, 0}; Strides dilations{1, 1}; const auto auto_pad = op::PadType::SAME_LOWER; auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto conv = std::make_shared<op::v1::Convolution>(data, filters, strides, pads_begin, pads_end, dilations, auto_pad); std::vector<PartialShape> input_shapes = {PartialShape{3, 6, 5, 5}, PartialShape{7, 6, 3, 3}}, output_shapes = {PartialShape{}}; shape_infer(conv.get(), input_shapes, output_shapes); ASSERT_EQ(output_shapes[0], PartialShape({3, 7, 5, 5})); ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{1, 1})); ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{1, 1})); std::vector<StaticShape> static_input_shapes = {StaticShape{3, 6, 5, 5}, StaticShape{7, 6, 3, 3}}, static_output_shapes = {StaticShape{}}; shape_infer(conv.get(), static_input_shapes, static_output_shapes); ASSERT_EQ(static_output_shapes[0], StaticShape({3, 7, 5, 5})); ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{1, 1})); ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{1, 1})); } TEST(StaticShapeInferenceTest, ExperimentalDetectronDetectionOutputTest) { using Attrs = op::v6::ExperimentalDetectronDetectionOutput::Attributes; Attrs attrs; attrs.class_agnostic_box_regression = true; attrs.deltas_weights = {10.0f, 10.0f, 5.0f, 5.0f}; attrs.max_delta_log_wh = 2.0f; attrs.max_detections_per_image = 5; attrs.nms_threshold = 0.2f; attrs.num_classes = 2; attrs.post_nms_count = 500; attrs.score_threshold = 0.01000000074505806f; int64_t rois_num = static_cast<int64_t>(attrs.max_detections_per_image); auto rois = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1}); auto deltas = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1}); auto scores = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1}); auto im_info = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1}); auto detection = std::make_shared<ov::op::v6::ExperimentalDetectronDetectionOutput>( rois, deltas, scores, im_info, attrs); std::vector<PartialShape> input_shapes = { PartialShape::dynamic(), PartialShape::dynamic(), PartialShape::dynamic(), PartialShape::dynamic()}; std::vector<PartialShape> output_shapes = {PartialShape::dynamic(), PartialShape::dynamic(), PartialShape::dynamic()}; shape_infer(detection.get(), input_shapes, output_shapes); ASSERT_EQ(output_shapes[0], (PartialShape{rois_num, 4})); ASSERT_EQ(output_shapes[1], (PartialShape{rois_num})); ASSERT_EQ(output_shapes[2], (PartialShape{rois_num})); input_shapes = {PartialShape{-1, -1}, PartialShape{-1, -1}, PartialShape{-1, -1}, PartialShape{-1, -1}}; output_shapes = {PartialShape{}, PartialShape{}, PartialShape{}}; shape_infer(detection.get(), input_shapes, output_shapes); ASSERT_EQ(output_shapes[0], (PartialShape{rois_num, 4})); ASSERT_EQ(output_shapes[1], (PartialShape{rois_num})); ASSERT_EQ(output_shapes[2], (PartialShape{rois_num})); input_shapes = {PartialShape{16, 4}, PartialShape{16, 8}, PartialShape{16, 2}, PartialShape{1, 3}}; output_shapes = {PartialShape{}, PartialShape{}, PartialShape{}}; shape_infer(detection.get(), input_shapes, output_shapes); ASSERT_EQ(output_shapes[0], (PartialShape{rois_num, 4})); ASSERT_EQ(output_shapes[1], (PartialShape{rois_num})); ASSERT_EQ(output_shapes[2], (PartialShape{rois_num})); std::vector<StaticShape> static_input_shapes = {StaticShape{16, 4}, StaticShape{16, 8}, StaticShape{16, 2}, StaticShape{1, 3}}; std::vector<StaticShape> static_output_shapes = {StaticShape{}, StaticShape{}, StaticShape{}}; shape_infer(detection.get(), static_input_shapes, static_output_shapes); ASSERT_EQ(static_output_shapes[0], StaticShape({attrs.max_detections_per_image, 4})); ASSERT_EQ(static_output_shapes[1], StaticShape({attrs.max_detections_per_image})); ASSERT_EQ(static_output_shapes[2], StaticShape({attrs.max_detections_per_image})); } #if 0 TEST(StaticShapeInferenceTest, ConvolutionTimeTest) { Strides strides{1, 1}; CoordinateDiff pads_begin{0, 0}; CoordinateDiff pads_end{0, 0}; Strides dilations{1, 1}; const auto auto_pad = op::PadType::SAME_LOWER; auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{3, 6, 5, 5}); auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{7, 6, 3, 3}); auto conv = std::make_shared<op::v1::Convolution>(data, filters, strides, pads_begin, pads_end, dilations, auto_pad); std::vector<StaticShape> static_input_shapes = {StaticShape{3, 6, 5, 5}, StaticShape{7, 6, 3, 3}}, static_output_shapes = {StaticShape{}}; auto before = std::chrono::high_resolution_clock::now(); auto after = std::chrono::high_resolution_clock::now(); std::cout << conv << std::endl; auto convolution_time_sum = 0; for (size_t i = 0; i < 10; ++i) { before = std::chrono::high_resolution_clock::now(); shape_infer(conv.get(), static_input_shapes, static_output_shapes); after = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before).count(); std::cout << diff << " ns" << std::endl; convolution_time_sum += diff; } // other operation creation and time measurements: ReLU is an example auto relu = std::make_shared<op::v0::Relu>(data); std::cout << relu << std::endl; auto other_op_time_sum = 0; for (size_t i = 0; i < 10; ++i) { before = std::chrono::high_resolution_clock::now(); relu->validate_and_infer_types(); after = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before).count(); std::cout << diff << " ns" << std::endl; other_op_time_sum += diff; } std::cout << (convolution_time_sum >= other_op_time_sum ? "ON PAR WITH CONVOLUTION: " : "LONGER THAN CONVOLUTION ") << 1. * other_op_time_sum / convolution_time_sum << std::endl; } #endif
49.496599
142
0.664651
[ "vector" ]
fea77811fbadc2c103a1438402d4a9bf06bb14e5
1,293
cpp
C++
test/palAngularMotorTest.cpp
kephale/Physics-Abstraction-Layer
3d5ef62213143bb9ddc410edef348c94bda70cab
[ "BSD-3-Clause" ]
6
2018-02-27T12:32:05.000Z
2020-12-21T09:43:38.000Z
test/palAngularMotorTest.cpp
5l1v3r1/Physics-Abstraction-Layer
3d5ef62213143bb9ddc410edef348c94bda70cab
[ "BSD-3-Clause" ]
null
null
null
test/palAngularMotorTest.cpp
5l1v3r1/Physics-Abstraction-Layer
3d5ef62213143bb9ddc410edef348c94bda70cab
[ "BSD-3-Clause" ]
4
2015-07-25T16:55:16.000Z
2020-07-15T05:46:30.000Z
/* * palBodyTest.cpp * * Created on: Jul 1, 2010 * Author: Chris Long * Copyright (C) 2010 SET Corporation */ #include <pal/pal.h> #include <pal/palFactory.h> #include <iostream> #include <cstdlib> #include <float.h> #include <assert.h> int main(int argc, char* argv[]) { //std::cout << "pAMT: type_info for pAM = " << &typeid(palAngularMotor) << std::endl; PF->LoadPhysicsEngines(); PF->SelectEngine("Bullet"); // Here is the name of the physics engine you wish to use. You could replace DEFAULT_ENGINE with "Tokamak", "ODE", etc... palPhysics *pp = PF->CreatePhysics(); //create the main physics class if (pp == NULL) { std::cerr << "Failed to create the physics engine. Check to see if you spelt the engine name correctly, or that the engine DLL is in the right location" << std::endl; return 1; } palPhysicsDesc desc; pp->Init(desc); //initialize it, set the main gravity vector palFactoryObject* obj = PF->CreateObject("palAngularMotor"); palAngularMotor* angularMotor = dynamic_cast<palAngularMotor*>(obj); //std::cout << "pAMT: type_info for pAM = " << &typeid(palAngularMotor) << std::endl; assert(angularMotor != 0); std::cout << "angularMotor = " << angularMotor << std::endl; pp->Cleanup(); std::cout << "success" << std::endl; return 0; }
31.536585
168
0.678268
[ "vector" ]