hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b163203adc5166a3a5947d9ed649f545a90789d3
3,625
cpp
C++
mcg/src/aux/mex_cands2masks.cpp
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
392
2015-01-14T13:19:40.000Z
2022-02-12T08:47:33.000Z
mcg/src/aux/mex_cands2masks.cpp
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
45
2015-02-03T12:16:10.000Z
2022-03-07T00:25:09.000Z
mcg/src/aux/mex_cands2masks.cpp
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
168
2015-01-05T02:29:53.000Z
2022-02-22T04:32:04.000Z
// ------------------------------------------------------------------------ // Copyright (C) // Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain // University of California Berkeley (UCB) - USA // // Jordi Pont-Tuset <jordi.pont@upc.edu> // Pablo Arbelaez <arbelaez@berkeley.edu> // June 2014 // ------------------------------------------------------------------------ // This file is part of the MCG package presented in: // Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J, // "Multiscale Combinatorial Grouping," // Computer Vision and Pattern Recognition (CVPR) 2014. // Please consider citing the paper if you use this code. // ------------------------------------------------------------------------ #include "mex.h" #include <iostream> #include <set> #include <map> #include <list> #include "matlab_multiarray.hpp" using namespace std; void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { /* Check for proper number of arguments */ if (nrhs != 3) { mexErrMsgTxt("Three input arguments required."); } else if (nlhs > 3) { mexErrMsgTxt("Too many output arguments."); } /* Input as a Multiarray */ ConstMatlabMultiArray<double> lp(prhs[0]); /* Leaves partition */ ConstMatlabMultiArray<double> ms(prhs[1]); /* Merging sequence */ ConstMatlabMultiArray<double> cands(prhs[2]); /* Candidates */ /* Input sizes and checks */ size_t sm = lp.shape()[0]; size_t sn = lp.shape()[1]; size_t n_sons_max= ms.shape()[1]-1; size_t n_merges = ms.shape()[0]; size_t n_leaves = ms[0][n_sons_max]-1; // n_merges+1; --> Not valid for non-binary trees size_t n_regs = n_leaves+n_merges; size_t n_cands = cands.shape()[0]; size_t n_regs_max= cands.shape()[1]; /* Create the list of activated pixels in each leave region */ vector<list<size_t> > x_coords(n_regs); vector<list<size_t> > y_coords(n_regs); for (size_t xx=0; xx<sm; ++xx) { for (size_t yy=0; yy<sn; ++yy) { size_t curr_leave = lp[xx][yy]-1; x_coords[curr_leave].push_back(xx); y_coords[curr_leave].push_back(yy); } } /* Bottom-up expansion of the lists of pixels */ for (size_t ii=0; ii<n_merges; ++ii) { for (size_t jj=0; jj<n_sons_max; ++jj) { if (ms[ii][jj]==0) break; x_coords[n_leaves+ii].insert(x_coords[n_leaves+ii].end(), x_coords[ms[ii][jj]-1].begin(), x_coords[ms[ii][jj]-1].end()); y_coords[n_leaves+ii].insert(y_coords[n_leaves+ii].end(), y_coords[ms[ii][jj]-1].begin(), y_coords[ms[ii][jj]-1].end()); } } /* Allocate out masks */ size_t ndim = 3; mwSize dims[3]; dims[0] = sm; dims[1] = sn; dims[2] = n_cands; plhs[0] = mxCreateLogicalArray(3, dims); MatlabMultiArray3<bool> out_masks(plhs[0]); for (size_t ii=0; ii<n_cands; ++ii) { for (size_t jj=0; jj<n_regs_max; ++jj) { if (cands[ii][jj]==0) break; list<size_t>::iterator itx = x_coords[cands[ii][jj]-1].begin(); list<size_t>::iterator ity = y_coords[cands[ii][jj]-1].begin(); for( ; itx!=x_coords[cands[ii][jj]-1].end(); ++itx, ++ity) { out_masks[*itx][*ity][ii] = true; } } } }
34.52381
94
0.516966
mouthwater
b163e11e45e58be069f09fea1e0a569225bb8217
283
cpp
C++
main.cpp
ipeperko/ivo_sandbox
92054b242c55d58432291b70b7874c253fc3474a
[ "MIT" ]
null
null
null
main.cpp
ipeperko/ivo_sandbox
92054b242c55d58432291b70b7874c253fc3474a
[ "MIT" ]
null
null
null
main.cpp
ipeperko/ivo_sandbox
92054b242c55d58432291b70b7874c253fc3474a
[ "MIT" ]
null
null
null
#include <iostream> #include "mysql/mysql.h" int main() { MYSQL* mysql = mysql_init(nullptr); mysql_close(mysql); #ifdef TEST_OPTION std::cout << "[ok] Test option enabled\n"; return 0; #else std::cout << "[error] Test option disabled\n"; return 1; #endif }
17.6875
50
0.636042
ipeperko
b164242e5fad22d2f461f58329efeb54918b88f2
2,397
cpp
C++
muta_io/server.cpp
mingkaic/verum
49a095373f5e30f798dfc73a023fd1a0d3ec2e58
[ "MIT" ]
null
null
null
muta_io/server.cpp
mingkaic/verum
49a095373f5e30f798dfc73a023fd1a0d3ec2e58
[ "MIT" ]
null
null
null
muta_io/server.cpp
mingkaic/verum
49a095373f5e30f798dfc73a023fd1a0d3ec2e58
[ "MIT" ]
null
null
null
#include <sstream> #include <iomanip> #include <grpcpp/grpcpp.h> #include <grpcpp/security/server_credentials.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include "muta/mutation.grpc.pb.h" template <typename T> static void to_string (std::ostream& out, const google::protobuf::RepeatedField<T>& vec) { if (vec.size() > 0) { out << std::setprecision(std::numeric_limits<T>::digits10 + 1) << vec.at(0); } for (size_t i = 1, n = vec.size(); i < n; ++i) { out << "," << vec.at(i); } } static void to_string (std::ostream& out, const google::protobuf::RepeatedPtrField<std::string>& vec) { if (vec.size() > 0) { out << vec.at(0); } for (size_t i = 1, n = vec.size(); i < n; ++i) { out << "," << vec.at(i); } } static void print_entry (std::ostream& out, const std::string& name, const muta::MutatorEntry& entry) { std::string type; std::stringstream ss; switch (entry.type()) { case muta::EntryType::INT: type = "int64_t"; to_string(ss, entry.is()); break; case muta::EntryType::DOUBLE: type = "double"; to_string(ss, entry.ds()); break; case muta::EntryType::STRING: type = "std::string"; to_string(ss, entry.ss()); break; default: break; } out << "std::vector<" << type << "> " << name << " = {" << ss.str() << "};"; } class MutationErrorStorageImpl final : public muta::MutationErrorStorage::Service { grpc::Status SaveSessions (grpc::ServerContext* context, const muta::SaveSessionsRequest* request, muta::SaveSessionsResponse* response) override { auto& sessions = request->sessions(); for (auto& session : sessions) { std::cout << "// failed " << session.id() << "\n"; auto& entries = session.entries(); for (auto& entry : entries) { print_entry(std::cout, entry.first, entry.second); std::cout << "\n"; } std::cout << std::endl; } return grpc::Status::OK; } }; void RunServer (void) { std::string server_address("0.0.0.0:50051"); MutationErrorStorageImpl service; grpc::ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<grpc::Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } int main (int argc, char** argv) { RunServer(); return 0; }
23.732673
101
0.647893
mingkaic
b1645c0f78a8e08be744c8f77c3bbcaf3f069366
18,857
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8HTMLTableRowElement.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8HTMLTableRowElement.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8HTMLTableRowElement.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8HTMLTableRowElement.h" #include "HTMLNames.h" #include "bindings/core/v8/V8HTMLCollection.h" #include "bindings/core/v8/V8HTMLElement.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "core/dom/ClassCollection.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/dom/TagCollection.h" #include "core/dom/custom/CustomElementCallbackDispatcher.h" #include "core/html/HTMLCollection.h" #include "core/html/HTMLFormControlsCollection.h" #include "core/html/HTMLTableRowsCollection.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(HTMLTableRowElement* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8HTMLTableRowElement::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::HTMLTableRowElement* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8HTMLTableRowElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8HTMLTableRowElement::domTemplate, V8HTMLTableRowElement::derefObject, 0, V8HTMLTableRowElement::toEventTarget, 0, V8HTMLTableRowElement::installPerContextEnabledMethods, &V8HTMLElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject }; namespace HTMLTableRowElementV8Internal { template <typename T> void V8_USE(T) { } static void rowIndexAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueInt(info, impl->rowIndex()); } static void rowIndexAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::rowIndexAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void sectionRowIndexAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueInt(info, impl->sectionRowIndex()); } static void sectionRowIndexAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::sectionRowIndexAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void cellsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueFast(info, WTF::getPtr(impl->cells()), impl); } static void cellsAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::cellsAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void alignAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::alignAttr), info.GetIsolate()); } static void alignAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::alignAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void alignAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::alignAttr, cppValue); } static void alignAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::alignAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void bgColorAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::bgcolorAttr), info.GetIsolate()); } static void bgColorAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::bgColorAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void bgColorAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<WithNullCheck>, cppValue, v8Value); impl->setAttribute(HTMLNames::bgcolorAttr, cppValue); } static void bgColorAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::bgColorAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::charAttr), info.GetIsolate()); } static void chAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::chAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::charAttr, cppValue); } static void chAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::chAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chOffAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::charoffAttr), info.GetIsolate()); } static void chOffAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::chOffAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chOffAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::charoffAttr, cppValue); } static void chOffAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::chOffAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void vAlignAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::valignAttr), info.GetIsolate()); } static void vAlignAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::vAlignAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void vAlignAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::valignAttr, cppValue); } static void vAlignAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::vAlignAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void insertCellMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "insertCell", "HTMLTableRowElement", info.Holder(), info.GetIsolate()); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(info.Holder()); int index; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); if (UNLIKELY(info.Length() <= 0)) { RefPtrWillBeRawPtr<HTMLElement> result = impl->insertCell(exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl); return; } TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(index, toInt32(info[0], exceptionState), exceptionState); } RefPtrWillBeRawPtr<HTMLElement> result = impl->insertCell(index, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl); } static void insertCellMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); HTMLTableRowElementV8Internal::insertCellMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void deleteCellMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "deleteCell", "HTMLTableRowElement", info.Holder(), info.GetIsolate()); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(info.Holder()); int index; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(index, toInt32(info[0], exceptionState), exceptionState); } impl->deleteCell(index, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void deleteCellMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); HTMLTableRowElementV8Internal::deleteCellMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } } // namespace HTMLTableRowElementV8Internal static const V8DOMConfiguration::AttributeConfiguration V8HTMLTableRowElementAttributes[] = { {"rowIndex", HTMLTableRowElementV8Internal::rowIndexAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"sectionRowIndex", HTMLTableRowElementV8Internal::sectionRowIndexAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"cells", HTMLTableRowElementV8Internal::cellsAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"align", HTMLTableRowElementV8Internal::alignAttributeGetterCallback, HTMLTableRowElementV8Internal::alignAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"bgColor", HTMLTableRowElementV8Internal::bgColorAttributeGetterCallback, HTMLTableRowElementV8Internal::bgColorAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"ch", HTMLTableRowElementV8Internal::chAttributeGetterCallback, HTMLTableRowElementV8Internal::chAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"chOff", HTMLTableRowElementV8Internal::chOffAttributeGetterCallback, HTMLTableRowElementV8Internal::chOffAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"vAlign", HTMLTableRowElementV8Internal::vAlignAttributeGetterCallback, HTMLTableRowElementV8Internal::vAlignAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static const V8DOMConfiguration::MethodConfiguration V8HTMLTableRowElementMethods[] = { {"insertCell", HTMLTableRowElementV8Internal::insertCellMethodCallback, 0, 0}, {"deleteCell", HTMLTableRowElementV8Internal::deleteCellMethodCallback, 0, 0}, }; static void configureV8HTMLTableRowElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "HTMLTableRowElement", V8HTMLElement::domTemplate(isolate), V8HTMLTableRowElement::internalFieldCount, V8HTMLTableRowElementAttributes, WTF_ARRAY_LENGTH(V8HTMLTableRowElementAttributes), 0, 0, V8HTMLTableRowElementMethods, WTF_ARRAY_LENGTH(V8HTMLTableRowElementMethods), isolate); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8HTMLTableRowElement::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8HTMLTableRowElementTemplate); } bool V8HTMLTableRowElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8HTMLTableRowElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } HTMLTableRowElement* V8HTMLTableRowElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } EventTarget* V8HTMLTableRowElement::toEventTarget(v8::Handle<v8::Object> object) { return toNative(object); } v8::Handle<v8::Object> wrap(HTMLTableRowElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8HTMLTableRowElement>(impl, isolate)); return V8HTMLTableRowElement::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8HTMLTableRowElement::createWrapper(PassRefPtrWillBeRawPtr<HTMLTableRowElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8HTMLTableRowElement>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8HTMLTableRowElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent); return wrapper; } void V8HTMLTableRowElement::derefObject(void* object) { #if !ENABLE(OILPAN) fromInternalPointer(object)->deref(); #endif // !ENABLE(OILPAN) } template<> v8::Handle<v8::Value> toV8NoInline(HTMLTableRowElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
46.560494
350
0.766241
jingcao80
b16748b573c6346e09a61f774b1ccd5309d61bfb
1,051
cc
C++
HTTP/src/HttpError.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
HTTP/src/HttpError.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
HTTP/src/HttpError.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2021 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/HttpError> namespace cc { HttpBadRequest::HttpBadRequest(): HttpError{HttpStatus::BadRequest, "Bad Request"} {} HttpForbidden::HttpForbidden(): HttpError{HttpStatus::Forbidden, "Forbidden"} {} HttpNotFound::HttpNotFound(): HttpError{HttpStatus::NotFound, "Not Found"} {} HttpRequestTimeout::HttpRequestTimeout(): HttpError{HttpStatus::RequestTimeout, "Request Timeout"} {} HttpPayloadTooLarge::HttpPayloadTooLarge(): HttpError{HttpStatus::PayloadTooLarge, "Payload Too Large"} {} HttpInternalServerError::HttpInternalServerError(): HttpError{HttpStatus::InternalServerError, "Internal Server Error"} {} HttpUnsupportedVersion::HttpUnsupportedVersion(): HttpError{HttpStatus::UnsupportedVersion, "HTTP Version Not Supported"} {} HttpNotImplemented::HttpNotImplemented(): HttpError{HttpStatus::NotImplemented, "Not Implemented"} {} } // namespace cc
22.847826
75
0.748811
frankencode
b168904ce51d091f29e795d8cf1c703af758af40
2,842
cpp
C++
src/graphics/RendererApiEnum.cpp
Kepler-Br/Vanadium
6769a55b7af64af1da83792c1049f3c37df5681f
[ "MIT" ]
1
2021-09-16T20:41:29.000Z
2021-09-16T20:41:29.000Z
src/graphics/RendererApiEnum.cpp
Kepler-Br/Vanadium
6769a55b7af64af1da83792c1049f3c37df5681f
[ "MIT" ]
null
null
null
src/graphics/RendererApiEnum.cpp
Kepler-Br/Vanadium
6769a55b7af64af1da83792c1049f3c37df5681f
[ "MIT" ]
1
2021-09-16T20:41:30.000Z
2021-09-16T20:41:30.000Z
#include "RendererApiEnum.h" namespace vanadium { std::string_view rendererApiToString(RendererApi rendererApi) { switch (rendererApi) { case RendererApi::Direct3D11: return "Direct3D11"; case RendererApi::Direct3D9: return "Direct3D9"; case RendererApi::Direct3D12: return "Direct3D12"; case RendererApi::Gnm: return "Gnm"; case RendererApi::Metal: return "Metal"; case RendererApi::Nvn: return "Nvn"; case RendererApi::OpenGLES: return "OpenGLES"; case RendererApi::OpenGL: return "OpenGL"; case RendererApi::Vulkan: return "Vulkan"; case RendererApi::WebGPU: return "WebGPU"; case RendererApi::Noop: return "Noop"; case RendererApi::Any: return "Any"; default: return "Undefined"; } } RendererApi bgfxTypeToRendererApi(bgfx::RendererType::Enum rendererType) { using namespace bgfx; switch (rendererType) { case RendererType::Enum::Direct3D9: return RendererApi::Direct3D9; case RendererType::Noop: return RendererApi::Noop; case RendererType::Direct3D11: return RendererApi::Direct3D11; case RendererType::Direct3D12: return RendererApi::Direct3D12; case RendererType::Gnm: return RendererApi::Gnm; case RendererType::Metal: return RendererApi::Metal; case RendererType::Nvn: return RendererApi::Nvn; case RendererType::OpenGLES: return RendererApi::OpenGLES; case RendererType::OpenGL: return RendererApi::OpenGL; case RendererType::Vulkan: return RendererApi::Vulkan; case RendererType::WebGPU: return RendererApi::WebGPU; case RendererType::Count: return RendererApi::Noop; default: return RendererApi::Undefined; } } bgfx::RendererType::Enum rendererApiToBgfxType(RendererApi rendererApi) { using namespace bgfx; switch (rendererApi) { case RendererApi::Direct3D11: return RendererType::Enum::Direct3D11; case RendererApi::Direct3D9: return RendererType::Enum::Direct3D9; case RendererApi::Direct3D12: return RendererType::Enum::Direct3D12; case RendererApi::Gnm: return RendererType::Enum::Gnm; case RendererApi::Metal: return RendererType::Enum::Metal; case RendererApi::Nvn: return RendererType::Enum::Nvn; case RendererApi::OpenGLES: return RendererType::Enum::OpenGLES; case RendererApi::OpenGL: return RendererType::Enum::OpenGL; case RendererApi::Vulkan: return RendererType::Enum::Vulkan; case RendererApi::WebGPU: return RendererType::Enum::WebGPU; default: return RendererType::Enum::Noop; } } } // namespace vanadium
29
75
0.655876
Kepler-Br
b168b58ea484682d51dc8f2dce0812958beacf55
4,749
cpp
C++
src/terminal/pty/ConPty.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
null
null
null
src/terminal/pty/ConPty.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
null
null
null
src/terminal/pty/ConPty.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
null
null
null
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <terminal/pty/ConPty.h> #include <Windows.h> #include <utility> using namespace std; namespace { string GetLastErrorAsString() { DWORD errorMessageID = GetLastError(); if (errorMessageID == 0) return ""; LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &messageBuffer, 0, nullptr); string message(messageBuffer, size); LocalFree(messageBuffer); return message; } } // anonymous namespace namespace terminal { ConPty::ConPty(PageSize const& _windowSize): size_ { _windowSize } { master_ = INVALID_HANDLE_VALUE; input_ = INVALID_HANDLE_VALUE; output_ = INVALID_HANDLE_VALUE; HANDLE hPipePTYIn { INVALID_HANDLE_VALUE }; HANDLE hPipePTYOut { INVALID_HANDLE_VALUE }; // Create the pipes to which the ConPty will connect to if (!CreatePipe(&hPipePTYIn, &output_, NULL, 0)) throw runtime_error { GetLastErrorAsString() }; if (!CreatePipe(&input_, &hPipePTYOut, NULL, 0)) { CloseHandle(hPipePTYIn); throw runtime_error { GetLastErrorAsString() }; } // Create the Pseudo Console of the required size, attached to the PTY-end of the pipes HRESULT hr = CreatePseudoConsole({ unbox<SHORT>(_windowSize.columns), unbox<SHORT>(_windowSize.lines) }, hPipePTYIn, hPipePTYOut, 0, &master_); if (hPipePTYIn != INVALID_HANDLE_VALUE) CloseHandle(hPipePTYIn); if (hPipePTYOut != INVALID_HANDLE_VALUE) CloseHandle(hPipePTYOut); if (hr != S_OK) throw runtime_error { GetLastErrorAsString() }; buffer_.resize(10240); } ConPty::~ConPty() { close(); } bool ConPty::isClosed() const { return master_ == INVALID_HANDLE_VALUE; } void ConPty::close() { auto const _ = std::lock_guard { mutex_ }; if (master_ != INVALID_HANDLE_VALUE) { ClosePseudoConsole(master_); master_ = INVALID_HANDLE_VALUE; } if (input_ != INVALID_HANDLE_VALUE) { CloseHandle(input_); input_ = INVALID_HANDLE_VALUE; } if (output_ != INVALID_HANDLE_VALUE) { CloseHandle(output_); output_ = INVALID_HANDLE_VALUE; } } void ConPty::prepareParentProcess() { } void ConPty::prepareChildProcess() { } optional<string_view> ConPty::read(size_t _size, std::chrono::milliseconds _timeout) { // TODO: wait for _timeout time at most AND got woken up upon wakeupReader() invokcation. (void) _timeout; auto const n = static_cast<DWORD>(min(_size, buffer_.size())); DWORD nread {}; if (!ReadFile(input_, buffer_.data(), n, &nread, nullptr)) return nullopt; return string_view { buffer_.data(), nread }; } void ConPty::wakeupReader() { // TODO: Windows ConPTY does *NOT* support non-blocking / overlapped I/O. // How can we make ReadFile() return early? We could maybe WriteFile() to it? } int ConPty::write(char const* buf, size_t size) { DWORD nwritten {}; if (WriteFile(output_, buf, static_cast<DWORD>(size), &nwritten, nullptr)) return static_cast<int>(nwritten); else return -1; } PageSize ConPty::pageSize() const noexcept { return size_; } void ConPty::resizeScreen(PageSize _cells, std::optional<ImageSize> _pixels) { (void) _pixels; // TODO Can we pass that information, too? COORD coords; coords.X = unbox<unsigned short>(_cells.columns); coords.Y = unbox<unsigned short>(_cells.lines); HRESULT const result = ResizePseudoConsole(master_, coords); if (result != S_OK) throw runtime_error { GetLastErrorAsString() }; size_ = _cells; } } // namespace terminal
26.530726
108
0.635923
dandycheung
b16a73d1932d69161cef21a71f386e6aa9590ffa
1,691
cpp
C++
tree/leetcode_tree/113_path_sum_3.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
tree/leetcode_tree/113_path_sum_3.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
tree/leetcode_tree/113_path_sum_3.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
// // 113_path_sum_3.cpp // leetcode_tree // // Created by Hadley on 11.07.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> using namespace std; /** * Definition for a binary tree node.*/ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; //better solution// //*https://leetcode.com/problems/path-sum-ii/discuss/723689/C%2B%2B-96-Faster-Easytounderstand-With-Explanation*// class Solution { public: vector<vector<int>> path(TreeNode* root){ if(!root)return{}; if(!root->left&&!root->right) return {{root->val}}; vector<vector<int>> a=path(root->left); for(auto &x:a) x.push_back(root->val); vector<vector<int>> b=path(root->right); for(auto &x:b) x.push_back(root->val); a.insert(a.end(), b.begin(),b.end()); return a; } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; for(auto &x:path(root)){ int s=0; for(auto &y:x){ s+=y; } if(s==sum){ reverse(x.begin(), x.end()); res.push_back(x); } } return res; } };
23.816901
114
0.556475
Hadleyhzy
b16b38aec1e015785c877a49a58f439d06f3dbcf
6,884
hpp
C++
VSDataReduction/VSLaserData.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
VSDataReduction/VSLaserData.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
VSDataReduction/VSLaserData.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file VSLaserData.hpp Simple pedestal data \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 05/18/2005 $Id: VSLaserData.hpp,v 3.8 2009/11/24 01:11:45 matthew Exp $ */ #ifndef VSLASERDATA_HPP #define VSLASERDATA_HPP #include<string> #include<vector> #include<VSOctaveIO.hpp> #include<VSSimpleHist.hpp> namespace VERITAS { class VSLaserData { public: struct CrateData { CrateData(): l2chan(), l2time(), cratetime_mean(), cratetime_dev() {} // Data ----------------------------------------------------------------- unsigned l2chan; // L2 channel double l2time; // L2 arrival time double cratetime_mean; // Crate arrival time - L2 time double cratetime_dev; // Crate arrival time dev static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,CrateData,l2chan); H5_ADDMEMBER(c,CrateData,l2time); H5_ADDMEMBER(c,CrateData,cratetime_mean); H5_ADDMEMBER(c,CrateData,cratetime_dev); } }; struct ChanData { ChanData(): nflash(), l2chan(), crate(), uncalibrated(), excluded(), chantime(), cratetime(), l2time(), gain(), gain_err(), absgain(), absgain_err(), eff(), eff_err(), signal_mean(), signal_dev(), signal_corr_mean(), signal_corr_dev(), signal_hist(0) { } // Data ----------------------------------------------------------------- unsigned nflash; // Number of flashes recorded unsigned l2chan; // L2 channel unsigned crate; // Crate number bool uncalibrated; // Has less than required # of laser flashes bool excluded; // Excluded from mean/median calculations double chantime; // Channel arrival time - L2 time double cratetime; // Crate arrival time - L2 time double l2time; // L2 arrival time for crate double gain; // Total gain relative to median double gain_err; double absgain; // Absolute single PE gain in DC double absgain_err; double eff; // Efficiency relative to median double eff_err; double signal_mean; // Laser amplitude mean double signal_dev; // Laser amplitude dev double signal_corr_mean; // Corrected laser amplitude mean double signal_corr_dev; // Corrected laser amplitude dev // Histograms ----------------------------------------------------------- VSSimpleHist<double> signal_hist; // Histogram of signal_mean static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,ChanData,nflash); H5_ADDMEMBER(c,ChanData,l2chan); H5_ADDMEMBER(c,ChanData,crate); H5_ADDMEMBER(c,ChanData,uncalibrated); H5_ADDMEMBER(c,ChanData,excluded); H5_ADDMEMBER(c,ChanData,chantime); H5_ADDMEMBER(c,ChanData,cratetime); H5_ADDMEMBER(c,ChanData,l2time); H5_ADDMEMBER(c,ChanData,gain); H5_ADDMEMBER(c,ChanData,gain_err); H5_ADDMEMBER(c,ChanData,absgain); H5_ADDMEMBER(c,ChanData,absgain_err); H5_ADDMEMBER(c,ChanData,eff); H5_ADDMEMBER(c,ChanData,eff_err); H5_ADDMEMBER(c,ChanData,signal_mean); H5_ADDMEMBER(c,ChanData,signal_dev); H5_ADDMEMBER(c,ChanData,signal_corr_mean); H5_ADDMEMBER(c,ChanData,signal_corr_dev); } }; struct ScopeData { ScopeData(): runno(), nchan(0), nevents(0), nflash(0), absgain_mean(), absgain_median(), npe_mean(), npe_median(), nchan_mean(), nchan_dev(), signal_mean(), signal_dev(), signal_hist(0), nchan_flash_hist(0), nchan_logain_hist(0), nchan_higain_hist(0), chan(), crate() {} // Data ----------------------------------------------------------------- unsigned runno; unsigned nchan; // Number channels in this telescope unsigned nevents; // Number events in laser run unsigned nflash; // Number events passing laser criteria double absgain_mean; // Mean absolute gain double absgain_median; // Median absolute gain double npe_mean; // Mean number of PEs per pixel double npe_median; // Median number of PEs per pixel double nchan_mean; // Number of channels in each flash mean double nchan_dev; // Number of channels in each flash dev double signal_mean; // Average telescope laser amplitude mean double signal_dev; // Average telescope laser amplitude dev // Histograms ----------------------------------------------------------- VSSimpleHist<double> signal_hist; VSSimpleHist<unsigned> nchan_flash_hist; VSSimpleHist<unsigned> nchan_logain_hist; VSSimpleHist<unsigned> nchan_higain_hist; // Vectors of structures ------------------------------------------------ std::vector<ChanData> chan; std::vector<CrateData> crate; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,ScopeData,runno); H5_ADDMEMBER(c,ScopeData,nchan); H5_ADDMEMBER(c,ScopeData,nevents); H5_ADDMEMBER(c,ScopeData,nflash); H5_ADDMEMBER(c,ScopeData,absgain_mean); H5_ADDMEMBER(c,ScopeData,absgain_median); H5_ADDMEMBER(c,ScopeData,npe_mean); H5_ADDMEMBER(c,ScopeData,npe_median); H5_ADDMEMBER(c,ScopeData,nchan_mean); H5_ADDMEMBER(c,ScopeData,nchan_dev); H5_ADDMEMBER(c,ScopeData,signal_mean); H5_ADDMEMBER(c,ScopeData,signal_dev); } }; // Data ------------------------------------------------------------------- unsigned m_runno; // Settings --------------------------------------------------------------- unsigned m_threshold_nchan; double m_threshold_dc; double m_singlepe_dev; // Vectors of structures -------------------------------------------------- std::vector<ScopeData> scope; VSLaserData(): m_runno(), m_threshold_nchan(), m_threshold_dc(), m_singlepe_dev(), scope() { /* nothing to see here */ } bool load(const std::string& filename); void suppress(const double lo, const double hi); void clear(); void load(VSOctaveH5ReaderStruct* reader); bool load(unsigned iscope,VSOctaveH5ReaderStruct* reader); void save(VSOctaveH5WriterStruct* writer) const; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,VSLaserData,m_runno); H5_ADDMEMBER(c,VSLaserData,m_threshold_nchan); H5_ADDMEMBER(c,VSLaserData,m_threshold_dc); H5_ADDMEMBER(c,VSLaserData,m_singlepe_dev); } private: VSLaserData(const VSLaserData&); VSLaserData& operator= (const VSLaserData&); }; }; #endif // VSLASERDATA_HPP
34.767677
79
0.601249
sfegan
b16dfa4c3eda784ca4228a393b0a8fcc1b88b2b3
1,405
cpp
C++
cf/Div2/B/Little Elephant and Magic Square/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Little Elephant and Magic Square/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Little Elephant and Magic Square/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define double long double using namespace std; // Easy O(1) solution, who needs general solutions anyways bool isPrim(int n){ return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19 || n == 23; } signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int counter = 0; vector<int>perm(9); for (int i = 0; i < 9; ++i) { cin >> perm[i]; } for (int i = 1; i < 100001; ++i) { perm[0]=i; perm[4]=perm[0]+perm[1]+perm[2]-perm[3]-perm[5]; perm[8]=perm[0]+perm[1]+perm[2]-perm[6]-perm[7]; int sum=perm[0]+perm[1]+perm[2]; vector<int>sums; for (int j = 0; j < 3; ++j) { sums.push_back(perm[3*j]+perm[3*j+1]+perm[3*j+2]); sums.push_back(perm[j]+perm[j+3]+perm[j+6]); } sums.push_back(perm[0]+perm[4]+perm[8]); sums.push_back(perm[2]+perm[4]+perm[6]); if(sums.size() == count(sums.begin(), sums.end(), sum)){ for (int j = 0; j < 3; ++j) { for (int k = 0; k < 3; ++k) { cout << perm[j*3+k] << " "; } cout << "\n"; } break; } } }
31.222222
103
0.479715
wdjpng
b16f1355b29ff33f505ef7af210fb49a0cc9c35c
842
cpp
C++
ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
26
2020-12-29T23:21:05.000Z
2022-03-23T01:26:02.000Z
ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
90
2020-12-29T18:19:37.000Z
2022-03-21T19:44:15.000Z
ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
26
2020-12-29T18:18:38.000Z
2022-03-10T09:13:46.000Z
#include "SetSkyboxModifier.h" #include "Utils/StringHelper.h" SetSkyboxModifier::SetSkyboxModifier(ZFile* nParent) : ZRoomCommand(nParent) { } void SetSkyboxModifier::ParseRawData() { ZRoomCommand::ParseRawData(); disableSky = parent->GetRawData().at(rawDataIndex + 0x04); disableSunMoon = parent->GetRawData().at(rawDataIndex + 0x05); } std::string SetSkyboxModifier::GetBodySourceCode() const { std::string sky = StringHelper::BoolStr(disableSky); std::string soonMoon = StringHelper::BoolStr(disableSunMoon); return StringHelper::Sprintf("SCENE_CMD_SKYBOX_DISABLES(%s, %s)", sky.c_str(), soonMoon.c_str()); } std::string SetSkyboxModifier::GetCommandCName() const { return "SCmdSkyboxDisables"; } RoomCommand SetSkyboxModifier::GetRoomCommand() const { return RoomCommand::SetSkyboxModifier; }
25.515152
79
0.744656
Dragorn421
b16f4f0b985634ed899cd6a9df085fd22dc96da3
1,431
hpp
C++
inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/include/lpt_ngraph_functions/common/constant.hpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/include/lpt_ngraph_functions/common/constant.hpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
21
2021-02-03T22:41:30.000Z
2022-02-21T13:04:48.000Z
inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/include/lpt_ngraph_functions/common/constant.hpp
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
1
2021-07-28T17:30:46.000Z
2021-07-28T17:30:46.000Z
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ostream> #include <string> #include <vector> #include <ngraph/ngraph.hpp> namespace ngraph { namespace builder { namespace subgraph { class Constant { public: Constant(); Constant(const float value); Constant(const std::vector<float>& values); Constant(const std::vector<float>& values, const ngraph::element::Type outPrecision); Constant(const std::vector<float>& values, const ngraph::element::Type outPrecision, const ngraph::Shape& shape); bool empty() const noexcept; std::vector<float> values; ngraph::element::Type outPrecision; ngraph::Shape shape; bool shapeIsDefined; private: bool isEmpty; }; inline std::ostream& operator<<(std::ostream& out, const Constant& constant) { auto toStream = [](const std::vector<float>& values) -> std::string { std::stringstream os; os << "{"; for (size_t i = 0; i < values.size(); ++i) { const float& value = values[i]; if (i > 0) { os << value; } else { os << ", " << value; } } os << "}"; return os.str(); }; return out << "_" << toStream(constant.values) << "_" << constant.outPrecision << "_" << constant.shape; } } // namespace subgraph } // namespace builder } // namespace ngraph
25.553571
117
0.599581
Andruxin52rus
b17845c7fc4a3f7f6035de3083c222f3fa14751a
3,017
hxx
C++
main/autodoc/source/inc/estack.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/autodoc/source/inc/estack.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/autodoc/source/inc/estack.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 ARY_ESTACK_HXX #define ARY_ESTACK_HXX // USED SERVICES // BASE CLASSES #include <slist> // COMPONENTS // PARAMETERS template <class ELEM> class EStack : private std::slist<ELEM> { private: typedef std::slist<ELEM> base; const base & Base() const { return *this; } base & Base() { return *this; } public: typedef ELEM value_type; typedef typename std::slist<ELEM>::size_type size_type; // LIFECYCLE EStack() {} EStack( const EStack & i_rStack ) : base( (const base &)(i_rStack) ) {} ~EStack() {} // OPERATORS EStack & operator=( const EStack & i_rStack ) { base::operator=( i_rStack.Base() ); return *this; } bool operator==( const EStack<ELEM> & i_r2 ) const { return std::operator==( Base(), this->i_rStack.Base() ); } bool operator<( const EStack<ELEM> & i_r2 ) const { return std::operator<( Base(), this->i_rStack.Base() ); } // OPERATIONS void push( const value_type & i_rElem ) { base::push_front(i_rElem); } void pop() { base::pop_front(); } void erase_all() { while (NOT empty()) pop(); } // INQUIRY const value_type & top() const { return base::front(); } bool empty() const { return base::empty(); } // ACCESS value_type & top() { return base::front(); } }; // IMPLEMENTATION #endif
33.522222
108
0.471661
Grosskopf
b17ac79da653ac0337fc3a95bed02edb21ed4715
1,078
hpp
C++
Sources/ECS/Tools/Color.hpp
n8vm/InteractiveComputerGraphics
022d1b7b5ca81846bf5f310b30fde9beda54ff22
[ "MIT" ]
null
null
null
Sources/ECS/Tools/Color.hpp
n8vm/InteractiveComputerGraphics
022d1b7b5ca81846bf5f310b30fde9beda54ff22
[ "MIT" ]
null
null
null
Sources/ECS/Tools/Color.hpp
n8vm/InteractiveComputerGraphics
022d1b7b5ca81846bf5f310b30fde9beda54ff22
[ "MIT" ]
1
2019-01-29T10:44:58.000Z
2019-01-29T10:44:58.000Z
#pragma once #include <glm/glm.hpp> namespace Colors { inline glm::vec3 hsvToRgb(glm::vec3 hsv) { glm::vec3 rgb; int i = (int)floorf(hsv[0] * 6.0f); float f = hsv[0] * 6 - i; float p = hsv[2] * (1 - hsv[1]); float q = hsv[2] * (1 - f * hsv[1]); float t = hsv[2] * (1 - (1 - f) * hsv[1]); switch (i % 6) { case 0: rgb[0] = hsv[2], rgb[1] = t, rgb[2] = p; break; case 1: rgb[0] = q, rgb[1] = hsv[2], rgb[2] = p; break; case 2: rgb[0] = p, rgb[1] = hsv[2], rgb[2] = t; break; case 3: rgb[0] = p, rgb[1] = q, rgb[2] = hsv[2]; break; case 4: rgb[0] = t, rgb[1] = p, rgb[2] = hsv[2]; break; case 5: rgb[0] = hsv[2], rgb[1] = p, rgb[2] = q; break; } return rgb; } static inline glm::vec4 black = glm::vec4(0.0, 0.0, 0.0, 1.0); static inline glm::vec4 white = glm::vec4(1.0, 1.0, 1.0, 1.0); static inline glm::vec4 darkGrey = glm::vec4(.05, .05, .05, 1.0); static inline glm::vec4 red = glm::vec4(1.0, 0.0, 0.0, 1.0); static inline glm::vec4 green = glm::vec4(0.0, 1.0, 0.0, 1.0); static inline glm::vec4 blue = glm::vec4(0.0, 0.0, 1.0, 1.0); }
34.774194
66
0.538961
n8vm
b17b6df61d569fbbc8c492038015124942f98545
1,368
cpp
C++
Codeforces 412E.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 412E.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 412E.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool isLetter(char l){ return (l>='a'&&l<='z') || (l>='A'&&l<='Z'); } int main(){ string input; cin >> input; long long ans = 0; for(int i = 0; i < input.size(); i++){ if(input[i] == '@'){ long long before = 0, after = 0; for(int j = i - 1; j >= 0; j--){ if(input[j] == '@' || input[j] == '.') break; if(isLetter(input[j])) before++; } for(int j = i + 1; j < input.size(); j++){ if(input[j] == '@' || input[j] == '_'){ i = j - 1; break; } if(input[j] == '.'){ if(j == i + 1) break; for(int k = j + 1; k < input.size(); k++){ if(!isLetter(input[k])) { i = k - 1; break; } i = k - 1; after++; } break; } } /* Multiplicar para obtener las multiples parejas (mini emails) que se forman con esos caracteres consecutivos. */ ans+=before*after; } } cout << ans << endl; return 0; }
29.106383
110
0.324561
Jvillegasd
b17fd74666d6aed009e12f75c955ea10bebe8e65
4,161
cpp
C++
float4d.cpp
shtty/cppcnn
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
[ "MIT" ]
6
2017-08-31T23:25:06.000Z
2019-09-30T06:39:33.000Z
float4d.cpp
shtty/cppcnn
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
[ "MIT" ]
null
null
null
float4d.cpp
shtty/cppcnn
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
[ "MIT" ]
1
2018-12-05T07:09:38.000Z
2018-12-05T07:09:38.000Z
//////////////////////////////////////////////////////////////////////////////////// //// This code is written by Ho Yub Jung //// //////////////////////////////////////////////////////////////////////////////////// #include "float4d.h" std::mt19937 float4d::n_random_seed = std::mt19937(0); void float4d::set(float min, float max, float cmin, float cmax, float multi, float add) { float4d r; r.resize(n_size); if (cmin >= cmax) { cmax = *max_element(p_v.begin(), p_v.end()); cmin = *min_element(p_v.begin(), p_v.end()); } for (int n = 0; n < n_size.n; n++) { for (int c = 0; c < n_size.c; c++) { for (int h = 0; h < n_size.h; h++) { for (int w = 0; w < n_size.w; w++) { float v = this->operator()(n, c, h, w); r(n, c, h, w) = ((v / (cmax - cmin))*(max - min) + min)*multi + add; } } } } *this = r; } void float4d::set(string init_method, std::mt19937 &rng) { if (init_method == "xavier" || init_method == "Xavier") { ////http://deepdish.io/2015/02/24/network-initialization/ //// X.Glorot and Y.Bengio, “Understanding the difficulty of training deep feedforward neural networks, ” in International conference on artificial intelligence and statistics, 2010, pp. 249–256. //// Xavier initialization float d = sqrt(12 / double(chw())) / 2; float max = d; float min = -d; set(min, max,rng); } else if (init_method == "pass") { set("xavier"); int ch = n_size.h / 2; int cw = n_size.w / 2; set(0, 0); this->operator()(0, 0, ch, cw) = 1; } } void float4d::set_borders(int border_width, float border_value) { for (int n = 0; n < n_size.n; n++) { for (int c = 0; c < n_size.c; c++) { for (int h = 0; h < n_size.h; h++) { for (int w = 0; w < n_size.w; w++) { if (h < border_width || h >= n_size.h - border_width || w < border_width || w >= n_size.w - border_width) { this->operator()(n, c, h, w) = border_value; } } } } } } void float4d::print(bool print_values) { cout << "size_NCHW " << n_size.n << " " << n_size.c << " " << n_size.h << " " << n_size.w << endl; if (print_values) { for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x cout << setw(4) << at(ps, pc, py, px) << " "; //if (at(ps, pc, py, px) >= 0) { cout << " "; } } cout << endl; } cout << endl; } } } } void float4d::rotate(int cy, int cx, int angle_degree, float out_bound_value) { float cosangle = std::cos(float(-angle_degree * PI / 180.0)); float sinangle = std::sin(float(-angle_degree * PI / 180.0)); float4d r; r.resize(this->size()); r.set(out_bound_value); for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x float y, x, ry, rx; y = cy - py; x = px - cx; rx = cosangle*x - sinangle*y; ry = sinangle*x + cosangle*y; int rpy, rpx; rpy = int(cy - ry + 0.5f); rpx = int(rx + cx + 0.5f); if (rpy >= 0 && rpy < n_size.h && rpx >= 0 && rpx < n_size.w) { r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, rpy, rpx)]; } } } } } this->p_v = r.p_v; } void float4d::translate(int th, int tw, float out_bound_value ) { float4d r; r.resize(this->size()); r.set(out_bound_value); for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x int ny, nx; ny = py + th; nx = px + tw; if (ny >= 0 && nx >= 0 && ny < n_size.h && nx < n_size.w) { r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, ny, nx)]; } } } } } this->p_v = r.p_v; }
33.02381
198
0.495554
shtty
b17fd7823ea89d912ffaf350ebd8b7e5092e959e
6,029
cpp
C++
src/Leddar/LdBoolProperty.cpp
deucedrone/LeddarSDK
c1deb6621e8ad845341e0185763c4a7706ecb788
[ "BSD-3-Clause" ]
null
null
null
src/Leddar/LdBoolProperty.cpp
deucedrone/LeddarSDK
c1deb6621e8ad845341e0185763c4a7706ecb788
[ "BSD-3-Clause" ]
null
null
null
src/Leddar/LdBoolProperty.cpp
deucedrone/LeddarSDK
c1deb6621e8ad845341e0185763c4a7706ecb788
[ "BSD-3-Clause" ]
1
2020-06-01T17:40:08.000Z
2020-06-01T17:40:08.000Z
// ***************************************************************************** // Module..: Leddar // /// \file LdBoolProperty.cpp /// /// \brief Definition of LdBoolProperty class. /// /// \author Patrick Boulay /// /// \since January 2016 // // Copyright (c) 2016 LeddarTech Inc. All rights reserved. // ***************************************************************************** #include "LdBoolProperty.h" #include "LtStringUtils.h" #include "LtScope.h" #include <string> // ***************************************************************************** // Function: LdBoolProperty::LdBoolProperty // /// \brief Constructor. /// /// \param aCategory See LdProperty. /// \param aFeatures See LdProperty. /// \param aId See LdProperty. /// \param aDeviceId See LdProperty. /// \param aDescription See LdProperty. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** LeddarCore::LdBoolProperty::LdBoolProperty( LdProperty::eCategories aCategory, uint32_t aFeatures, uint32_t aId, uint16_t aDeviceId, const std::string &aDescription ) : LdProperty( LdProperty::TYPE_BOOL, aCategory, aFeatures, aId, aDeviceId, sizeof( bool ), sizeof( bool ), aDescription ) { } // ***************************************************************************** // Function: LdBoolProperty::SetValue // /// \brief Change the value at the given index. /// /// \param aIndex Index in array of value to change. /// \param aValue New value to write. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** void LeddarCore::LdBoolProperty::SetValue( size_t aIndex, bool aValue ) { CanEdit(); // Initialize the count to 1 on the fist SetValue if not done before. if( Count() == 0 && aIndex == 0 ) { SetCount( 1 ); } if( aIndex >= Count() ) { throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) ); } bool *lValues = reinterpret_cast<bool *>( Storage() ); if( !IsInitialized() || lValues[ aIndex ] != aValue ) { SetInitialized( true ); lValues[ aIndex ] = aValue; EmitSignal( LdObject::VALUE_CHANGED ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue ) /// /// \brief Force value /// /// \param aIndex Index in array of value to change. /// \param aValue New value to write. /// /// \author David Levy /// \date March 2019 //////////////////////////////////////////////////////////////////////////////////////////////////// void LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue ) { LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true ); mCheckEditable = false; SetValue( aIndex, aValue ); } // ***************************************************************************** // Function: LdBoolProperty::GetStringValue // /// \brief Display the value in string format /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** std::string LeddarCore::LdBoolProperty::GetStringValue( size_t aIndex ) const { return ( Value( aIndex ) == true ? "true" : "false" ); } // ***************************************************************************** // Function: LdBoolProperty::SetStringValue // /// \brief Property writer for the value as text. Possible value: true and false (lower case) /// /// \param aIndex Index of value to write. /// \param aValue The new value. /// /// \exception std::invalid_argument If the string is not valid. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** void LeddarCore::LdBoolProperty::SetStringValue( size_t aIndex, const std::string &aValue ) { bool lNewValue = false; if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "true" ) { lNewValue = true; } else if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "false" ) { lNewValue = false; } else { throw( std::invalid_argument( "Invalid string value (use \"true\" or \"false\"." ) ); } SetValue( aIndex, lNewValue ); return; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue ) /// /// \brief Force the value /// /// \param aIndex Index of value to write. /// \param aValue The new value. /// /// \author David Levy /// \date March 2019 //////////////////////////////////////////////////////////////////////////////////////////////////// void LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue ) { LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true ); mCheckEditable = false; SetStringValue( aIndex, aValue ); } // ***************************************************************************** // Function: LdBoolProperty::Value // /// \brief Return the property value /// /// \param aIndex Index of value. /// /// \exception std::out_of_range Value out of range ( from std::stoi ) /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** bool LeddarCore::LdBoolProperty::Value( size_t aIndex ) const { VerifyInitialization(); if( aIndex >= Count() ) { throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) ); } return reinterpret_cast<const bool *>( CStorage() )[ aIndex ]; }
30.296482
168
0.502405
deucedrone
b181efefb66df7109b9f875b56e654ff92a672cd
4,659
cpp
C++
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include "gtest/gtest.h" #include "Units/Runtime/DynamicQuantity.h" #include "Units/Runtime/Unit.h" #include "Units/Length.h" #include "Units/Mass.h" #include "Units/ForAllDimensions.h" #include "Units/Reflection/ReflectQuantities.h" #include "Reflection/Classes/Class.h" #include "Reflection/TypeLibraries/TypeLibraryFactory.h" #include "Reflection/Objects/Object.h" #include "Units/Reflection/Details/ReflectLength.h" using namespace DNVS::MoFa::Reflection::Classes; using namespace DNVS::MoFa::Reflection::Objects; using namespace DNVS::MoFa::Reflection::TypeLibraries; using namespace DNVS::MoFa::Reflection::TypeConversions; using namespace DNVS::MoFa::Reflection; using namespace DNVS::MoFa::Units; using namespace DNVS::MoFa::Units::Runtime; struct ConverterFromDynamicQuantityToStaticQuantity { public: ConverterFromDynamicQuantityToStaticQuantity(const Variants::Variant& dynamicQuantity) : m_dynamicQuantity(Variants::VariantService::Unreflect<DynamicQuantity>(dynamicQuantity)) , m_staticQuantity(dynamicQuantity) { } template<typename DimensionT> void Apply() { typedef Quantity<DimensionT> StaticQuantity; if(DynamicDimension(DimensionT()) == m_dynamicQuantity.GetSimplifiedUnit().GetDimension()) m_staticQuantity = Variants::VariantService::Reflect<StaticQuantity>(StaticQuantity(m_dynamicQuantity.GetNeutralValue())); } Variants::Variant GetStaticQuantity() const { return m_staticQuantity; } private: Variants::Variant m_staticQuantity; DynamicQuantity m_dynamicQuantity; }; struct FallbackUnitConverter : public IConversion { virtual Variants::Variant Convert(const Variants::Variant& other) { ConverterFromDynamicQuantityToStaticQuantity converter(other); ForAllUsedDimensions(converter); return converter.GetStaticQuantity(); } virtual void IntrusiveConvert( Variants::Variant& variable ) { ConverterFromDynamicQuantityToStaticQuantity converter(variable); ForAllUsedDimensions(converter); variable = converter.GetStaticQuantity(); } }; TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_AddLengths) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, _m)); Object b(typeLibrary, DynamicQuantity(4.2, _m)); Object c = a + b; EXPECT_EQ(DynamicQuantity(5.2 + 4.2, _m), c.As<DynamicQuantity>()); } TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_ConvertToLength) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, _m)); Object b(typeLibrary, DynamicQuantity(4.2, _m)); Object c = a + b; EXPECT_EQ(Length(5.2 + 4.2), c.As<Length>()); EXPECT_THROW(c.As<Mass>(), std::runtime_error); } TEST(DynamicReflectQuantityTests, TestInvalidConversionFromDynamicQuantity_NoCrash) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(4, 4, 4, 4, 4)))); EXPECT_NO_FATAL_FAILURE( EXPECT_THROW(a.As<Length>(), std::runtime_error) ); } TEST(DynamicReflectQuantityTests, TestConversionOfNonDimensionalToDouble) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(0, 0, 0, 0, 0)))); EXPECT_DOUBLE_EQ(5.2, a.As<double>()); }
38.188525
134
0.75059
dnv-opensource
b1837ebd6ad25f4a9ddd8e856c43d7c54184fd20
16,075
cpp
C++
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
1
2019-05-30T03:42:22.000Z
2019-05-30T03:42:22.000Z
/* Copyright (c) 2010-2015, Delft University of Technology * 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 Delft University of Technology 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. * * Changelog * YYMMDD Author Comment * 140106 J. Geul File creatad, copied from unitTestOrbitalStateDerivativeModel. * * * References * * Notes: * Test tolerance was set at 5.0e-15 instead of epsilon due to rounding errors in Eigen types * with entries over a number of orders of magnitude, presumably causing the observed larger * than epsilon relative differences between expected and computed values. * */ #define BOOST_TEST_MAIN #include <boost/assign/list_of.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include "Tudat/Basics/testMacros.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testAccelerationModels.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testBody.h" #include "Tudat/Astrodynamics/StateDerivativeModels/orbitalStateDerivativeModel.h" #include "Tudat/Mathematics/BasicMathematics/linearAlgebraTypes.h" namespace tudat { namespace unit_tests { using boost::assign::list_of; using basic_mathematics::Vector6d; //! Rotate vector over arbitrary angles. /*! * This function computes a composite rotation of the input vector over arbitrary angles about the * unit x-, y-, and z-axes. This is used in conjunction with rotateOverOtherArbitraryAngles() to * test the frame transformation features provided by the orbitalStateDerivativeModel. * \param inputVector Input vector before rotation. * \return Rotated vector. * \sa orbitalStateDerivativeModel, rotateOverOtherArbitraryAngles(). */ Eigen::Vector3d rotateOverArbitraryAngles( const Eigen::Vector3d& inputVector ) { // Declare rotation matrix. Eigen::Matrix3d rotationMatrix; rotationMatrix = Eigen::AngleAxisd( -1.15, Eigen::Vector3d::UnitX( ) ) * Eigen::AngleAxisd( 0.23, Eigen::Vector3d::UnitY( ) ) * Eigen::AngleAxisd( 2.56, Eigen::Vector3d::UnitZ( ) ); // Compute rotated matrix and return. return rotationMatrix * inputVector; } //! Rotate vector over other arbitrary angles. /*! * This function computes another composite rotation of the input vector over different arbitrary * angles (compared to the rotateOverArbitraryAngles() function) about the unit x-, y-, and z-axes. * This is used in conjunction with rotateOverArbitraryAngles() to test the frame transformation * features provided by the OrbitalStateDerivativeModel. * \param inputVector Input vector before rotation. * \return Rotated vector. * \sa orbitalStateDerivativeModel, rotateOverArbitraryAngles(). */ Eigen::Vector3d rotateOverOtherArbitraryAngles( const Eigen::Vector3d& inputVector ) { // Declare rotation matrix. Eigen::Matrix3d rotationMatrix; rotationMatrix = Eigen::AngleAxisd( 0.24, Eigen::Vector3d::UnitX( ) ) * Eigen::AngleAxisd( -1.55, Eigen::Vector3d::UnitY( ) ) * Eigen::AngleAxisd( 2.13, Eigen::Vector3d::UnitZ( ) ); // Compute rotated matrix and return. return rotationMatrix * inputVector; } //! Perform Mapping from Acceleration to Cartesian State Derivative /*! * This function is implemented in order to not use any external * mapping functions. The function was build completely from pieces of * code of the old cartesianStateDerivativeModel in order to use * completely different, but also verified methods of constructing a * stateDerivative from the total accelerations. * \param currentState The current state. * \param accelerations Total sum of accelerations. * \return stateDerivative */ Vector6d mapCartesian( const Vector6d& cartesianState, const Eigen::Vector3d& acceleration ) { // {{{ Snippets from cartesianStateDerivativeModel.h typedef Vector6d CartesianStateDerivativeType; // Declare Cartesian state derivative size. unsigned int stateDerivativeSize = cartesianState.rows( ); // Declare Cartesian state derivative of the same size as Cartesian state. CartesianStateDerivativeType cartesianStateDerivative = CartesianStateDerivativeType::Zero( stateDerivativeSize ); // Set derivative of position components to current Cartesian velocity. cartesianStateDerivative.segment( 0, stateDerivativeSize / 2 ) = cartesianState.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 ); // Add transformed acceleration to state derivative. cartesianStateDerivative.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 ) += acceleration; // Return assembled state derivative. return cartesianStateDerivative; // }}} End Snippets from cartesianStateDerivativeModel.h } BOOST_AUTO_TEST_SUITE( test_orbital_state_derivative_model ) //! Test whether 6D Cartesian state derivative model works correctly without frame transformations. BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithoutFrameTransformations ) { using basic_astrodynamics::AccelerationModel3dPointer; using state_derivative_models::OrbitalStateDerivativeModelType; using state_derivative_models::OrbitalStateDerivativeModelPointer; // Shortcuts. typedef TestBody< 3, double > TestBody3d; typedef boost::shared_ptr< TestBody3d > TestBody3dPointer; typedef DerivedAccelerationModel< > DerivedAccelerationModel3d; typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d; // Set current state. const Vector6d currentState = ( basic_mathematics::Vector6d( ) << Eigen::Vector3d( -1.1, 2.2, -3.3 ), Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( ); // Set current time. const double currentTime = 5.6; // Set current position. const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 ); // Set current velocity. const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 ); // Create body with zombie time and state. TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 ); // Create acceleration models. AccelerationModel3dPointer firstAccelerationModel3d = boost::make_shared< DerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); AccelerationModel3dPointer secondAccelerationModel3d = boost::make_shared< AnotherDerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentVelocity, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); // Create list of acceleration models to provide to state derivative model. OrbitalStateDerivativeModelType::AccelerationModelPointerVector listOfAccelerations = list_of( firstAccelerationModel3d )( secondAccelerationModel3d ); // Declare Cartesian state derivative model. OrbitalStateDerivativeModelPointer cartesianStateDerivativeModel = boost::make_shared< OrbitalStateDerivativeModelType >( listOfAccelerations, boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), boost::bind( &mapCartesian, _1, _2 ) ); // // Set Earth gravitational parameter [m^3 s^-2]. // const double earthGravitationalParameter = 3.986004415e14; // // Declare Keplerian state derivative model. // OrbitalStateDerivativeModelPointer keplerianStateDerivativeModel // = boost::make_shared< OrbitalStateDerivativeModelType >( // listOfAccelerations, // boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), // boost::bind( &stateDerivativeMapKeplerian, _1, _2, // earthGravitationalParameter ) ); // // Declare Modified Equinoctial state derivative model. // OrbitalStateDerivativeModelPointer modifiedEquinoctialStateDerivativeModel // = boost::make_shared< OrbitalStateDerivativeModelType >( // listOfAccelerations, // boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), // boost::bind( &stateDerivativeMapModifiedEquinoctial, _1, _2, // earthGravitationalParameter ) ); // Set expected accelerations. const Eigen::Vector3d expectedAccelerationFirstModel = currentPosition / ( currentTime * currentTime ); const Eigen::Vector3d expectedAccelerationSecondModel = 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime ) + currentVelocity / currentTime; // Set expected (cumulative) Cartesian state derivative. const Vector6d expectedCartesianStateDerivative = ( basic_mathematics::Vector6d( ) << currentVelocity, expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( ); // Compute Cartesian state derivative. const Vector6d computedCartesianStateDerivative = cartesianStateDerivativeModel->computeStateDerivative( currentTime, currentState ); // Check that computed Cartesian state derivative matches expected values. TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative ) BOOST_CHECK_SMALL( computedCartesianStateDerivative.coeff( row, col ) - expectedCartesianStateDerivative.coeff( row, col ), 5.0e-15 ); } //! Test whether 6D Cartesian state derivative model works correctly with frame transformations. BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithFrameTransformations ) { using basic_astrodynamics::AccelerationModel3dPointer; using state_derivative_models::OrbitalStateDerivativeModelType; using state_derivative_models::OrbitalStateDerivativeModelPointer; // Shortcuts. typedef TestBody< 3, double > TestBody3d; typedef boost::shared_ptr< TestBody3d > TestBody3dPointer; typedef DerivedAccelerationModel< > DerivedAccelerationModel3d; typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d; // Set current state. const Vector6d currentState = ( basic_mathematics::Vector6d( ) << Eigen::Vector3d( -1.1, 2.2, -3.3 ), Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( ); // Set current time. const double currentTime = 5.6; // Set current position. const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 ); // Set current velocity. const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 ); // Create body with zombie time and state. TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 ); // Create acceleration models. AccelerationModel3dPointer firstAccelerationModel3d = boost::make_shared< DerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); AccelerationModel3dPointer secondAccelerationModel3d = boost::make_shared< AnotherDerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentVelocity, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); // Create list of reference frame transformations for first acceleration model. // NB: The order of this list is VERY important! The order of transformations executed is from // the beginning of the vector to the end sequentially. OrbitalStateDerivativeModelType::ListOfReferenceFrameTransformations listOfFrameTransformations = list_of( &rotateOverArbitraryAngles )( &rotateOverOtherArbitraryAngles ); // Create list to pass to constructor of acceleration model/frame transformation list pairs. // In this case, there are two frame transformations executed for the first acceleration model, // and none for the second. OrbitalStateDerivativeModelType::ListOfAccelerationFrameTransformationPairs listOfAccelerationFrameTransformations = list_of( std::make_pair( firstAccelerationModel3d, listOfFrameTransformations ) ) ( std::make_pair( secondAccelerationModel3d, OrbitalStateDerivativeModelType:: ListOfReferenceFrameTransformations( ) ) ); // Declare Cartesian state derivative model. OrbitalStateDerivativeModelPointer stateDerivativeModel = boost::make_shared< OrbitalStateDerivativeModelType >( listOfAccelerationFrameTransformations, boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), boost::bind( &mapCartesian, _1, _2 ) ); // Set expected accelerations. const Eigen::Vector3d expectedAccelerationFirstModel = rotateOverOtherArbitraryAngles( rotateOverArbitraryAngles( currentPosition / ( currentTime * currentTime ) ) ); const Eigen::Vector3d expectedAccelerationSecondModel = 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime ) + currentVelocity / currentTime; // Set expected (cumulative) Cartesian state derivative. const Vector6d expectedCartesianStateDerivative = ( basic_mathematics::Vector6d( ) << currentVelocity, expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( ); // Compute Cartesian state derivative. const Vector6d computedCartesianStateDerivative = stateDerivativeModel->computeStateDerivative( currentTime, currentState ); // Check that computed Cartesian state derivative matches expected values. TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative ) BOOST_CHECK_CLOSE_FRACTION( computedCartesianStateDerivative.coeff( row, col ), expectedCartesianStateDerivative.coeff( row, col ), 5.0e-15 ); } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
47.418879
99
0.71689
JPelamatti
b183cc19212e409463dc908e2e931782bbd787ca
2,702
cpp
C++
hphp/runtime/ext/vsdebug/logging.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/vsdebug/logging.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/vsdebug/logging.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2017-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <time.h> #include <string> #include "hphp/runtime/ext/vsdebug/logging.h" namespace HPHP { namespace VSDEBUG { // Linkage for the log file pointer, this is a singleton for the extension. FILE* VSDebugLogger::s_logFile {nullptr}; void VSDebugLogger::InitializeLogging(std::string& logFilePath) { if (logFilePath.empty()) { return; } // This is only expected to be invoked once, when the extension is loaded. assert(s_logFile == nullptr); // TODO: (Ericblue) Add logic for max file size, log file rotation, etc. const char* path = logFilePath.c_str(); s_logFile = fopen(path, "a"); if (s_logFile == nullptr) { return; } // Start with a visual delimiter so it's easy to see where // the session started. Log(VSDebugLogger::LogLevelInfo, "-------------------------------"); } void VSDebugLogger::FinalizeLogging() { if (s_logFile == nullptr) { return; } Log(VSDebugLogger::LogLevelInfo, "VSDebugExtension shutting down."); Log(VSDebugLogger::LogLevelInfo, "-------------------------------"); LogFlush(); fclose(s_logFile); s_logFile = nullptr; } void VSDebugLogger::Log(const char* level, const char* fmt, ...) { if (s_logFile == nullptr) { return; } time_t t = time(NULL); struct tm tm = *localtime(&t); fprintf(s_logFile, "[%d-%d-%d %d:%d:%d]", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec ); fprintf(s_logFile, "[%s]\t", level); va_list args; va_start(args, fmt); vfprintf(s_logFile, fmt, args); va_end(args); fprintf(s_logFile, "\n"); } void VSDebugLogger::LogFlush() { if (s_logFile == nullptr) { return; } fflush(s_logFile); } } }
28.145833
76
0.53849
ActindoForks
b1847bac7c32eed075864bf7869b823c5c8bc277
7,392
cc
C++
ocr-pfst/ocrofst-impl.cc
michaelyin/ocropus-git
b2673354bbcfba38f7a807708f64cd33aaeb0f6d
[ "Apache-2.0" ]
3
2016-06-24T10:48:36.000Z
2020-07-04T16:00:41.000Z
ocr-pfst/ocrofst-impl.cc
michaelyin/ocropus-git
b2673354bbcfba38f7a807708f64cd33aaeb0f6d
[ "Apache-2.0" ]
null
null
null
ocr-pfst/ocrofst-impl.cc
michaelyin/ocropus-git
b2673354bbcfba38f7a807708f64cd33aaeb0f6d
[ "Apache-2.0" ]
11
2016-06-24T09:35:57.000Z
2020-12-01T21:26:43.000Z
// Copyright 2008-2009 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz // or its licensors, as applicable. // // You may not use this file except under the terms of the accompanying 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. // // Project: // File: ocrofst-impl.h // Purpose: OcroFST class implementation // Responsible: mezhirov // Reviewer: // Primary Repository: // Web Sites: www.iupr.org, www.dfki.de, www.ocropus.org #include "ocr-pfst.h" #include "fst-io.h" #include "a-star.h" namespace ocropus { struct OcroFSTImpl : OcroFST { objlist<intarray> m_targets; objlist<intarray> m_inputs; objlist<intarray> m_outputs; objlist<floatarray> m_costs; floatarray m_heuristics; floatarray accept_costs; int start; virtual intarray &targets(int vertex) { return m_targets[vertex]; } virtual intarray &inputs(int vertex) { return m_inputs[vertex]; } virtual intarray &outputs(int vertex) { return m_outputs[vertex]; } virtual floatarray &costs(int vertex) { return m_costs[vertex]; } virtual float acceptCost(int vertex) { return accept_costs[vertex]; } virtual void setAcceptCost(int vertex, float new_value) { accept_costs[vertex] = new_value; } virtual const char *description() { return "Lattice"; } // reading virtual int nStates() { return accept_costs.length(); } virtual int getStart() { return start; } virtual float getAcceptCost(int node) { return accept_costs[node]; } virtual void arcs(intarray &out_inputs, intarray &out_targets, intarray &out_outputs, floatarray &out_costs, int from) { copy(out_inputs, m_inputs[from]); copy(out_targets, m_targets[from]); copy(out_outputs, m_outputs[from]); copy(out_costs, m_costs[from]); } virtual void clear() { start = 0; m_targets.clear(); m_inputs.clear(); m_outputs.clear(); m_costs.clear(); accept_costs.clear(); } // writing virtual int newState() { accept_costs.push() = INFINITY; m_targets.push(); m_inputs.push(); m_outputs.push(); m_costs.push(); return accept_costs.length() - 1; } virtual void addTransition(int from,int to,int output,float cost,int input) { m_targets[from].push(to); m_outputs[from].push(output); m_inputs[from].push(input); m_costs[from].push(cost); } virtual void rescore(int from,int to,int output,float cost,int input) { intarray &t = m_targets[from]; intarray &i = m_inputs[from]; intarray &o = m_outputs[from]; for(int j = 0; j < t.length(); j++) { if(t[j] == to && i[j] == input && o[j] == output) { m_costs[from][j] = cost; break; } } } virtual void setStart(int node) { start = node; } virtual void setAccept(int node,float cost=0.0) { accept_costs[node] = cost; } virtual int special(const char *s) { return 0; } virtual void bestpath(colib::ustrg &result) { a_star(result, *this); } virtual void save(const char *path) { fst_write(path, *this); } virtual void load(const char *path) { fst_read(*this, path); } private: int flags; void achieve(int flag) { CHECK_ARG(flag == SORTED_BY_INPUT || flag == SORTED_BY_OUTPUT || flag == HAS_HEURISTICS); if(flags & flag) return; if(flag == HAS_HEURISTICS) { a_star_backwards(m_heuristics, *this); return; } for(int node = 0; node < nStates(); node++) { intarray permutation; if(flag == OcroFST::SORTED_BY_INPUT) quicksort(permutation, m_inputs[node]); else quicksort(permutation, m_outputs[node]); permute(m_inputs[node], permutation); permute(m_outputs[node], permutation); permute(m_targets[node], permutation); permute(m_costs[node], permutation); } flags |= flag; } public: virtual void sortByInput() { achieve(SORTED_BY_INPUT); } virtual void sortByOutput() { achieve(SORTED_BY_OUTPUT); } virtual bool hasFlag(int flag) { return flags & flag; } virtual floatarray &heuristics() { return m_heuristics; } virtual void calculateHeuristics() { achieve(HAS_HEURISTICS); } OcroFSTImpl(int max_size=0) : m_targets(max_size), m_inputs(max_size), m_outputs(max_size), m_costs(max_size), accept_costs(max_size), start(0), flags(0) { } virtual void clearFlags() { flags = 0; } }; OcroFST *make_OcroFST() { return new OcroFSTImpl(); }; void scale_fst(OcroFST &fst,float scale) { using namespace narray_ops; if(fabs(scale-1.0)<1e-6) return; for(int i=0;i<fst.nStates();i++) { fst.costs(i) *= scale; float accept = fst.acceptCost(i); if(accept>=0 && accept<1e37) fst.setAcceptCost(i,accept*scale); } } static void make_neg(intarray &a) { for(int i=0;i<a.length();i++) if(a[i]>0&&a[i]<=4) a[i] = -a[i]; } static void make_pos(intarray &a) { for(int i=0;i<a.length();i++) if(a[i]>=-40&&a[i]<0) a[i] = -a[i]; } void make_specials_neg(OcroFST &fst,bool input,bool output) { using namespace narray_ops; for(int i=0;i<fst.nStates();i++) { if(input) make_neg(fst.inputs(i)); if(output) make_neg(fst.outputs(i)); } } void make_specials_pos(OcroFST &fst,bool input,bool output) { using namespace narray_ops; for(int i=0;i<fst.nStates();i++) { if(input) make_pos(fst.inputs(i)); if(output) make_pos(fst.outputs(i)); } } }
29.333333
85
0.528815
michaelyin
b18b765b66829e8bd0911bbaaad839d8a9f02ed6
26,273
hpp
C++
library/src/blas3/Tensile/gemm.hpp
pruthvistony/rocBLAS
9463526235e38f505caeaf29cf41bac22c1ab238
[ "MIT" ]
null
null
null
library/src/blas3/Tensile/gemm.hpp
pruthvistony/rocBLAS
9463526235e38f505caeaf29cf41bac22c1ab238
[ "MIT" ]
null
null
null
library/src/blas3/Tensile/gemm.hpp
pruthvistony/rocBLAS
9463526235e38f505caeaf29cf41bac22c1ab238
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #pragma once #ifndef _GEMM_HOST_HPP_ #define _GEMM_HOST_HPP_ #include "handle.hpp" #ifdef USE_TENSILE_HOST #include "tensile_host.hpp" #else // USE_TENSILE_HOST /******************************************************************************* * Helper enumeration over different transpose combinations ******************************************************************************/ typedef enum { // First letter refers to A, second letter refers to B NN, NT, TN, TT, NC, CN, TC, CT, CC, } transpose_mode; constexpr transpose_mode GetTransposeMode(rocblas_operation trans_a, rocblas_operation trans_b) { if(trans_a == rocblas_operation_none) { if(trans_b == rocblas_operation_none) return NN; if(trans_b == rocblas_operation_conjugate_transpose) return NC; return NT; } else if(trans_a == rocblas_operation_conjugate_transpose) { if(trans_b == rocblas_operation_none) return CN; if(trans_b == rocblas_operation_conjugate_transpose) return CC; return CT; } else { if(trans_b == rocblas_operation_none) return TN; if(trans_b == rocblas_operation_conjugate_transpose) return TC; return TT; } } #include "Tensile.h" /******************************************************************************* * Tensile Helper Function call ******************************************************************************/ template <typename T> rocblas_status tensile_helper(const T& alpha_h, const T& beta_h, const T* A, const T* B, T* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle); #define TENSILE_ARGS(T) \ (T*)C, (const T*)C, (const T*)A, (const T*)B, *((const T*)&alpha_h), *((const T*)&beta_h), \ strideC1, strideC2, strideC1, strideC2, strideA1, strideA2, strideB1, strideB2, sizeI, \ sizeJ, sizeK, sizeL, handle->rocblas_stream, 0, nullptr, nullptr, nullptr template <> inline rocblas_status tensile_helper(const rocblas_half& alpha_h, const rocblas_half& beta_h, const rocblas_half* A, const rocblas_half* B, rocblas_half* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_HB(TENSILE_ARGS(rocblas_half)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_HB(TENSILE_ARGS(rocblas_half)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_HB(TENSILE_ARGS(rocblas_half)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_HB(TENSILE_ARGS(rocblas_half)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const float& alpha_h, const float& beta_h, const float* A, const float* B, float* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_SB(TENSILE_ARGS(float)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_SB(TENSILE_ARGS(float)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_SB(TENSILE_ARGS(float)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_SB(TENSILE_ARGS(float)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const double& alpha_h, const double& beta_h, const double* A, const double* B, double* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_DB(TENSILE_ARGS(double)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_DB(TENSILE_ARGS(double)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_DB(TENSILE_ARGS(double)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_DB(TENSILE_ARGS(double)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const rocblas_float_complex& alpha_h, const rocblas_float_complex& beta_h, const rocblas_float_complex* A, const rocblas_float_complex* B, rocblas_float_complex* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { static_assert(std::is_standard_layout<TensileComplexFloat>{}, "TensileComplexFloat is not a standard layout type, and thus is " "incompatible with C."); static_assert(std::is_trivial<TensileComplexFloat>{}, "TensileComplexFloat is not a trivial type, and thus is " "incompatible with C."); static_assert(sizeof(rocblas_float_complex) == sizeof(TensileComplexFloat), "TensileComplexFloat does not match rocblas_float_complex"); hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case NT: status = tensile_Cijk_Ailk_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TN: status = tensile_Cijk_Alik_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TT: status = tensile_Cijk_Alik_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case NC: status = tensile_Cijk_Ailk_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CN: status = tensile_Cijk_AlikC_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TC: status = tensile_Cijk_Alik_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CT: status = tensile_Cijk_AlikC_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CC: status = tensile_Cijk_AlikC_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const rocblas_double_complex& alpha_h, const rocblas_double_complex& beta_h, const rocblas_double_complex* A, const rocblas_double_complex* B, rocblas_double_complex* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { static_assert(std::is_standard_layout<TensileComplexDouble>{}, "TensileComplexDouble is not a standard layout type, and thus is " "incompatible with C."); static_assert(std::is_trivial<TensileComplexDouble>{}, "TensileComplexDouble is not a trivial type, and thus is " "incompatible with C."); static_assert(sizeof(rocblas_double_complex) == sizeof(TensileComplexDouble), "TensileComplexDouble does not match rocblas_double_complex"); hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case NT: status = tensile_Cijk_Ailk_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TN: status = tensile_Cijk_Alik_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TT: status = tensile_Cijk_Alik_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case NC: status = tensile_Cijk_Ailk_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CN: status = tensile_Cijk_AlikC_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TC: status = tensile_Cijk_Alik_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CT: status = tensile_Cijk_AlikC_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CC: status = tensile_Cijk_AlikC_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; } return get_rocblas_status_for_hip_status(status); } #undef TENSILE_ARGS #endif // USE_TENSILE_HOST /********************************************************************************* * Right now Tensile requires alpha and beta to be passed by value on host. * * If in device pointer mode, copy alpha and beta to host. * * If k == 0, we set alpha = 0 instead of copying from device. * * TODO: Make this asynchronous, putting synchronization closer to Tensile call. * *********************************************************************************/ template <typename T, typename Tc> rocblas_status copy_alpha_beta_to_host_if_on_device( rocblas_handle handle, const T*& alpha, const T*& beta, Tc& alpha_h, Tc& beta_h, rocblas_int k) { if(handle->pointer_mode == rocblas_pointer_mode_device) { if(alpha) { if(k == 0) alpha_h = 0; else RETURN_IF_HIP_ERROR(hipMemcpy(&alpha_h, alpha, sizeof(Tc), hipMemcpyDeviceToHost)); alpha = &alpha_h; } if(beta) { RETURN_IF_HIP_ERROR(hipMemcpy(&beta_h, beta, sizeof(Tc), hipMemcpyDeviceToHost)); beta = &beta_h; } } return rocblas_status_success; } /******************************************************************************* * Tensile Function call ******************************************************************************/ template <typename T> inline rocblas_status call_tensile(rocblas_handle handle, const T* alpha, const T* beta, const T* A, const T* B, T* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int ld_c, rocblas_stride stride_c, rocblas_int ld_a, rocblas_stride stride_a, rocblas_int ld_b, rocblas_stride stride_b, rocblas_int m, rocblas_int n, rocblas_int k, rocblas_int batch_count = 1) { #ifdef USE_TENSILE_HOST RocblasContractionProblem<T> problem{handle, trans_a, trans_b, m, n, k, alpha, A, ld_a, stride_a, B, ld_b, stride_b, beta, C, ld_c, stride_c, batch_count}; return runContractionProblem(problem); #else // USE_TENSILE_HOST return tensile_helper(*alpha, *beta, A, B, C, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, batch_count, k, handle); #endif // USE_TENSILE_HOST } /******************************************************************************* * Validate Arguments ******************************************************************************/ template <typename T> inline rocblas_status validateArgs(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const T* alpha, const void* a, rocblas_int ld_a, const void* b, rocblas_int ld_b, const T* beta, const void* c, rocblas_int ld_c, rocblas_int batch_count = 1) { // handle must be valid if(!handle) return rocblas_status_invalid_handle; // sizes must not be negative if(m < 0 || n < 0 || k < 0 || batch_count < 0) return rocblas_status_invalid_size; rocblas_int num_rows_a = trans_a == rocblas_operation_none ? m : k; rocblas_int num_rows_b = trans_b == rocblas_operation_none ? k : n; rocblas_int num_rows_c = m; // leading dimensions must be valid if(num_rows_a > ld_a || num_rows_b > ld_b || num_rows_c > ld_c) return rocblas_status_invalid_size; // quick return 0 is valid in BLAS // Note: k==0 is not a quick return, because C must still be multiplied by beta if(!m || !n || !batch_count) return rocblas_status_success; if(!beta) return rocblas_status_invalid_pointer; if(handle->pointer_mode == rocblas_pointer_mode_host && *beta == 1) { if(!k) return rocblas_status_success; if(!alpha) return rocblas_status_invalid_pointer; if(!*alpha) return rocblas_status_success; } // pointers must be valid if((k && (!a || !b || !alpha)) || !c) return rocblas_status_invalid_pointer; return rocblas_status_continue; } /* * =========================================================================== * template interface * =========================================================================== */ template <bool BATCHED, typename T, typename U, typename V> ROCBLAS_EXPORT_NOINLINE rocblas_status rocblas_gemm_template(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const T* alpha, const U* A, rocblas_int offset_a, rocblas_int ld_a, rocblas_stride stride_a, const U* B, rocblas_int offset_b, rocblas_int ld_b, rocblas_stride stride_b, const T* beta, V* C, rocblas_int offset_c, rocblas_int ld_c, rocblas_stride stride_c, rocblas_int batch_count) { // Early exit. Note: k==0 is not an early exit, since C still needs to be multiplied by beta. if(m == 0 || n == 0 || batch_count == 0) return rocblas_status_success; // Temporarily change the thread's default device ID to the handle's device ID auto saved_device_id = handle->push_device_id(); T alpha_h, beta_h; RETURN_IF_ROCBLAS_ERROR( copy_alpha_beta_to_host_if_on_device(handle, alpha, beta, alpha_h, beta_h, k)); // When beta == 1 and either k == 0 or alpha == 0, the operation is a no-op if(*beta == 1 && (k == 0 || *alpha == 0)) return rocblas_status_success; rocblas_status status = rocblas_status_success; // TODO: Use C++17 constexpr if if(BATCHED) { // We cannot do this with a device array, so array of pointers must be on host for now // Host arrays of device pointers. auto hostA = std::make_unique<T*[]>(batch_count); auto hostB = std::make_unique<T*[]>(batch_count); auto hostC = std::make_unique<T*[]>(batch_count); RETURN_IF_HIP_ERROR( hipMemcpy(&hostA[0], A, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); RETURN_IF_HIP_ERROR( hipMemcpy(&hostB[0], B, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); RETURN_IF_HIP_ERROR( hipMemcpy(&hostC[0], C, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); for(rocblas_int b = 0; b < batch_count; b++) { status = call_tensile(handle, alpha, beta, hostA[b] + offset_a, hostB[b] + offset_b, hostC[b] + offset_c, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, k); if(status != rocblas_status_success) break; } } else { // The (T*) casts are to prevent template deduction errors when BATCHED==true and the A, B, C // pointers are pointers to arrays of pointers. constexpr if(BATCHED) above could avoid this. status = call_tensile(handle, alpha, beta, (T*)A + offset_a, (T*)B + offset_b, (T*)C + offset_c, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, k, batch_count); } return status; } #endif // _GEMM_HOST_HPP_
40.670279
101
0.421954
pruthvistony
b18c4360ea984ec96940403ce311c28af7a61049
12,185
cpp
C++
CC++/WTL/WTL/AppWiz/Files/Templates/1033/Frame.cpp
Peterinor/Coding
3ac4908b3c6ae5df96390332e5452da934d12c3b
[ "MIT" ]
null
null
null
CC++/WTL/WTL/AppWiz/Files/Templates/1033/Frame.cpp
Peterinor/Coding
3ac4908b3c6ae5df96390332e5452da934d12c3b
[ "MIT" ]
null
null
null
CC++/WTL/WTL/AppWiz/Files/Templates/1033/Frame.cpp
Peterinor/Coding
3ac4908b3c6ae5df96390332e5452da934d12c3b
[ "MIT" ]
null
null
null
// [!output WTL_FRAME_FILE].cpp : implmentation of the [!output WTL_FRAME_CLASS] class // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" [!if WTL_USE_RIBBON] #include "Ribbon.h" [!endif] #include "resource.h" #include "aboutdlg.h" [!if WTL_USE_VIEW] #include "[!output WTL_VIEW_FILE].h" [!endif] [!if WTL_APPTYPE_MDI] #include "[!output WTL_CHILD_FRAME_FILE].h" [!endif] #include "[!output WTL_FRAME_FILE].h" BOOL [!output WTL_FRAME_CLASS]::PreTranslateMessage(MSG* pMsg) { [!if WTL_APPTYPE_MDI] if([!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg)) return TRUE; HWND hWnd = MDIGetActive(); if(hWnd != NULL) return (BOOL)::SendMessage(hWnd, WM_FORWARDMSG, 0, (LPARAM)pMsg); return FALSE; [!else] [!if WTL_USE_VIEW] if([!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg)) return TRUE; return m_view.PreTranslateMessage(pMsg); [!else] return [!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg); [!endif] [!endif] } BOOL [!output WTL_FRAME_CLASS]::OnIdle() { [!if WTL_USE_TOOLBAR] UIUpdateToolBar(); [!endif] return FALSE; } LRESULT [!output WTL_FRAME_CLASS]::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { [!if WTL_RIBBON_DUAL_UI] bool bRibbonUI = RunTimeHelper::IsRibbonUIAvailable(); if (bRibbonUI) UIAddMenu(GetMenu(), true); else CMenuHandle(GetMenu()).DeleteMenu(ID_VIEW_RIBBON, MF_BYCOMMAND); [!else] [!if WTL_RIBBON_SINGLE_UI] UIAddMenu(GetMenu(), true); [!endif] [!endif] [!if WTL_USE_RIBBON && !WTL_USE_CMDBAR] m_CmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD); m_CmdBar.AttachMenu(GetMenu()); m_CmdBar.LoadImages(IDR_MAINFRAME); [!endif] [!if WTL_USE_TOOLBAR] [!if WTL_USE_REBAR] [!if WTL_USE_CMDBAR] // create command bar window HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE); // attach menu m_CmdBar.AttachMenu(GetMenu()); // load command bar images m_CmdBar.LoadImages(IDR_MAINFRAME); // remove old menu SetMenu(NULL); [!endif] HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE); CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE); [!if WTL_USE_CMDBAR] AddSimpleReBarBand(hWndCmdBar); AddSimpleReBarBand(hWndToolBar, NULL, TRUE); [!else] AddSimpleReBarBand(hWndToolBar); [!endif] [!else] CreateSimpleToolBar(); [!endif] [!endif] [!if WTL_USE_STATUSBAR] CreateSimpleStatusBar(); [!endif] [!if WTL_APPTYPE_MDI] CreateMDIClient(); [!if WTL_USE_CMDBAR] m_CmdBar.SetMDIClient(m_hWndMDIClient); [!endif] [!endif] [!if WTL_APPTYPE_SDI || WTL_APPTYPE_MTSDI] [!if WTL_USE_VIEW] [!if WTL_VIEWTYPE_FORM] m_hWndClient = m_view.Create(m_hWnd); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice m_hWndClient = m_view.Create(m_hWnd, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] m_font = AtlCreateControlFont(); m_view.SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app m_view.SetScrollSize(2000, 1000); [!endif] [!endif] [!endif] [!endif] [!if WTL_APPTYPE_TABVIEW] m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE); [!endif] [!if WTL_APPTYPE_EXPLORER] m_hWndClient = m_splitter.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); m_pane.SetPaneContainerExtendedStyle(PANECNT_NOBORDER); m_pane.Create(m_splitter, _T("Tree"), WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); m_treeview.Create(m_pane, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, WS_EX_CLIENTEDGE); m_pane.SetClient(m_treeview); [!if WTL_VIEWTYPE_FORM] m_view.Create(m_splitter); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice m_view.Create(m_splitter, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] m_view.Create(m_splitter, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] m_font = AtlCreateControlFont(); m_view.SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app m_view.SetScrollSize(2000, 1000); [!endif] [!endif] m_splitter.SetSplitterPanes(m_pane, m_view); UpdateLayout(); m_splitter.SetSplitterPosPct(25); [!endif] [!if WTL_USE_TOOLBAR] [!if WTL_USE_REBAR] UIAddToolBar(hWndToolBar); [!else] UIAddToolBar(m_hWndToolBar); [!endif] UISetCheck(ID_VIEW_TOOLBAR, 1); [!endif] [!if WTL_USE_STATUSBAR] UISetCheck(ID_VIEW_STATUS_BAR, 1); [!endif] [!if WTL_APPTYPE_EXPLORER] UISetCheck(ID_VIEW_TREEPANE, 1); [!endif] // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); [!if WTL_USE_RIBBON] [!if WTL_RIBBON_SINGLE_UI] ShowRibbonUI(true); [!else] ShowRibbonUI(bRibbonUI); UISetCheck(ID_VIEW_RIBBON, bRibbonUI); [!endif] [!endif] [!if WTL_APPTYPE_TABVIEW] [!if WTL_USE_CMDBAR] CMenuHandle menuMain = m_CmdBar.GetMenu(); [!else] CMenuHandle menuMain = GetMenu(); [!endif] m_view.SetWindowMenu(menuMain.GetSubMenu(WINDOW_MENU_POSITION)); [!endif] return 0; } [!if WTL_COM_SERVER] LRESULT [!output WTL_FRAME_CLASS]::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { [!if WTL_APPTYPE_MDI] [!if WTL_USE_CMDBAR] m_CmdBar.AttachMenu(NULL); [!endif] [!endif] // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); // if UI is the last thread, no need to wait if(_Module.GetLockCount() == 1) { _Module.m_dwTimeOut = 0L; _Module.m_dwPause = 0L; } _Module.Unlock(); [!if WTL_APPTYPE_MTSDI] ::PostQuitMessage(1); [!endif] return 0; } [!else] LRESULT [!output WTL_FRAME_CLASS]::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { [!if WTL_APPTYPE_MDI] [!if WTL_USE_CMDBAR] m_CmdBar.AttachMenu(NULL); [!endif] [!endif] // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); bHandled = FALSE; return 1; } [!endif] LRESULT [!output WTL_FRAME_CLASS]::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PostMessage(WM_CLOSE); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { [!if WTL_APPTYPE_TABVIEW] [!output WTL_VIEW_CLASS]* pView = new [!output WTL_VIEW_CLASS]; [!if WTL_VIEWTYPE_FORM] pView->Create(m_view); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice pView->Create(m_view, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] pView->Create(m_view, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] pView->SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app pView->SetScrollSize(2000, 1000); [!endif] [!endif] m_view.AddPage(pView->m_hWnd, _T("Document")); [!endif] [!if WTL_APPTYPE_MDI] [!output WTL_CHILD_FRAME_CLASS]* pChild = new [!output WTL_CHILD_FRAME_CLASS]; pChild->CreateEx(m_hWndClient); [!endif] // TODO: add code to initialize document return 0; } [!if WTL_APPTYPE_MTSDI] LRESULT [!output WTL_FRAME_CLASS]::OnFileNewWindow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ::PostThreadMessage(_Module.m_dwMainThreadID, WM_USER, 0, 0L); return 0; } [!endif] [!if WTL_USE_TOOLBAR] LRESULT [!output WTL_FRAME_CLASS]::OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { [!if WTL_USE_REBAR] static BOOL bVisible = TRUE; // initially visible bVisible = !bVisible; CReBarCtrl rebar = m_hWndToolBar; [!if WTL_USE_CMDBAR] int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1); // toolbar is 2nd added band [!else] int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST); // toolbar is first 1st band [!endif] rebar.ShowBand(nBandIndex, bVisible); [!else] BOOL bVisible = !::IsWindowVisible(m_hWndToolBar); ::ShowWindow(m_hWndToolBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE); [!endif] UISetCheck(ID_VIEW_TOOLBAR, bVisible); UpdateLayout(); return 0; } [!endif] [!if WTL_USE_STATUSBAR] LRESULT [!output WTL_FRAME_CLASS]::OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { BOOL bVisible = !::IsWindowVisible(m_hWndStatusBar); ::ShowWindow(m_hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE); UISetCheck(ID_VIEW_STATUS_BAR, bVisible); UpdateLayout(); return 0; } [!endif] [!if WTL_RIBBON_DUAL_UI] LRESULT [!output WTL_FRAME_CLASS]::OnViewRibbon(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShowRibbonUI(!IsRibbonUI()); UISetCheck(ID_VIEW_RIBBON, IsRibbonUI()); [!if !WTL_USE_CMDBAR] if (!IsRibbonUI()) SetMenu(AtlLoadMenu(IDR_MAINFRAME)); [!endif] return 0; } [!endif] LRESULT [!output WTL_FRAME_CLASS]::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CAboutDlg dlg; dlg.DoModal(); return 0; } [!if WTL_APPTYPE_MDI] LRESULT [!output WTL_FRAME_CLASS]::OnWindowCascade(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDICascade(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowTile(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDITile(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowArrangeIcons(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDIIconArrange(); return 0; } [!endif] [!if WTL_APPTYPE_TABVIEW] LRESULT [!output WTL_FRAME_CLASS]::OnWindowClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int nActivePage = m_view.GetActivePage(); if(nActivePage != -1) m_view.RemovePage(nActivePage); else ::MessageBeep((UINT)-1); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowCloseAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { m_view.RemoveAllPages(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowActivate(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int nPage = wID - ID_WINDOW_TABFIRST; m_view.SetActivePage(nPage); return 0; } [!endif] [!if WTL_APPTYPE_EXPLORER] LRESULT [!output WTL_FRAME_CLASS]::OnViewTreePane(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { bool bShow = (m_splitter.GetSinglePaneMode() != SPLIT_PANE_NONE); m_splitter.SetSinglePaneMode(bShow ? SPLIT_PANE_NONE : SPLIT_PANE_RIGHT); UISetCheck(ID_VIEW_TREEPANE, bShow); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnTreePaneClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND hWndCtl, BOOL& /*bHandled*/) { if(hWndCtl == m_pane.m_hWnd) { m_splitter.SetSinglePaneMode(SPLIT_PANE_RIGHT); UISetCheck(ID_VIEW_TREEPANE, 0); } return 0; } [!endif]
27.883295
192
0.704801
Peterinor
b18c662df9a7d74637ad3540d633f3a069954954
3,761
cpp
C++
plugins/dmetaphone/dmetaphone.cpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
plugins/dmetaphone/dmetaphone.cpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
plugins/dmetaphone/dmetaphone.cpp
cloLN/HPCC-Platform
42ffb763a1cdcf611d3900831973d0a68e722bbe
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
#include "platform.h" #include <time.h> #include <stdlib.h> #include <string.h> #include "dmetaphone.hpp" #include "metaphone.h" #define DMETAPHONE_VERSION "DMETAPHONE 1.1.05" static const char * compatibleVersions[] = { "DMETAPHONE 1.1.05 [0e64c86ec1d5771d4ce0abe488a98a2a]", "DMETAPHONE 1.1.05", NULL }; DMETAPHONE_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb) { if (pb->size == sizeof(ECLPluginDefinitionBlockEx)) { ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb; pbx->compatibleVersions = compatibleVersions; } else if (pb->size != sizeof(ECLPluginDefinitionBlock)) return false; pb->magicVersion = PLUGIN_VERSION; pb->version = DMETAPHONE_VERSION; pb->moduleName = "lib_metaphone"; pb->ECL = NULL; // Definition is in lib_metaphone.ecllib pb->flags = PLUGIN_IMPLICIT_MODULE; pb->description = "Metaphone library"; return true; } namespace nsDmetaphone { IPluginContext * parentCtx = NULL; } using namespace nsDmetaphone; DMETAPHONE_API void setPluginContext(IPluginContext * _ctx) { parentCtx = _ctx; } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph2); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph2); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph) + strlen((char*) metaph2); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph); strcat(__ret_str, (char*) metaph2); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1_20(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 20); size32_t metaph_len = strlen((char*) metaph); strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2_20(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 20); size32_t metaph2_len = strlen((char*) metaph2); strncpy(__ret_str, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth_40(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 40); size32_t metaph_len = strlen((char*) metaph); strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len); size32_t metaph2_len = strlen((char*) metaph2); strncpy(__ret_str+metaph_len, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len); }
31.605042
132
0.708588
miguelvazq
b18d55a2d3735b5c31fd9acc502cf9a8bdb3f5ee
788
hpp
C++
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
alex-public/online-smart-storage
3d066f8728b645d98cd786c2c2f637399669444b
[ "MIT" ]
null
null
null
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
alex-public/online-smart-storage
3d066f8728b645d98cd786c2c2f637399669444b
[ "MIT" ]
null
null
null
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
alex-public/online-smart-storage
3d066f8728b645d98cd786c2c2f637399669444b
[ "MIT" ]
2
2018-11-12T21:42:44.000Z
2019-04-25T07:28:37.000Z
const char* const asserter_abi = R"=====( { "version": "eosio::abi/1.0", "types": [], "structs": [ { "name": "assertdef", "base": "", "fields": [ { "name": "condition", "type": "int8" },{ "name": "message", "type": "string" } ] }, { "name": "nothing", "base": "", "fields": [] } ], "actions": [ { "name": "procassert", "type": "assertdef", "ricardian_contract": "" }, { "name": "provereset", "type": "nothing", "ricardian_contract": "" } ], "tables": [], "ricardian_clauses": [], "abi_extensions": [] } )=====";
19.7
41
0.347716
alex-public
b18d7cab6b3cb369c34fda45e9bfc0ab8c6eee57
1,078
hpp
C++
src/ast/ast_var_decl.hpp
Wassasin/splicpp
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
[ "Beerware" ]
2
2019-04-09T01:04:36.000Z
2019-05-12T06:17:03.000Z
src/ast/ast_var_decl.hpp
Wassasin/splicpp
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
[ "Beerware" ]
null
null
null
src/ast/ast_var_decl.hpp
Wassasin/splicpp
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
[ "Beerware" ]
null
null
null
#ifndef AST_VAR_DECL_H #define AST_VAR_DECL_H #include <memory> #include "ast.hpp" #include "../common/typedefs.hpp" #include "../typing/substitution.hpp" namespace splicpp { class ast_type; class ast_exp; class ast_id; class symboltable; class varcontext; class typecontext; class ltypecontext; class sl_type; class ir_stmt; class ircontext; class ast_var_decl : public ast { public: const s_ptr<ast_type> t; const s_ptr<ast_id> id; const s_ptr<ast_exp> exp; ast_var_decl(__decltype(t) t, __decltype(id) id, __decltype(exp) exp, const sloc sl) : ast(sl) , t(t) , id(id) , exp(exp) {} void assign(sid i); std::string fetch_name() const; sid fetch_id() const; void assign_ids(const varcontext& c); void register_types(symboltable& s, varcontext& c); s_ptr<const sl_type> fetch_assigned_type(const typecontext& c) const; substitution declare_type(ltypecontext& c) const; s_ptr<const ir_stmt> translate(const ircontext& c) const; virtual void pretty_print(std::ostream& s, const uint tab) const; }; } #endif
19.6
86
0.714286
Wassasin
b18d8212b9015540071f5512237d4d6356dc1bfe
64,921
cpp
C++
test/localPRG_test.cpp
rffrancon/pandora
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
[ "MIT" ]
null
null
null
test/localPRG_test.cpp
rffrancon/pandora
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
[ "MIT" ]
null
null
null
test/localPRG_test.cpp
rffrancon/pandora
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "test_macro.cpp" #include "localPRG.h" #include "minimizer.h" #include "minirecord.h" #include "minihit.h" #include "interval.h" #include "prg/path.h" #include "localgraph.h" #include "localnode.h" #include "index.h" #include "inthash.h" #include "pangenome/pannode.h" #include "pangenome/panread.h" #include "utils.h" #include "seq.h" #include "kmergraph.h" #include "kmernode.h" #include <stdint.h> #include <iostream> using namespace std; TEST(LocalPRGTest, create) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); uint32_t j = 0; EXPECT_EQ(j, l0.id); EXPECT_EQ("empty", l0.name); EXPECT_EQ("", l0.seq); j = 1; EXPECT_EQ(j, l1.id); EXPECT_EQ("simple", l1.name); EXPECT_EQ("AGCT", l1.seq); j = 2; EXPECT_EQ(j, l2.id); EXPECT_EQ("varsite", l2.name); EXPECT_EQ("A 5 GC 6 G 5 T", l2.seq); j = 3; EXPECT_EQ(j, l3.id); EXPECT_EQ("nested varsite", l3.name); EXPECT_EQ("A 5 G 7 C 8 T 7 6 G 5 T", l3.seq); } TEST(LocalPRGTest, isalphaEmptyString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string(""); bool a1 = l1.isalpha_string(""); bool a2 = l2.isalpha_string(""); bool a3 = l3.isalpha_string(""); EXPECT_EQ(a0, 1) << "isalpha_string thinks the empty string is not alphabetic for l0"; EXPECT_EQ(a1, 1) << "isalpha_string thinks the empty string is not alphabetic for l1"; EXPECT_EQ(a2, 1) << "isalpha_string thinks the empty string is not alphabetic for l2"; EXPECT_EQ(a3, 1) << "isalpha_string thinks the empty string is not alphabetic for l3"; } TEST(LocalPRGTest, isalphaSpaceString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string("AGCT T"); bool a1 = l1.isalpha_string("AGCT T"); bool a2 = l2.isalpha_string("AGCT T"); bool a3 = l3.isalpha_string("AGCT T"); EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a space is alphabetic for l0"; EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a space is alphabetic for l1"; EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a space is alphabetic for l2"; EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a space is alphabetic for l3"; } TEST(LocalPRGTest, isalphaNumberString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string("AGCT 8 T"); bool a1 = l1.isalpha_string("AGCT 8 T"); bool a2 = l2.isalpha_string("AGCT 8 T"); bool a3 = l3.isalpha_string("AGCT 8 T"); EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a number is alphabetic for l0"; EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a number is alphabetic for l1"; EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a number is alphabetic for l2"; EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a number is alphabetic for l3"; } TEST(LocalPRGTest, string_along_path) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); // empty interval deque<Interval> d = {Interval(0, 0)}; Path p; p.initialize(d); EXPECT_EQ("", l0.string_along_path(p)); EXPECT_EQ("", l1.string_along_path(p)); EXPECT_EQ("", l2.string_along_path(p)); EXPECT_EQ("", l3.string_along_path(p)); // positive length interval d = {Interval(1, 3)}; p.initialize(d); EXPECT_EQ("GC", l1.string_along_path(p)); EXPECT_EQ(" 5", l2.string_along_path(p)); EXPECT_EQ(" 5", l3.string_along_path(p)); // multiple intervals d = {Interval(0, 1), Interval(2, 3)}; p.initialize(d); EXPECT_EQ("AC", l1.string_along_path(p)); EXPECT_EQ("A5", l2.string_along_path(p)); EXPECT_EQ("A5", l3.string_along_path(p)); // including empty interval d = {Interval(0, 1), Interval(2, 2)}; p.initialize(d); EXPECT_EQ("A", l1.string_along_path(p)); EXPECT_EQ("A", l2.string_along_path(p)); EXPECT_EQ("A", l3.string_along_path(p)); // forbidden paths d = {Interval(2, 3), Interval(13, 25)}; p.initialize(d); EXPECT_DEATH(l1.string_along_path(p), ""); EXPECT_DEATH(l1.string_along_path(p), ""); EXPECT_DEATH(l2.string_along_path(p), ""); EXPECT_DEATH(l3.string_along_path(p), ""); } TEST(LocalPRGTest, string_along_localpath) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); // empty interval vector<LocalNodePtr> p = {l0.prg.nodes[0]}; EXPECT_EQ("", l0.string_along_path(p)); p = {l1.prg.nodes[0]}; EXPECT_EQ("AGCT", l1.string_along_path(p)); // extract from intervals p = {l2.prg.nodes[0], l2.prg.nodes[1]}; EXPECT_EQ("AGC", l2.string_along_path(p)); p = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; EXPECT_EQ("AGT", l2.string_along_path(p)); } TEST(LocalPRGTest, nodes_along_path) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); // empty interval expects no nodes along deque<Interval> d = {Interval(0, 0)}; Path p; p.initialize(d); vector<LocalNodePtr> v; //EXPECT_EQ(v, l0.nodes_along_path(p)); EXPECT_EQ(v, l1.nodes_along_path(p)); EXPECT_EQ(v, l2.nodes_along_path(p)); EXPECT_EQ(v, l3.nodes_along_path(p)); // positive length interval d = {Interval(1, 3)}; p.initialize(d); uint32_t j = 1; EXPECT_EQ(j, l1.nodes_along_path(p).size()); j = 0; EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l2.nodes_along_path(p).size()); // no nodes in this interval EXPECT_EQ(j, l3.nodes_along_path(p).size()); // different interval d = {Interval(4, 5)}; p.initialize(d); j = 1; EXPECT_EQ(j, l2.nodes_along_path(p).size()); EXPECT_EQ(j, l3.nodes_along_path(p).size()); EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); // multiple intervals d = {Interval(0, 1), Interval(4, 5)}; p.initialize(d); j = 1; EXPECT_EQ(j, l1.nodes_along_path(p).size()); j = 2; EXPECT_EQ(j, l2.nodes_along_path(p).size()); EXPECT_EQ(j, l3.nodes_along_path(p).size()); j = 0; EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 1; EXPECT_EQ(j, l2.nodes_along_path(p)[1]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); // including empty interval d = {Interval(12, 13), Interval(16, 16), Interval(23, 24)}; p.initialize(d); j = 3; vector<LocalNodePtr> w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); j = 6; EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id); // a path with an empty node at end d = {Interval(12, 13), Interval(16, 16), Interval(23, 23)}; p.initialize(d); j = 3; w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); j = 6; EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id); // and a path which ends on a null node d = {Interval(12, 13), Interval(16, 16)}; p.initialize(d); j = 2; w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); j = 3; EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); // and a path that can't really exist still works d = {Interval(12, 13), Interval(19, 20)}; p.initialize(d); j = 2; EXPECT_EQ(j, l3.nodes_along_path(p).size()); j = 3; EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 5; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); } TEST(LocalPRGTest, split_by_siteNoSites) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); vector<Interval> v0, v1; v0.push_back(Interval(0, 0)); EXPECT_ITERABLE_EQ(vector<Interval>, v0, l0.split_by_site(Interval(0, 0)));// << "Failed to split empty string with input Interval"; v1.push_back(Interval(0, 4)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(0, 4)));// << "Failed to split string with input Interval"; v1.clear(); v1.push_back(Interval(0, 2)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(0, 2)));// << "Failed to split string with short input Interval"; v1.clear(); v1.push_back(Interval(1, 3)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(1, 3)));// << "Failed to split string with middle input Interval"; } TEST(LocalPRGTest, split_by_siteSite) { LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); vector<Interval> v2; v2.push_back(Interval(0, 1)); l2.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3); //EXPECT_ITERABLE_EQ( vector< Interval >,v2, l2.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4); v2.push_back(Interval(4, 6)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 6)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 7)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 8)));// << "Failed to split string in Interval" << Interval(0,8); v2.push_back(Interval(9, 10)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 10)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 11)));// << "Failed to split string in Interval" << Interval(0,11); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 12)));// << "Failed to split string in Interval" << Interval(0,12); v2.push_back(Interval(13, 14)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 14)));// << "Failed to split string in Interval" << Interval(0,14); v2.clear(); v2.push_back(Interval(5, 6)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site( Interval(5, 8)));// << "Failed to split string in mid Interval" << Interval(5,8); } TEST(LocalPRGTest, split_by_siteNestedSite) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "nested varsite start immediately", " 5 G 7 C 8 T 7 6 G 5 "); vector<Interval> v3; v3.push_back(Interval(0, 1)); l3.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3); //EXPECT_ITERABLE_EQ( vector< Interval >,v3, l3.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4); v3.push_back(Interval(4, 16)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 18)));// << "Failed to split string in Interval" << Interval(0,8); v3.push_back(Interval(19, 20)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 21)));// << "Failed to split string in Interval" << Interval(0,11); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 22)));// << "Failed to split string in Interval" << Interval(0,12); v3.push_back(Interval(23, 24)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 24)));// << "Failed to split string in Interval" << Interval(0,14); l3.next_site = 7; v3.clear(); v3.push_back(Interval(4, 5)); v3.push_back(Interval(8, 9)); v3.push_back(Interval(12, 13)); v3.push_back(Interval(16, 16)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site( Interval(4, 16)));// << "Failed to split string in mid Interval" << Interval(5,8); vector<Interval> v4; v4.push_back(Interval(0, 0)); l4.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); v4.push_back(Interval(3, 15)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 15)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,8); v4.push_back(Interval(18, 19)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 19)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,11); l4.next_site = 7; v4.clear(); v4.push_back(Interval(0, 4)); v4.push_back(Interval(7, 8)); v4.push_back(Interval(11, 12)); v4.push_back(Interval(15, 22)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site( Interval(0, 22)));// << "Failed to split string in mid Interval" << Interval(5,8); } TEST(LocalPRGTest, build_graph) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalGraph lg0; lg0.add_node(0, "", Interval(0, 0)); EXPECT_EQ(lg0, l0.prg); LocalGraph lg1; lg1.add_node(0, "AGCT", Interval(0, 4)); EXPECT_EQ(lg1, l1.prg); LocalGraph lg2; lg2.add_node(0, "A", Interval(0, 1)); lg2.add_node(1, "GC", Interval(4, 6)); lg2.add_node(2, "G", Interval(9, 10)); lg2.add_node(3, "T", Interval(13, 14)); lg2.add_edge(0, 1); lg2.add_edge(0, 2); lg2.add_edge(1, 3); lg2.add_edge(2, 3); EXPECT_EQ(lg2, l2.prg); LocalGraph lg3; lg3.add_node(0, "A", Interval(0, 1)); lg3.add_node(1, "G", Interval(4, 5)); lg3.add_node(2, "C", Interval(8, 9)); lg3.add_node(3, "T", Interval(12, 13)); lg3.add_node(4, "", Interval(16, 16)); lg3.add_node(5, "G", Interval(19, 20)); lg3.add_node(6, "T", Interval(23, 24)); lg3.add_edge(0, 1); lg3.add_edge(0, 5); lg3.add_edge(1, 2); lg3.add_edge(1, 3); lg3.add_edge(2, 4); lg3.add_edge(3, 4); lg3.add_edge(4, 6); lg3.add_edge(5, 6); EXPECT_EQ(lg3, l3.prg); } TEST(LocalPRGTest, shift) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "AT 5 G 7 C 8 T 7 6 G 5 T"); //LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG"); LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between", " 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 "); LocalPRG l6(6, "one representing a possible deletion at end", "GATCTCTAG 5 TTATG 6 5 "); deque<Interval> d = {Interval(0, 3)}; Path p, q; p.initialize(d); d = {Interval(1, 4)}; q.initialize(d); vector<Path> v_exp = {q}; EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(p)); v_exp.clear(); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(q)); // there are no shifts over end of prg d = {Interval(0, 1), Interval(4, 6)}; p.initialize(d); d = {Interval(4, 6), Interval(13, 14)}; q.initialize(d); v_exp = {q}; EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(p)); v_exp.clear(); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(q)); v_exp.clear(); d = {Interval(0, 2)}; p.initialize(d); d = {Interval(1, 2), Interval(5, 6)}; q.initialize(d); v_exp.push_back(q); d = {Interval(1, 2), Interval(20, 21)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p)); v_exp.clear(); d = {Interval(1, 2), Interval(5, 6)}; p.initialize(d); d = {Interval(5, 6), Interval(9, 10)}; q.initialize(d); v_exp.push_back(q); d = {Interval(5, 6), Interval(13, 14)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p)); v_exp.clear(); d = {Interval(0, 0), Interval(3, 3), Interval(6, 6), Interval(9, 9), Interval(13, 18)}; p.initialize(d); d = {Interval(14, 19)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l5.shift(p)); v_exp.clear(); d = {Interval(3, 8)}; p.initialize(d); d = {Interval(4, 9), Interval(20, 20), Interval(23, 23)}; q.initialize(d); v_exp.push_back(q); d = {Interval(4, 9)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p)); v_exp.clear(); d = {Interval(4, 9)}; p.initialize(d); d = {Interval(5, 9), Interval(12, 13)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p)); } TEST(LocalPRGTest, minimizer_sketch) { // note this is a bad test LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG"); LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between", " 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 "); Index *idx; idx = new Index(); KmerHash hash; l0.minimizer_sketch(idx, 1, 3); uint32_t j = 0; EXPECT_EQ(j, idx->minhash.size()); l1.minimizer_sketch(idx, 2, 3); j = 1; EXPECT_EQ(j, idx->minhash.size()); l1.minimizer_sketch(idx, 1, 3); EXPECT_EQ(j, idx->minhash.size()); j = 2; pair<uint64_t, uint64_t> kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l2.minimizer_sketch(idx, 2, 3); j = 1; EXPECT_EQ(j, idx->minhash.size()); l2.minimizer_sketch(idx, 1, 3); j = 2; EXPECT_EQ(j, idx->minhash.size()); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("AGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l3.minimizer_sketch(idx, 2, 3); j = 2; EXPECT_EQ(j, idx->minhash.size()); l3.minimizer_sketch(idx, 1, 3); j = 3; EXPECT_EQ(j, idx->minhash.size()); j = 2; kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGC kh = hash.kmerhash("AGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGTx2 j = 1; kh = hash.kmerhash("GTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l4.minimizer_sketch(idx, 1, 3); j = 16; EXPECT_EQ(j, idx->minhash.size()); j = 5; kh = hash.kmerhash("TCA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 4; kh = hash.kmerhash("CTA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 3; kh = hash.kmerhash("ACT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CAA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AAG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TCT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 2; kh = hash.kmerhash("TTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("CAT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("ATT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l4.minimizer_sketch(idx, 3, 3); j = 10; EXPECT_EQ(j, idx->minhash.size()); j = 4; kh = hash.kmerhash("CTA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 3; kh = hash.kmerhash("CTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 2; kh = hash.kmerhash("CAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("ATT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("ACT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TCA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GAG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l5.minimizer_sketch(idx, 4, 5); EXPECT_EQ((idx->minhash.size() > 2), true); idx->clear(); delete idx; } struct MiniPos { bool operator()(Minimizer lhs, Minimizer rhs) { return (lhs.pos.start) < (rhs.pos.start); } }; TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw1) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 1, 15); Seq s = Seq(0, "read", st, 1, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw5) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 5, 15); Seq s = Seq(0, "read", st, 5, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw10) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 10, 15); Seq s = Seq(0, "read", st, 10, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw15) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 15, 15); Seq s = Seq(0, "read", st, 15, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, localnode_path_from_kmernode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); //vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp); vector<LocalNodePtr> lmp_exp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); lmp = l3.localnode_path_from_kmernode_path(kmp, 2); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); idx->clear(); l4.minimizer_sketch(idx, 3, 3); //kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]}; kmp = {l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 2); lmp_exp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]}; EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); lmp = l4.localnode_path_from_kmernode_path(kmp, 3); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); delete idx; } TEST(LocalPRGTest, kmernode_path_from_localnode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); LocalPRG l5(5, "nested varsite", "A 5 G 7 C 8 T 7 T 9 CCG 10 CGG 9 6 G 5 TAT"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); l3.kmer_prg.sort_topologically(); vector<LocalNodePtr> lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<KmerNodePtr> kmp = l3.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); vector<KmerNodePtr> kmp_exp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); idx->clear(); l4.minimizer_sketch(idx, 3, 3); l4.kmer_prg.sort_topologically(); lmp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]}; kmp = l4.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); kmp_exp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); // case where we don't have start and end point in localpath, so need to consider whether kmer overlaps idx->clear(); l5.minimizer_sketch(idx, 2, 3); l5.kmer_prg.sort_topologically(); lmp = {l5.prg.nodes[1], l5.prg.nodes[2], l5.prg.nodes[4], l5.prg.nodes[6], l5.prg.nodes[7]}; kmp = l5.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); cout << l5.kmer_prg << endl; kmp_exp = {l5.kmer_prg.nodes[1], l5.kmer_prg.nodes[2], l5.kmer_prg.nodes[6], l5.kmer_prg.nodes[8], l5.kmer_prg.nodes[10], l5.kmer_prg.nodes[12], l5.kmer_prg.nodes[13]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); delete idx; } TEST(LocalPRGTest, get_covgs_along_localnode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3")); pn3->kmer_prg = l3.kmer_prg; for (const auto &n : pn3->kmer_prg.nodes) { n->covg[0] += 1; } vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp); vector<uint> covgs_exp = {0, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); idx->clear(); l4.minimizer_sketch(idx, 1, 3); kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[12], l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18], l4.kmer_prg.nodes[21], l4.kmer_prg.nodes[23], l4.kmer_prg.nodes[25], l4.kmer_prg.nodes[27], l4.kmer_prg.nodes[29]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 1); shared_ptr<pangenome::Node> pn4(make_shared<pangenome::Node>(4, 4, "4")); pn4->kmer_prg = l4.kmer_prg; for (const auto &n : pn4->kmer_prg.nodes) { n->covg[0] += 1; } covgs = get_covgs_along_localnode_path(pn4, lmp, kmp); //covgs_exp = {1,2,3,3,3,3,3,3,3,3,3,3,2,1}; covgs_exp = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[12], l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18], l4.kmer_prg.nodes[25]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 2); covgs = get_covgs_along_localnode_path(pn4, lmp, kmp); //covgs_exp = {0,1,2,2,1,1,2,3,2,1,1,1,1,0}; covgs_exp = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); delete idx; } TEST(LocalPRGTest, write_covgs_to_file) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3")); pn3->kmer_prg = l3.kmer_prg; for (const auto &n : pn3->kmer_prg.nodes) { n->covg[0] += 1; } vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp); vector<uint> covgs_exp = {0, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); l3.write_covgs_to_file("localPRG_test.covgs", covgs); delete idx; } TEST(LocalPRGTest, write_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.write_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, append_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.append_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, write_aligned_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.write_aligned_path_to_fasta("localPRG_test.alignedpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, build_vcf) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG" "AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA" "TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA" "AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13" " G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG"); LocalPRG l5(5, "another real PRG", "ATGACAAAGGTTACACCGT 5 C 6 T 5 TGACGTGCTACGCCTGTCAGGCCTATTCGACTCCTGCAAT 7 G 8 A 7 TATTGAATTTGCATAGTTTT 9 G 10 A 9 TAGGTCGA 11 G 12 A 11 TAAGGCGTTCACGCCGCATCCGGCGTGAACAAA 13 G 14 T 13 TACTCTTTTT 15 17 19 C 20 T 19 GCACAATCCAA 18 CGCACAAACCAA 17 16 21 CGCACAATCCAA 22 23 CGT 24 CGC 23 ACAAACCA 25 A 26 T 25 21 TATGTGCAAATTATTACTTTTTCCAGAAATCATCGAAAACGG 15 "); VCF vcf; l1.build_vcf(vcf, l1.prg.top_path()); uint j = 0; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ(j, vcf.samples.size()); vcf.clear(); l2.build_vcf(vcf, l2.prg.top_path()); j = 1; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GC", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); vcf.clear(); vector<LocalNodePtr> lmp = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; l2.build_vcf(vcf, lmp); j = 1; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("G", vcf.records[0].ref); EXPECT_EQ("GC", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); vcf.clear(); l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); j = 2; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GC", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info); EXPECT_EQ((uint) 2, vcf.records[1].pos); EXPECT_EQ("C", vcf.records[1].ref); EXPECT_EQ("T", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info); vcf.clear(); lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, lmp); vcf.sort_records(); EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GT", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info); EXPECT_EQ((uint) 2, vcf.records[1].pos); EXPECT_EQ("T", vcf.records[1].ref); EXPECT_EQ("C", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info); vcf.clear(); lmp = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]}; l3.build_vcf(vcf, lmp); vcf.sort_records(); EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("G", vcf.records[0].ref); EXPECT_EQ("GC", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 1, vcf.records[1].pos); EXPECT_EQ("G", vcf.records[1].ref); EXPECT_EQ("GT", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[1].info); vcf.clear(); l4.build_vcf(vcf, l4.prg.top_path()); vcf.sort_records(); j = 5; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("small real PRG", vcf.records[0].chrom); EXPECT_EQ((uint) 119, vcf.records[0].pos); EXPECT_EQ("T", vcf.records[0].ref); EXPECT_EQ("C", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 158, vcf.records[1].pos); EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref); EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info); EXPECT_EQ((uint) 251, vcf.records[2].pos); EXPECT_EQ("A", vcf.records[2].ref); EXPECT_EQ("G", vcf.records[2].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info); EXPECT_EQ((uint) 272, vcf.records[3].pos); EXPECT_EQ("A", vcf.records[3].ref); EXPECT_EQ("C", vcf.records[3].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info); EXPECT_EQ((uint) 293, vcf.records[4].pos); EXPECT_EQ("G", vcf.records[4].ref); EXPECT_EQ("T", vcf.records[4].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info); vcf.clear(); lmp = {l4.prg.nodes[0], l4.prg.nodes[2], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6], l4.prg.nodes[8], l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[14], l4.prg.nodes[15]}; l4.build_vcf(vcf, lmp); vcf.sort_records(); j = 5; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("small real PRG", vcf.records[0].chrom); EXPECT_EQ((uint) 119, vcf.records[0].pos); EXPECT_EQ("C", vcf.records[0].ref); EXPECT_EQ("T", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 158, vcf.records[1].pos); EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref); EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info); EXPECT_EQ((uint) 251, vcf.records[2].pos); EXPECT_EQ("G", vcf.records[2].ref); EXPECT_EQ("A", vcf.records[2].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info); EXPECT_EQ((uint) 272, vcf.records[3].pos); EXPECT_EQ("A", vcf.records[3].ref); EXPECT_EQ("C", vcf.records[3].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info); EXPECT_EQ((uint) 293, vcf.records[4].pos); EXPECT_EQ("T", vcf.records[4].ref); EXPECT_EQ("G", vcf.records[4].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info); vcf.clear(); l5.build_vcf(vcf, l5.prg.top_path()); vcf.sort_records(); } TEST(LocalPRGTest, add_sample_gt_to_vcf) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG" "AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA" "TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA" "AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13" " G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG"); LocalPRG l5(5, "another real PRG", " 5 ATGCTTATTGGCTATGT 7 9 ACGCGTA 10 TCGCGTA 10 ACGTGTG 9 TCAACAAATGACCAGAACA" "C 11 A 12 C 11 8 ACGCGTATCAACAAATGATCAGAACACA 7 GATCTACAACGTAATGCG 6 AAGT 5 "); VCF vcf; vector<LocalNodePtr> lmp1 = {l1.prg.nodes[0]}; l1.build_vcf(vcf, l1.prg.top_path()); l1.add_sample_gt_to_vcf(vcf, l1.prg.top_path(), lmp1, "sample"); uint j = 1; EXPECT_EQ(j, vcf.samples.size()); vcf.clear(); vector<LocalNodePtr> lmp2 = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; l2.build_vcf(vcf, l2.prg.top_path()); l2.add_sample_gt_to_vcf(vcf, l2.prg.top_path(), lmp2, "sample"); j = 1; EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[0].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp4 = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[5], l4.prg.nodes[6], l4.prg.nodes[8], l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[13], l4.prg.nodes[15]}; l4.build_vcf(vcf, l4.prg.top_path()); vcf.sort_records(); l4.add_sample_gt_to_vcf(vcf, l4.prg.top_path(), lmp4, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[1].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[2].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[2].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[4].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp5 = {l5.prg.nodes[0], l5.prg.nodes[1], l5.prg.nodes[10], l5.prg.nodes[11], l5.prg.nodes[13]}; l5.build_vcf(vcf, l5.prg.top_path()); vcf.sort_records(); l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), lmp5, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ((uint) 5, vcf.records.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_TRUE(vcf.records[0].samples[0].find("GT") == vcf.records[0].samples[0].end()); EXPECT_EQ(j, vcf.records[1].samples.size()); EXPECT_TRUE(vcf.records[1].samples[0].find("GT") == vcf.records[1].samples[0].end()); EXPECT_EQ(j, vcf.records[2].samples.size()); EXPECT_TRUE(vcf.records[2].samples[0].find("GT") == vcf.records[2].samples[0].end()); EXPECT_EQ(j, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[3].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[4].samples.size()); EXPECT_TRUE(vcf.records[4].samples[0].find("GT") == vcf.records[4].samples[0].end()); // add the ref path l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), l5.prg.top_path(), "sample2"); EXPECT_EQ((uint) 2, vcf.samples.size()); EXPECT_EQ((uint) 5, vcf.records.size()); EXPECT_EQ((uint) 2, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[1].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[2].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[2].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[4].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[1]["GT"][0]); } TEST(LocalPRGTest, moreupdateVCF) { // load PRGs from file std::vector<std::shared_ptr<LocalPRG>> prgs; read_prg_file(prgs, "../../test/test_cases/updatevcf_test.fa"); EXPECT_EQ((uint) 3, prgs.size()); VCF vcf; prgs[0]->build_vcf(vcf, prgs[0]->prg.top_path()); prgs[1]->build_vcf(vcf, prgs[1]->prg.top_path()); prgs[2]->build_vcf(vcf, prgs[2]->prg.top_path()); vcf.sort_records(); //for (uint i=0; i!=prgs[2]->vcf.records.size(); ++i) //{ //cout << prgs[2]->vcf.records[i]; //} vector<LocalNodePtr> lmp1 = {prgs[1]->prg.nodes[0], prgs[1]->prg.nodes[11], prgs[1]->prg.nodes[12], prgs[1]->prg.nodes[17], prgs[1]->prg.nodes[65], prgs[1]->prg.nodes[67]}; //cout << "PRG 1 has " << prgs[1]->prg.nodes.size() << " nodes" << endl; prgs[1]->add_sample_gt_to_vcf(vcf, prgs[1]->prg.top_path(), lmp1, "sample"); vector<LocalNodePtr> lmp2 = {prgs[2]->prg.nodes[0], prgs[2]->prg.nodes[1], prgs[2]->prg.nodes[3], prgs[2]->prg.nodes[4], prgs[2]->prg.nodes[6], prgs[2]->prg.nodes[7], prgs[2]->prg.nodes[9], prgs[2]->prg.nodes[10], prgs[2]->prg.nodes[11], prgs[2]->prg.nodes[13], prgs[2]->prg.nodes[14], prgs[2]->prg.nodes[16], prgs[2]->prg.nodes[17], prgs[2]->prg.nodes[19], prgs[2]->prg.nodes[44], prgs[2]->prg.nodes[45], prgs[2]->prg.nodes[47], prgs[2]->prg.nodes[118], prgs[2]->prg.nodes[119], prgs[2]->prg.nodes[121], prgs[2]->prg.nodes[123], prgs[2]->prg.nodes[125], prgs[2]->prg.nodes[126], prgs[2]->prg.nodes[130], prgs[2]->prg.nodes[131], prgs[2]->prg.nodes[133], prgs[2]->prg.nodes[135], prgs[2]->prg.nodes[141], prgs[2]->prg.nodes[142], prgs[2]->prg.nodes[144], prgs[2]->prg.nodes[145], prgs[2]->prg.nodes[160]}; //cout << "PRG 2 has " << prgs[2]->prg.nodes.size() << " nodes" << endl; prgs[2]->add_sample_gt_to_vcf(vcf, prgs[2]->prg.top_path(), lmp2, "sample"); } TEST(LocalPRGTest, find_alt_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT 9 T 10 9 ATG"); vector<LocalNodePtr> top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<LocalNodePtr> middle = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<LocalNodePtr> bottom = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]}; vector<LocalNodePtr> alt_path = l3.find_alt_path(top, 2, "C", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path); alt_path = l3.find_alt_path(top, 1, "GC", "G"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(middle, 2, "T", "C"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); alt_path = l3.find_alt_path(top, 1, "GT", "G"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(bottom, 1, "G", "GT"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path); alt_path = l3.find_alt_path(bottom, 1, "G", "GC"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // and now for the one where the alt or ref is "." top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[7], l3.prg.nodes[9]}; bottom = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[8], l3.prg.nodes[9]}; alt_path = l3.find_alt_path(top, 6, "T", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(bottom, 6, ".", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // if the site is at the start and alt is "." LocalPRG l3_(3, "nested varsite", " 5 G 7 C 8 T 7 6 5 TAT 9 T 10 9 "); top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6]}; bottom = {l3_.prg.nodes[0], l3_.prg.nodes[5], l3_.prg.nodes[6]}; alt_path = l3_.find_alt_path(top, 0, "GC", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3_.find_alt_path(bottom, 0, ".", "GC"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // if the site at the end has ref/alt as "." top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6], l3_.prg.nodes[7], l3_.prg.nodes[9]}; bottom = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6], l3_.prg.nodes[8], l3_.prg.nodes[9]}; alt_path = l3_.find_alt_path(top, 5, "T", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3_.find_alt_path(bottom, 5, ".", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); } TEST(LocalPRGTest, append_kmer_covgs_in_range) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); l3.kmer_prg.nodes[2]->covg[0] = 4; l3.kmer_prg.nodes[2]->covg[1] = 3; l3.kmer_prg.nodes[5]->covg[0] = 4; l3.kmer_prg.nodes[5]->covg[1] = 5; l3.kmer_prg.nodes[7]->covg[0] = 2; l3.kmer_prg.nodes[7]->covg[1] = 3; l3.kmer_prg.nodes[8]->covg[0] = 4; l3.kmer_prg.nodes[8]->covg[1] = 6; for (const auto &n : l3.kmer_prg.nodes) { cout << *n; } vector<LocalNodePtr> lmp = {}; vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[5], l3.kmer_prg.nodes[8], l3.kmer_prg.nodes[10], l3.kmer_prg.nodes[11]}; vector<uint32_t> fwd, rev, exp_fwd, exp_rev; l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 0, fwd, rev); exp_fwd = {}; exp_rev = {}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 1, fwd, rev); exp_fwd = {4}; exp_rev = {3}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 2, fwd, rev); exp_fwd = {4, 4}; exp_rev = {3, 5}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 3, fwd, rev); exp_fwd = {4, 4, 4}; exp_rev = {3, 5, 6}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 1, 2, fwd, rev); exp_fwd = {4, 4}; exp_rev = {3, 5}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); } TEST(LocalPRGTest, add_sample_covgs_to_vcf) { Index *idx; idx = new Index(); vector<string> short_formats = {"GT"}; vector<string> formats = {"GT", "MEAN_FWD_COVG", "MEAN_REV_COVG", "MED_FWD_COVG", "MED_REV_COVG", "SUM_FWD_COVG", "SUM_REV_COVG"}; LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); l3.kmer_prg.sort_topologically(); VCF vcf; vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, short_formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][1]); // ref l3.kmer_prg.nodes[1]->covg[0] = 1; l3.kmer_prg.nodes[1]->covg[1] = 0; l3.kmer_prg.nodes[4]->covg[0] = 1; l3.kmer_prg.nodes[4]->covg[1] = 0; l3.kmer_prg.nodes[7]->covg[0] = 1; l3.kmer_prg.nodes[7]->covg[1] = 0; // alt l3.kmer_prg.nodes[2]->covg[0] = 6; l3.kmer_prg.nodes[2]->covg[1] = 8; l3.kmer_prg.nodes[5]->covg[0] = 5; l3.kmer_prg.nodes[5]->covg[1] = 5; l3.kmer_prg.nodes[8]->covg[0] = 4; l3.kmer_prg.nodes[8]->covg[1] = 5; l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 6, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MED_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_REV_COVG"][1]); EXPECT_EQ((uint8_t) 3, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]); EXPECT_EQ((uint8_t) 15, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 18, vcf.records[1].samples[0]["SUM_REV_COVG"][1]); delete idx; } TEST(LocalPRGTest, add_consensus_path_to_fastaq_bin) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three")); pn3->kmer_prg = l3.kmer_prg; pn3->kmer_prg.nodes[2]->covg[0] = 4; pn3->kmer_prg.nodes[2]->covg[1] = 3; pn3->kmer_prg.nodes[5]->covg[0] = 4; pn3->kmer_prg.nodes[5]->covg[0] = 5; pn3->kmer_prg.nodes[7]->covg[0] = 2; pn3->kmer_prg.nodes[7]->covg[1] = 3; pn3->kmer_prg.nodes[8]->covg[0] = 4; pn3->kmer_prg.nodes[8]->covg[0] = 6; pn3->kmer_prg.num_reads = 6; pn3->kmer_prg.set_p(0.0001); shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0)); pn3->reads.insert(pr); Fastaq fq(false, true); vector<KmerNodePtr> kmp; vector<LocalNodePtr> lmp; l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, true, 8); EXPECT_EQ("AGTTAT", l3.string_along_path(lmp)); bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end(); EXPECT_TRUE(added_to_fq); bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end(); EXPECT_TRUE(added_to_seqs); bool added_to_scores = fq.scores.find("three") != fq.scores.end(); EXPECT_TRUE(added_to_scores); bool added_to_headers = fq.headers.find("three") != fq.headers.end(); EXPECT_TRUE(added_to_headers); EXPECT_EQ("AGTTAT", fq.sequences["three"]); EXPECT_EQ(fq.scores["three"], "DDD\?\?!"); cout << fq << endl; } TEST(LocalPRGTest, add_consensus_path_to_fastaq_nbin) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three")); pn3->kmer_prg = l3.kmer_prg; pn3->kmer_prg.nodes[2]->covg[0] = 4; pn3->kmer_prg.nodes[2]->covg[1] = 3; pn3->kmer_prg.nodes[5]->covg[0] = 4; pn3->kmer_prg.nodes[5]->covg[0] = 5; pn3->kmer_prg.nodes[7]->covg[0] = 2; pn3->kmer_prg.nodes[7]->covg[1] = 3; pn3->kmer_prg.nodes[8]->covg[0] = 4; pn3->kmer_prg.nodes[8]->covg[0] = 6; pn3->kmer_prg.num_reads = 6; pn3->kmer_prg.set_nb(0.05, 2.0); shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0)); pn3->reads.insert(pr); Fastaq fq(false, true); vector<KmerNodePtr> kmp; vector<LocalNodePtr> lmp; l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, false, 8); EXPECT_EQ("AGTTAT", l3.string_along_path(lmp)); bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end(); EXPECT_TRUE(added_to_fq); bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end(); EXPECT_TRUE(added_to_seqs); bool added_to_scores = fq.scores.find("three") != fq.scores.end(); EXPECT_TRUE(added_to_scores); bool added_to_headers = fq.headers.find("three") != fq.headers.end(); EXPECT_TRUE(added_to_headers); EXPECT_EQ("AGTTAT", fq.sequences["three"]); EXPECT_EQ(fq.scores["three"], "DDD\?\?!"); cout << fq << endl; }
42.739302
790
0.636913
rffrancon
b18e06d0512c64b33691bc04dbdbad6eda9196a9
2,238
cpp
C++
BZOJ/2142/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/2142/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/2142/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define N 100010 #define mp make_pair #define pa pair<ll,ll> #define fi first #define se second using namespace std ; typedef long long ll; ll p,n,m,w[N]; ll prime[N],mod[N],cnt[N],a[N]; int tot; ll quick_my(ll a,ll b,ll M) { ll ret=1; while(b) { if(b&1)ret=(ret*a)%M; a=(a*a)%M; b>>=1; } return ret; } void exgcd(ll a,ll b,ll &x,ll &y,ll &gcd) { if(!b) { x=1,y=0,gcd=a; return ; } exgcd(b,a%b,x,y,gcd); ll t=y; y=x-a/b*y;x=t; } void get_factor(ll x) { for(int i=2;i*i<=x;i++) { if(x%i==0) { prime[++tot]=i,cnt[tot]=0,mod[tot]=1; while(x%i==0){x/=i,cnt[tot]++,mod[tot]*=i;} } } if(x>1)prime[++tot]=x,cnt[tot]=1,mod[tot]=x; } ll inverse(ll a,ll b) { ll xx,yy,d; exgcd(a,b,xx,yy,d); return (xx+b)%b; } pa fact(ll k,ll n) { if(n==0)return mp(0,1); int x=n/prime[k],y=n/mod[k]; ll ans=1; if(y) { for(int i=2;i<mod[k];i++) { if(i%prime[k]!=0)ans=(ans*i)%mod[k]; } ans=quick_my(ans,y,mod[k]); } for(int i=y*mod[k]+1;i<=n;i++) { if(i%prime[k]!=0)ans=ans*i%mod[k]; } pa tmp=fact(k,x); return mp(x+tmp.fi,ans*tmp.se%mod[k]); } ll calc(int k,ll n,ll m) { if(n<m)return 0; pa a=fact(k,n),b=fact(k,m),c=fact(k,n-m); return a.se%mod[k]*inverse(b.se,mod[k])%mod[k]*inverse(c.se,mod[k])%mod[k]*quick_my(prime[k],a.fi-b.fi-c.fi,mod[k])%mod[k]; } ll china() { ll gcd,y,x=0; for(int i=1;i<=tot;i++) { ll r=p/mod[i]; exgcd(mod[i],r,gcd,y,gcd); x=(x+r*y*a[i])%p; } return (x+p)%p; } ll work(ll n,ll m) { for(int i=1;i<=tot;i++) a[i]=calc(i,n,m); return china(); } int main() { freopen("code.in","r",stdin);freopen("std.out","w",stdout); scanf("%lld%lld%lld",&p,&n,&m); get_factor(p); int sum=0; for(int i=1;i<=m;i++)scanf("%lld",&w[i]),sum+=w[i]; if(sum>n){printf("Impossible\n");return 0;} ll ans=work(n,sum)%p; for(int i=1;i<=m;i++) { ans=ans*work(sum,w[i])%p; sum-=w[i]; } printf("%lld\n",ans); }
19.631579
127
0.488382
sjj118
b18fcce746bab43b072a0679baa95fdaebf8b77d
10,606
cpp
C++
ProjectEuler+/euler-0237.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0237.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0237.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
1
2021-05-28T11:14:34.000Z
2021-05-28T11:14:34.000Z
// //////////////////////////////////////////////////////// // # Title // Tours on a 4 x n playing board // // # URL // https://projecteuler.net/problem=237 // http://euler.stephan-brumme.com/237/ // // # Problem // Let `T(n)` be the number of tours over a `4 * n` playing board such that: // - The tour starts in the top left corner. // - The tour consists of moves that are up, down, left, or right one square. // - The tour visits each square exactly once. // - The tour ends in the bottom left corner. // // The diagram shows one tour over a `4 * 10` board: // // ![tour](p237.gif) // // `T(10)` is 2329. What is `T(10^12) mod 10^8`? // // # Solved by // Stephan Brumme // October 2017 // // # Algorithm // A nice problem that you can easily understand within a few seconds. But it took a few days to come up with a solution ... // // Of course I immediately wrote a ''bruteForce'' algorithm and it solves the `T(10)` case. Anything beyond that is impossible. // // The main realization was to split the whole board in its columns. // I identified 15 different columns (A - O) which can have a unique "flow" on their left and right border. // The term "flow" means the chronological way how a piece moves across the board. // // The arrows symbolize the "flow" in and out of a column while hash signs stand for "no border crossing": // // || 4 || 4 || 4 || 4 || 4 || // ||! A ++ B ++ C ++ D ++ E || // || ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ## || // || <== <== ++ <== ## ++ ## <== ++ <== <== ++ <== ## || // || ==> ==> ++ ==> ## ++ ## ==> ++ ==> ## ++ ==> ==> || // || <== <== ++ <== <== ++ <== <== ++ <== ## ++ <== <== || // // || 4 || 4 || 4 || 4 || 4 || // ||! F ++ G ++ H ++ I ++ J || // || ==> ==> ++ ## ==> ++ ==> ## ++ ## ==> ++ ==> ==> || // || <== <== ++ ## <== ++ ## ==> ++ ==> ## ++ <== ## || // || ## ==> ++ ==> ==> ++ ## <== ++ <== ## ++ ## ## || // || ## <== ++ <== <== ++ <== ## ++ ## <== ++ ## <== || // // || 4 || 4 || 4 || 4 || 4 || // ||! K ++ L ++ M ++ N ++ O || // || ==> ## ++ ==> ==> ++ ## ==> ++ ==> ## ++ ==> ## || // || ## ## ++ ## <== ++ ## ## ++ <== ## ++ ## ## || // || ## ==> ++ ## ## ++ ==> ## ++ ==> ## ++ ## ## || // || <== <== ++ <== ## ++ <== <== ++ <== ## ++ <== ## || // // Columns N and O can only be found at the right edge of the board. // // Unfortunately it's not sufficient to represent the flow by arrows because they are still ambigious: // there are three different chronological orders how the "flow" can pass through column A. // // If I look at each column's left and right border then there are just 6 patterns for these borders. // With a proper labelling of the flow's chronological order (indicated by 1,2,3,4 and a hash means "no crossing") I get 8 different borders: // // || 2 || 2 || 2 || 2 || 2 || 2 || 2 || 2 || // || 1 ++ 1 ++ 1 ++ # ++ # ++ 1 ++ 3 ++ # || // || # ++ 2 ++ 2 ++ 1 ++ # ++ 4 ++ 2 ++ # || // || # ++ # ++ 3 ++ 2 ++ 1 ++ 3 ++ 1 ++ # || // || 2 ++ # ++ 4 ++ # ++ 2 ++ 2 ++ 4 ++ # || // // The function ''fill()'' stores the borders of each column, e.g. column C is // ''neighbors.insert( { "1##2", "1234" } );'' // Trust me, getting all this stuff right was a lot of work: I made tons of mistakes ! // // I wrote two algorithms: a simple one that verifies `T(10)` and a much faster one to solve `T(10^12)`. // ''slow()'' linearly goes through all borders that are allowed on the right side of the current border and stops if it reaches the right side of the board. // Assuming that there are about 3 borders that are compatible in such a way, the routine analyzes `3^width` combinations. // There's no way it can solve `T(10^12)` - but I really needed this algorithm to get my borders right. // When the output finally matched the results of ''bruteForce'' I went on to write a faster (and more complex) algorithm. // // ''fast()'' is a divide-and-conquer approach: // - I treat a group of columns as a blackbox where I only knows its left and right border // - if I cut through this blackbox at an arbitrary point then any of the 8 borders could be found // - well, that's not quite right, since the 8th border is reserved for the right-most border of the board ==> only 7 borders "inside" the blackbox // - then the number of combinations of a blackbox is the product of its left and right half // - if I keep doing this until the blackbox contains only a single column then I check whether this type of column is valid // // This isn't much faster than what ''slow()'' does ... but when the blackbox becomes smaller, I process the same kinds of blackboxes over and over again. // Thus memoization drastically reduced the number of __different__ blackboxes. At the end, ''cache'' contains 3417 values. // // # Note // Even though the result is found within about 0.02 seconds, I felt that dividing each blackbox in the middle isn't optimal: // if I try to divide the blackbox in such a way that at least one half's size is a power of two (that means `2^i`) then ''cache'' contains only 2031 values. // Moreover, the program runs about 50% faster. // // Replacing the ''std::string'' by plain integers would be still faster but I think it would be much harder to understand the code. // // # Alternative // I was blown away by the simple solutions found by others: they discovered a relationship between `T(n)` and `T(n-1)`, ..., `T(n-4)`. // Incredible stuff - or maybe just looked up in OEIS A181688. #include <iostream> #include <set> #include <map> #include <vector> #include <tuple> // assuming that the route could exceed the left border I get these states for the left-most and right-most borders: typedef std::string Border; const Border LeftBorder = "1##2"; const Border RightBorder = "####"; // all possible borders that can be found inside the grid std::set<Border> borders; // define which borders can be next to each other std::set<std::pair<Border, Border>> neighbors; // set up the containers "borders" and "neighbors" void fill() { // the following lines are derived from my drawings above // left right column neighbors.insert( { "1234", "1234" } ); // A neighbors.insert( { "1432", "1432" } ); // A neighbors.insert( { "3214", "3214" } ); // A neighbors.insert( { "1432", "1##2" } ); // B neighbors.insert( { "3214", "1##2" } ); // B neighbors.insert( { "1##2", "1234" } ); // C neighbors.insert( { "1234", "12##" } ); // D neighbors.insert( { "1234", "##12" } ); // E neighbors.insert( { "12##", "1432" } ); // F neighbors.insert( { "##12", "3214" } ); // G neighbors.insert( { "1##2", "#12#" } ); // H neighbors.insert( { "#12#", "1##2" } ); // I neighbors.insert( { "12##", "1##2" } ); // J neighbors.insert( { "1##2", "##12" } ); // K neighbors.insert( { "1##2", "12##" } ); // L neighbors.insert( { "##12", "1##2" } ); // M neighbors.insert( { "1234", RightBorder } ); // N neighbors.insert( { "1##2", RightBorder } ); // O for (auto x : neighbors) borders.insert(x.first); } // fast search in O(log n) unsigned long long search(const Border& left, const Border& right, unsigned long long length, unsigned int modulo) { // reduced to a single column ? if (length == 1) // can these two borders be next to each other ? return neighbors.count(std::make_pair(left, right)); // memoize auto id = std::make_tuple(left, right, length); // I don't add "modulo" to the key to keep it simple static std::map<std::tuple<Border, Border, unsigned long long>, unsigned long long> cache; auto lookup = cache.find(id); if (lookup != cache.end()) return lookup->second; // split region into two parts: every possible border can be at the splitting point unsigned long long result = 0; for (const auto& next : borders) { // prefer a "power of two"-splitting, causes less states than splitting 50:50 unsigned long long pow2 = 1; while (pow2 < length / 2) pow2 *= 2; //pow2 = length / 2; // alternatively: less efficient 50:50 method // process left half auto leftHalf = search(left, next, pow2, modulo); // process right half auto rightHalf = search(next, right, length - pow2, modulo); // each left half can be combined with each right half auto combined = (leftHalf * rightHalf) % modulo; result += combined; } result %= modulo; cache[id] = result; return result; } // slow search, no caching whatsoever unsigned long long slow(const std::string& border, unsigned int length, unsigned int width, unsigned int modulo) { // walked across the whole board ? if (length == width) return (border == RightBorder) ? 1 : 0; // proceed with each border that is compatible to the current one unsigned long long result = 0; for (auto x : neighbors) if (x.first == border) result += slow(x.second, length + 1, width, modulo); return result % modulo; } // backtracking of possible paths, doesn't need the information about borders etc. typedef std::vector<std::vector<unsigned int>> Grid; unsigned int bruteForce(Grid& grid, unsigned int x, unsigned int y, unsigned int step) { // reached final position ? if (x == 0 && y == 3) return (step == grid.size() * grid[0].size()) ? 1 : 0; // take a step grid[x][y] = step; // try to search deeper in each direction unsigned int result = 0; if (x > 0 && grid[x - 1][y] == 0) result += bruteForce(grid, x - 1, y, step + 1); if (x + 1 < grid.size() && grid[x + 1][y] == 0) result += bruteForce(grid, x + 1, y, step + 1); if (y > 0 && grid[x][y - 1] == 0) result += bruteForce(grid, x, y - 1, step + 1); if (y < 3 && grid[x][y + 1] == 0) result += bruteForce(grid, x, y + 1, step + 1); // undo step grid[x][y] = 0; return result; } int main() { // set up borders and their relationships fill(); unsigned int modulo = 100000000; unsigned long long limit = 1000000000000; std::cin >> limit; //#define BRUTEFORCE #ifdef BRUTEFORCE // allocate memory Grid grid(limit); for (auto& column : grid) column.resize(4, 0); // start in upper left corner (0,0), that's the first step std::cout << bruteForce(grid, 0, 0, 1) << std::endl; #endif //#define SLOW #ifdef SLOW std::cout << slow(LeftBorder, 0, limit, modulo) << std::endl; #endif #define FAST #ifdef FAST std::cout << search(LeftBorder, RightBorder, limit, modulo) << std::endl; #endif return 0; }
40.326996
157
0.580898
sarvekash
b19083840d67f9ec00bca8cea9ad3c5d62a6e39c
409
cpp
C++
Source/FSD/Private/LevelGenerationCarver.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/LevelGenerationCarver.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/LevelGenerationCarver.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "LevelGenerationCarver.h" FLevelGenerationCarver::FLevelGenerationCarver() { this->MeshCarver = NULL; this->ConvexCarver = NULL; this->StaticMeshCarver = NULL; this->ConvexExpensiveNoise = 0.00f; this->CarveCellSize = CarveOptionsCellSize::CARVE_CELL_SIZE_25; this->TerrainMaterial = NULL; this->Filter = ECarveFilterType::ReplaceAll; this->ToBeDiscarded = false; }
29.214286
67
0.731051
trumank
b19372a16d8c3d42e0619dfaa01516cce0bde149
74,881
cc
C++
src/bin/dhcp6/tests/classify_unittests.cc
kphf1995cm/kea
2f6940ef5ed697f3f683035ed7a16046253add4d
[ "Apache-2.0" ]
null
null
null
src/bin/dhcp6/tests/classify_unittests.cc
kphf1995cm/kea
2f6940ef5ed697f3f683035ed7a16046253add4d
[ "Apache-2.0" ]
null
null
null
src/bin/dhcp6/tests/classify_unittests.cc
kphf1995cm/kea
2f6940ef5ed697f3f683035ed7a16046253add4d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2016-2019 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <dhcp/dhcp6.h> #include <dhcp/option.h> #include <dhcp/option_int.h> #include <dhcp/option_int_array.h> #include <dhcp/pkt6.h> #include <dhcp/tests/iface_mgr_test_config.h> #include <dhcp/opaque_data_tuple.h> #include <dhcp/option_string.h> #include <dhcp/option_vendor_class.h> #include <dhcp/option6_addrlst.h> #include <dhcp/tests/pkt_captures.h> #include <dhcpsrv/cfgmgr.h> #include <dhcp6/tests/dhcp6_test_utils.h> #include <dhcp6/tests/dhcp6_client.h> #include <asiolink/io_address.h> #include <stats/stats_mgr.h> #include <boost/pointer_cast.hpp> #include <string> using namespace isc; using namespace isc::asiolink; using namespace isc::dhcp; using namespace isc::dhcp::test; namespace { /// @brief Set of JSON configurations used by the classification unit tests. /// /// - Configuration 0: /// - Specifies 3 classes: 'router', 'reserved-class1' and 'reserved-class2'. /// - 'router' class is assigned when the client sends option 1234 (string) /// equal to 'foo'. /// - The other two classes are reserved for the client having /// DUID '01:02:03:04' /// - Class 'router' includes option 'ipv6-forwarding'. /// - Class 'reserved-class1' includes option DNS servers. /// - Class 'reserved-class2' includes option NIS servers. /// - All three options are sent when client has reservations for the /// 'reserved-class1', 'reserved-class2' and sends option 1234 with /// the 'foo' value. /// - There is one subnet specified 2001:db8:1::/48 with pool of /// IPv6 addresses. /// /// - Configuration 1: /// - Used for complex membership (example taken from HA) /// - 1 subnet: 2001:db8:1::/48 /// - 4 pools: 2001:db8:1:1::/64, 2001:db8:1:2::/64, /// 2001:db8:1:3::/64 and 2001:db8:1:4::/64 /// - 4 classes to compose: /// server1 and server2 for each HA server /// option 1234 'foo' aka telephones /// option 1234 'bar' aka computers /// /// - Configuration 2: /// - Used for complex membership (example taken from HA) and pd-pools /// - 1 subnet: 2001:db8::/32 /// - 4 pd-pools: 2001:db8:1::/48, 2001:db8:2::/48, /// 2001:db8:3::/48 and 2001:db8:4::/48 /// - 4 classes to compose: /// server1 and server2 for each HA server /// option 1234 'foo' aka telephones /// option 1234 'bar' aka computers /// /// - Configuration 3: /// - Used for the DROP class /// - 1 subnet: 2001:db8:1::/48 /// - 2 pool: 2001:db8:1:1::/64 /// - the following class defined: option 1234 'foo', DROP /// const char* CONFIGS[] = { // Configuration 0 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "}," "{" " \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"router\"," " \"test\": \"option[host-name].text == 'foo'\"," " \"option-data\": [" " {" " \"name\": \"ipv6-forwarding\", " " \"data\": \"true\"" " } ]" "}," "{" " \"name\": \"reserved-class1\"," " \"option-data\": [" " {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::50\"" " }" " ]" "}," "{" " \"name\": \"reserved-class2\"," " \"option-data\": [" " {" " \"name\": \"nis-servers\"," " \"data\": \"2001:db8:1::100\"" " }" " ]" "}" "]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"," " \"reservations\": [" " {" " \"duid\": \"01:02:03:04\"," " \"client-classes\": [ \"reserved-class1\", \"reserved-class2\" ]" " } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 1 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"server1\"" "}," "{" " \"name\": \"server2\"" "}," "{" " \"name\": \"telephones\"," " \"test\": \"option[host-name].text == 'foo'\"" "}," "{" " \"name\": \"computers\"," " \"test\": \"option[host-name].text == 'bar'\"" "}," "{" " \"name\": \"server1_and_telephones\"," " \"test\": \"member('server1') and member('telephones')\"" "}," "{" " \"name\": \"server1_and_computers\"," " \"test\": \"member('server1') and member('computers')\"" "}," "{" " \"name\": \"server2_and_telephones\"," " \"test\": \"member('server2') and member('telephones')\"" "}," "{" " \"name\": \"server2_and_computers\"," " \"test\": \"member('server2') and member('computers')\"" "}" "]," "\"subnet6\": [ " "{ \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"," " \"pools\": [ " " { \"pool\": \"2001:db8:1:1::/64\"," " \"client-class\": \"server1_and_telephones\" }," " { \"pool\": \"2001:db8:1:2::/64\"," " \"client-class\": \"server1_and_computers\" }," " { \"pool\": \"2001:db8:1:3::/64\"," " \"client-class\": \"server2_and_telephones\" }," " { \"pool\": \"2001:db8:1:4::/64\"," " \"client-class\": \"server2_and_computers\" } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 2 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"server1\"" "}," "{" " \"name\": \"server2\"" "}," "{" " \"name\": \"telephones\"," " \"test\": \"option[host-name].text == 'foo'\"" "}," "{" " \"name\": \"computers\"," " \"test\": \"option[host-name].text == 'bar'\"" "}," "{" " \"name\": \"server1_and_telephones\"," " \"test\": \"member('server1') and member('telephones')\"" "}," "{" " \"name\": \"server1_and_computers\"," " \"test\": \"member('server1') and member('computers')\"" "}," "{" " \"name\": \"server2_and_telephones\"," " \"test\": \"member('server2') and member('telephones')\"" "}," "{" " \"name\": \"server2_and_computers\"," " \"test\": \"member('server2') and member('computers')\"" "}" "]," "\"subnet6\": [ " "{ \"subnet\": \"2001:db8::/32\", " " \"interface\": \"eth1\"," " \"pd-pools\": [ " " { \"prefix\": \"2001:db8:1::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server1_and_telephones\" }," " { \"prefix\": \"2001:db8:2::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server1_and_computers\" }," " { \"prefix\": \"2001:db8:3::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server2_and_telephones\" }," " { \"prefix\": \"2001:db8:4::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server2_and_computers\" } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 3 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "}," "{" " \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"DROP\"," " \"test\": \"option[host-name].text == 'foo'\"" "}" "]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"" " } ]," "\"valid-lifetime\": 4000 }" }; /// @brief Test fixture class for testing client classification by the /// DHCPv6 server. /// /// @todo There are numerous tests not using Dhcp6Client class. They should be /// migrated to use it one day. class ClassifyTest : public Dhcpv6SrvTest { public: /// @brief Constructor. /// /// Sets up fake interfaces. ClassifyTest() : Dhcpv6SrvTest(), iface_mgr_test_config_(true) { } /// @brief Verify values of options returned by the server when the server /// uses configuration with index 0. /// /// @param config Reference to DHCP client's configuration received. /// @param ip_forwarding Expected value of IP forwarding option. This option /// is expected to always be present. /// @param dns_servers String holding an address carried within DNS /// servers option. If this value is empty, the option is expected to not /// be included in the response. /// @param nis_servers String holding an address carried within NIS /// servers option. If this value is empty, the option is expected to not /// be included in the response. void verifyConfig0Options(const Dhcp6Client::Configuration& config, const uint8_t ip_forwarding = 1, const std::string& dns_servers = "", const std::string& nis_servers = "") { // IP forwarding option should always exist. OptionPtr ip_forwarding_opt = config.findOption(2345); ASSERT_TRUE(ip_forwarding_opt); // The option comprises 2 bytes of option code, 2 bytes of option length, // and a single 1 byte value. This makes it 5 bytes of a total length. ASSERT_EQ(5, ip_forwarding_opt->len()); ASSERT_EQ(static_cast<int>(ip_forwarding), static_cast<int>(ip_forwarding_opt->getUint8())); // DNS servers. Option6AddrLstPtr dns_servers_opt = boost::dynamic_pointer_cast< Option6AddrLst>(config.findOption(D6O_NAME_SERVERS)); if (!dns_servers.empty()) { ASSERT_TRUE(dns_servers_opt); Option6AddrLst::AddressContainer addresses = dns_servers_opt->getAddresses(); // For simplicity, we expect only a single address. ASSERT_EQ(1, addresses.size()); EXPECT_EQ(dns_servers, addresses[0].toText()); } else { EXPECT_FALSE(dns_servers_opt); } // NIS servers. Option6AddrLstPtr nis_servers_opt = boost::dynamic_pointer_cast< Option6AddrLst>(config.findOption(D6O_NIS_SERVERS)); if (!nis_servers.empty()) { ASSERT_TRUE(nis_servers_opt); Option6AddrLst::AddressContainer addresses = nis_servers_opt->getAddresses(); // For simplicity, we expect only a single address. ASSERT_EQ(1, addresses.size()); EXPECT_EQ(nis_servers, addresses[0].toText()); } else { EXPECT_FALSE(nis_servers_opt); } } /// @brief Create a solicit Pkt6Ptr createSolicit(std::string remote_addr = "fe80::abcd") { OptionPtr clientid = generateClientId(); Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 1234)); query->setRemoteAddr(IOAddress(remote_addr)); query->addOption(clientid); query->setIface("eth1"); query->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); return (query); } /// @brief Interface Manager's fake configuration control. IfaceMgrTestConfig iface_mgr_test_config_; }; // Checks if DOCSIS client packets are classified properly TEST_F(ClassifyTest, docsisClientClassification) { NakedDhcpv6Srv srv(0); // Let's create a relayed SOLICIT. This particular relayed SOLICIT has // vendor-class set to docsis3.0 Pkt6Ptr sol1; ASSERT_NO_THROW(sol1 = PktCaptures::captureDocsisRelayedSolicit()); ASSERT_NO_THROW(sol1->unpack()); srv.classifyPacket(sol1); // It should belong to docsis3.0 class. It should not belong to eRouter1.0 EXPECT_TRUE(sol1->inClass("VENDOR_CLASS_docsis3.0")); EXPECT_FALSE(sol1->inClass("eRouter1.0")); // Let's get a relayed SOLICIT. This particular relayed SOLICIT has // vendor-class set to eRouter1.0 Pkt6Ptr sol2; ASSERT_NO_THROW(sol2 = PktCaptures::captureeRouterRelayedSolicit()); ASSERT_NO_THROW(sol2->unpack()); srv.classifyPacket(sol2); EXPECT_TRUE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "eRouter1.0")); EXPECT_FALSE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "docsis3.0")); } // Checks if client packets are classified properly using match expressions. // Note option names and definitions are used. TEST_F(ClassifyTest, matchClassification) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet Pkt6Ptr query1 = createSolicit(); Pkt6Ptr query2 = createSolicit(); Pkt6Ptr query3 = createSolicit(); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // Packets with the exception of the second should be in the router class EXPECT_TRUE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_TRUE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); // But only for the first query: second was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // But only for the first query: third has no ORO OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Check that only-if-required classes are not evaluated by classifyPacket TEST_F(ClassifyTest, required) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"only-if-required\": true, " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // No packet is in the router class EXPECT_FALSE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_FALSE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should do nothing OptionPtr opt1 = response1->getOption(2345); EXPECT_FALSE(opt1); OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Checks that when only-if-required classes are still evaluated TEST_F(ClassifyTest, requiredClassification) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"require-client-classes\": [ \"router\" ], " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"only-if-required\": true, " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // No packet is in the router class yet EXPECT_FALSE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_FALSE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); // But only for the first query: second was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // But only for the first query: third has no ORO OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Checks subnet options have the priority over class options TEST_F(ClassifyTest, subnetClassPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ] } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[1234].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks subnet options have the priority over global options TEST_F(ClassifyTest, subnetGlobalPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ] } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Global sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks class options have the priority over global options TEST_F(ClassifyTest, classGlobalPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // A global ipv6-forwarding option is set in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[1234].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, global to false/0 // Here class has the priority EXPECT_NE(0, opt->getUint8()); } // Checks class options have the priority over global persistent options TEST_F(ClassifyTest, classGlobalPersistency) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. // Note the persistency flag follows a "OR" semantic so to set // it to false (or to leave the default) has no effect. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\", " " \"always-send\": true } ], " "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\", " " \"always-send\": false } ] } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Do not add an ORO. OptionPtr oro = query->getOption(D6O_ORO); EXPECT_FALSE(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Global sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks if the client-class field is indeed used for subnet selection. // Note that packet classification is already checked in ClassifyTest // .*Classification above. TEST_F(ClassifyTest, clientClassifySubnet) { // This test configures 2 subnets. We actually only need the // first one, but since there's still this ugly hack that picks // the pool if there is only one, we must use more than one // subnet. That ugly hack will be removed in #3242, currently // under review. // The second subnet does not play any role here. The client's // IP address belongs to the first subnet, so only that first // subnet is being tested. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ]," " \"subnet\": \"2001:db8:1::/48\", " " \"client-class\": \"foo\" " " }, " " { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ]," " \"subnet\": \"2001:db8:2::/48\", " " \"client-class\": \"xyzzy\" " " } " "]," "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); Pkt6Ptr sol = createSolicit("2001:db8:1::3"); // This discover does not belong to foo class, so it will not // be serviced bool drop = false; EXPECT_FALSE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Let's add the packet to bar class and try again. sol->addClass("bar"); // Still not supported, because it belongs to wrong class. EXPECT_FALSE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Let's add it to matching class. sol->addClass("foo"); // This time it should work EXPECT_TRUE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); } // Checks if the client-class field is indeed used for pool selection. TEST_F(ClassifyTest, clientClassifyPool) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // This test configures 2 pools. // The second pool does not play any role here. The client's // IP address belongs to the first pool, so only that first // pool is being tested. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"client-classes\": [ " " { " " \"name\": \"foo\" " " }, " " { " " \"name\": \"bar\" " " } " "], " "\"subnet6\": [ " " { \"pools\": [ " " { " " \"pool\": \"2001:db8:1::/64\", " " \"client-class\": \"foo\" " " }, " " { " " \"pool\": \"2001:db8:2::/64\", " " \"client-class\": \"xyzzy\" " " } " " ], " " \"subnet\": \"2001:db8::/40\" " " } " "], " "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); Pkt6Ptr query1 = createSolicit("2001:db8:1::3"); Pkt6Ptr query2 = createSolicit("2001:db8:1::3"); Pkt6Ptr query3 = createSolicit("2001:db8:1::3"); // This discover does not belong to foo class, so it will not // be serviced srv.classifyPacket(query1); AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); ASSERT_TRUE(response1); OptionPtr ia_na1 = response1->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na1); EXPECT_TRUE(ia_na1->getOption(D6O_STATUS_CODE)); EXPECT_FALSE(ia_na1->getOption(D6O_IAADDR)); // Let's add the packet to bar class and try again. query2->addClass("bar"); // Still not supported, because it belongs to wrong class. srv.classifyPacket(query2); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); ASSERT_TRUE(response2); OptionPtr ia_na2 = response2->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na2); EXPECT_TRUE(ia_na2->getOption(D6O_STATUS_CODE)); EXPECT_FALSE(ia_na2->getOption(D6O_IAADDR)); // Let's add it to matching class. query3->addClass("foo"); // This time it should work srv.classifyPacket(query3); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); ASSERT_TRUE(response3); OptionPtr ia_na3 = response3->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na3); EXPECT_FALSE(ia_na3->getOption(D6O_STATUS_CODE)); EXPECT_TRUE(ia_na3->getOption(D6O_IAADDR)); } // Checks if the [UN]KNOWN built-in classes is indeed used for pool selection. TEST_F(ClassifyTest, clientClassifyPoolKnown) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // This test configures 2 pools. // The first one requires reservation, the second does the opposite. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ " " { " " \"pool\": \"2001:db8:1::/64\", " " \"client-class\": \"KNOWN\" " " }, " " { " " \"pool\": \"2001:db8:2::/64\", " " \"client-class\": \"UNKNOWN\" " " } " " ], " " \"subnet\": \"2001:db8::/40\", " " \"reservations\": [ " " { \"duid\": \"01:02:03:04\", \"hostname\": \"foo\" } ] " " } " "], " "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); OptionPtr clientid1 = generateClientId(); Pkt6Ptr query1 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("2001:db8:1::3")); query1->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); query1->addOption(clientid1); query1->setIface("eth1"); // First pool requires reservation so the second will be used srv.classifyPacket(query1); AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); ASSERT_TRUE(response1); OptionPtr ia_na1 = response1->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na1); EXPECT_FALSE(ia_na1->getOption(D6O_STATUS_CODE)); OptionPtr iaaddr1 = ia_na1->getOption(D6O_IAADDR); ASSERT_TRUE(iaaddr1); boost::shared_ptr<Option6IAAddr> addr1 = boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr1); ASSERT_TRUE(addr1); EXPECT_EQ("2001:db8:2::", addr1->getAddress().toText()); // Try with DUID 01:02:03:04 uint8_t duid[] = { 0x01, 0x02, 0x03, 0x04 }; OptionBuffer buf(duid, duid + sizeof(duid)); OptionPtr clientid2(new Option(Option::V6, D6O_CLIENTID, buf)); Pkt6Ptr query2 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 2345)); query2->setRemoteAddr(IOAddress("2001:db8:1::3")); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); query2->addOption(clientid2); query2->setIface("eth1"); // Now the first pool will be used srv.classifyPacket(query2); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); ASSERT_TRUE(response2); OptionPtr ia_na2 = response2->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na2); EXPECT_FALSE(ia_na2->getOption(D6O_STATUS_CODE)); OptionPtr iaaddr2 = ia_na2->getOption(D6O_IAADDR); ASSERT_TRUE(iaaddr2); boost::shared_ptr<Option6IAAddr> addr2 = boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr2); ASSERT_TRUE(addr2); EXPECT_EQ("2001:db8:1::", addr2->getAddress().toText()); } // Tests whether a packet with custom vendor-class (not erouter or docsis) // is classified properly. TEST_F(ClassifyTest, vendorClientClassification2) { NakedDhcpv6Srv srv(0); // Let's create a SOLICIT. Pkt6Ptr sol = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234)); sol->setRemoteAddr(IOAddress("2001:db8:1::3")); sol->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); OptionPtr clientid = generateClientId(); sol->addOption(clientid); // Now let's add a vendor-class with id=1234 and content "foo" OptionVendorClassPtr vendor_class(new OptionVendorClass(Option::V6, 1234)); OpaqueDataTuple tuple(OpaqueDataTuple::LENGTH_2_BYTES); tuple = "foo"; vendor_class->addTuple(tuple); sol->addOption(vendor_class); // Now the server classifies the packet. srv.classifyPacket(sol); // The packet should now belong to VENDOR_CLASS_foo. EXPECT_TRUE(sol->inClass(srv.VENDOR_CLASS_PREFIX + "foo")); // It should not belong to "foo" EXPECT_FALSE(sol->inClass("foo")); } // Checks if relay IP address specified in the relay-info structure can be // used together with client-classification. TEST_F(ClassifyTest, relayOverrideAndClientClass) { // This test configures 2 subnets. They both are on the same link, so they // have the same relay-ip address. Furthermore, the first subnet is // reserved for clients that belong to class "foo". std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ]," " \"subnet\": \"2001:db8:1::/48\", " " \"client-class\": \"foo\", " " \"relay\": { " " \"ip-address\": \"2001:db8:3::1\"" " }" " }, " " { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ]," " \"subnet\": \"2001:db8:2::/48\", " " \"relay\": { " " \"ip-address\": \"2001:db8:3::1\"" " }" " } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config)); // Let's get the subnet configuration objects const Subnet6Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll(); ASSERT_EQ(2, subnets->size()); // Let's get them for easy reference Subnet6Ptr subnet1 = (*subnets)[0]; Subnet6Ptr subnet2 = (*subnets)[1]; ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); Pkt6Ptr sol = createSolicit("2001:db8:1::3"); // Now pretend the packet came via one relay. Pkt6::RelayInfo relay; relay.linkaddr_ = IOAddress("2001:db8:3::1"); relay.peeraddr_ = IOAddress("fe80::1"); sol->relay_info_.push_back(relay); // This packet does not belong to class foo, so it should be rejected in // subnet[0], even though the relay-ip matches. It should be accepted in // subnet[1], because the subnet matches and there are no class // requirements. bool drop = false; EXPECT_TRUE(subnet2 == srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Now let's add this packet to class foo and recheck. This time it should // be accepted in the first subnet, because both class and relay-ip match. sol->addClass("foo"); EXPECT_TRUE(subnet1 == srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); } // This test checks that it is possible to specify static reservations for // client classes. TEST_F(ClassifyTest, clientClassesInHostReservations) { Dhcp6Client client; // Initially use a DUID for which there are no reservations. As a result, // the client should be assigned a single class "router". client.setDUID("01:02:03:05"); client.setInterface("eth1"); client.requestAddress(); // Request all options we may potentially get. Otherwise, the server will // not return them, even when the client is assigned to the classes for // which these options should be sent. client.requestOption(2345); client.requestOption(D6O_NAME_SERVERS); client.requestOption(D6O_NIS_SERVERS); ASSERT_NO_THROW(configure(CONFIGS[0], *client.getServer())); // Adding this option to the client's message will cause the client to // belong to the 'router' class. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Send a message to the server. ASSERT_NO_THROW(client.doSolicit(true)); // IP forwarding should be present, but DNS and NIS servers should not. ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_)); // Modify the DUID of our client to the one for which class reservations // have been made. client.setDUID("01:02:03:04"); ASSERT_NO_THROW(client.doSolicit(true)); // This time, the client should obtain options from all three classes. ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // This should also work for Request case. ASSERT_NO_THROW(client.doSARR()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Renew case. ASSERT_NO_THROW(client.doRenew()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Rebind case. ASSERT_NO_THROW(client.doRebind()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Confirm case. This must be before Information-request because the // client must have an address to confirm from one of the transactions // involving address assignment, i.e. Request, Renew or Rebind. ASSERT_NO_THROW(client.doConfirm()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Information-request case. ASSERT_NO_THROW(client.doInfRequest()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); } // Check classification using membership expressions. TEST_F(ClassifyTest, member) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"not-foo\", " " \"test\": \"not (option[host-name].text == 'foo')\"" "}," "{ \"name\": \"foo\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"not member('not-foo')\"" "}," "{ \"name\": \"bar\", " " \"test\": \"option[host-name].text == 'bar'\"" "}," "{ \"name\": \"baz\", " " \"test\": \"option[host-name].text == 'baz'\"" "}," "{ \"name\": \"barz\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " " \"test\": \"member('bar') or member('baz')\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); query3->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname1(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname1); query1->addOption(hostname1); OptionStringPtr hostname3(new OptionString(Option::V6, 1234, "baz")); ASSERT_TRUE(hostname3); query3->addOption(hostname3); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // Check classes EXPECT_FALSE(query1->inClass("not-foo")); EXPECT_TRUE(query1->inClass("foo")); EXPECT_FALSE(query1->inClass("bar")); EXPECT_FALSE(query1->inClass("baz")); EXPECT_FALSE(query1->inClass("barz")); EXPECT_TRUE(query2->inClass("not-foo")); EXPECT_FALSE(query2->inClass("foo")); EXPECT_FALSE(query2->inClass("bar")); EXPECT_FALSE(query2->inClass("baz")); EXPECT_FALSE(query2->inClass("barz")); EXPECT_TRUE(query3->inClass("not-foo")); EXPECT_FALSE(query3->inClass("foo")); EXPECT_FALSE(query3->inClass("bar")); EXPECT_TRUE(query3->inClass("baz")); EXPECT_TRUE(query3->inClass("barz")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); OptionCustomPtr ipf1 = boost::dynamic_pointer_cast<OptionCustom>(opt1); ASSERT_TRUE(ipf1); EXPECT_TRUE(ipf1->readBoolean()); // But not the second query which was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // The third has the option but with another value OptionPtr opt3 = response3->getOption(2345); EXPECT_TRUE(opt3); OptionCustomPtr ipf3 = boost::dynamic_pointer_cast<OptionCustom>(opt3); ASSERT_TRUE(ipf3); EXPECT_FALSE(ipf3->readBoolean()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceNone) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000," "\"renew-timer\": 1000," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); EXPECT_FALSE(opt); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedencePool) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::1", addrs[0].toText()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceSubnet) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"require-client-classes\": [ \"for-subnet\" ]," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::2", addrs[0].toText()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceNetwork) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"require-client-classes\": [ \"for-network\" ]," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"require-client-classes\": [ \"for-subnet\" ]," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::3", addrs[0].toText()); } // This test checks the complex membership from HA with server1 telephone. TEST_F(ClassifyTest, server1Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the first pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:1::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 computer. TEST_F(ClassifyTest, server1Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the second pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:2::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 telephone. TEST_F(ClassifyTest, server2Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the third pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:3::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 computer. TEST_F(ClassifyTest, server2Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the forth pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:4::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 telephone // with prefixes. TEST_F(ClassifyTest, pDserver1Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the first pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 computer // with prefix. TEST_F(ClassifyTest, pDserver1Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the second pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:2::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 telephone // with prefixes. TEST_F(ClassifyTest, pDserver2Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the third pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:3::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 computer // with prefix. TEST_F(ClassifyTest, pDserver2Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the forth pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:4::", lease_client.addr_.toText()); } // This test checks the handling for the DROP special class. TEST_F(ClassifyTest, dropClass) { Dhcp6Client client; client.setDUID("01:02:03:05"); client.setInterface("eth1"); client.requestAddress(); // Configure DHCP server. ASSERT_NO_THROW(configure(CONFIGS[3], *client.getServer())); // Send a message to the server. ASSERT_NO_THROW(client.doSolicit(true)); // No option: no drop. EXPECT_TRUE(client.getContext().response_); // Retry with an option matching the DROP class. Dhcp6Client client2; // Add the host-name option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); client2.addExtraOption(hostname); // Send a message to the server. ASSERT_NO_THROW(client2.doSolicit(true)); // Option, dropped. EXPECT_FALSE(client2.getContext().response_); // There should also be pkt6-receive-drop stat bumped up. stats::StatsMgr& mgr = stats::StatsMgr::instance(); stats::ObservationPtr drop_stat = mgr.getObservation("pkt6-receive-drop"); // This statistic must be present and must be set to 1. ASSERT_TRUE(drop_stat); EXPECT_EQ(1, drop_stat->getInteger().first); } } // end of anonymous namespace
35.287936
89
0.557071
kphf1995cm
b193e7449f191cfd9d8fdc0e3324ca49a5116f0f
4,010
cpp
C++
modules/tracktion_engine/plugins/tracktion_PluginWindowState.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
734
2018-11-16T09:39:40.000Z
2022-03-30T16:56:14.000Z
modules/tracktion_engine/plugins/tracktion_PluginWindowState.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
100
2018-11-16T18:04:08.000Z
2022-03-31T17:47:53.000Z
modules/tracktion_engine/plugins/tracktion_PluginWindowState.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
123
2018-11-16T15:51:50.000Z
2022-03-29T12:21:27.000Z
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { PluginWindowState::PluginWindowState (Edit& e) : edit (e), engine (e.engine), windowLocked (engine.getPluginManager().areGUIsLockedByDefault()) { } void PluginWindowState::deleteWindow() { pluginWindow.reset(); } void PluginWindowState::incRefCount() { TRACKTION_ASSERT_MESSAGE_THREAD ++windowShowerCount; startTimer (100); } void PluginWindowState::decRefCount() { TRACKTION_ASSERT_MESSAGE_THREAD --windowShowerCount; startTimer (100); } void PluginWindowState::showWindowExplicitly() { TRACKTION_ASSERT_MESSAGE_THREAD wasExplicitlyClosed = false; stopTimer(); showWindow(); } void PluginWindowState::closeWindowExplicitly() { TRACKTION_ASSERT_MESSAGE_THREAD if (pluginWindow && pluginWindow->isVisible()) { wasExplicitlyClosed = true; deleteWindow(); stopTimer(); } } bool PluginWindowState::isWindowShowing() const { return pluginWindow != nullptr && pluginWindow->isVisible(); } void PluginWindowState::recreateWindowIfShowing() { deleteWindow(); startTimer (100); } void PluginWindowState::hideWindowForShutdown() { deleteWindow(); stopTimer(); } void PluginWindowState::pickDefaultWindowBounds() { lastWindowBounds = { 100, 100, 600, 500 }; if (auto focused = juce::Component::getCurrentlyFocusedComponent()) lastWindowBounds.setPosition (focused->getTopLevelComponent()->getPosition() + juce::Point<int> (80, 80)); } void PluginWindowState::showWindow() { if (! pluginWindow) { // Ensure at least 40px of the window is on screen const auto displayRects = [] { RectangleList<int> trimmedDisplays; for (auto rect : Desktop::getInstance().getDisplays().getRectangleList (true)) trimmedDisplays.addWithoutMerging (rect.withTrimmedLeft (100).withTrimmedRight (100).withTrimmedBottom (100)); return trimmedDisplays; }(); const bool windowBoundsIsOnScreen = displayRects.intersectsRectangle (lastWindowBounds); if (lastWindowBounds.isEmpty() || ! windowBoundsIsOnScreen) pickDefaultWindowBounds(); WeakReference<Component> oldFocus (Component::getCurrentlyFocusedComponent()); pluginWindow = engine.getUIBehaviour().createPluginWindow (*this); if (oldFocus != nullptr) oldFocus->grabKeyboardFocus(); } if (pluginWindow) { windowOpenTime = Time::getCurrentTime(); pluginWindow->setVisible (true); pluginWindow->toFront (false); } } void PluginWindowState::pluginClicked (const MouseEvent& e) { bool isShowing = isWindowShowing(); if (e.getNumberOfClicks() >= 2) { if ((Time::getCurrentTime() - windowOpenTime).inMilliseconds() < 300) return; if (isShowing) closeWindowExplicitly(); else showWindowExplicitly(); } else if (! (isShowing || engine.getPluginManager().doubleClickToOpenWindows())) { showWindowExplicitly(); } } void PluginWindowState::timerCallback() { stopTimer(); if (windowShowerCount > 0) { if ((pluginWindow == nullptr || ! pluginWindow->isVisible()) && ! (engine.getPluginManager().doubleClickToOpenWindows() || wasExplicitlyClosed)) showWindow(); } else if (! windowLocked) { deleteWindow(); } } }
25.379747
126
0.599501
adamnemecek
b19679891ba7a9d5c215a23e01d926e4afd07437
6,982
cpp
C++
admin/activec/conui/evtsink.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/conui/evtsink.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/conui/evtsink.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: evtsink.cpp // //-------------------------------------------------------------------------- #include "stdafx.h" #include "winnls.h" #include "AMC.h" #include "AMCDoc.h" #include "AMCView.h" #include "histlist.h" #include "exdisp.h" // for the IE dispatch interfaces. #include "websnk.h" #include "evtsink.h" #include "WebCtrl.h" #include "cstr.h" #include "constatbar.h" #ifdef DBG CTraceTag tagWebEventSink(TEXT("Web View"), TEXT("Web Event Sink")); #endif // DBG CWebEventSink::CWebEventSink() : m_bBrowserBackEnabled(false), m_bBrowserForwardEnabled(false), m_pWebViewControl(NULL), m_pStatusBar(NULL), m_pwndProgressCtrl(NULL), m_pHistoryList(NULL) { } SC CWebEventSink::ScInitialize(CAMCWebViewCtrl *pWebViewControl) { DECLARE_SC(sc, TEXT("CWebEventSink::ScInitialize")); sc = ScCheckPointers(pWebViewControl); if(sc) return sc; m_pWebViewControl = pWebViewControl; CAMCView* pAMCView = dynamic_cast<CAMCView*>(pWebViewControl->GetParent()); CFrameWnd* pwndParentFrame = pWebViewControl->GetParentFrame(); sc = ScCheckPointers(pAMCView, pwndParentFrame); if(sc) return sc; m_pHistoryList = pAMCView->GetHistoryList(); sc = ScCheckPointers(m_pHistoryList); if(sc) return sc; // Create the status bar for this instance of the web control m_pStatusBar = dynamic_cast<CConsoleStatusBar*>(pwndParentFrame); sc = ScCheckPointers(m_pStatusBar, E_UNEXPECTED); if(sc) return sc; // find the progress control on the status bar for the parent frame CAMCStatusBar* pwndStatusBar = reinterpret_cast<CAMCStatusBar*>(pwndParentFrame->GetMessageBar()); sc = ScCheckPointers(pwndStatusBar); if(sc) return sc; ASSERT_KINDOF (CAMCStatusBar, pwndStatusBar); m_pwndProgressCtrl = pwndStatusBar->GetStatusProgressCtrlHwnd(); m_fLastTextWasEmpty = false; return sc; } CWebEventSink::~CWebEventSink() { /* * clear the status bar text */ if (m_pStatusBar != NULL) m_pStatusBar->ScSetStatusText(NULL); } void CWebEventSink::SetActiveTo(BOOL /*bState*/) { } STDMETHODIMP_(void) CWebEventSink::BeforeNavigate(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Cancel) { Trace(tagWebEventSink, TEXT("BeginNavigate(URL:%s, flags:%0X, targetfrm:%s, headers:%s)\n"), URL, Flags, TargetFrameName, Headers); bool bPageBreak = IsPageBreak(URL); m_pHistoryList->OnPageBreakStateChange(bPageBreak); m_pHistoryList->UpdateWebBar (HB_STOP, TRUE); // turn on "stop" button } STDMETHODIMP_(void) CWebEventSink::CommandStateChange(int Command, VARIANT_BOOL Enable) { if(Command == CSC_NAVIGATEFORWARD) { m_bBrowserForwardEnabled = Enable; } else if(Command == CSC_NAVIGATEBACK) { m_bBrowserBackEnabled = Enable; } } STDMETHODIMP_(void) CWebEventSink::DownloadBegin() { Trace(tagWebEventSink, TEXT("DownloadBegin()")); } STDMETHODIMP_(void) CWebEventSink::DownloadComplete() { Trace(tagWebEventSink, TEXT("DownloadComplete()")); } STDMETHODIMP_(void) CWebEventSink::FrameBeforeNavigate(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Cancel) { m_pHistoryList->UpdateWebBar (HB_STOP, TRUE); // turn on "stop" button } STDMETHODIMP_(void) CWebEventSink::FrameNavigateComplete(BSTR URL) { } STDMETHODIMP_(void) CWebEventSink::FrameNewWindow(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Processed) { } bool CWebEventSink::IsPageBreak(BSTR URL) { USES_CONVERSION; CStr strURL = OLE2T(URL); strURL.MakeLower(); bool bPageBreak = (_tcsstr(strURL, PAGEBREAK_URL) != NULL); return bPageBreak; } STDMETHODIMP_(void) CWebEventSink::NavigateComplete(BSTR URL) { Trace(tagWebEventSink, TEXT("NavigateComplete()\n")); // Set progress bar position to 0 m_pwndProgressCtrl->SetPos (0); bool bPageBreak = IsPageBreak(URL); m_pHistoryList->OnPageBreakStateChange(bPageBreak); // send the browser state across AFTER sending the OnPageBreakStateChange and BEFORE // the OnPageBreak. m_pHistoryList->OnBrowserStateChange(m_bBrowserForwardEnabled, m_bBrowserBackEnabled); if(bPageBreak) { // Extract the Page Break ID. Since bPageBreak is true, the URL // is guaranteed to be prefixed with PAGEBREAK_URL USES_CONVERSION; LPCTSTR szPageBreakID = OLE2CT(URL) + _tcslen(PAGEBREAK_URL); int nPageBreakID = _tstoi(szPageBreakID); //PageBreakIDs start with 1; _tstoi returns 0 if it can't convert ASSERT(nPageBreakID != 0); m_pHistoryList->ScOnPageBreak(nPageBreakID); } } STDMETHODIMP_(void) CWebEventSink::NewWindow(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, BSTR Referrer) { } STDMETHODIMP_(void) CWebEventSink::Progress(long Progress, long ProgressMax) { Trace(tagWebEventSink, TEXT("Progress(Progress:%ld ProgressMax:%ld)\n"), Progress, ProgressMax); // display progress only if the web view is visible. if(m_pWebViewControl && m_pWebViewControl->IsWindowVisible()) { m_pwndProgressCtrl->SetRange (0, ProgressMax); m_pwndProgressCtrl->SetPos (Progress); } // maintain "stop" button m_pHistoryList->UpdateWebBar (HB_STOP, ProgressMax != 0); } STDMETHODIMP_(void) CWebEventSink::PropertyChange(BSTR szProperty) { } STDMETHODIMP_(void) CWebEventSink::Quit(VARIANT_BOOL* pCancel) { Trace(tagWebEventSink, TEXT("Quit()")); } STDMETHODIMP_(void) CWebEventSink::StatusTextChange(BSTR bstrText) { // display progress only if the web view is visible. if(m_pWebViewControl && m_pWebViewControl->IsWindowVisible()) { bool fThisTextIsEmpty = ((bstrText == NULL) || (bstrText[0] == 0)); if (m_fLastTextWasEmpty && fThisTextIsEmpty) return; m_fLastTextWasEmpty = fThisTextIsEmpty; Trace(tagWebEventSink, TEXT("StatusTextChange(%s)"), bstrText); USES_CONVERSION; m_pStatusBar->ScSetStatusText(W2T( bstrText)); } } STDMETHODIMP_(void) CWebEventSink::TitleChange(BSTR Text) { Trace(tagWebEventSink, TEXT("TitleChange(%s)"), Text); } STDMETHODIMP_(void) CWebEventSink::WindowActivate() { } STDMETHODIMP_(void) CWebEventSink::WindowMove() { } STDMETHODIMP_(void) CWebEventSink::WindowResize() { }
28.153226
136
0.65984
npocmaka
b196e57f1237f15db988464f02b0ea45981686b9
1,842
cpp
C++
src/BufferedInsert.cpp
slate6715/GN_Utilities
642f8dfadef06073320e38deab614a7807e3d332
[ "MIT" ]
null
null
null
src/BufferedInsert.cpp
slate6715/GN_Utilities
642f8dfadef06073320e38deab614a7807e3d332
[ "MIT" ]
null
null
null
src/BufferedInsert.cpp
slate6715/GN_Utilities
642f8dfadef06073320e38deab614a7807e3d332
[ "MIT" ]
null
null
null
/* * File: BufferedInsert.cpp * Author: root * * Created on October 3, 2012, 2:06 PM */ #ifdef _WIN32 #include "stdafx.h" #endif #include "BufferedInsert.h" #include <memory> namespace util { BufferedInsert::BufferedInsert(DBase &conn, const char *preface, const char *postface) : _conn(conn) , _preface(preface) , _postface(postface) { buf_size = BUFFER_SIZE; count = 0; _buf.reserve(buf_size * 50); _buf = preface; } BufferedInsert::BufferedInsert(const BufferedInsert& orig): _conn(orig._conn) , _preface(orig._preface) , _postface(orig._postface) , _buf(orig._buf) , buf_size(orig.buf_size) { } BufferedInsert::~BufferedInsert(void) { } bool BufferedInsert::insertValues(const char *values) { if (count != 0) _buf += ", "; _buf += values; count++; if (count > buf_size) flush(); return true; } bool BufferedInsert::insertValues(std::string &values) { if (count != 0) _buf += ", "; _buf += values; count++; if (count > buf_size) flush(); return true; } void BufferedInsert::flush() { if (!_conn.isConnected()) throw DBException("BufferedInsert Flush: Database connection not established."); if (count == 0) return; if (_postface.length() > 0) _buf += _postface; std::unique_ptr<util::Query> stmt = _conn.getQueryObj(); *stmt << _buf; stmt->execUpdate(); _buf.clear(); _buf.reserve(buf_size * 50); // a guess on the size of each value string _buf = _preface; count = 0; } } // namespace util
22.463415
89
0.536374
slate6715
b19d8b5d5db7db1a5fe9772b7b5f697865047fbd
540
cpp
C++
templates/window.cpp
qaqwqaqwq-0/YGP
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
[ "MIT" ]
5
2020-12-07T08:58:24.000Z
2021-03-22T08:21:16.000Z
templates/window.cpp
qaqwqaqwq-0/YGP
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
[ "MIT" ]
null
null
null
templates/window.cpp
qaqwqaqwq-0/YGP
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
[ "MIT" ]
2
2021-01-26T07:45:52.000Z
2021-02-14T15:54:54.000Z
#define YGP_DISABLE_BROOM #define YGP_DISABLE_DEMENTOR #define YGP_DISABLE_BROWSER #define YGP_DISABLE_PLAYER #include"../include/ygp.hpp" YGP_INIT YGP_WNDPROC { static window win; YGP_BEGIN_MSG_MAP case WM_CREATE: { win=hwnd; break; } case WM_DESTROY: { PostQuitMessage(0); break; } YGP_END_MSG_MAP return 0; } YGP_WINMAIN { YGP_TRY YGP_REGCLS("YGPWindowClass") window win("YGPWindowClass","Caption"); messageloop(); YGP_CATCH_MSGBOX }
17.419355
47
0.648148
qaqwqaqwq-0
b19eea6d8ecb650cbabc95346422e7358cabed79
138
cpp
C++
TextRPG/Source/Random.cpp
DanDanCool/TextRPG
f3404a6f1b4590909b37a4c61211527276462738
[ "Apache-2.0" ]
1
2021-01-07T14:33:22.000Z
2021-01-07T14:33:22.000Z
TextRPG/Source/Random.cpp
DanDanCool/TextRPG
f3404a6f1b4590909b37a4c61211527276462738
[ "Apache-2.0" ]
2
2020-05-15T22:20:54.000Z
2020-05-24T06:49:52.000Z
TextRPG/Source/Random.cpp
DanDanCool/TextRPG
f3404a6f1b4590909b37a4c61211527276462738
[ "Apache-2.0" ]
null
null
null
#include "Random.h" std::mt19937 Random::s_RandomEngine; std::uniform_int_distribution<std::mt19937::result_type> Random::s_Distribution;
34.5
80
0.811594
DanDanCool
b1a1ca02efd4919326c503aedc371115c9c08ec4
1,675
cpp
C++
src/cm/cf/func/SdeFFunction.cpp
ukjhsa/ADEF
ce9e16d6a0f40558860a222b20065297f1a1c8fb
[ "MIT" ]
null
null
null
src/cm/cf/func/SdeFFunction.cpp
ukjhsa/ADEF
ce9e16d6a0f40558860a222b20065297f1a1c8fb
[ "MIT" ]
8
2015-12-03T10:21:21.000Z
2019-02-20T11:20:57.000Z
src/cm/cf/func/SdeFFunction.cpp
ukjhsa/ADEF
ce9e16d6a0f40558860a222b20065297f1a1c8fb
[ "MIT" ]
null
null
null
#include <memory> #include <vector> #include <string> #include <any> #include "cm/cf/func/SdeFFunction.h" #include "cm/ControlledObject.h" #include "Configuration.h" #include "PrototypeManager.h" #include "Individual.h" namespace adef { void SdeFFunction::setup(const Configuration & config, const PrototypeManager & pm) { auto rand_config = config.get_config("rand"); auto rand = make_and_setup_type<BaseFunction>(rand_config, pm); rand->set_function_name("rand"); add_function(rand); parameters_.resize(config.get_uint_value("number_of_parameters")); } SdeFFunction::Object SdeFFunction::generate() { Object diff = 0; auto size = parameters_.size(); for (decltype(size) idx = 1; idx < size; idx += 2) { diff += parameters_.at(idx) - parameters_.at(idx + 1); } return parameters_.at(0) + get_function("rand")->generate() * diff; } bool SdeFFunction::record(const std::vector<std::any>& params, const std::string & name) { if (params.size() == parameters_.size()) { for (decltype(params.size()) idx = 0; idx < params.size(); ++idx) { parameters_.at(idx) = std::any_cast<Object>(params.at(idx)); } } else { throw std::logic_error("SdeFFunction accept wrong parameters."); } return true; } bool SdeFFunction::record(const std::vector<std::any>& params, std::shared_ptr<const Individual> parent, std::shared_ptr<const Individual> offspring, const std::string & name) { return record(params, name); } void SdeFFunction::update() { get_function("rand")->update(); } unsigned int SdeFFunction::number_of_parameters() const { return parameters_.size(); } }
27.016129
175
0.677612
ukjhsa
b1a2d077d8855870818295a1e8d1726cabebfba3
13,989
cc
C++
chrome/browser/page_info_model.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
1
2019-04-23T15:57:04.000Z
2019-04-23T15:57:04.000Z
chrome/browser/page_info_model.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/page_info_model.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "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 "chrome/browser/page_info_model.h" #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/i18n/time_formatting.h" #include "base/string16.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/page_info_model_observer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/ssl_error_info.h" #include "content/public/browser/cert_store.h" #include "content/public/common/ssl_status.h" #include "content/public/common/url_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/cert_status_flags.h" #include "net/base/ssl_cipher_suite_names.h" #include "net/base/ssl_connection_status_flags.h" #include "net/base/x509_certificate.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" using content::SSLStatus; PageInfoModel::PageInfoModel(Profile* profile, const GURL& url, const SSLStatus& ssl, bool show_history, PageInfoModelObserver* observer) : observer_(observer) { Init(); if (url.SchemeIs(chrome::kChromeUIScheme)) { sections_.push_back( SectionInfo(ICON_STATE_INTERNAL_PAGE, string16(), l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE), SECTION_INFO_INTERNAL_PAGE)); return; } SectionStateIcon icon_id = ICON_STATE_OK; string16 headline; string16 description; scoped_refptr<net::X509Certificate> cert; // Identity section. string16 subject_name(UTF8ToUTF16(url.host())); bool empty_subject_name = false; if (subject_name.empty()) { subject_name.assign( l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); empty_subject_name = true; } if (ssl.cert_id && content::CertStore::GetInstance()->RetrieveCert(ssl.cert_id, &cert) && (!net::IsCertStatusError(ssl.cert_status) || net::IsCertStatusMinorError(ssl.cert_status))) { // There are no major errors. Check for minor errors. if (net::IsCertStatusMinorError(ssl.cert_status)) { string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName())); if (issuer_name.empty()) { issuer_name.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); } description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name)); description += ASCIIToUTF16("\n\n"); if (ssl.cert_status & net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) { description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION); } else if (ssl.cert_status & net::CERT_STATUS_NO_REVOCATION_MECHANISM) { description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM); } else { NOTREACHED() << "Need to specify string for this warning"; } icon_id = ICON_STATE_WARNING_MINOR; } else if (ssl.cert_status & net::CERT_STATUS_IS_EV) { // EV HTTPS page. DCHECK(!cert->subject().organization_names.empty()); headline = l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE, UTF8ToUTF16(cert->subject().organization_names[0]), UTF8ToUTF16(url.host())); // An EV Cert is required to have a city (localityName) and country but // state is "if any". DCHECK(!cert->subject().locality_name.empty()); DCHECK(!cert->subject().country_name.empty()); string16 locality; if (!cert->subject().state_or_province_name.empty()) { locality = l10n_util::GetStringFUTF16( IDS_PAGEINFO_ADDRESS, UTF8ToUTF16(cert->subject().locality_name), UTF8ToUTF16(cert->subject().state_or_province_name), UTF8ToUTF16(cert->subject().country_name)); } else { locality = l10n_util::GetStringFUTF16( IDS_PAGEINFO_PARTIAL_ADDRESS, UTF8ToUTF16(cert->subject().locality_name), UTF8ToUTF16(cert->subject().country_name)); } DCHECK(!cert->subject().organization_names.empty()); description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV, UTF8ToUTF16(cert->subject().organization_names[0]), locality, UTF8ToUTF16(cert->issuer().GetDisplayName()))); } else if (ssl.cert_status & net::CERT_STATUS_IS_DNSSEC) { // DNSSEC authenticated page. if (empty_subject_name) headline.clear(); // Don't display any title. else headline.assign(subject_name); description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, UTF8ToUTF16("DNSSEC"))); } else { // Non-EV OK HTTPS page. if (empty_subject_name) headline.clear(); // Don't display any title. else headline.assign(subject_name); string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName())); if (issuer_name.empty()) { issuer_name.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); } description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name)); } } else { // HTTP or HTTPS with errors (not warnings). description.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY)); icon_id = ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED ? ICON_STATE_WARNING_MAJOR : ICON_STATE_ERROR; const string16 bullet = UTF8ToUTF16("\n • "); std::vector<SSLErrorInfo> errors; SSLErrorInfo::GetErrorsForCertStatus(ssl.cert_id, ssl.cert_status, url, &errors); for (size_t i = 0; i < errors.size(); ++i) { description += bullet; description += errors[i].short_description(); } if (ssl.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) { description += ASCIIToUTF16("\n\n"); description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME); } } sections_.push_back(SectionInfo( icon_id, headline, description, SECTION_INFO_IDENTITY)); // Connection section. // We consider anything less than 80 bits encryption to be weak encryption. // TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and // weakly encrypted connections. icon_id = ICON_STATE_OK; headline.clear(); description.clear(); if (!ssl.cert_id) { // Not HTTPS. DCHECK_EQ(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED); icon_id = ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED ? ICON_STATE_WARNING_MAJOR : ICON_STATE_ERROR; description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT, subject_name)); } else if (ssl.security_bits < 0) { // Security strength is unknown. Say nothing. icon_id = ICON_STATE_ERROR; } else if (ssl.security_bits == 0) { DCHECK_NE(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED); icon_id = ICON_STATE_ERROR; description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT, subject_name)); } else if (ssl.security_bits < 80) { icon_id = ICON_STATE_ERROR; description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT, subject_name)); } else { description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT, subject_name, base::IntToString16(ssl.security_bits))); if (ssl.content_status) { bool ran_insecure_content = !!(ssl.content_status & SSLStatus::RAN_INSECURE_CONTENT); icon_id = ran_insecure_content ? ICON_STATE_ERROR : ICON_STATE_WARNING_MINOR; description.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK, description, l10n_util::GetStringUTF16(ran_insecure_content ? IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR : IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING))); } } uint16 cipher_suite = net::SSLConnectionStatusToCipherSuite(ssl.connection_status); if (ssl.security_bits > 0 && cipher_suite) { int ssl_version = net::SSLConnectionStatusToVersion(ssl.connection_status); const char* ssl_version_str; net::SSLVersionToString(&ssl_version_str, ssl_version); description += ASCIIToUTF16("\n\n"); description += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION, ASCIIToUTF16(ssl_version_str)); bool did_fallback = (ssl.connection_status & net::SSL_CONNECTION_VERSION_FALLBACK) != 0; bool no_renegotiation = (ssl.connection_status & net::SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION) != 0; const char *key_exchange, *cipher, *mac; net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, cipher_suite); description += ASCIIToUTF16("\n\n"); description += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS, ASCIIToUTF16(cipher), ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange)); description += ASCIIToUTF16("\n\n"); uint8 compression_id = net::SSLConnectionStatusToCompression(ssl.connection_status); if (compression_id) { const char* compression; net::SSLCompressionToString(&compression, compression_id); description += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_COMPRESSION_DETAILS, ASCIIToUTF16(compression)); } else { description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_NO_COMPRESSION); } if (did_fallback) { // For now, only SSL/TLS version fallback will trigger a warning icon. if (icon_id < ICON_STATE_WARNING_MINOR) icon_id = ICON_STATE_WARNING_MINOR; description += ASCIIToUTF16("\n\n"); description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_FALLBACK_MESSAGE); } if (no_renegotiation) { description += ASCIIToUTF16("\n\n"); description += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_RENEGOTIATION_MESSAGE); } } if (!description.empty()) { sections_.push_back(SectionInfo( icon_id, headline, description, SECTION_INFO_CONNECTION)); } // Request the number of visits. HistoryService* history = profile->GetHistoryService( Profile::EXPLICIT_ACCESS); if (show_history && history) { history->GetVisibleVisitCountToHost( url, &request_consumer_, base::Bind(&PageInfoModel::OnGotVisitCountToHost, base::Unretained(this))); } if (ssl.cert_id) { certificate_label_ = l10n_util::GetStringUTF16( IDS_PAGEINFO_CERT_INFO_BUTTON); } } PageInfoModel::~PageInfoModel() {} int PageInfoModel::GetSectionCount() { return sections_.size(); } PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) { DCHECK(index < static_cast<int>(sections_.size())); return sections_[index]; } gfx::Image* PageInfoModel::GetIconImage(SectionStateIcon icon_id) { if (icon_id == ICON_NONE) return NULL; // The bubble uses new, various icons. return icons_[icon_id]; } void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle, bool found_visits, int count, base::Time first_visit) { if (!found_visits) { // This indicates an error, such as the page wasn't http/https; do nothing. return; } bool visited_before_today = false; if (count) { base::Time today = base::Time::Now().LocalMidnight(); base::Time first_visit_midnight = first_visit.LocalMidnight(); visited_before_today = (first_visit_midnight < today); } string16 headline = l10n_util::GetStringUTF16(IDS_PAGE_INFO_SITE_INFO_TITLE); if (!visited_before_today) { sections_.push_back(SectionInfo( ICON_STATE_WARNING_MAJOR, headline, l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY), SECTION_INFO_FIRST_VISIT)); } else { sections_.push_back(SectionInfo( ICON_STATE_INFO, headline, l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY, base::TimeFormatShortDate(first_visit)), SECTION_INFO_FIRST_VISIT)); } observer_->OnPageInfoModelChanged(); } string16 PageInfoModel::GetCertificateLabel() const { return certificate_label_; } PageInfoModel::PageInfoModel() : observer_(NULL) { Init(); } void PageInfoModel::Init() { // Loads the icons into the vector. The order must match the SectionStateIcon // enum. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_GOOD)); icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_WARNING_MINOR)); icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_WARNING_MAJOR)); icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_BAD)); icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_INFO)); icons_.push_back(&rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_26)); }
37.706199
79
0.691972
1065672644894730302
b1a62eafc01aafb7f991ddbf2d86af8a305701f3
1,428
cpp
C++
Source/GravityGun/GravityGunCameraShake.cpp
jSplunk/GravityGun
1157d876a6a6b9843602171781c52b12e7e2dd69
[ "Apache-2.0" ]
null
null
null
Source/GravityGun/GravityGunCameraShake.cpp
jSplunk/GravityGun
1157d876a6a6b9843602171781c52b12e7e2dd69
[ "Apache-2.0" ]
null
null
null
Source/GravityGun/GravityGunCameraShake.cpp
jSplunk/GravityGun
1157d876a6a6b9843602171781c52b12e7e2dd69
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "GravityGunCameraShake.h" void UGravityGunCameraShake::SetRotPitch(float Amplitude, float Frequency) { //Setting new values for the roational pitch of the oscillation RotPitch.Amplitude = Amplitude; RotPitch.Frequency = Frequency; RotOscillation.Pitch = RotPitch; } void UGravityGunCameraShake::SetRotYaw(float Amplitude, float Frequency) { //Setting new values for the roational yaw of the oscillation RotYaw.Amplitude = Amplitude; RotYaw.Frequency = Frequency; RotOscillation.Pitch = RotYaw; } UGravityGunCameraShake::UGravityGunCameraShake() { //Default values being applied for both pitch and yaw rotational oscillation RotPitch.Amplitude = 1.0f; RotPitch.Frequency = FMath::RandRange(15.0f, 50.0f); RotYaw.Amplitude = 1.0f; RotYaw.Frequency = FMath::RandRange(15.0f, 50.0f); RotOscillation.Pitch = RotPitch; RotOscillation.Yaw = RotYaw; //Setting the duration of the oscillation OscillationDuration = .5f; } void UGravityGunCameraShake::PlayShake(APlayerCameraManager* Camera, float Scale, ECameraAnimPlaySpace::Type InPlaySpace, FRotator UserPlaySpaceRot) { Super::PlayShake(Camera, Scale, InPlaySpace, UserPlaySpaceRot); } void UGravityGunCameraShake::UpdateAndApplyCameraShake(float DeltaTime, float Alpha, FMinimalViewInfo& InOutPOV) { Super::UpdateAndApplyCameraShake(DeltaTime, Alpha, InOutPOV); }
29.142857
148
0.794118
jSplunk
b1a70972281a31d591aede137638cb0761a8f267
1,272
cc
C++
cc/test-bezier-gradient.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
cc/test-bezier-gradient.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
cc/test-bezier-gradient.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
#include "acmacs-base/argv.hh" #include "acmacs-base/color-gradient.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } argument<str> color1{*this, arg_name{"color1"}, mandatory}; argument<str> color2{*this, arg_name{"color2"}, mandatory}; argument<str> color3{*this, arg_name{"color3"}, mandatory}; argument<size_t> output_size{*this, arg_name{"output-size"}, mandatory}; }; int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); const Color c1{*opt.color1}, c2{*opt.color2}, c3{*opt.color3}; const auto result = acmacs::color::bezier_gradient(c1, c2, c3, opt.output_size); for (const auto& color : result) fmt::print("{:X}\n", color); } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
31.8
129
0.556604
acorg
b1a74ba2798aa83b8e00fb35def02c352a7183dd
5,756
cc
C++
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
eglrp/maplab-note
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
[ "Apache-2.0" ]
2
2020-12-25T07:00:18.000Z
2022-03-15T14:35:59.000Z
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
eglrp/maplab-note
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
[ "Apache-2.0" ]
null
null
null
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
eglrp/maplab-note
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
[ "Apache-2.0" ]
1
2020-06-09T04:07:33.000Z
2020-06-09T04:07:33.000Z
#include <aslam/cameras/distortion-fisheye.h> namespace aslam { std::ostream& operator<<(std::ostream& out, const FisheyeDistortion& distortion) { distortion.printParameters(out, std::string("")); return out; } FisheyeDistortion::FisheyeDistortion(const Eigen::VectorXd& dist_coeffs) : Base(dist_coeffs, Distortion::Type::kFisheye) { CHECK(distortionParametersValid(dist_coeffs)) << dist_coeffs.transpose(); } void FisheyeDistortion::distortUsingExternalCoefficients(const Eigen::VectorXd* dist_coeffs, Eigen::Vector2d* point, Eigen::Matrix2d* out_jacobian) const { CHECK_NOTNULL(point); // Use internal params if dist_coeffs==nullptr if(!dist_coeffs) dist_coeffs = &distortion_coefficients_; CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!"; const double& w = (*dist_coeffs)(0); const double r_u = point->norm(); const double r_u_cubed = r_u * r_u * r_u; const double tanwhalf = tan(w / 2.); const double tanwhalfsq = tanwhalf * tanwhalf; const double atan_wrd = atan(2. * tanwhalf * r_u); double r_rd; if (w * w < 1e-5) { // Limit w > 0. r_rd = 1.0; } else { if (r_u * r_u < 1e-5) { // Limit r_u > 0. r_rd = 2. * tanwhalf / w; } else { r_rd = atan_wrd / (r_u * w); } } const double& u = (*point)(0); const double& v = (*point)(1); // If Jacobian calculation is requested. if (out_jacobian) { out_jacobian->resize(2, 2); if (w * w < 1e-5) { out_jacobian->setIdentity(); } else if (r_u * r_u < 1e-5) { out_jacobian->setIdentity(); // The coordinates get multiplied by an expression not depending on r_u. *out_jacobian *= (2. * tanwhalf / w); } else { const double duf_du = (atan_wrd) / (w * r_u) - (u * u * atan_wrd) / (w * r_u_cubed) + (2 * u * u * tanwhalf) / (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1)); const double duf_dv = (2 * u * v * tanwhalf) / (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1)) - (u * v * atan_wrd) / (w * r_u_cubed); const double dvf_du = (2 * u * v * tanwhalf) / (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1)) - (u * v * atan_wrd) / (w * r_u_cubed); const double dvf_dv = (atan_wrd) / (w * r_u) - (v * v * atan_wrd) / (w * r_u_cubed) + (2 * v * v * tanwhalf) / (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1)); *out_jacobian << duf_du, duf_dv, dvf_du, dvf_dv; } } *point *= r_rd; } void FisheyeDistortion::distortParameterJacobian(const Eigen::VectorXd* dist_coeffs, const Eigen::Vector2d& point, Eigen::Matrix<double, 2, Eigen::Dynamic>* out_jacobian) const { CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!"; CHECK_NOTNULL(out_jacobian); const double& w = (*dist_coeffs)(0); const double tanwhalf = tan(w / 2.); const double tanwhalfsq = tanwhalf * tanwhalf; const double r_u = point.norm(); const double atan_wrd = atan(2. * tanwhalf * r_u); const double& u = point(0); const double& v = point(1); out_jacobian->resize(2, kNumOfParams); if (w * w < 1e-5) { out_jacobian->setZero(); } else if (r_u * r_u < 1e-5) { out_jacobian->setOnes(); *out_jacobian *= (w - sin(w)) / (w * w * cos(w / 2) * cos(w / 2)); } else { const double dxd_d_w = (2 * u * (tanwhalfsq / 2 + 0.5)) / (w * (4 * tanwhalfsq * r_u * r_u + 1)) - (u * atan_wrd) / (w * w * r_u); const double dyd_d_w = (2 * v * (tanwhalfsq / 2 + 0.5)) / (w * (4 * tanwhalfsq * r_u * r_u + 1)) - (v * atan_wrd) / (w * w * r_u); *out_jacobian << dxd_d_w, dyd_d_w; } } void FisheyeDistortion::undistortUsingExternalCoefficients(const Eigen::VectorXd& dist_coeffs, Eigen::Vector2d* point) const { CHECK_NOTNULL(point); CHECK_EQ(dist_coeffs.size(), kNumOfParams) << "dist_coeffs: invalid size!"; const double& w = dist_coeffs(0); double mul2tanwby2 = tan(w / 2.0) * 2.0; // Calculate distance from point to center. double r_d = point->norm(); if (mul2tanwby2 == 0 || r_d == 0) { return; } // Calculate undistorted radius of point. double r_u; if (fabs(r_d * w) <= kMaxValidAngle) { r_u = tan(r_d * w) / (r_d * mul2tanwby2); } else { return; } (*point) *= r_u; } bool FisheyeDistortion::areParametersValid(const Eigen::VectorXd& parameters) { // Check the vector size. if (parameters.size() != kNumOfParams) return false; // Expect w to have sane magnitude. double w = parameters(0); bool valid = std::abs(w) < 1e-16 || (w >= kMinValidW && w <= kMaxValidW); LOG_IF(INFO, !valid) << "Invalid w parameter: " << w << ", expected w in [" << kMinValidW << ", " << kMaxValidW << "]."; return valid; } bool FisheyeDistortion::distortionParametersValid(const Eigen::VectorXd& dist_coeffs) const { return areParametersValid(dist_coeffs); } void FisheyeDistortion::printParameters(std::ostream& out, const std::string& text) const { const Eigen::VectorXd& distortion_coefficients = getParameters(); CHECK_EQ(distortion_coefficients.size(), kNumOfParams) << "dist_coeffs: invalid size!"; out << text << std::endl; out << "Distortion: (FisheyeDistortion) " << std::endl; out << " w: " << distortion_coefficients(0) << std::endl; } } // namespace aslam
33.271676
112
0.567582
eglrp
b1a8297f4924bbbdd9f1bc4267fa25a0152f6ebc
15,640
cc
C++
tests/unit/regression/lars_unittest.cc
shiyi001/shogun
287f02d11d5914ded2d410ab9c6f38712e11ca2b
[ "BSD-3-Clause" ]
1
2020-03-29T18:28:09.000Z
2020-03-29T18:28:09.000Z
tests/unit/regression/lars_unittest.cc
shiyi001/shogun
287f02d11d5914ded2d410ab9c6f38712e11ca2b
[ "BSD-3-Clause" ]
null
null
null
tests/unit/regression/lars_unittest.cc
shiyi001/shogun
287f02d11d5914ded2d410ab9c6f38712e11ca2b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Parijat Mazumdar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <gtest/gtest.h> #include <shogun/features/DenseFeatures.h> #include <shogun/lib/SGMatrix.h> #include <shogun/regression/LeastAngleRegression.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/mathematics/eigen3.h> #include <shogun/mathematics/linalg/LinalgNamespace.h> #include <shogun/preprocessor/PruneVarSubMean.h> #include <shogun/preprocessor/NormOne.h> using namespace Eigen; using namespace shogun; //Generate the Data that N is greater than D void generate_data_n_greater_d(SGMatrix<float64_t> &data, SGVector<float64_t> &lab) { data(0,0)=0.044550005575722; data(1,0)=-0.433969606728583; data(2,0)=-0.397935396933392; data(0,1)=-0.778754072066602; data(1,1)=-0.620105076569903; data(2,1)=-0.542538248707627; data(0,2)=0.334313094513960; data(1,2)=0.421985645755003; data(2,2)=0.263031426076997; data(0,3)=0.516043376162584; data(1,3)=0.159041471773470; data(2,3)=0.691318725364356; data(0,4)=-0.116152404185664; data(1,4)=0.473047565770014; data(2,4)=-0.013876505800334; lab[0]=-0.196155100498902; lab[1]=-5.376485285422094; lab[2]=-1.717489351713958; lab[3]=4.506538567065213; lab[4]=2.783591170569741; } //Generate the Data that N is less than D void generate_data_n_less_d(SGMatrix<float64_t> &data, SGVector<float64_t> &lab) { data(0,0)=0.217778502400306; data(1,0)=0.660755393455389; data(2,0)=0.492143169178889; data(3,0)=0.668618163874328; data(4,0)=0.806098163441828; data(0,1)=-0.790379818206924; data(1,1)=-0.745771163834136; data(2,1)=-0.810293460958058; data(3,1)=-0.740156729710306; data(4,1)=-0.515540473266151; data(0,2)=0.572601315806618; data(1,2)=0.085015770378747; data(2,2)=0.318150291779169; data(3,2)=0.071538565835978; data(4,2)=-0.290557690175677; lab[0]=3.771471612608209; lab[1]=-3.218048715328546; lab[2]=-0.553422897279663; } TEST(LeastAngleRegression, lasso_n_greater_than_d) { SGMatrix<float64_t> data(3,5); SGVector<float64_t> lab(5); generate_data_n_greater_d(data, lab); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(); lars->set_labels((CLabels*) labels); lars->train(features); SGVector<float64_t> active3=SGVector<float64_t>(lars->get_w_for_var(3)); SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2)); SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1)); float64_t epsilon=0.000000000001; EXPECT_NEAR(active3[0],2.911072069591,epsilon); EXPECT_NEAR(active3[1],1.290672330338,epsilon); EXPECT_NEAR(active3[2],2.208741384416,epsilon); EXPECT_NEAR(active2[0],1.747958837898,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],1.840553057519,epsilon); EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.092594219621,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); } TEST(LeastAngleRegression, lasso_n_less_than_d) { SGMatrix<float64_t> data(5,3); SGVector<float64_t> lab(3); generate_data_n_less_d(data,lab); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(); lars->set_labels(labels); lars->train(features); SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2)); SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1)); float64_t epsilon=0.000000000001; EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.000000000000,epsilon); EXPECT_NEAR(active1[3],0.039226231353,epsilon); EXPECT_NEAR(active1[4],0.000000000000,epsilon); EXPECT_NEAR(active2[0],0.000000000000,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],0.000000000000,epsilon); EXPECT_NEAR(active2[3],2.578863294056,epsilon); EXPECT_NEAR(active2[4],2.539637062702,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); } TEST(LeastAngleRegression, lars_n_greater_than_d) { SGMatrix<float64_t> data(3,5); SGVector<float64_t> lab(5); generate_data_n_greater_d(data, lab); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(false); lars->set_labels((CLabels*) labels); lars->train(features); SGVector<float64_t> active3=SGVector<float64_t>(lars->get_w_for_var(3)); SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2)); SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1)); float64_t epsilon=0.000000000001; EXPECT_NEAR(active3[0],2.911072069591,epsilon); EXPECT_NEAR(active3[1],1.290672330338,epsilon); EXPECT_NEAR(active3[2],2.208741384416,epsilon); EXPECT_NEAR(active2[0],1.747958837898,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],1.840553057519,epsilon); EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.092594219621,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); } TEST(LeastAngleRegression, lars_n_less_than_d) { SGMatrix<float64_t> data(5,3); SGVector<float64_t> lab(3); generate_data_n_less_d(data,lab); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(false); lars->set_labels(labels); lars->train(features); SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2)); SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1)); float64_t epsilon=0.000000000001; EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.000000000000,epsilon); EXPECT_NEAR(active1[3],0.039226231353,epsilon); EXPECT_NEAR(active1[4],0.000000000000,epsilon); EXPECT_NEAR(active2[0],0.000000000000,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],0.000000000000,epsilon); EXPECT_NEAR(active2[3],2.578863294056,epsilon); EXPECT_NEAR(active2[4],2.539637062702,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); } template <typename ST> void lars_n_less_than_d_feature_test_templated() { SGMatrix<float64_t> data_64(5,3); SGVector<float64_t> lab(3); generate_data_n_less_d(data_64,lab); //copy data_64 into a ST SGMatrix SGMatrix<ST> data(5,3); for(index_t c = 0; c < data_64.num_cols; ++c) for(index_t r = 0; r < data_64.num_rows; ++r) data(r, c) = (ST) data_64(r, c); CDenseFeatures<ST>* features = new CDenseFeatures<ST>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(false); SG_REF(lars) lars->set_labels(labels); //Catch exceptions thrown when training, clean up try { lars->train(features); } catch(...) { SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); throw; } SGVector<float64_t> active2 = lars->get_w_for_var(2); SGVector<float64_t> active1 = lars->get_w_for_var(1); float64_t epsilon=0.0001; EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.000000000000,epsilon); EXPECT_NEAR(active1[3],0.039226231353,epsilon); EXPECT_NEAR(active1[4],0.000000000000,epsilon); EXPECT_NEAR(active2[0],0.000000000000,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],0.000000000000,epsilon); EXPECT_NEAR(active2[3],2.578863294056,epsilon); EXPECT_NEAR(active2[4],2.539637062702,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); } TEST(LeastAngleRegression, lars_template_test_bool) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<bool>()); } TEST(LeastAngleRegression, lars_template_test_char) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<char>()); } TEST(LeastAngleRegression, lars_template_test_int8) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int8_t>()); } TEST(LeastAngleRegression, lars_template_test_unit8) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint8_t>()); } TEST(LeastAngleRegression, lars_template_test_int16) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int16_t>()); } TEST(LeastAngleRegression, lars_template_test_uint16) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint16_t>()); } TEST(LeastAngleRegression, lars_template_test_int32) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int32_t>()); } TEST(LeastAngleRegression, lars_template_test_uint32) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint32_t>()); } TEST(LeastAngleRegression, lars_template_test_int64) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int64_t>()); } TEST(LeastAngleRegression, lars_template_test_uint64) { EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint64_t>()); } TEST(LeastAngleRegression, lars_template_test_float32) { lars_n_less_than_d_feature_test_templated<float32_t>(); } TEST(LeastAngleRegression, lars_template_test_float64) { lars_n_less_than_d_feature_test_templated<float64_t>(); } TEST(LeastAngleRegression, lars_template_test_floatmax) { lars_n_less_than_d_feature_test_templated<floatmax_t>(); } #ifndef USE_VIENNACL_GLOBAL TEST(LeastAngleRegression, cholesky_insert) { class lars_helper: public CLeastAngleRegression { public: SGMatrix<float64_t> cholesky_insert_helper(const SGMatrix<float64_t>& X, const SGMatrix<float64_t>& X_active, SGMatrix<float64_t>& R, int32_t i, int32_t n) { return CLeastAngleRegression::cholesky_insert<float64_t>(X, X_active, R, i, n); } }; int32_t num_feats=5, num_vec=6; SGMatrix<float64_t> R(num_feats, num_feats); SGMatrix<float64_t> mat(num_vec, num_feats-1); SGMatrix<float64_t> matnew(num_vec, num_feats); SGVector<float64_t> vec(num_vec); vec.random(0.0,1.0); Map<VectorXd> map_vec(vec.vector, vec.size()); for (index_t i=0; i<num_vec; i++) { for (index_t j=0; j<num_feats-1; j++) { mat(i,j)=CMath::random(0.0,1.0); matnew(i,j)=mat(i,j); } } for (index_t i=0 ; i<num_vec; i++) matnew(i, num_feats-1)=vec[i]; Map<MatrixXd> mat_old(mat.matrix, num_vec, num_feats-1); Map<MatrixXd> mat_new(matnew.matrix, num_vec, num_feats); Map<MatrixXd> map_R(R.matrix, num_feats, num_feats); MatrixXd XX=mat_old.transpose()*mat_old; // Compute matrix R which has to be updated SGMatrix<float64_t> R_old=linalg::cholesky_factor(SGMatrix<float64_t>(XX), false); // Update cholesky decomposition matrix R lars_helper lars; SGMatrix<float64_t> R_new = lars.cholesky_insert_helper(matnew, mat, R_old, 4, 4); Map<MatrixXd> map_R_new(R_new.matrix, R_new.num_rows, R_new.num_cols); // Compute true cholesky decomposition MatrixXd XX_new=mat_new.transpose()*mat_new; SGMatrix<float64_t> R_true=linalg::cholesky_factor(SGMatrix<float64_t>(XX_new), false); Map<MatrixXd> map_R_true(R_true.matrix, num_feats, num_feats); EXPECT_NEAR((map_R_true - map_R_new).norm(), 0.0, 1E-12); } TEST(LeastAngleRegression, ols_equivalence) { int32_t n_feat=25, n_vec=100; SGMatrix<float64_t> data(n_feat, n_vec); for (index_t i=0; i<n_feat; i++) { for (index_t j=0; j<n_vec; j++) data(i,j)=CMath::random(0.0,1.0); } SGVector<float64_t> lab=SGVector<float64_t>(n_vec); lab.random(0.0,1.0); float64_t mean=linalg::mean(lab); for (index_t i=0; i<lab.size(); i++) lab[i]-=mean; auto features = some<CDenseFeatures<float64_t>>(data); auto proc1 = some<CPruneVarSubMean>(); auto proc2 = some<CNormOne>(); proc1->fit(features); features = wrap(proc1->transform(features)->as<CDenseFeatures<float64_t>>()); proc2->fit(features); features = wrap(proc2->transform(features)->as<CDenseFeatures<float64_t>>()); auto labels = some<CRegressionLabels>(lab); auto lars = some<CLeastAngleRegression>(false); lars->set_labels((CLabels*) labels); lars->train(features); // Full LAR model SGVector<float64_t> w=lars->get_w(); Map<VectorXd> map_w(w.vector, w.size()); SGMatrix<float64_t> mat=features->get_feature_matrix(); Map<MatrixXd> feat(mat.matrix, mat.num_rows, mat.num_cols); Map<VectorXd> l(lab.vector, lab.size()); // OLS #if EIGEN_WITH_TRANSPOSITION_BUG MatrixXd feat_t = feat.transpose().eval(); VectorXd solve=feat_t.colPivHouseholderQr().solve(l); #else VectorXd solve=feat.transpose().colPivHouseholderQr().solve(l); #endif // Check if full LAR model is equivalent to OLS EXPECT_EQ( w.size(), n_feat); EXPECT_NEAR( (map_w - solve).norm(), 0.0, 1E-12); } #endif TEST(LeastAngleRegression, early_stop_l1_norm) { SGMatrix<float64_t> data(3,5); SGVector<float64_t> lab(5); generate_data_n_greater_d(data, lab); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); SG_REF(features); CRegressionLabels* labels=new CRegressionLabels(lab); SG_REF(labels); CLeastAngleRegression* lars=new CLeastAngleRegression(false); lars->set_labels((CLabels*) labels); // set max l1 norm lars->set_max_l1_norm(1); lars->train(features); SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2)); SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1)); float64_t epsilon=0.000000000001; EXPECT_NEAR(active2[0],0.453702890189,epsilon); EXPECT_NEAR(active2[1],0.000000000000,epsilon); EXPECT_NEAR(active2[2],0.546297109810,epsilon); EXPECT_NEAR(active1[0],0.000000000000,epsilon); EXPECT_NEAR(active1[1],0.000000000000,epsilon); EXPECT_NEAR(active1[2],0.092594219621,epsilon); SG_UNREF(lars); SG_UNREF(features); SG_UNREF(labels); }
31.405622
88
0.77257
shiyi001
b1afc8a8d08db2792989acf9ba24e88993e6c627
5,945
cpp
C++
src/imgui_glfw.cpp
pperehozhih/imgui_glfw
726549cbec2b754dbbd0afdfecc23e60c015378f
[ "Apache-2.0" ]
null
null
null
src/imgui_glfw.cpp
pperehozhih/imgui_glfw
726549cbec2b754dbbd0afdfecc23e60c015378f
[ "Apache-2.0" ]
null
null
null
src/imgui_glfw.cpp
pperehozhih/imgui_glfw
726549cbec2b754dbbd0afdfecc23e60c015378f
[ "Apache-2.0" ]
null
null
null
#ifdef __EMSCRIPTEN__ #include <emscripten.h> #define GL_GLEXT_PROTOTYPES #define EGL_EGLEXT_PROTOTYPES #else extern "C" { #include "examples/libs/gl3w/GL/gl3w.c" } #define IMGUI_IMPL_OPENGL_LOADER_CUSTOM "examples/libs/gl3w/GL/gl3w.h" #endif #include "backends/imgui_impl_opengl3.cpp" #include "backends/imgui_impl_glfw.cpp" #include "misc/cpp/imgui_stdlib.cpp" #include "misc/freetype/imgui_freetype.cpp" #include "imgui.h" #include "imgui-glfw.h" #include <map> namespace ImGui { namespace GLFW { int g_UnloadTextureInterval = 1; std::map<void*, std::pair<int, ImTextureID>> g_TexturesCache; GLuint GetNativeTexture(const GLFWimage& texture) { auto&& found = g_TexturesCache.find(texture.pixels); GLuint gl_texture = 0; if (found != g_TexturesCache.end()) { found->second.first = g_UnloadTextureInterval; gl_texture = (GLuint)(intptr_t)found->second.second; return gl_texture; } glGenTextures(1, &gl_texture); glBindTexture(GL_TEXTURE_2D, gl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef GL_UNPACK_ROW_LENGTH glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.pixels); glBindTexture(GL_TEXTURE_2D, gl_texture); g_TexturesCache[texture.pixels] = std::make_pair(g_UnloadTextureInterval, (ImTextureID)(intptr_t)gl_texture); return gl_texture; } bool Init(GLFWwindow* window) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); #ifdef __EMSCRIPTEN__ const char* glsl_version = "#version 100"; #elif __APPLE__ // GL 3.2 + GLSL 150 const char* glsl_version = "#version 150"; #else // GL 3.0 + GLSL 130 const char* glsl_version = "#version 130"; #endif #ifdef __EMSCRIPTEN__ bool err = false; #else bool err = gl3wInit() != 0; #endif if (err) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return false; } if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) { fprintf(stderr, "Failed to initialize imgui OpenGL!\n"); return false; } if (!ImGui_ImplOpenGL3_Init(glsl_version)) { fprintf(stderr, "Failed to initialize imgui!\n"); return false; } return true; } void UpdateFontTexture() { if (g_FontTexture) { ImGui_ImplOpenGL3_DestroyFontsTexture(); } ImGui_ImplOpenGL3_CreateFontsTexture(); } void NewFrame() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); } void Render(GLFWwindow* window) { ImGui::Render(); int display_w, display_h; glfwGetFramebufferSize(window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); auto&& texture = g_TexturesCache.begin(); while (texture != g_TexturesCache.end()) { texture->second.first--; if (texture->second.first < 0) { GLuint gl_texture = (GLuint)(intptr_t)texture->second.second; glDeleteTextures(1, &gl_texture); texture = g_TexturesCache.erase(texture); } else { ++texture; } } } void Shutdown() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } void SetTextureUnloadInterval(int updateCount) { g_UnloadTextureInterval = updateCount; } } // Image overloads void Image(const GLFWimage& texture, const glm::vec4& tintColor, const glm::vec4& borderColor) { Image(texture, glm::vec2(texture.width, texture.height), tintColor, borderColor); } void Image(const GLFWimage& texture, const glm::vec2& size, const glm::vec4& tintColor, const glm::vec4& borderColor) { ImTextureID textureID = (ImTextureID)GLFW::GetNativeTexture(texture); ImGui::Image(textureID, size, ImVec2(0, 0), ImVec2(1, 1), tintColor, borderColor); } // ImageButton overloads bool ImageButton(const GLFWimage& texture, const int framePadding, const glm::vec4& bgColor, const glm::vec4& tintColor) { return ImageButton(texture, glm::vec2(texture.width, texture.height), framePadding, bgColor, tintColor); } bool ImageButton(const GLFWimage& texture, const glm::vec2& size, const int framePadding, const glm::vec4& bgColor, const glm::vec4& tintColor) { ImTextureID textureID = (ImTextureID)GLFW::GetNativeTexture(texture); return ImGui::ImageButton(textureID, size, ImVec2(0, 0), ImVec2(1, 1), framePadding, bgColor, tintColor); } // Draw_list overloads. All positions are in relative coordinates (relative to top-left of the current window) void DrawLine(const glm::vec2& a, const glm::vec2& b, const glm::vec4& col, float thickness) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); glm::vec2 pos = ImGui::GetCursorScreenPos(); draw_list->AddLine(a + pos, b + pos, ColorConvertFloat4ToU32(col), thickness); } }
36.697531
129
0.600673
pperehozhih
b1b4136da617904151dcb1a541b979ff21f674c6
665
cpp
C++
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_8/Lesson 8.3 Pointer Reassignment to Another Variable.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_8/Lesson 8.3 Pointer Reassignment to Another Variable.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_8/Lesson 8.3 Pointer Reassignment to Another Variable.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; int main () { cout << endl; //Extra space cout << "__________________________________________________________" << endl; cout << "Lesson 8.3 Pointer Reassignment to Another Variable" << endl; cout << "----------------------------------------------------------" << endl; int Age = 30; int* pInteger = &Age; cout << "pInteger points to Age now " << endl; //Display the value of the Pointer cout << "pInteger is " << hex << pInteger << endl; int DogsAge = 9; pInteger = &DogsAge; cout << "pInteger points to DogsAge now " << endl; cout << "pInteger is " << hex << pInteger << endl; return 0; }
25.576923
79
0.581955
mccrudd3n
b1b8d020689258d84b1b020b3d6eedf5e355817a
3,246
hpp
C++
SeeingMachinesVisualization/SeeingMachinesProject/faceAPISensorCommercial/SFML/include/SFML/System/Randomizer.hpp
dgerding/Construct
ecbb0ee5591a89e71906ad676bc6684583716d84
[ "MIT" ]
1
2016-03-14T16:02:04.000Z
2016-03-14T16:02:04.000Z
vs2010/include/SFML/System/Randomizer.hpp
mfichman/cs248-sfml-template
a8d286d48343ece7fb8292d52e45db09866024ea
[ "Zlib" ]
null
null
null
vs2010/include/SFML/System/Randomizer.hpp
mfichman/cs248-sfml-template
a8d286d48343ece7fb8292d52e45db09866024ea
[ "Zlib" ]
null
null
null
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_RANDOMIZER_HPP #define SFML_RANDOMIZER_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Config.hpp> namespace sf { //////////////////////////////////////////////////////////// /// Randomizer is an utility class for generating pseudo-random /// numbers //////////////////////////////////////////////////////////// class SFML_API Randomizer { public : //////////////////////////////////////////////////////////// /// Set the seed for the generator. Using a known seed /// allows you to reproduce the same sequence of random number /// /// \param Seed : Number to use as the seed /// //////////////////////////////////////////////////////////// static void SetSeed(unsigned int Seed); //////////////////////////////////////////////////////////// /// Get the seed used to generate random numbers the generator. /// /// \return Current seed /// //////////////////////////////////////////////////////////// static unsigned int GetSeed(); //////////////////////////////////////////////////////////// /// Get a random float number in a given range /// /// \return Start : Start of the range /// \return End : End of the range /// /// \return Random number in [Begin, End] /// //////////////////////////////////////////////////////////// static float Random(float Begin, float End); //////////////////////////////////////////////////////////// /// Get a random integer number in a given range /// /// \return Start : Start of the range /// \return End : End of the range /// /// \return Random number in [Begin, End] /// //////////////////////////////////////////////////////////// static int Random(int Begin, int End); private : //////////////////////////////////////////////////////////// // Static member variables //////////////////////////////////////////////////////////// static unsigned int ourSeed; }; } // namespace sf #endif // SFML_RANDOMIZER_HPP
34.168421
101
0.469193
dgerding
b1bd5b16e7ed13b229a7b98dfd0ea1fa98e1c305
3,911
cpp
C++
Kernel/Heap.cpp
Archlisk/fos2
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
[ "MIT" ]
null
null
null
Kernel/Heap.cpp
Archlisk/fos2
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
[ "MIT" ]
null
null
null
Kernel/Heap.cpp
Archlisk/fos2
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
[ "MIT" ]
null
null
null
#include <Heap.h> #include <Memory.h> using namespace Kernel; Heap::Heap(void* start_addr, u64 size) : m_start_addr(start_addr), m_size(size) { Header* first_header = (Header*)start_addr; Header* last_header = (Header*)((u64)start_addr + size - sizeof(Header)); first_header->prev = nullptr; first_header->free = true; first_header->first = true; first_header->last = false; first_header->next = last_header; last_header->prev = first_header; last_header->free = false; last_header->first = false; last_header->last = true; last_header->next = nullptr; } #include <TTY.h> void* Heap::alloc(u32 bytes) { if (!bytes) return nullptr; Header* c_header = (Header*)m_start_addr; while (!c_header->last) { if (c_header->free) { u32 c_size = ((u64)c_header->next - (u64)c_header) - sizeof(Header); if (c_size >= bytes && c_size <= bytes + sizeof(Header)) { c_header->free = false; return (void*)((u64)c_header + sizeof(Header)); } if (c_size >= bytes + sizeof(Header)) { Header* new_header = (Header*)((u64)c_header + bytes + sizeof(Header)); new_header->free = true; new_header->last = false; new_header->first = false; new_header->prev = c_header; new_header->next = c_header->next; c_header->next = new_header; c_header->free = false; new_header->next->prev = new_header; return (void*)((u64)c_header + sizeof(Header)); } } c_header = c_header->next; } out << "Heap is out of memory!\n"; return nullptr; } void* Heap::realloc(void* addr, u32 bytes) { if (!bytes) { free(addr); return nullptr; } if (!addr) return alloc(bytes); Header* header = (Header*)((u64)addr - sizeof(Header)); u32 alloc_size = (u64)header->next - (u64)header - sizeof(Header); // TODO: When the current allocated size is smaller it should create a new header instead of free()-ing and alloc()-ing. if (bytes > alloc_size) { void* new_addr = alloc(bytes); FC::Memory::copy(new_addr, addr, alloc_size); free(addr); return new_addr; } if (bytes < alloc_size) { void* new_addr = alloc(bytes); FC::Memory::copy(new_addr, addr, bytes); free(addr); return new_addr; } return addr; } void Heap::free(void* addr) { if (!addr) return; Header* header = (Header*)((u64)addr - sizeof(Header)); header->free = true; if (!header->first && header->prev->free) erase_header(header); if (!header->next->last && header->next->free) erase_header(header->next); // if (check_corruption()) { // out << "HEAP CORRUPTED!\n"; // print_headers(); // while (true) {} // } } bool Heap::check_corruption() { Header* c_header = (Header*)m_start_addr; Header* next_header_ptr = nullptr; Header* prev_header_ptr = nullptr; while (!c_header->last) { if (next_header_ptr != c_header && next_header_ptr) return true; if (prev_header_ptr != c_header->prev && prev_header_ptr) return true; next_header_ptr = c_header->next; prev_header_ptr = c_header; c_header = c_header->next; } return false; } void Heap::print_headers() { Header* c_header = (Header*)m_start_addr; Header* next_header_ptr = nullptr; Header* prev_header_ptr = nullptr; while (!c_header->last) { if (next_header_ptr != c_header && next_header_ptr) out << "HEAP CORRUPTION DETECTED!\n"; if (prev_header_ptr != c_header->prev && prev_header_ptr) out << "HEAP CORRUPTION DETECTED!\n"; u32 c_size = (u64)c_header->next - (u64)c_header - sizeof(Header); if (c_header->free) out << "FREE:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n"; else out << "USED:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n"; next_header_ptr = c_header->next; prev_header_ptr = c_header; c_header = c_header->next; } }
23.70303
131
0.645615
Archlisk
b1bd5ff05ddcd6d24c3700c53a80b8ffad9a0ecf
1,994
cpp
C++
B2G/external/skia/src/pdf/SkPDFStream.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/external/skia/src/pdf/SkPDFStream.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/external/skia/src/pdf/SkPDFStream.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* * Copyright (C) 2010 Google 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 "SkFlate.h" #include "SkPDFCatalog.h" #include "SkPDFStream.h" #include "SkStream.h" SkPDFStream::SkPDFStream(SkStream* stream) { if (SkFlate::HaveFlate()) SkAssertResult(SkFlate::Deflate(stream, &fCompressedData)); if (SkFlate::HaveFlate() && fCompressedData.getOffset() < stream->getLength()) { fLength = fCompressedData.getOffset(); insert("Filter", new SkPDFName("FlateDecode"))->unref(); } else { fCompressedData.reset(); fPlainData = stream; fLength = fPlainData->getLength(); } insert("Length", new SkPDFInt(fLength))->unref(); } SkPDFStream::~SkPDFStream() { } void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { if (indirect) return emitIndirectObject(stream, catalog); this->INHERITED::emitObject(stream, catalog, false); stream->writeText(" stream\n"); if (fPlainData.get()) stream->write(fPlainData->getMemoryBase(), fLength); else stream->write(fCompressedData.getStream(), fLength); stream->writeText("\nendstream"); } size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) { if (indirect) return getIndirectOutputSize(catalog); return this->INHERITED::getOutputSize(catalog, false) + strlen(" stream\n\nendstream") + fLength; }
32.16129
75
0.677031
wilebeast
04d9905b635aebf0e5aa8229500f93f27ea3c49e
2,597
cpp
C++
cext/src/JUtil.cpp
u2i/jruby
a04e24e55ef3a3e4d0d8246d1789600087815f23
[ "Ruby", "Apache-2.0" ]
2
2018-02-18T01:05:13.000Z
2021-12-10T16:45:58.000Z
cext/src/JUtil.cpp
u2i/jruby
a04e24e55ef3a3e4d0d8246d1789600087815f23
[ "Ruby", "Apache-2.0" ]
null
null
null
cext/src/JUtil.cpp
u2i/jruby
a04e24e55ef3a3e4d0d8246d1789600087815f23
[ "Ruby", "Apache-2.0" ]
1
2016-09-15T12:25:22.000Z
2016-09-15T12:25:22.000Z
/***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.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.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2008, 2009 Wayne Meissner * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ #include <string.h> #include <stdlib.h> #include <jni.h> #include "JUtil.h" JavaVM* jruby::jvm; JNIEnv* jruby::getCurrentEnv() { JNIEnv* env; jvm->GetEnv((void **) & env, JNI_VERSION_1_4); if (env == NULL) { jvm->AttachCurrentThread((void **) & env, NULL); } return env; } void jruby::throwExceptionByName(JNIEnv* env, const char* exceptionName, const char* fmt, ...) { va_list ap; char buf[1024] = { 0 }; va_start(ap, fmt); vsnprintf(buf, sizeof(buf) - 1, fmt, ap); env->PushLocalFrame(10); jclass exceptionClass = env->FindClass(exceptionName); if (exceptionClass != NULL) { env->ThrowNew(exceptionClass, buf); } env->PopLocalFrame(NULL); va_end(ap); } const char* jruby::IllegalArgumentException = "java/lang/IllegalArgumentException"; const char* jruby::NullPointerException = "java/lang/NullPointerException"; const char* jruby::OutOfBoundsException = "java/lang/IndexOutOfBoundsException"; const char* jruby::OutOfMemoryException = "java/lang/OutOfMemoryError"; const char* jruby::RuntimeException = "java/lang/RuntimeException";
37.1
89
0.711975
u2i
04df13f38390d13206dfdb640d4b9480527dc934
1,623
cpp
C++
c++-library/suffix_array.cpp
knuu/contest_library
94b0c9eb82e7e2543bf82ea5a07bfe80e5f2ddc3
[ "MIT" ]
2
2019-05-21T12:12:58.000Z
2022-01-20T03:19:33.000Z
c++-library/suffix_array.cpp
knuu/contest_library
94b0c9eb82e7e2543bf82ea5a07bfe80e5f2ddc3
[ "MIT" ]
null
null
null
c++-library/suffix_array.cpp
knuu/contest_library
94b0c9eb82e7e2543bf82ea5a07bfe80e5f2ddc3
[ "MIT" ]
null
null
null
#include <functional> #include <string> #include <vector> struct SuffixArray { int N, k; std::string S; std::vector<int> sa, rank, tmp; std::vector<int> lcp, rank_lcp; SuffixArray(std::string &S) : N(S.size()), S(S), sa(N + 1), rank(N + 1), tmp(N + 1) { construct(); } void construct() { for (int i = 0; i <= N; i++) { sa[i] = i; rank[i] = i < N ? S[i] : -1; } std::function<bool(int, int)> compare = [&](int i, int j) { if (rank[i] != rank[j]) { return rank[i] < rank[j]; } else { int ri = i + k <= N ? rank[i + k] : -1; int rj = j + k <= N ? rank[j + k] : -1; return ri < rj; } }; for (k = 1; k <= N; k *= 2) { sort(sa.begin(), sa.end(), compare); tmp[sa[0]] = 0; for (int i = 1; i <= N; i++) { tmp[sa[i]] = tmp[sa[i - 1]] + (compare(sa[i - 1], sa[i]) ? 1 : 0); } for (int i = 0; i <= N; i++) rank[i] = tmp[i]; } } bool contain(const std::string &T) const { int left = 0, right = N; while (left + 1 < right) { int mid = (left + right) / 2; (S.compare(sa[mid], T.length(), T) < 0 ? left : right) = mid; } return S.compare(sa[right], T.length(), T) == 0; } void construct_lcp() { lcp.resize(N), rank_lcp.resize(N + 1); for (int i = 0; i <= N; i++) rank_lcp[sa[i]] = i; int h = 0; lcp[0] = 0; for (int i = 0; i < N; i++) { int j = sa[rank[i] - 1]; if (h > 0) h--; for (; j + h < N and i + h < N; h++) { if (S[j + h] != S[i + h]) break; } lcp[rank[i] - 1] = h; } } };
23.867647
74
0.429452
knuu
04df61e9469c036c18ce1d54b9672164fc18d18b
2,082
cpp
C++
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
20
2015-01-13T08:14:46.000Z
2022-01-09T21:01:41.000Z
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
null
null
null
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
3
2016-07-13T08:58:33.000Z
2021-01-29T07:06:34.000Z
/** * ofxMPMFluid.cpp * The MIT License (MIT) * Copyright (c) 2010 respective contributors * * 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. * ***************************************** * MPM FLuid Simulation Demo * OpenFrameworks version by Golan Levin * http://www.flong.com * * ofxAddon created by James George (@obviousjm) * http://www.jamesgeorge.org * * Original Java version: * http://grantkot.com/MPM/Liquid.html * * Flash version: * Copyright iunpin ( http://wonderfl.net/user/iunpin ) * MIT License ( http://www.opensource.org/licenses/mit-license.php ) * Downloaded from: http://wonderfl.net/c/6eu4 * * Javascript version: * Copyright Stephen Sinclair (radarsat1) ( http://www.music.mcgill.ca/~sinclair ) * MIT License ( http://www.opensource.org/licenses/mit-license.php ) * Downloaded from: http://www.music.mcgill.ca/~sinclair/blog */ #include "ofxMPMObstacle.h" ofxMPMObstacle::ofxMPMObstacle ( float inx, float iny, float inr) { cx = inx; cy = iny; radius = inr; radius2 = radius * radius; }
39.283019
82
0.716138
eraly5555
04e01ab7bc1d1eb226f49ea65bf13fa5ffd56fcb
700
hpp
C++
lib/hmat/hmatrix_dense_compressor.hpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
lib/hmat/hmatrix_dense_compressor.hpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
lib/hmat/hmatrix_dense_compressor.hpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
// vi: set et ts=4 sw=2 sts=2: #ifndef HMAT_HMATRIX_DENSE_COMPRESSOR_HPP #define HMAT_HMATRIX_DENSE_COMPRESSOR_HPP #include "common.hpp" #include "hmatrix_compressor.hpp" #include "data_accessor.hpp" namespace hmat { template <typename ValueType, int N> class HMatrixDenseCompressor : public HMatrixCompressor<ValueType, N> { public: HMatrixDenseCompressor(const DataAccessor<ValueType, N> &dataAccessor); void compressBlock(const BlockClusterTreeNode<N> &blockClusterTreeNode, shared_ptr<HMatrixData<ValueType>> &hMatrixData) const override; private: const DataAccessor<ValueType, N> &m_dataAccessor; }; } #include "hmatrix_dense_compressor_impl.hpp" #endif
24.137931
75
0.771429
mdavezac
04e1eeb3e4599cd968033d30d1cbbed235809c6d
1,584
cpp
C++
sres/OptItems.cpp
CiaranWelsh/SRES
71e31aabdda8ff40efd543ede14cf8846a334342
[ "MIT" ]
1
2021-03-25T23:10:45.000Z
2021-03-25T23:10:45.000Z
sres/OptItems.cpp
CiaranWelsh/SRES
71e31aabdda8ff40efd543ede14cf8846a334342
[ "MIT" ]
4
2021-02-01T14:06:00.000Z
2021-02-07T11:17:53.000Z
sres/OptItems.cpp
sys-bio/SRES
71e31aabdda8ff40efd543ede14cf8846a334342
[ "MIT" ]
null
null
null
// // Created by Ciaran on 05/02/2021. // #include <algorithm> #include "OptItems.h" #include "Error.h" namespace opt { OptItems::OptItems(std::vector<OptItem> optItems) : optItems_(std::move(optItems)) {} OptItems::OptItems(const std::vector<double> &startingValues, const std::vector<double> &lb, const std::vector<double> &ub) { int s1 = startingValues.size(); int s2 = lb.size(); int s3 = ub.size(); std::vector<int> sizes({s1, s2, s3}); bool equal = false; if (std::adjacent_find(sizes.begin(), sizes.end(), std::not_equal_to<>()) == sizes.end()) { equal = true; } if (!equal) { LOGIC_ERROR << "Input vectors are not equal sizes. The startingValues vector is " << s1 << "; the lb vector is: " << s2 << "; and the ub vector is " << s3 << std::endl; } for (int i = 0; i < startingValues.size(); i++) { optItems_.emplace_back(startingValues[i], lb[i], ub[i]); } } OptItems::OptItems(std::initializer_list<OptItem> optItems) : optItems_(std::vector<OptItem>(optItems.begin(), optItems.end())) {} int OptItems::size() { return optItems_.size(); } std::vector<OptItem>::iterator OptItems::begin() { return optItems_.begin(); } std::vector<OptItem>::iterator OptItems::end() { return optItems_.end(); } OptItem &OptItems::operator[](int index) { return optItems_[index]; } }
28.285714
99
0.547348
CiaranWelsh
04e3991c5e8a88c6e632bdd0e1f0d808392422e8
2,222
cpp
C++
blast/src/objects/biblio/Cit_proc.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
blast/src/objects/biblio/Cit_proc.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
blast/src/objects/biblio/Cit_proc.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: Cit_proc.cpp 272611 2011-04-08 18:57:08Z ucko $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: ....... * * File Description: * ....... * * Remark: * This code was originally generated by application DATATOOL * using specifications from the ASN data definition file * 'biblio.asn'. */ // standard includes // generated includes #include <ncbi_pch.hpp> #include <objects/biblio/Cit_proc.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // destructor CCit_proc::~CCit_proc(void) { } bool CCit_proc::GetLabelV1(string* label, TLabelFlags flags) const { // return GetBook().GetLabelV1(label, flags); return GetBook().GetLabel(label, flags, eLabel_V1); } bool CCit_proc::GetLabelV2(string* label, TLabelFlags flags) const { return GetBook().GetLabel(label, flags, eLabel_V2); } END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE /* Original file checksum: lines: 61, chars: 1883, CRC32: 78b997ee */
30.438356
78
0.666967
mycolab
04e4ad8aba946a547875ef09ec87454d428cfc12
4,139
cpp
C++
src/templateargumentprocessor.cpp
strandfield/libscript
5d413762ad8ce88ff887642f6947032017dd284c
[ "MIT" ]
3
2020-12-28T01:40:45.000Z
2021-05-18T01:47:07.000Z
src/templateargumentprocessor.cpp
strandfield/libscript
5d413762ad8ce88ff887642f6947032017dd284c
[ "MIT" ]
4
2019-06-29T12:23:11.000Z
2020-07-25T15:38:46.000Z
src/templateargumentprocessor.cpp
strandfield/libscript
5d413762ad8ce88ff887642f6947032017dd284c
[ "MIT" ]
1
2021-11-17T01:49:42.000Z
2021-11-17T01:49:42.000Z
// Copyright (C) 2018-2020 Vincent Chambrin // This file is part of the libscript library // For conditions of distribution and use, see copyright notice in LICENSE #include "script/templateargumentprocessor.h" #include "script/class.h" #include "script/classtemplate.h" #include "script/classtemplateinstancebuilder.h" #include "script/diagnosticmessage.h" #include "script/private/template_p.h" #include "script/compiler/compilererrors.h" #include "script/compiler/literalprocessor.h" #include "script/compiler/nameresolver.h" #include "script/compiler/typeresolver.h" #include "script/ast/node.h" #include "script/compiler/compiler.h" namespace script { TemplateArgument TemplateArgumentProcessor::argument(const Scope & scp, const std::shared_ptr<ast::Node> & arg) { if (arg->is<ast::Identifier>()) { auto name = std::static_pointer_cast<ast::Identifier>(arg); NameLookup lookup = NameLookup::resolve(name, scp); if (lookup.resultType() == NameLookup::TypeName) return TemplateArgument{ lookup.typeResult() }; else throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument }; } else if (arg->is<ast::Literal>()) { const ast::Literal & l = arg->as<ast::Literal>(); if (l.is<ast::BoolLiteral>()) return TemplateArgument{ l.token == parser::Token::True }; else if (l.is<ast::IntegerLiteral>()) return TemplateArgument{ compiler::LiteralProcessor::generate(std::static_pointer_cast<ast::IntegerLiteral>(arg)) }; else throw compiler::CompilationFailure{ CompilerError::InvalidLiteralTemplateArgument }; } else if (arg->is<ast::TypeNode>()) { auto type = std::static_pointer_cast<ast::TypeNode>(arg); compiler::TypeResolver r; return TemplateArgument{ r.resolve(type->value, scp) }; } throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument }; } std::vector<TemplateArgument> TemplateArgumentProcessor::arguments(const Scope & scp, const std::vector<std::shared_ptr<ast::Node>> & args) { std::vector<TemplateArgument> result; result.reserve(args.size()); for (const auto & a : args) result.push_back(argument(scp, a)); return result; } Class TemplateArgumentProcessor::instantiate(ClassTemplate & ct, const std::vector<TemplateArgument> & args) { ClassTemplateInstanceBuilder builder{ ct, std::vector<TemplateArgument>{ args} }; Class ret = ct.backend()->instantiate(builder); ct.impl()->instances[args] = ret; return ret; } Class TemplateArgumentProcessor::process(const Scope & scp, ClassTemplate & ct, const std::shared_ptr<ast::TemplateIdentifier> & tmplt) { try { std::vector<TemplateArgument> targs = arguments(scp, tmplt->arguments); complete(ct, scp, targs); Class c; const bool result = ct.hasInstance(targs, &c); if (result) return c; return instantiate(ct, targs); } catch (const compiler::CompilationFailure& ex) { // silently discard the error (void)ex; } catch (const TemplateInstantiationError & error) { // silently discard the error (void)error; } return Class{}; } void TemplateArgumentProcessor::complete(const Template & t, const Scope &scp, std::vector<TemplateArgument> & args) { if (t.parameters().size() == args.size()) return; for (size_t i(0); i < t.parameters().size(); ++i) { if (!t.parameters().at(i).hasDefaultValue()) throw compiler::CompilationFailure{ CompilerError::MissingNonDefaultedTemplateParameter }; TemplateArgument arg = argument(scp, t.parameters().at(i).defaultValue()); args.push_back(arg); } } const std::vector<std::shared_ptr<ast::Node>> & TemplateArgumentProcessor::getTemplateArguments(const std::shared_ptr<ast::Identifier> & tname) { if (tname->is<ast::TemplateIdentifier>()) { const auto & name = tname->as<ast::TemplateIdentifier>(); return name.arguments; } else if (tname->is<ast::ScopedIdentifier>()) { return getTemplateArguments(tname->as<ast::ScopedIdentifier>().rhs); } throw std::runtime_error{ "Bad call to TemplateArgumentProcessor::getTemplateArguments()" }; } } // namespace script
31.356061
143
0.712491
strandfield
04e63d8b01982081dba6536e567c4f7d691639ac
6,407
hh
C++
maxutils/maxbase/include/maxbase/log.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxbase/include/maxbase/log.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxbase/include/maxbase/log.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2026-01-04 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxbase/ccdefs.hh> #include <stdexcept> #include <maxbase/log.h> enum mxb_log_target_t { MXB_LOG_TARGET_DEFAULT, MXB_LOG_TARGET_FS, // File system MXB_LOG_TARGET_STDOUT, // Standard output }; /** * Prototype for function providing additional information. * * If the function returns a non-zero value, that amount of characters * will be enclosed between '(' and ')', and written first to a logged * message. * * @param buffer Buffer where additional context may be written. * @param len Length of @c buffer. * * @return Length of data written to buffer. */ using mxb_log_context_provider_t = size_t (*)(char* buffer, size_t len); using mxb_in_memory_log_t = void (*)(const std::string& buffer); /** * Typedef for conditional logging callback. * * @param priority The syslog priority under which the message is logged. * @return True if the message should be logged, false if it should be suppressed. */ using mxb_should_log_t = bool (*)(int priority); /** * @brief Initialize the log * * This function must be called before any of the log function should be * used. * * @param ident The syslog ident. If NULL, then the program name is used. * @param logdir The directory for the log file. If NULL, file output is discarded. * @param filename The name of the log-file. If NULL, the program name will be used * if it can be deduced, otherwise the name will be "messages.log". * @param target Logging target * @param context_provider Optional function for providing contextual information * at logging time. * * @return true if succeed, otherwise false */ bool mxb_log_init(const char* ident, const char* logdir, const char* filename, mxb_log_target_t target, mxb_log_context_provider_t context_provider, mxb_in_memory_log_t in_memory_log, mxb_should_log_t should_log); /** * @brief Finalize the log * * A successfull call to @c max_log_init() should be followed by a call * to this function before the process exits. */ void mxb_log_finish(); /** * @brief Initialize the log * * This function initializes the log using * - the program name as the syslog ident, * - the current directory as the logdir, and * - the default log name (program name + ".log"). * * @param target The specified target for the logging. * * @return True if succeeded, false otherwise. */ inline bool mxb_log_init(mxb_log_target_t target = MXB_LOG_TARGET_FS) { return mxb_log_init(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr); } namespace maxbase { /** * @class Log * * A simple utility RAII class where the constructor initializes the log and * the destructor finalizes it. */ class Log { Log(const Log&) = delete; Log& operator=(const Log&) = delete; public: Log(const char* ident, const char* logdir, const char* filename, mxb_log_target_t target, mxb_log_context_provider_t context_provider, mxb_in_memory_log_t in_memory_log, mxb_should_log_t should_log) { if (!mxb_log_init(ident, logdir, filename, target, context_provider, in_memory_log, should_log)) { throw std::runtime_error("Failed to initialize the log."); } } Log(mxb_log_target_t target = MXB_LOG_TARGET_FS) : Log(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr) { } ~Log() { mxb_log_finish(); } }; // RAII class for setting and clearing the "scope" of the log messages. Adds the given object name to log // messages as long as the object is alive. class LogScope { public: LogScope(const LogScope&) = delete; LogScope& operator=(const LogScope&) = delete; explicit LogScope(const char* name) : m_prev_scope(s_current_scope) , m_name(name) { s_current_scope = this; } ~LogScope() { s_current_scope = m_prev_scope; } static const char* current_scope() { return s_current_scope ? s_current_scope->m_name : nullptr; } private: LogScope* m_prev_scope; const char* m_name; static thread_local LogScope* s_current_scope; }; // Class for redirecting the thread-local log message stream to a different handler. Only one of these should // be constructed in the callstack. class LogRedirect { public: LogRedirect(const LogRedirect&) = delete; LogRedirect& operator=(const LogRedirect&) = delete; /** * The message handler type * * @param level Syslog log level of the message * @param msg The message itself * * @return True if the message was consumed (i.e. it should not be logged) */ using Func = bool (*)(int level, const std::string& msg); explicit LogRedirect(Func func); ~LogRedirect(); static Func current_redirect(); private: static thread_local Func s_redirect; }; #define MXB_STREAM_LOG_HELPER(CMXBLOGLEVEL__, mxb_msg_str__) \ do { \ if (!mxb_log_is_priority_enabled(CMXBLOGLEVEL__)) \ { \ break; \ } \ thread_local std::ostringstream os; \ os.str(std::string()); \ os << mxb_msg_str__; \ mxb_log_message(CMXBLOGLEVEL__, MXB_MODULE_NAME, __FILE__, __LINE__, \ __func__, "%s", os.str().c_str()); \ } while (false) #define MXB_SALERT(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ALERT, mxb_msg_str__) #define MXB_SERROR(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ERR, mxb_msg_str__) #define MXB_SWARNING(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_WARNING, mxb_msg_str__) #define MXB_SNOTICE(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_NOTICE, mxb_msg_str__) #define MXB_SINFO(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_INFO, mxb_msg_str__) #if defined (SS_DEBUG) #define MXB_SDEBUG(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_DEBUG, mxb_msg_str__) #else #define MXB_SDEBUG(mxb_msg_str__) #endif }
29.255708
109
0.68472
sdrik
04e7d48960ce3c3793261c217a806a4544892acb
1,310
cpp
C++
src/ai/external/hauser_parabolic_smoother/HauserUtil.cpp
icaros-usc/wecook
27bbb6b78a48e04765a87d33cc8a5d3748d2d4cc
[ "BSD-3-Clause" ]
15
2019-09-15T05:24:19.000Z
2021-02-26T20:31:19.000Z
src/ai/external/hauser_parabolic_smoother/HauserUtil.cpp
icaros-usc/wecook
27bbb6b78a48e04765a87d33cc8a5d3748d2d4cc
[ "BSD-3-Clause" ]
16
2019-10-10T23:27:00.000Z
2020-05-14T02:30:56.000Z
src/ai/external/hauser_parabolic_smoother/HauserUtil.cpp
icaros-usc/wecook
27bbb6b78a48e04765a87d33cc8a5d3748d2d4cc
[ "BSD-3-Clause" ]
2
2020-02-01T16:31:29.000Z
2020-04-07T21:00:04.000Z
// // Created by hejia on 9/22/19. // #include "ai/external/hauser_parabolic_smoother/HauserUtil.h" #include "ai/external/hauser_parabolic_smoother/DynamicPath.h" namespace wecook { namespace ai { namespace external { namespace hauser_parabolic_smoother { //============================================================================== ParabolicRamp::Vector toVector(const Eigen::VectorXd &_x) { ParabolicRamp::Vector output(_x.size()); for (int i = 0; i < _x.size(); ++i) output[i] = _x[i]; return output; } //============================================================================== Eigen::VectorXd toEigen(const ParabolicRamp::Vector &_x) { Eigen::VectorXd output(_x.size()); for (std::size_t i = 0; i < _x.size(); ++i) output[i] = _x[i]; return output; } //============================================================================== void evaluateAtTime(const ParabolicRamp::DynamicPath &_path, double _t, Eigen::VectorXd &_position, Eigen::VectorXd &_velocity) { ParabolicRamp::Vector positionVector; _path.Evaluate(_t, positionVector); _position = toEigen(positionVector); ParabolicRamp::Vector velocityVector; _path.Derivative(_t, velocityVector); _velocity = toEigen(velocityVector); } } } } }
27.291667
80
0.554198
icaros-usc
04ea7e1f8f57f7fe9110fa01a5b13e9cdbda6551
3,777
cpp
C++
oneflow/xrt/tensorrt/ops/op_context.cpp
xxg1413/oneflow
f2e3c85a25b8aecfb6c0c0af1737833b1a77e135
[ "Apache-2.0" ]
2
2021-09-10T00:19:49.000Z
2021-11-16T11:27:20.000Z
oneflow/xrt/tensorrt/ops/op_context.cpp
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
null
null
null
oneflow/xrt/tensorrt/ops/op_context.cpp
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
1
2021-11-10T07:57:01.000Z
2021-11-10T07:57:01.000Z
/* Copyright 2020 The OneFlow 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 "oneflow/xrt/tensorrt/ops/op_context.h" #include "oneflow/xrt/tensorrt/trt_value.h" namespace oneflow { namespace xrt { namespace tensorrt { const std::string &TrtOpContext::SoleOutputName() const { CHECK_EQ(num_outputs(), 1); return param_.output_names.front(); } nvinfer1::ITensor *TrtOpContext::Input(const std::string &name) { return Input(ArgumentFromKey(name)); } nvinfer1::ITensor *TrtOpContext::Output(const std::string &name) { return Output(ArgumentFromKey(name)); } nvinfer1::ITensor *TrtOpContext::Input(const Argument &arg) { CHECK_GT(param_.inputs.count(arg), 0); return param_.inputs.at(arg).AsTensor(builder()); } nvinfer1::ITensor *TrtOpContext::Output(const Argument &arg) { CHECK_GT(outputs_.count(arg), 0); return outputs_.at(arg).AsTensor(builder()); } nvinfer1::ITensor *TrtOpContext::SoleInput() { CHECK_EQ(num_inputs(), 1); auto it = param_.inputs.begin(); return (it->second).AsTensor(builder()); } nvinfer1::ITensor *TrtOpContext::SoleOutput() { CHECK_EQ(outputs_.size(), 1); auto it = outputs_.begin(); return (it->second).AsTensor(builder()); } nvinfer1::Weights &TrtOpContext::Weight(const std::string &name) { return Weight(ArgumentFromKey(name)); } nvinfer1::Weights &TrtOpContext::Weight(const Argument &arg) { CHECK_GT(param_.inputs.count(arg), 0); return param_.inputs.at(arg).AsWeight(builder()); } void TrtOpContext::SetOutput(const std::string &name, nvinfer1::ITensor *tensor) { SetOutput(name, TrtValue::Tensor(builder(), tensor)); } void TrtOpContext::SetOutput(const std::string &name, const TrtValue &value) { Argument arg = ArgumentFromKey(name); outputs_[arg] = value; nvinfer1::ITensor *tensor = builder()->GetTensor(value.handle()); tensor->setName(arg.name().c_str()); } void TrtOpContext::SetSoleOutput(nvinfer1::ITensor *tensor) { CHECK_EQ(outputs_.size(), 0); SetOutput(SoleOutputName(), tensor); } DataType TrtOpContext::InputType(const std::string &name) const { return ArgumentFromKey(name).data_type(); } DataType TrtOpContext::SoleInputType() const { CHECK_EQ(num_inputs(), 1); auto it = param_.inputs.begin(); return (it->first).data_type(); } DataType TrtOpContext::OutputType(const std::string &name) const { return ArgumentFromKey(name).data_type(); } DataType TrtOpContext::SoleOutputType() const { return ArgumentFromKey(SoleOutputName()).data_type(); } Shape TrtOpContext::InputShape(const std::string &name) const { return ArgumentFromKey(name).shape(); } Shape TrtOpContext::SoleInputShape() const { CHECK_EQ(num_inputs(), 1); auto it = param_.inputs.begin(); return (it->first).shape(); } Shape TrtOpContext::OutputShape(const std::string &name) const { return ArgumentFromKey(name).shape(); } Shape TrtOpContext::SoleOutputShape() const { return ArgumentFromKey(SoleOutputName()).shape(); } bool TrtOpContext::HasInput(const std::string &name) const { return param_.arguments.count(name) > 0; } Argument TrtOpContext::ArgumentFromKey(const std::string &key) const { CHECK_GT(param_.arguments.count(key), 0); return param_.arguments.at(key); } } // namespace tensorrt } // namespace xrt } // namespace oneflow
28.832061
82
0.737622
xxg1413
04eb53258babfb8b10e0b47571fad57dfe9d560f
6,577
hpp
C++
src/core/util/ImageProcessing.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
src/core/util/ImageProcessing.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
src/core/util/ImageProcessing.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
// // ImageProgressing.hpp // Kessler Syndrome // // Created by Shamyl Zakariya on 11/30/17. // #ifndef ImageProcessing_hpp #define ImageProcessing_hpp #include <cinder/Channel.h> #include <cinder/Perlin.h> #include "core/Common.hpp" #include "core/MathHelpers.hpp" namespace core { namespace util { namespace ip { // perform a dilation pass such that each pixel in dst image is the max of the pixels in src kernel for that pixel void dilate(const Channel8u &src, Channel8u &dst, int radius); // perform a dilation pass such that each pixel in dst image is the min of the pixels in src kernel for that pixel void erode(const Channel8u &src, Channel8u &dst, int radius); // acting on copy of `src, floodfill into `dst void floodfill(const Channel8u &src, Channel8u &dst, ivec2 start, uint8_t targetValue, uint8_t newValue, bool copy); // remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue void remap(const Channel8u &src, Channel8u &dst, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue); // perform blur of size `radius of `src into `dst void blur(const Channel8u &src, Channel8u &dst, int radius); // for every value in src, maxV if pixelV >= threshV else minV void threshold(const Channel8u &src, Channel8u &dst, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0); // apply vignette effect to src, into dst, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius void vignette(const Channel8u &src, Channel8u &dst, double innerRadius, double outerRadius, uint8_t vignetteColor = 0); // perform a dilation pass such that each pixel in result image is the max of the pixels in the kernel inline Channel8u dilate(const Channel8u &src, int size) { Channel8u dst; ::core::util::ip::dilate(src, dst, size); return dst; } // perform a dilation pass such that each pixel in result image is the min of the pixels in the kernel inline Channel8u erode(const Channel8u &src, int size) { Channel8u dst; ::core::util::ip::erode(src, dst, size); return dst; } // remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue inline Channel8u remap(const Channel8u &src, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) { Channel8u dst; ::core::util::ip::remap(src, dst, targetValue, newTargetValue, defaultValue); return dst; } // perform blur of size `radius inline Channel8u blur(const Channel8u &src, int radius) { Channel8u dst; ::core::util::ip::blur(src, dst, radius); return dst; } // for every value in src, maxV if pixelV >= threshV else minV inline Channel8u threshold(const Channel8u &src, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) { Channel8u dst; ::core::util::ip::threshold(src, dst, threshV, maxV, minV); return dst; } // apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius inline Channel8u vignette(const Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) { Channel8u dst; ::core::util::ip::vignette(src, dst, innerRadius, outerRadius, vignetteColor); return dst; } namespace in_place { // operations which can act on a single channel, in-place, safely // fill all pixels in channel with a given value void fill(Channel8u &channel, uint8_t value); // fill all pixels of rect in channel with a given value void fill(Channel8u &channel, Area rect, uint8_t value); // fill all pixels of channel with noise at a given frequency void perlin(Channel8u &channel, Perlin &noise, double frequency); // add value of the perlin noise function, scaled, to each existing pixel void perlin_add(Channel8u &channel, Perlin &noise, double frequency, double scale); // fill all pixels of channel with noise at a given frequency, where the noise is absoluted and thresholded void perlin_abs_thresh(Channel8u &channel, Perlin &noise, double frequency, uint8_t threshold); // flood fill into channel starting at `start, where pixels of `targetValue are changed to `newValue - modifies `channel inline void floodfill(Channel8u &channel, ivec2 start, uint8_t targetValue, uint8_t newValue) { ::core::util::ip::floodfill(channel, channel, start, targetValue, newValue, false); } // remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue inline void remap(Channel8u &channel, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) { ::core::util::ip::remap(channel, channel, targetValue, newTargetValue, defaultValue); } // for every value in src, maxV if pixelV >= threshV else minV inline void threshold(Channel8u &channel, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) { ::core::util::ip::threshold(channel, channel, threshV, maxV, minV); } // apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius inline void vignette(Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) { ::core::util::ip::vignette(src, src, innerRadius, outerRadius, vignetteColor); } } } } } // end namespace core::util::ip #endif /* ImageProcessing_hpp */
49.825758
145
0.610005
ShamylZakariya
04eb66a4e3bd630eb33cd10064113df68094b628
510
hpp
C++
wxRecognize/src/cDialogConfigureDetection.hpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
1
2020-09-06T21:44:56.000Z
2020-09-06T21:44:56.000Z
wxRecognize/src/cDialogConfigureDetection.hpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
null
null
null
wxRecognize/src/cDialogConfigureDetection.hpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
null
null
null
#pragma once #include "wx/dialog.h" #include "wx/textctrl.h" #include "wx/button.h" class cDialogConfigureDetection : public wxDialog { public: cDialogConfigureDetection ( wxWindow * parent, wxWindowID id, const wxString & title, const wxPoint & pos, const wxSize & size, wxString& yoloCfg, wxString& yoloWeight, wxString& yoloClasses); ~cDialogConfigureDetection(); wxTextCtrl * dialogText; wxString GetText(); // private: // void OnOk(wxCommandEvent & event); };
23.181818
87
0.696078
enzo418
04ebc87204d0b084f35987a10fe1f9168a7d3f3a
2,847
cpp
C++
pkcs11-gui/src/importp12dialog.cpp
T-Bonhagen/pkcs11-gui
95eed0e907235af826d79a58531dca07b77cca5d
[ "Apache-2.0" ]
7
2018-06-06T12:53:46.000Z
2022-02-28T16:42:09.000Z
pkcs11-gui/src/importp12dialog.cpp
n3wtron/pkcs11-gui
faccbaa79dd58d803d8466ae28af7098c3a8e92a
[ "Apache-2.0" ]
4
2020-07-28T06:46:28.000Z
2021-01-22T09:55:13.000Z
pkcs11-gui/src/importp12dialog.cpp
n3wtron/pkcs11-gui
faccbaa79dd58d803d8466ae28af7098c3a8e92a
[ "Apache-2.0" ]
4
2018-04-25T16:57:55.000Z
2021-01-21T19:59:11.000Z
/* * Copyright 2017 Igor Maculan <n3wtron@gmail.com> * * 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 <importp12dialog.h> #include <ui_importp12dialog.h> #include <QShowEvent> #include <QFileDialog> #include <QMessageBox> #include <QtConcurrent/QtConcurrent> ImportP12Dialog::ImportP12Dialog(QWidget *parent, SmartCardReader **smartCardReader) : QDialog(parent), ui(new Ui::ImportP12Dialog) { ui->setupUi(this); this->smartCardReader = smartCardReader; connect(ui->browseBtn,SIGNAL(clicked()),this,SLOT(browseFile())); connect(ui->importBtn,SIGNAL(clicked()),this,SLOT(importP12())); connect(ui->cancelBtn,SIGNAL(clicked()),this,SLOT(close())); } void ImportP12Dialog::browseFile(){ QString fileName = QFileDialog::getOpenFileName(this,tr("Open PEM Private Key")); ui->privKeyFilePathEdt->setText(fileName); } void ImportP12Dialog::importP12(){ this->setEnabled(false); QApplication::setOverrideCursor(Qt::WaitCursor); if (*(this->smartCardReader)!=nullptr){ SmartCard* smCard = (*this->smartCardReader)->getSmartCard(); if (smCard!=NULL){ if (ui->privKeyFilePathEdt->text().isEmpty()){ QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key without a selected file")); this->setEnabled(true); QApplication::restoreOverrideCursor(); return; } QFile privKeyFile(ui->privKeyFilePathEdt->text()); if (!privKeyFile.exists()){ QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key. file does not exist")); this->setEnabled(true); QApplication::restoreOverrideCursor(); return; } Either<QString, bool> result = smCard->storeP12(ui->privKeyFilePathEdt->text(),ui->passwordEdt->text(),ui->labelEdt->text(),ui->idEdt->text().toInt()); if (result.isLeft){ QMessageBox::critical(this,tr("Import Private Key"),result.leftValue); }else{ emit(this->imported()); this->close(); } } } QApplication::restoreOverrideCursor(); this->setEnabled(true); } ImportP12Dialog::~ImportP12Dialog() { delete ui; }
35.148148
163
0.651212
T-Bonhagen
04ed2a8339473a505b57b7cdaa6452d583729559
4,822
cpp
C++
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
6
2020-01-29T14:05:56.000Z
2021-04-24T04:37:27.000Z
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
null
null
null
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
1
2020-05-22T06:37:20.000Z
2020-05-22T06:37:20.000Z
// Created on 15-07-2019 18:51:46 by necronomicon #include <bits/stdc++.h> using namespace std; #define MP make_pair #define PB push_back #define ARR_MAX (int)1e5 //Max array length #define INF (int)1e9 //10^9 #define EPS 1e-9 //10^-9 #define MOD 1000000007 //10^9+7 #define PI 3.1415926535897932384626433832795 typedef long int int32; typedef unsigned long int uint32; typedef long long int int64; typedef unsigned long long int uint64; typedef pair<int, int> Pii; typedef vector<int> Vi; typedef vector<string> Vs; typedef vector<Pii> VPii; typedef vector<Vi> VVi; typedef map<int,int> Mii; typedef set<int> Si; typedef multimap<int,int> MMii; typedef multiset<int> MSi; typedef unordered_map<int,int> UMii; typedef unordered_set<int> USi; typedef unordered_multimap<int,int> UMMii; typedef unordered_multiset<int> UMSi; typedef priority_queue<int> PQi; typedef queue<int> Qi; typedef deque<int> DQi; /* We need 3 vectors : visited, ids and low (explained below) Slow Algo: Run dfs and find number of Connected components for each vertex, remove it and run dfs, see if number of Connected Components increase. If it does then its an articulation point. for each edge remove it and see if number of Connected Components increase. If it does then its an bridge. Faster algo takes O(n) check it in single dfs. Doesnt count if CC increase Algo: call dfs with 2 params the node to visit and its parent. increment the global id/time assign this node's id and low with it call all the children of this node if the node has children as parent skip it if the child is already visited and child has lower low than id of current node then this child is an ancestor. else child isnt discovered if its low is lesser than id of current then this is bridge if its low is lesser than or equal to id of current then this is artPoint Time Complexity: O(n) Space Complexity: O(n) below links have same implementations https://cp-algorithms.com/graph/cutpoints.html https://www.youtube.com/watch?v=aZXi1unBdJA */ int id; vector<bool> visited; Vi ids; // stores uniqueId or timestamp based on discovery of node during dfs Vi low; // stores the minimum uniqueId reachable from that node VPii bridges; //contains the list of bridge-edges which can break the graph into more sets Vi articulationPoints; //contains the list of cut-points which can break the graph into more sets void dfs(VVi Adj, int at, int parent){ visited[at] = true; id++; low[at] = ids[at] = id; int children = 0; for (int to: Adj[at]) { if(to == parent) continue; // if backedge to parent we dont do anything if(visited[to]){ // this is backedge to an ancestor and we need its id as our low low[at] = min(low[at], ids[to]); } else{ // a child is discovered which is undiscovered and we need to update our low with its low (not its id) dfs(Adj, to, at); low[at] = min(low[at], low[to]); if(ids[at] < low[to]){ // if child (to) is not linked to an ancestor above (at) bridges.push_back({at, to}); } if(ids[at] <= low[to] && parent != -1){ // if the child has lowest articulationPoints.push_back(at); } children++; // only required for checking if the root can be an articulation point. When dfs starts from root and marks all nodes visited then this remains 1 hence not artPoint. } } if(parent == -1 && children > 1){ articulationPoints.push_back(at); } } void find(VVi Adj){ visited = vector<bool>(Adj.size(), false), ids = Vi(Adj.size(), 0), low = Vi(Adj.size(), 0), id = -1; bridges.clear(); articulationPoints.clear(); for(int i=0; i<Adj.size(); i++){ if(!visited[i]){ dfs(Adj, i, -1); } } } int main (int argc, char const *argv[]) { VVi Adj; // Adjency list Adj = { {1,2}, {0,2}, {0,1,3,5}, {2,4}, {3}, {2,6,8}, {5,7}, {6,8}, {5,7} }; // Adj = { // {1}, // {2,3,4,5}, // {1}, // {1}, // {1, 5}, // {1, 4} // }; // Adj = { // {1,2}, // {0,2}, // {0,1} // }; find(Adj); std::for_each(std::begin(bridges), std::end(bridges), [](Pii p) { cout << p.first << ' ' << p.second << endl; }); cout << endl; std::for_each(std::begin(articulationPoints), std::end(articulationPoints), [](int x) { cout << x << ' '; }); return EXIT_SUCCESS; }
32.362416
190
0.597677
eashwaranRaghu
04eefdbcf0fefbbd48ede43d5cd37c50150e6d5f
1,772
cpp
C++
display/hal/default_standard/src/display_device/hdi_composer.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
display/hal/default_standard/src/display_device/hdi_composer.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
display/hal/default_standard/src/display_device/hdi_composer.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
2
2021-09-13T10:12:47.000Z
2021-09-13T11:16:31.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hdi_composer.h" namespace OHOS { namespace HDI { namespace DISPLAY { HdiComposer::HdiComposer(std::unique_ptr<HdiComposition> pre, std::unique_ptr<HdiComposition> post) { mPreComp = std::move(pre); mPostComp = std::move(post); } int32_t HdiComposer::Prepare(std::vector<HdiLayer *> &layers, HdiLayer &clientLayer) { int ret = mPreComp->SetLayers(layers, clientLayer); DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("pre composition prepare failed")); ret = mPostComp->SetLayers(layers, clientLayer); DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("post composition prepare failed")); return DISPLAY_SUCCESS; } int32_t HdiComposer::Commit(bool modeSet) { int ret = mPreComp->Apply(modeSet); DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("pre composition apply failed")); ret = mPostComp->Apply(modeSet); DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("post composition apply failed")); return DISPLAY_SUCCESS; } } // OHOS } // HDI } // DISPLAY
37.702128
116
0.718397
openharmony-gitee-mirror
04f4016359f6f2986f2fdf3f368e5a69cd757811
11,727
cpp
C++
main/PIKern/KextDeviceNotify.cpp
minku1024/endpointdlp
931ab140eef053498907d1db74a5c055bea8ef93
[ "Apache-2.0" ]
33
2020-11-18T09:30:13.000Z
2022-03-03T17:56:24.000Z
main/PIKern/KextDeviceNotify.cpp
s4ngsuk-sms/endpointdlp
9e87e352e23bff3b5e0701dd278756aadc8a0539
[ "Apache-2.0" ]
25
2020-07-31T01:43:17.000Z
2020-11-27T12:32:09.000Z
main/PIKern/KextDeviceNotify.cpp
s4ngsuk-sms/endpointdlp
9e87e352e23bff3b5e0701dd278756aadc8a0539
[ "Apache-2.0" ]
26
2020-11-18T09:30:15.000Z
2022-01-18T08:24:01.000Z
#include <stdio.h> #include <string.h> #ifdef LINUX #include <stdlib.h> #include <mntent.h> #include <libudev.h> #else #import <Foundation/Foundation.h> #import <IOKit/IOKitLib.h> #import <IOKit/usb/IOUSBLib.h> #import <IOKit/hid/IOHIDKeys.h> #endif #ifdef LINUX #include "../../PISupervisor/apple/include/KernelProtocol.h" #else #include "../../PISupervisor/PISupervisor/apple/include/KernelProtocol.h" #endif #include "KextDeviceNotify.h" #include "PISecSmartDrv.h" #ifndef VFS_RETURNED #define VFS_RETURNED 0 #endif #ifdef LINUX int EnumMountCallback(void* pMount, void* pParam); #else int EnumMountCallback(mount_t pMount, void* pParam); #endif void FetchVolumes() { VolCtx_Clear(); EnumMountCallback(NULL, NULL); } #ifdef LINUX int get_storage_type(struct udev* udev, char* mnt_fsname) { int ret = BusTypeUnknown; struct udev_enumerate* enumerate = NULL; if (udev == NULL || mnt_fsname == NULL) return ret; enumerate = udev_enumerate_new(udev); if (enumerate == NULL) return ret; printf("DEVNAME = %s\n", mnt_fsname); udev_enumerate_add_match_property(enumerate, "DEVNAME", mnt_fsname); udev_enumerate_scan_devices(enumerate); struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate); struct udev_list_entry *entry = NULL; udev_list_entry_foreach(entry, devices) { const char* path = udev_list_entry_get_name(entry); if (path == NULL) continue; struct udev_device* parent = udev_device_new_from_syspath(udev, path); if (parent == NULL) continue; const char *id_cdrom = udev_device_get_property_value(parent, "ID_CDROM"); //printf("\tproperty [ID_CDROM][%s]\n", id_cdrom); const char *devtype = udev_device_get_property_value(parent, "DEVTYPE"); //printf("\tproperty [DEVTYPE][%s]\n", devtype); if (id_cdrom != NULL) { ret = BusTypeAtapi; } else if (devtype != NULL) { ret = BusTypeUsb; } break; } udev_enumerate_unref(enumerate); if (ret == BusTypeUnknown) { #ifdef WSL ret = BusTypeUsb; #else ret = BusTypeSFolder; #endif } return ret; } int EnumMountCallback(void *pMount, void* pParam) #else int EnumMountCallback(mount_t pMount, void* pParam) #endif { int nBusType = 0; boolean_t bUsbStor = FALSE; boolean_t bCDStor = FALSE; boolean_t bSFolder = FALSE; boolean_t bTBStor = FALSE; #ifdef LINUX struct mntent *ent = NULL; FILE *aFile = NULL; struct udev* udev = NULL; aFile = setmntent("/proc/mounts", "r"); if (aFile == NULL) { printf("[DLP][%s] setmntent() failed \n", __FUNCTION__); return -1; } udev = udev_new(); if (udev == NULL) { printf("[DLP][%s] udev_new() failed \n", __FUNCTION__); endmntent(aFile); return -1; } while (NULL != (ent = getmntent(aFile))) { // e.g. // f_mntonname /media/somansa/PRIVACY-I // f_mntfromname /dev/sdb1 // // ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts // /dev/sdb1 /media/somansa/PRIVACY-I vfat rw,nosuid,nodev,relatime,uid=1001,gid=1001,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,showexec,utf8,flush,errors=remount-ro // /dev/sda3 / ext4 rw,relatime,errors=remount-ro #ifdef WSL if (strstr(ent->mnt_dir, "/dev/") == NULL && strstr(ent->mnt_dir, "/mnt/") == NULL) #else if (strstr(ent->mnt_fsname, "/dev/") == NULL && strstr(ent->mnt_fsname, "/mnt/") == NULL) #endif { #ifdef WSL if (ent->mnt_fsname[0] == '/' && ent->mnt_fsname[1] == '/') #else if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == '/') #endif { // //192.168.181.1/tmp } else { continue; } } else { #ifdef WSL #else // /dev/sda3 / if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == 0) { continue; } #endif } #ifdef WSL if (strlen(ent->mnt_dir) <= 1) #else if (strlen(ent->mnt_fsname) <= 1) #endif { continue; } //printf("%s %s %s %s \n", ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts); //#ifdef WSL int type = get_storage_type(udev, ent->mnt_fsname); //#else // int type = get_storage_type(udev, ent->mnt_dir); //#endif VolCtx_Update( ent->mnt_fsname, ent->mnt_dir, type ); } endmntent(aFile); udev_unref(udev); return 0; #else // Get all mounted path NSArray *mounted = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:nil options:0]; // Get mounted USB information for(NSURL *url in mounted) { char f_mntfromname[MAX_PATH] = {0}; char f_mntonname[MAX_PATH] = {0}; char f_fstypename[] = ""; GetMountPath([url.path UTF8String], f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname)); if (f_mntfromname[0] == 0 || f_mntonname[0] == 0) continue; // 1. Volume Context Search. nBusType = VolCtx_Search_BusType( f_mntonname ); if(nBusType == BusTypeUsb || nBusType == BusType1394 || nBusType == BusTypeThunderBolt || nBusType == BusTypeAtapi || nBusType == BusTypeSFolder) { switch(nBusType) { case BusType1394: case BusTypeUsb: bUsbStor = TRUE; break; case BusTypeThunderBolt: bTBStor = TRUE; break; case BusTypeAtapi: bCDStor = TRUE; break; case BusTypeSFolder: bSFolder = TRUE; break; default: break; } } else { // 2. First Acess Check. bUsbStor = IsMediaPath_UsbStor( f_mntonname ); if(bUsbStor) { nBusType = BusTypeUsb; VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb ); } bCDStor = IsMediaPath_CDStor( f_mntonname ); if(bCDStor) { nBusType = BusTypeAtapi; VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi ); } bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename ); if(bSFolder) { nBusType = BusTypeSFolder; VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder ); } } } return (VFS_RETURNED); //VFS_RETURENED_DONE #endif } boolean_t IsControlDeviceType( const vnode_t pVnode, const char* pczPath ) { boolean_t bSFolder = FALSE; boolean_t bUsbStor = FALSE; boolean_t bCDStor = FALSE; boolean_t bTBStor = FALSE; boolean_t bVoulmesDir = FALSE; boolean_t bCups = FALSE; //if(!pVnode) return FALSE; if(pczPath) { bCups = IsCupsDirectory( pczPath ); if(TRUE == bCups) return TRUE; } if(pczPath) { bVoulmesDir = IsVolumesDirectory( pczPath ); // printf("[DLP][%s] pczPath=%s \n", __FUNCTION__, pczPath ); } char f_mntonname[MAX_PATH] = {0}; char f_mntfromname[MAX_PATH] = {0}; char f_fstypename[] = ""; if(bVoulmesDir) { int nBusType = 0; // e.g. // f_mntonname /Volumes/새 볼륨 // f_mntfromname disk2s2 GetMountPath(pczPath, f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname)); // 1. Volume Context Search. //nBusType = VolCtx_Search_BusType( Stat.f_mntonname ); nBusType = VolCtx_Search_BusType( f_mntonname ); if(nBusType == BusTypeUsb || nBusType == BusType1394 || nBusType == BusTypeThunderBolt || nBusType == BusTypeAtapi || nBusType == BusTypeSFolder) { return TRUE; } // 2. First Acess Check. //bUsbStor = IsMediaPath_UsbStor( f_mntfromname ); bUsbStor = IsMediaPath_UsbStor( f_mntonname ); if(bUsbStor) { printf("[DLP][%s] UsbStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname ); VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb ); return bUsbStor; } //bCDStor = IsMediaPath_CDStor( f_mntfromname ); bCDStor = IsMediaPath_CDStor( f_mntonname ); if(bCDStor) { printf("[DLP][%s] CDStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname ); VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi ); return bCDStor; } bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename ); if(bSFolder) { // '/Volumes/shared2/.DS_Store' skip printf("[DLP][%s] SFolder=1, fs=%s, from=%s, name=%s, pczPath=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname, pczPath ); if(NULL == sms_strnstr( pczPath, "/.DS_Store", strlen("/.DS_Store") )) { VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder ); return bSFolder; } else return FALSE; } } return FALSE; } boolean_t IsCupsdConfigFile( const char* pczPath ) { boolean_t bCups = FALSE; size_t nlen = 0; if(!pczPath) return FALSE; if(pczPath) { nlen = strlen(FILE_CUPSD_CONFIG); if(nlen > 0 && 0 == strncasecmp( pczPath, FILE_CUPSD_CONFIG, nlen)) { bCups = TRUE; } } return bCups; } boolean_t IsCupsDirectory(const char* pczPath) { size_t nLength = 0; size_t nCups = 0; if(!pczPath) return FALSE; nLength = strlen(pczPath); nCups = strlen(g_czCupsSpoolPath); if(0 == nCups || nLength < nCups) return FALSE; if(0 == strncasecmp( pczPath, g_czCupsSpoolPath, nCups )) { size_t nLenght = (int)strlen(pczPath); int nAdd = ('/' == g_czCupsSpoolPath[nCups-1])?0:1; for(size_t i=nCups+nAdd; i<nLenght; i++) { // is file?? if('/' == pczPath[i]) { printf("[DLP][%s] Detected Path is not file=%s \n", __FUNCTION__, pczPath ); return FALSE; } } printf("[DLP][%s] Detect Path=%s \n", __FUNCTION__, pczPath ); return TRUE; } return FALSE; } boolean_t IsVolumesDirectory(const char* path) { boolean_t volumesDir = FALSE; #ifdef LINUX volumesDir = TRUE; #else if (path != NULL && strlen(path) >= strlen("/Volumes/") && *(path+0) == '/' && *(path+1) == 'V' && *(path+2) == 'o' && *(path+3) == 'l' && *(path+4) == 'u' && *(path+5) == 'm' && *(path+6) == 'e' && *(path+7) == 's' && *(path+8) == '/') { volumesDir = TRUE; } #endif return volumesDir; } void SetProtectUsbMobileNotify(void) { } void SetProtect_Camera_UsbDeviceNotify(void) { } void SetProtect_RNDIS_UsbDeviceNotify(void) { } void SetProtect_RNDIS_BthDeviceNotify(void) { } boolean_t KextNotify_Init() { return true; } boolean_t KextNotify_Uninit() { return true; }
25.660832
202
0.560672
minku1024
04f4f85c36d483addd2997684f76e5dd9ccf0604
16,923
cpp
C++
src/tx/dexoperatortx.cpp
xiaoyu1998/wasm.bitcoin
0fbd7bdc4555382abca64b5df33e8aec7a65ff3b
[ "MIT" ]
1,313
2018-01-09T01:49:01.000Z
2022-02-26T11:10:40.000Z
src/tx/dexoperatortx.cpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
32
2018-06-07T10:21:21.000Z
2021-12-07T06:53:42.000Z
src/tx/dexoperatortx.cpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
322
2018-02-26T03:41:36.000Z
2022-02-08T08:12:16.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2017-2019 The WaykiChain Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "dexoperatortx.h" #include "config/configuration.h" #include "main.h" #include <regex> #include <algorithm> //////////////////////////////////////////////////////////////////////////////// // ProcessAssetFee static const string OPERATOR_ACTION_REGISTER = "register"; static const string OPERATOR_ACTION_UPDATE = "update"; static const uint32_t MAX_NAME_LEN = 32; static const uint64_t MAX_MATCH_FEE_RATIO_VALUE = 50000000; // 50% static const uint64_t ORDER_OPEN_DEXOP_LIST_SIZE_MAX = 500; static bool ProcessDexOperatorFee(CBaseTx &tx, CTxExecuteContext& context, const string &action) { IMPLEMENT_DEFINE_CW_STATE; uint64_t exchangeFee = 0; if (action == OPERATOR_ACTION_REGISTER) { if (!cw.sysParamCache.GetParam(DEX_OPERATOR_REGISTER_FEE, exchangeFee)) return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_REGISTER_FEE error"), REJECT_INVALID, "read-sysparam-error"); } else { assert(action == OPERATOR_ACTION_UPDATE); if (!cw.sysParamCache.GetParam(DEX_OPERATOR_UPDATE_FEE, exchangeFee)) return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_UPDATE_FEE error"), REJECT_INVALID, "read-sysparam-error"); } if (!tx.sp_tx_account->OperateBalance(SYMB::WICC, BalanceOpType::SUB_FREE, exchangeFee, ReceiptType::DEX_OPERATOR_REG_UPDATE_FEE_FROM_OPERATOR, tx.receipts)) return state.DoS(100, ERRORMSG("tx account insufficient funds for operator %s fee! fee=%llu, tx_addr=%s", action, exchangeFee, tx.sp_tx_account->keyid.ToAddress()), UPDATE_ACCOUNT_FAIL, "insufficent-funds"); uint64_t dexOperatorRiskFeeRatio; if(!cw.sysParamCache.GetParam(SysParamType::DEX_OPERATOR_RISK_FEE_RATIO, dexOperatorRiskFeeRatio)) { return state.DoS(100, ERRORMSG("ProcessDexOperatorFee, get dexOperatorRiskFeeRatio error"), READ_SYS_PARAM_FAIL, "read-db-error"); } uint64_t riskFee = exchangeFee * dexOperatorRiskFeeRatio / RATIO_BOOST; uint64_t minerTotalFee = exchangeFee - riskFee; auto spFcoinAccount = tx.GetAccount(context, SysCfg().GetFcoinGenesisRegId(), "fcoin"); if (!spFcoinAccount) return false; ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_RESERVE : ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_RESERVE; if (!spFcoinAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, riskFee, code, tx.receipts)) { return state.DoS(100, ERRORMSG("operate balance failed! add %s asset fee=%llu to risk reserve account error", action, riskFee), UPDATE_ACCOUNT_FAIL, "update-account-failed"); } VoteDelegateVector delegates; if (!cw.delegateCache.GetActiveDelegates(delegates)) { return state.DoS(100, ERRORMSG("GetActiveDelegates failed"), REJECT_INVALID, "get-delegates-failed"); } assert(delegates.size() != 0 ); for (size_t i = 0; i < delegates.size(); i++) { const CRegID &delegateRegid = delegates[i].regid; auto spDelegateAccount = tx.GetAccount(context, delegateRegid, "delegate_regid"); if (!spDelegateAccount) return false; uint64_t minerFee = minerTotalFee / delegates.size(); if (i == 0) minerFee += minerTotalFee % delegates.size(); // give the dust amount to topmost miner ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_MINER : ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_MINER; if (!spDelegateAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, minerFee, code, tx.receipts)) { return state.DoS(100, ERRORMSG("add %s asset fee to miner failed, miner regid=%s", action, delegateRegid.ToString()), UPDATE_ACCOUNT_FAIL, "operate-account-failed"); } } return true; } //////////////////////////////////////////////////////////////////////////////// // class CDEXOperatorRegisterTx Object CDEXOperatorRegisterTx::ToJson(CCacheWrapper &cw) const { Object result = CBaseTx::ToJson(cw); result.push_back(Pair("owner_uid", data.owner_uid.ToString())); result.push_back(Pair("fee_receiver_uid", data.fee_receiver_uid.ToString())); result.push_back(Pair("dex_name", data.name)); result.push_back(Pair("portal_url", data.portal_url)); result.push_back(Pair("maker_fee_ratio",data.maker_fee_ratio)); result.push_back(Pair("taker_fee_ratio",data.taker_fee_ratio)); result.push_back(Pair("memo",data.memo)); return result; } bool CDEXOperatorRegisterTx::CheckTx(CTxExecuteContext &context) { CValidationState &state = *context.pState; if (!data.owner_uid.is<CRegID>()) return state.DoS(100, ERRORMSG("owner_uid must be regid"), REJECT_INVALID, "owner-uid-type-error"); if (!data.fee_receiver_uid.is<CRegID>()) return state.DoS(100, ERRORMSG("fee_receiver_uid must be regid"), REJECT_INVALID, "match-uid-type-error"); if (data.name.size() > MAX_NAME_LEN) return state.DoS(100, ERRORMSG("name len=%d greater than %d", data.name.size(), MAX_NAME_LEN), REJECT_INVALID, "invalid-name"); if(data.memo.size() > MAX_COMMON_TX_MEMO_SIZE) return state.DoS(100, ERRORMSG("memo len=%d greater than %d", data.memo.size(), MAX_COMMON_TX_MEMO_SIZE), REJECT_INVALID, "invalid-memo"); if (data.maker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE) return state.DoS(100, ERRORMSG("maker_fee_ratio=%d is greater than %d", data.maker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type"); if (data.taker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE) return state.DoS(100, ERRORMSG("taker_fee_ratio=%d is greater than %d", data.taker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type"); if (data.order_open_dexop_list.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX) return state.DoS(100, ERRORMSG("size=%u of order_open_dexop_list exceed max=%u", data.order_open_dexop_list.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX), REJECT_INVALID, "invalid-shared-dexop-list-size"); return true; } bool CDEXOperatorRegisterTx::ExecuteTx(CTxExecuteContext &context) { CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState; DexOpIdValueSet dexIdSet; for (auto &item : data.order_open_dexop_list) { if (!cw.dexCache.HaveDexOperator(item.get())) { return state.DoS(100, ERRORMSG("operator item=%s not exist", db_util::ToString(item)), REJECT_INVALID, "operator-not-exist"); } auto ret = dexIdSet.insert(item); if (!ret.second) { return state.DoS(100, ERRORMSG("duplicated item=%s in order_open_dexop_list", db_util::ToString(item)), REJECT_INVALID, "duplicated-item-of-dexop-list"); } } shared_ptr<CAccount> spOwnerAccount; if (sp_tx_account->IsSelfUid(data.owner_uid)) { spOwnerAccount = sp_tx_account; } else { spOwnerAccount = GetAccount(context, data.owner_uid, "owner_uid"); if (!spOwnerAccount) return false; } shared_ptr<CAccount> pMatchAccount; if (!sp_tx_account->IsSelfUid(data.fee_receiver_uid) && !sp_tx_account->IsSelfUid(data.fee_receiver_uid)) { pMatchAccount = GetAccount(context, data.fee_receiver_uid, "fee_receiver_uid"); if (!pMatchAccount) return false; } if (cw.dexCache.HasDexOperatorByOwner(spOwnerAccount->regid)) return state.DoS(100, ERRORMSG("the owner's operator exist! owner_regid=%s", spOwnerAccount->regid.ToString()), REJECT_INVALID, "owner-dexoperator-exist"); if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_REGISTER)) return false; uint32_t new_id; if (!cw.dexCache.IncDexID(new_id)) return state.DoS(100, ERRORMSG("increase dex id error! txUid=%s", GetHash().ToString() ), UPDATE_ACCOUNT_FAIL, "inc_dex_id_error"); DexOperatorDetail detail = { data.owner_uid.get<CRegID>(), data.fee_receiver_uid.get<CRegID>(), data.name, data.portal_url, data.order_open_mode, data.maker_fee_ratio, data.taker_fee_ratio, dexIdSet, data.memo }; if (!cw.dexCache.CreateDexOperator(new_id, detail)) return state.DoS(100, ERRORMSG("save new dex operator error! new_id=%u", new_id), UPDATE_ACCOUNT_FAIL, "save-operator-error"); return true; } bool CDEXOperatorUpdateData::Check(CBaseTx &tx, CCacheWrapper &cw, string& errmsg, string& errcode,const uint32_t currentHeight){ DexOperatorDetail dex; if(!cw.dexCache.GetDexOperator(dexId,dex)) { errmsg = strprintf("dexoperator(id=%d) not found", dexId); errcode = "invalid-dex-id"; return false; } if(field == UPDATE_NONE || field > MEMO ){ errmsg = "CDEXOperatorUpdateData::check(): update field is error"; errcode= "empty-update-data"; return false; } if (field == FEE_RECEIVER_UID || field == OWNER_UID){ string placeholder = (field == FEE_RECEIVER_UID)? "fee_receiver": "owner"; const auto &uid = get<CUserID>(); auto spAccount = tx.GetAccount(cw, uid); if (!spAccount) { errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) is not exist! ",placeholder, ValueToString()); errcode = strprintf("%s-uid-invalid", placeholder); return false; } if (!spAccount->IsRegistered() || !spAccount->regid.IsMature(currentHeight)) { errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) not register or regid is immature ! ",placeholder, ValueToString() ); errcode = strprintf("%s-uid-invalid", placeholder); return false; } } if (field == NAME && get<string>().size() > MAX_NAME_LEN) { errmsg = strprintf("%s, name len=%d greater than %d", __func__,get<string>().size(), MAX_NAME_LEN); errcode = "invalid-name"; return false; } if (field == MEMO && get<string>().size() > MAX_COMMON_TX_MEMO_SIZE){ errmsg = strprintf("%s, memo len=%d greater than %d", __func__,get<string>().size(), MAX_COMMON_TX_MEMO_SIZE); errcode = "invalid-memo"; return false; } if (field == TAKER_FEE_RATIO || field == MAKER_FEE_RATIO ){ uint64_t v = get<uint64_t>(); if( v > MAX_MATCH_FEE_RATIO_VALUE){ errmsg = strprintf("%s, fee_ratio=%d is greater than %d", __func__, v, MAX_MATCH_FEE_RATIO_VALUE); errcode = "invalid-match-fee-ratio-type"; return false; } } if (field == OPEN_MODE) { dex::OpenMode om = get<dex::OpenMode>(); if (om != dex::OpenMode::PRIVATE && om != dex::OpenMode::PUBLIC) { errmsg = strprintf("dex open mode value(%d) is error", (uint8_t)om); errcode = "invalid-open-mode"; return false; } if (om == dex.order_open_mode) { errmsg = strprintf("the new dex open mode value(%d) is as same as old open mode", (uint8_t)om); errcode = "same-open-mode"; return false; } } if (field == ORDER_OPEN_DEXOP_LIST) { const auto &dexlist = get<DexOpIdValueList>(); if (dexlist.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX) { errmsg = strprintf("size=%u of order_open_dexop_list exceed max=%u", dexlist.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX); errcode = "invalid-shared-dexop-list-size"; return false; } DexOpIdValueSet dexIdSet; for (auto dexOpId : dexlist) { if (dexOpId.get() == dexId) { errmsg = strprintf("dexid=%d is self", dexOpId.get()); errcode = "self-dexid-error"; return false; } if (!cw.dexCache.HaveDexOperator(dexOpId.get())) { errmsg = strprintf("dex(id=%d) not exist!!", dexOpId.get()); errcode = "dexid-not-exist"; return false; } } } return true; } bool CDEXOperatorUpdateData::UpdateToDexOperator(DexOperatorDetail& detail,CCacheWrapper& cw) { switch (field) { case FEE_RECEIVER_UID:{ if(get<CUserID>().is<CRegID>()) { detail.fee_receiver_regid = get<CUserID>().get<CRegID>(); return true; } else{ return false; } } case OWNER_UID:{ if(get<CUserID>().is<CRegID>()){ detail.owner_regid = get<CUserID>().get<CRegID>(); return true; } else{ return false; } } case NAME: detail.name = get<string>(); break; case PORTAL_URL: detail.portal_url = get<string>(); break; case TAKER_FEE_RATIO: detail.taker_fee_ratio = get<uint64_t>(); break; case MAKER_FEE_RATIO: detail.maker_fee_ratio = get<uint64_t>(); break; case MEMO: detail.memo = get<string>(); break; case OPEN_MODE: detail.order_open_mode = get<dex::OpenMode>(); break; case ORDER_OPEN_DEXOP_LIST:{ const auto &dexIdList = get<DexOpIdValueList>(); DexOpIdValueSet dexIdSet; for (auto dexId: dexIdList) { dexIdSet.insert(dexId); } detail.order_open_dexop_set = dexIdSet; break; } default: return false; } return true; } string CDEXOperatorUpdateTx::ToString(CAccountDBCache &accountCache) { return ""; } Object CDEXOperatorUpdateTx::ToJson(CCacheWrapper &cw) const { Object result = CBaseTx::ToJson(cw); result.push_back(Pair("update_field", update_data.field)); result.push_back(Pair("update_value", update_data.ValueToString())); result.push_back(Pair("dex_id", update_data.dexId)); return result; } bool CDEXOperatorUpdateTx::CheckTx(CTxExecuteContext &context) { IMPLEMENT_DEFINE_CW_STATE; string errmsg; string errcode; if(!update_data.Check(*this, cw, errmsg ,errcode, context.height )){ return state.DoS(100, ERRORMSG("%s", errmsg), REJECT_INVALID, errcode); } if(update_data.field == CDEXOperatorUpdateData::OWNER_UID){ if(cw.dexCache.HasDexOperatorByOwner(CRegID(update_data.ValueToString()))) return state.DoS(100, ERRORMSG("the owner already has a dex operator! owner_regid=%s", update_data.ValueToString()), REJECT_INVALID, "owner-had-dexoperator"); } return true; } bool CDEXOperatorUpdateTx::ExecuteTx(CTxExecuteContext &context) { CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState; DexOperatorDetail oldDetail; if (!cw.dexCache.GetDexOperator((DexID)update_data.dexId, oldDetail)) return state.DoS(100, ERRORMSG("the dexoperator( id= %u) is not exist!", update_data.dexId), UPDATE_ACCOUNT_FAIL, "dexoperator-not-exist"); if (!sp_tx_account->IsSelfUid(oldDetail.owner_regid)) return state.DoS(100, ERRORMSG("only owner can update dexoperator! owner_regid=%s, txUid=%s, dexId=%u", oldDetail.owner_regid.ToString(),txUid.ToString(), update_data.dexId), UPDATE_ACCOUNT_FAIL, "dexoperator-update-permession-deny"); if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_UPDATE)) return false; DexOperatorDetail detail = oldDetail; if (!update_data.UpdateToDexOperator(detail, cw)) return state.DoS(100, ERRORMSG("copy updated dex operator error! dex_id=%u", update_data.dexId), UPDATE_ACCOUNT_FAIL, "copy-updated-operator-error"); if (!cw.dexCache.UpdateDexOperator(update_data.dexId, oldDetail, detail)) return state.DoS(100, ERRORMSG("save updated dex operator error! dex_id=%u", update_data.dexId), UPDATE_ACCOUNT_FAIL, "save-updated-operator-error"); return true; }
40.778313
146
0.629085
xiaoyu1998
04f50b1dcb0423c4c6aa123021f3eb27c0d528bc
650
hh
C++
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#pragma once #include <Render/Pipelining/Render/FrameBufferRender.hh> #include <glm\glm.hpp> namespace AGE { class Texture2D; class Program; class GaussianBlur : public FrameBufferRender { public: GaussianBlur(glm::uvec2 const &screenSize, std::shared_ptr<PaintingManager> painterManager, std::shared_ptr<Texture2D> src, std::shared_ptr<Texture2D> dst, bool horizontal); virtual ~GaussianBlur() = default; protected: virtual void renderPass(const DRBCameraDrawableList &infos); glm::vec2 _inverseSourceSize; std::shared_ptr<Texture2D> _source; Key<Vertices> _quadVertices; std::shared_ptr<Painter> _quadPainter; }; }
22.413793
93
0.763077
Another-Game-Engine
04f512e764550c0c54c81fc8cc2c4879d458aae7
4,332
cpp
C++
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
31
2015-12-15T19:14:10.000Z
2021-12-31T17:40:21.000Z
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
5
2015-12-04T08:06:47.000Z
2020-08-09T21:49:46.000Z
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
21
2015-11-05T08:25:45.000Z
2021-06-19T02:24:50.000Z
#include "../../BenchmarkNode.h" #include <stdint.h> #include <iostream> #include <cmath> #define ITER_COUNT 2 #define CACHE_LINE 32 // cache line in byte /* this structure represents a point */ /* these will be passed around to avoid copying coordinates */ typedef struct { float weight; float *coord; long assign; /* number of point where this one is assigned */ float cost; /* cost of that assignment, weight*distance */ } Point; /* this is the array of points */ typedef struct { long num; /* number of points; may not be N if this is a sample */ int dim; /* dimensionality */ Point *p; /* the array itself */ } Points; class SW_StreamCluster : public BenchmarkNode { int dataSize; int dim; int thread; bool* is_center; //whether a point is a center int* center_table; //index table of centers int* work_mem; Points points; int *switch_membership; float *lower; float cost_of_opening_x; float *low; float *gl_lower; int number_of_centers_to_close; int x; public: SW_StreamCluster() { std::cin >> dataSize; } virtual void Initialize(int threadID, int procID); virtual void Run(); virtual void Shutdown(); float dist(Point p1, Point p2, int dim); double pgain(long x, Points *points, double z, long int *numcenters, int pid); }; BENCH_DECL(SW_StreamCluster); void SW_StreamCluster::Initialize(int threadID, int procID) { thread = threadID; uint8_t* constCluster; //dataSize=1024; dim = 32; is_center = new bool[dataSize]; center_table = new int[dataSize]; work_mem = new int[dataSize]; points.dim = dim; points.num = dataSize; points.p = (Point *)malloc(dataSize*sizeof(Point)); for( int i = 0; i < dataSize; i++ ) { points.p[i].coord = (float*)malloc( dim*sizeof(float) ); } switch_membership = new int[dataSize]; lower = new float[dataSize]; low = new float[dataSize]; gl_lower = new float[dataSize]; memset(center_table, 0, dataSize*sizeof(int)); memset(work_mem, 0, dataSize*sizeof(int)); memset(switch_membership, 0, dataSize*sizeof(int)); memset(lower, 0, dataSize*sizeof(float)); memset(low, 0, dataSize*sizeof(float)); memset(gl_lower, 0, dataSize*sizeof(float)); for (int i=0;i<dataSize;i++) { if (i%2) is_center[i] = false; else is_center[i]= true; } } void SW_StreamCluster::Shutdown() { while(true); } void SW_StreamCluster::Run() { int k1 = 0; int k2 = dataSize; for(int it= 0; it< ITER_COUNT; it++) { int count = 0; for( int i = k1; i < k2; i++ ) { if( is_center[i] ) { center_table[i] = count++; } } //this section is omitted because it is only required to normalize the partial counting done in the previous step for parallel code. Since this code is sequential, this step is unnecessary. To simplify things, I removed this step in the LCA and CFU versions as well. /* for( int i = k1; i < k2; i++ ) { if( is_center[i] ) { center_table[i] += (int)work_mem[thread]; } }*/ for (int i = k1; i < k2; i++ ) { float x_cost = dist(points.p[i], points.p[x], points.dim) * points.p[i].weight; float current_cost = points.p[i].cost; if ( x_cost < current_cost ) { switch_membership[i] = 1; cost_of_opening_x += x_cost - current_cost; } else { int assign = points.p[i].assign; lower[center_table[assign]] += current_cost - x_cost; } } for ( int i = k1; i < k2; i++ ) { if( is_center[i] ) { gl_lower[center_table[i]] = low[i]; if ( low[i] > 0 ) { ++number_of_centers_to_close; } } } for ( int i = k1; i < k2; i++ ) { bool close_center = gl_lower[center_table[points.p[i].assign]] > 0 ; if ( switch_membership[i] || close_center ) { points.p[i].cost = points.p[i].weight * dist(points.p[i], points.p[x], points.dim); points.p[i].assign = x; } } for( int i = k1; i < k2; i++ ) { if( is_center[i] && gl_lower[center_table[i]] > 0 ) { is_center[i] = false; } } } } /* compute Euclidean distance squared between two points */ float SW_StreamCluster::dist(Point p1, Point p2, int dim) { int i; float result=0.0; for (i=0;i<dim;i++) result += (p1.coord[i] - p2.coord[i])*(p1.coord[i] - p2.coord[i]); return(result); }
24.896552
268
0.627193
cdsc-github
04f8467cb8c5d9b8b541f9054558e777feaa9d13
76,844
cpp
C++
Libs/Optimize/Optimize.cpp
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Libs/Optimize/Optimize.cpp
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Libs/Optimize/Optimize.cpp
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
/*========================================================================= Program: ShapeWorks: Particle-based Shape Correspondence & Visualization File: Optimize.cpp Copyright (c) 2020 Scientific Computing and Imaging Institute. See ShapeWorksLicense.txt 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 notices for more information. =========================================================================*/ // std #include <sstream> #include <string> #include <iostream> #include <vector> #include <numeric> #include <algorithm> #ifdef _WIN32 #include <direct.h> #define mkdir _mkdir #else #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #endif // ifdef _WIN32 // itk #include <itkImageFileReader.h> #include <itkMultiThreaderBase.h> #include <itkZeroCrossingImageFilter.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkMacro.h> // vtk #include <vtkContourFilter.h> #include <vtkSmartPointer.h> #include <vtkImageData.h> #include <vtkPolyData.h> #include <vtkMassProperties.h> // particle system #include "TriMesh.h" #include "itkImageToVTKImageFilter.h" #include "itkParticleImageDomain.h" #include "itkParticleImageDomainWithGradients.h" #include "itkParticleImplicitSurfaceDomain.h" #include "itkParticleImageDomainWithHessians.h" #include "object_reader.h" #include "object_writer.h" #include <Optimize.h> //--------------------------------------------------------------------------- Optimize::Optimize() { this->m_sampler = itk::MaximumEntropyCorrespondenceSampler<ImageType>::New(); } //--------------------------------------------------------------------------- bool Optimize::Run() { // sanity check if (this->m_domains_per_shape != this->m_number_of_particles.size()) { std::cerr << "Inconsistency in parameters... m_domains_per_shape != m_number_of_particles.size()\n"; return false; } this->SetParameters(); int number_of_splits = static_cast<int>( std::log2(static_cast<double>(this->m_number_of_particles[0])) + 1); this->m_iteration_count = 0; this->m_total_iterations = (number_of_splits * this->m_iterations_per_split) + this->m_optimization_iterations; if (this->m_verbosity_level > 0) { std::cout << "Total number of iterations = " << this->m_total_iterations << "\n"; } m_disable_procrustes = true; m_disable_checkpointing = true; // Initialize if (m_processing_mode >= 0) { this->Initialize();} // Introduce adaptivity if (m_processing_mode >= 1 || m_processing_mode == -1) { this->AddAdaptivity();} // Optimize if (m_processing_mode >= 2 || m_processing_mode == -2) { this->RunOptimize();} this->UpdateExportablePoints(); return true; } //--------------------------------------------------------------------------- void Optimize::RunProcrustes() { this->OptimizerStop(); m_procrustes->RunRegistration(); } //--------------------------------------------------------------------------- void Optimize::SetParameters() { if (this->m_verbosity_level == 0) { std::cout << "Verbosity 0: This will be the only output on your screen, unless there are any errors. Increase the verbosity if needed." << std::endl; } // Set up the optimization process this->m_sampler->SetDomainsPerShape(this->m_domains_per_shape); // must be done first! this->m_sampler->SetTimeptsPerIndividual(this->m_timepts_per_subject); this->m_sampler->GetParticleSystem()->SetDomainsPerShape(this->m_domains_per_shape); this->m_sampler->SetVerbosity(this->m_verbosity_level); if (this->m_use_xyz.size() > 0) { for (int i = 0; i < this->m_domains_per_shape; i++) { this->m_sampler->SetXYZ(i, this->m_use_xyz[i]); } } else { for (int i = 0; i < this->m_domains_per_shape; i++) { this->m_sampler->SetXYZ(i, false); } } if (this->m_use_normals.size() > 0) { for (int i = 0; i < this->m_domains_per_shape; i++) { this->m_sampler->SetNormals(i, this->m_use_normals[i]); } } else { for (int i = 0; i < this->m_domains_per_shape; i++) { this->m_sampler->SetNormals(i, false); } } // Set up the procrustes registration object. this->m_procrustes = itk::ParticleProcrustesRegistration < 3 > ::New(); this->m_procrustes->SetParticleSystem(this->m_sampler->GetParticleSystem()); this->m_procrustes->SetDomainsPerShape(this->m_domains_per_shape); if (this->m_procrustes_scaling == 0) { this->m_procrustes->ScalingOff(); } else { this->m_procrustes->ScalingOn(); } this->SetIterationCallback(); this->PrintStartMessage("Initializing variables..."); this->InitializeSampler(); this->PrintDoneMessage(); if (m_use_normals.size() > 0) { int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains(); for (int i = 0; i < numShapes; i++) { if (m_use_normals[i % m_domains_per_shape]) { continue; } itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess = static_cast < itk::ParticleImageDomainWithHessians<float, 3>*> (m_sampler->GetParticleSystem() ->GetDomain(i)); domainWithHess->DeletePartialDerivativeImages(); } } else { int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains(); for (int i = 0; i < numShapes; i++) { itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess = static_cast < itk::ParticleImageDomainWithHessians < float, 3 > * > (m_sampler->GetParticleSystem()->GetDomain(i)); domainWithHess->DeletePartialDerivativeImages(); } } if (m_domain_flags.size() > 0) { for (int i = 0; i < m_domain_flags.size(); i++) { itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess = static_cast < itk::ParticleImageDomainWithHessians < float, 3 > * > (m_sampler->GetParticleSystem()->GetDomain(m_domain_flags[i])); if (m_use_normals.size() > 0) { if (m_use_normals[i % m_domains_per_shape]) { domainWithHess->DeletePartialDerivativeImages(); } else { domainWithHess->DeleteImages(); } } } } if (m_verbosity_level > 1) { this->PrintParamInfo(); } m_good_bad = itk::ParticleGoodBadAssessment<float, 3>::New(); m_good_bad->SetDomainsPerShape(m_domains_per_shape); m_good_bad->SetCriterionAngle(m_normal_angle); m_good_bad->SetPerformAssessment(m_perform_good_bad); m_energy_a.clear(); m_energy_b.clear(); m_total_energy.clear(); // Now read the transform file if present. if (m_transform_file != "") { this->ReadTransformFile(); } if (m_prefix_transform_file != "") { this->ReadPrefixTransformFile(m_prefix_transform_file); } } //--------------------------------------------------------------------------- Optimize::~Optimize() {} //--------------------------------------------------------------------------- void Optimize::SetVerbosity(int verbosity_level) { this->m_verbosity_level = verbosity_level; } //--------------------------------------------------------------------------- void Optimize::SetDomainsPerShape(int domains_per_shape) { this->m_domains_per_shape = domains_per_shape; this->m_sampler->SetDomainsPerShape(this->m_domains_per_shape); } //--------------------------------------------------------------------------- int Optimize::GetDomainsPerShape() { return this->m_domains_per_shape; } //--------------------------------------------------------------------------- void Optimize::SetNumberOfParticles(std::vector<unsigned int> number_of_particles) { this->m_number_of_particles = number_of_particles; } //--------------------------------------------------------------------------- std::vector<unsigned int> Optimize::GetNumberOfParticles() { return this->m_number_of_particles; } //--------------------------------------------------------------------------- void Optimize::SetTransformFile(std::string filename) { this->m_transform_file = filename; } //--------------------------------------------------------------------------- std::string Optimize::GetTransformFile() { return this->m_transform_file; } //--------------------------------------------------------------------------- void Optimize::SetPrefixTransformFile(std::string prefix_transform_file) { this->m_prefix_transform_file = prefix_transform_file; } //--------------------------------------------------------------------------- std::string Optimize::GetPrefixTransformFile() { return this->m_prefix_transform_file; } //--------------------------------------------------------------------------- void Optimize::SetOutputDir(std::string output_dir) { this->m_output_dir = output_dir; } //--------------------------------------------------------------------------- void Optimize::SetOutputTransformFile(std::string output_transform_file) { this->m_output_transform_file = output_transform_file; } //--------------------------------------------------------------------------- void Optimize::SetUseMeshBasedAttributes(bool use_mesh_based_attributes) { this->m_mesh_based_attributes = use_mesh_based_attributes; if (this->m_mesh_based_attributes) { this->m_sampler->RegisterGeneralShapeMatrices(); } } //--------------------------------------------------------------------------- bool Optimize::GetUseMeshBasedAttributes() { return this->m_mesh_based_attributes; } //--------------------------------------------------------------------------- void Optimize::SetUseXYZ(std::vector<bool> use_xyz) { this->m_use_xyz = use_xyz; } //--------------------------------------------------------------------------- void Optimize::SetUseNormals(std::vector<bool> use_normals) { this->m_use_normals = use_normals; } //--------------------------------------------------------------------------- void Optimize::SetAttributesPerDomain(std::vector<int> attributes_per_domain) { this->m_attributes_per_domain = attributes_per_domain; this->m_sampler->SetAttributesPerDomain(attributes_per_domain); } //--------------------------------------------------------------------------- std::vector<int> Optimize::GetAttributesPerDomain() { return this->m_attributes_per_domain; } //--------------------------------------------------------------------------- void Optimize::SetDistributionDomainID(int distribution_domain_id) { this->m_distribution_domain_id = distribution_domain_id; } //--------------------------------------------------------------------------- int Optimize::GetDistributionDomainID() { return this->m_distribution_domain_id; } //--------------------------------------------------------------------------- void Optimize::SetOutputCuttingPlaneFile(std::string output_cutting_plane_file) { this->m_output_cutting_plane_file = output_cutting_plane_file; } //--------------------------------------------------------------------------- void Optimize::SetUseCuttingPlanes(bool use_cutting_planes) { this->m_use_cutting_planes = use_cutting_planes; } //--------------------------------------------------------------------------- void Optimize::SetCuttingPlane(unsigned int i, const vnl_vector_fixed<double, 3> &va, const vnl_vector_fixed<double, 3> &vb, const vnl_vector_fixed<double, 3> &vc) { this->m_sampler->SetCuttingPlane(i, va, vb, vc); } //--------------------------------------------------------------------------- void Optimize::SetProcessingMode(int mode) { this->m_processing_mode = mode; } //--------------------------------------------------------------------------- void Optimize::SetAdaptivityMode(int adaptivity_mode) { this->m_adaptivity_mode = adaptivity_mode; } //--------------------------------------------------------------------------- void Optimize::SetAdaptivityStrength(double adaptivity_strength) { this->m_adaptivity_strength = adaptivity_strength; } //--------------------------------------------------------------------------- void Optimize::ReadTransformFile() { object_reader < itk::ParticleSystem < 3 > ::TransformType > reader; reader.SetFileName(m_transform_file); reader.Update(); for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { m_sampler->GetParticleSystem()->SetTransform(i, reader.GetOutput()[i]); } } //--------------------------------------------------------------------------- void Optimize::ReadPrefixTransformFile(const std::string &fn) { object_reader < itk::ParticleSystem < 3 > ::TransformType > reader; reader.SetFileName(fn.c_str()); reader.Update(); for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { m_sampler->GetParticleSystem()->SetPrefixTransform(i, reader.GetOutput()[i]); } } //--------------------------------------------------------------------------- // Initialization and Optimization void Optimize::InitializeSampler() { float nbhd_to_sigma = 3.0; // 3.0 -> 1.0 float flat_cutoff = 0.3; // 0.3 -> 0.85 m_sampler->SetPairwisePotentialType(m_pairwise_potential_type); m_sampler->GetGradientFunction()->SetFlatCutoff(flat_cutoff); m_sampler->GetCurvatureGradientFunction()->SetFlatCutoff(flat_cutoff); m_sampler->GetGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma); m_sampler->GetCurvatureGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma); m_sampler->GetModifiedCotangentGradientFunction()->SetFlatCutoff(flat_cutoff); m_sampler->GetModifiedCotangentGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma); m_sampler->GetOmegaGradientFunction()->SetFlatCutoff(flat_cutoff); m_sampler->GetOmegaGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma); m_sampler->GetEnsembleEntropyFunction()->SetMinimumVariance(m_starting_regularization); m_sampler->GetEnsembleEntropyFunction()->SetRecomputeCovarianceInterval(1); m_sampler->GetEnsembleEntropyFunction()->SetHoldMinimumVariance(false); m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVariance( m_starting_regularization); m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetRecomputeCovarianceInterval(1); m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetHoldMinimumVariance(false); m_sampler->GetEnsembleRegressionEntropyFunction()->SetMinimumVariance(m_starting_regularization); m_sampler->GetEnsembleRegressionEntropyFunction()->SetRecomputeCovarianceInterval(1); m_sampler->GetEnsembleRegressionEntropyFunction()->SetHoldMinimumVariance(false); m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVariance(m_starting_regularization); m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetRecomputeCovarianceInterval(1); m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetHoldMinimumVariance(false); m_sampler->GetOptimizer()->SetTimeStep(1.0); if (m_optimizer_type == 0) { m_sampler->GetOptimizer()->SetModeToJacobi(); } else if (m_optimizer_type == 1) { m_sampler->GetOptimizer()->SetModeToGaussSeidel(); } else { m_sampler->GetOptimizer()->SetModeToAdaptiveGaussSeidel(); } m_sampler->SetSamplingOn(); m_sampler->SetCorrespondenceOn(); m_sampler->SetAdaptivityMode(m_adaptivity_mode); m_sampler->GetEnsembleEntropyFunction() ->SetRecomputeCovarianceInterval(m_recompute_regularization_interval); m_sampler->GetMeshBasedGeneralEntropyGradientFunction() ->SetRecomputeCovarianceInterval(m_recompute_regularization_interval); m_sampler->GetEnsembleRegressionEntropyFunction() ->SetRecomputeCovarianceInterval(m_recompute_regularization_interval); m_sampler->GetEnsembleMixedEffectsEntropyFunction() ->SetRecomputeCovarianceInterval(m_recompute_regularization_interval); m_sampler->Initialize(); m_sampler->GetOptimizer()->SetTolerance(0.0); } //--------------------------------------------------------------------------- double Optimize::GetMinNeighborhoodRadius() { double rad = 0.0; typename itk::ImageToVTKImageFilter < ImageType > ::Pointer itk2vtkConnector; for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { const itk::ParticleImageDomain < float, 3 >* domain = static_cast < const itk::ParticleImageDomain < float, 3 > * > (m_sampler->GetParticleSystem() ->GetDomain(i)); itk2vtkConnector = itk::ImageToVTKImageFilter < ImageType > ::New(); itk2vtkConnector->SetInput(domain->GetImage()); vtkSmartPointer < vtkContourFilter > ls = vtkSmartPointer < vtkContourFilter > ::New(); ls->SetInputData(itk2vtkConnector->GetOutput()); ls->SetValue(0, 0.0); ls->Update(); vtkSmartPointer < vtkMassProperties > mp = vtkSmartPointer < vtkMassProperties > ::New(); mp->SetInputData(ls->GetOutput()); mp->Update(); double area = mp->GetSurfaceArea(); double sigma = std::sqrt(area / (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) * M_PI)); if (rad < sigma) { rad = sigma; } } return rad; } //--------------------------------------------------------------------------- void Optimize::AddSinglePoint() { typedef itk::ParticleSystem < 3 > ParticleSystemType; typedef ParticleSystemType::PointType PointType; for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) > 0) { continue; } bool done = false; ImageType::Pointer img = dynamic_cast < itk::ParticleImageDomain < float, 3 >* > ( m_sampler->GetParticleSystem()->GetDomain(i))->GetImage(); itk::ZeroCrossingImageFilter < ImageType, ImageType > ::Pointer zc = itk::ZeroCrossingImageFilter < ImageType, ImageType > ::New(); zc->SetInput(img); zc->Update(); itk::ImageRegionConstIteratorWithIndex < ImageType > it(zc->GetOutput(), zc->GetOutput()->GetRequestedRegion()); for (it.GoToReverseBegin(); !it.IsAtReverseEnd() && done == false; --it) { if (it.Get() == 1.0) { PointType pos; img->TransformIndexToPhysicalPoint(it.GetIndex(), pos); done = true; try { m_sampler->GetParticleSystem()->AddPosition(pos, i); } catch (itk::ExceptionObject &) { done = false; } } } } } //--------------------------------------------------------------------------- void Optimize::Initialize() { if (m_verbosity_level > 0) { std::cout << "------------------------------\n"; std::cout << "*** Initialize Step\n"; std::cout << "------------------------------\n"; } m_disable_checkpointing = true; m_disable_procrustes = false; if (m_procrustes_interval != 0) { // Initial registration for (int i = 0; i < this->m_domains_per_shape; i++) { if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) > 10) { m_procrustes->RunRegistration(i); } } this->WritePointFiles(); this->WriteTransformFile(); } m_disable_procrustes = true; m_sampler->GetParticleSystem()->SynchronizePositions(); m_sampler->GetCurvatureGradientFunction()->SetRho(0.0); m_sampler->GetOmegaGradientFunction()->SetRho(0.0); m_sampler->SetCorrespondenceOn(); if (m_use_shape_statistics_in_init) { if (m_attributes_per_domain.size() > 0 && *std::max_element(m_attributes_per_domain.begin(), m_attributes_per_domain.end()) > 0) { if (m_mesh_based_attributes) { m_sampler->SetCorrespondenceMode(5); } else { m_sampler->SetCorrespondenceMode(2); } } else { if (m_mesh_based_attributes) { m_sampler->SetCorrespondenceMode(5); } else { m_sampler->SetCorrespondenceMode(1); } } m_sampler->GetEnsembleEntropyFunction()->SetMinimumVarianceDecay(m_starting_regularization, m_ending_regularization, m_iterations_per_split); m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVarianceDecay( m_starting_regularization, m_ending_regularization, m_iterations_per_split); } else { // force to mean if ((m_attributes_per_domain.size() > 0 && *std::max_element(m_attributes_per_domain.begin(), m_attributes_per_domain.end()) > 0) || m_mesh_based_attributes) { m_sampler->SetCorrespondenceMode(6); } else { m_sampler->SetCorrespondenceMode(0); } } m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_initial_relative_weighting); m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_initial_relative_weighting); this->AddSinglePoint(); m_sampler->GetParticleSystem()->SynchronizePositions(); int split_number = 0; int n = m_sampler->GetParticleSystem()->GetNumberOfDomains(); vnl_vector_fixed < double, 3 > random; srand(1); for (int i = 0; i < 3; i++) { random[i] = static_cast < double > (rand()); } double norm = random.magnitude(); random /= norm; double epsilon = this->m_spacing; bool flag_split = false; for (int i = 0; i < n; i++) { int d = i % m_domains_per_shape; if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) { flag_split = true; break; } } while (flag_split) { // m_Sampler->GetEnsembleEntropyFunction()->PrintShapeMatrix(); this->OptimizerStop(); for (int i = 0; i < n; i++) { int d = i % m_domains_per_shape; if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) { m_sampler->GetParticleSystem()->SplitAllParticlesInDomain(random, epsilon, i, 0); } } m_sampler->GetParticleSystem()->SynchronizePositions(); split_number++; if (m_verbosity_level > 0) { std::cout << "split number = " << split_number << std::endl; std::cout << std::endl << "Particle count: "; for (unsigned int i = 0; i < this->m_domains_per_shape; i++) { std::cout << m_sampler->GetParticleSystem()->GetNumberOfParticles(i) << " "; } std::cout << std::endl; } if (m_save_init_splits == true) { std::stringstream ss; ss << split_number; std::stringstream ssp; std::string dir_name = "split" + ss.str(); for (int i = 0; i < m_domains_per_shape; i++) { ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i); dir_name += "_" + ssp.str(); ssp.str(""); } dir_name += "pts_wo_opt"; std::string out_path = m_output_dir; std::string tmp_dir_name = out_path + "/" + dir_name; this->WritePointFiles(tmp_dir_name + "/"); this->WritePointFilesWithFeatures(tmp_dir_name + "/"); this->WriteTransformFile(tmp_dir_name + "/" + m_output_transform_file); this->WriteParameters(split_number); } m_energy_a.clear(); m_energy_b.clear(); m_total_energy.clear(); std::stringstream ss; ss << split_number; std::stringstream ssp; ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0 m_str_energy = "split" + ss.str(); for (int i = 0; i < m_domains_per_shape; i++) { ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i); m_str_energy += "_" + ssp.str(); ssp.str(""); } m_str_energy += "pts_init"; if (this->m_pairwise_potential_type == 1) { this->SetCotanSigma(); double minRad = 3.0 * this->GetMinNeighborhoodRadius(); m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad); m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius( minRad); } m_saturation_counter = 0; m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(m_iterations_per_split); m_sampler->GetOptimizer()->SetNumberOfIterations(0); m_sampler->Modified(); m_sampler->Update(); if (m_save_init_splits == true) { std::stringstream ss; ss << split_number; std::stringstream ssp; std::string dir_name = "split" + ss.str(); for (int i = 0; i < m_domains_per_shape; i++) { ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i); dir_name += "_" + ssp.str(); ssp.str(""); } dir_name += "pts_w_opt"; std::string out_path = m_output_dir; std::string tmp_dir_name = out_path + "/" + dir_name; this->WritePointFiles(tmp_dir_name + "/"); this->WritePointFilesWithFeatures(tmp_dir_name + "/"); this->WriteTransformFile(tmp_dir_name + "/" + m_output_transform_file); this->WriteParameters(split_number); } this->WritePointFiles(); this->WritePointFilesWithFeatures(); this->WriteEnergyFiles(); this->WriteTransformFile(); flag_split = false; for (int i = 0; i < n; i++) { int d = i % m_domains_per_shape; if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) { flag_split = true; break; } } } this->WritePointFiles(); this->WritePointFilesWithFeatures(); this->WriteTransformFile(); this->WriteCuttingPlanePoints(); if (m_verbosity_level > 0) { std::cout << "Finished initialization!!!" << std::endl; } } //--------------------------------------------------------------------------- void Optimize::AddAdaptivity() { if (m_verbosity_level > 0) { std::cout << "------------------------------\n"; std::cout << "*** AddAdaptivity Step\n"; std::cout << "------------------------------\n"; } if (m_adaptivity_strength == 0.0) { return;} m_disable_checkpointing = true; m_disable_procrustes = true; if (this->m_pairwise_potential_type == 1) { this->SetCotanSigma(); } double minRad = 3.0 * this->GetMinNeighborhoodRadius(); m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad); m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad); m_sampler->GetCurvatureGradientFunction()->SetRho(m_adaptivity_strength); m_sampler->GetOmegaGradientFunction()->SetRho(m_adaptivity_strength); m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_initial_relative_weighting); m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_initial_relative_weighting); m_saturation_counter = 0; m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(m_iterations_per_split); m_sampler->GetOptimizer()->SetNumberOfIterations(0); m_sampler->Modified(); m_sampler->Update(); this->WritePointFiles(); this->WritePointFilesWithFeatures(); this->WriteTransformFile(); this->WriteCuttingPlanePoints(); if (m_verbosity_level > 0) { std::cout << "Finished adaptivity!!!" << std::endl; } } //--------------------------------------------------------------------------- void Optimize::RunOptimize() { if (m_verbosity_level > 0) { std::cout << "------------------------------\n"; std::cout << "*** Optimize Step\n"; std::cout << "------------------------------\n"; } m_optimizing = true; m_sampler->GetCurvatureGradientFunction()->SetRho(m_adaptivity_strength); m_sampler->GetOmegaGradientFunction()->SetRho(m_adaptivity_strength); m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_relative_weighting); m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_relative_weighting); if (this->m_pairwise_potential_type == 1) { this->SetCotanSigma(); double minRad = 3.0 * this->GetMinNeighborhoodRadius(); m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad); m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius( minRad); } m_disable_checkpointing = false; m_disable_procrustes = false; if (m_procrustes_interval != 0) { // Initial registration m_procrustes->RunRegistration(); this->WritePointFiles(); this->WriteTransformFile(); if (m_use_cutting_planes == true && m_distribution_domain_id > -1) { // transform cutting planes m_sampler->TransformCuttingPlanes(m_distribution_domain_id); } } if (m_optimizer_type == 0) { m_sampler->GetOptimizer()->SetModeToJacobi(); } else if (m_optimizer_type == 1) { m_sampler->GetOptimizer()->SetModeToGaussSeidel(); } else { m_sampler->GetOptimizer()->SetModeToAdaptiveGaussSeidel(); } // Set up the minimum variance decay m_sampler->GetEnsembleEntropyFunction()->SetMinimumVarianceDecay(m_starting_regularization, m_ending_regularization, m_optimization_iterations - m_optimization_iterations_completed); m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVarianceDecay( m_starting_regularization, m_ending_regularization, m_optimization_iterations - m_optimization_iterations_completed); m_sampler->GetEnsembleRegressionEntropyFunction()->SetMinimumVarianceDecay( m_starting_regularization, m_ending_regularization, m_optimization_iterations - m_optimization_iterations_completed); m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVarianceDecay( m_starting_regularization, m_ending_regularization, m_optimization_iterations - m_optimization_iterations_completed); m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVarianceDecay( m_starting_regularization, m_ending_regularization, m_optimization_iterations - m_optimization_iterations_completed); m_sampler->SetCorrespondenceOn(); if ((m_attributes_per_domain.size() > 0 && *std::max_element(m_attributes_per_domain.begin(), m_attributes_per_domain.end()) > 0) || m_mesh_based_attributes) { m_sampler->SetCorrespondenceMode(5); } else if (m_use_regression == true) { if (m_use_mixed_effects == true) { m_sampler->SetCorrespondenceMode(4); // MixedEffects } else { m_sampler->SetCorrespondenceMode(3); // Regression } } else if (m_starting_regularization == m_ending_regularization) { m_sampler->SetCorrespondenceMode(0); // mean force } else { m_sampler->SetCorrespondenceMode(1); // Ensemble Entropy } if (m_optimization_iterations - m_optimization_iterations_completed > 0) { m_sampler->GetOptimizer()->SetMaximumNumberOfIterations( m_optimization_iterations - m_optimization_iterations_completed); } else { m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(0);} m_energy_a.clear(); m_energy_b.clear(); m_total_energy.clear(); m_str_energy = "opt"; m_saturation_counter = 0; m_sampler->GetOptimizer()->SetNumberOfIterations(0); m_sampler->GetOptimizer()->SetTolerance(0.0); m_sampler->Modified(); m_sampler->Update(); this->WritePointFiles(); this->WritePointFilesWithFeatures(); this->WriteEnergyFiles(); this->WriteTransformFile(); this->WriteModes(); this->WriteCuttingPlanePoints(); this->WriteParameters(); if (m_verbosity_level > 0) { std::cout << "Finished optimization!!!" << std::endl; } } //--------------------------------------------------------------------------- void Optimize::OptimizeStart() { m_sampler->GetOptimizer()->StartOptimization(); } //--------------------------------------------------------------------------- void Optimize::OptimizerStop() { m_sampler->GetOptimizer()->StopOptimization(); } //--------------------------------------------------------------------------- void Optimize::AbortOptimization() { this->m_aborted = true; this->m_sampler->GetOptimizer()->AbortProcessing(); } //--------------------------------------------------------------------------- void Optimize::IterateCallback(itk::Object*, const itk::EventObject &) { if (m_perform_good_bad == true) { std::vector < std::vector < int >> tmp; tmp = m_good_bad->RunAssessment(m_sampler->GetParticleSystem(), m_sampler->GetMeanCurvatureCache()); if (!tmp.empty()) { if (this->m_bad_ids.empty()) { this->m_bad_ids.resize(m_domains_per_shape); } for (int i = 0; i < m_domains_per_shape; i++) { for (int j = 0; j < tmp[i].size(); j++) { if (m_bad_ids[i].empty()) { this->m_bad_ids[i].push_back(tmp[i][j]); } else { if (std::count(m_bad_ids[i].begin(), m_bad_ids[i].end(), tmp[i][j]) == 0) { this->m_bad_ids[i].push_back(tmp[i][j]); } } } } } ReportBadParticles(); } this->ComputeEnergyAfterIteration(); int lnth = m_total_energy.size(); if (lnth > 1) { double val = std::abs(m_total_energy[lnth - 1] - m_total_energy[lnth - 2]) / std::abs( m_total_energy[lnth - 2]); if ((m_optimizing == false && val < m_initialization_criterion) || (m_optimizing == true && val < m_optimization_criterion)) { m_saturation_counter++; } else { m_saturation_counter = 0; } if (m_saturation_counter > 10) { if (m_verbosity_level > 2) { std::cout << " \n ----Early termination due to minimal energy decay---- \n"; } this->OptimizerStop(); } } if (m_checkpointing_interval != 0 && m_disable_checkpointing == false) { m_checkpoint_counter++; if (m_checkpoint_counter == (int)m_checkpointing_interval) { m_checkpoint_counter = 0; this->WritePointFiles(); this->WriteTransformFile(); this->WritePointFilesWithFeatures(); this->WriteModes(); this->WriteParameters(); this->WriteEnergyFiles(); } } if (m_optimizing == false) { return;} if (m_procrustes_interval != 0 && m_disable_procrustes == false) { m_procrustes_counter++; if (m_procrustes_counter >= (int)m_procrustes_interval) { m_procrustes_counter = 0; m_procrustes->RunRegistration(); if (m_use_cutting_planes == true && m_distribution_domain_id > -1) { // transform cutting planes m_sampler->TransformCuttingPlanes(m_distribution_domain_id); } } } static unsigned int iteration_no = 0; // Checkpointing after procrustes (override for optimizing step) if (m_checkpointing_interval != 0 && m_disable_checkpointing == false) { m_checkpoint_counter++; if (m_checkpoint_counter == (int)m_checkpointing_interval) { iteration_no += m_checkpointing_interval; m_checkpoint_counter = 0; this->WritePointFiles(); this->WriteTransformFile(); this->WritePointFilesWithFeatures(); this->WriteModes(); this->WriteParameters(); this->WriteEnergyFiles(); if (m_keep_checkpoints) { this->WritePointFiles(iteration_no); this->WritePointFilesWithFeatures(iteration_no); this->WriteTransformFile(iteration_no); this->WriteParameters(iteration_no); } } } } //--------------------------------------------------------------------------- void Optimize::ComputeEnergyAfterIteration() { int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains(); double corrEnergy = 0.0; double sampEnergy = 0.0; for (int i = 0; i < numShapes; i++) { m_sampler->GetLinkingFunction()->SetDomainNumber(i); for (int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) { if (m_sampler->GetParticleSystem()->GetDomainFlag(i)) { sampEnergy += 0.0; } else { sampEnergy += m_sampler->GetLinkingFunction()->EnergyA(j, i, m_sampler->GetParticleSystem()); } if (m_sampler->GetCorrespondenceMode() == 0) { corrEnergy += m_sampler->GetLinkingFunction()->EnergyB(j, i, m_sampler->GetParticleSystem()); } } } if (m_sampler->GetCorrespondenceMode() > 0) { corrEnergy = m_sampler->GetLinkingFunction()->EnergyB(0, 0, m_sampler->GetParticleSystem()); } double totalEnergy = sampEnergy + corrEnergy; m_energy_a.push_back(sampEnergy); m_energy_b.push_back(corrEnergy); m_total_energy.push_back(totalEnergy); if (m_verbosity_level > 2) { std::cout << "Energy: " << totalEnergy << std::endl; } } //--------------------------------------------------------------------------- void Optimize::SetCotanSigma() { itk::ImageToVTKImageFilter<ImageType>::Pointer itk2vtkConnector; m_sampler->GetModifiedCotangentGradientFunction()->ClearGlobalSigma(); for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { using DomainType = itk::ParticleImageDomain<float, 3>; const DomainType* domain = static_cast<const DomainType*> (m_sampler->GetParticleSystem()->GetDomain(i)); itk2vtkConnector = itk::ImageToVTKImageFilter<ImageType>::New(); itk2vtkConnector->SetInput(domain->GetImage()); vtkSmartPointer<vtkContourFilter> ls = vtkSmartPointer<vtkContourFilter>::New(); ls->SetInputData(itk2vtkConnector->GetOutput()); ls->SetValue(0, 0.0); ls->Update(); vtkSmartPointer<vtkMassProperties> mp = vtkSmartPointer<vtkMassProperties>::New(); mp->SetInputData(ls->GetOutput()); mp->Update(); double area = mp->GetSurfaceArea(); double sigma = m_cotan_sigma_factor * std::sqrt(area / (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) * M_PI)); m_sampler->GetModifiedCotangentGradientFunction()->SetGlobalSigma(sigma); } } // File writers and info display functions //--------------------------------------------------------------------------- void Optimize::PrintParamInfo() { if (m_verbosity_level < 2) { return; } #ifdef SW_USE_OPENMP std::cout << "OpenMP is enabled ... \n" << std::flush; #else std::cout << "OpenMP is disabled ... \n" << std::flush; #endif // Write out the parameters std::cout << "---------------------" << std::endl; std::cout << " I/O parameters" << std::endl; std::cout << "---------------------" << std::endl << std::endl; std::cout << "Domains per shape = " << m_domains_per_shape << std::endl; std::cout << m_filenames.size() << " image files provided!!!" << std::endl; if (m_domain_flags.size() > 0) { std::cout << "Following " << m_domain_flags.size() << " domains have been declared fixed: " << std::endl; for (int i = 0; i < m_domain_flags.size(); i++) { std::cout << m_domain_flags[i] << "\t" << m_filenames[m_domain_flags[i]] << std::endl; } std::cout << std::endl; } if (m_adaptivity_mode == 3) { std::cout << std::endl << std::endl << "*****Using constraints on shapes*****" << std::endl; } std::cout << "Target number of particles = "; if (m_domains_per_shape == 1) { std::cout << m_number_of_particles[0]; } else { for (unsigned int i = 0; i < this->m_domains_per_shape; i++) { std::cout << "domain " << i << " : " << m_number_of_particles[i] << ", "; } } std::cout << std::endl; if (m_particle_flags.size() > 0) { std::cout << "Total " << m_particle_flags.size() / 2 << " particles have been declared fixed." << std::endl; } if (m_mesh_based_attributes) { std::cout << std::endl << std::endl << "*****Using attributes*****" << std::endl; std::cout << "Domain(s) using XYZ: "; for (int i = 0; i < m_domains_per_shape; i++) { if (m_use_xyz[i]) { std::cout << i << " "; } } std::cout << std::endl; std::cout << "Domain(s) using Normals: "; for (int i = 0; i < m_domains_per_shape; i++) { if (m_use_normals[i]) { std::cout << i << " "; } } std::cout << std::endl; if (this->m_attributes_per_domain.size() > 0) { std::cout << "Other attributes per domain:" << std::endl; for (int i = 0; i < m_domains_per_shape; i++) { std::cout << i << ":" << m_attributes_per_domain[i] << " "; } std::cout << std::endl; } } if (m_transform_file.length() > 0) { std::cout << "m_transform_file = " << m_transform_file << std::endl; } if (m_prefix_transform_file.length() > 0) { std::cout << "m_prefix_transform_file = " << m_prefix_transform_file << std::endl; } std::cout << "Output path = " << m_output_dir << std::endl; std::cout << "Output transform filename = " << m_output_transform_file << std::endl; std::cout << std::endl; std::cout << "------------------------------" << std::endl; std::cout << " Optimization parameters" << std::endl; std::cout << "------------------------------" << std::endl; std::cout << "Processing modes = "; if (m_processing_mode >= 0) { std::cout << "Initialization"; } if ((m_processing_mode >= 1 || m_processing_mode == -1) && m_adaptivity_strength > 0.0) { std::cout << ", Adaptivity"; } if (m_processing_mode >= 2 || m_processing_mode == -2) { std::cout << ", Optimization"; } std::cout << std::endl; if (m_adaptivity_strength > 0.0) { std::cout << "adaptivity_strength = " << m_adaptivity_strength << std::endl; } std::cout << "pairwise_potential_type = "; if (m_pairwise_potential_type == 0) { std::cout << "gaussian" << std::endl; } else { std::cout << "cotan" << std::endl; } std::cout << "optimizer_type = "; if (m_optimizer_type == 0) { std::cout << "jacobi"; } else if (m_optimizer_type == 1) { std::cout << "gauss seidel"; } else if (m_optimizer_type == 2) { std::cout << "adaptive gauss seidel (with bad moves)"; } else { std::cerr << "Incorrect option!!"; throw 1; } std::cout << std::endl; std::cout << "m_optimization_iterations = " << m_optimization_iterations << std::endl; std::cout << "m_optimization_iterations_completed = " << m_optimization_iterations_completed << std::endl; std::cout << "m_iterations_per_split = " << m_iterations_per_split << std::endl; std::cout << "m_init_criterion = " << m_initialization_criterion << std::endl; std::cout << "m_opt_criterion = " << m_optimization_criterion << std::endl; std::cout << "m_use_shape_statistics_in_init = " << m_use_shape_statistics_in_init << std::endl; std::cout << "m_procrustes_interval = " << m_procrustes_interval << std::endl; std::cout << "m_procrustes_scaling = " << m_procrustes_scaling << std::endl; std::cout << "m_relative_weighting = " << m_relative_weighting << std::endl; std::cout << "m_initial_relative_weighting = " << m_initial_relative_weighting << std::endl; std::cout << "m_starting_regularization = " << m_starting_regularization << std::endl; std::cout << "m_ending_regularization = " << m_ending_regularization << std::endl; std::cout << "m_recompute_regularization_interval = " << m_recompute_regularization_interval << std::endl; std::cout << "m_save_init_splits = " << m_save_init_splits << std::endl; std::cout << "m_checkpointing_interval = " << m_checkpointing_interval << std::endl; std::cout << "m_keep_checkpoints = " << m_keep_checkpoints << std::endl; std::cout << std::endl; if (m_perform_good_bad) { std::cout << "Debug: Bad particles will be reported during optimization, expect significant delays!!! " << std::endl; } if (m_log_energy) { std::cout << "Debug: Write energy logs, might increase runtime!!! " << std::endl; } } //--------------------------------------------------------------------------- void Optimize::WriteTransformFile(int iter) const { if (!this->m_file_output_enabled) { return; } std::string output_file = m_output_dir + "/" + m_output_transform_file; if (iter >= 0) { std::stringstream ss; ss << iter + m_optimization_iterations_completed; std::stringstream ssp; ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0 output_file = m_output_dir + "/iter" + ss.str() + "_p" + ssp.str() + "/" + m_output_transform_file; } this->WriteTransformFile(output_file); } //--------------------------------------------------------------------------- void Optimize::WriteTransformFile(std::string iter_prefix) const { if (!this->m_file_output_enabled) { return; } std::string output_file = iter_prefix; std::vector < itk::ParticleSystem < 3 > ::TransformType > tlist; for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { tlist.push_back(m_sampler->GetParticleSystem()->GetTransform(i)); } std::string str = "writing " + output_file + " ..."; PrintStartMessage(str); object_writer < itk::ParticleSystem < 3 > ::TransformType > writer; writer.SetFileName(output_file); writer.SetInput(tlist); writer.Update(); PrintDoneMessage(); } //--------------------------------------------------------------------------- void Optimize::WritePointFiles(int iter) { if (!this->m_file_output_enabled) { return; } std::stringstream ss; ss << iter + m_optimization_iterations_completed; std::stringstream ssp; ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0 std::string out_path = m_output_dir; std::string tmp_dir_name = iter >= 0 ? out_path + "/iter" + ss.str() + "_p" + ssp.str() : out_path; this->WritePointFiles(tmp_dir_name); } //--------------------------------------------------------------------------- void Optimize::WritePointFiles(std::string iter_prefix) { if (!this->m_file_output_enabled) { return; } this->PrintStartMessage("Writing point files...\n"); #ifdef _WIN32 mkdir(iter_prefix.c_str()); #else mkdir(iter_prefix.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType; const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains(); int counter; for (int i = 0; i < n; i++) { counter = 0; std::string local_file = iter_prefix + "/" + m_filenames[i] + "_local.particles"; std::string world_file = iter_prefix + "/" + m_filenames[i] + "_world.particles"; std::ofstream out(local_file.c_str()); std::ofstream outw(world_file.c_str()); std::string str = "Writing " + world_file + " and " + local_file + " files..."; this->PrintStartMessage(str, 1); if (!out) { std::cerr << "Error opening output file: " << local_file << std::endl; throw 1; } if (!outw) { std::cerr << "Error opening output file: " << world_file << std::endl; throw 1; } for (unsigned int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) { PointType pos = m_sampler->GetParticleSystem()->GetPosition(j, i); PointType wpos = m_sampler->GetParticleSystem()->GetTransformedPosition(j, i); for (unsigned int k = 0; k < 3; k++) { out << pos[k] << " "; } out << std::endl; for (unsigned int k = 0; k < 3; k++) { outw << wpos[k] << " "; } outw << std::endl; counter++; } // end for points out.close(); outw.close(); std::stringstream st; st << counter; str = "with " + st.str() + "points..."; this->PrintStartMessage(str, 1); this->PrintDoneMessage(1); } // end for files this->PrintDoneMessage(); } //--------------------------------------------------------------------------- void Optimize::WritePointFilesWithFeatures(int iter) { if (!this->m_file_output_enabled) { return; } std::stringstream ss; ss << iter + m_optimization_iterations_completed; std::stringstream ssp; ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0 std::string out_path = m_output_dir; std::string tmp_dir_name = iter >= 0 ? out_path + "/iter" + ss.str() + "_p" + ssp.str() : out_path; this->WritePointFilesWithFeatures(tmp_dir_name); } //--------------------------------------------------------------------------- void Optimize::WritePointFilesWithFeatures(std::string iter_prefix) { if (!this->m_file_output_enabled) { return; } if (!m_mesh_based_attributes) { return; } this->PrintStartMessage("Writing point with attributes files...\n"); typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType; const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains(); int counter; for (int i = 0; i < n; i++) { counter = 0; std::string world_file = iter_prefix + "/" + m_filenames[i] + "_wptsFeatures.particles"; std::ofstream outw(world_file.c_str()); std::string str = "Writing " + world_file + "..."; int attrNum = 3 * int(m_use_xyz[i % m_domains_per_shape]) + 3 * int(m_use_normals[i % m_domains_per_shape]); if (m_attributes_per_domain.size() > 0) { attrNum += m_attributes_per_domain[i % m_domains_per_shape]; } std::stringstream st; st << attrNum; str += "with " + st.str() + " attributes per point..."; this->PrintStartMessage(str, 1); if (!outw) { std::cerr << "Error opening output file: " << world_file << std::endl; throw 1; } const itk::ParticleImplicitSurfaceDomain < float, 3 >* domain = static_cast < const itk::ParticleImplicitSurfaceDomain < float, 3 >* > (m_sampler-> GetParticleSystem()-> GetDomain(i)); const itk::ParticleImageDomainWithGradients < float, 3 >* domainWithGrad = static_cast < const itk::ParticleImageDomainWithGradients < float, 3 >* > (m_sampler-> GetParticleSystem()-> GetDomain(i)); TriMesh* ptr; std::vector < float > fVals; if (m_mesh_based_attributes && m_attributes_per_domain.size() > 0) { if (m_attributes_per_domain[i % m_domains_per_shape] > 0) { ptr = domain->GetMesh(); } } for (unsigned int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) { PointType pos = m_sampler->GetParticleSystem()->GetPosition(j, i); PointType wpos = m_sampler->GetParticleSystem()->GetTransformedPosition(j, i); for (unsigned int k = 0; k < 3; k++) { outw << wpos[k] << " "; } if (m_use_normals[i % m_domains_per_shape]) { // if (m_Sampler->GetParticleSystem()->GetDomainFlag(i)) // { // outw << 0.0 << " " << 0.0 << " " << 0.0 << " "; // } // else // { typename itk::ParticleImageDomainWithGradients < float, 3 > ::VnlVectorType pG = domainWithGrad->SampleNormalVnl(pos); VectorType pN; pN[0] = pG[0]; pN[1] = pG[1]; pN[2] = pG[2]; pN = m_sampler->GetParticleSystem()->TransformVector(pN, m_sampler->GetParticleSystem()->GetTransform( i) * m_sampler->GetParticleSystem()->GetPrefixTransform( i)); outw << pN[0] << " " << pN[1] << " " << pN[2] << " "; // } } if (m_attributes_per_domain.size() > 0) { if (m_attributes_per_domain[i % m_domains_per_shape] > 0) { // if (m_Sampler->GetParticleSystem()->GetDomainFlag(i)) // { // for (unsigned int k = 0; k < m_attributes_per_domain[i % m_domains_per_shape]; k++) // outw << 0.0 << " "; // } // else // { point pt; pt.clear(); pt[0] = pos[0]; pt[1] = pos[1]; pt[2] = pos[2]; fVals.clear(); ptr->GetFeatureValues(pt, fVals); for (unsigned int k = 0; k < m_attributes_per_domain[i % m_domains_per_shape]; k++) { outw << fVals[k] << " "; } // } } } outw << std::endl; counter++; } // end for points outw.close(); this->PrintDoneMessage(1); } // end for files this->PrintDoneMessage(); } //--------------------------------------------------------------------------- void Optimize::WriteEnergyFiles() { if (!this->m_file_output_enabled) { return; } if (!this->m_log_energy) { return; } this->PrintStartMessage("Writing energy files...\n"); std::string strA = m_output_dir + "/" + this->m_str_energy + "_samplingEnergy.txt"; std::string strB = m_output_dir + "/" + this->m_str_energy + "_correspondenceEnergy.txt"; std::string strTotal = m_output_dir + "/" + this->m_str_energy + "_totalEnergy.txt"; std::ofstream outA(strA.c_str(), std::ofstream::app); std::ofstream outB(strB.c_str(), std::ofstream::app); std::ofstream outTotal(strTotal.c_str(), std::ofstream::app); if (!outA) { std::cerr << "Error opening output energy file: " << strA << std::endl; throw 1; } if (!outB) { std::cerr << "Error opening output energy file: " << strB << std::endl; throw 1; } if (!outTotal) { std::cerr << "Error opening output energy file: " << strTotal << std::endl; throw 1; } int n = m_energy_a.size() - 1; n = n < 0 ? 0 : n; std::string str = "Appending to " + strA + " ..."; this->PrintStartMessage(str, 1); outA << m_energy_a[n] << std::endl; outA.close(); this->PrintDoneMessage(1); str = "Appending to " + strB + " ..."; this->PrintStartMessage(str, 1); outB << m_energy_b[n] << std::endl; outB.close(); this->PrintDoneMessage(1); str = "Appending to " + strTotal + " ..."; this->PrintStartMessage(str, 1); outTotal << m_total_energy[n] << std::endl; outTotal.close(); this->PrintDoneMessage(1); this->PrintDoneMessage(); } //--------------------------------------------------------------------------- void Optimize::WriteCuttingPlanePoints(int iter) { if (!this->m_file_output_enabled) { return; } this->PrintStartMessage("Writing cutting plane points...\n"); std::string output_file = m_output_cutting_plane_file; if (iter >= 0) { std::stringstream ss; ss << iter + m_optimization_iterations_completed; output_file = "./iter" + ss.str() + "/" + output_file; } std::ofstream out(output_file.c_str()); std::string str = "Writing " + output_file + "..."; this->PrintStartMessage(str, 1); for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) { const itk::ParticleImplicitSurfaceDomain < float, 3 >* dom = static_cast < const itk::ParticleImplicitSurfaceDomain < float , 3 >* > (m_sampler-> GetParticleSystem()-> GetDomain(i)); for (unsigned int j = 0; j < dom->GetNumberOfPlanes(); j++) { vnl_vector_fixed < double, 3 > a = dom->GetA(j); vnl_vector_fixed < double, 3 > b = dom->GetB(j); vnl_vector_fixed < double, 3 > c = dom->GetC(j); for (int d = 0; d < 3; d++) { out << a[d] << " "; } for (int d = 0; d < 3; d++) { out << b[d] << " "; } for (int d = 0; d < 3; d++) { out << c[d] << " "; } out << std::endl; } } out.close(); this->PrintDoneMessage(1); this->PrintDoneMessage(); } //--------------------------------------------------------------------------- void Optimize::WriteParameters(int iter) { if (!this->m_file_output_enabled) { return; } if (!m_use_regression) { return; } std::string slopename, interceptname; slopename = std::string(m_output_dir) + std::string("slope"); interceptname = std::string(m_output_dir) + std::string("intercept"); if (iter >= 0) { std::stringstream ss; ss << iter + m_optimization_iterations_completed; slopename = "./.iter" + ss.str() + "/" + slopename; interceptname = "./.iter" + ss.str() + "/" + interceptname; } std::cout << "writing " << slopename << std::endl; std::cout << "writing " << interceptname << std::endl; std::vector < double > slope; std::vector < double > intercept; if (m_use_mixed_effects == true) { vnl_vector < double > slopevec = dynamic_cast < itk::ParticleShapeMixedEffectsMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleMixedEffectsEntropyFunction()-> GetShapeMatrix())->GetSlope(); for (unsigned int i = 0; i < slopevec.size(); i++) { slope.push_back(slopevec[i]); } std::ofstream out(slopename.c_str()); for (unsigned int i = 0; i < slope.size(); i++) { out << slope[i] << "\n"; } out.close(); vnl_vector < double > interceptvec = dynamic_cast < itk::ParticleShapeMixedEffectsMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleMixedEffectsEntropyFunction()-> GetShapeMatrix())->GetIntercept(); for (unsigned int i = 0; i < slopevec.size(); i++) { intercept.push_back(interceptvec[i]); } out.open(interceptname.c_str()); for (unsigned int i = 0; i < slope.size(); i++) { out << intercept[i] << "\n"; } out.close(); slopename = std::string(m_output_dir) + std::string("sloperand"); interceptname = std::string(m_output_dir) + std::string("interceptrand"); if (iter >= 0) { std::stringstream ss; ss << iter + m_optimization_iterations_completed; slopename = "./.iter" + ss.str() + "/" + slopename; interceptname = "./.iter" + ss.str() + "/" + interceptname; } std::cout << "writing " << slopename << std::endl; std::cout << "writing " << interceptname << std::endl; vnl_matrix < double > sloperand_mat = dynamic_cast < itk::ParticleShapeMixedEffectsMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleMixedEffectsEntropyFunction()-> GetShapeMatrix())->GetSlopeRandom(); out.open(slopename.c_str()); for (unsigned int i = 0; i < sloperand_mat.rows(); i++) { for (unsigned int j = 0; j < sloperand_mat.cols(); j++) { out << sloperand_mat.get(i, j) << " "; } out << "\n"; } out.close(); vnl_matrix < double > interceptrand_mat = dynamic_cast < itk::ParticleShapeMixedEffectsMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleMixedEffectsEntropyFunction()-> GetShapeMatrix())->GetInterceptRandom(); out.open(interceptname.c_str()); for (unsigned int i = 0; i < interceptrand_mat.rows(); i++) { for (unsigned int j = 0; j < interceptrand_mat.cols(); j++) { out << interceptrand_mat.get(i, j) << " "; } out << "\n"; } out.close(); } else { vnl_vector < double > slopevec = dynamic_cast < itk::ParticleShapeLinearRegressionMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleRegressionEntropyFunction()-> GetShapeMatrix())->GetSlope(); for (unsigned int i = 0; i < slopevec.size(); i++) { slope.push_back(slopevec[i]); } std::ofstream out(slopename.c_str()); for (unsigned int i = 0; i < slope.size(); i++) { out << slope[i] << "\n"; } out.close(); std::vector < double > intercept; vnl_vector < double > interceptvec = dynamic_cast < itk::ParticleShapeLinearRegressionMatrixAttribute < double, 3 >* > (m_sampler->GetEnsembleRegressionEntropyFunction()-> GetShapeMatrix())->GetIntercept(); for (unsigned int i = 0; i < slopevec.size(); i++) { intercept.push_back(interceptvec[i]); } out.open(interceptname.c_str()); for (unsigned int i = 0; i < slope.size(); i++) { out << intercept[i] << "\n"; } out.close(); } } //--------------------------------------------------------------------------- void Optimize::ReportBadParticles() { if (!this->m_file_output_enabled) { return; } this->PrintStartMessage("Reporting bad particles...", 2); typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType; const int totalDomains = m_sampler->GetParticleSystem()->GetNumberOfDomains(); const int numShapes = totalDomains / m_domains_per_shape; std::string outDomDir; std::string outPtDir; if (this->m_bad_ids.empty()) { return; } for (int i = 0; i < this->m_domains_per_shape; i++) { if (this->m_bad_ids[i].empty()) { continue; } std::stringstream ss; ss << i; outDomDir = m_output_dir + "/" + this->m_str_energy + "_BadParticles_domain" + ss.str(); #ifdef _WIN32 mkdir(outDomDir.c_str()); #else mkdir(outDomDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif for (int j = 0; j < this->m_bad_ids[i].size(); j++) { std::stringstream ssj; ssj << m_bad_ids[i][j]; outPtDir = outDomDir + "/particle" + ssj.str(); #ifdef _WIN32 mkdir(outPtDir.c_str()); #else mkdir(outPtDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif for (int k = 0; k < numShapes; k++) { int dom = k * m_domains_per_shape + i; std::string localPtFile = outPtDir + "/" + m_filenames[dom] + ".particles"; std::ofstream outl(localPtFile.c_str(), std::ofstream::app); PointType pos = m_sampler->GetParticleSystem()->GetPosition(m_bad_ids[i][j], dom); for (unsigned int d = 0; d < 3; d++) { outl << pos[d] << " "; } outl << std::endl; outl.close(); } } } this->PrintDoneMessage(2); } //--------------------------------------------------------------------------- std::vector<std::vector<itk::Point<double>>> Optimize::GetLocalPoints() { return this->m_local_points; } //--------------------------------------------------------------------------- std::vector<std::vector<itk::Point<double>>> Optimize::GetGlobalPoints() { return this->m_global_points; } //--------------------------------------------------------------------------- void Optimize::SetCutPlanes(std::vector<std::array<itk::Point<double>, 3>> cut_planes) { this->m_cut_planes = cut_planes; } //--------------------------------------------------------------------------- bool Optimize::GetAborted() { return this->m_aborted; } //--------------------------------------------------------------------------- void Optimize::UpdateExportablePoints() { this->m_local_points.clear(); this->m_global_points.clear(); for (size_t d = 0; d < this->m_sampler-> GetParticleSystem()->GetNumberOfDomains(); d++) { // blank set of points this->m_local_points.push_back(std::vector<itk::Point<double>>()); this->m_global_points.push_back(std::vector<itk::Point<double>>()); // for each particle for (size_t j = 0; j < this->m_sampler-> GetParticleSystem()->GetNumberOfParticles(d); j++) { auto pos = this->m_sampler->GetParticleSystem()->GetPosition(j, d); auto pos2 = this->m_sampler->GetParticleSystem()->GetTransformedPosition(j, d); this->m_local_points[d].push_back(pos); this->m_global_points[d].push_back(pos2); } } } //--------------------------------------------------------------------------- void Optimize::SetPairwisePotentialType(int pairwise_potential_type) { this->m_pairwise_potential_type = pairwise_potential_type;} //--------------------------------------------------------------------------- void Optimize::SetOptimizerType(int optimizer_type) { this->m_optimizer_type = optimizer_type;} //--------------------------------------------------------------------------- void Optimize::SetTimePtsPerSubject(int time_pts_per_subject) { this->m_timepts_per_subject = time_pts_per_subject;} //--------------------------------------------------------------------------- int Optimize::GetTimePtsPerSubject() { return this->m_timepts_per_subject; } //--------------------------------------------------------------------------- void Optimize::SetOptimizationIterations(int optimization_iterations) { this->m_optimization_iterations = optimization_iterations;} //--------------------------------------------------------------------------- void Optimize::SetOptimizationIterationsCompleted(int optimization_iterations_completed) { this->m_optimization_iterations_completed = optimization_iterations_completed;} //--------------------------------------------------------------------------- void Optimize::SetIterationsPerSplit(int iterations_per_split) { this->m_iterations_per_split = iterations_per_split;} //--------------------------------------------------------------------------- void Optimize::SetInitializationCriterion(double init_criterion) { this->m_initialization_criterion = init_criterion;} //--------------------------------------------------------------------------- void Optimize::SetOptimizationCriterion(double opt_criterion) { this->m_optimization_criterion = opt_criterion;} //--------------------------------------------------------------------------- void Optimize::SetUseShapeStatisticsInInit(bool use_shape_statistics_in_init) { this->m_use_shape_statistics_in_init = use_shape_statistics_in_init;} //--------------------------------------------------------------------------- void Optimize::SetProcrustesInterval(int procrustes_interval) { this->m_procrustes_interval = procrustes_interval;} //--------------------------------------------------------------------------- void Optimize::SetProcrustesScaling(int procrustes_scaling) { this->m_procrustes_scaling = procrustes_scaling;} //--------------------------------------------------------------------------- void Optimize::SetRelativeWeighting(double relative_weighting) { this->m_relative_weighting = relative_weighting;} //--------------------------------------------------------------------------- void Optimize::SetInitialRelativeWeighting(double initial_relative_weighting) { this->m_initial_relative_weighting = initial_relative_weighting;} //--------------------------------------------------------------------------- void Optimize::SetStartingRegularization(double starting_regularization) { this->m_starting_regularization = starting_regularization;} //--------------------------------------------------------------------------- void Optimize::SetEndingRegularization(double ending_regularization) { this->m_ending_regularization = ending_regularization;} //--------------------------------------------------------------------------- void Optimize::SetRecomputeRegularizationInterval(int recompute_regularization_interval) { this->m_recompute_regularization_interval = recompute_regularization_interval;} //--------------------------------------------------------------------------- void Optimize::SetSaveInitSplits(bool save_init_splits) { this->m_save_init_splits = save_init_splits;} //--------------------------------------------------------------------------- void Optimize::SetCheckpointingInterval(int checkpointing_interval) { this->m_checkpointing_interval = checkpointing_interval;} //--------------------------------------------------------------------------- void Optimize::SetKeepCheckpoints(int keep_checkpoints) { this->m_keep_checkpoints = keep_checkpoints;} //--------------------------------------------------------------------------- void Optimize::SetCotanSigmaFactor(double cotan_sigma_factor) { this->m_cotan_sigma_factor = cotan_sigma_factor;} //--------------------------------------------------------------------------- void Optimize::SetUseRegression(bool use_regression) { this->m_use_regression = use_regression; } //--------------------------------------------------------------------------- void Optimize::SetUseMixedEffects(bool use_mixed_effects) { this->m_use_mixed_effects = use_mixed_effects; } //--------------------------------------------------------------------------- void Optimize::SetNormalAngle(double normal_angle) { this->m_normal_angle = normal_angle;} //--------------------------------------------------------------------------- void Optimize::SetPerformGoodBad(bool perform_good_bad) { this->m_perform_good_bad = perform_good_bad;} //--------------------------------------------------------------------------- void Optimize::SetLogEnergy(bool log_energy) { this->m_log_energy = log_energy;} //--------------------------------------------------------------------------- void Optimize::SetImages(const std::vector<ImageType::Pointer> &images) { this->m_images = images; this->m_sampler->SetImages(images); ImageType::Pointer first_image = images[0]; this->m_sampler->SetInput(0, first_image); // set the 0th input this->m_spacing = first_image->GetSpacing()[0]; this->m_num_shapes = images.size(); } //--------------------------------------------------------------------------- std::vector<Optimize::ImageType::Pointer> Optimize::GetImages() { return this->m_images; } //--------------------------------------------------------------------------- void Optimize::SetFilenames(const std::vector<std::string> &filenames) { this->m_filenames = filenames; } //--------------------------------------------------------------------------- void Optimize::SetPointFiles(const std::vector<std::string> &point_files) { for (int shapeCount = 0; shapeCount < point_files.size(); shapeCount++) { this->m_sampler->SetPointsFile(shapeCount, point_files[shapeCount]); } } //--------------------------------------------------------------------------- int Optimize::GetNumShapes() { return this->m_num_shapes; } //--------------------------------------------------------------------------- void Optimize::SetMeshFiles(const std::vector<std::string> &mesh_files) { m_sampler->SetMeshFiles(mesh_files); } //--------------------------------------------------------------------------- void Optimize::SetAttributeScales(const std::vector<double> &scales) { this->m_sampler->SetAttributeScales(scales); } //--------------------------------------------------------------------------- void Optimize::SetFeaFiles(const std::vector<std::string> &files) { this->m_sampler->SetFeaFiles(files); } //--------------------------------------------------------------------------- void Optimize::SetFeaGradFiles(const std::vector<std::string> &files) { this->m_sampler->SetFeaGradFiles(files); } //--------------------------------------------------------------------------- void Optimize::SetFidsFiles(const std::vector<std::string> &files) { this->m_sampler->SetFidsFiles(files); } //--------------------------------------------------------------------------- void Optimize::SetParticleFlags(std::vector<int> flags) { this->m_particle_flags = flags; for (unsigned int i = 0; i < flags.size() / 2; i++) { this->GetSampler()->GetParticleSystem()->SetFixedParticleFlag(flags[2 * i], flags[2 * i + 1]); } } //--------------------------------------------------------------------------- void Optimize::SetDomainFlags(std::vector<int> flags) { this->m_domain_flags = flags; for (unsigned int i = 0; i < flags.size(); i++) { this->GetSampler()->GetParticleSystem()->FlagDomain(flags[i]); } } //--------------------------------------------------------------------------- void Optimize::SetFileOutputEnabled(bool enabled) { this->m_file_output_enabled = enabled; } //--------------------------------------------------------------------------- std::vector<bool> Optimize::GetUseXYZ() { return this->m_use_xyz; } //--------------------------------------------------------------------------- std::vector<bool> Optimize::GetUseNormals() { return this->m_use_normals; } //--------------------------------------------------------------------------- void Optimize::SetIterationCallback() { this->m_iterate_command = itk::MemberCommand<Optimize>::New(); this->m_iterate_command->SetCallbackFunction(this, &Optimize::IterateCallback); this->m_sampler->GetOptimizer()->AddObserver(itk::IterationEvent(), m_iterate_command); } //--------------------------------------------------------------------------- void Optimize::WriteModes() { const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains() % m_domains_per_shape; if (n >= 5) { m_sampler->GetEnsembleEntropyFunction()->WriteModes(m_output_dir + "/pts", 5); } } //--------------------------------------------------------------------------- void Optimize::PrintStartMessage(std::string str, unsigned int vlevel) const { if (this->m_verbosity_level > vlevel) { std::cout << str; std::cout.flush(); } } //--------------------------------------------------------------------------- void Optimize::PrintDoneMessage(unsigned int vlevel) const { if (m_verbosity_level > vlevel) { std::cout << "Done." << std::endl; } }
35.675023
129
0.555073
amylenz
04f907d4b9efd4565b9880c36d4e309cefed618d
1,551
hpp
C++
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
5
2020-03-24T07:44:49.000Z
2021-08-30T14:43:31.000Z
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
#ifndef GENERATED_419896c26be84c4028d040a9d3789448_HPP #define GENERATED_419896c26be84c4028d040a9d3789448_HPP #include "bullet.hpp" void stepfunc_10c3a88a8e44bab5c0812abd588467e2_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_6536e4546bdcfcf651852434db03b678_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_afa1c1a48bcda114ef4e13212c0aee71_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_f46bc191f7167f122835b57dc03cf3ba_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_faeb9ac81b7a64ffed123259883c3994_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_ae9f735c6401a821cc04ce1cd68278bf_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_6c1f8924f1816c4b17037ca35cdfb188_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); void stepfunc_f802ea525850e7f56f2d815678960bc3_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p); extern const BulletStepFunc bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0[]; const unsigned int bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0_size = 70; extern const BulletStepFunc bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0[]; const unsigned int bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0_size = 2; extern const BulletStepFunc bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0[]; const unsigned int bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0_size = 2; #endif
59.653846
104
0.909736
pqrs-org
04f980874480007455014b3cb0fad4ba69baeea2
462
cpp
C++
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/mix/scal.hpp> #include <gtest/gtest.h> #include <math/rev/scal/util.hpp> TEST(AgradRev, value_of_rec_0) { using stan::math::fvar; using stan::math::value_of_rec; using stan::math::var; fvar<var> fv_a(5.0); fvar<fvar<var> > ffv_a(5.0); fvar<fvar<fvar<fvar<fvar<var> > > > > fffffv_a(5.0); EXPECT_FLOAT_EQ(5.0, value_of_rec(fv_a)); EXPECT_FLOAT_EQ(5.0, value_of_rec(ffv_a)); EXPECT_FLOAT_EQ(5.0, value_of_rec(fffffv_a)); }
25.666667
54
0.692641
alashworth
04f9cf4712dfa5787abb48dfeba3280f57cae510
592
cxx
C++
src/Kinematics.cxx
luketpickering/HepMCNuEvtTools
1ec8590cb81475ae525ed32b70211786c67acaa4
[ "MIT" ]
2
2021-02-17T15:09:27.000Z
2021-03-15T16:57:05.000Z
src/Kinematics.cxx
luketpickering/HepMCNuEvtTools
1ec8590cb81475ae525ed32b70211786c67acaa4
[ "MIT" ]
null
null
null
src/Kinematics.cxx
luketpickering/HepMCNuEvtTools
1ec8590cb81475ae525ed32b70211786c67acaa4
[ "MIT" ]
null
null
null
#include "NuHepMC/Kinematics.hxx" #include "NuHepMC/ParticleStackReaderHelper.hxx" #include <iostream> namespace NuHepMC { HepMC3::FourVector GetFourMomentumTransfer(HepMC3::GenEvent const &evt) { auto ISProbe = GetProbe(evt); if (!ISProbe) { return HepMC3::FourVector::ZERO_VECTOR(); } auto FSProbe = GetFSProbe(evt, ISProbe->pid()); if (!FSProbe) { return HepMC3::FourVector::ZERO_VECTOR(); } return (ISProbe->momentum() - FSProbe->momentum()); } double GetQ2(HepMC3::GenEvent const &evt) { return -GetFourMomentumTransfer(evt).m2(); } } // namespace NuHepMC
21.925926
73
0.709459
luketpickering
04fc2bddc73e7738bb6eaec9b0a5614d14b68792
643
cpp
C++
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
1
2021-01-14T06:01:02.000Z
2021-01-14T06:01:02.000Z
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
8
2018-03-27T11:47:19.000Z
2018-11-12T06:02:12.000Z
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
2
2020-04-30T09:47:01.000Z
2020-12-03T09:34:08.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { int diam = 0; maxDepth(root, diam); return diam; } int maxDepth(TreeNode* root, int& diam) { if (root == nullptr) { return 0; } int left = maxDepth(root->left, diam); int right = maxDepth(root->right, diam); diam = max(diam, left + right); return 1 + max(left, right); } };
22.964286
59
0.527216
nettee
04fc48087dbea9865ea7d0c9765dcc951b4eb33e
329
cpp
C++
Chapter4/Practice/1090.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
1
2022-02-13T02:22:39.000Z
2022-02-13T02:22:39.000Z
Chapter4/Practice/1090.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
null
null
null
Chapter4/Practice/1090.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int m, k, n, w, t = 0; cin >> m >> k; n = m; while (n) { w = n % 10; if (w == 3) ++t; n /= 10; } if (m % 19 == 0 && t == k) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
13.708333
30
0.343465
flics04
04fc723f94a4f0ba29db7ca4dd467f73898a457a
6,364
cpp
C++
src/caffe/layers/mvn_layer.cpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/mvn_layer.cpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/mvn_layer.cpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <vector> #include "caffe/common_layers.hpp" #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype, typename Mtype> void MVNLayer<Dtype,Mtype>::Reshape(const vector<Blob<Dtype,Mtype>*>& bottom, const vector<Blob<Dtype,Mtype>*>& top) { top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); mean_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); variance_.Reshape(bottom[0]->num(), bottom[0]->channels(), 1, 1); temp_.Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); if ( this->layer_param_.mvn_param().across_channels() ) { sum_multiplier_.Reshape(1, bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); } else { sum_multiplier_.Reshape(1, 1, bottom[0]->height(), bottom[0]->width()); } Dtype* multiplier_data = sum_multiplier_.mutable_cpu_data(); caffe_set(sum_multiplier_.count(), Get<Dtype>(1), multiplier_data); eps_ = this->layer_param_.mvn_param().eps(); } template <typename Dtype, typename Mtype> void MVNLayer<Dtype,Mtype>::Forward_cpu(const vector<Blob<Dtype,Mtype>*>& bottom, const vector<Blob<Dtype,Mtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); int num; if (this->layer_param_.mvn_param().across_channels()) num = bottom[0]->num(); else num = bottom[0]->num() * bottom[0]->channels(); int dim = bottom[0]->count() / num; if (this->layer_param_.mvn_param().normalize_variance()) { // put the squares of bottom into temp_ caffe_powx<Dtype,Mtype>(bottom[0]->count(), bottom_data, Mtype(2), temp_.mutable_cpu_data()); // computes variance using var(X) = E(X^2) - (EX)^2 caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data, sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), temp_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.), variance_.mutable_cpu_data()); // E(X^2) caffe_powx<Dtype,Mtype>(mean_.count(), mean_.cpu_data(), Mtype(2), temp_.mutable_cpu_data()); // (EX)^2 caffe_sub<Dtype,Mtype>(mean_.count(), variance_.cpu_data(), temp_.cpu_data(), variance_.mutable_cpu_data()); // variance // do mean and variance normalization // subtract mean caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f), mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f), temp_.mutable_cpu_data()); caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data); // normalize variance caffe_powx<Dtype,Mtype>(variance_.count(), variance_.cpu_data(), Mtype(0.5), variance_.mutable_cpu_data()); caffe_add_scalar<Dtype,Mtype>(variance_.count(), eps_, variance_.mutable_cpu_data()); caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f), variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.), temp_.mutable_cpu_data()); caffe_div<Dtype,Mtype>(temp_.count(), top_data, temp_.cpu_data(), top_data); } else { caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data, sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX // subtract mean caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.), mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.), temp_.mutable_cpu_data()); caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data); } } template <typename Dtype, typename Mtype> void MVNLayer<Dtype,Mtype>::Backward_cpu(const vector<Blob<Dtype,Mtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype,Mtype>*>& bottom) { const Dtype* top_diff = top[0]->cpu_diff(); const Dtype* top_data = top[0]->cpu_data(); const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); int num; if (this->layer_param_.mvn_param().across_channels()) num = bottom[0]->num(); else num = bottom[0]->num() * bottom[0]->channels(); int dim = bottom[0]->count() / num; if (this->layer_param_.mvn_param().normalize_variance()) { caffe_mul<Dtype,Mtype>(temp_.count(), top_data, top_diff, bottom_diff); caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), bottom_diff, sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.), mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f), bottom_diff); caffe_mul<Dtype,Mtype>(temp_.count(), top_data, bottom_diff, bottom_diff); caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), top_diff, sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data()); caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.), mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(1.f), bottom_diff); caffe_cpu_axpby<Dtype,Mtype>(temp_.count(), Mtype(1), top_diff, Mtype(-1. / dim), bottom_diff); // put the squares of bottom into temp_ caffe_powx<Dtype,Mtype>(temp_.count(), bottom_data, Mtype(2), temp_.mutable_cpu_data()); caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f), variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f), temp_.mutable_cpu_data()); caffe_div<Dtype,Mtype>(temp_.count(), bottom_diff, temp_.cpu_data(), bottom_diff); } else { caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), top_diff, sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data()); caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f), mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f), temp_.mutable_cpu_data()); caffe_add<Dtype,Mtype>(temp_.count(), top_diff, temp_.cpu_data(), bottom_diff); } } #ifdef CPU_ONLY STUB_GPU(MVNLayer); #endif INSTANTIATE_CLASS(MVNLayer); REGISTER_LAYER_CLASS(MVN); } // namespace caffe
41.058065
90
0.675519
oscmansan
04fcae2c2f1451c9bfc342f06a81a1f5e700e157
6,448
cc
C++
chrome/utility/image_writer/image_writer_win.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/utility/image_writer/image_writer_win.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/utility/image_writer/image_writer_win.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2014 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 <windows.h> #include <setupapi.h> #include <stddef.h> #include <winioctl.h> #include "base/logging.h" #include "chrome/utility/image_writer/error_message_strings.h" #include "chrome/utility/image_writer/image_writer.h" namespace image_writer { const size_t kStorageQueryBufferSize = 1024; bool ImageWriter::IsValidDevice() { base::win::ScopedHandle device_handle( CreateFile(device_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH, NULL)); if (!device_handle.IsValid()) { Error(error::kOpenDevice); return false; } STORAGE_PROPERTY_QUERY query = STORAGE_PROPERTY_QUERY(); query.PropertyId = StorageDeviceProperty; query.QueryType = PropertyStandardQuery; DWORD bytes_returned; std::unique_ptr<char[]> output_buf(new char[kStorageQueryBufferSize]); BOOL status = DeviceIoControl( device_handle.Get(), // Device handle. IOCTL_STORAGE_QUERY_PROPERTY, // Flag to request device properties. &query, // Query parameters. sizeof(STORAGE_PROPERTY_QUERY), // query parameters size. output_buf.get(), // output buffer. kStorageQueryBufferSize, // Size of buffer. &bytes_returned, // Number of bytes returned. // Must not be null. NULL); // Optional unused overlapped perameter. if (!status) { PLOG(ERROR) << "Storage property query failed"; return false; } STORAGE_DEVICE_DESCRIPTOR* device_descriptor = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(output_buf.get()); return device_descriptor->RemovableMedia == TRUE || device_descriptor->BusType == BusTypeUsb; } bool ImageWriter::OpenDevice() { // Windows requires that device files be opened with FILE_FLAG_NO_BUFFERING // and FILE_FLAG_WRITE_THROUGH. These two flags are not part of base::File. device_file_ = base::File(CreateFile(device_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH, NULL)); return device_file_.IsValid(); } void ImageWriter::UnmountVolumes(base::OnceClosure continuation) { if (!InitializeFiles()) { return; } STORAGE_DEVICE_NUMBER sdn = {0}; DWORD bytes_returned; BOOL status = DeviceIoControl( device_file_.GetPlatformFile(), IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, // Unused, must be NULL. 0, // Unused, must be 0. &sdn, // An input buffer to hold the STORAGE_DEVICE_NUMBER sizeof(sdn), // The size of the input buffer. &bytes_returned, // the actual number of bytes returned. NULL); // Unused overlap. if (!status) { PLOG(ERROR) << "Unable to get device number."; return; } ULONG device_number = sdn.DeviceNumber; TCHAR volume_path[MAX_PATH + 1]; HANDLE volume_finder = FindFirstVolume(volume_path, MAX_PATH + 1); if (volume_finder == INVALID_HANDLE_VALUE) { return; } HANDLE volume_handle; bool first_volume = true; bool success = true; while (first_volume || FindNextVolume(volume_finder, volume_path, MAX_PATH + 1)) { first_volume = false; size_t length = wcsnlen(volume_path, MAX_PATH + 1); if (length < 1) { continue; } volume_path[length - 1] = L'\0'; volume_handle = CreateFile(volume_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (volume_handle == INVALID_HANDLE_VALUE) { PLOG(ERROR) << "Opening volume handle failed."; success = false; break; } volume_handles_.push_back(volume_handle); VOLUME_DISK_EXTENTS disk_extents = {0}; status = DeviceIoControl(volume_handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &disk_extents, sizeof(disk_extents), &bytes_returned, NULL); if (!status) { DWORD error = GetLastError(); if (error == ERROR_MORE_DATA || error == ERROR_INVALID_FUNCTION || error == ERROR_NOT_READY) { continue; } else { PLOG(ERROR) << "Unable to get volume disk extents."; success = false; break; } } if (disk_extents.NumberOfDiskExtents != 1 || disk_extents.Extents[0].DiskNumber != device_number) { continue; } status = DeviceIoControl(volume_handle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL); if (!status) { PLOG(ERROR) << "Unable to lock volume."; success = false; break; } status = DeviceIoControl(volume_handle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL); if (!status) { DWORD error = GetLastError(); if (error != ERROR_NOT_SUPPORTED) { PLOG(ERROR) << "Unable to dismount volume."; success = false; break; } } } if (volume_finder != INVALID_HANDLE_VALUE) { FindVolumeClose(volume_finder); } if (success) std::move(continuation).Run(); } } // namespace image_writer
31.920792
79
0.555676
zealoussnow
04fcc311b301e319fe9202e65eb3003d5d4f86ca
7,742
cpp
C++
dev/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/IO/SystemFile.h> #include <AzCore/IO/FileIO.h> #include <AzCore/IO/FileIOEventBus.h> #include <AzCore/Casting/numeric_cast.h> #include <AzCore/PlatformIncl.h> #include <AzCore/Utils/Utils.h> #include <../Common/UnixLike/AzCore/IO/Internal/SystemFileUtils_UnixLike.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <dirent.h> namespace AZ::IO { namespace UnixLikePlatformUtil { // Platform specific helpers bool CanCreateDirRecursive(char* dirPath); } namespace { //========================================================================= // Internal utility to create a folder hierarchy recursively without // any additional string copies. // If this function fails (returns false), the error will be available // via errno on Unix platforms //========================================================================= bool CreateDirRecursive(char* dirPath) { if (!UnixLikePlatformUtil::CanCreateDirRecursive(dirPath)) { // Our current platform has told us we have failed return false; } int result = mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (result == 0) { return true; // Created without error } else if (result == -1) { // If result == -1, the error is stored in errno // http://pubs.opengroup.org/onlinepubs/007908799/xsh/mkdir.html result = errno; } if (result == ENOTDIR || result == ENOENT) { // try to create our parent hierarchy for (size_t i = strlen(dirPath); i > 0; --i) { if (dirPath[i] == '/' || dirPath[i] == '\\') { char delimiter = dirPath[i]; dirPath[i] = 0; // null-terminate at the previous slash bool ret = CreateDirRecursive(dirPath); dirPath[i] = delimiter; // restore slash if (ret) { // now that our parent is created, try to create again return mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0; } return false; } } // if we reach here then there was no parent folder to create, so we failed for other reasons } else if (result == EEXIST) { struct stat s; if (stat(dirPath, &s) == 0) { return s.st_mode & S_IFDIR; } } return false; } } namespace Platform { void FindFiles(const char* filter, SystemFile::FindFileCB cb) { // If we have wildcards, peel off char filePath[AZ_MAX_PATH_LEN]; char extensionPath[AZ_MAX_PATH_LEN]; if (!AZ::IO::Internal::FormatAndPeelOffWildCardExtension(filter, filePath, sizeof(filePath), extensionPath, sizeof(extensionPath), true)) { // FormatAndPeelOffWildCardExtension emits an error when it returns false return; } DIR* dir = opendir(filePath); if (dir != NULL) { // clear the errno state so we can distinguish between real errors and end of stream errno = 0; struct dirent* entry = readdir(dir); // List all the other files in the directory. while (entry != NULL) { if (NameMatchesFilter(entry->d_name, extensionPath)) { cb(entry->d_name, (entry->d_type & DT_DIR) == 0); } entry = readdir(dir); } int lastError = errno; if (lastError != 0) { EBUS_EVENT(FileIOEventBus, OnError, nullptr, filter, lastError); } closedir(dir); } else { int lastError = errno; if (lastError != ENOENT) { EBUS_EVENT(FileIOEventBus, OnError, nullptr, filter, 0); } } } AZ::u64 ModificationTime(const char* fileName) { struct stat statResult; if (stat(fileName, &statResult) != 0) { return 0; } return aznumeric_cast<AZ::u64>(statResult.st_mtime); } SystemFile::SizeType Length(const char* fileName) { SizeType len = 0; SystemFile f; if (f.Open(fileName, SystemFile::SF_OPEN_READ_ONLY)) { len = f.Length(); f.Close(); } return len; } bool Delete(const char* fileName) { int result = remove(fileName); if (result != 0) { EBUS_EVENT(FileIOEventBus, OnError, nullptr, fileName, result); return false; } return true; } bool Rename(const char* sourceFileName, const char* targetFileName, bool overwrite) { int result = rename(sourceFileName, targetFileName); if (result) { EBUS_EVENT(FileIOEventBus, OnError, nullptr, sourceFileName, result); return false; } return true; } #if !(AZ_TRAIT_SYSTEMFILE_UNIX_LIKE_PLATFORM_IS_WRITEABLE_DEFINED_ELSEWHERE) bool IsWritable(const char* sourceFileName) { return (access(sourceFileName, W_OK) == 0); } #endif // !(AZ_TRAIT_SYSTEMFILE_UNIX_LIKE_PLATFORM_IS_WRITEABLE_DEFINED_ELSEWHERE) bool SetWritable(const char* sourceFileName, bool writable) { struct stat s; if (stat(sourceFileName, &s) == 0) { int permissions = (s.st_mode & S_IRWXU) | (s.st_mode & S_IRWXO) | (s.st_mode & S_IRWXG); if (writable) { if (s.st_mode & S_IWUSR) { return true; } return chmod(sourceFileName, permissions | S_IWUSR) == 0; } else { if (s.st_mode & S_IRUSR) { return true; } return chmod(sourceFileName, permissions | S_IRUSR) == 0; } } return false; } bool CreateDir(const char* dirName) { if (dirName) { char dirPath[AZ_MAX_PATH_LEN]; if (strlen(dirName) > AZ_MAX_PATH_LEN) { return false; } azstrcpy(dirPath, AZ_MAX_PATH_LEN, dirName); bool success = CreateDirRecursive(dirPath); if (!success) { EBUS_EVENT(FileIOEventBus, OnError, nullptr, dirName, errno); } return success; } return false; } bool DeleteDir(const char* dirName) { AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::DeleteDir(util) - %s", dirName); if (dirName) { return rmdir(dirName) == 0; } return false; } } } // namespace AZ::IO
29.215094
145
0.530871
BadDevCode
04fdfa60440ea7fc5cba70c2ea416036838c44ab
10,583
cpp
C++
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
null
null
null
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
null
null
null
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
1
2021-11-03T00:21:07.000Z
2021-11-03T00:21:07.000Z
// Arquivo pangya_db.cpp // Criado em 25/12/2017 por Acrisio // Implementação da classe pangya_db #if defined(_WIN32) #pragma pack(1) #endif #if defined(_WIN32) #include <WinSock2.h> #elif defined(__linux__) #include "../UTIL/WinPort.h" #include <unistd.h> #endif #include "pangya_db.h" #include "../UTIL/exception.h" #include "../UTIL/message_pool.h" #include "../UTIL/string_util.hpp" using namespace stdA; // Teste call db cmd log #ifdef _DEBUG #define _TESTCMD_LOG 1 #endif #if defined(_WIN32) && defined(_TESTCMD_LOG) // !@ Teste #include <fstream> #include <map> struct call_db_cmd_st { public: call_db_cmd_st() : m_hMutex(INVALID_HANDLE_VALUE) { m_hMutex = CreateMutexA(NULL, FALSE, "xg_CALL_DB_CMD_LOG"); if (m_hMutex == NULL) _smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::call_db_cmd_st][Error] fail to create Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE)); }; ~call_db_cmd_st() { if (isValid()) CloseHandle(m_hMutex); }; std::map< std::string, std::string > loadCmds() { std::map< std::string, std::string > v_cmds; if (!isValid() || !lock()) return v_cmds; std::ifstream in(url_log); if (in.is_open()) { std::string name, value; while (in.good()) { in >> name >> value; v_cmds.insert(std::make_pair(name, value)); } in.close(); } if (!unlock()) _smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::loadCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE)); return v_cmds; }; void saveCmds(std::map< std::string, std::string >& _cmds) { if (_cmds.empty() || !isValid() || !lock()) return; std::ofstream out(url_log); if (out.is_open()) { for (auto& el : _cmds) out << el.first << " " << el.second << std::endl; out.close(); } if (!unlock()) _smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::saveCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE)); }; private: bool isValid() { return m_hMutex != INVALID_HANDLE_VALUE && m_hMutex != NULL; }; bool lock() { if (!isValid()) return false; DWORD dwResult = WaitForSingleObject(m_hMutex, INFINITE); return dwResult == WAIT_OBJECT_0 ? true : false; }; bool unlock() { if (!isValid()) return false; return ReleaseMutex(m_hMutex) == TRUE; }; private: HANDLE m_hMutex; const char url_log[30] = "H:/Server Lib/call_db_cmd.log"; }; // !@ Teste bool logExecuteCmds(std::string _name) { static call_db_cmd_st cdcs; // Load auto v_cmds = cdcs.loadCmds(); auto it = v_cmds.find(_name); if (it == v_cmds.end()) { v_cmds.insert(std::make_pair(_name, "yes")); // Save cdcs.saveCmds(v_cmds); return true; // show log }else if (it->second.compare("no") == 0) { it->second = "yes"; // Save cdcs.saveCmds(v_cmds); return true; // show log } return false; } // !@ Teste #endif list_fifo_asyc< exec_query > pangya_db::m_query_pool; list_async< exec_query* > pangya_db::m_cache_query; pangya_db::pangya_db(bool _waitable) : m_exception("", 0), m_waitable(_waitable), #if defined(_WIN32) hEvent(INVALID_HANDLE_VALUE) #elif defined(__linux__) hEvent(nullptr) #endif { #if defined(_WIN32) if (_waitable) if ((hEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == INVALID_HANDLE_VALUE) _smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, GetLastError())), CL_FILE_LOG_AND_CONSOLE)); #elif defined(__linux__) if (_waitable) { hEvent = new Event(false, 0u); if (!hEvent->is_good()) { delete hEvent; hEvent = nullptr; _smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, errno)), CL_FILE_LOG_AND_CONSOLE)); } } #endif }; pangya_db::~pangya_db() { #if defined(_WIN32) if (hEvent != INVALID_HANDLE_VALUE) CloseHandle(hEvent); hEvent = INVALID_HANDLE_VALUE; #elif defined(__linux__) if (hEvent != nullptr) delete hEvent; hEvent = nullptr; #endif }; inline void pangya_db::exec(database& _db) { response *r = nullptr; try { if ((r = prepareConsulta(_db)) != nullptr) { for (auto num_result = 0u; num_result < r->getNumResultSet(); ++num_result) { if (r->getResultSetAt(num_result) != nullptr && r->getResultSetAt(num_result)->getNumLines() > 0 && r->getResultSetAt(num_result)->getState() == result_set::HAVE_DATA) { for (auto _result = r->getResultSetAt(num_result)->getFirstLine(); _result != nullptr; _result = _result->next) { lineResult(_result, num_result); } }// só faz esse else se for mandar uma exception clear_result(r->getResultSetAt(num_result)); } clear_response(r); } }catch (exception& e) { //UNREFERENCED_PARAMETER(e); if (r != nullptr) clear_response(r); //throw; m_exception = e; _smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Error] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } #if defined(_WIN32) && defined(_TESTCMD_LOG) // !@ Teste if (logExecuteCmds(_getName())) _smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Log] Executado. ------------------->>", CL_FILE_LOG_AND_CONSOLE)); #endif }; exception& pangya_db::getException() { return m_exception; }; void pangya_db::waitEvent() { #if defined(_WIN32) if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, GetLastError())); #elif defined(__linux__) if (hEvent == nullptr || hEvent->wait(INFINITE) != WAIT_OBJECT_0) throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, errno)); #endif } void pangya_db::wakeupWaiter() { #if defined(_WIN32) SetEvent(hEvent); #elif defined(__linux__) if (hEvent != nullptr) hEvent->set(); #endif }; bool pangya_db::isWaitable() { return m_waitable; }; inline response* pangya_db::_insert(database& _db, std::string _query) { return _insert(_db, MbToWc(_query)); } inline response* pangya_db::_insert(database& _db, std::wstring _query) { /*exec_query query(_query, exec_query::_INSERT); postAndWaitResponseQuery(query); return query.getRes();*/ return _db.ExecQuery(_query); } inline response* pangya_db::_update(database& _db, std::string _query) { return _update(_db, MbToWc(_query)); }; inline response* pangya_db::_update(database& _db, std::wstring _query) { //exec_query query(_query, exec_query::_UPDATE); //postAndWaitResponseQuery(query); ////clear_response(query.getRes()); //return query.getRes(); return _db.ExecQuery(_query); }; inline response* pangya_db::_delete(database& _db, std::string _query) { return _delete(_db, MbToWc(_query)); }; inline response* pangya_db::_delete(database& _db, std::wstring _query) { //exec_query query(_query, exec_query::_DELETE); //postAndWaitResponseQuery(query); ////clear_response(query.getRes()); //return query.getRes(); return _db.ExecQuery(_query); }; inline response* pangya_db::consulta(database& _db, std::string _query) { return consulta(_db, MbToWc(_query)); }; inline response* pangya_db::consulta(database& _db, std::wstring _query) { /*exec_query query(_query, exec_query::_QUERY); postAndWaitResponseQuery(query); return query.getRes();*/ return _db.ExecQuery(_query); }; inline response* pangya_db::procedure(database& _db, std::string _name, std::string _params) { return procedure(_db, MbToWc(_name), MbToWc(_params)); }; inline response* pangya_db::procedure(database& _db, std::wstring _name, std::wstring _params) { /*exec_query query(_name, _params, exec_query::_PROCEDURE); postAndWaitResponseQuery(query); return query.getRes();*/ return _db.ExecProc(_name, _params); }; inline void pangya_db::postAndWaitResponseQuery(exec_query& _query) { DWORD wait = INFINITE; //pangya_base_db::m_query_pool.push(&_query); // post query m_query_pool.push(&_query); while (1) { try { _query.waitEvent(wait); break; }catch (exception& e) { if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::EXEC_QUERY) { if (STDA_ERROR_DECODE(e.getCodeError()) == 7 && wait == INFINITE) { wait = 1000; // Espera um segundo se não for da próxima dá error continue; } //pangya_base_db::m_query_pool.remove(&_query); m_query_pool.remove(&_query); throw; }else throw; }catch (std::exception& e) { throw exception("System error: " + std::string(e.what()), STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 0)); }catch (...) { throw exception("System error: Desconhecido", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 1)); } } }; inline void pangya_db::clear_result(result_set*& _rs) { if (_rs != nullptr) delete _rs; _rs = nullptr; }; inline void pangya_db::clear_response(response* _res) { if (_res != nullptr) delete _res; }; inline void pangya_db::checkColumnNumber(uint32_t _number_cols1, uint32_t _number_cols2) { if (_number_cols1 != 0 && _number_cols1 != _number_cols2) throw exception("[pangya_db::" + _getName() + "::checkColumnNumber][Error] numero de colunas retornada pela consulta sao diferente do esperado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 2, 0)); }; inline void pangya_db::checkResponse(response* r, std::string _exception_msg) { if (r == nullptr || r->getNumResultSet() <= 0) throw exception("[pangya_db::" + _getName() + "::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0)); }; inline void pangya_db::checkResponse(response* r, std::wstring _exception_msg) { if (r == nullptr || r->getNumResultSet() <= 0) throw exception(L"[pangya_db::" + _wgetName() + L"::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0)); }; bool pangya_db::compare(exec_query* _query1, exec_query* _query2) { return _query1->getQuery().compare(_query2->getQuery()) == 0; };
25.749392
230
0.681187
eantoniobr
04ff6d158f1e6e4c092de54081d3e681d50acbcd
3,824
cpp
C++
tests/SRGBTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
tests/SRGBTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
tests/SRGBTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2016 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/SkColorSpace.h" #include "include/core/SkTypes.h" #include "src/core/SkColorSpaceXformSteps.h" #include "src/core/SkRasterPipeline.h" #include "tests/Test.h" #include <math.h> DEF_TEST(srgb_roundtrip, r) { uint32_t reds[256]; for (int i = 0; i < 256; i++) { reds[i] = i; } SkRasterPipeline_MemoryCtx ptr = { reds, 0 }; sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB(), linear = sRGB->makeLinearGamma(); const SkAlphaType upm = kUnpremul_SkAlphaType; SkColorSpaceXformSteps linearize{ sRGB.get(),upm, linear.get(),upm}, reencode {linear.get(),upm, sRGB.get(),upm}; SkRasterPipeline_<256> p; p.append(SkRasterPipeline::load_8888, &ptr); linearize.apply(&p); reencode .apply(&p); p.append(SkRasterPipeline::store_8888, &ptr); p.run(0,0,256,1); for (int i = 0; i < 256; i++) { if (reds[i] != (uint32_t)i) { ERRORF(r, "%d doesn't round trip, %d", i, reds[i]); } } } DEF_TEST(srgb_edge_cases, r) { // We need to run at least 4 pixels to make sure we hit all specializations. float colors[4][4] = { {0,1,1,1}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0} }; auto& color = colors[0]; SkRasterPipeline_MemoryCtx dst = { &color, 0 }; sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB(), linear = sRGB->makeLinearGamma(); const SkAlphaType upm = kUnpremul_SkAlphaType; SkColorSpaceXformSteps steps {linear.get(),upm, sRGB.get(),upm}; SkSTArenaAlloc<256> alloc; SkRasterPipeline p(&alloc); p.append_constant_color(&alloc, color); steps.apply(&p); p.append(SkRasterPipeline::store_f32, &dst); p.run(0,0,4,1); if (color[0] != 0.0f) { ERRORF(r, "expected to_srgb() to map 0.0f to 0.0f, got %f", color[0]); } if (color[1] != 1.0f) { float f = color[1]; uint32_t x; memcpy(&x, &f, 4); ERRORF(r, "expected to_srgb() to map 1.0f to 1.0f, got %f (%08x)", color[1], x); } } // Linearize and then re-encode pixel values, testing that the output is close to the input. DEF_TEST(srgb_roundtrip_extended, r) { static const int kSteps = 128; SkColor4f rgba[kSteps]; auto expected = [=](int i) { float scale = 10000.0f / (3*kSteps); return SkColor4f{ (3*i+0) * scale, (3*i+1) * scale, (3*i+2) * scale, 1.0f, }; }; for (int i = 0; i < kSteps; i++) { rgba[i] = expected(i); } SkRasterPipeline_MemoryCtx ptr = { rgba, 0 }; sk_sp<SkColorSpace> cs = SkColorSpace::MakeSRGB(); sk_sp<SkColorSpace> linear = cs->makeLinearGamma(); const SkAlphaType upm = kUnpremul_SkAlphaType; SkColorSpaceXformSteps linearize{ cs.get(),upm, linear.get(),upm}, reencode {linear.get(),upm, cs.get(),upm}; SkRasterPipeline_<256> p; p.append(SkRasterPipeline::load_f32, &ptr); linearize.apply(&p); reencode .apply(&p); p.append(SkRasterPipeline::store_f32, &ptr); p.run(0,0,kSteps,1); auto close = [=](float x, float y) { return x == y || (x/y < 1.001f && y/x < 1.001f); }; for (int i = 0; i < kSteps; i++) { SkColor4f want = expected(i); #if 0 SkDebugf("got %g %g %g, want %g %g %g\n", rgba[i].fR, rgba[i].fG, rgba[i].fB, want.fR, want.fG, want.fB); #endif REPORTER_ASSERT(r, close(rgba[i].fR, want.fR)); REPORTER_ASSERT(r, close(rgba[i].fG, want.fG)); REPORTER_ASSERT(r, close(rgba[i].fB, want.fB)); } }
29.643411
92
0.572699
JimmySoftware
ca012ee4ec0f3d0223dcb884c068974dd3eb7988
7,717
cpp
C++
examples/world_gen/game.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
13
2017-04-12T16:26:46.000Z
2022-03-01T22:04:34.000Z
examples/world_gen/game.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
examples/world_gen/game.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
#include <bonsai_types.h> #include <game_constants.h> #include <game_types.h> #define RANDOM_HOTKEY_MASHING 0 #if RANDOM_HOTKEY_MASHING static u32 HotkeyFrameTimeout = 0; static random_series HotkeyEntropy = {}; static hotkeys StashedHotkeys = {}; #endif model * AllocateGameModels(game_state *GameState, memory_arena *Memory) { model *Result = Allocate(model, GameState->Memory, ModelIndex_Count); Result[ModelIndex_Enemy] = LoadVoxModel(Memory, &GameState->Heap, ENEMY_MODEL); Result[ModelIndex_Player] = LoadCollada(Memory, &GameState->Heap, "models/two-axis-animated-cube.dae"); /* Result[ModelIndex_Player] = LoadVoxModel(Memory, PLAYER_MODEL); */ Result[ModelIndex_Loot] = LoadVoxModel(Memory, &GameState->Heap, LOOT_MODEL); /* chunk_dimension ProjectileDim = Chunk_Dimension(1,30,1); */ /* Result[ModelIndex_Projectile].Chunk = AllocateChunk(Memory, &GameState->Heap, ProjectileDim); */ /* Result[ModelIndex_Projectile].Dim = ProjectileDim; */ /* FillChunk(Result[ModelIndex_Projectile].Chunk, ProjectileDim, GREEN); */ Result[ModelIndex_Proton] = LoadVoxModel(Memory, &GameState->Heap, PROJECTILE_MODEL); return Result; } BONSAI_API_WORKER_THREAD_CALLBACK() { switch (Entry->Type) { case type_work_queue_entry_init_world_chunk: { world_chunk* DestChunk = (world_chunk*)Entry->work_queue_entry_init_world_chunk.Input; if (!ChunkIsGarbage(DestChunk)) { s32 Amplititude = 100; s32 StartingZDepth = -100; InitializeWorldChunkPerlinPlane(Thread, DestChunk, WORLD_CHUNK_DIM, Amplititude, StartingZDepth); /* Assert(DestChunk->CurrentTriangles->SurfacePoints->Count == 0); */ /* GetBoundingVoxels(DestChunk, DestChunk->CurrentTriangles->SurfacePoints); */ /* Triangulate(DestChunk->LodMesh, DestChunk, WORLD_CHUNK_DIM, Thread->TempMemory); */ /* Triangulate(DestChunk->LodMesh, DestChunk->CurrentTriangles, DestChunk, Thread->TempMemory); */ } } break; case type_work_queue_entry_copy_buffer: { untextured_3d_geometry_buffer* Src = Entry->work_queue_entry_copy_buffer.Src; untextured_3d_geometry_buffer* Dest = &Entry->work_queue_entry_copy_buffer.Dest; Assert(Src->At <= Dest->End); v3 Basis = Entry->work_queue_entry_copy_buffer.Basis; BufferVertsChecked(Src, Dest, Basis, V3(1.0f)); } break; InvalidDefaultCase; } return; } BONSAI_API_MAIN_THREAD_CALLBACK() { TIMED_FUNCTION(); GetDebugState()->Plat = GameState->Plat; GetDebugState()->GameState = GameState; /* DebugPrint(*GameState->Plat); */ GL.Disable(GL_CULL_FACE); #if BONSAI_INTERNAL if (!GetDebugState) { GetDebugState = GameState->GetDebugState; } #endif world *World = GameState->World; graphics *Graphics = GameState->Graphics; g_buffer_render_group *gBuffer = Graphics->gBuffer; ao_render_group *AoGroup = Graphics->AoGroup; camera *Camera = Graphics->Camera; Graphics->GpuBufferWriteIndex = (Graphics->GpuBufferWriteIndex + 1) % 2; gpu_mapped_element_buffer* GpuMap = Graphics->GpuBuffers + Graphics->GpuBufferWriteIndex; MapGpuElementBuffer(GpuMap); entity *Player = GameState->Player; ClearFramebuffers(Graphics); #if RANDOM_HOTKEY_MASHING if (HotkeyFrameTimeout == 0) { Hotkeys->Left = RandomChoice(&HotkeyEntropy); Hotkeys->Right = RandomChoice(&HotkeyEntropy); Hotkeys->Forward = RandomChoice(&HotkeyEntropy); Hotkeys->Backward = RandomChoice(&HotkeyEntropy); StashedHotkeys = *Hotkeys; HotkeyFrameTimeout = 100; } else { HotkeyFrameTimeout--; *Hotkeys = StashedHotkeys; } #endif #if DEBUG_DRAW_WORLD_AXIES { untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_LINE*3); DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(10000, 0, 0), RED, 0.5f ); DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 10000, 0), GREEN, 0.5f ); DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 0, 10000), BLUE, 0.5f ); } #endif if (Hotkeys->Player_Spawn) { Unspawn(Player); world_position PlayerChunkP = World_Position(0, 0, -2); SpawnPlayer(GameState->Models, Player, Canonical_Position(V3(0,0,2), World_Position(0,0,0)), &GameState->Entropy); World->Center = PlayerChunkP; } SimulatePlayer(World, Player, Camera, Hotkeys, Plat->dt, g_VisibleRegion); CollectUnusedChunks(World, &GameState->MeshFreelist, GameState->Memory, g_VisibleRegion); v2 MouseDelta = GetMouseDelta(Plat); input* GameInput = &Plat->Input; #if BONSAI_INTERNAL if (GetDebugState()->UiGroup.PressedInteractionId != StringHash("GameViewport")) { GameInput = 0; } #endif UpdateGameCamera(MouseDelta, GameInput, Player->P, Camera, World->ChunkDim); SimulateEntities(World, GameState->EntityTable, Plat->dt, g_VisibleRegion); SimulateAndRenderParticleSystems(GameState->EntityTable, World->ChunkDim, &GpuMap->Buffer, Graphics, Plat->dt); gBuffer->ViewProjection = ProjectionMatrix(Camera, Plat->WindowWidth, Plat->WindowHeight) * ViewMatrix(World->ChunkDim, Camera); DEBUG_COMPUTE_PICK_RAY(Plat, &gBuffer->ViewProjection); TIMED_BLOCK("BufferMeshes"); BufferWorld(Plat, &GpuMap->Buffer, World, Graphics, g_VisibleRegion); BufferEntities( GameState->EntityTable, &GpuMap->Buffer, Graphics, World, Plat->dt); END_BLOCK("BufferMeshes"); #if BONSAI_INTERNAL for (u32 ChunkIndex = 0; ChunkIndex < GetDebugState()->PickedChunkCount; ++ChunkIndex) { world_chunk *Chunk = GetDebugState()->PickedChunks[ChunkIndex]; untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_AABB); u8 Color = GREEN; if (Chunk == GetDebugState()->HotChunk) { Color = PINK; } DEBUG_DrawChunkAABB(&CopyDest, Graphics, Chunk, World->ChunkDim, Color, 0.35f); } #endif TIMED_BLOCK("Wait for worker threads"); for (;;) { if (QueueIsEmpty(&Plat->HighPriority)) { break; } } END_BLOCK("Wait for worker threads"); TIMED_BLOCK("RenderToScreen"); RenderGBuffer(GpuMap, Graphics); RenderAoTexture(AoGroup); DrawGBufferToFullscreenQuad(Plat, Graphics); END_BLOCK("RenderToScreen"); Graphics->Lights->Count = 0; return; } BONSAI_API_MAIN_THREAD_INIT_CALLBACK() { Info("Initializing Game"); GL = *GL_in; GetDebugState = GetDebugState_in; Init_Global_QuadVertexBuffer(); game_state *GameState = Allocate(game_state, GameMemory, 1); GameState->Memory = GameMemory; GameState->Noise = perlin_noise(DEBUG_NOISE_SEED); GameState->Graphics = GraphicsInit(GameMemory); if (!GameState->Graphics) { Error("Initializing Graphics"); return False; } StandardCamera(GameState->Graphics->Camera, 10000.0f, 300.0f); GameState->Plat = Plat; GameState->Entropy.Seed = DEBUG_NOISE_SEED; world_position WorldCenter = World_Position(0, 0, 0); GameState->Heap = InitHeap(Gigabytes(4)); GameState->World = AllocateAndInitWorld(WorldCenter, WORLD_CHUNK_DIM, g_VisibleRegion); GameState->EntityTable = AllocateEntityTable(GameMemory, TOTAL_ENTITY_COUNT); GameState->Models = AllocateGameModels(GameState, GameState->Memory); GameState->Player = GetFreeEntity(GameState->EntityTable); SpawnPlayer(GameState->Models, GameState->Player, Canonical_Position(Voxel_Position(0), WorldCenter), &GameState->Entropy); return GameState; } BONSAI_API_WORKER_THREAD_INIT_CALLBACK() { Thread->MeshFreelist = &GameState->MeshFreelist; Thread->Noise = &GameState->Noise; }
31.116935
125
0.705067
jjbandit
ca01560870d938fafd39fcc70b08ba9abb9f6dca
145
cpp
C++
nmnnmm.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
nmnnmm.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
nmnnmm.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
#include<iostream> using namespace std; int hey(int a){ int c= a+3; return c; } int main(){ int i= 29; cout<<hey(i); }
13.181818
21
0.524138
taareek
ca03daaaf43fbbb876ff8dec0968976ad62433cc
3,137
cpp
C++
mbed-os/TESTS/mbed_drivers/race_test/main.cpp
ghsecuritylab/mbed-os-wave_player-example
39af3df51503c77e149eb732dbc07c7fd4ee351e
[ "Apache-2.0" ]
8
2017-01-20T13:14:49.000Z
2020-10-22T01:12:40.000Z
mbed-os/TESTS/mbed_drivers/race_test/main.cpp
ghsecuritylab/mbed-os-wave_player-example
39af3df51503c77e149eb732dbc07c7fd4ee351e
[ "Apache-2.0" ]
5
2018-08-15T12:02:20.000Z
2018-09-03T11:28:18.000Z
mbed-os/TESTS/mbed_drivers/race_test/main.cpp
ghsecuritylab/mbed-os-wave_player-example
39af3df51503c77e149eb732dbc07c7fd4ee351e
[ "Apache-2.0" ]
5
2018-03-09T15:48:38.000Z
2020-10-22T01:12:44.000Z
/* * Copyright (c) 2016-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "rtos.h" #include "greentea-client/test_env.h" #include "unity/unity.h" #include "utest/utest.h" #include "SingletonPtr.h" #include <stdio.h> #ifdef MBED_RTOS_SINGLE_THREAD #error [NOT_SUPPORTED] test not supported for single threaded enviroment #endif #if !DEVICE_USTICKER #error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; #define TEST_STACK_SIZE 512 static uint32_t instance_count = 0; class TestClass { public: TestClass() { Thread::wait(500); instance_count++; } void do_something() { Thread::wait(100); } ~TestClass() { instance_count--; } }; static TestClass *get_test_class() { static TestClass tc; return &tc; } static SingletonPtr<TestClass> test_class; static void main_func_race() { get_test_class(); TEST_ASSERT_EQUAL_UINT32(1, instance_count); } static void main_class_race() { test_class->do_something(); TEST_ASSERT_EQUAL_UINT32(1, instance_count); } void test_case_func_race() { Callback<void()> cb(main_func_race); Thread t1(osPriorityNormal, TEST_STACK_SIZE); Thread t2(osPriorityNormal, TEST_STACK_SIZE); // Start start first thread t1.start(cb); // Start second thread while the first is inside the constructor Thread::wait(250); t2.start(cb); // Wait for the threads to finish t1.join(); t2.join(); TEST_ASSERT_EQUAL_UINT32(1, instance_count); // Reset instance count instance_count = 0; } void test_case_class_race() { Callback<void()> cb(main_class_race); Thread t1(osPriorityNormal, TEST_STACK_SIZE); Thread t2(osPriorityNormal, TEST_STACK_SIZE); // Start start first thread t1.start(cb); // Start second thread while the first is inside the constructor Thread::wait(250); t2.start(cb); // Wait for the threads to finish t1.join(); t2.join(); TEST_ASSERT_EQUAL_UINT32(1, instance_count); // Reset instance count instance_count = 0; } Case cases[] = { Case("function init race", test_case_func_race), Case("class init race", test_case_class_race), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); }
22.731884
88
0.706407
ghsecuritylab
ca0cbaf2d15916a5a1ab9f854b8d6b3323f5fa2f
1,631
cpp
C++
Basic Programs/CPP/LenghtofLL(recursive).cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/CPP/LenghtofLL(recursive).cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/CPP/LenghtofLL(recursive).cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
/* Given a linked list, find and return the length of input LL recursively. Input format : Linked list elements (separated by space and terminated by -1) Output format : Length of LL Sample Input : 3 4 5 2 6 1 9 -1 Sample Output : 7 */ /********** * Following is the Node class that is already written. class Node{ public: int data; Node *next; Node(int data){ this -> data = data; this -> next = NULL; } }; *********/ #include <iostream> using namespace std; class Node{ public: int data; Node *next; Node(int data){ this -> data = data; this -> next = NULL; } }; Node* takeinput() { int data; cin >> data; Node* head = NULL, *tail = NULL; while(data != -1){ Node *newNode = new Node(data); if(head == NULL) { head = newNode; tail = newNode; } else{ tail -> next = newNode; tail = newNode; } cin >> data; } return head; } int length(Node *head) { /* Don't write main(). * Don't read input, it is passed as function argument. * Return output and don't print it. * Taking input is handled automatically. */ if(head==NULL) return 0; int ans=length(head->next); return ans+1; } void print(Node *head) { Node *temp = head; while(temp != NULL) { cout << temp -> data << " "; temp = temp -> next; } cout<<endl; } int main() { Node *head = takeinput(); int pos; cin >> pos; cout << length(head); return 0; }
15.533333
72
0.517474
PrajaktaSathe
ca0d4c6b467942844ddd87d378229d2df7cddc08
1,187
cpp
C++
1175/e_fin.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1175/e_fin.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1175/e_fin.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; const int INF = 1e9; const int MAX_N = 5e5 + 5; const int MAX_P = 21; int f[MAX_N][MAX_P]; int next_right[MAX_N]; int n, m; int main() { cin >> n >> m; for (int i = 0; i < n; ++i) { int l, r; cin >> l >> r; next_right[l] = max(next_right[l], r); } for (int i = 1; i < MAX_N; ++i) { next_right[i] = max(next_right[i], i); next_right[i] = max(next_right[i], next_right[i - 1]); f[i][0] = next_right[i]; } f[0][0] = next_right[0]; for (int j = 1; j < MAX_P; ++j) { for (int i = 0; i < MAX_N; ++i) { f[i][j] = f[f[i][j - 1]][j - 1]; } } for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; int cur_p = MAX_P - 1; // cout << "x: " << x << ", y: " << y << endl; int ans = 0; for (int j = MAX_P - 1; j >= 0; --j) { if (f[x][j] < y) { // cout << "f[" << x << "][" << j << "] = " << f[x][j] << endl; x = f[x][j]; ans += 1 << j; } } ++ans; if (ans <= n) { cout << ans << "\n"; } else { cout << "-1\n"; } } return 0; }
19.459016
71
0.428812
vladshablinsky
ca105b6ad8eadb8ebbfced706b616d58a3d2c50e
87,328
hpp
C++
include/GlobalNamespace/MultiplayerSessionManager.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MultiplayerSessionManager.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MultiplayerSessionManager.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: StandaloneMonobehavior #include "GlobalNamespace/StandaloneMonobehavior.hpp" // Including type: IMultiplayerSessionManager #include "GlobalNamespace/IMultiplayerSessionManager.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IConnectionInitParams`1<T> template<typename T> class IConnectionInitParams_1; // Forward declaring type: NetworkPacketSerializer`2<TType, TData> template<typename TType, typename TData> class NetworkPacketSerializer_2; // Forward declaring type: IConnectedPlayer class IConnectedPlayer; // Forward declaring type: SynchronizedActionQueue class SynchronizedActionQueue; // Forward declaring type: ConnectedPlayerManager class ConnectedPlayerManager; // Forward declaring type: INetworkPacketSubSerializer`1<TData> template<typename TData> class INetworkPacketSubSerializer_1; // Forward declaring type: IConnectionManager class IConnectionManager; // Skipping declaration: SessionType because it is already included! // Forward declaring type: UpdateConnectionStateReason struct UpdateConnectionStateReason; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Queue`1<T> template<typename T> class Queue_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: HashSet`1<T> template<typename T> class HashSet_1; // Forward declaring type: IReadOnlyList`1<T> template<typename T> class IReadOnlyList_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action class Action; // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: String class String; // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; // Forward declaring type: Func`1<TResult> template<typename TResult> class Func_1; } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: INetSerializable class INetSerializable; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0xB8 #pragma pack(push, 1) // Autogenerated type: MultiplayerSessionManager // [TokenAttribute] Offset: FFFFFFFF class MultiplayerSessionManager : public GlobalNamespace::StandaloneMonobehavior/*, public GlobalNamespace::IMultiplayerSessionManager*/ { public: // Writing base type padding for base size: 0x2C to desired offset: 0x30 char ___base_padding[0x4] = {}; // Nested type: GlobalNamespace::MultiplayerSessionManager::SessionType struct SessionType; // Nested type: GlobalNamespace::MultiplayerSessionManager::ConnectionState struct ConnectionState; // Nested type: GlobalNamespace::MultiplayerSessionManager::$$c__DisplayClass97_0 class $$c__DisplayClass97_0; // Nested type: GlobalNamespace::MultiplayerSessionManager::$$c class $$c; // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: MultiplayerSessionManager/SessionType // [TokenAttribute] Offset: FFFFFFFF struct SessionType/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: SessionType constexpr SessionType(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public MultiplayerSessionManager/SessionType Player static constexpr const int Player = 0; // Get static field: static public MultiplayerSessionManager/SessionType Player static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Player(); // Set static field: static public MultiplayerSessionManager/SessionType Player static void _set_Player(GlobalNamespace::MultiplayerSessionManager::SessionType value); // static field const value: static public MultiplayerSessionManager/SessionType Spectator static constexpr const int Spectator = 1; // Get static field: static public MultiplayerSessionManager/SessionType Spectator static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Spectator(); // Set static field: static public MultiplayerSessionManager/SessionType Spectator static void _set_Spectator(GlobalNamespace::MultiplayerSessionManager::SessionType value); // static field const value: static public MultiplayerSessionManager/SessionType DedicatedServer static constexpr const int DedicatedServer = 2; // Get static field: static public MultiplayerSessionManager/SessionType DedicatedServer static GlobalNamespace::MultiplayerSessionManager::SessionType _get_DedicatedServer(); // Set static field: static public MultiplayerSessionManager/SessionType DedicatedServer static void _set_DedicatedServer(GlobalNamespace::MultiplayerSessionManager::SessionType value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // MultiplayerSessionManager/SessionType #pragma pack(pop) static check_size<sizeof(MultiplayerSessionManager::SessionType), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_SessionTypeSizeCheck; static_assert(sizeof(MultiplayerSessionManager::SessionType) == 0x4); // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: MultiplayerSessionManager/ConnectionState // [TokenAttribute] Offset: FFFFFFFF struct ConnectionState/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: ConnectionState constexpr ConnectionState(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public MultiplayerSessionManager/ConnectionState Disconnected static constexpr const int Disconnected = 0; // Get static field: static public MultiplayerSessionManager/ConnectionState Disconnected static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnected(); // Set static field: static public MultiplayerSessionManager/ConnectionState Disconnected static void _set_Disconnected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value); // static field const value: static public MultiplayerSessionManager/ConnectionState Connecting static constexpr const int Connecting = 1; // Get static field: static public MultiplayerSessionManager/ConnectionState Connecting static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connecting(); // Set static field: static public MultiplayerSessionManager/ConnectionState Connecting static void _set_Connecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value); // static field const value: static public MultiplayerSessionManager/ConnectionState Connected static constexpr const int Connected = 2; // Get static field: static public MultiplayerSessionManager/ConnectionState Connected static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connected(); // Set static field: static public MultiplayerSessionManager/ConnectionState Connected static void _set_Connected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value); // static field const value: static public MultiplayerSessionManager/ConnectionState Disconnecting static constexpr const int Disconnecting = 3; // Get static field: static public MultiplayerSessionManager/ConnectionState Disconnecting static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnecting(); // Set static field: static public MultiplayerSessionManager/ConnectionState Disconnecting static void _set_Disconnecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // MultiplayerSessionManager/ConnectionState #pragma pack(pop) static check_size<sizeof(MultiplayerSessionManager::ConnectionState), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_ConnectionStateSizeCheck; static_assert(sizeof(MultiplayerSessionManager::ConnectionState) == 0x4); // private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer // Size: 0x8 // Offset: 0x30 GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer; // Field size check static_assert(sizeof(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers // Size: 0x8 // Offset: 0x38 System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState // Size: 0x8 // Offset: 0x40 System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState; // Field size check static_assert(sizeof(System::Collections::Generic::HashSet_1<::Il2CppString*>*) == 0x8); // private readonly SynchronizedActionQueue _synchronizedActionQueue // Size: 0x8 // Offset: 0x48 GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue; // Field size check static_assert(sizeof(GlobalNamespace::SynchronizedActionQueue*) == 0x8); // private System.Int32 _maxPlayerCount // Size: 0x4 // Offset: 0x50 int maxPlayerCount; // Field size check static_assert(sizeof(int) == 0x4); // private MultiplayerSessionManager/ConnectionState _connectionState // Size: 0x4 // Offset: 0x54 GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState; // Field size check static_assert(sizeof(GlobalNamespace::MultiplayerSessionManager::ConnectionState) == 0x4); // private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices // Size: 0x8 // Offset: 0x58 System::Collections::Generic::Queue_1<int>* freeSortIndices; // Field size check static_assert(sizeof(System::Collections::Generic::Queue_1<int>*) == 0x8); // private System.Action connectedEvent // Size: 0x8 // Offset: 0x60 System::Action* connectedEvent; // Field size check static_assert(sizeof(System::Action*) == 0x8); // private System.Action`1<ConnectionFailedReason> connectionFailedEvent // Size: 0x8 // Offset: 0x68 System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::ConnectionFailedReason>*) == 0x8); // private System.Action`1<IConnectedPlayer> playerConnectedEvent // Size: 0x8 // Offset: 0x70 System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private System.Action`1<IConnectedPlayer> playerDisconnectedEvent // Size: 0x8 // Offset: 0x78 System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent // Size: 0x8 // Offset: 0x80 System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private System.Action`1<IConnectedPlayer> playerStateChangedEvent // Size: 0x8 // Offset: 0x88 System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent // Size: 0x8 // Offset: 0x90 System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8); // private System.Action`1<DisconnectedReason> disconnectedEvent // Size: 0x8 // Offset: 0x98 System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::DisconnectedReason>*) == 0x8); // private IConnectedPlayer <connectionOwner>k__BackingField // Size: 0x8 // Offset: 0xA0 GlobalNamespace::IConnectedPlayer* connectionOwner; // Field size check static_assert(sizeof(GlobalNamespace::IConnectedPlayer*) == 0x8); // private System.Boolean _exclusiveConnectedPlayerManager // Size: 0x1 // Offset: 0xA8 bool exclusiveConnectedPlayerManager; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: exclusiveConnectedPlayerManager and: connectedPlayerManager char __padding16[0x7] = {}; // private ConnectedPlayerManager _connectedPlayerManager // Size: 0x8 // Offset: 0xB0 GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager; // Field size check static_assert(sizeof(GlobalNamespace::ConnectedPlayerManager*) == 0x8); // Creating value type constructor for type: MultiplayerSessionManager MultiplayerSessionManager(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer_ = {}, System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers_ = {}, System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState_ = {}, GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue_ = {}, int maxPlayerCount_ = {}, GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState_ = {}, System::Collections::Generic::Queue_1<int>* freeSortIndices_ = {}, System::Action* connectedEvent_ = {}, System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent_ = {}, GlobalNamespace::IConnectedPlayer* connectionOwner_ = {}, bool exclusiveConnectedPlayerManager_ = {}, GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager_ = {}) noexcept : packetSerializer{packetSerializer_}, connectedPlayers{connectedPlayers_}, localPlayerState{localPlayerState_}, synchronizedActionQueue{synchronizedActionQueue_}, maxPlayerCount{maxPlayerCount_}, connectionState{connectionState_}, freeSortIndices{freeSortIndices_}, connectedEvent{connectedEvent_}, connectionFailedEvent{connectionFailedEvent_}, playerConnectedEvent{playerConnectedEvent_}, playerDisconnectedEvent{playerDisconnectedEvent_}, playerAvatarChangedEvent{playerAvatarChangedEvent_}, playerStateChangedEvent{playerStateChangedEvent_}, connectionOwnerStateChangedEvent{connectionOwnerStateChangedEvent_}, disconnectedEvent{disconnectedEvent_}, connectionOwner{connectionOwner_}, exclusiveConnectedPlayerManager{exclusiveConnectedPlayerManager_}, connectedPlayerManager{connectedPlayerManager_} {} // Creating interface conversion operator: operator GlobalNamespace::IMultiplayerSessionManager operator GlobalNamespace::IMultiplayerSessionManager() noexcept { return *reinterpret_cast<GlobalNamespace::IMultiplayerSessionManager*>(this); } // static field const value: static private System.String kMultiplayerSessionState static constexpr const char* kMultiplayerSessionState = "multiplayer_session"; // Get static field: static private System.String kMultiplayerSessionState static ::Il2CppString* _get_kMultiplayerSessionState(); // Set static field: static private System.String kMultiplayerSessionState static void _set_kMultiplayerSessionState(::Il2CppString* value); // Get instance field reference: private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*& dyn__packetSerializer(); // Get instance field reference: private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*& dyn__connectedPlayers(); // Get instance field reference: private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState System::Collections::Generic::HashSet_1<::Il2CppString*>*& dyn__localPlayerState(); // Get instance field reference: private readonly SynchronizedActionQueue _synchronizedActionQueue GlobalNamespace::SynchronizedActionQueue*& dyn__synchronizedActionQueue(); // Get instance field reference: private System.Int32 _maxPlayerCount int& dyn__maxPlayerCount(); // Get instance field reference: private MultiplayerSessionManager/ConnectionState _connectionState GlobalNamespace::MultiplayerSessionManager::ConnectionState& dyn__connectionState(); // Get instance field reference: private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices System::Collections::Generic::Queue_1<int>*& dyn__freeSortIndices(); // Get instance field reference: private System.Action connectedEvent System::Action*& dyn_connectedEvent(); // Get instance field reference: private System.Action`1<ConnectionFailedReason> connectionFailedEvent System::Action_1<GlobalNamespace::ConnectionFailedReason>*& dyn_connectionFailedEvent(); // Get instance field reference: private System.Action`1<IConnectedPlayer> playerConnectedEvent System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerConnectedEvent(); // Get instance field reference: private System.Action`1<IConnectedPlayer> playerDisconnectedEvent System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerDisconnectedEvent(); // Get instance field reference: private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerAvatarChangedEvent(); // Get instance field reference: private System.Action`1<IConnectedPlayer> playerStateChangedEvent System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerStateChangedEvent(); // Get instance field reference: private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_connectionOwnerStateChangedEvent(); // Get instance field reference: private System.Action`1<DisconnectedReason> disconnectedEvent System::Action_1<GlobalNamespace::DisconnectedReason>*& dyn_disconnectedEvent(); // Get instance field reference: private IConnectedPlayer <connectionOwner>k__BackingField GlobalNamespace::IConnectedPlayer*& dyn_$connectionOwner$k__BackingField(); // Get instance field reference: private System.Boolean _exclusiveConnectedPlayerManager bool& dyn__exclusiveConnectedPlayerManager(); // Get instance field reference: private ConnectedPlayerManager _connectedPlayerManager GlobalNamespace::ConnectedPlayerManager*& dyn__connectedPlayerManager(); // public System.Boolean get_isConnectionOwner() // Offset: 0x16F1FCC bool get_isConnectionOwner(); // public IConnectedPlayer get_connectionOwner() // Offset: 0x16F1FE4 GlobalNamespace::IConnectedPlayer* get_connectionOwner(); // private System.Void set_connectionOwner(IConnectedPlayer value) // Offset: 0x16F1FEC void set_connectionOwner(GlobalNamespace::IConnectedPlayer* value); // public System.Boolean get_isSpectating() // Offset: 0x16F1FF4 bool get_isSpectating(); // public System.Boolean get_isConnectingOrConnected() // Offset: 0x16F20D0 bool get_isConnectingOrConnected(); // public System.Boolean get_isConnected() // Offset: 0x16F20F4 bool get_isConnected(); // public System.Boolean get_isConnecting() // Offset: 0x16F20E4 bool get_isConnecting(); // public System.Boolean get_isDisconnecting() // Offset: 0x16F2104 bool get_isDisconnecting(); // public System.Collections.Generic.IReadOnlyList`1<IConnectedPlayer> get_connectedPlayers() // Offset: 0x16F2114 System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* get_connectedPlayers(); // public System.Int32 get_connectedPlayerCount() // Offset: 0x16F211C int get_connectedPlayerCount(); // public System.Single get_syncTime() // Offset: 0x16F216C float get_syncTime(); // public System.Boolean get_isSyncTimeInitialized() // Offset: 0x16F2184 bool get_isSyncTimeInitialized(); // public System.Single get_syncTimeDelay() // Offset: 0x16F2198 float get_syncTimeDelay(); // public IConnectedPlayer get_localPlayer() // Offset: 0x16F21B0 GlobalNamespace::IConnectedPlayer* get_localPlayer(); // public ConnectedPlayerManager get_connectedPlayerManager() // Offset: 0x16F21C8 GlobalNamespace::ConnectedPlayerManager* get_connectedPlayerManager(); // public System.Int32 get_maxPlayerCount() // Offset: 0x16F21D0 int get_maxPlayerCount(); // public System.Void add_connectedEvent(System.Action value) // Offset: 0x16F158C void add_connectedEvent(System::Action* value); // public System.Void remove_connectedEvent(System.Action value) // Offset: 0x16F1630 void remove_connectedEvent(System::Action* value); // public System.Void add_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value) // Offset: 0x16F16D4 void add_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value); // public System.Void remove_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value) // Offset: 0x16F1778 void remove_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value); // public System.Void add_playerConnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F181C void add_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerConnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F18C0 void remove_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1964 void add_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1A08 void remove_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1AAC void add_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1B50 void remove_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1BF4 void add_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1C98 void remove_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1D3C void add_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0x16F1DE0 void remove_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_disconnectedEvent(System.Action`1<DisconnectedReason> value) // Offset: 0x16F1E84 void add_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value); // public System.Void remove_disconnectedEvent(System.Action`1<DisconnectedReason> value) // Offset: 0x16F1F28 void remove_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value); // public System.Void RegisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer) // Offset: 0x16F2BA4 void RegisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer); // public System.Void UnregisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer) // Offset: 0x16F2C14 void UnregisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer); // public System.Void RegisterCallback(MultiplayerSessionManager/MessageType serializerType, System.Action`2<T,IConnectedPlayer> callback, System.Func`1<T> constructor) // Offset: 0xFFFFFFFF template<class T> void RegisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, System::Action_2<T, GlobalNamespace::IConnectedPlayer*>* callback, System::Func_1<T>* constructor) { static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>); static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::RegisterCallback"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(constructor)}))); auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); auto ___instance_arg = this; ::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType, callback, constructor); } // public System.Void UnregisterCallback(MultiplayerSessionManager/MessageType serializerType) // Offset: 0xFFFFFFFF template<class T> void UnregisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType) { static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>); static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::UnregisterCallback"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType)}))); auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); auto ___instance_arg = this; ::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType); } // public System.Void StartSession(MultiplayerSessionManager/SessionType sessionType, T connectionManager, IConnectionInitParams`1<T> initParams) // Offset: 0xFFFFFFFF template<class T> void StartSession(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType, T connectionManager, GlobalNamespace::IConnectionInitParams_1<T>* initParams) { static_assert(std::is_base_of_v<GlobalNamespace::IConnectionManager, std::remove_pointer_t<T>>); static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::StartSession"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "StartSession", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sessionType), ::il2cpp_utils::ExtractType(connectionManager), ::il2cpp_utils::ExtractType(initParams)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); auto ___instance_arg = this; ::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, sessionType, connectionManager, initParams); } // public System.Void StartSession(ConnectedPlayerManager connectedPlayerManager) // Offset: 0x16F2C84 void StartSession(GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager); // public System.Void SetMaxPlayerCount(System.Int32 maxPlayerCount) // Offset: 0x16F310C void SetMaxPlayerCount(int maxPlayerCount); // private System.Void InitInternal(MultiplayerSessionManager/SessionType sessionType) // Offset: 0x16F2CD0 void InitInternal(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType); // public System.Void EndSession() // Offset: 0x16F2788 void EndSession(); // public System.Void Disconnect() // Offset: 0x16F3114 void Disconnect(); // public System.Void Send(T message) // Offset: 0xFFFFFFFF template<class T> void Send(T message) { static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>); static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::Send"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Send", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)}))); auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); auto ___instance_arg = this; ::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message); } // public System.Void SendUnreliable(T message) // Offset: 0xFFFFFFFF template<class T> void SendUnreliable(T message) { static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>); static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::SendUnreliable"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SendUnreliable", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)}))); auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); auto ___instance_arg = this; ::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message); } // public System.Void PerformAtSyncTime(System.Single syncTime, System.Action action) // Offset: 0x16F317C void PerformAtSyncTime(float syncTime, System::Action* action); // private System.Void UpdateSynchronizedActions() // Offset: 0x16F2314 void UpdateSynchronizedActions(); // private System.Void HandleReinitialized() // Offset: 0x16F3398 void HandleReinitialized(); // private System.Void HandleConnected() // Offset: 0x16F33A8 void HandleConnected(); // private System.Void HandleDisconnected(DisconnectedReason disconnectedReason) // Offset: 0x16F33B8 void HandleDisconnected(GlobalNamespace::DisconnectedReason disconnectedReason); // private System.Void HandleConnectionFailed(ConnectionFailedReason reason) // Offset: 0x16F33C8 void HandleConnectionFailed(GlobalNamespace::ConnectionFailedReason reason); // private System.Void HandleSyncTimeInitialized() // Offset: 0x16F33D8 void HandleSyncTimeInitialized(); // private System.Void HandlePlayerConnected(IConnectedPlayer player) // Offset: 0x16F33E8 void HandlePlayerConnected(GlobalNamespace::IConnectedPlayer* player); // private System.Void HandlePlayerDisconnected(IConnectedPlayer player) // Offset: 0x16F3A0C void HandlePlayerDisconnected(GlobalNamespace::IConnectedPlayer* player); // private System.Void HandlePlayerStateChanged(IConnectedPlayer player) // Offset: 0x16F3AE0 void HandlePlayerStateChanged(GlobalNamespace::IConnectedPlayer* player); // private System.Void HandlePlayerAvatarChanged(IConnectedPlayer player) // Offset: 0x16F3CA0 void HandlePlayerAvatarChanged(GlobalNamespace::IConnectedPlayer* player); // private System.Void HandlePlayerOrderChanged(IConnectedPlayer player) // Offset: 0x16F3D38 void HandlePlayerOrderChanged(GlobalNamespace::IConnectedPlayer* player); // public IConnectedPlayer GetPlayerByUserId(System.String userId) // Offset: 0x16F3D70 GlobalNamespace::IConnectedPlayer* GetPlayerByUserId(::Il2CppString* userId); // public IConnectedPlayer GetConnectedPlayer(System.Int32 i) // Offset: 0x16F3EF8 GlobalNamespace::IConnectedPlayer* GetConnectedPlayer(int i); // public System.Void SetLocalPlayerState(System.String state, System.Boolean hasState) // Offset: 0x16F222C void SetLocalPlayerState(::Il2CppString* state, bool hasState); // public System.Void KickPlayer(System.String userId) // Offset: 0x16F3F70 void KickPlayer(::Il2CppString* userId); // public System.Boolean LocalPlayerHasState(System.String state) // Offset: 0x16F3F88 bool LocalPlayerHasState(::Il2CppString* state); // private System.Void UpdateConnectionState(UpdateConnectionStateReason updateReason, DisconnectedReason disconnectedReason, ConnectionFailedReason connectionFailedReason) // Offset: 0x16F23A8 void UpdateConnectionState(GlobalNamespace::UpdateConnectionStateReason updateReason, GlobalNamespace::DisconnectedReason disconnectedReason, GlobalNamespace::ConnectionFailedReason connectionFailedReason); // private System.Boolean TryUpdateConnectedPlayer(IConnectedPlayer player, System.Boolean isPlayerConnected) // Offset: 0x16F34BC bool TryUpdateConnectedPlayer(GlobalNamespace::IConnectedPlayer* player, bool isPlayerConnected); // private System.Int32 GetNextAvailableSortIndex() // Offset: 0x16F40AC int GetNextAvailableSortIndex(); // public System.Void .ctor() // Offset: 0x16F4144 // Implemented from: StandaloneMonobehavior // Base method: System.Void StandaloneMonobehavior::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MultiplayerSessionManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MultiplayerSessionManager*, creationType>())); } // protected override System.Void Start() // Offset: 0x16F21D8 // Implemented from: StandaloneMonobehavior // Base method: System.Void StandaloneMonobehavior::Start() void Start(); // protected override System.Void Update() // Offset: 0x16F22DC // Implemented from: StandaloneMonobehavior // Base method: System.Void StandaloneMonobehavior::Update() void Update(); // protected override System.Void OnDestroy() // Offset: 0x16F2378 // Implemented from: StandaloneMonobehavior // Base method: System.Void StandaloneMonobehavior::OnDestroy() void OnDestroy(); // protected override System.Void OnApplicationPause(System.Boolean pauseStatus) // Offset: 0x16F2B44 // Implemented from: StandaloneMonobehavior // Base method: System.Void StandaloneMonobehavior::OnApplicationPause(System.Boolean pauseStatus) void OnApplicationPause(bool pauseStatus); }; // MultiplayerSessionManager #pragma pack(pop) static check_size<sizeof(MultiplayerSessionManager), 176 + sizeof(GlobalNamespace::ConnectedPlayerManager*)> __GlobalNamespace_MultiplayerSessionManagerSizeCheck; static_assert(sizeof(MultiplayerSessionManager) == 0xB8); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager*, "", "MultiplayerSessionManager"); DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::SessionType, "", "MultiplayerSessionManager/SessionType"); DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::ConnectionState, "", "MultiplayerSessionManager/ConnectionState"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner // Il2CppName: get_isConnectionOwner template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectionOwner // Il2CppName: get_connectionOwner template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectionOwner)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::set_connectionOwner // Il2CppName: set_connectionOwner template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::set_connectionOwner)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "set_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSpectating // Il2CppName: get_isSpectating template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSpectating)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSpectating", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected // Il2CppName: get_isConnectingOrConnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectingOrConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnected // Il2CppName: get_isConnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnected)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnecting // Il2CppName: get_isConnecting template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnecting)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting // Il2CppName: get_isDisconnecting template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isDisconnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers // Il2CppName: get_connectedPlayers template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount // Il2CppName: get_connectedPlayerCount template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTime // Il2CppName: get_syncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized // Il2CppName: get_isSyncTimeInitialized template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay // Il2CppName: get_syncTimeDelay template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTimeDelay", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_localPlayer // Il2CppName: get_localPlayer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_localPlayer)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_localPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager // Il2CppName: get_connectedPlayerManager template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::ConnectedPlayerManager* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerManager", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount // Il2CppName: get_maxPlayerCount template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_maxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectedEvent // Il2CppName: add_connectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent // Il2CppName: remove_connectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent // Il2CppName: add_connectionFailedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent // Il2CppName: remove_connectionFailedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent // Il2CppName: add_playerConnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent // Il2CppName: remove_playerConnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent // Il2CppName: add_playerDisconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent // Il2CppName: remove_playerDisconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent // Il2CppName: add_playerAvatarChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent // Il2CppName: remove_playerAvatarChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent // Il2CppName: add_playerStateChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent // Il2CppName: remove_playerStateChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent // Il2CppName: add_connectionOwnerStateChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent // Il2CppName: remove_connectionOwnerStateChangedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent // Il2CppName: add_disconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent // Il2CppName: remove_disconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterSerializer // Il2CppName: RegisterSerializer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::RegisterSerializer)> { static const MethodInfo* get() { static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg; static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "RegisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer // Il2CppName: UnregisterSerializer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer)> { static const MethodInfo* get() { static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg; static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UnregisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterCallback // Il2CppName: RegisterCallback // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterCallback // Il2CppName: UnregisterCallback // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession // Il2CppName: StartSession // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession // Il2CppName: StartSession template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectedPlayerManager*)>(&GlobalNamespace::MultiplayerSessionManager::StartSession)> { static const MethodInfo* get() { static auto* connectedPlayerManager = &::il2cpp_utils::GetClassFromName("", "ConnectedPlayerManager")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "StartSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{connectedPlayerManager}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount // Il2CppName: SetMaxPlayerCount template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount)> { static const MethodInfo* get() { static auto* maxPlayerCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetMaxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{maxPlayerCount}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::InitInternal // Il2CppName: InitInternal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager::SessionType)>(&GlobalNamespace::MultiplayerSessionManager::InitInternal)> { static const MethodInfo* get() { static auto* sessionType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/SessionType")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "InitInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionType}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::EndSession // Il2CppName: EndSession template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::EndSession)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "EndSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Disconnect // Il2CppName: Disconnect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Disconnect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Disconnect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Send // Il2CppName: Send // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SendUnreliable // Il2CppName: SendUnreliable // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime // Il2CppName: PerformAtSyncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(float, System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime)> { static const MethodInfo* get() { static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; static auto* action = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "PerformAtSyncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime, action}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions // Il2CppName: UpdateSynchronizedActions template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateSynchronizedActions", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleReinitialized // Il2CppName: HandleReinitialized template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleReinitialized)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleReinitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnected // Il2CppName: HandleConnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleConnected)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleDisconnected // Il2CppName: HandleDisconnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::DisconnectedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleDisconnected)> { static const MethodInfo* get() { static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disconnectedReason}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed // Il2CppName: HandleConnectionFailed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed)> { static const MethodInfo* get() { static auto* reason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnectionFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reason}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized // Il2CppName: HandleSyncTimeInitialized template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected // Il2CppName: HandlePlayerConnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected // Il2CppName: HandlePlayerDisconnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged // Il2CppName: HandlePlayerStateChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged // Il2CppName: HandlePlayerAvatarChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerAvatarChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged // Il2CppName: HandlePlayerOrderChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerOrderChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId // Il2CppName: GetPlayerByUserId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId)> { static const MethodInfo* get() { static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetPlayerByUserId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer // Il2CppName: GetConnectedPlayer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer)> { static const MethodInfo* get() { static auto* i = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{i}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState // Il2CppName: SetLocalPlayerState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*, bool)>(&GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState)> { static const MethodInfo* get() { static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* hasState = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetLocalPlayerState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state, hasState}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::KickPlayer // Il2CppName: KickPlayer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::KickPlayer)> { static const MethodInfo* get() { static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "KickPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState // Il2CppName: LocalPlayerHasState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState)> { static const MethodInfo* get() { static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "LocalPlayerHasState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState // Il2CppName: UpdateConnectionState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::UpdateConnectionStateReason, GlobalNamespace::DisconnectedReason, GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState)> { static const MethodInfo* get() { static auto* updateReason = &::il2cpp_utils::GetClassFromName("", "UpdateConnectionStateReason")->byval_arg; static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg; static auto* connectionFailedReason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateConnectionState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{updateReason, disconnectedReason, connectionFailedReason}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer // Il2CppName: TryUpdateConnectedPlayer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*, bool)>(&GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer)> { static const MethodInfo* get() { static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg; static auto* isPlayerConnected = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "TryUpdateConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player, isPlayerConnected}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex // Il2CppName: GetNextAvailableSortIndex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetNextAvailableSortIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Update // Il2CppName: Update template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Update)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnDestroy // Il2CppName: OnDestroy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::OnDestroy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnApplicationPause // Il2CppName: OnApplicationPause template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(bool)>(&GlobalNamespace::MultiplayerSessionManager::OnApplicationPause)> { static const MethodInfo* get() { static auto* pauseStatus = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnApplicationPause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pauseStatus}); } };
73.077824
2,247
0.774998
Fernthedev
ca10ce59e8add44aa2c13e8d28484a80163462eb
1,122
cpp
C++
imgplane.cpp
dghilardi/Sgherender
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
[ "MIT" ]
null
null
null
imgplane.cpp
dghilardi/Sgherender
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
[ "MIT" ]
null
null
null
imgplane.cpp
dghilardi/Sgherender
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
[ "MIT" ]
null
null
null
#include "imgplane.h" ImgPlane::ImgPlane(int w, int h) : width(w), height(h) { int size = w*h; for(int i=0; i<size; ++i){ image.push_back(new Color(0,0,0)); raysNumber.push_back(0); } } void ImgPlane::updatePixel(int x, int y, Color &pxl, int rays){ Color *actual = image[x*width+y]; int actualRays = raysNumber[x*width+y]; actual->setColor((actual->getR()*actualRays+pxl.getR()*rays)/(rays+actualRays), (actual->getG()*actualRays+pxl.getG()*rays)/(rays+actualRays), (actual->getB()*actualRays+pxl.getB()*rays)/(rays+actualRays) ); raysNumber[x*width+y] += rays; } void ImgPlane::writeImg(const string &fileName){ cv::Mat img(height, width, CV_8UC3); for(int x=0; x<width; ++x) for(int y=0; y<height; ++y){ Color toAssign = *(image[x*width+y]); toAssign.clampVars(); img.at<uchar>(y,3*x+2) = (uchar)255*toAssign.getR(); img.at<uchar>(y,3*x+1) = (uchar)255*toAssign.getG(); img.at<uchar>(y,3*x) = (uchar)255*toAssign.getB(); } cv::imwrite(fileName, img); }
34
83
0.578431
dghilardi
ca11d073f33b173a5993690aa4c7400e6d6024cf
3,503
cpp
C++
Graph/ManucianGoesToDerby_IMP_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
Graph/ManucianGoesToDerby_IMP_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
Graph/ManucianGoesToDerby_IMP_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
/**************erik****************/ #include<bits/stdc++.h> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long int ll; typedef unsigned long long int ull; map<int,int> mp1; set<int> s1; //set<int>::iterator it; #define maxm(a,b,c) max(a,max(c,b)) #define minm(a,b,c) min(a,min(c,b)) #define f(i,n) for(int i=1;i<n;i++) #define rf(i,n) for(int i=n-1;i>=0;i--) const int MAX = 100005; vector<pair<int,int> > vec[MAX]; ll dist[MAX]; bool vis[MAX]; void dijkstra(int source){ dist[source] = 0; multiset < pair < ll , int > > s; s.insert({0 , source}); while(!s.empty()){ pair <ll , int> p = *s.begin(); s.erase(s.begin()); int x = p.second; // if( vis[x] ) continue; // vis[x] = true; for(int i = 0; i < vec[x].size(); i++){ int e = vec[x][i].second; int w = vec[x][i].first; if(w==1){ if(dist[x]%2==0 && dist[e]>dist[x]+1){ dist[e] = dist[x]+2; //if wgt is odd but arrival time is even s.insert({dist[e],e}); } else if(dist[x]%2!=0 && dist[e]>dist[x]+1){ dist[e] = dist[x]+1; s.insert({dist[e],e}); } } else if(w==0){ if(dist[x]%2==0 && dist[e]>dist[x]+1){ dist[e] = dist[x]+1; s.insert({dist[e],e}); } else if(dist[x]%2!=0 && dist[e]>dist[x]+1){ dist[e] = dist[x]+2; // if wgt is even but arrival time is odd s.insert({dist[e],e}); } } } } } /*void dfs(int x,ll timed,int n){ vis[x]=1; tot = timed; if(vis[n]){ //cout<<x<<"*"<<timed+1<<endl; return; } if(timed%2==0){ if(vec[x][0].size()!=0){ bool f = true; for(int i=0;i<vec[x][0].size();i++){ int y = vec[x][0][i]; if(vis[y]==0){ f = false; //cout<<y<<'*'<<timed+1<<endl; dfs(y,timed+1,n); } } if(f){ //cout<<x<<"*"<<timed+1<<endl; dfs(x,timed+1,n); } } else { //cout<<x<<"*"<<timed+1<<endl; dfs(x,timed+1,n); } } else { if(vec[x][1].size()!=0){ bool f = true; for(int i=0;i<vec[x][1].size();i++){ int y = vec[x][1][i]; if(vis[y]==0){ f = false; //cout<<y<<' '<<timed+1<<endl; dfs(y,timed+1,n); } } //cout<<x<<"*"<<timed+1<<endl; dfs(x,timed+1,n); } else { //cout<<x<<"*"<<timed+1<<endl; dfs(x,timed+1,n); } } }*/ int main() { int n,m,q; cin>>n>>m>>q; for(int i=0;i<m;i++){ int x,y; cin>>x>>y; vec[x].push_back({0,y}); vec[y].push_back({1,x}); } for(int i=1;i<=n+1;i++){ dist[i]=1e12; vec[i].clear(); } dist[1]=0; dijkstra(1); cout<<dist[n]<<endl; for(int i=0;i<q;i++){ ll tt; cin>>tt; if(tt<dist[n]){ cout<<"FML"<<endl; } else { cout<<"GGMU"<<endl; } } //cout<<tot; return 0; }
26.338346
82
0.375393
Satyabrat35
ca147e45cea256785a4437433d70cbc6a13c4bd0
143,300
cpp
C++
src/libbrep/PullbackCurve.cpp
quadmotor/brlcad
05952aafa27ee9df17cd900f5d8f8217ed2194af
[ "BSD-4-Clause", "BSD-3-Clause" ]
35
2015-03-11T11:51:48.000Z
2021-07-25T16:04:49.000Z
src/libbrep/PullbackCurve.cpp
CloudComputer/brlcad
05952aafa27ee9df17cd900f5d8f8217ed2194af
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/libbrep/PullbackCurve.cpp
CloudComputer/brlcad
05952aafa27ee9df17cd900f5d8f8217ed2194af
[ "BSD-4-Clause", "BSD-3-Clause" ]
19
2016-05-04T08:39:37.000Z
2021-12-07T12:45:54.000Z
/* P U L L B A C K C U R V E . C P P * BRL-CAD * * Copyright (c) 2009-2014 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file step/PullbackCurve.cpp * * Pull curve back into UV space from 3D space * */ #include "common.h" #include "vmath.h" #include "dvec.h" #include <assert.h> #include <vector> #include <list> #include <limits> #include <set> #include <map> #include <string> #include "brep.h" /* interface header */ #include "PullbackCurve.h" #define RANGE_HI 0.55 #define RANGE_LO 0.45 #define UNIVERSAL_SAMPLE_COUNT 1001 /* FIXME: duplicated with opennurbs_ext.cpp */ class BSpline { public: int p; // degree int m; // num_knots-1 int n; // num_samples-1 (aka number of control points) std::vector<double> params; std::vector<double> knots; ON_2dPointArray controls; }; bool isFlat(const ON_2dPoint& p1, const ON_2dPoint& m, const ON_2dPoint& p2, double flatness) { ON_Line line = ON_Line(ON_3dPoint(p1), ON_3dPoint(p2)); return line.DistanceTo(ON_3dPoint(m)) <= flatness; } void utah_ray_planes(const ON_Ray &r, ON_3dVector &p1, double &p1d, ON_3dVector &p2, double &p2d) { ON_3dPoint ro(r.m_origin); ON_3dVector rdir(r.m_dir); double rdx, rdy, rdz; double rdxmag, rdymag, rdzmag; rdx = rdir.x; rdy = rdir.y; rdz = rdir.z; rdxmag = fabs(rdx); rdymag = fabs(rdy); rdzmag = fabs(rdz); if (rdxmag > rdymag && rdxmag > rdzmag) p1 = ON_3dVector(rdy, -rdx, 0); else p1 = ON_3dVector(0, rdz, -rdy); p1.Unitize(); p2 = ON_CrossProduct(p1, rdir); p1d = -(p1 * ro); p2d = -(p2 * ro); } enum seam_direction seam_direction(ON_2dPoint uv1, ON_2dPoint uv2) { if (NEAR_EQUAL(uv1.x, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 0.0, PBC_TOL)) { return WEST_SEAM; } else if (NEAR_EQUAL(uv1.x, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 1.0, PBC_TOL)) { return EAST_SEAM; } else if (NEAR_EQUAL(uv1.y, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 0.0, PBC_TOL)) { return SOUTH_SEAM; } else if (NEAR_EQUAL(uv1.y, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 1.0, PBC_TOL)) { return NORTH_SEAM; } else { return UNKNOWN_SEAM_DIRECTION; } } ON_BOOL32 GetDomainSplits( const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval, ON_Interval domSplits[2][2] ) { ON_3dPoint min, max; ON_Interval dom[2]; double length[2]; // initialize intervals for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { domSplits[i][j] = ON_Interval::EmptyInterval; } } min[0] = u_interval.m_t[0]; min[1] = v_interval.m_t[0]; max[0] = u_interval.m_t[1]; max[1] = v_interval.m_t[1]; for (int i=0; i<2; i++) { if (surf->IsClosed(i)) { dom[i] = surf->Domain(i); length[i] = dom[i].Length(); if ((max[i] - min[i]) >= length[i]) { domSplits[i][0] = dom[i]; } else { double minbound = min[i]; double maxbound = max[i]; while (minbound < dom[i].m_t[0]) { minbound += length[i]; maxbound += length[i]; } while (minbound > dom[i].m_t[1]) { minbound -= length[i]; maxbound -= length[i]; } if (maxbound > dom[i].m_t[1]) { domSplits[i][0].m_t[0] = minbound; domSplits[i][0].m_t[1] = dom[i].m_t[1]; domSplits[i][1].m_t[0] = dom[i].m_t[0]; domSplits[i][1].m_t[1] = maxbound - length[i]; } else { domSplits[i][0].m_t[0] = minbound; domSplits[i][0].m_t[1] = maxbound; } } } else { domSplits[i][0].m_t[0] = min[i]; domSplits[i][0].m_t[1] = max[i]; } } return true; } /* * Wrapped OpenNURBS 'EvNormal()' because it fails when at surface singularity * but not on edge of domain. If fails and at singularity this wrapper will * reevaluate at domain edge. */ ON_BOOL32 surface_EvNormal( // returns false if unable to evaluate const ON_Surface *surf, double s, double t, // evaluation parameters (s,t) ON_3dPoint& point, // returns value of surface ON_3dVector& normal, // unit normal int side, // optional - determines which side to evaluate from // 0 = default // 1 from NE quadrant // 2 from NW quadrant // 3 from SW quadrant // 4 from SE quadrant int* hint // optional - evaluation hint (int[2]) used to speed // repeated evaluations ) { ON_BOOL32 rc = false; if (!(rc=surf->EvNormal(s, t, point, normal, side, hint))) { side = IsAtSingularity(surf, s, t, PBC_SEAM_TOL);// 0 = south, 1 = east, 2 = north, 3 = west if (side >= 0) { ON_Interval u = surf->Domain(0); ON_Interval v = surf->Domain(1); if (side == 0) { rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint); } else if (side == 1) { rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint); } else if (side == 2) { rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint); } else if (side == 3) { rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint); } } } return rc; } ON_BOOL32 surface_GetBoundingBox( const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval, ON_BoundingBox& bbox, ON_BOOL32 bGrowBox ) { /* TODO: Address for threading * defined static for first time thru initialization, will * have to do something else here for multiple threads */ static ON_RevSurface *rev_surface = ON_RevSurface::New(); static ON_NurbsSurface *nurbs_surface = ON_NurbsSurface::New(); static ON_Extrusion *extr_surface = new ON_Extrusion(); static ON_PlaneSurface *plane_surface = new ON_PlaneSurface(); static ON_SumSurface *sum_surface = ON_SumSurface::New(); static ON_SurfaceProxy *proxy_surface = new ON_SurfaceProxy(); ON_Interval domSplits[2][2] = { { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }, { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }}; if (!GetDomainSplits(surf,u_interval,v_interval,domSplits)) { return false; } bool growcurrent = bGrowBox; for (int i=0; i<2; i++) { if (domSplits[0][i] == ON_Interval::EmptyInterval) continue; for (int j=0; j<2; j++) { if (domSplits[1][j] != ON_Interval::EmptyInterval) { if (dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf)) != NULL) { *rev_surface = *dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf)); if (rev_surface->Trim(0, domSplits[0][i]) && rev_surface->Trim(1, domSplits[1][j])) { if (!rev_surface->GetBoundingBox(bbox, growcurrent)) { return false; } growcurrent = true; } } else if (dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf)) != NULL) { *nurbs_surface = *dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf)); if (nurbs_surface->Trim(0, domSplits[0][i]) && nurbs_surface->Trim(1, domSplits[1][j])) { if (!nurbs_surface->GetBoundingBox(bbox, growcurrent)) { return false; } } growcurrent = true; } else if (dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf)) != NULL) { *extr_surface = *dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf)); if (extr_surface->Trim(0, domSplits[0][i]) && extr_surface->Trim(1, domSplits[1][j])) { if (!extr_surface->GetBoundingBox(bbox, growcurrent)) { return false; } } growcurrent = true; } else if (dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf)) != NULL) { *plane_surface = *dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf)); if (plane_surface->Trim(0, domSplits[0][i]) && plane_surface->Trim(1, domSplits[1][j])) { if (!plane_surface->GetBoundingBox(bbox, growcurrent)) { return false; } } growcurrent = true; } else if (dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf)) != NULL) { *sum_surface = *dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf)); if (sum_surface->Trim(0, domSplits[0][i]) && sum_surface->Trim(1, domSplits[1][j])) { if (!sum_surface->GetBoundingBox(bbox, growcurrent)) { return false; } } growcurrent = true; } else if (dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf)) != NULL) { *proxy_surface = *dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf)); if (proxy_surface->Trim(0, domSplits[0][i]) && proxy_surface->Trim(1, domSplits[1][j])) { if (!proxy_surface->GetBoundingBox(bbox, growcurrent)) { return false; } } growcurrent = true; } else { std::cerr << "Unknown Surface Type" << std::endl; } } } } return true; } ON_BOOL32 face_GetBoundingBox( const ON_BrepFace &face, ON_BoundingBox& bbox, ON_BOOL32 bGrowBox ) { const ON_Surface *surf = face.SurfaceOf(); // may be a smaller trimmed subset of surface so worth getting // face boundary bool growcurrent = bGrowBox; ON_3dPoint min, max; for (int li = 0; li < face.LoopCount(); li++) { for (int ti = 0; ti < face.Loop(li)->TrimCount(); ti++) { ON_BrepTrim *trim = face.Loop(li)->Trim(ti); trim->GetBoundingBox(min, max, growcurrent); growcurrent = true; } } ON_Interval u_interval(min.x, max.x); ON_Interval v_interval(min.y, max.y); if (!surface_GetBoundingBox(surf, u_interval,v_interval,bbox,growcurrent)) { return false; } return true; } ON_BOOL32 surface_GetIntervalMinMaxDistance( const ON_3dPoint& p, ON_BoundingBox &bbox, double &min_distance, double &max_distance ) { min_distance = bbox.MinimumDistanceTo(p); max_distance = bbox.MaximumDistanceTo(p); return true; } ON_BOOL32 surface_GetIntervalMinMaxDistance( const ON_Surface *surf, const ON_3dPoint& p, const ON_Interval &u_interval, const ON_Interval &v_interval, double &min_distance, double &max_distance ) { ON_BoundingBox bbox; if (surface_GetBoundingBox(surf,u_interval,v_interval,bbox, false)) { min_distance = bbox.MinimumDistanceTo(p); max_distance = bbox.MaximumDistanceTo(p); return true; } return false; } double surface_GetOptimalNormalUSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol) { ON_3dVector normal[4]; double u = u_interval.Mid(); if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) && (normal[2] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[1]))) { double step = u_interval.Length()/2.0; double stepdir = 1.0; u = u_interval.m_t[0] + stepdir * step; while (step > tol) { if ((normal[1] = surf->NormalAt(u,v_interval.m_t[0])) && (normal[3] = surf->NormalAt(u,v_interval.m_t[1]))) { double udot_1 = normal[0] * normal[1]; double udot_2 = normal[2] * normal[3]; if ((udot_1 < 0.0) || (udot_2 < 0.0)) { stepdir = -1.0; } else { stepdir = 1.0; } step = step / 2.0; u = u + stepdir * step; } } } return u; } double surface_GetOptimalNormalVSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol) { ON_3dVector normal[4]; double v = v_interval.Mid(); if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) && (normal[1] = surf->NormalAt(u_interval.m_t[1],v_interval.m_t[0]))) { double step = v_interval.Length()/2.0; double stepdir = 1.0; v = v_interval.m_t[0] + stepdir * step; while (step > tol) { if ((normal[2] = surf->NormalAt(u_interval.m_t[0],v)) && (normal[3] = surf->NormalAt(u_interval.m_t[1],v))) { double vdot_1 = normal[0] * normal[2]; double vdot_2 = normal[1] * normal[3]; if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) { stepdir = -1.0; } else { stepdir = 1.0; } step = step / 2.0; v = v + stepdir * step; } } } return v; } //forward for cyclic double surface_GetClosestPoint3dFirstOrderByRange(const ON_Surface *surf,const ON_3dPoint& p,const ON_Interval& u_range, const ON_Interval& v_range,double current_closest_dist,ON_2dPoint& p2d,ON_3dPoint& p3d,double same_point_tol, double within_distance_tol,int level); double surface_GetClosestPoint3dFirstOrderSubdivision(const ON_Surface *surf, const ON_3dPoint& p, const ON_Interval &u_interval, double u, const ON_Interval &v_interval, double v, double current_closest_dist, ON_2dPoint& p2d, ON_3dPoint& p3d, double same_point_tol, double within_distance_tol, int level) { double min_distance, max_distance; ON_Interval new_u_interval = u_interval; ON_Interval new_v_interval = v_interval; for (int iu = 0; iu < 2; iu++) { new_u_interval.m_t[iu] = u_interval.m_t[iu]; new_u_interval.m_t[1 - iu] = u; for (int iv = 0; iv < 2; iv++) { new_v_interval.m_t[iv] = v_interval.m_t[iv]; new_v_interval.m_t[1 - iv] = v; if (surface_GetIntervalMinMaxDistance(surf, p, new_u_interval,new_v_interval, min_distance, max_distance)) { double distance = DBL_MAX; if ((min_distance < current_closest_dist) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// ON_3dVector normal[4]; if ((normal[0] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[0])) && (normal[1] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[0])) && (normal[2] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[1])) && (normal[3] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[1]))) { double udot_1 = normal[0] * normal[1]; double udot_2 = normal[2] * normal[3]; double vdot_1 = normal[0] * normal[2]; double vdot_2 = normal[1] * normal[3]; if ((udot_1 < 0.0) || (udot_2 < 0.0) || (vdot_1 < 0.0) || (vdot_2 < 0.0)) { double u_split,v_split; if ((udot_1 < 0.0) || (udot_2 < 0.0)) { //get optimal U split u_split = surface_GetOptimalNormalUSplit(surf,new_u_interval,new_v_interval,same_point_tol); } else { u_split = new_u_interval.Mid(); } if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) { //get optimal V split v_split = surface_GetOptimalNormalVSplit(surf,new_u_interval,new_v_interval,same_point_tol); } else { v_split = new_v_interval.Mid(); } distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,new_u_interval,u_split,new_v_interval,v_split,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_closest_dist) { current_closest_dist = distance; if (current_closest_dist < same_point_tol) return current_closest_dist; } } else { distance = surface_GetClosestPoint3dFirstOrderByRange(surf,p,new_u_interval,new_v_interval,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_closest_dist) { current_closest_dist = distance; if (current_closest_dist < same_point_tol) return current_closest_dist; } } } } } } } return current_closest_dist; } double surface_GetClosestPoint3dFirstOrderByRange( const ON_Surface *surf, const ON_3dPoint& p, const ON_Interval& u_range, const ON_Interval& v_range, double current_closest_dist, ON_2dPoint& p2d, ON_3dPoint& p3d, double same_point_tol, double within_distance_tol, int level ) { ON_3dPoint p0; ON_2dPoint p2d0; ON_3dVector ds, dt, dss, dst, dtt; ON_2dPoint working_p2d; ON_3dPoint working_p3d; ON_3dPoint P; ON_3dVector Ds, Dt, Dss, Dst, Dtt; bool notdone = true; double previous_distance = DBL_MAX; double distance; int errcnt = 0; p2d0.x = u_range.Mid(); p2d0.y = v_range.Mid(); while (notdone && (surf->Ev2Der(p2d0.x, p2d0.y, p0, ds, dt, dss, dst, dtt))) { if ((distance = p0.DistanceTo(p)) >= previous_distance) { if (++errcnt <= 10) { p2d0 = (p2d0 + working_p2d) / 2.0; continue; } else { /////////////////////////// // Don't Subdivide just not getting any closer /////////////////////////// /* double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf, p, u_range, u_range.Mid(), v_range, v_range.Mid(), current_closest_dist, p2d, p3d, tol, level++); if (distance < current_closest_dist) { current_closest_dist = distance; if (current_closest_dist < tol) return current_closest_dist; } */ break; } } else { if (distance < current_closest_dist) { current_closest_dist = distance; p3d = p0; p2d = p2d0; if (current_closest_dist < same_point_tol) return current_closest_dist; } previous_distance = distance; working_p3d = p0; working_p2d = p2d0; errcnt = 0; } ON_3dVector N = ON_CrossProduct(ds, dt); N.Unitize(); ON_Plane plane(p0, N); ON_3dPoint q = plane.ClosestPointTo(p); ON_2dVector pullback; ON_3dVector vector = q - p0; double vlength = vector.Length(); if (vlength > 0.0) { if (ON_Pullback3dVector(vector, 0.0, ds, dt, dss, dst, dtt, pullback)) { p2d0 = p2d0 + pullback; if (!u_range.Includes(p2d0.x, false)) { int i = (u_range.m_t[0] <= u_range.m_t[1]) ? 0 : 1; p2d0.x = (p2d0.x < u_range.m_t[i]) ? u_range.m_t[i] : u_range.m_t[1 - i]; } if (!v_range.Includes(p2d0.y, false)) { int i = (v_range.m_t[0] <= v_range.m_t[1]) ? 0 : 1; p2d0.y = (p2d0.y < v_range.m_t[i]) ? v_range.m_t[i] : v_range.m_t[1 - i]; } } else { /////////////////////////// // Subdivide and go again /////////////////////////// notdone = false; distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf, p, u_range, u_range.Mid(), v_range, v_range.Mid(), current_closest_dist, p2d, p3d, same_point_tol, within_distance_tol, level++); if (distance < current_closest_dist) { current_closest_dist = distance; if (current_closest_dist < same_point_tol) return current_closest_dist; } break; } } else { // can't get any closer notdone = false; break; } } if (previous_distance < current_closest_dist) { current_closest_dist = previous_distance; p3d = working_p3d; p2d = working_p2d; } return current_closest_dist; } bool surface_GetClosestPoint3dFirstOrder( const ON_Surface *surf, const ON_3dPoint& p, ON_2dPoint& p2d, ON_3dPoint& p3d, double &current_distance, int quadrant, // optional - determines which quadrant to evaluate from // 0 = default // 1 from NE quadrant // 2 from NW quadrant // 3 from SW quadrant // 4 from SE quadrant double same_point_tol, double within_distance_tol ) { ON_3dPoint p0; ON_2dPoint p2d0; ON_3dVector ds, dt, dss, dst, dtt; ON_3dVector T, K; bool rc = false; static const ON_Surface *prev_surface = NULL; static int prev_u_spancnt = 0; static int u_spancnt = 0; static int v_spancnt = 0; static double *uspan = NULL; static double *vspan = NULL; static ON_BoundingBox **bbox = NULL; static double umid = 0.0; static int umid_index = 0; static double vmid = 0.0; static int vmid_index = 0; current_distance = DBL_MAX; int prec = std::cerr.precision(); std::cerr.precision(15); if (prev_surface != surf) { if (uspan) delete [] uspan; if (vspan) delete [] vspan; if (bbox) { for( int i = 0 ; i < (prev_u_spancnt + 2) ; i++ ) delete [] bbox[i] ; delete [] bbox; } u_spancnt = prev_u_spancnt = surf->SpanCount(0); v_spancnt = surf->SpanCount(1); // adding 2 here because going to divide at midpoint uspan = new double[u_spancnt + 2]; vspan = new double[v_spancnt + 2]; bbox = new ON_BoundingBox *[(u_spancnt + 2)]; for( int i = 0 ; i < (u_spancnt + 2) ; i++ ) bbox[i] = new ON_BoundingBox [v_spancnt + 2]; if (surf->GetSpanVector(0, uspan) && surf->GetSpanVector(1, vspan)) { prev_surface = surf; umid = surf->Domain(0).Mid(); umid_index = u_spancnt/2; for (int u_span_index = 0; u_span_index < u_spancnt + 1;u_span_index++) { if (NEAR_EQUAL(uspan[u_span_index],umid,same_point_tol)) { umid_index = u_span_index; break; } else if (uspan[u_span_index] > umid) { for (u_span_index = u_spancnt + 1; u_span_index > 0;u_span_index--) { if (uspan[u_span_index-1] < umid) { uspan[u_span_index] = umid; umid_index = u_span_index; u_spancnt++; u_span_index = u_spancnt+1; break; } else { uspan[u_span_index] = uspan[u_span_index-1]; } } } } vmid = surf->Domain(1).Mid(); vmid_index = v_spancnt/2; for (int v_span_index = 0; v_span_index < v_spancnt + 1;v_span_index++) { if (NEAR_EQUAL(vspan[v_span_index],vmid,same_point_tol)) { vmid_index = v_span_index; break; } else if (vspan[v_span_index] > vmid) { for (v_span_index = v_spancnt + 1; v_span_index > 0;v_span_index--) { if (vspan[v_span_index-1] < vmid) { vspan[v_span_index] = vmid; vmid_index = v_span_index; v_spancnt++; v_span_index = v_spancnt+1; break; } else { vspan[v_span_index] = vspan[v_span_index-1]; } } } } for (int u_span_index = 1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); if (!surface_GetBoundingBox(surf,u_interval,v_interval,bbox[u_span_index-1][v_span_index-1], false)) { std::cerr << "Error computing bounding box for surface interval" << std::endl; } } } } else { prev_surface = NULL; } } if (prev_surface == surf) { if (quadrant == 0) { for (int u_span_index = 1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } if (current_distance < within_distance_tol) { rc = true; goto cleanup; } } else if (quadrant == 1) { if (surf->IsClosed(0)) { //NE,SE,NW.SW // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } else { //NE,NW,SW,SE // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } if (current_distance < within_distance_tol) { rc = true; goto cleanup; } } else if (quadrant == 2) { if (surf->IsClosed(0)) { // NW,SW,NE,SE // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } else { // NW,NE,SW,SE // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } if (current_distance < within_distance_tol) { rc = true; goto cleanup; } } else if (quadrant == 3) { if (surf->IsClosed(0)) { // SW,NW,SE,NE // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } else { // SW,SE,NW,NE // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } if (current_distance < within_distance_tol) { rc = true; goto cleanup; } } else if (quadrant == 4) { if (surf->IsClosed(0)) { // SE,NE,SW,NW // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } else { // SE,SW,NE,NW // 4 from SE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 3 from SW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 1 from NE quadrant for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } // 2 from NW quadrant for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) { for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) { ON_Interval u_interval(uspan[u_span_index - 1], uspan[u_span_index]); ON_Interval v_interval(vspan[v_span_index - 1], vspan[v_span_index]); double min_distance,max_distance; int level = 1; if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) { if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) { ///////////////////////////////////////// // Could check normals and CV angles here ///////////////////////////////////////// double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++); if (distance < current_distance) { current_distance = distance; if (current_distance < same_point_tol) { rc = true; goto cleanup; } } } } } } } if (current_distance < within_distance_tol) { rc = true; goto cleanup; } } } cleanup: std::cerr.precision(prec); return rc; } bool trim_GetClosestPoint3dFirstOrder( const ON_BrepTrim& trim, const ON_3dPoint& p, ON_2dPoint& p2d, double& t, double& distance, const ON_Interval* interval, double same_point_tol, double within_distance_tol ) { bool rc = false; const ON_Surface *surf = trim.SurfaceOf(); double t0 = interval->Mid(); ON_3dPoint p3d; ON_3dPoint p0; ON_3dVector ds,dt,dss,dst,dtt; ON_3dVector T,K; int prec = std::cerr.precision(); ON_BoundingBox tight_bbox; std::vector<ON_BoundingBox> bbox; std::cerr.precision(15); ON_Curve *c = trim.Brep()->m_C2[trim.m_c2i]; ON_NurbsCurve N; if ( 0 == c->GetNurbForm(N) ) return false; if ( N.m_order < 2 || N.m_cv_count < N.m_order ) return false; p2d = trim.PointAt(t); int quadrant = 0; // optional - determines which quadrant to evaluate from // 0 = default // 1 from NE quadrant // 2 from NW quadrant // 3 from SW quadrant // 4 from SE quadrant ON_Interval u_interval = surf->Domain(0); ON_Interval v_interval = surf->Domain(1); if (p2d.y > v_interval.Mid()) { // North quadrants -> 1 or 2; if (p2d.x > u_interval.Mid()) { quadrant = 1; // NE } else { quadrant = 2; //NW } } else { // South quadrants -> 3 or 4; if (p2d.x > u_interval.Mid()) { quadrant = 4; // SE } else { quadrant = 3; //SW } } if (surface_GetClosestPoint3dFirstOrder(surf,p,p2d,p3d,distance,quadrant,same_point_tol,within_distance_tol)) { ON_BezierCurve B; bool bGrowBox = false; ON_3dVector d1,d2; double max_dist_to_closest_pt = DBL_MAX; ON_Interval *span_interval = new ON_Interval[N.m_cv_count - N.m_order + 1]; double *min_distance = new double[N.m_cv_count - N.m_order + 1]; double *max_distance = new double[N.m_cv_count - N.m_order + 1]; bool *skip = new bool[N.m_cv_count - N.m_order + 1]; bbox.resize(N.m_cv_count - N.m_order + 1); for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ ) { skip[span_index] = true; if ( !(N.m_knot[span_index + N.m_order-2] < N.m_knot[span_index + N.m_order-1]) ) continue; // check for span out of interval int i = (interval->m_t[0] <= interval->m_t[1]) ? 0 : 1; if ( N.m_knot[span_index + N.m_order-2] > interval->m_t[1-i] ) continue; if ( N.m_knot[span_index + N.m_order-1] < interval->m_t[i] ) continue; if ( !N.ConvertSpanToBezier( span_index, B ) ) continue; ON_Interval bi = B.Domain(); if ( !B.GetTightBoundingBox(tight_bbox,bGrowBox,NULL) ) continue; bbox[span_index] = tight_bbox; d1 = tight_bbox.m_min - p2d; d2 = tight_bbox.m_max - p2d; min_distance[span_index] = tight_bbox.MinimumDistanceTo(p2d); if (min_distance[span_index] > max_dist_to_closest_pt) { max_distance[span_index] = DBL_MAX; continue; } skip[span_index] = false; span_interval[span_index].m_t[0] = ((N.m_knot[span_index + N.m_order-2]) < interval->m_t[i]) ? interval->m_t[i] : N.m_knot[span_index + N.m_order-2]; span_interval[span_index].m_t[1] = ((N.m_knot[span_index + N.m_order-1]) > interval->m_t[1 -i]) ? interval->m_t[1 -i] : (N.m_knot[span_index + N.m_order-1]); ON_3dPoint d1sq(d1.x*d1.x,d1.y*d1.y,0.0),d2sq(d2.x*d2.x,d2.y*d2.y,0.0); double distancesq; if (d1sq.x < d2sq.x) { if (d1sq.y < d2sq.y) { if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) { distancesq = d1sq.x + d2sq.y; } else { distancesq = d2sq.x + d1sq.y; } } else { if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) { distancesq = d1sq.x + d1sq.y; } else { distancesq = d2sq.x + d2sq.y; } } } else { if (d1sq.y < d2sq.y) { if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) { distancesq = d1sq.x + d1sq.y; } else { distancesq = d2sq.x + d2sq.y; } } else { if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) { distancesq = d1sq.x + d2sq.y; } else { distancesq = d2sq.x + d1sq.y; } } } max_distance[span_index] = sqrt(distancesq); if (max_distance[span_index] < max_dist_to_closest_pt) { max_dist_to_closest_pt = max_distance[span_index]; } if (max_distance[span_index] < min_distance[span_index]) { // should only be here for near equal fuzz min_distance[span_index] = max_distance[span_index]; } } for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ ) { if ( skip[span_index] ) continue; if (min_distance[span_index] > max_dist_to_closest_pt) { skip[span_index] = true; continue; } } ON_3dPoint q; ON_3dPoint point; double closest_distance = DBL_MAX; double closestT = DBL_MAX; for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ ) { if (skip[span_index]) { continue; } t0 = span_interval[span_index].Mid(); bool closestfound = false; bool notdone = true; double distance = DBL_MAX; double previous_distance = DBL_MAX; ON_3dVector firstDervative, secondDervative; while (notdone && trim.Ev2Der(t0, point, firstDervative, secondDervative) && ON_EvCurvature(firstDervative, secondDervative, T, K)) { ON_Line line(point, point + 100.0 * T); q = line.ClosestPointTo(p2d); double delta_t = (firstDervative * (q - point)) / (firstDervative * firstDervative); double new_t0 = t0 + delta_t; if (!span_interval[span_index].Includes(new_t0, false)) { // limit to interval int i = (span_interval[span_index].m_t[0] <= span_interval[span_index].m_t[1]) ? 0 : 1; new_t0 = (new_t0 < span_interval[span_index].m_t[i]) ? span_interval[span_index].m_t[i] : span_interval[span_index].m_t[1 - i]; } delta_t = new_t0 - t0; t0 = new_t0; point = trim.PointAt(t0); distance = point.DistanceTo(p2d); if (distance < previous_distance) { closestfound = true; closestT = t0; previous_distance = distance; if (fabs(delta_t) < same_point_tol) { notdone = false; } } else { notdone = false; } } if (closestfound && (distance < closest_distance)) { closest_distance = distance; rc = true; t = closestT; } } delete [] span_interval; delete [] min_distance; delete [] max_distance; delete [] skip; } std::cerr.precision(prec); return rc; } bool toUV(PBCData& data, ON_2dPoint& out_pt, double t, double knudge = 0.0) { ON_3dPoint pointOnCurve = data.curve->PointAt(t); ON_3dPoint knudgedPointOnCurve = data.curve->PointAt(t + knudge); ON_2dPoint uv; if (data.surftree->getSurfacePoint((const ON_3dPoint&)pointOnCurve, uv, (const ON_3dPoint&)knudgedPointOnCurve, BREP_EDGE_MISS_TOLERANCE) > 0) { out_pt.Set(uv.x, uv.y); return true; } else { return false; } } bool toUV(brlcad::SurfaceTree *surftree, const ON_Curve *curve, ON_2dPoint& out_pt, double t, double knudge = 0.0) { if (!surftree) return false; const ON_Surface *surf = surftree->getSurface(); if (!surf) return false; ON_3dPoint pointOnCurve = curve->PointAt(t); ON_3dPoint knudgedPointOnCurve = curve->PointAt(t + knudge); ON_3dVector dt; curve->Ev1Der(t, pointOnCurve, dt); ON_3dVector tangent = curve->TangentAt(t); //data.surf->GetClosestPoint(pointOnCurve, &a, &b, 0.0001); ON_Ray r(pointOnCurve, tangent); plane_ray pr; brep_get_plane_ray(r, pr); ON_3dVector p1; double p1d; ON_3dVector p2; double p2d; utah_ray_planes(r, p1, p1d, p2, p2d); VMOVE(pr.n1, p1); pr.d1 = p1d; VMOVE(pr.n2, p2); pr.d2 = p2d; try { pt2d_t uv; ON_2dPoint uv2d = surftree->getClosestPointEstimate(knudgedPointOnCurve); move(uv, uv2d); ON_3dVector dir = surf->NormalAt(uv[0], uv[1]); dir.Reverse(); ON_Ray ray(pointOnCurve, dir); brep_get_plane_ray(ray, pr); //know use this as guess to iterate to closer solution pt2d_t Rcurr; pt2d_t new_uv; ON_3dPoint pt; ON_3dVector su, sv; #ifdef SHOW_UNUSED bool found = false; #endif fastf_t Dlast = MAX_FASTF; for (int i = 0; i < 10; i++) { brep_r(surf, pr, uv, pt, su, sv, Rcurr); fastf_t d = v2mag(Rcurr); if (d < BREP_INTERSECTION_ROOT_EPSILON) { TRACE1("R:" << ON_PRINT2(Rcurr)); #ifdef SHOW_UNUSED found = true; break; #endif } else if (d > Dlast) { #ifdef SHOW_UNUSED found = false; //break; #endif break; //return brep_edge_check(found, sbv, face, surf, ray, hits); } brep_newton_iterate(pr, Rcurr, su, sv, uv, new_uv); move(uv, new_uv); Dlast = d; } /////////////////////////////////////// out_pt.Set(uv[0], uv[1]); return true; } catch (...) { return false; } } double randomPointFromRange(PBCData& data, ON_2dPoint& out, double lo, double hi) { assert(lo < hi); double random_pos = drand48() * (RANGE_HI - RANGE_LO) + RANGE_LO; double newt = random_pos * (hi - lo) + lo; assert(toUV(data, out, newt)); return newt; } bool sample(PBCData& data, double t1, double t2, const ON_2dPoint& p1, const ON_2dPoint& p2) { ON_2dPoint m; double t = randomPointFromRange(data, m, t1, t2); if (!data.segments.empty()) { ON_2dPointArray * samples = data.segments.back(); if (isFlat(p1, m, p2, data.flatness)) { samples->Append(p2); } else { sample(data, t1, t, p1, m); sample(data, t, t2, m, p2); } return true; } return false; } void generateKnots(BSpline& bspline) { int num_knots = bspline.m + 1; bspline.knots.resize(num_knots); for (int i = 0; i <= bspline.p; i++) { bspline.knots[i] = 0.0; } for (int i = bspline.m - bspline.p; i <= bspline.m; i++) { bspline.knots[i] = 1.0; } for (int i = 1; i <= bspline.n - bspline.p; i++) { bspline.knots[bspline.p + i] = (double)i / (bspline.n - bspline.p + 1.0); } } int getKnotInterval(BSpline& bspline, double u) { int k = 0; while (u >= bspline.knots[k]) k++; k = (k == 0) ? k : k - 1; return k; } ON_NurbsCurve* interpolateLocalCubicCurve(ON_2dPointArray &Q) { int num_samples = Q.Count(); int num_segments = Q.Count() - 1; int qsize = num_samples + 4; std::vector < ON_2dVector > qarray(qsize); for (int i = 1; i < Q.Count(); i++) { qarray[i + 1] = Q[i] - Q[i - 1]; } qarray[1] = 2.0 * qarray[2] - qarray[3]; qarray[0] = 2.0 * qarray[1] - qarray[2]; qarray[num_samples + 1] = 2 * qarray[num_samples] - qarray[num_samples - 1]; qarray[num_samples + 2] = 2 * qarray[num_samples + 1] - qarray[num_samples]; qarray[num_samples + 3] = 2 * qarray[num_samples + 2] - qarray[num_samples + 1]; std::vector < ON_2dVector > T(num_samples); std::vector<double> A(num_samples); for (int k = 0; k < num_samples; k++) { ON_3dVector a = ON_CrossProduct(qarray[k], qarray[k + 1]); ON_3dVector b = ON_CrossProduct(qarray[k + 2], qarray[k + 3]); double alength = a.Length(); if (NEAR_ZERO(alength, PBC_TOL)) { A[k] = 1.0; } else { A[k] = (a.Length()) / (a.Length() + b.Length()); } T[k] = (1.0 - A[k]) * qarray[k + 1] + A[k] * qarray[k + 2]; T[k].Unitize(); } std::vector < ON_2dPointArray > P(num_samples - 1); ON_2dPointArray control_points; control_points.Append(Q[0]); for (int i = 1; i < num_samples; i++) { ON_2dPoint P0 = Q[i - 1]; ON_2dPoint P3 = Q[i]; ON_2dVector T0 = T[i - 1]; ON_2dVector T3 = T[i]; double a, b, c; ON_2dVector vT0T3 = T0 + T3; ON_2dVector dP0P3 = P3 - P0; a = 16.0 - vT0T3.Length() * vT0T3.Length(); b = 12.0 * (dP0P3 * vT0T3); c = -36.0 * dP0P3.Length() * dP0P3.Length(); double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a); ON_2dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0; control_points.Append(P1); ON_2dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3; control_points.Append(P2); P[i - 1].Append(P0); P[i - 1].Append(P1); P[i - 1].Append(P2); P[i - 1].Append(P3); } control_points.Append(Q[num_samples - 1]); std::vector<double> u(num_segments + 1); u[0] = 0.0; for (int k = 0; k < num_segments; k++) { u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length(); } int degree = 3; int n = control_points.Count(); int p = degree; int m = n + p - 1; int dimension = 2; ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n); c->ReserveKnotCapacity(m); for (int i = 0; i < degree; i++) { c->SetKnot(i, 0.0); } for (int i = 1; i < num_segments; i++) { double knot_value = u[i] / u[num_segments]; c->SetKnot(degree + 2 * (i - 1), knot_value); c->SetKnot(degree + 2 * (i - 1) + 1, knot_value); } for (int i = m - p; i < m; i++) { c->SetKnot(i, 1.0); } // insert the control points for (int i = 0; i < n; i++) { ON_3dPoint pnt = control_points[i]; c->SetCV(i, pnt); } return c; } ON_NurbsCurve* interpolateLocalCubicCurve(const ON_3dPointArray &Q) { int num_samples = Q.Count(); int num_segments = Q.Count() - 1; int qsize = num_samples + 3; std::vector<ON_3dVector> qarray(qsize + 1); ON_3dVector *q = &qarray[1]; for (int i = 1; i < Q.Count(); i++) { q[i] = Q[i] - Q[i - 1]; } q[0] = 2.0 * q[1] - q[2]; q[-1] = 2.0 * q[0] - q[1]; q[num_samples] = 2 * q[num_samples - 1] - q[num_samples - 2]; q[num_samples + 1] = 2 * q[num_samples] - q[num_samples - 1]; q[num_samples + 2] = 2 * q[num_samples + 1] - q[num_samples]; std::vector<ON_3dVector> T(num_samples); std::vector<double> A(num_samples); for (int k = 0; k < num_samples; k++) { ON_3dVector avec = ON_CrossProduct(q[k - 1], q[k]); ON_3dVector bvec = ON_CrossProduct(q[k + 1], q[k + 2]); double alength = avec.Length(); if (NEAR_ZERO(alength, PBC_TOL)) { A[k] = 1.0; } else { A[k] = (avec.Length()) / (avec.Length() + bvec.Length()); } T[k] = (1.0 - A[k]) * q[k] + A[k] * q[k + 1]; T[k].Unitize(); } std::vector<ON_3dPointArray> P(num_samples - 1); ON_3dPointArray control_points; control_points.Append(Q[0]); for (int i = 1; i < num_samples; i++) { ON_3dPoint P0 = Q[i - 1]; ON_3dPoint P3 = Q[i]; ON_3dVector T0 = T[i - 1]; ON_3dVector T3 = T[i]; double a, b, c; ON_3dVector vT0T3 = T0 + T3; ON_3dVector dP0P3 = P3 - P0; a = 16.0 - vT0T3.Length() * vT0T3.Length(); b = 12.0 * (dP0P3 * vT0T3); c = -36.0 * dP0P3.Length() * dP0P3.Length(); double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a); ON_3dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0; control_points.Append(P1); ON_3dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3; control_points.Append(P2); P[i - 1].Append(P0); P[i - 1].Append(P1); P[i - 1].Append(P2); P[i - 1].Append(P3); } control_points.Append(Q[num_samples - 1]); std::vector<double> u(num_segments + 1); u[0] = 0.0; for (int k = 0; k < num_segments; k++) { u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length(); } int degree = 3; int n = control_points.Count(); int p = degree; int m = n + p - 1; int dimension = 3; ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n); c->ReserveKnotCapacity(m); for (int i = 0; i < degree; i++) { c->SetKnot(i, 0.0); } for (int i = 1; i < num_segments; i++) { double knot_value = u[i] / u[num_segments]; c->SetKnot(degree + 2 * (i - 1), knot_value); c->SetKnot(degree + 2 * (i - 1) + 1, knot_value); } for (int i = m - p; i < m; i++) { c->SetKnot(i, 1.0); } // insert the control points for (int i = 0; i < n; i++) { ON_3dPoint pnt = control_points[i]; c->SetCV(i, pnt); } return c; } ON_NurbsCurve* newNURBSCurve(BSpline& spline, int dimension = 3) { // we now have everything to complete our spline ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, spline.p + 1, spline.n + 1); c->ReserveKnotCapacity(spline.knots.size() - 2); for (unsigned int i = 1; i < spline.knots.size() - 1; i++) { c->m_knot[i - 1] = spline.knots[i]; } for (int i = 0; i < spline.controls.Count(); i++) { c->SetCV(i, ON_3dPoint(spline.controls[i])); } return c; } ON_Curve* interpolateCurve(ON_2dPointArray &samples) { ON_NurbsCurve* nurbs; if (samples.Count() == 2) // build a line return new ON_LineCurve(samples[0], samples[1]); // local vs. global interpolation for large point sampled curves nurbs = interpolateLocalCubicCurve(samples); return nurbs; } int IsAtSeam(const ON_Surface *surf, int dir, double u, double v, double tol) { int rc = 0; if (!surf->IsClosed(dir)) return rc; double p = (dir) ? v : u; if (NEAR_EQUAL(p, surf->Domain(dir)[0], tol) || NEAR_EQUAL(p, surf->Domain(dir)[1], tol)) rc += (dir + 1); return rc; } /* * Similar to openNURBS's surf->IsAtSeam() function but uses tolerance to do a near check versus * the floating point equality used by openNURBS. * rc = 0 Not on seam, 1 on East/West seam(umin/umax), 2 on North/South seam(vmin/vmax), 3 seam on both U/V boundaries */ int IsAtSeam(const ON_Surface *surf, double u, double v, double tol) { int rc = 0; int i; for (i = 0; i < 2; i++) { rc += IsAtSeam(surf, i, u, v, tol); } return rc; } int IsAtSeam(const ON_Surface *surf, int dir, const ON_2dPoint &pt, double tol) { int rc = 0; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol); rc = IsAtSeam(surf,dir,unwrapped_pt.x,unwrapped_pt.y,tol); return rc; } /* * Similar to IsAtSeam(surf,u,v,tol) function but takes a ON_2dPoint * and unwraps any closed seam extents before passing on IsAtSeam(surf,u,v,tol) */ int IsAtSeam(const ON_Surface *surf, const ON_2dPoint &pt, double tol) { int rc = 0; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol); rc = IsAtSeam(surf,unwrapped_pt.x,unwrapped_pt.y,tol); return rc; } int IsAtSingularity(const ON_Surface *surf, double u, double v, double tol) { // 0 = south, 1 = east, 2 = north, 3 = west //std::cerr << "IsAtSingularity = u, v - " << u << ", " << v << std::endl; //std::cerr << "surf->Domain(0) - " << surf->Domain(0)[0] << ", " << surf->Domain(0)[1] << std::endl; //std::cerr << "surf->Domain(1) - " << surf->Domain(1)[0] << ", " << surf->Domain(1)[1] << std::endl; if (NEAR_EQUAL(u, surf->Domain(0)[0], tol)) { if (surf->IsSingular(3)) return 3; } else if (NEAR_EQUAL(u, surf->Domain(0)[1], tol)) { if (surf->IsSingular(1)) return 1; } if (NEAR_EQUAL(v, surf->Domain(1)[0], tol)) { if (surf->IsSingular(0)) return 0; } else if (NEAR_EQUAL(v, surf->Domain(1)[1], tol)) { if (surf->IsSingular(2)) return 2; } return -1; } int IsAtSingularity(const ON_Surface *surf, const ON_2dPoint &pt, double tol) { int rc = 0; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol); rc = IsAtSingularity(surf,unwrapped_pt.x,unwrapped_pt.y,tol); return rc; } ON_2dPointArray * pullback_samples(PBCData* data, double t, double s) { if (!data) return NULL; const ON_Curve* curve = data->curve; const ON_Surface* surf = data->surf; ON_2dPointArray *samples = new ON_2dPointArray(); int numKnots = curve->SpanCount(); double *knots = new double[numKnots + 1]; curve->GetSpanVector(knots); int istart = 0; while (t >= knots[istart]) istart++; if (istart > 0) { istart--; knots[istart] = t; } int istop = numKnots; while (s <= knots[istop]) istop--; if (istop < numKnots) { istop++; knots[istop] = s; } int samplesperknotinterval; int degree = curve->Degree(); if (degree > 1) { samplesperknotinterval = 3 * degree; } else { samplesperknotinterval = 18 * degree; } ON_2dPoint pt; ON_3dPoint p = ON_3dPoint::UnsetPoint; ON_3dPoint p3d = ON_3dPoint::UnsetPoint; double distance; for (int i = istart; i <= istop; i++) { if (i <= numKnots / 2) { if (i > 0) { double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval; for (int j = 1; j < samplesperknotinterval; j++) { p = curve->PointAt(knots[i - 1] + j * delta); p3d = ON_3dPoint::UnsetPoint; if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { samples->Append(pt); } } } p = curve->PointAt(knots[i]); p3d = ON_3dPoint::UnsetPoint; if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { samples->Append(pt); } } else { if (i > 0) { double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval; for (int j = 1; j < samplesperknotinterval; j++) { p = curve->PointAt(knots[i - 1] + j * delta); p3d = ON_3dPoint::UnsetPoint; if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { samples->Append(pt); } } p = curve->PointAt(knots[i]); p3d = ON_3dPoint::UnsetPoint; if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { samples->Append(pt); } } } } delete[] knots; return samples; } /* * Unwrap 2D UV point values to within actual surface UV. Points often wrap around the closed seam. */ ON_2dPoint UnwrapUVPoint(const ON_Surface *surf,const ON_2dPoint &pt, double tol) { ON_2dPoint p = pt; for (int i=0; i<2; i++) { if (!surf->IsClosed(i)) continue; while (p[i] < surf->Domain(i).m_t[0] - tol) { double length = surf->Domain(i).Length(); if (i<=0) { p.x = p.x + length; } else { p.y = p.y + length; } } while (p[i] >= surf->Domain(i).m_t[1] + tol) { double length = surf->Domain(i).Length(); if (i<=0) { p.x = p.x - length; } else { p.y = p.y - length; } } } return p; } double DistToNearestClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt) { double dist = -1.0; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt); for (int i=0; i<2; i++) { if (!surf->IsClosed(i)) continue; dist = fabs(unwrapped_pt[i] - surf->Domain(i)[0]); V_MIN(dist,fabs(surf->Domain(i)[1]-unwrapped_pt[i])); } return dist; } void GetClosestExtendedPoint(const ON_Surface *surf,ON_2dPoint &pt,ON_2dPoint &prev_pt, double tol) { if (surf->IsClosed(0)) { double length = surf->Domain(0).Length(); double delta=pt.x-prev_pt.x; while (fabs(delta) > length/2.0) { if (delta > length/2.0) { pt.x = pt.x - length; delta=pt.x-prev_pt.x; } else { pt.x = pt.x + length; delta=pt.x - prev_pt.x; } } } if (surf->IsClosed(1)) { double length = surf->Domain(1).Length(); double delta=pt.y-prev_pt.y; while (fabs(delta) > length/2.0) { if (delta > length/2.0) { pt.y = pt.y - length; delta=pt.y - prev_pt.y; } else { pt.y = pt.y + length; delta=pt.y -prev_pt.y; } } } } /* * Simple check to determine if two consecutive points pulled back from 3d curve sampling * to 2d UV parameter space crosses the seam of the closed UV. The assumption here is that * the sampling of the 3d curve is a small fraction of the UV domain. * * // dir - 0 = not crossing, 1 = south/east bound, 2 = north/west bound */ bool ConsecutivePointsCrossClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt,const ON_2dPoint &prev_pt, int &udir, int &vdir, double tol) { bool rc = false; /* * if one of the points is at a seam then not crossing */ int dir =0; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt); ON_2dPoint unwrapped_prev_pt = UnwrapUVPoint(surf,prev_pt); if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) { udir = vdir = 0; if (surf->IsClosed(0)) { double delta=unwrapped_pt.x-unwrapped_prev_pt.x; if (fabs(delta) > surf->Domain(0).Length()/2.0) { if (delta < 0.0) { udir = 1; // east bound } else { udir= 2; // west bound } rc = true; } } } dir = 1; if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) { if (surf->IsClosed(1)) { double delta=unwrapped_pt.y-unwrapped_prev_pt.y; if (fabs(delta) > surf->Domain(1).Length()/2.0) { if (delta < 0.0) { vdir = 2; // north bound } else { vdir= 1; // south bound } rc = true; } } } return rc; } /* * If within UV tolerance to a seam force force to actually seam value so surface * seam function can be used. */ void ForceToClosestSeam(const ON_Surface *surf, ON_2dPoint &pt, double tol) { int seam; ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol); ON_2dVector wrap = ON_2dVector::ZeroVector; ON_Interval dom[2] = { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }; double length[2] = { ON_UNSET_VALUE, ON_UNSET_VALUE}; for (int i=0; i<2; i++) { dom[i] = surf->Domain(i); length[i] = dom[i].Length(); if (!surf->IsClosed(i)) continue; if (pt[i] > (dom[i].m_t[1] + tol)) { ON_2dPoint p = pt; while (p[i] > (dom[i].m_t[1] + tol)) { p[i] -= length[i]; wrap[i] += 1.0; } } else if (pt[i] < (dom[i].m_t[0] - tol)) { ON_2dPoint p = pt; while (p[i] < (dom[i].m_t[0] - tol)) { p[i] += length[i]; wrap[i] -= 1.0; } } wrap[i] = wrap[i] * length[i]; } if ((seam=IsAtSeam(surf, unwrapped_pt, tol)) > 0) { if (seam == 1) { // east/west seam if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) { unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam } else { unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam } } else if (seam == 2) { // north/south seam if (fabs(unwrapped_pt.y - dom[1].m_t[0]) < length[1]/2.0) { unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam } else { unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam } } else { //on both seams if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) { unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam } else { unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam } if (fabs(pt.y - dom[1].m_t[0]) < length[1]/2.0) { unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam } else { unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam } } } pt = unwrapped_pt + wrap; } /* * If point lies on a seam(s) swap to opposite side of UV. * hint = 1 swap E/W, 2 swap N/S or default 3 swap both */ void SwapUVSeamPoint(const ON_Surface *surf, ON_2dPoint &p, int hint) { int seam; ON_Interval dom[2]; dom[0] = surf->Domain(0); dom[1] = surf->Domain(1); if ((seam=surf->IsAtSeam(p.x,p.y)) > 0) { if (seam == 1) { // east/west seam if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) { p.x = dom[0].m_t[0]; // on east swap to west seam } else { p.x = dom[0].m_t[1]; // on west swap to east seam } } else if (seam == 2) { // north/south seam if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) { p.y = dom[1].m_t[0]; // on north swap to south seam } else { p.y = dom[1].m_t[1]; // on south swap to north seam } } else { //on both seams check hint 1=east/west only, 2=north/south, 3 = both if (hint == 1) { if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) { p.x = dom[0].m_t[0]; // on east swap to west seam } else { p.x = dom[0].m_t[1]; // on west swap to east seam } } else if (hint == 2) { if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) { p.y = dom[1].m_t[0]; // on north swap to south seam } else { p.y = dom[1].m_t[1]; // on south swap to north seam } } else { if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) { p.x = dom[0].m_t[0]; // on east swap to west seam } else { p.x = dom[0].m_t[1]; // on west swap to east seam } if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) { p.y = dom[1].m_t[0]; // on north swap to south seam } else { p.y = dom[1].m_t[1]; // on south swap to north seam } } } } } /* * Find where Pullback of 3d curve crosses closed seam of surface UV */ bool Find3DCurveSeamCrossing(PBCData &data,double t0,double t1, double offset,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol) { bool rc = true; const ON_Surface *surf = data.surf; // quick bail out is surface not closed if (surf->IsClosed(0) || surf->IsClosed(1)) { ON_2dPoint p0_2d = ON_2dPoint::UnsetPoint; ON_2dPoint p1_2d = ON_2dPoint::UnsetPoint; ON_3dPoint p0_3d = data.curve->PointAt(t0); ON_3dPoint p1_3d = data.curve->PointAt(t1); ON_Interval dom[2]; double p0_distance; double p1_distance; dom[0] = surf->Domain(0); dom[1] = surf->Domain(1); ON_3dPoint check_pt_3d = ON_3dPoint::UnsetPoint; int udir=0; int vdir=0; if (surface_GetClosestPoint3dFirstOrder(surf,p0_3d,p0_2d,check_pt_3d,p0_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) && surface_GetClosestPoint3dFirstOrder(surf,p1_3d,p1_2d,check_pt_3d,p1_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) ) { if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p1_2d,udir,vdir,tol)) { ON_2dPoint p_2d; //lets check to see if p0 || p1 are already on a seam int seam0=0; if ((seam0 = IsAtSeam(surf,p0_2d, tol)) > 0) { ForceToClosestSeam(surf, p0_2d, tol); } int seam1 = 0; if ((seam1 = IsAtSeam(surf,p1_2d, tol)) > 0) { ForceToClosestSeam(surf, p1_2d, tol); } if (seam0 > 0 ) { if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false rc = false; } else { // just p0 on seam from = to = p0_2d; seam_t = t0; SwapUVSeamPoint(surf, to); } } else if (seam1 > 0) { // only p1 on seam from = to = p1_2d; seam_t = t1; SwapUVSeamPoint(surf, from); } else { // crosses the seam somewhere in between the two points bool seam_not_found = true; while(seam_not_found) { double d0 = DistToNearestClosedSeam(surf,p0_2d); double d1 = DistToNearestClosedSeam(surf,p1_2d); if ((d0 > 0.0) && (d1 > 0.0)) { double t = t0 + (t1 - t0)*(d0/(d0+d1)); int seam; ON_3dPoint p_3d = data.curve->PointAt(t); double distance; if (surface_GetClosestPoint3dFirstOrder(surf,p_3d,p_2d,check_pt_3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { if ((seam=IsAtSeam(surf,p_2d, tol)) > 0) { ForceToClosestSeam(surf, p_2d, tol); from = to = p_2d; seam_t = t; if (p0_2d.DistanceTo(p_2d) < p1_2d.DistanceTo(p_2d)) { SwapUVSeamPoint(surf, to); } else { SwapUVSeamPoint(surf, from); } seam_not_found=false; rc = true; } else { if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p_2d,udir,vdir,tol)) { p1_2d = p_2d; t1 = t; } else if (ConsecutivePointsCrossClosedSeam(surf,p_2d,p1_2d,udir,vdir,tol)) { p0_2d = p_2d; t0=t; } else { seam_not_found=false; rc = false; } } } else { seam_not_found=false; rc = false; } } else { seam_not_found=false; rc = false; } } } } } } return rc; } /* * Find where 2D trim curve crosses closed seam of surface UV */ bool FindTrimSeamCrossing(const ON_BrepTrim &trim,double t0,double t1,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol) { bool rc = true; const ON_Surface *surf = trim.SurfaceOf(); // quick bail out is surface not closed if (surf->IsClosed(0) || surf->IsClosed(1)) { ON_2dPoint p0 = trim.PointAt(t0); ON_2dPoint p1 = trim.PointAt(t1); ON_Interval dom[2]; dom[0] = surf->Domain(0); dom[1] = surf->Domain(1); p0 = UnwrapUVPoint(surf,p0); p1 = UnwrapUVPoint(surf,p1); int udir=0; int vdir=0; if (ConsecutivePointsCrossClosedSeam(surf,p0,p1,udir,vdir,tol)) { ON_2dPoint p; //lets check to see if p0 || p1 are already on a seam int seam0=0; if ((seam0 = IsAtSeam(surf,p0, tol)) > 0) { ForceToClosestSeam(surf, p0, tol); } int seam1 = 0; if ((seam1 = IsAtSeam(surf,p1, tol)) > 0) { ForceToClosestSeam(surf, p1, tol); } if (seam0 > 0 ) { if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false rc = false; } else { // just p0 on seam from = to = p0; seam_t = t0; SwapUVSeamPoint(surf, to); } } else if (seam1 > 0) { // only p1 on seam from = to = p1; seam_t = t1; SwapUVSeamPoint(surf, from); } else { // crosses the seam somewhere in between the two points bool seam_not_found = true; while (seam_not_found) { double d0 = DistToNearestClosedSeam(surf,p0); double d1 = DistToNearestClosedSeam(surf,p1); if ((d0 > tol) && (d1 > tol)) { double t = t0 + (t1 - t0)*(d0/(d0+d1)); int seam; p = trim.PointAt(t); if ((seam=IsAtSeam(surf,p, tol)) > 0) { ForceToClosestSeam(surf, p, tol); from = to = p; seam_t = t; if (p0.DistanceTo(p) < p1.DistanceTo(p)) { SwapUVSeamPoint(surf, to); } else { SwapUVSeamPoint(surf, from); } seam_not_found=false; rc = true; } else { if (ConsecutivePointsCrossClosedSeam(surf,p0,p,udir,vdir,tol)) { p1 = p; t1 = t; } else if (ConsecutivePointsCrossClosedSeam(surf,p,p1,udir,vdir,tol)) { p0 = p; t0=t; } else { seam_not_found=false; rc = false; } } } else { seam_not_found=false; rc = false; } } } } } return rc; } void pullback_samples_from_closed_surface(PBCData* data, double t, double s) { if (!data) return; if (!data->surf || !data->curve) return; const ON_Curve* curve= data->curve; const ON_Surface *surf = data->surf; ON_2dPointArray *samples= new ON_2dPointArray(); size_t numKnots = curve->SpanCount(); double *knots = new double[numKnots+1]; curve->GetSpanVector(knots); size_t istart = 0; while ((istart < (numKnots+1)) && (t >= knots[istart])) istart++; if (istart > 0) { knots[--istart] = t; } size_t istop = numKnots; while ((istop > 0) && (s <= knots[istop])) istop--; if (istop < numKnots) { knots[++istop] = s; } size_t degree = curve->Degree(); size_t samplesperknotinterval=18*degree; ON_2dPoint pt; ON_2dPoint prev_pt; double prev_t = knots[istart]; double offset = 0.0; double delta; for (size_t i=istart; i<istop; i++) { delta = (knots[i+1] - knots[i])/(double)samplesperknotinterval; if (i <= numKnots/2) { offset = PBC_FROM_OFFSET; } else { offset = -PBC_FROM_OFFSET; } for (size_t j=0; j<=samplesperknotinterval; j++) { if ((j == samplesperknotinterval) && (i < istop - 1)) continue; double curr_t = knots[i]+j*delta; if (curr_t < (s-t)/2.0) { offset = PBC_FROM_OFFSET; } else { offset = -PBC_FROM_OFFSET; } ON_3dPoint p = curve->PointAt(curr_t); ON_3dPoint p3d = ON_3dPoint::UnsetPoint; double distance; if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { if (IsAtSeam(surf,pt,PBC_SEAM_TOL) > 0) { ForceToClosestSeam(surf, pt, PBC_SEAM_TOL); } if ((i == istart) && (j == 0)) { // first point just append and set reference in prev_pt samples->Append(pt); prev_pt = pt; prev_t = curr_t; continue; } int udir= 0; int vdir= 0; if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) { int pt_seam = surf->IsAtSeam(pt.x,pt.y); int prev_pt_seam = surf->IsAtSeam(prev_pt.x,prev_pt.y); if ( pt_seam > 0) { if ((prev_pt_seam > 0) && (samples->Count() == 1)) { samples->Empty(); SwapUVSeamPoint(surf, prev_pt,pt_seam); samples->Append(prev_pt); } else { if (pt_seam == 3) { if (prev_pt_seam == 1) { pt.x = prev_pt.x; if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) { SwapUVSeamPoint(surf, pt, 2); } } else if (prev_pt_seam == 2) { pt.y = prev_pt.y; if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) { SwapUVSeamPoint(surf, pt, 1); } } } else { SwapUVSeamPoint(surf, pt, prev_pt_seam); } } } else if (prev_pt_seam > 0) { if (samples->Count() == 1) { samples->Empty(); SwapUVSeamPoint(surf, prev_pt); samples->Append(prev_pt); } } else if (data->curve->IsClosed()) { ON_2dPoint from,to; double seam_t; if (Find3DCurveSeamCrossing(*data,prev_t,curr_t,offset,seam_t,from,to,PBC_TOL)) { samples->Append(from); data->segments.push_back(samples); samples= new ON_2dPointArray(); samples->Append(to); prev_pt = to; prev_t = seam_t; } else { std::cout << "Can not find seam crossing...." << std::endl; } } } samples->Append(pt); prev_pt = pt; prev_t = curr_t; } } } delete [] knots; if (samples != NULL) { data->segments.push_back(samples); int numsegs = data->segments.size(); if (numsegs > 1) { if (curve->IsClosed()) { ON_2dPointArray *reordered_samples= new ON_2dPointArray(); // must have walked over seam but have closed curve so reorder stitching int seg = 0; for (std::list<ON_2dPointArray *>::reverse_iterator rit=data->segments.rbegin(); rit!=data->segments.rend(); ++seg) { samples = *rit; if (seg < numsegs-1) { // since end points should be repeated reordered_samples->Append(samples->Count()-1,(const ON_2dPoint *)samples->Array()); } else { reordered_samples->Append(samples->Count(),(const ON_2dPoint *)samples->Array()); } data->segments.erase((++rit).base()); rit = data->segments.rbegin(); delete samples; } data->segments.clear(); data->segments.push_back(reordered_samples); } else { //punt for now } } } return; } PBCData * pullback_samples(const ON_Surface* surf, const ON_Curve* curve, double tolerance, double flatness) { if (!surf) return NULL; PBCData *data = new PBCData; data->tolerance = tolerance; data->flatness = flatness; data->curve = curve; data->surf = surf; data->surftree = NULL; double tmin, tmax; data->curve->GetDomain(&tmin, &tmax); if (surf->IsClosed(0) || surf->IsClosed(1)) { if ((tmin < 0.0) && (tmax > 0.0)) { ON_2dPoint uv = ON_2dPoint::UnsetPoint; ON_3dPoint p = curve->PointAt(0.0); ON_3dPoint p3d = ON_3dPoint::UnsetPoint; double distance; int quadrant = 0; // optional - 0 = default, 1 from NE quadrant, 2 from NW quadrant, 3 from SW quadrant, 4 from SE quadrant if (surface_GetClosestPoint3dFirstOrder(surf,p,uv,p3d,distance,quadrant,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) { if (IsAtSeam(surf, uv, PBC_SEAM_TOL) > 0) { ON_2dPointArray *samples1 = pullback_samples(data, tmin, 0.0); ON_2dPointArray *samples2 = pullback_samples(data, 0.0, tmax); if (samples1 != NULL) { data->segments.push_back(samples1); } if (samples2 != NULL) { data->segments.push_back(samples2); } } else { ON_2dPointArray *samples = pullback_samples(data, tmin, tmax); if (samples != NULL) { data->segments.push_back(samples); } } } else { std::cerr << "pullback_samples:Error: cannot evaluate curve at parameter 0.0" << std::endl; delete data; return NULL; } } else { pullback_samples_from_closed_surface(data, tmin, tmax); } } else { ON_2dPointArray *samples = pullback_samples(data, tmin, tmax); if (samples != NULL) { data->segments.push_back(samples); } } return data; } ON_Curve* refit_edge(const ON_BrepEdge* edge, double UNUSED(tolerance)) { double edge_tolerance = 0.01; ON_Brep *brep = edge->Brep(); #ifdef SHOW_UNUSED ON_3dPoint start = edge->PointAtStart(); ON_3dPoint end = edge->PointAtEnd(); #endif ON_BrepTrim& trim1 = brep->m_T[edge->m_ti[0]]; ON_BrepTrim& trim2 = brep->m_T[edge->m_ti[1]]; ON_BrepFace *face1 = trim1.Face(); ON_BrepFace *face2 = trim2.Face(); const ON_Surface *surface1 = face1->SurfaceOf(); const ON_Surface *surface2 = face2->SurfaceOf(); bool removeTrimmed = false; brlcad::SurfaceTree *st1 = new brlcad::SurfaceTree(face1, removeTrimmed); brlcad::SurfaceTree *st2 = new brlcad::SurfaceTree(face2, removeTrimmed); ON_Curve *curve = brep->m_C3[edge->m_c3i]; double t0, t1; curve->GetDomain(&t0, &t1); ON_Plane plane; curve->FrameAt(t0, plane); #ifdef SHOW_UNUSED ON_3dPoint origin = plane.Origin(); ON_3dVector xaxis = plane.Xaxis(); ON_3dVector yaxis = plane.Yaxis(); ON_3dVector zaxis = plane.zaxis; ON_3dPoint px = origin + xaxis; ON_3dPoint py = origin + yaxis; ON_3dPoint pz = origin + zaxis; #endif int numKnots = curve->SpanCount(); double *knots = new double[numKnots + 1]; curve->GetSpanVector(knots); int samplesperknotinterval; int degree = curve->Degree(); if (degree > 1) { samplesperknotinterval = 3 * degree; } else { samplesperknotinterval = 18 * degree; } ON_2dPoint pt; double t = 0.0; ON_3dPoint pointOnCurve; ON_3dPoint knudgedPointOnCurve; for (int i = 0; i <= numKnots; i++) { if (i <= numKnots / 2) { if (i > 0) { double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval; for (int j = 1; j < samplesperknotinterval; j++) { t = knots[i - 1] + j * delta; pointOnCurve = curve->PointAt(t); knudgedPointOnCurve = curve->PointAt(t + PBC_TOL); ON_3dPoint point = pointOnCurve; ON_3dPoint knudgepoint = knudgedPointOnCurve; ON_3dPoint ps1; ON_3dPoint ps2; bool found = false; double dist; while (!found) { ON_2dPoint uv; if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps1 = surface1->PointAt(uv.x, uv.y); if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps2 = surface2->PointAt(uv.x, uv.y); } } dist = ps1.DistanceTo(ps2); if (NEAR_ZERO(dist, PBC_TOL)) { point = ps1; found = true; } else { ON_3dVector v1 = ps1 - point; ON_3dVector v2 = ps2 - point; knudgepoint = point; ON_3dVector deltav = v1 + v2; if (NEAR_ZERO(deltav.Length(), PBC_TOL)) { found = true; // as close as we are going to get } else { point = point + v1 + v2; } } } } } t = knots[i]; pointOnCurve = curve->PointAt(t); knudgedPointOnCurve = curve->PointAt(t + PBC_TOL); ON_3dPoint point = pointOnCurve; ON_3dPoint knudgepoint = knudgedPointOnCurve; ON_3dPoint ps1; ON_3dPoint ps2; bool found = false; double dist; while (!found) { ON_2dPoint uv; if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps1 = surface1->PointAt(uv.x, uv.y); if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps2 = surface2->PointAt(uv.x, uv.y); } } dist = ps1.DistanceTo(ps2); if (NEAR_ZERO(dist, PBC_TOL)) { point = ps1; found = true; } else { ON_3dVector v1 = ps1 - point; ON_3dVector v2 = ps2 - point; knudgepoint = point; ON_3dVector deltav = v1 + v2; if (NEAR_ZERO(deltav.Length(), PBC_TOL)) { found = true; // as close as we are going to get } else { point = point + v1 + v2; } } } } else { if (i > 0) { double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval; for (int j = 1; j < samplesperknotinterval; j++) { t = knots[i - 1] + j * delta; pointOnCurve = curve->PointAt(t); knudgedPointOnCurve = curve->PointAt(t - PBC_TOL); ON_3dPoint point = pointOnCurve; ON_3dPoint knudgepoint = knudgedPointOnCurve; ON_3dPoint ps1; ON_3dPoint ps2; bool found = false; double dist; while (!found) { ON_2dPoint uv; if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps1 = surface1->PointAt(uv.x, uv.y); if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps2 = surface2->PointAt(uv.x, uv.y); } } dist = ps1.DistanceTo(ps2); if (NEAR_ZERO(dist, PBC_TOL)) { point = ps1; found = true; } else { ON_3dVector v1 = ps1 - point; ON_3dVector v2 = ps2 - point; knudgepoint = point; ON_3dVector deltav = v1 + v2; if (NEAR_ZERO(deltav.Length(), PBC_TOL)) { found = true; // as close as we are going to get } else { point = point + v1 + v2; } } } } t = knots[i]; pointOnCurve = curve->PointAt(t); knudgedPointOnCurve = curve->PointAt(t - PBC_TOL); ON_3dPoint point = pointOnCurve; ON_3dPoint knudgepoint = knudgedPointOnCurve; ON_3dPoint ps1; ON_3dPoint ps2; bool found = false; double dist; while (!found) { ON_2dPoint uv; if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps1 = surface1->PointAt(uv.x, uv.y); if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) { ps2 = surface2->PointAt(uv.x, uv.y); } } dist = ps1.DistanceTo(ps2); if (NEAR_ZERO(dist, PBC_TOL)) { point = ps1; found = true; } else { ON_3dVector v1 = ps1 - point; ON_3dVector v2 = ps2 - point; knudgepoint = point; ON_3dVector deltav = v1 + v2; if (NEAR_ZERO(deltav.Length(), PBC_TOL)) { found = true; // as close as we are going to get } else { point = point + v1 + v2; } } } } } } delete [] knots; return NULL; } bool has_singularity(const ON_Surface *surf) { bool ret = false; if (UNLIKELY(!surf)) return ret; // 0 = south, 1 = east, 2 = north, 3 = west for (int i = 0; i < 4; i++) { if (surf->IsSingular(i)) { /* switch (i) { case 0: std::cout << "Singular South" << std::endl; break; case 1: std::cout << "Singular East" << std::endl; break; case 2: std::cout << "Singular North" << std::endl; break; case 3: std::cout << "Singular West" << std::endl; } */ ret = true; } } return ret; } bool is_closed(const ON_Surface *surf) { bool ret = false; if (UNLIKELY(!surf)) return ret; // dir 0 = "s", 1 = "t" for (int i = 0; i < 2; i++) { if (surf->IsClosed(i)) { // switch (i) { // case 0: // std::cout << "Closed in U" << std::endl; // break; // case 1: // std::cout << "Closed in V" << std::endl; // } ret = true; } } return ret; } bool check_pullback_closed(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator d = pbcs.begin(); if ((*d) == NULL || (*d)->surf == NULL) return false; const ON_Surface *surf = (*d)->surf; //TODO: // 0 = U, 1 = V if (surf->IsClosed(0) && surf->IsClosed(1)) { //TODO: need to check how torus UV looks to determine checks std::cerr << "Is this some kind of torus????" << std::endl; } else if (surf->IsClosed(0)) { //check_pullback_closed_U(pbcs); std::cout << "check closed in U" << std::endl; } else if (surf->IsClosed(1)) { //check_pullback_closed_V(pbcs); std::cout << "check closed in V" << std::endl; } return true; } bool check_pullback_singular_east(std::list<PBCData*> &pbcs) { std::list<PBCData *>::iterator cs = pbcs.begin(); if ((*cs) == NULL || (*cs)->surf == NULL) return false; const ON_Surface *surf = (*cs)->surf; double umin, umax; ON_2dPoint *prev = NULL; surf->GetDomain(0, &umin, &umax); std::cout << "Umax: " << umax << std::endl; while (cs != pbcs.end()) { PBCData *data = (*cs); std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); int segcnt = 0; while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); std::cerr << std::endl << "Segment:" << ++segcnt << std::endl; if (true) { int ilast = samples->Count() - 1; std::cerr << std::endl << 0 << "- " << (*samples)[0].x << ", " << (*samples)[0].y << std::endl; std::cerr << ilast << "- " << (*samples)[ilast].x << ", " << (*samples)[ilast].y << std::endl; } else { for (int i = 0; i < samples->Count(); i++) { if (NEAR_EQUAL((*samples)[i].x, umax, PBC_TOL)) { if (prev != NULL) { std::cerr << "prev - " << prev->x << ", " << prev->y << std::endl; } std::cerr << i << "- " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl << std::endl; } prev = &(*samples)[i]; } } si ++; } cs++; } return true; } bool check_pullback_singular(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator d = pbcs.begin(); if ((*d) == NULL || (*d)->surf == NULL) return false; const ON_Surface *surf = (*d)->surf; int cnt = 0; for (int i = 0; i < 4; i++) { if (surf->IsSingular(i)) { cnt++; } } if (cnt > 2) { //TODO: I don't think this makes sense but check out std::cerr << "Is this some kind of sickness????" << std::endl; return false; } else if (cnt == 2) { if (surf->IsSingular(0) && surf->IsSingular(2)) { std::cout << "check singular North-South" << std::endl; } else if (surf->IsSingular(1) && surf->IsSingular(2)) { std::cout << "check singular East-West" << std::endl; } else { //TODO: I don't think this makes sense but check out std::cerr << "Is this some kind of sickness????" << std::endl; return false; } } else { if (surf->IsSingular(0)) { std::cout << "check singular South" << std::endl; } else if (surf->IsSingular(1)) { std::cout << "check singular East" << std::endl; if (check_pullback_singular_east(pbcs)) { return true; } } else if (surf->IsSingular(2)) { std::cout << "check singular North" << std::endl; } else if (surf->IsSingular(3)) { std::cout << "check singular West" << std::endl; } } return true; } #ifdef _DEBUG_TESTING_ void print_pullback_data(std::string str, std::list<PBCData*> &pbcs, bool justendpoints) { std::list<PBCData*>::iterator cs = pbcs.begin(); int trimcnt = 0; if (justendpoints) { // print out endpoints before std::cerr << "EndPoints " << str << ":" << std::endl; while (cs != pbcs.end()) { PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); int segcnt = 0; while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); std::cerr << std::endl << " Segment:" << ++segcnt << std::endl; int ilast = samples->Count() - 1; std::cerr << " T:" << ++trimcnt << std::endl; int i = 0; int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL); int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL); std::cerr << "--------"; if ((seam > 0) && (singularity >= 0)) { std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y; } else if (seam > 0) { std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y; } else if (singularity >= 0) { std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y; } else { std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y; } ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y); std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl; i = ilast; singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL); seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL); std::cerr << " "; if ((seam > 0) && (singularity >= 0)) { std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl; } else if (seam > 0) { std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl; } else if (singularity >= 0) { std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl; } else { std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl; } p = surf->PointAt((*samples)[i].x, (*samples)[i].y); std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl; si++; } cs++; } } else { // print out all points trimcnt = 0; cs = pbcs.begin(); std::cerr << str << ":" << std::endl; while (cs != pbcs.end()) { PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); int segcnt = 0; std::cerr << "2d surface domain: " << std::endl; std::cerr << "in rpp rpp" << surf->Domain(0).m_t[0] << " " << surf->Domain(0).m_t[1] << " " << surf->Domain(1).m_t[0] << " " << surf->Domain(1).m_t[1] << " 0.0 0.01" << std::endl; while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); std::cerr << std::endl << " Segment:" << ++segcnt << std::endl; std::cerr << " T:" << ++trimcnt << std::endl; for (int i = 0; i < samples->Count(); i++) { int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL); int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL); if (_debug_print_mged2d_points_) { std::cerr << "in pt_" << _debug_point_count_++ << " sph " << (*samples)[i].x << " " << (*samples)[i].y << " 0.0 0.1000" << std::endl; } else if (_debug_print_mged3d_points_) { ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y); std::cerr << "in pt_" << _debug_point_count_++ << " sph " << p.x << " " << p.y << " " << p.z << " 0.1000" << std::endl; } else { if (i == 0) { std::cerr << "--------"; } else { std::cerr << " "; } if ((seam > 0) && (singularity >= 0)) { std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y; } else if (seam > 0) { std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y; } else if (singularity >= 0) { std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y; } else { std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y; } ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y); std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl; } } si++; } cs++; } } ///// } #endif bool resolve_seam_segment_from_prev(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *prev = NULL) { bool complete = false; double umin, umax, umid; double vmin, vmax, vmid; surface->GetDomain(0, &umin, &umax); surface->GetDomain(1, &vmin, &vmax); umid = (umin + umax) / 2.0; vmid = (vmin + vmax) / 2.0; for (int i = 0; i < segment.Count(); i++) { int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL); int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL); if ((seam > 0)) { if (prev != NULL) { //std::cerr << " at seam " << seam << " but has prev" << std::endl; //std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; switch (seam) { case 1: //east/west if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } break; case 2: //north/south if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } break; case 3: //both if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } } prev = &segment[i]; } else { //std::cerr << " at seam and no prev" << std::endl; complete = false; } } else { if (singularity < 0) { prev = &segment[i]; } else { prev = NULL; } } } return complete; } bool resolve_seam_segment_from_next(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *next = NULL) { bool complete = false; double umin, umax, umid; double vmin, vmax, vmid; surface->GetDomain(0, &umin, &umax); surface->GetDomain(1, &vmin, &vmax); umid = (umin + umax) / 2.0; vmid = (vmin + vmax) / 2.0; if (next != NULL) { complete = true; for (int i = segment.Count() - 1; i >= 0; i--) { int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL); int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL); if ((seam > 0)) { if (next != NULL) { switch (seam) { case 1: //east/west if (next->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } break; case 2: //north/south if (next->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } break; case 3: //both if (next->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } if (next->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } } next = &segment[i]; } else { //std::cerr << " at seam and no prev" << std::endl; complete = false; } } else { if (singularity < 0) { next = &segment[i]; } else { next = NULL; } } } } return complete; } bool resolve_seam_segment(const ON_Surface *surface, ON_2dPointArray &segment, bool &u_resolved, bool &v_resolved) { ON_2dPoint *prev = NULL; bool complete = false; double umin, umax, umid; double vmin, vmax, vmid; int prev_seam = 0; surface->GetDomain(0, &umin, &umax); surface->GetDomain(1, &vmin, &vmax); umid = (umin + umax) / 2.0; vmid = (vmin + vmax) / 2.0; for (int i = 0; i < segment.Count(); i++) { int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL); int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL); if ((seam > 0)) { if (prev != NULL) { //std::cerr << " at seam " << seam << " but has prev" << std::endl; //std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; switch (seam) { case 1: //east/west if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } break; case 2: //north/south if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } break; case 3: //both if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } } prev = &segment[i]; } else { //std::cerr << " at seam and no prev" << std::endl; complete = false; } prev_seam = seam; } else { if (singularity < 0) { prev = &segment[i]; prev_seam = 0; } else { prev = NULL; } } } prev_seam = 0; if ((!complete) && (prev != NULL)) { complete = true; for (int i = segment.Count() - 2; i >= 0; i--) { int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL); int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL); if ((seam > 0)) { if (prev != NULL) { //std::cerr << " at seam " << seam << " but has prev" << std::endl; //std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; switch (seam) { case 1: //east/west if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } break; case 2: //north/south if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } break; case 3: //both if (prev->x < umid) { segment[i].x = umin; } else { segment[i].x = umax; } if (prev->y < vmid) { segment[i].y = vmin; } else { segment[i].y = vmax; } } prev = &segment[i]; } else { //std::cerr << " at seam and no prev" << std::endl; complete = false; } } else { if (singularity < 0) { prev = &segment[i]; } else { prev = NULL; } } } } return complete; } /* * number_of_seam_crossings */ int number_of_seam_crossings(std::list<PBCData*> &pbcs) { int rc = 0; std::list<PBCData*>::iterator cs; cs = pbcs.begin(); while (cs != pbcs.end()) { PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); ON_2dPoint *pt = NULL; ON_2dPoint *prev_pt = NULL; ON_2dPoint *next_pt = NULL; while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); for (int i = 0; i < samples->Count(); i++) { pt = &(*samples)[i]; if (!IsAtSeam(surf,*pt,PBC_SEAM_TOL)) { if (prev_pt == NULL) { prev_pt = pt; } else { next_pt = pt; } int udir=0; int vdir=0; if (next_pt != NULL) { if (ConsecutivePointsCrossClosedSeam(surf,*prev_pt,*next_pt,udir,vdir,PBC_SEAM_TOL)) { rc++; } prev_pt = next_pt; next_pt = NULL; } } } if (si != data->segments.end()) si++; } if (cs != pbcs.end()) cs++; } return rc; } /* * if current and previous point on seam make sure they are on same seam */ bool check_for_points_on_same_seam(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator cs = pbcs.begin(); ON_2dPoint *prev_pt = NULL; int prev_seam = 0; while ( cs != pbcs.end()) { PBCData *data = (*cs); const ON_Surface *surf = data->surf; std::list<ON_2dPointArray *>::iterator seg = data->segments.begin(); while (seg != data->segments.end()) { ON_2dPointArray *points = (*seg); for (int i=0; i < points->Count(); i++) { ON_2dPoint *pt = points->At(i); int seam = IsAtSeam(surf,*pt,PBC_SEAM_TOL); if (seam > 0) { if (prev_seam > 0) { if ((seam == 1) && ((prev_seam % 2) == 1)) { pt->x = prev_pt->x; } else if ((seam == 2) && (prev_seam > 1)) { pt->y = prev_pt->y; } else if (seam == 3) { if ((prev_seam % 2) == 1) { pt->x = prev_pt->x; } if (prev_seam > 1) { pt->y = prev_pt->y; } } } prev_seam = seam; prev_pt = pt; } } seg++; } cs++; } return true; } /* * extend_pullback_at_shared_3D_curve_seam */ bool extend_pullback_at_shared_3D_curve_seam(std::list<PBCData*> &pbcs) { const ON_Curve *next_curve = NULL; std::set<const ON_Curve *> set; std::map<const ON_Curve *,int> map; std::list<PBCData*>::iterator cs = pbcs.begin(); while ( cs != pbcs.end()) { PBCData *data = (*cs++); const ON_Curve *curve = data->curve; const ON_Surface *surf = data->surf; if (cs != pbcs.end()) { PBCData *nextdata = (*cs); next_curve = nextdata->curve; } if (curve == next_curve) { std::cerr << "Consecutive seam usage" << std::endl; //find which direction we need to extend if (surf->IsClosed(0) && !surf->IsClosed(1)) { double length = surf->Domain(0).Length(); std::list<ON_2dPointArray *>::iterator seg = data->segments.begin(); while (seg != data->segments.end()) { ON_2dPointArray *points = (*seg); for (int i=0; i < points->Count(); i++) { points->At(i)->x = points->At(i)->x + length; } seg++; } } else if (!surf->IsClosed(0) && surf->IsClosed(1)) { double length = surf->Domain(1).Length(); std::list<ON_2dPointArray *>::iterator seg = data->segments.begin(); while (seg != data->segments.end()) { ON_2dPointArray *points = (*seg); for (int i=0; i < points->Count(); i++) { points->At(i)->y = points->At(i)->y + length; } seg++; } } else { std::cerr << "both directions" << std::endl; } } next_curve = NULL; } return true; } /* * shift_closed_curve_split_over_seam */ bool shift_single_curve_loop_straddled_over_seam(std::list<PBCData*> &pbcs) { if (pbcs.size() == 1) { // single curve for this loop std::list<PBCData*>::iterator cs; PBCData *data = pbcs.front(); if (!data || !data->surf) return false; const ON_Surface *surf = data->surf; ON_Interval udom = surf->Domain(0); ON_Interval vdom = surf->Domain(1); std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); ON_2dPoint pt; ON_2dPoint prev_pt; if (data->curve->IsClosed()) { int numseamcrossings = number_of_seam_crossings(pbcs); if (numseamcrossings == 1) { ON_2dPointArray part1,part2; ON_2dPointArray* curr_point_array = &part2; while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); for (int i = 0; i < samples->Count(); i++) { pt = (*samples)[i]; if (i == 0) { prev_pt = pt; curr_point_array->Append(pt); continue; } int udir= 0; int vdir= 0; if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) { if (surf->IsAtSeam(pt.x,pt.y) > 0) { SwapUVSeamPoint(surf, pt); curr_point_array->Append(pt); curr_point_array = &part1; SwapUVSeamPoint(surf, pt); } else if (surf->IsAtSeam(prev_pt.x,prev_pt.y) > 0) { SwapUVSeamPoint(surf, prev_pt); curr_point_array->Append(prev_pt); } else { std::cerr << "shift_single_curve_loop_straddled_over_seam(): Error expecting to see seam in sample points" << std::endl; } } curr_point_array->Append(pt); prev_pt = pt; } samples->Empty(); samples->Append(part1.Count(),part1.Array()); samples->Append(part2.Count(),part2.Array()); if (si != data->segments.end()) si++; } } } } return true; } /* * extend_over_seam_crossings - all incoming points assumed to be within UV bounds */ bool extend_over_seam_crossings(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator cs; ON_2dPoint *pt = NULL; ON_2dPoint *prev_non_seam_pt = NULL; ON_2dPoint *prev_pt = NULL; ON_2dVector curr_uv_offsets = ON_2dVector::ZeroVector; ///// Loop through and fix any seam ambiguities cs = pbcs.begin(); while (cs != pbcs.end()) { PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; ON_Interval udom = surf->Domain(0); double ulength = udom.Length(); ON_Interval vdom = surf->Domain(1); double vlength = vdom.Length(); std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); for (int i = 0; i < samples->Count(); i++) { pt = &(*samples)[i]; if (prev_pt != NULL) { GetClosestExtendedPoint(surf,*pt,*prev_pt,PBC_SEAM_TOL); } prev_pt = pt; } if (si != data->segments.end()) si++; } if (cs != pbcs.end()) cs++; } return true; } /* * run through curve loop to determine correct start/end * points resolving ambiguities when point lies on a seam or * singularity */ bool resolve_pullback_seams(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator cs; ///// Loop through and fix any seam ambiguities ON_2dPoint *prev = NULL; ON_2dPoint *next = NULL; bool u_resolved = false; bool v_resolved = false; cs = pbcs.begin(); while (cs != pbcs.end()) { PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; double umin, umax; double vmin, vmax; surf->GetDomain(0, &umin, &umax); surf->GetDomain(1, &vmin, &vmax); std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); if (resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) { // Found a starting point //1) walk back up with resolved next point next = (*samples).First(); std::list<PBCData*>::reverse_iterator rcs(cs); rcs--; std::list<ON_2dPointArray *>::reverse_iterator rsi(si); while (rcs != pbcs.rend()) { PBCData *rdata = (*rcs); while (rsi != rdata->segments.rend()) { ON_2dPointArray *rsamples = (*rsi); // first try and resolve on own merits if (!resolve_seam_segment(surf, *rsamples,u_resolved,v_resolved)) { resolve_seam_segment_from_next(surf, *rsamples, next); } next = (*rsamples).First(); rsi++; } rcs++; if (rcs != pbcs.rend()) { rdata = (*rcs); rsi = rdata->segments.rbegin(); } } //2) walk rest of way down with resolved prev point if (samples->Count() > 1) prev = &(*samples)[samples->Count() - 1]; else prev = NULL; si++; std::list<PBCData*>::iterator current(cs); while (cs != pbcs.end()) { while (si != data->segments.end()) { samples = (*si); // first try and resolve on own merits if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) { resolve_seam_segment_from_prev(surf, *samples, prev); } if (samples->Count() > 1) prev = &(*samples)[samples->Count() - 1]; else prev = NULL; si++; } cs++; if (cs != pbcs.end()) { data = (*cs); si = data->segments.begin(); } } // make sure to wrap back around with previous cs = pbcs.begin(); data = (*cs); si = data->segments.begin(); while ((cs != pbcs.end()) && (cs != current)) { while (si != data->segments.end()) { samples = (*si); // first try and resolve on own merits if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) { resolve_seam_segment_from_prev(surf, *samples, prev); } if (samples->Count() > 1) prev = &(*samples)[samples->Count() - 1]; else prev = NULL; si++; } cs++; if (cs != pbcs.end()) { data = (*cs); si = data->segments.begin(); } } } if (si != data->segments.end()) si++; } if (cs != pbcs.end()) cs++; } return true; } /* * run through curve loop to determine correct start/end * points resolving ambiguities when point lies on a seam or * singularity */ bool resolve_pullback_singularities(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator cs = pbcs.begin(); ///// Loop through and fix any seam ambiguities ON_2dPoint *prev = NULL; bool complete = false; int checkcnt = 0; prev = NULL; complete = false; checkcnt = 0; while (!complete && (checkcnt < 2)) { cs = pbcs.begin(); complete = true; checkcnt++; //std::cerr << "Checkcnt - " << checkcnt << std::endl; while (cs != pbcs.end()) { int singularity; prev = NULL; PBCData *data = (*cs); if (!data || !data->surf) continue; const ON_Surface *surf = data->surf; std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); for (int i = 0; i < samples->Count(); i++) { // 0 = south, 1 = east, 2 = north, 3 = west if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) { if (prev != NULL) { //std::cerr << " at singularity " << singularity << " but has prev" << std::endl; //std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; switch (singularity) { case 0: //south (*samples)[i].x = prev->x; (*samples)[i].y = surf->Domain(1)[0]; break; case 1: //east (*samples)[i].y = prev->y; (*samples)[i].x = surf->Domain(0)[1]; break; case 2: //north (*samples)[i].x = prev->x; (*samples)[i].y = surf->Domain(1)[1]; break; case 3: //west (*samples)[i].y = prev->y; (*samples)[i].x = surf->Domain(0)[0]; } prev = NULL; //std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; } else { //std::cerr << " at singularity " << singularity << " and no prev" << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; complete = false; } } else { prev = &(*samples)[i]; } } if (!complete) { //std::cerr << "Lets work backward:" << std::endl; for (int i = samples->Count() - 2; i >= 0; i--) { // 0 = south, 1 = east, 2 = north, 3 = west if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) { if (prev != NULL) { //std::cerr << " at singularity " << singularity << " but has prev" << std::endl; //std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; switch (singularity) { case 0: //south (*samples)[i].x = prev->x; (*samples)[i].y = surf->Domain(1)[0]; break; case 1: //east (*samples)[i].y = prev->y; (*samples)[i].x = surf->Domain(0)[1]; break; case 2: //north (*samples)[i].x = prev->x; (*samples)[i].y = surf->Domain(1)[1]; break; case 3: //west (*samples)[i].y = prev->y; (*samples)[i].x = surf->Domain(0)[0]; } prev = NULL; //std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; } else { //std::cerr << " at singularity " << singularity << " and no prev" << std::endl; //std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl; complete = false; } } else { prev = &(*samples)[i]; } } } si++; } cs++; } } return true; } void remove_consecutive_intersegment_duplicates(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator cs = pbcs.begin(); while (cs != pbcs.end()) { PBCData *data = (*cs); std::list<ON_2dPointArray *>::iterator si = data->segments.begin(); while (si != data->segments.end()) { ON_2dPointArray *samples = (*si); if (samples->Count() == 0) { si = data->segments.erase(si); } else { for (int i = 0; i < samples->Count() - 1; i++) { while ((i < (samples->Count() - 1)) && (*samples)[i].DistanceTo((*samples)[i + 1]) < 1e-9) { samples->Remove(i + 1); } } si++; } } if (data->segments.empty()) { cs = pbcs.erase(cs); } else { cs++; } } } bool check_pullback_data(std::list<PBCData*> &pbcs) { std::list<PBCData*>::iterator d = pbcs.begin(); if ((*d) == NULL || (*d)->surf == NULL) return false; const ON_Surface *surf = (*d)->surf; bool singular = has_singularity(surf); bool closed = is_closed(surf); if (singular) { if (!resolve_pullback_singularities(pbcs)) { std::cerr << "Error: Can not resolve singular ambiguities." << std::endl; } } if (closed) { // check for same 3D curve use if (!check_for_points_on_same_seam(pbcs)) { std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl; return false; } // check for same 3D curve use if (!extend_pullback_at_shared_3D_curve_seam(pbcs)) { std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl; return false; } if (!shift_single_curve_loop_straddled_over_seam(pbcs)) { std::cerr << "Error: Can not resolve seam ambiguities." << std::endl; return false; } if (!resolve_pullback_seams(pbcs)) { std::cerr << "Error: Can not resolve seam ambiguities." << std::endl; return false; } if (!extend_over_seam_crossings(pbcs)) { std::cerr << "Error: Can not resolve seam ambiguities." << std::endl; return false; } } // consecutive duplicates within segment will cause problems in curve fit remove_consecutive_intersegment_duplicates(pbcs); return true; } int check_pullback_singularity_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2) { if (has_singularity(surf)) { int is, js; if (((is = IsAtSingularity(surf, p1, PBC_SEAM_TOL)) >= 0) && ((js = IsAtSingularity(surf, p2, PBC_SEAM_TOL)) >= 0)) { //create new singular trim if (is == js) { return is; } } } return -1; } int check_pullback_seam_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2) { if (is_closed(surf)) { int is, js; if (((is = IsAtSeam(surf, p1, PBC_SEAM_TOL)) > 0) && ((js = IsAtSeam(surf, p2, PBC_SEAM_TOL)) > 0)) { //create new seam trim if (is == js) { // need to check if seam 3d points are equal double endpoint_distance = p1.DistanceTo(p2); double t0, t1; int dir = is - 1; surf->GetDomain(dir, &t0, &t1); if (endpoint_distance > 0.5 * (t1 - t0)) { return is; } } } } return -1; } ON_Curve* pullback_curve(const brlcad::SurfaceTree* surfacetree, const ON_Surface* surf, const ON_Curve* curve, double tolerance, double flatness) { PBCData data; data.tolerance = tolerance; data.flatness = flatness; data.curve = curve; data.surf = surf; data.surftree = (brlcad::SurfaceTree*)surfacetree; ON_2dPointArray samples; data.segments.push_back(&samples); // Step 1 - adaptively sample the curve double tmin, tmax; data.curve->GetDomain(&tmin, &tmax); ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned if (!toUV(data, start, tmin, 0.001)) { return NULL; // fails if first point is out of tolerance! } ON_2dPoint uv; ON_3dPoint p = curve->PointAt(tmin); ON_3dPoint from = curve->PointAt(tmin + 0.0001); brlcad::SurfaceTree *st = (brlcad::SurfaceTree *)surfacetree; if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) { std::cerr << "Error: Can not get surface point." << std::endl; } ON_2dPoint p1, p2; #ifdef SHOW_UNUSED if (!data.surf) return NULL; const ON_Surface *surf = data.surf; #endif if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) { #ifdef SHOW_UNUSED ON_3dPoint a = surf->PointAt(p1.x, p1.y); ON_3dPoint b = surf->PointAt(p2.x, p2.y); #endif p = curve->PointAt(tmax); from = curve->PointAt(tmax - 0.0001); if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) { std::cerr << "Error: Can not get surface point." << std::endl; } if (!sample(data, tmin, tmax, p1, p2)) { return NULL; } for (int i = 0; i < samples.Count(); i++) { std::cerr << samples[i].x << ", " << samples[i].y << std::endl; } } else { return NULL; } return interpolateCurve(samples); } ON_Curve* pullback_seam_curve(enum seam_direction seam_dir, const brlcad::SurfaceTree* surfacetree, const ON_Surface* surf, const ON_Curve* curve, double tolerance, double flatness) { PBCData data; data.tolerance = tolerance; data.flatness = flatness; data.curve = curve; data.surf = surf; data.surftree = (brlcad::SurfaceTree*)surfacetree; ON_2dPointArray samples; data.segments.push_back(&samples); // Step 1 - adaptively sample the curve double tmin, tmax; data.curve->GetDomain(&tmin, &tmax); ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned if (!toUV(data, start, tmin, 0.001)) { return NULL; // fails if first point is out of tolerance! } ON_2dPoint p1, p2; if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) { if (!sample(data, tmin, tmax, p1, p2)) { return NULL; } for (int i = 0; i < samples.Count(); i++) { if (seam_dir == NORTH_SEAM) { samples[i].y = 1.0; } else if (seam_dir == EAST_SEAM) { samples[i].x = 1.0; } else if (seam_dir == SOUTH_SEAM) { samples[i].y = 0.0; } else if (seam_dir == WEST_SEAM) { samples[i].x = 0.0; } std::cerr << samples[i].x << ", " << samples[i].y << std::endl; } } else { return NULL; } return interpolateCurve(samples); } // Local Variables: // tab-width: 8 // mode: C++ // c-basic-offset: 4 // indent-tabs-mode: t // c-file-style: "stroustrup" // End: // ex: shiftwidth=4 tabstop=8
31.11835
204
0.603803
quadmotor
ca155a3ed1b5de97d9d89de64f6d806f518bcf37
1,895
cpp
C++
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
2
2021-11-22T00:52:48.000Z
2021-12-24T09:33:55.000Z
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
1
2021-12-31T05:08:00.000Z
2021-12-31T05:08:00.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/TCPServer.hpp> # include <Siv3D/TCPServer/TCPServerDetail.hpp> namespace s3d { TCPServer::TCPServer() : pImpl{ std::make_shared<TCPServerDetail>() } {} TCPServer::~TCPServer() {} void TCPServer::startAccept(const uint16 port) { pImpl->startAccept(port); } void TCPServer::startAcceptMulti(const uint16 port) { pImpl->startAcceptMulti(port); } void TCPServer::cancelAccept() { pImpl->cancelAccept(); } bool TCPServer::isAccepting() const { return pImpl->isAccepting(); } void TCPServer::disconnect() { return pImpl->disconnect(); } bool TCPServer::hasSession() const { return pImpl->hasSession(); } bool TCPServer::hasSession(const TCPSessionID id) const { return pImpl->hasSession(id); } size_t TCPServer::num_sessions() const { return pImpl->num_sessions(); } Array<TCPSessionID> TCPServer::getSessionIDs() const { return pImpl->getSessionIDs(); } uint16 TCPServer::port() const { return pImpl->port(); } size_t TCPServer::available(const Optional<TCPSessionID>& id) { return pImpl->available(id); } bool TCPServer::skip(const size_t size, const Optional<TCPSessionID>& id) { return pImpl->skip(size, id); } bool TCPServer::lookahead(void* dst, const size_t size, const Optional<TCPSessionID>& id) const { return pImpl->lookahead(dst, size, id); } bool TCPServer::read(void* dst, const size_t size, const Optional<TCPSessionID>& id) { return pImpl->read(dst, size, id); } bool TCPServer::send(const void* data, const size_t size, const Optional<TCPSessionID>& id) { return pImpl->send(data, size, id); } }
19.536082
96
0.661214
tas9n
ca15af76b7aa10d521476e7213ca8ee5d49dec14
11,799
cpp
C++
Core-src/PeakFile.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
6
2015-03-04T19:41:12.000Z
2022-03-27T09:44:25.000Z
Core-src/PeakFile.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
20
2015-03-03T21:02:20.000Z
2021-08-02T13:26:59.000Z
Core-src/PeakFile.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
8
2015-02-23T19:10:32.000Z
2020-10-26T08:03:00.000Z
/* Copyright (c) 2003, Xentronix Author: Frans van Nispen (frans@xentronix.com) 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 Xentronix 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 <stdlib.h> #include <stdio.h> #include "Globals.h" #include "PeakFile.h" #include "VMSystem.h" CPeakFile Peak; #define BUFFER_SIZE 64*256 // 64Kb // ============================================================ CPeakFile::CPeakFile() { buffer_left = NULL; buffer_right = NULL; buffer = NULL; } // ============================================================ CPeakFile::~CPeakFile() { if (buffer) delete[] buffer; if (buffer_left) free(buffer_left); if (buffer_right) free(buffer_right); } // ============================================================ void CPeakFile::Init(int32 size, bool mono) { if (buffer) delete[] buffer; buffer = new float[BUFFER_SIZE]; m_size = size; size = (size >> 7) + 1; m_mono = mono; int64 mem = size * 4 +16; // 2 int16's for each channel if (!mono) mem *= 2; int16 *p = (int16*)realloc(buffer_left, mem); if (p){ buffer_left = p; // new block memset( buffer_left, 0, mem); // wipe buffer }else{ (new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go(); be_app->Quit(); } if (!mono){ int16 *p = (int16*)realloc(buffer_right, mem); if (p){ buffer_right = p; // new block memset( buffer_right, 0, mem); // wipe buffer }else{ (new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go(); be_app->Quit(); } }else{ if (buffer_right) free(buffer_right); buffer_right = NULL; } } // ============================================================ void CPeakFile::CreatePeaks(int32 start, int32 end, int32 progress) { float min, max, max_r, min_r; int32 to, ii; start &= 0xfffffff8; // mask off 1st 7 bits to round on 128 bytes int32 p_add = 0, p_count = 0, count = 0; if (progress){ // init progress process p_count = (end-start)/(100*128); p_add = progress/100; if (!m_mono) p_add <<=1; } if (m_mono) // mono { #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 index = 0; VM.ReadBlockAt(start, p, BUFFER_SIZE); #endif for (int32 i=start; i<=end; i+=128){ min = max = 0.0; to = i+127; if (to>Pool.size) to = Pool.size; for (int32 x=i; x<=to; x++){ #ifndef __VM_SYSTEM // RAM if (p[x]>max) max = p[x]; if (p[x]<min) min = p[x]; #else if (p[index]>max) max = p[index]; if (p[index]<min) min = p[index]; index++; if (index == BUFFER_SIZE){ index = 0; VM.ReadBlock(p, BUFFER_SIZE); } #endif } ii = i>>6; buffer_left[ii] = (int16)(min * 32767); buffer_left[ii+1] = (int16)(max * 32767); if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); } } } else // Stereo { #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 index = 0; VM.ReadBlockAt(start, p, BUFFER_SIZE); #endif for (int32 i=start*2; i<=end*2; i+=256){ min = max = 0.0; min_r = max_r = 0.0; to = i+255; if (to>Pool.size) to = Pool.size; for (int32 x=i; x<=to; x+=2){ #ifndef __VM_SYSTEM // RAM if (p[x]>max) max = p[x]; if (p[x]<min) min = p[x]; if (p[x+1]>max_r) max_r = p[x+1]; if (p[x+1]<min_r) min_r = p[x+1]; #else if (p[index]>max) max = p[index]; if (p[index]<min) min = p[index]; if (p[index+1]>max_r) max_r = p[index+1]; if (p[index+1]<min_r) min_r = p[index+1]; index+=2; if (index >= BUFFER_SIZE){ index = 0; VM.ReadBlock(p, BUFFER_SIZE); } #endif } ii = i>>6; buffer_left[ii] = (int16)(min * 32767); buffer_left[ii+1] = (int16)(max * 32767); buffer_right[ii] = (int16)(min_r * 32767); buffer_right[ii+1] = (int16)(max_r * 32767); if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); } } } Pool.update_peak = true; } // ============================================================ void CPeakFile::MonoBuffer(float *out, int32 start, int32 end, float w) { if (!buffer_left || !m_mono) return; float step = (end - start)/w; int32 iStep = (int32)step; int32 index, to; #ifdef __VM_SYSTEM // VM int32 nBufferSize = MIN( BUFFER_SIZE, end-start); #endif if ( step <= 1 ) { #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ #ifndef __VM_SYSTEM // RAM index = start + (int32)(x * step); #else index = (int32)(x * step); #endif float fTemp = p[index]; if (fTemp>1.0f) fTemp = 1.0f; else if (fTemp<-1.0f) fTemp = -1.0f; *out++ = fTemp; *out++ = 0.0f; } }else if ( step < 64 ) { float min, max; #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 idx = 0; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; min = max = 0; for (int32 i=index; i<=to; i++){ #ifndef __VM_SYSTEM // RAM if (p[i]>max) max = p[i]; if (p[i]<min) min = p[i]; #else if (p[idx]>max) max = p[idx]; if (p[idx]<min) min = p[idx]; idx++; if (idx == nBufferSize){ idx = 0; VM.ReadBlock(p, nBufferSize); } #endif } if (max > -min) *out++ = MIN(max, 1); else *out++ = MAX(min, -1); *out++ = 0.0f; } }else if ( step < 128 ) { float min, max; #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 idx = 0; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; min = max = 0; for (int32 i=index; i<=to; i++){ #ifndef __VM_SYSTEM // RAM if (p[i]>max) max = p[i]; if (p[i]<min) min = p[i]; #else if (p[idx]>max) max = p[idx]; if (p[idx]<min) min = p[idx]; idx++; if (idx == nBufferSize){ idx = 0; VM.ReadBlock(p, nBufferSize); } #endif } *out++ = min; *out++ = max; } } else { int16 min, max; for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; index >>= 6; index &= 0xfffffffe; to >>= 6; to &= 0xfffffffe; min = max = 0; for (int32 i=index; i<=to; i+=2){ if (buffer_left[i]<min) min = buffer_left[i]; if (buffer_left[i+1]>max) max = buffer_left[i+1]; } *out++ = min/32767.0; *out++ = max/32767.0; } } } // ============================================================ void CPeakFile::StereoBuffer(float *out, float *out_r, int32 start, int32 end, float w) { if (!buffer_left ||!buffer_right || m_mono) return; float step = (end - start)/w; int32 iStep = (int32)step; int32 index, to; #ifdef __VM_SYSTEM // VM int32 nBufferSize = MIN( BUFFER_SIZE, (end-start)*2); #endif if ( step <= 1 ) { #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ #ifndef __VM_SYSTEM // RAM index = start + (int32)(x * step); #else index = (int32)(x * step); #endif float fTemp = p[index*2]; float fTempR = p[index*2+1]; if (fTemp>1.0f) fTemp = 1.0f; else if (fTemp<-1.0f) fTemp = -1.0f; if (fTempR>1.0f) fTempR = 1.0f; else if (fTempR<-1.0f) fTempR = -1.0f; *out++ = fTemp; *out++ = 0.0f; *out_r++ = fTempR; *out_r++ = 0.0f; } }else if ( step < 64 ) { float min, max, min_r, max_r; #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 idx = 0; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; index *= 2; to *= 2; min = max = min_r = max_r = 0; for (int32 i=index; i<=to; i+=2){ #ifndef __VM_SYSTEM // RAM if (p[i]>max) max = p[i]; if (p[i]<min) min = p[i]; if (p[i+1]>max_r) max_r = p[i+1]; if (p[i+1]<min_r) min_r = p[i+1]; #else if (p[idx]>max) max = p[idx]; if (p[idx]<min) min = p[idx]; idx++; if (p[idx]>max_r) max_r = p[idx]; if (p[idx]<min_r) min_r = p[idx]; idx++; if (idx >= nBufferSize){ idx = 0; VM.ReadBlock(p, nBufferSize); } #endif } if (max > -min) *out++ = MIN(max, 1); else *out++ = MAX(min, -1); *out++ = 0.0f; if (max_r > -min_r) *out_r++ = MIN(max_r, 1); else *out_r++ = MAX(min_r, -1); *out_r++ = 0.0f; } }else if (step <128) { float min, max, min_r, max_r; #ifndef __VM_SYSTEM // RAM float *p = Pool.sample_memory; #else float *p = buffer; int32 idx = 0; VM.ReadBlockAt(start, p, nBufferSize); #endif for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; index *= 2; to *= 2; min = max = min_r = max_r = 0; for (int32 i=index; i<=to; i+=2){ #ifndef __VM_SYSTEM // RAM if (p[i]>max) max = p[i]; if (p[i]<min) min = p[i]; if (p[i+1]>max_r) max_r = p[i+1]; if (p[i+1]<min_r) min_r = p[i+1]; #else if (p[idx]>max) max = p[idx]; if (p[idx]<min) min = p[idx]; idx++; if (p[idx]>max_r) max_r = p[idx]; if (p[idx]<min_r) min_r = p[idx]; idx++; if (idx >= nBufferSize){ idx = 0; VM.ReadBlock(p, nBufferSize); } #endif } *out++ = min; *out++ = max; *out_r++ = min_r; *out_r++ = max_r; } } else { int16 min, max, min_r, max_r; for (int32 x = 0; x<w; x++){ index = start + (int32)(x * step); to = index + iStep; if (to>m_size) to = m_size; index >>= 6; index &= 0xfffffffe; to >>= 6; to &= 0xfffffffe; min = max = min_r = max_r = 0; for (int32 i=index; i<=to; i+=2){ if (buffer_left[i]<min) min = buffer_left[i]; if (buffer_left[i+1]>max) max = buffer_left[i+1]; if (buffer_right[i]<min_r) min_r = buffer_right[i]; if (buffer_right[i+1]>max_r) max_r = buffer_right[i+1]; } *out++ = min/32767.0; *out++ = max/32767.0; *out_r++ = min_r/32767.0; *out_r++ = max_r/32767.0; } } }
25.157783
89
0.56437
HaikuArchives
ca16e67e1877b5938779837034e9e48dd1883b06
8,914
cpp
C++
src/common/sort/radix_sort.cpp
DavidKorczynski/duckdb
46fb0e1b13a803be49e4565f9878d6d3e5a32380
[ "MIT" ]
1
2021-10-05T11:20:43.000Z
2021-10-05T11:20:43.000Z
src/common/sort/radix_sort.cpp
DavidKorczynski/duckdb
46fb0e1b13a803be49e4565f9878d6d3e5a32380
[ "MIT" ]
null
null
null
src/common/sort/radix_sort.cpp
DavidKorczynski/duckdb
46fb0e1b13a803be49e4565f9878d6d3e5a32380
[ "MIT" ]
null
null
null
#include "duckdb/common/sort/comparators.hpp" #include "duckdb/common/sort/sort.hpp" namespace duckdb { //! Calls std::sort on strings that are tied by their prefix after the radix sort static void SortTiedBlobs(BufferManager &buffer_manager, const data_ptr_t dataptr, const idx_t &start, const idx_t &end, const idx_t &tie_col, bool *ties, const data_ptr_t blob_ptr, const SortLayout &sort_layout) { const auto row_width = sort_layout.blob_layout.GetRowWidth(); const idx_t &col_idx = sort_layout.sorting_to_blob_col.at(tie_col); // Locate the first blob row in question data_ptr_t row_ptr = dataptr + start * sort_layout.entry_size; data_ptr_t blob_row_ptr = blob_ptr + Load<uint32_t>(row_ptr + sort_layout.comparison_size) * row_width; if (!Comparators::TieIsBreakable(col_idx, blob_row_ptr, sort_layout.blob_layout)) { // Quick check to see if ties can be broken return; } // Fill pointer array for sorting auto ptr_block = unique_ptr<data_ptr_t[]>(new data_ptr_t[end - start]); auto entry_ptrs = (data_ptr_t *)ptr_block.get(); for (idx_t i = start; i < end; i++) { entry_ptrs[i - start] = row_ptr; row_ptr += sort_layout.entry_size; } // Slow pointer-based sorting const int order = sort_layout.order_types[tie_col] == OrderType::DESCENDING ? -1 : 1; const auto &tie_col_offset = sort_layout.blob_layout.GetOffsets()[col_idx]; auto logical_type = sort_layout.blob_layout.GetTypes()[col_idx]; std::sort(entry_ptrs, entry_ptrs + end - start, [&blob_ptr, &order, &sort_layout, &tie_col_offset, &row_width, &logical_type](const data_ptr_t l, const data_ptr_t r) { idx_t left_idx = Load<uint32_t>(l + sort_layout.comparison_size); idx_t right_idx = Load<uint32_t>(r + sort_layout.comparison_size); data_ptr_t left_ptr = blob_ptr + left_idx * row_width + tie_col_offset; data_ptr_t right_ptr = blob_ptr + right_idx * row_width + tie_col_offset; return order * Comparators::CompareVal(left_ptr, right_ptr, logical_type) < 0; }); // Re-order auto temp_block = buffer_manager.Allocate(MaxValue((end - start) * sort_layout.entry_size, (idx_t)Storage::BLOCK_SIZE)); data_ptr_t temp_ptr = temp_block->Ptr(); for (idx_t i = 0; i < end - start; i++) { memcpy(temp_ptr, entry_ptrs[i], sort_layout.entry_size); temp_ptr += sort_layout.entry_size; } memcpy(dataptr + start * sort_layout.entry_size, temp_block->Ptr(), (end - start) * sort_layout.entry_size); // Determine if there are still ties (if this is not the last column) if (tie_col < sort_layout.column_count - 1) { data_ptr_t idx_ptr = dataptr + start * sort_layout.entry_size + sort_layout.comparison_size; // Load current entry data_ptr_t current_ptr = blob_ptr + Load<uint32_t>(idx_ptr) * row_width + tie_col_offset; for (idx_t i = 0; i < end - start - 1; i++) { // Load next entry and compare idx_ptr += sort_layout.entry_size; data_ptr_t next_ptr = blob_ptr + Load<uint32_t>(idx_ptr) * row_width + tie_col_offset; ties[start + i] = Comparators::CompareVal(current_ptr, next_ptr, logical_type) == 0; current_ptr = next_ptr; } } } //! Identifies sequences of rows that are tied by the prefix of a blob column, and sorts them static void SortTiedBlobs(BufferManager &buffer_manager, SortedBlock &sb, bool *ties, data_ptr_t dataptr, const idx_t &count, const idx_t &tie_col, const SortLayout &sort_layout) { D_ASSERT(!ties[count - 1]); auto &blob_block = sb.blob_sorting_data->data_blocks.back(); auto blob_handle = buffer_manager.Pin(blob_block.block); const data_ptr_t blob_ptr = blob_handle->Ptr(); for (idx_t i = 0; i < count; i++) { if (!ties[i]) { continue; } idx_t j; for (j = i; j < count; j++) { if (!ties[j]) { break; } } SortTiedBlobs(buffer_manager, dataptr, i, j + 1, tie_col, ties, blob_ptr, sort_layout); i = j; } } //! Returns whether there are any 'true' values in the ties[] array static bool AnyTies(bool ties[], const idx_t &count) { D_ASSERT(!ties[count - 1]); bool any_ties = false; for (idx_t i = 0; i < count - 1; i++) { any_ties = any_ties || ties[i]; } return any_ties; } //! Compares subsequent rows to check for ties static void ComputeTies(data_ptr_t dataptr, const idx_t &count, const idx_t &col_offset, const idx_t &tie_size, bool ties[], const SortLayout &sort_layout) { D_ASSERT(!ties[count - 1]); D_ASSERT(col_offset + tie_size <= sort_layout.comparison_size); // Align dataptr dataptr += col_offset; for (idx_t i = 0; i < count - 1; i++) { ties[i] = ties[i] && memcmp(dataptr, dataptr + sort_layout.entry_size, tie_size) == 0; dataptr += sort_layout.entry_size; } } //! Textbook LSD radix sort static void RadixSort(BufferManager &buffer_manager, data_ptr_t dataptr, const idx_t &count, const idx_t &col_offset, const idx_t &sorting_size, const SortLayout &sort_layout) { auto temp_block = buffer_manager.Allocate(MaxValue(count * sort_layout.entry_size, (idx_t)Storage::BLOCK_SIZE)); data_ptr_t temp = temp_block->Ptr(); bool swap = false; idx_t counts[256]; uint8_t byte; for (idx_t offset = col_offset + sorting_size - 1; offset + 1 > col_offset; offset--) { // Init counts to 0 memset(counts, 0, sizeof(counts)); // Collect counts for (idx_t i = 0; i < count; i++) { byte = *(dataptr + i * sort_layout.entry_size + offset); counts[byte]++; } // Compute offsets from counts for (idx_t val = 1; val < 256; val++) { counts[val] = counts[val] + counts[val - 1]; } // Re-order the data in temporary array for (idx_t i = count; i > 0; i--) { byte = *(dataptr + (i - 1) * sort_layout.entry_size + offset); memcpy(temp + (counts[byte] - 1) * sort_layout.entry_size, dataptr + (i - 1) * sort_layout.entry_size, sort_layout.entry_size); counts[byte]--; } std::swap(dataptr, temp); swap = !swap; } // Move data back to original buffer (if it was swapped) if (swap) { memcpy(temp, dataptr, count * sort_layout.entry_size); } } //! Identifies sequences of rows that are tied, and calls radix sort on these static void SubSortTiedTuples(BufferManager &buffer_manager, const data_ptr_t dataptr, const idx_t &count, const idx_t &col_offset, const idx_t &sorting_size, bool ties[], const SortLayout &sort_layout) { D_ASSERT(!ties[count - 1]); for (idx_t i = 0; i < count; i++) { if (!ties[i]) { continue; } idx_t j; for (j = i + 1; j < count; j++) { if (!ties[j]) { break; } } RadixSort(buffer_manager, dataptr + i * sort_layout.entry_size, j - i + 1, col_offset, sorting_size, sort_layout); i = j; } } void LocalSortState::SortInMemory() { auto &sb = *sorted_blocks.back(); auto &block = sb.radix_sorting_data.back(); const auto &count = block.count; auto handle = buffer_manager->Pin(block.block); const auto dataptr = handle->Ptr(); // Assign an index to each row data_ptr_t idx_dataptr = dataptr + sort_layout->comparison_size; for (uint32_t i = 0; i < count; i++) { Store<uint32_t>(i, idx_dataptr); idx_dataptr += sort_layout->entry_size; } // Radix sort and break ties until no more ties, or until all columns are sorted idx_t sorting_size = 0; idx_t col_offset = 0; unique_ptr<bool[]> ties_ptr; unique_ptr<BufferHandle> ties_handle; bool *ties = nullptr; for (idx_t i = 0; i < sort_layout->column_count; i++) { sorting_size += sort_layout->column_sizes[i]; if (sort_layout->constant_size[i] && i < sort_layout->column_count - 1 && sorting_size < 32) { // Add columns to the sorting size until we reach a variable size column, or the last column continue; } if (!ties) { // This is the first sort RadixSort(*buffer_manager, dataptr, count, col_offset, sorting_size, *sort_layout); ties_ptr = unique_ptr<bool[]>(new bool[count]); ties = ties_ptr.get(); std::fill_n(ties, count - 1, true); ties[count - 1] = false; } else { // For subsequent sorts, we only have to subsort the tied tuples SubSortTiedTuples(*buffer_manager, dataptr, count, col_offset, sorting_size, ties, *sort_layout); } if (sort_layout->constant_size[i] && i == sort_layout->column_count - 1) { // All columns are sorted, no ties to break because last column is constant size break; } ComputeTies(dataptr, count, col_offset, sorting_size, ties, *sort_layout); if (!AnyTies(ties, count)) { // No ties, stop sorting break; } if (!sort_layout->constant_size[i]) { SortTiedBlobs(*buffer_manager, sb, ties, dataptr, count, i, *sort_layout); if (!AnyTies(ties, count)) { // No more ties after tie-breaking, stop break; } } col_offset += sorting_size; sorting_size = 0; } } } // namespace duckdb
39.096491
120
0.67523
DavidKorczynski
ca197403de71028efb91aaef9f94f71c9dba68b3
6,493
hpp
C++
src/slave/containerizer/docker.hpp
HICAS-ChameLeon/Chameleon
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
[ "Apache-2.0" ]
4
2019-03-06T03:04:40.000Z
2019-07-20T15:35:00.000Z
src/slave/containerizer/docker.hpp
HICAS-ChameLeon/Chameleon
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
[ "Apache-2.0" ]
6
2018-11-30T08:04:45.000Z
2019-05-15T03:04:28.000Z
src/slave/containerizer/docker.hpp
HICAS-ChameLeon/Chameleon
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
[ "Apache-2.0" ]
4
2019-03-11T11:51:22.000Z
2020-05-11T07:27:31.000Z
/* * Copyright :SIAT 异构智能计算体系结构与系统研究中心 * Author : Heldon 764165887@qq.com * Date :19-03-01 * Description:containerizer(docker) codes */ #ifndef CHAMELEON_DOCKER_HPP #define CHAMELEON_DOCKER_HPP //C++11 dependencies #include <list> #include <map> #include <set> #include <string> //stout dependencies #include <stout/os.hpp> //google dependencies #include <gflags/gflags.h> //libprocess dependencies #include <process/owned.hpp> #include <process/shared.hpp> #include <process/process.hpp> //chameleon dependencies #include <resources.hpp> #include "docker/docker.hpp" #include "docker/resources.hpp" namespace chameleon{ namespace slave{ //Foward declaration class DockerContainerizerProcess; class DockerContainerizer{ public: static Try<DockerContainerizer*> create(); DockerContainerizer(process::Shared<Docker> docker); virtual process::Future<bool> launch( const mesos::ContainerID& containerId, const Option<mesos::TaskInfo>& taskInfo, const mesos::ExecutorInfo& executorInfo, const std::string directory, const Option<std::string>& user, const mesos::SlaveID& slaveId, const std::map<std::string, std::string>& environment); virtual ~DockerContainerizer(); private: process::Owned<DockerContainerizerProcess> m_process; }; class DockerContainerizerProcess : public process::Process<DockerContainerizerProcess>{ public: DockerContainerizerProcess(process::Shared<Docker> _docker) : m_docker(_docker){} //start launch containerizer virtual process::Future<bool> launch( const mesos::ContainerID& contaierId, const Option<mesos::TaskInfo>& taskInfo, const mesos::ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const mesos::SlaveID& slaveId, const std::map<std::string, std::string>& environment); // pull the image virtual process::Future<Nothing> pull(const mesos::ContainerID& containerId); private: process::Future<bool> _launch( const mesos::ContainerID& containerId, const Option<mesos::TaskInfo>& taskInfo, const mesos::ExecutorInfo& executorInfo, const std::string& directory, const mesos::SlaveID& slaveId); // Starts the executor in a Docker container. process::Future<Docker::Container> launchExecutorContainer( const mesos::ContainerID& containerId, const std::string& containerName); //const Flags m_flags; process::Shared<Docker> m_docker; struct Container{ const mesos::ContainerID m_id; const Option<mesos::TaskInfo> m_task; const mesos::ExecutorInfo m_executor; mesos::ContainerInfo m_container; mesos::CommandInfo m_command; std::map<std::string, std::string> m_environment; Option<std::map<std::string, std::string>> m_taskEnvironment; // The sandbox directory for the container. std::string m_directory; const Option<std::string> m_user; mesos::SlaveID m_slaveId; //const Flags m_flags; mesos::Resources m_resources; process::Future<Docker::Image> m_pull; process::Future<bool> m_launch; static Try<Container*> create( const mesos::ContainerID& id, const Option<mesos::TaskInfo>& taskInfo, const mesos::ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const mesos::SlaveID& slaveId, const std::map<std::string, std::string>& environment); static std::string name(const mesos::SlaveID& slaveId, const std::string& id) { return "chameleon-" + slaveId.value() + "." + stringify(id); } Container(const mesos::ContainerID& id, const Option<mesos::TaskInfo>& taskInfo, const mesos::ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const mesos::SlaveID& slaveId, const Option<mesos::CommandInfo>& _command, const Option<mesos::ContainerInfo>& _container, const std::map<std::string, std::string>& _environment) : m_id(id), m_task(taskInfo), m_executor(executorInfo), m_environment(_environment), m_directory(directory), m_user(user), m_slaveId(slaveId){ LOG(INFO)<<"Heldon Enter construct function Container"; m_resources = m_executor.resources(); if (m_task.isSome()) { CHECK(m_resources.contains(m_task.get().resources())); } if (_command.isSome()) { m_command = _command.get(); } else if (m_task.isSome()) { m_command = m_task.get().command(); } else { m_command = m_executor.command(); } if (_container.isSome()) { m_container = _container.get(); } else if (m_task.isSome()) { m_container = m_task.get().container(); } else { m_container = m_executor.container(); } } ~Container() { os::rm(m_directory); } std::string name(){ return name(m_slaveId, stringify(m_id)); } std::string image() const{ if(m_task.isSome()){ return m_task.get().container().docker().image(); } return m_executor.container().docker().image(); } }; hashmap<mesos::ContainerID, Container*> m_containers; }; } } #endif //CHAMELEON_DOCKER_HPP
33.297436
91
0.551517
HICAS-ChameLeon
ca19ce947ee073ce2ea4f581d3a999c5189f0211
1,147
cpp
C++
src/behaviour/meleeattackbhv.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/behaviour/meleeattackbhv.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/behaviour/meleeattackbhv.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
#include "meleeattackbhv.h" #include "util/math.h" #include "objects//enemy.h" #include "level/level.h" MeleeAttackBhv::MeleeAttackBhv(Enemy* owner): Behaviour(owner), _attackTime { 0.0f } { } void MeleeAttackBhv::collision(float x, float y, float z) { (void) x; (void) y; (void) z; } void MeleeAttackBhv::damage(float damage) { (void) damage; } void MeleeAttackBhv::update(double dt) { if(_attackTime > .0f) _attackTime -= dt; auto player = owner->level->player(); vec2 delta(player->x() - owner->x(), player->y() - owner->y()); if(delta.length() < minAttackDistance) { owner->speedXY(.0f, .0f); if(_attackTime <= .0f) { player->damage(attackDamage, vec3(owner->x(), owner->y(), owner->z())); _attackTime = attackCooldown; } if(owner->state() != EnemyState::ES_ATTACK) owner->state(EnemyState::ES_ATTACK); } else { delta.normalize(); delta *= owner->maxSpeed(); owner->dir(atan2(delta.y, delta.x)); owner->speedXY(delta.x, delta.y); } }
21.641509
83
0.562337
alexeyden
ca19e5870270f147d6b3ea9fc9cb083435fd16b8
76,520
cpp
C++
gui/qtc-gdbmacros/gdbmacros.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2016-03-23T08:12:33.000Z
2022-01-25T14:07:03.000Z
gui/qtc-gdbmacros/gdbmacros.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
null
null
null
gui/qtc-gdbmacros/gdbmacros.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2015-06-29T12:00:06.000Z
2019-09-03T12:40:47.000Z
/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the packaging ** of this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #include <qglobal.h> // this relies on contents copied from qobject_p.h #define PRIVATE_OBJECT_ALLOWED 1 #include <QDateTime> #include <QDebug> #include <QDir> #include <QFile> #include <QFileInfo> #include <QHash> #include <QLocale> #include <QMap> #include <QMetaObject> #include <QMetaProperty> #include <QModelIndex> #include <QObject> #include <QPointer> #include <QString> #include <QTextCodec> #include <QVector> /*! \class QDumper \brief Helper class for producing "nice" output in Qt Creator's debugger. \internal The whole "custom dumper" implementation is currently far less modular than it could be. But as the code is still in a flux, making it nicer from a pure archtectural point of view seems still be a waste of resources. Some hints: New dumpers for non-templated classes should be mentioned in \c{qDumpObjectData440()} in the \c{protocolVersion == 1} branch. Templated classes need extra support on the IDE level (see plugins/debugger/gdbengine.cpp) and should not be mentiond in \c{qDumpObjectData440()}. In any case, dumper processesing should end up in \c{handleProtocolVersion2and3()} and needs an entry in the bis switch there. Next step is to create a suitable \c{static void qDumpFoo(QDumper &d)} function. At the bare minimum it should contain something like: \c{ const Foo &foo = *reinterpret_cast<const Foo *>(d.data); P(d, "value", ...); P(d, "type", "Foo"); P(d, "numchild", "0"); } 'P(d, name, value)' roughly expands to: d << (name) << "=\"" << value << "\""; Useful (i.e. understood by the IDE) names include: \list \o "name" shows up in the first column in the Locals&Watchers view. \o "value" shows up in the second column. \o "valueencoded" should be set to "1" if the value is base64 encoded. Always base64-encode values that might use unprintable or otherwise "confuse" the protocol (like spaces and quotes). [A-Za-z0-9] is "safe". A value of "3" is used for base64-encoded UCS4, "2" denotes base64-encoded UTF16. \o "numchild" return the number of children in the view. Effectively, only 0 and != 0 will be used, so don't try too hard to get the number right. \endlist If the current item has children, it might be queried to produce information about thes children. In this case the dumper should use something like \c{ if (d.dumpChildren) { d << ",children=["; } */ int qtGhVersion = QT_VERSION; #ifdef QT_GUI_LIB # include <QPixmap> # include <QImage> #endif #include <list> #include <map> #include <string> #include <vector> #include <ctype.h> #include <stdio.h> #ifdef Q_OS_WIN # include <windows.h> #endif #undef NS #ifdef QT_NAMESPACE # define STRINGIFY0(s) #s # define STRINGIFY1(s) STRINGIFY0(s) # define NS STRINGIFY1(QT_NAMESPACE) "::" # define NSX "'" STRINGIFY1(QT_NAMESPACE) "::" # define NSY "'" #else # define NS "" # define NSX "" # define NSY "" #endif #if PRIVATE_OBJECT_ALLOWED #if defined(QT_BEGIN_NAMESPACE) QT_BEGIN_NAMESPACE #endif class QVariant; class QThreadData; class QObjectConnectionListVector; class QObjectPrivate : public QObjectData { Q_DECLARE_PUBLIC(QObject) public: QObjectPrivate() {} virtual ~QObjectPrivate() {} // preserve binary compatibility with code compiled without Qt 3 support QList<QObject *> pendingChildInsertedEvents; // unused // id of the thread that owns the object QThreadData *threadData; struct Sender { QObject *sender; int signal; int ref; }; Sender *currentSender; // object currently activating the object QObject *currentChildBeingDeleted; QList<QPointer<QObject> > eventFilters; struct ExtraData; ExtraData *extraData; mutable quint32 connectedSignals; QString objectName; struct Connection { QObject *receiver; int method; uint connectionType : 3; // 0 == auto, 1 == direct, 2 == queued, 4 == blocking QBasicAtomicPointer<int> argumentTypes; }; typedef QList<Connection> ConnectionList; QObjectConnectionListVector *connectionLists; QList<Sender> senders; int *deleteWatch; }; #if defined(QT_BEGIN_NAMESPACE) QT_END_NAMESPACE #endif #endif // PRIVATE_OBJECT_ALLOWED // this can be mangled typenames of nested templates, each char-by-char // comma-separated integer list static char qDumpInBuffer[10000]; static char qDumpBuffer[1000]; namespace { static bool isPointerType(const QByteArray &type) { return type.endsWith("*") || type.endsWith("* const"); } static QByteArray stripPointerType(QByteArray type) { if (type.endsWith("*")) type.chop(1); if (type.endsWith("* const")) type.chop(7); if (type.endsWith(' ')) type.chop(1); return type; } // This is used to abort evaluation of custom data dumpers in a "coordinated" // way. Abortion will happen anyway when we try to access a non-initialized // non-trivial object, so there is no way to prevent this from occuring at all // conceptionally. Gdb will catch SIGSEGV and return to the calling frame. // This is just fine provided we only _read_ memory in the custom handlers // below. volatile int qProvokeSegFaultHelper; static const void *addOffset(const void *p, int offset) { return offset + reinterpret_cast<const char *>(p); } static const void *skipvtable(const void *p) { return sizeof(void*) + reinterpret_cast<const char *>(p); } static const void *deref(const void *p) { return *reinterpret_cast<const char* const*>(p); } static const void *dfunc(const void *p) { return deref(skipvtable(p)); } static bool isEqual(const char *s, const char *t) { return qstrcmp(s, t) == 0; } static bool startsWith(const char *s, const char *t) { return qstrncmp(s, t, strlen(t)) == 0; } // provoke segfault when address is not readable #define qCheckAccess(d) do { qProvokeSegFaultHelper = *(char*)d; } while (0) #define qCheckPointer(d) do { if (d) qProvokeSegFaultHelper = *(char*)d; } while (0) // provoke segfault unconditionally #define qCheck(b) do { if (!(b)) qProvokeSegFaultHelper = *(char*)0; } while (0) const char *stripNamespace(const char *type) { static const size_t nslen = strlen(NS); return startsWith(type, NS) ? type + nslen : type; } static bool isSimpleType(const char *type) { switch (type[0]) { case 'c': return isEqual(type, "char"); case 'd': return isEqual(type, "double"); case 'f': return isEqual(type, "float"); case 'i': return isEqual(type, "int"); case 'l': return isEqual(type, "long") || startsWith(type, "long "); case 's': return isEqual(type, "short") || isEqual(type, "signed") || startsWith(type, "signed "); case 'u': return isEqual(type, "unsigned") || startsWith(type, "unsigned "); } return false; } static bool isShortKey(const char *type) { return isSimpleType(type) || isEqual(type, "QString"); } static bool isMovableType(const char *type) { if (isPointerType(type)) return true; if (isSimpleType(type)) return true; type = stripNamespace(type); switch (type[1]) { case 'B': return isEqual(type, "QBrush") || isEqual(type, "QBitArray") || isEqual(type, "QByteArray") ; case 'C': return isEqual(type, "QCustomTypeInfo"); case 'D': return isEqual(type, "QDate") || isEqual(type, "QDateTime"); case 'F': return isEqual(type, "QFileInfo") || isEqual(type, "QFixed") || isEqual(type, "QFixedPoint") || isEqual(type, "QFixedSize"); case 'H': return isEqual(type, "QHashDummyValue"); case 'I': return isEqual(type, "QIcon") || isEqual(type, "QImage"); case 'L': return isEqual(type, "QLine") || isEqual(type, "QLineF") || isEqual(type, "QLocal"); case 'M': return isEqual(type, "QMatrix") || isEqual(type, "QModelIndex"); case 'P': return isEqual(type, "QPoint") || isEqual(type, "QPointF") || isEqual(type, "QPen") || isEqual(type, "QPersistentModelIndex"); case 'R': return isEqual(type, "QResourceRoot") || isEqual(type, "QRect") || isEqual(type, "QRectF") || isEqual(type, "QRegExp"); case 'S': return isEqual(type, "QSize") || isEqual(type, "QSizeF") || isEqual(type, "QString"); case 'T': return isEqual(type, "QTime") || isEqual(type, "QTextBlock"); case 'U': return isEqual(type, "QUrl"); case 'V': return isEqual(type, "QVariant"); case 'X': return isEqual(type, "QXmlStreamAttribute") || isEqual(type, "QXmlStreamNamespaceDeclaration") || isEqual(type, "QXmlStreamNotationDeclaration") || isEqual(type, "QXmlStreamEntityDeclaration"); } return false; } struct QDumper { explicit QDumper(); ~QDumper(); void flush(); void checkFill(); QDumper &operator<<(long c); QDumper &operator<<(int i); QDumper &operator<<(double d); QDumper &operator<<(float d); QDumper &operator<<(unsigned long c); QDumper &operator<<(unsigned int i); QDumper &operator<<(const void *p); QDumper &operator<<(qulonglong c); QDumper &operator<<(const char *str); QDumper &operator<<(const QByteArray &ba); QDumper &operator<<(const QString &str); void put(char c); void addCommaIfNeeded(); void putBase64Encoded(const char *buf, int n); void putEllipsis(); void disarm(); void beginHash(); // start of data hash output void endHash(); // start of data hash output void write(const void *buf, int len); // raw write to stdout // the dumper arguments int protocolVersion; // dumper protocol version int token; // some token to show on success const char *outertype; // object type const char *iname; // object name used for display const char *exp; // object expression const char *innertype; // 'inner type' for class templates const void *data; // pointer to raw data bool dumpChildren; // do we want to see children? // handling of nested templates void setupTemplateParameters(); enum { maxTemplateParameters = 10 }; const char *templateParameters[maxTemplateParameters + 1]; int templateParametersCount; // internal state bool success; // are we finished? int pos; int extraInt[4]; }; QDumper::QDumper() { success = false; pos = 0; } QDumper::~QDumper() { flush(); char buf[30]; int len = qsnprintf(buf, sizeof(buf) - 1, "%d^done\n", token); write(buf, len); } void QDumper::write(const void *buf, int len) { ::fwrite(buf, len, 1, stdout); ::fflush(stdout); } void QDumper::flush() { if (pos != 0) { char buf[30]; int len = qsnprintf(buf, sizeof(buf) - 1, "%d#%d,", token, pos); write(buf, len); write(qDumpBuffer, pos); write("\n", 1); pos = 0; } } void QDumper::setupTemplateParameters() { char *s = const_cast<char *>(innertype); templateParametersCount = 1; templateParameters[0] = s; for (int i = 1; i != maxTemplateParameters + 1; ++i) templateParameters[i] = 0; while (*s) { while (*s && *s != '@') ++s; if (*s) { *s = '\0'; ++s; templateParameters[templateParametersCount++] = s; } } } QDumper &QDumper::operator<<(unsigned long long c) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%llu", c); return *this; } QDumper &QDumper::operator<<(unsigned long c) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%lu", c); return *this; } QDumper &QDumper::operator<<(float d) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%f", d); return *this; } QDumper &QDumper::operator<<(double d) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%f", d); return *this; } QDumper &QDumper::operator<<(unsigned int i) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%u", i); return *this; } QDumper &QDumper::operator<<(long c) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%ld", c); return *this; } QDumper &QDumper::operator<<(int i) { checkFill(); pos += sprintf(qDumpBuffer + pos, "%d", i); return *this; } QDumper &QDumper::operator<<(const void *p) { static char buf[100]; if (p) { sprintf(buf, "%p", p); // we get a '0x' prefix only on some implementations. // if it isn't there, write it out manually. if (buf[1] != 'x') { put('0'); put('x'); } *this << buf; } else { *this << "<null>"; } return *this; } void QDumper::checkFill() { if (pos >= int(sizeof(qDumpBuffer)) - 100) flush(); } void QDumper::put(char c) { checkFill(); qDumpBuffer[pos++] = c; } void QDumper::addCommaIfNeeded() { if (pos == 0) return; char c = qDumpBuffer[pos - 1]; if (c == '}' || c == '"' || c == ']') put(','); } void QDumper::putBase64Encoded(const char *buf, int n) { const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef" "ghijklmn" "opqrstuv" "wxyz0123" "456789+/"; const char padchar = '='; int padlen = 0; //int tmpsize = ((n * 4) / 3) + 3; int i = 0; while (i < n) { int chunk = 0; chunk |= int(uchar(buf[i++])) << 16; if (i == n) { padlen = 2; } else { chunk |= int(uchar(buf[i++])) << 8; if (i == n) padlen = 1; else chunk |= int(uchar(buf[i++])); } int j = (chunk & 0x00fc0000) >> 18; int k = (chunk & 0x0003f000) >> 12; int l = (chunk & 0x00000fc0) >> 6; int m = (chunk & 0x0000003f); put(alphabet[j]); put(alphabet[k]); put(padlen > 1 ? padchar : alphabet[l]); put(padlen > 0 ? padchar : alphabet[m]); } } QDumper &QDumper::operator<<(const char *str) { if (!str) return *this << "<null>"; while (*str) put(*(str++)); return *this; } QDumper &QDumper::operator<<(const QByteArray &ba) { putBase64Encoded(ba.constData(), ba.size()); return *this; } QDumper &QDumper::operator<<(const QString &str) { QByteArray ba = str.toUtf8(); putBase64Encoded(ba.constData(), ba.size()); return *this; } void QDumper::disarm() { flush(); success = true; } void QDumper::beginHash() { addCommaIfNeeded(); put('{'); } void QDumper::endHash() { put('}'); } void QDumper::putEllipsis() { addCommaIfNeeded(); *this << "{name=\"<incomplete>\",value=\"\",type=\"" << innertype << "\"}"; } // // Some helpers to keep the dumper code short // // dump property=value pair #undef P #define P(dumper,name,value) \ do { \ dumper.addCommaIfNeeded(); \ dumper << (name) << "=\"" << value << "\""; \ } while (0) // simple string property #undef S #define S(dumper, name, value) \ dumper.beginHash(); \ P(dumper, "name", name); \ P(dumper, "value", value); \ P(dumper, "type", NS"QString"); \ P(dumper, "numchild", "0"); \ P(dumper, "valueencoded", "1"); \ dumper.endHash(); // simple integer property #undef I #define I(dumper, name, value) \ dumper.beginHash(); \ P(dumper, "name", name); \ P(dumper, "value", value); \ P(dumper, "type", "int"); \ P(dumper, "numchild", "0"); \ dumper.endHash(); // simple boolean property #undef BL #define BL(dumper, name, value) \ dumper.beginHash(); \ P(dumper, "name", name); \ P(dumper, "value", (value ? "true" : "false")); \ P(dumper, "type", "bool"); \ P(dumper, "numchild", "0"); \ dumper.endHash(); // a single QChar #undef QC #define QC(dumper, name, value) \ dumper.beginHash(); \ P(dumper, "name", name); \ P(dumper, "value", QString(QLatin1String("'%1' (%2, 0x%3)")) \ .arg(value).arg(value.unicode()).arg(value.unicode(), 0, 16)); \ P(dumper, "valueencoded", "1"); \ P(dumper, "type", NS"QChar"); \ P(dumper, "numchild", "0"); \ dumper.endHash(); #undef TT #define TT(type, value) \ "<tr><td>" << type << "</td><td> : </td><td>" << value << "</td></tr>" static void qDumpUnknown(QDumper &d) { P(d, "iname", d.iname); P(d, "addr", d.data); P(d, "value", "<internal error>"); P(d, "type", d.outertype); P(d, "numchild", "0"); d.disarm(); } static void qDumpInnerValueHelper(QDumper &d, const char *type, const void *addr, const char *key = "value") { type = stripNamespace(type); switch (type[1]) { case 'l': if (isEqual(type, "float")) P(d, key, *(float*)addr); return; case 'n': if (isEqual(type, "int")) P(d, key, *(int*)addr); else if (isEqual(type, "unsigned")) P(d, key, *(unsigned int*)addr); else if (isEqual(type, "unsigned int")) P(d, key, *(unsigned int*)addr); else if (isEqual(type, "unsigned long")) P(d, key, *(unsigned long*)addr); else if (isEqual(type, "unsigned long long")) P(d, key, *(qulonglong*)addr); return; case 'o': if (isEqual(type, "bool")) switch (*(bool*)addr) { case 0: P(d, key, "false"); break; case 1: P(d, key, "true"); break; default: P(d, key, *(bool*)addr); break; } else if (isEqual(type, "double")) P(d, key, *(double*)addr); else if (isEqual(type, "long")) P(d, key, *(long*)addr); else if (isEqual(type, "long long")) P(d, key, *(qulonglong*)addr); return; case 'B': if (isEqual(type, "QByteArray")) { d << key << "encoded=\"1\","; P(d, key, *(QByteArray*)addr); } return; case 'L': if (startsWith(type, "QList<")) { const QListData *ldata = reinterpret_cast<const QListData*>(addr); P(d, "value", "<" << ldata->size() << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", ldata->size()); } return; case 'O': if (isEqual(type, "QObject *")) { if (addr) { const QObject *ob = reinterpret_cast<const QObject *>(addr); P(d, "addr", ob); P(d, "value", ob->objectName()); P(d, "valueencoded", "1"); P(d, "type", NS"QObject"); P(d, "displayedtype", ob->metaObject()->className()); } else { P(d, "value", "0x0"); P(d, "type", NS"QObject *"); } } return; case 'S': if (isEqual(type, "QString")) { d << key << "encoded=\"1\","; P(d, key, *(QString*)addr); } return; default: return; } } static void qDumpInnerValue(QDumper &d, const char *type, const void *addr) { P(d, "addr", addr); P(d, "type", type); if (!type[0]) return; qDumpInnerValueHelper(d, type, addr); } static void qDumpInnerValueOrPointer(QDumper &d, const char *type, const char *strippedtype, const void *addr) { if (strippedtype) { if (deref(addr)) { P(d, "addr", deref(addr)); P(d, "type", strippedtype); qDumpInnerValueHelper(d, strippedtype, deref(addr)); } else { P(d, "addr", addr); P(d, "type", strippedtype); P(d, "value", "<null>"); P(d, "numchild", "0"); } } else { P(d, "addr", addr); P(d, "type", type); qDumpInnerValueHelper(d, type, addr); } } ////////////////////////////////////////////////////////////////////////////// static void qDumpQByteArray(QDumper &d) { const QByteArray &ba = *reinterpret_cast<const QByteArray *>(d.data); if (!ba.isEmpty()) { qCheckAccess(ba.constData()); qCheckAccess(ba.constData() + ba.size()); } if (ba.size() <= 100) P(d, "value", ba); else P(d, "value", ba.left(100) << " <size: " << ba.size() << ", cut...>"); P(d, "valueencoded", "1"); P(d, "type", NS"QByteArray"); P(d, "numchild", ba.size()); P(d, "childtype", "char"); P(d, "childnumchild", "0"); if (d.dumpChildren) { d << ",children=["; char buf[20]; for (int i = 0; i != ba.size(); ++i) { unsigned char c = ba.at(i); unsigned char u = isprint(c) && c != '"' ? c : '?'; sprintf(buf, "%02x (%u '%c')", c, c, u); d.beginHash(); P(d, "name", "[" << i << "]"); P(d, "value", buf); d.endHash(); } d << "]"; } d.disarm(); } static void qDumpQDateTime(QDumper &d) { #ifdef QT_NO_DATESTRING qDumpUnknown(d); #else const QDateTime &date = *reinterpret_cast<const QDateTime *>(d.data); if (date.isNull()) { P(d, "value", "(null)"); } else { P(d, "value", date.toString()); P(d, "valueencoded", "1"); } P(d, "type", NS"QDateTime"); P(d, "numchild", "3"); if (d.dumpChildren) { d << ",children=["; BL(d, "isNull", date.isNull()); I(d, "toTime_t", (long)date.toTime_t()); S(d, "toString", date.toString()); S(d, "toString_(ISO)", date.toString(Qt::ISODate)); S(d, "toString_(SystemLocale)", date.toString(Qt::SystemLocaleDate)); S(d, "toString_(Locale)", date.toString(Qt::LocaleDate)); S(d, "toString", date.toString()); #if 0 d.beginHash(); P(d, "name", "toUTC"); P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")" "->toTimeSpec('"NS"Qt::UTC')"); P(d, "type", NS"QDateTime"); P(d, "numchild", "1"); d.endHash(); #endif #if 0 d.beginHash(); P(d, "name", "toLocalTime"); P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")" "->toTimeSpec('"NS"Qt::LocalTime')"); P(d, "type", NS"QDateTime"); P(d, "numchild", "1"); d.endHash(); #endif d << "]"; } d.disarm(); #endif // ifdef QT_NO_DATESTRING } static void qDumpQDir(QDumper &d) { const QDir &dir = *reinterpret_cast<const QDir *>(d.data); P(d, "value", dir.path()); P(d, "valueencoded", "1"); P(d, "type", NS"QDir"); P(d, "numchild", "3"); if (d.dumpChildren) { d << ",children=["; S(d, "absolutePath", dir.absolutePath()); S(d, "canonicalPath", dir.canonicalPath()); d << "]"; } d.disarm(); } static void qDumpQFile(QDumper &d) { const QFile &file = *reinterpret_cast<const QFile *>(d.data); P(d, "value", file.fileName()); P(d, "valueencoded", "1"); P(d, "type", NS"QFile"); P(d, "numchild", "2"); if (d.dumpChildren) { d << ",children=["; S(d, "fileName", file.fileName()); BL(d, "exists", file.exists()); d << "]"; } d.disarm(); } static void qDumpQFileInfo(QDumper &d) { const QFileInfo &info = *reinterpret_cast<const QFileInfo *>(d.data); P(d, "value", info.filePath()); P(d, "valueencoded", "1"); P(d, "type", NS"QFileInfo"); P(d, "numchild", "3"); if (d.dumpChildren) { d << ",children=["; S(d, "absolutePath", info.absolutePath()); S(d, "absoluteFilePath", info.absoluteFilePath()); S(d, "canonicalPath", info.canonicalPath()); S(d, "canonicalFilePath", info.canonicalFilePath()); S(d, "completeBaseName", info.completeBaseName()); S(d, "completeSuffix", info.completeSuffix()); S(d, "baseName", info.baseName()); #ifdef Q_OS_MACX BL(d, "isBundle", info.isBundle()); S(d, "bundleName", info.bundleName()); #endif S(d, "completeSuffix", info.completeSuffix()); S(d, "fileName", info.fileName()); S(d, "filePath", info.filePath()); S(d, "group", info.group()); S(d, "owner", info.owner()); S(d, "path", info.path()); I(d, "groupid", (long)info.groupId()); I(d, "ownerid", (long)info.ownerId()); //QFile::Permissions permissions () const I(d, "permissions", info.permissions()); //QDir absoluteDir () const //QDir dir () const BL(d, "caching", info.caching()); BL(d, "exists", info.exists()); BL(d, "isAbsolute", info.isAbsolute()); BL(d, "isDir", info.isDir()); BL(d, "isExecutable", info.isExecutable()); BL(d, "isFile", info.isFile()); BL(d, "isHidden", info.isHidden()); BL(d, "isReadable", info.isReadable()); BL(d, "isRelative", info.isRelative()); BL(d, "isRoot", info.isRoot()); BL(d, "isSymLink", info.isSymLink()); BL(d, "isWritable", info.isWritable()); d.beginHash(); P(d, "name", "created"); P(d, "value", info.created().toString()); P(d, "valueencoded", "1"); P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->created()"); P(d, "type", NS"QDateTime"); P(d, "numchild", "1"); d.endHash(); d.beginHash(); P(d, "name", "lastModified"); P(d, "value", info.lastModified().toString()); P(d, "valueencoded", "1"); P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastModified()"); P(d, "type", NS"QDateTime"); P(d, "numchild", "1"); d.endHash(); d.beginHash(); P(d, "name", "lastRead"); P(d, "value", info.lastRead().toString()); P(d, "valueencoded", "1"); P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastRead()"); P(d, "type", NS"QDateTime"); P(d, "numchild", "1"); d.endHash(); d << "]"; } d.disarm(); } bool isOptimizedIntKey(const char *keyType) { return isEqual(keyType, "int") #if defined(Q_BYTE_ORDER) && Q_BYTE_ORDER == Q_LITTLE_ENDIAN || isEqual(keyType, "short") || isEqual(keyType, "ushort") #endif || isEqual(keyType, "uint"); } int hashOffset(bool optimizedIntKey, bool forKey, unsigned keySize, unsigned valueSize) { // int-key optimization, small value struct NodeOS { void *next; uint k; uint v; } nodeOS; // int-key optimiatzion, large value struct NodeOL { void *next; uint k; void *v; } nodeOL; // no optimization, small value struct NodeNS { void *next; uint h; uint k; uint v; } nodeNS; // no optimization, large value struct NodeNL { void *next; uint h; uint k; void *v; } nodeNL; // complex key struct NodeL { void *next; uint h; void *k; void *v; } nodeL; if (forKey) { // offsetof(...,...) not yet in Standard C++ const ulong nodeOSk ( (char *)&nodeOS.k - (char *)&nodeOS ); const ulong nodeOLk ( (char *)&nodeOL.k - (char *)&nodeOL ); const ulong nodeNSk ( (char *)&nodeNS.k - (char *)&nodeNS ); const ulong nodeNLk ( (char *)&nodeNL.k - (char *)&nodeNL ); const ulong nodeLk ( (char *)&nodeL.k - (char *)&nodeL ); if (optimizedIntKey) return valueSize > sizeof(int) ? nodeOLk : nodeOSk; if (keySize > sizeof(int)) return nodeLk; return valueSize > sizeof(int) ? nodeNLk : nodeNSk; } else { const ulong nodeOSv ( (char *)&nodeOS.v - (char *)&nodeOS ); const ulong nodeOLv ( (char *)&nodeOL.v - (char *)&nodeOL ); const ulong nodeNSv ( (char *)&nodeNS.v - (char *)&nodeNS ); const ulong nodeNLv ( (char *)&nodeNL.v - (char *)&nodeNL ); const ulong nodeLv ( (char *)&nodeL.v - (char *)&nodeL ); if (optimizedIntKey) return valueSize > sizeof(int) ? nodeOLv : nodeOSv; if (keySize > sizeof(int)) return nodeLv; return valueSize > sizeof(int) ? nodeNLv : nodeNSv; } } static void qDumpQHash(QDumper &d) { QHashData *h = *reinterpret_cast<QHashData *const*>(d.data); const char *keyType = d.templateParameters[0]; const char *valueType = d.templateParameters[1]; qCheckPointer(h->fakeNext); qCheckPointer(h->buckets); unsigned keySize = d.extraInt[0]; unsigned valueSize = d.extraInt[1]; int n = h->size; if (n < 0) qCheck(false); if (n > 0) { qCheckPointer(h->fakeNext); qCheckPointer(*h->buckets); } P(d, "value", "<" << n << " items>"); P(d, "numchild", n); if (d.dumpChildren) { if (n > 1000) n = 1000; bool simpleKey = isShortKey(keyType); bool simpleValue = isShortKey(valueType); bool opt = isOptimizedIntKey(keyType); int keyOffset = hashOffset(opt, true, keySize, valueSize); int valueOffset = hashOffset(opt, false, keySize, valueSize); P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue << " keySize: " << keyOffset << " valueOffset: " << valueOffset << " opt: " << opt); QHashData::Node *node = h->firstNode(); QHashData::Node *end = reinterpret_cast<QHashData::Node *>(h); int i = 0; d << ",children=["; while (node != end) { d.beginHash(); if (simpleKey) { qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name"); P(d, "nameisindex", "1"); if (simpleValue) qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset)); P(d, "type", valueType); P(d, "addr", addOffset(node, valueOffset)); } else { P(d, "name", "[" << i << "]"); //P(d, "exp", "*(char*)" << node); P(d, "exp", "*('"NS"QHashNode<" << keyType << "," << valueType << " >'*)" << node); P(d, "type", "'"NS"QHashNode<" << keyType << "," << valueType << " >'"); } d.endHash(); ++i; node = QHashData::nextNode(node); } d << "]"; } d.disarm(); } static void qDumpQHashNode(QDumper &d) { const QHashData *h = reinterpret_cast<const QHashData *>(d.data); const char *keyType = d.templateParameters[0]; const char *valueType = d.templateParameters[1]; P(d, "value", ""); P(d, "numchild", 2); if (d.dumpChildren) { unsigned keySize = d.extraInt[0]; unsigned valueSize = d.extraInt[1]; bool opt = isOptimizedIntKey(keyType); int keyOffset = hashOffset(opt, true, keySize, valueSize); int valueOffset = hashOffset(opt, false, keySize, valueSize); // there is a hash specialization in cast the key are integers or shorts d << ",children=["; d.beginHash(); P(d, "name", "key"); P(d, "type", keyType); P(d, "addr", addOffset(h, keyOffset)); d.endHash(); d.beginHash(); P(d, "name", "value"); P(d, "type", valueType); P(d, "addr", addOffset(h, valueOffset)); d.endHash(); d << "]"; } d.disarm(); } static void qDumpQImage(QDumper &d) { #ifdef QT_GUI_LIB const QImage &im = *reinterpret_cast<const QImage *>(d.data); P(d, "value", "(" << im.width() << "x" << im.height() << ")"); P(d, "type", NS"QImage"); P(d, "numchild", "0"); d.disarm(); #else Q_UNUSED(d); #endif } static void qDumpQList(QDumper &d) { // This uses the knowledge that QList<T> has only a single member // of type union { QListData p; QListData::Data *d; }; const QListData &ldata = *reinterpret_cast<const QListData*>(d.data); const QListData::Data *pdata = *reinterpret_cast<const QListData::Data* const*>(d.data); int nn = ldata.size(); if (nn < 0) qCheck(false); if (nn > 0) { qCheckAccess(ldata.d->array); //qCheckAccess(ldata.d->array[0]); //qCheckAccess(ldata.d->array[nn - 1]); #if QT_VERSION >= 0x040400 if (ldata.d->ref._q_value <= 0) qCheck(false); #endif } int n = nn; P(d, "value", "<" << n << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", n); P(d, "childtype", d.innertype); if (d.dumpChildren) { unsigned innerSize = d.extraInt[0]; bool innerTypeIsPointer = isPointerType(d.innertype); QByteArray strippedInnerType = stripPointerType(d.innertype); // The exact condition here is: // QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic // but this data is available neither in the compiled binary nor // in the frontend. // So as first approximation only do the 'isLarge' check: bool isInternal = innerSize <= int(sizeof(void*)) && isMovableType(d.innertype); P(d, "internal", (int)isInternal); P(d, "childtype", d.innertype); if (n > 1000) n = 1000; d << ",children=["; for (int i = 0; i != n; ++i) { d.beginHash(); P(d, "name", "[" << i << "]"); if (innerTypeIsPointer) { void *p = ldata.d->array + i + pdata->begin; if (p) { //P(d, "value","@" << p); qDumpInnerValue(d, strippedInnerType.data(), deref(p)); } else { P(d, "value", "<null>"); P(d, "numchild", "0"); } } else { void *p = ldata.d->array + i + pdata->begin; if (isInternal) { //qDumpInnerValue(d, d.innertype, p); P(d, "addr", p); qDumpInnerValueHelper(d, d.innertype, p); } else { //qDumpInnerValue(d, d.innertype, deref(p)); P(d, "addr", deref(p)); qDumpInnerValueHelper(d, d.innertype, deref(p)); } } d.endHash(); } if (n < nn) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpQLocale(QDumper &d) { const QLocale &locale = *reinterpret_cast<const QLocale *>(d.data); P(d, "value", locale.name()); P(d, "valueencoded", "1"); P(d, "type", NS"QLocale"); P(d, "numchild", "8"); if (d.dumpChildren) { d << ",children=["; d.beginHash(); P(d, "name", "country"); P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->country()"); d.endHash(); d.beginHash(); P(d, "name", "language"); P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->language()"); d.endHash(); d.beginHash(); P(d, "name", "measurementSystem"); P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->measurementSystem()"); d.endHash(); d.beginHash(); P(d, "name", "numberOptions"); P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->numberOptions()"); d.endHash(); S(d, "timeFormat_(short)", locale.timeFormat(QLocale::ShortFormat)); S(d, "timeFormat_(long)", locale.timeFormat(QLocale::LongFormat)); QC(d, "decimalPoint", locale.decimalPoint()); QC(d, "exponential", locale.exponential()); QC(d, "percent", locale.percent()); QC(d, "zeroDigit", locale.zeroDigit()); QC(d, "groupSeparator", locale.groupSeparator()); QC(d, "negativeSign", locale.negativeSign()); d << "]"; } d.disarm(); } static void qDumpQMap(QDumper &d) { QMapData *h = *reinterpret_cast<QMapData *const*>(d.data); const char *keyType = d.templateParameters[0]; const char *valueType = d.templateParameters[1]; int n = h->size; if (n < 0) qCheck(false); if (n > 0) { qCheckAccess(h->backward); qCheckAccess(h->forward[0]); qCheckPointer(h->backward->backward); qCheckPointer(h->forward[0]->backward); } P(d, "value", "<" << n << " items>"); P(d, "numchild", n); if (d.dumpChildren) { if (n > 1000) n = 1000; //unsigned keySize = d.extraInt[0]; //unsigned valueSize = d.extraInt[1]; unsigned mapnodesize = d.extraInt[2]; unsigned valueOff = d.extraInt[3]; bool simpleKey = isShortKey(keyType); bool simpleValue = isShortKey(valueType); // both negative: int keyOffset = 2 * sizeof(void*) - int(mapnodesize); int valueOffset = 2 * sizeof(void*) - int(mapnodesize) + valueOff; P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue << " keyOffset: " << keyOffset << " valueOffset: " << valueOffset << " mapnodesize: " << mapnodesize); d << ",children=["; QMapData::Node *node = reinterpret_cast<QMapData::Node *>(h->forward[0]); QMapData::Node *end = reinterpret_cast<QMapData::Node *>(h); int i = 0; while (node != end) { d.beginHash(); if (simpleKey) { P(d, "type", valueType); qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name"); P(d, "nameisindex", "1"); if (simpleValue) qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset)); P(d, "type", valueType); P(d, "addr", addOffset(node, valueOffset)); } else { P(d, "name", "[" << i << "]"); P(d, "type", NS"QMapNode<" << keyType << "," << valueType << " >"); // actually, any type (even 'char') will do... P(d, "exp", "*('"NS"QMapNode<" << keyType << "," << valueType << " >'*)" << node); //P(d, "exp", "*('"NS"QMapData'*)" << (void*)node); //P(d, "exp", "*(char*)" << (void*)node); // P(d, "addr", node); does not work as gdb fails to parse // e.g. &((*('"NS"QMapNode<QString,Foo>'*)0x616658)) } d.endHash(); ++i; node = node->forward[0]; } d << "]"; } d.disarm(); } static void qDumpQModelIndex(QDumper &d) { const QModelIndex *mi = reinterpret_cast<const QModelIndex *>(d.data); P(d, "type", NS"QModelIndex"); if (mi->isValid()) { P(d, "value", "(" << mi->row() << ", " << mi->column() << ")"); P(d, "numchild", 5); if (d.dumpChildren) { d << ",children=["; I(d, "row", mi->row()); I(d, "column", mi->column()); d.beginHash(); P(d, "name", "parent"); const QModelIndex parent = mi->parent(); if (parent.isValid()) P(d, "value", "(" << mi->row() << ", " << mi->column() << ")"); else P(d, "value", "<invalid>"); P(d, "exp", "(("NSX"QModelIndex"NSY"*)" << d.data << ")->parent()"); P(d, "type", NS"QModelIndex"); P(d, "numchild", "1"); d.endHash(); S(d, "internalId", QString::number(mi->internalId(), 10)); d.beginHash(); P(d, "name", "model"); P(d, "value", static_cast<const void *>(mi->model())); P(d, "type", NS"QAbstractItemModel*"); P(d, "numchild", "1"); d.endHash(); d << "]"; } } else { P(d, "value", "<invalid>"); P(d, "numchild", 0); } d.disarm(); } static void qDumpQMapNode(QDumper &d) { const QMapData *h = reinterpret_cast<const QMapData *>(d.data); const char *keyType = d.templateParameters[0]; const char *valueType = d.templateParameters[1]; qCheckAccess(h->backward); qCheckAccess(h->forward[0]); P(d, "value", ""); P(d, "numchild", 2); if (d.dumpChildren) { //unsigned keySize = d.extraInt[0]; //unsigned valueSize = d.extraInt[1]; unsigned mapnodesize = d.extraInt[2]; unsigned valueOff = d.extraInt[3]; unsigned keyOffset = 2 * sizeof(void*) - mapnodesize; unsigned valueOffset = 2 * sizeof(void*) - mapnodesize + valueOff; d << ",children=["; d.beginHash(); P(d, "name", "key"); qDumpInnerValue(d, keyType, addOffset(h, keyOffset)); d.endHash(); d.beginHash(); P(d, "name", "value"); qDumpInnerValue(d, valueType, addOffset(h, valueOffset)); d.endHash(); d << "]"; } d.disarm(); } static void qDumpQObject(QDumper &d) { const QObject *ob = reinterpret_cast<const QObject *>(d.data); const QMetaObject *mo = ob->metaObject(); unsigned childrenOffset = d.extraInt[0]; P(d, "value", ob->objectName()); P(d, "valueencoded", "1"); P(d, "type", NS"QObject"); P(d, "displayedtype", mo->className()); P(d, "numchild", 4); if (d.dumpChildren) { const QObjectList &children = ob->children(); int slotCount = 0; int signalCount = 0; for (int i = mo->methodCount(); --i >= 0; ) { QMetaMethod::MethodType mt = mo->method(i).methodType(); signalCount += (mt == QMetaMethod::Signal); slotCount += (mt == QMetaMethod::Slot); } d << ",children=["; d.beginHash(); P(d, "name", "properties"); // FIXME: Note that when simply using '(QObject*)' // in the cast below, Gdb/MI _sometimes_ misparses // expressions further down in the tree. P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "type", NS"QObjectPropertyList"); P(d, "value", "<" << mo->propertyCount() << " items>"); P(d, "numchild", mo->propertyCount()); d.endHash(); #if 0 d.beginHash(); P(d, "name", "methods"); P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "value", "<" << mo->methodCount() << " items>"); P(d, "numchild", mo->methodCount()); d.endHash(); #endif #if 0 d.beginHash(); P(d, "name", "senders"); P(d, "exp", "(*(class '"NS"QObjectPrivate'*)" << dfunc(ob) << ")->senders"); P(d, "type", NS"QList<"NS"QObjectPrivateSender>"); d.endHash(); #endif #if PRIVATE_OBJECT_ALLOWED d.beginHash(); P(d, "name", "signals"); P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "type", NS"QObjectSignalList"); P(d, "value", "<" << signalCount << " items>"); P(d, "numchild", signalCount); d.endHash(); d.beginHash(); P(d, "name", "slots"); P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "type", NS"QObjectSlotList"); P(d, "value", "<" << slotCount << " items>"); P(d, "numchild", slotCount); d.endHash(); #endif d.beginHash(); P(d, "name", "children"); // works always, but causes additional traffic on the list //P(d, "exp", "((class '"NS"QObject'*)" << d.data << ")->children()"); // //P(d, "addr", addOffset(dfunc(ob), childrenOffset)); //P(d, "type", NS"QList<QObject *>"); //P(d, "value", "<" << children.size() << " items>"); qDumpInnerValue(d, NS"QList<"NS"QObject *>", addOffset(dfunc(ob), childrenOffset)); P(d, "numchild", children.size()); d.endHash(); #if 0 // Unneeded (and not working): Connections are listes as childen // of the signal or slot they are connected to. // d.beginHash(); // P(d, "name", "connections"); // P(d, "exp", "*(*(class "NS"QObjectPrivate*)" << dfunc(ob) << ")->connectionLists"); // P(d, "type", NS"QVector<"NS"QList<"NS"QObjectPrivate::Connection> >"); // d.endHash(); #endif #if 0 d.beginHash(); P(d, "name", "objectprivate"); P(d, "type", NS"QObjectPrivate"); P(d, "addr", dfunc(ob)); P(d, "value", ""); P(d, "numchild", "1"); d.endHash(); #endif d.beginHash(); P(d, "name", "parent"); qDumpInnerValueHelper(d, NS"QObject *", ob->parent()); d.endHash(); #if 1 d.beginHash(); P(d, "name", "className"); P(d, "value",ob->metaObject()->className()); P(d, "type", ""); P(d, "numchild", "0"); d.endHash(); #endif d << "]"; } d.disarm(); } static void qDumpQObjectPropertyList(QDumper &d) { const QObject *ob = (const QObject *)d.data; const QMetaObject *mo = ob->metaObject(); P(d, "addr", "<synthetic>"); P(d, "type", NS"QObjectPropertyList"); P(d, "numchild", mo->propertyCount()); if (d.dumpChildren) { d << ",children=["; for (int i = mo->propertyCount(); --i >= 0; ) { const QMetaProperty & prop = mo->property(i); d.beginHash(); P(d, "name", prop.name()); P(d, "exp", "((" << mo->className() << "*)" << ob << ")->" << prop.name() << "()"); if (isEqual(prop.typeName(), "QString")) { P(d, "value", prop.read(ob).toString()); P(d, "valueencoded", "1"); P(d, "type", NS"QString"); P(d, "numchild", "0"); } else if (isEqual(prop.typeName(), "bool")) { P(d, "value", (prop.read(ob).toBool() ? "true" : "false")); P(d, "numchild", "0"); } else if (isEqual(prop.typeName(), "int")) { P(d, "value", prop.read(ob).toInt()); P(d, "numchild", "0"); } P(d, "type", prop.typeName()); P(d, "numchild", "1"); d.endHash(); } d << "]"; } d.disarm(); } static void qDumpQObjectMethodList(QDumper &d) { const QObject *ob = (const QObject *)d.data; const QMetaObject *mo = ob->metaObject(); P(d, "addr", "<synthetic>"); P(d, "type", NS"QObjectMethodList"); P(d, "numchild", mo->methodCount()); P(d, "childtype", "QMetaMethod::Method"); P(d, "childnumchild", "0"); if (d.dumpChildren) { d << ",children=["; for (int i = 0; i != mo->methodCount(); ++i) { const QMetaMethod & method = mo->method(i); int mt = method.methodType(); d.beginHash(); P(d, "name", "[" << i << "] " << mo->indexOfMethod(method.signature()) << " " << method.signature()); P(d, "value", (mt == QMetaMethod::Signal ? "<Signal>" : "<Slot>") << " (" << mt << ")"); d.endHash(); } d << "]"; } d.disarm(); } #if PRIVATE_OBJECT_ALLOWED const char * qConnectionTypes[] ={ "auto", "direct", "queued", "autocompat", "blockingqueued" }; #if QT_VERSION >= 0x040400 static const QObjectPrivate::ConnectionList &qConnectionList(const QObject *ob, int signalNumber) { static const QObjectPrivate::ConnectionList emptyList; const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob)); if (!p->connectionLists) return emptyList; typedef QVector<QObjectPrivate::ConnectionList> ConnLists; const ConnLists *lists = reinterpret_cast<const ConnLists *>(p->connectionLists); // there's an optimization making the lists only large enough to hold the // last non-empty item if (signalNumber >= lists->size()) return emptyList; return lists->at(signalNumber); } #endif static void qDumpQObjectSignal(QDumper &d) { unsigned signalNumber = d.extraInt[0]; P(d, "addr", "<synthetic>"); P(d, "numchild", "1"); P(d, "type", NS"QObjectSignal"); #if QT_VERSION >= 0x040400 if (d.dumpChildren) { const QObject *ob = reinterpret_cast<const QObject *>(d.data); d << ",children=["; const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, signalNumber); for (int i = 0; i != connList.size(); ++i) { const QObjectPrivate::Connection &conn = connList.at(i); d.beginHash(); P(d, "name", "[" << i << "] receiver"); qDumpInnerValueHelper(d, NS"QObject *", conn.receiver); d.endHash(); d.beginHash(); P(d, "name", "[" << i << "] slot"); P(d, "type", ""); if (conn.receiver) P(d, "value", conn.receiver->metaObject()->method(conn.method).signature()); else P(d, "value", "<invalid receiver>"); P(d, "numchild", "0"); d.endHash(); d.beginHash(); P(d, "name", "[" << i << "] type"); P(d, "type", ""); P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>"); P(d, "numchild", "0"); d.endHash(); } d << "]"; P(d, "numchild", connList.size()); } #endif d.disarm(); } static void qDumpQObjectSignalList(QDumper &d) { const QObject *ob = reinterpret_cast<const QObject *>(d.data); const QMetaObject *mo = ob->metaObject(); int count = 0; for (int i = mo->methodCount(); --i >= 0; ) count += (mo->method(i).methodType() == QMetaMethod::Signal); P(d, "addr", d.data); P(d, "numchild", count); #if QT_VERSION >= 0x040400 if (d.dumpChildren) { d << ",children=["; for (int i = 0; i != mo->methodCount(); ++i) { const QMetaMethod & method = mo->method(i); if (method.methodType() == QMetaMethod::Signal) { int k = mo->indexOfSignal(method.signature()); const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, k); d.beginHash(); P(d, "name", "[" << k << "]"); P(d, "value", method.signature()); P(d, "numchild", connList.size()); //P(d, "numchild", "1"); P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "type", NS"QObjectSignal"); d.endHash(); } } d << "]"; } #endif d.disarm(); } static void qDumpQObjectSlot(QDumper &d) { int slotNumber = d.extraInt[0]; P(d, "addr", d.data); P(d, "numchild", "1"); P(d, "type", NS"QObjectSlot"); #if QT_VERSION >= 0x040400 if (d.dumpChildren) { d << ",children=["; int numchild = 0; const QObject *ob = reinterpret_cast<const QObject *>(d.data); const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob)); for (int s = 0; s != p->senders.size(); ++s) { const QObjectPrivate::Sender &sender = p->senders.at(s); const QObjectPrivate::ConnectionList &connList = qConnectionList(sender.sender, sender.signal); for (int i = 0; i != connList.size(); ++i) { const QObjectPrivate::Connection &conn = connList.at(i); if (conn.receiver == ob && conn.method == slotNumber) { ++numchild; const QMetaMethod & method = sender.sender->metaObject()->method(sender.signal); d.beginHash(); P(d, "name", "[" << s << "] sender"); qDumpInnerValueHelper(d, NS"QObject *", sender.sender); d.endHash(); d.beginHash(); P(d, "name", "[" << s << "] signal"); P(d, "type", ""); P(d, "value", method.signature()); P(d, "numchild", "0"); d.endHash(); d.beginHash(); P(d, "name", "[" << s << "] type"); P(d, "type", ""); P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>"); P(d, "numchild", "0"); d.endHash(); } } } d << "]"; P(d, "numchild", numchild); } #endif d.disarm(); } static void qDumpQObjectSlotList(QDumper &d) { const QObject *ob = reinterpret_cast<const QObject *>(d.data); #if QT_VERSION >= 0x040400 const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob)); #endif const QMetaObject *mo = ob->metaObject(); int count = 0; for (int i = mo->methodCount(); --i >= 0; ) count += (mo->method(i).methodType() == QMetaMethod::Slot); P(d, "addr", d.data); P(d, "numchild", count); #if QT_VERSION >= 0x040400 if (d.dumpChildren) { d << ",children=["; for (int i = 0; i != mo->methodCount(); ++i) { const QMetaMethod & method = mo->method(i); if (method.methodType() == QMetaMethod::Slot) { d.beginHash(); int k = mo->indexOfSlot(method.signature()); P(d, "name", "[" << k << "]"); P(d, "value", method.signature()); // count senders. expensive... int numchild = 0; for (int s = 0; s != p->senders.size(); ++s) { const QObjectPrivate::Sender & sender = p->senders.at(s); const QObjectPrivate::ConnectionList &connList = qConnectionList(sender.sender, sender.signal); for (int c = 0; c != connList.size(); ++c) { const QObjectPrivate::Connection &conn = connList.at(c); if (conn.receiver == ob && conn.method == k) ++numchild; } } P(d, "numchild", numchild); P(d, "exp", "*(class '"NS"QObject'*)" << d.data); P(d, "type", NS"QObjectSlot"); d.endHash(); } } d << "]"; } #endif d.disarm(); } #endif // PRIVATE_OBJECT_ALLOWED static void qDumpQPixmap(QDumper &d) { #ifdef QT_GUI_LIB const QPixmap &im = *reinterpret_cast<const QPixmap *>(d.data); P(d, "value", "(" << im.width() << "x" << im.height() << ")"); P(d, "type", NS"QPixmap"); P(d, "numchild", "0"); d.disarm(); #else Q_UNUSED(d); #endif } static void qDumpQSet(QDumper &d) { // This uses the knowledge that QHash<T> has only a single member // of union { QHashData *d; QHashNode<Key, T> *e; }; QHashData *hd = *(QHashData**)d.data; QHashData::Node *node = hd->firstNode(); int n = hd->size; if (n < 0) qCheck(false); if (n > 0) { qCheckAccess(node); qCheckPointer(node->next); } P(d, "value", "<" << n << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", 2 * n); if (d.dumpChildren) { if (n > 100) n = 100; d << ",children=["; int i = 0; for (int bucket = 0; bucket != hd->numBuckets && i <= 10000; ++bucket) { for (node = hd->buckets[bucket]; node->next; node = node->next) { d.beginHash(); P(d, "name", "[" << i << "]"); P(d, "type", d.innertype); P(d, "exp", "(('"NS"QHashNode<" << d.innertype << ","NS"QHashDummyValue>'*)" << static_cast<const void*>(node) << ")->key" ); d.endHash(); ++i; if (i > 10000) { d.putEllipsis(); break; } } } d << "]"; } d.disarm(); } static void qDumpQString(QDumper &d) { const QString &str = *reinterpret_cast<const QString *>(d.data); if (!str.isEmpty()) { qCheckAccess(str.unicode()); qCheckAccess(str.unicode() + str.size()); } P(d, "value", str); P(d, "valueencoded", "1"); P(d, "type", NS"QString"); //P(d, "editvalue", str); // handled generically below P(d, "numchild", "0"); d.disarm(); } static void qDumpQStringList(QDumper &d) { const QStringList &list = *reinterpret_cast<const QStringList *>(d.data); int n = list.size(); if (n < 0) qCheck(false); if (n > 0) { qCheckAccess(&list.front()); qCheckAccess(&list.back()); } P(d, "value", "<" << n << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", n); P(d, "childtype", NS"QString"); P(d, "childnumchild", "0"); if (d.dumpChildren) { if (n > 1000) n = 1000; d << ",children=["; for (int i = 0; i != n; ++i) { d.beginHash(); P(d, "name", "[" << i << "]"); P(d, "value", list[i]); P(d, "valueencoded", "1"); d.endHash(); } if (n < list.size()) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpQTextCodec(QDumper &d) { const QTextCodec &codec = *reinterpret_cast<const QTextCodec *>(d.data); P(d, "value", codec.name()); P(d, "valueencoded", "1"); P(d, "type", NS"QTextCodec"); P(d, "numchild", "2"); if (d.dumpChildren) { d << ",children=["; S(d, "name", codec.name()); I(d, "mibEnum", codec.mibEnum()); d << "]"; } d.disarm(); } static void qDumpQVariantHelper(const void *data, QString *value, QString *exp, int *numchild) { const QVariant &v = *reinterpret_cast<const QVariant *>(data); switch (v.type()) { case QVariant::Invalid: *value = QLatin1String("<invalid>"); *numchild = 0; break; case QVariant::String: *value = QLatin1Char('"') + v.toString() + QLatin1Char('"'); *numchild = 0; break; case QVariant::StringList: *exp = QString(QLatin1String("((QVariant*)%1)->d.data.c")) .arg((quintptr)data); *numchild = v.toStringList().size(); break; case QVariant::Int: *value = QString::number(v.toInt()); *numchild= 0; break; case QVariant::Double: *value = QString::number(v.toDouble()); *numchild = 0; break; default: { char buf[1000]; const char *format = (v.typeName()[0] == 'Q') ? "'"NS"%s "NS"qVariantValue<"NS"%s >'(*('"NS"QVariant'*)%p)" : "'%s "NS"qVariantValue<%s >'(*('"NS"QVariant'*)%p)"; qsnprintf(buf, sizeof(buf) - 1, format, v.typeName(), v.typeName(), data); *exp = QLatin1String(buf); *numchild = 1; break; } } } static void qDumpQVariant(QDumper &d) { const QVariant &v = *reinterpret_cast<const QVariant *>(d.data); QString value; QString exp; int numchild = 0; qDumpQVariantHelper(d.data, &value, &exp, &numchild); bool isInvalid = (v.typeName() == 0); if (isInvalid) { P(d, "value", "(invalid)"); } else if (value.isEmpty()) { P(d, "value", "(" << v.typeName() << ") " << qPrintable(value)); } else { QByteArray ba; ba += '('; ba += v.typeName(); ba += ") "; ba += qPrintable(value); P(d, "value", ba); P(d, "valueencoded", "1"); } P(d, "type", NS"QVariant"); P(d, "numchild", (isInvalid ? "0" : "1")); if (d.dumpChildren) { d << ",children=["; d.beginHash(); P(d, "name", "value"); if (!exp.isEmpty()) P(d, "exp", qPrintable(exp)); if (!value.isEmpty()) { P(d, "value", value); P(d, "valueencoded", "1"); } P(d, "type", v.typeName()); P(d, "numchild", numchild); d.endHash(); d << "]"; } d.disarm(); } static void qDumpQVector(QDumper &d) { QVectorData *v = *reinterpret_cast<QVectorData *const*>(d.data); // Try to provoke segfaults early to prevent the frontend // from asking for unavailable child details int nn = v->size; if (nn < 0) qCheck(false); if (nn > 0) { //qCheckAccess(&vec.front()); //qCheckAccess(&vec.back()); } unsigned innersize = d.extraInt[0]; unsigned typeddatasize = d.extraInt[1]; int n = nn; P(d, "value", "<" << n << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", n); if (d.dumpChildren) { QByteArray strippedInnerType = stripPointerType(d.innertype); const char *stripped = isPointerType(d.innertype) ? strippedInnerType.data() : 0; if (n > 1000) n = 1000; d << ",children=["; for (int i = 0; i != n; ++i) { d.beginHash(); P(d, "name", "[" << i << "]"); qDumpInnerValueOrPointer(d, d.innertype, stripped, addOffset(v, i * innersize + typeddatasize)); d.endHash(); } if (n < nn) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpStdList(QDumper &d) { const std::list<int> &list = *reinterpret_cast<const std::list<int> *>(d.data); const void *p = d.data; qCheckAccess(p); p = deref(p); qCheckAccess(p); p = deref(p); qCheckAccess(p); p = deref(addOffset(d.data, sizeof(void*))); qCheckAccess(p); p = deref(addOffset(p, sizeof(void*))); qCheckAccess(p); p = deref(addOffset(p, sizeof(void*))); qCheckAccess(p); int nn = 0; std::list<int>::const_iterator it = list.begin(); for (; nn < 101 && it != list.end(); ++nn, ++it) qCheckAccess(it.operator->()); if (nn > 100) P(d, "value", "<more than 100 items>"); else P(d, "value", "<" << nn << " items>"); P(d, "numchild", nn); P(d, "valuedisabled", "true"); if (d.dumpChildren) { QByteArray strippedInnerType = stripPointerType(d.innertype); const char *stripped = isPointerType(d.innertype) ? strippedInnerType.data() : 0; d << ",children=["; it = list.begin(); for (int i = 0; i < 1000 && it != list.end(); ++i, ++it) { d.beginHash(); P(d, "name", "[" << i << "]"); qDumpInnerValueOrPointer(d, d.innertype, stripped, it.operator->()); d.endHash(); } if (it != list.end()) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpStdMap(QDumper &d) { typedef std::map<int, int> DummyType; const DummyType &map = *reinterpret_cast<const DummyType*>(d.data); const char *keyType = d.templateParameters[0]; const char *valueType = d.templateParameters[1]; const void *p = d.data; qCheckAccess(p); p = deref(p); int nn = map.size(); qCheck(nn >= 0); DummyType::const_iterator it = map.begin(); for (int i = 0; i < nn && i < 10 && it != map.end(); ++i, ++it) qCheckAccess(it.operator->()); QByteArray strippedInnerType = stripPointerType(d.innertype); P(d, "numchild", nn); P(d, "value", "<" << nn << " items>"); P(d, "valuedisabled", "true"); P(d, "valueoffset", d.extraInt[2]); if (d.dumpChildren) { bool simpleKey = isSimpleType(keyType); bool simpleValue = isShortKey(valueType); int valueOffset = d.extraInt[2]; d << ",children=["; it = map.begin(); for (int i = 0; i < 1000 && it != map.end(); ++i, ++it) { const void *node = it.operator->(); if (simpleKey) { d.beginHash(); P(d, "type", valueType); qDumpInnerValueHelper(d, keyType, node, "name"); P(d, "nameisindex", "1"); if (simpleValue) qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset)); P(d, "addr", addOffset(node, valueOffset)); d.endHash(); } else { d.beginHash(); P(d, "name", "[" << i << "]"); P(d, "addr", it.operator->()); P(d, "type", "std::pair<const " << keyType << "," << valueType << " >"); d.endHash(); } } if (it != map.end()) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpStdString(QDumper &d) { const std::string &str = *reinterpret_cast<const std::string *>(d.data); if (!str.empty()) { qCheckAccess(str.c_str()); qCheckAccess(str.c_str() + str.size() - 1); } d << ",value=\""; d.putBase64Encoded(str.c_str(), str.size()); d << "\""; P(d, "valueencoded", "1"); P(d, "type", "std::string"); P(d, "numchild", "0"); d.disarm(); } static void qDumpStdWString(QDumper &d) { const std::wstring &str = *reinterpret_cast<const std::wstring *>(d.data); if (!str.empty()) { qCheckAccess(str.c_str()); qCheckAccess(str.c_str() + str.size() - 1); } d << "value=\""; d.putBase64Encoded((const char *)str.c_str(), str.size() * sizeof(wchar_t)); d << "\""; P(d, "valueencoded", (sizeof(wchar_t) == 2 ? "2" : "3")); P(d, "type", "std::wstring"); P(d, "numchild", "0"); d.disarm(); } static void qDumpStdVector(QDumper &d) { // Correct type would be something like: // std::_Vector_base<int,std::allocator<int, std::allocator<int> >>::_Vector_impl struct VectorImpl { char *start; char *finish; char *end_of_storage; }; const VectorImpl *v = static_cast<const VectorImpl *>(d.data); // Try to provoke segfaults early to prevent the frontend // from asking for unavailable child details int nn = (v->finish - v->start) / d.extraInt[0]; if (nn < 0) qCheck(false); if (nn > 0) { qCheckAccess(v->start); qCheckAccess(v->finish); qCheckAccess(v->end_of_storage); } int n = nn; P(d, "value", "<" << n << " items>"); P(d, "valuedisabled", "true"); P(d, "numchild", n); if (d.dumpChildren) { unsigned innersize = d.extraInt[0]; QByteArray strippedInnerType = stripPointerType(d.innertype); const char *stripped = isPointerType(d.innertype) ? strippedInnerType.data() : 0; if (n > 1000) n = 1000; d << ",children=["; for (int i = 0; i != n; ++i) { d.beginHash(); P(d, "name", "[" << i << "]"); qDumpInnerValueOrPointer(d, d.innertype, stripped, addOffset(v->start, i * innersize)); d.endHash(); } if (n < nn) d.putEllipsis(); d << "]"; } d.disarm(); } static void qDumpStdVectorBool(QDumper &d) { // FIXME return qDumpStdVector(d); } static void handleProtocolVersion2and3(QDumper & d) { if (!d.outertype[0]) { qDumpUnknown(d); return; } d.setupTemplateParameters(); P(d, "iname", d.iname); P(d, "addr", d.data); #ifdef QT_NO_QDATASTREAM if (d.protocolVersion == 3) { QVariant::Type type = QVariant::nameToType(d.outertype); if (type != QVariant::Invalid) { QVariant v(type, d.data); QByteArray ba; QDataStream ds(&ba, QIODevice::WriteOnly); ds << v; P(d, "editvalue", ba); } } #endif const char *type = stripNamespace(d.outertype); // type[0] is usally 'Q', so don't use it switch (type[1]) { case 'B': if (isEqual(type, "QByteArray")) qDumpQByteArray(d); break; case 'D': if (isEqual(type, "QDateTime")) qDumpQDateTime(d); else if (isEqual(type, "QDir")) qDumpQDir(d); break; case 'F': if (isEqual(type, "QFile")) qDumpQFile(d); else if (isEqual(type, "QFileInfo")) qDumpQFileInfo(d); break; case 'H': if (isEqual(type, "QHash")) qDumpQHash(d); else if (isEqual(type, "QHashNode")) qDumpQHashNode(d); break; case 'I': if (isEqual(type, "QImage")) qDumpQImage(d); break; case 'L': if (isEqual(type, "QList")) qDumpQList(d); else if (isEqual(type, "QLocale")) qDumpQLocale(d); break; case 'M': if (isEqual(type, "QMap")) qDumpQMap(d); else if (isEqual(type, "QMapNode")) qDumpQMapNode(d); else if (isEqual(type, "QModelIndex")) qDumpQModelIndex(d); break; case 'O': if (isEqual(type, "QObject")) qDumpQObject(d); else if (isEqual(type, "QObjectPropertyList")) qDumpQObjectPropertyList(d); else if (isEqual(type, "QObjectMethodList")) qDumpQObjectMethodList(d); #if PRIVATE_OBJECT_ALLOWED else if (isEqual(type, "QObjectSignal")) qDumpQObjectSignal(d); else if (isEqual(type, "QObjectSignalList")) qDumpQObjectSignalList(d); else if (isEqual(type, "QObjectSlot")) qDumpQObjectSlot(d); else if (isEqual(type, "QObjectSlotList")) qDumpQObjectSlotList(d); #endif break; case 'P': if (isEqual(type, "QPixmap")) qDumpQPixmap(d); break; case 'S': if (isEqual(type, "QSet")) qDumpQSet(d); else if (isEqual(type, "QString")) qDumpQString(d); else if (isEqual(type, "QStringList")) qDumpQStringList(d); break; case 'T': if (isEqual(type, "QTextCodec")) qDumpQTextCodec(d); break; case 'V': if (isEqual(type, "QVariant")) qDumpQVariant(d); else if (isEqual(type, "QVector")) qDumpQVector(d); break; case 's': if (isEqual(type, "wstring")) qDumpStdWString(d); break; case 't': if (isEqual(type, "std::vector")) qDumpStdVector(d); else if (isEqual(type, "std::vector::bool")) qDumpStdVectorBool(d); else if (isEqual(type, "std::list")) qDumpStdList(d); else if (isEqual(type, "std::map")) qDumpStdMap(d); else if (isEqual(type, "std::string") || isEqual(type, "string")) qDumpStdString(d); else if (isEqual(type, "std::wstring")) qDumpStdWString(d); break; } if (!d.success) qDumpUnknown(d); } } // anonymous namespace extern "C" Q_DECL_EXPORT void qDumpObjectData440( int protocolVersion, int token, void *data, bool dumpChildren, int extraInt0, int extraInt1, int extraInt2, int extraInt3) { if (protocolVersion == 1) { QDumper d; d.protocolVersion = protocolVersion; d.token = token; //qDebug() << "SOCKET: after connect: state: " << qDumperSocket.state(); // simpledumpers is a list of all available dumpers that are // _not_ templates. templates currently require special // hardcoded handling in the debugger plugin. // don't mention them here in this list d << "simpledumpers=[" "\""NS"QByteArray\"," "\""NS"QDir\"," "\""NS"QImage\"," "\""NS"QFile\"," "\""NS"QFileInfo\"," "\""NS"QLocale\"," "\""NS"QModelIndex\"," //"\""NS"QHash\"," // handled on GH side //"\""NS"QHashNode\"," //"\""NS"QMap\"," // handled on GH side //"\""NS"QMapNode\"," "\""NS"QObject\"," "\""NS"QObjectMethodList\"," // hack to get nested properties display "\""NS"QObjectPropertyList\"," #if PRIVATE_OBJECT_ALLOWED "\""NS"QObjectSignal\"," "\""NS"QObjectSignalList\"," "\""NS"QObjectSlot\"," "\""NS"QObjectSlotList\"," #endif // PRIVATE_OBJECT_ALLOWED "\""NS"QString\"," "\""NS"QStringList\"," "\""NS"QTextCodec\"," "\""NS"QVariant\"," "\""NS"QWidget\"," "\""NS"QDateTime\"," "\"string\"," "\"wstring\"," "\"std::string\"," "\"std::wstring\"," // << "\""NS"QRegion\"," "]"; d << ",namespace=\""NS"\""; d.disarm(); } else if (protocolVersion == 2 || protocolVersion == 3) { QDumper d; d.protocolVersion = protocolVersion; d.token = token; d.data = data; d.dumpChildren = dumpChildren; d.extraInt[0] = extraInt0; d.extraInt[1] = extraInt1; d.extraInt[2] = extraInt2; d.extraInt[3] = extraInt3; const char *inbuffer = qDumpInBuffer; d.outertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer; d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer; d.exp = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer; d.innertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer; d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer; handleProtocolVersion2and3(d); } else { qDebug() << "Unsupported protocol version" << protocolVersion; } }
30.595762
103
0.511683
frooms
ca1c14abb3bd707028de6793c56e9d0ecc84737c
4,446
hpp
C++
include/aikido/statespace/SE2.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
include/aikido/statespace/SE2.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
include/aikido/statespace/SE2.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#ifndef AIKIDO_STATESPACE_SE2STATESPACE_HPP_ #define AIKIDO_STATESPACE_SE2STATESPACE_HPP_ #include <Eigen/Geometry> #include "aikido/statespace/ScopedState.hpp" #include "aikido/statespace/StateSpace.hpp" namespace aikido { namespace statespace { /// Defined in detail/SE2-impl.hpp template <class> class SE2StateHandle; /// The two-dimensional special Euclidean group SE(2), i.e. the space of planar /// rigid body transformations. Note that the group operation for SE(2) differs /// from the group operation of the Cartesian product space R^2 x SO(2) because /// it is constructed through the semi-direct product. class SE2 : public virtual StateSpace { public: class State : public StateSpace::State { public: using Isometry2d = Eigen::Transform<double, 2, Eigen::Isometry, Eigen::DontAlign>; /// Constructs the identity element. State(); ~State() = default; /// Constructs the state from an Eigen transformation object. /// /// \param _transform Eigen transformation explicit State(const Isometry2d& _transform); /// Sets value to an Eigen transfomation object. /// /// \param _transform Eigen transformation void setIsometry(const Isometry2d& _transform); /// Gets value as an Eigen transformation object. /// /// \return Eigen trasnformation const Isometry2d& getIsometry() const; private: Isometry2d mTransform; friend class SE2; }; using StateHandle = SE2StateHandle<State>; using StateHandleConst = SE2StateHandle<const State>; using ScopedState = statespace::ScopedState<StateHandle>; using ScopedStateConst = statespace::ScopedState<StateHandleConst>; using StateSpace::compose; using Isometry2d = State::Isometry2d; /// Constructs a state space representing SE(2). SE2() = default; /// Helper function to create a \c ScopedState. /// /// \return new \c ScopedState ScopedState createState() const; /// Creates an identical clone of \c stateIn. ScopedState cloneState(const StateSpace::State* stateIn) const; /// Gets value as an Eigen transformation object. /// /// \param _state a \c State in this state space /// \return Eigen transformation const Isometry2d& getIsometry(const State* _state) const; /// Sets value to an Eigen transfomation object. /// /// \param _state a \c State in this state space /// \param _transform Eigen transformation void setIsometry(State* _state, const Isometry2d& _transform) const; // Documentation inherited. std::size_t getStateSizeInBytes() const override; // Documentation inherited. StateSpace::State* allocateStateInBuffer(void* _buffer) const override; // Documentation inherited. void freeStateInBuffer(StateSpace::State* _state) const override; // Documentation inherited. void compose( const StateSpace::State* _state1, const StateSpace::State* _state2, StateSpace::State* _out) const override; // Documentation inherited void getIdentity(StateSpace::State* _out) const override; // Documentation inherited void getInverse( const StateSpace::State* _in, StateSpace::State* _out) const override; // Documentation inherited std::size_t getDimension() const override; // Documentation inherited void copyState( const StateSpace::State* _source, StateSpace::State* _destination) const override; /// Exponential mapping of Lie algebra element to a Lie group element. The /// tangent space is parameterized a planar twist of the form (translation, /// translation, rotation). /// /// \param _tangent element of the tangent space /// \param[out] _out corresponding element of the Lie group void expMap( const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override; /// Log mapping of Lie group element to a Lie algebra element. The tangent /// space is parameterized as a planar twist of the form (translation, /// translation, rotation). /// /// \param _state element of this Lie group /// \param[out] _tangent corresponding element of the tangent space void logMap(const StateSpace::State* _state, Eigen::VectorXd& _tangent) const override; /// Print the state. Format: [x, y, theta] void print(const StateSpace::State* _state, std::ostream& _os) const override; }; } // namespace statespace } // namespace aikido #include "detail/SE2-impl.hpp" #endif // ifndef AIKIDO_STATESPACE_SE2STATESPACE_HPP_
30.662069
80
0.724022
personalrobotics
ca20d5d8ec321839eedc607acf85098ea9bba148
14,710
cpp
C++
clang/test/OpenMP/taskgroup_task_reduction_codegen.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
clang/test/OpenMP/taskgroup_task_reduction_codegen.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
clang/test/OpenMP/taskgroup_task_reduction_codegen.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
// RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple x86_64-apple-darwin10 | FileCheck %s --check-prefix=CHECK --check-prefix=DEBUG // RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c++ -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple x86_64-apple-darwin10 | FileCheck --check-prefix SIMD-ONLY0 %s // SIMD-ONLY0-NOT: {{__kmpc|__tgt}} // expected-no-diagnostics #ifndef HEADER #define HEADER typedef void **omp_allocator_handle_t; extern const omp_allocator_handle_t omp_null_allocator; extern const omp_allocator_handle_t omp_default_mem_alloc; extern const omp_allocator_handle_t omp_large_cap_mem_alloc; extern const omp_allocator_handle_t omp_const_mem_alloc; extern const omp_allocator_handle_t omp_high_bw_mem_alloc; extern const omp_allocator_handle_t omp_low_lat_mem_alloc; extern const omp_allocator_handle_t omp_cgroup_mem_alloc; extern const omp_allocator_handle_t omp_pteam_mem_alloc; extern const omp_allocator_handle_t omp_thread_mem_alloc; // CHECK-DAG: @reduction_size.[[ID:.+]]_[[CID:[0-9]+]].artificial. // CHECK-DAG: @reduction_size.[[ID]]_[[CID]].artificial..cache. struct S { int a; S() : a(0) {} S(const S&) {} S& operator=(const S&) {return *this;} ~S() {} friend S operator+(const S&a, const S&b) {return a;} }; int main(int argc, char **argv) { int a; float b; S c[5]; short d[argc]; #pragma omp taskgroup allocate(omp_pteam_mem_alloc: a) task_reduction(+: a, b, argc) { #pragma omp taskgroup task_reduction(-:c, d) ; } return 0; } // CHECK-LABEL: @main // CHECK: alloca i32, // CHECK: [[ARGC_ADDR:%.+]] = alloca i32, // CHECK: [[ARGV_ADDR:%.+]] = alloca i8**, // CHECK: [[A:%.+]] = alloca i32, // CHECK: [[B:%.+]] = alloca float, // CHECK: [[C:%.+]] = alloca [5 x %struct.S], // CHECK: [[RD_IN1:%.+]] = alloca [3 x [[T1:%[^,]+]]], // CHECK: [[TD1:%.+]] = alloca i8*, // CHECK: [[RD_IN2:%.+]] = alloca [2 x [[T2:%[^,]+]]], // CHECK: [[TD2:%.+]] = alloca i8*, // CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* // CHECK: [[VLA:%.+]] = alloca i16, i64 [[VLA_SIZE:%[^,]+]], // CHECK: call void @__kmpc_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]]) // CHECK-DAG: [[BC_A:%.+]] = bitcast i32* [[A]] to i8* // CHECK-DAG: store i8* [[BC_A]], i8** [[A_REF:[^,]+]], // CHECK-DAG: [[A_REF]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[BC_A:%.+]] = bitcast i32* [[A]] to i8* // CHECK-DAG: store i8* [[BC_A]], i8** [[A_REF:[^,]+]], // CHECK-DAG: [[A_REF]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 1 // CHECK-DAG: [[GEPA]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64 // CHECK-DAG: [[TMP6:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 2 // CHECK-DAG: store i64 4, i64* [[TMP6]], // CHECK-DAG: [[TMP7:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 3 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[AINIT:.+]] to i8*), i8** [[TMP7]], // CHECK-DAG: [[TMP8:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 4 // CHECK-DAG: store i8* null, i8** [[TMP8]], // CHECK-DAG: [[TMP9:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 5 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ACOMB:.+]] to i8*), i8** [[TMP9]], // CHECK-DAG: [[TMP10:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 6 // CHECK-DAG: [[TMP11:%.+]] = bitcast i32* [[TMP10]] to i8* // CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP11]], i8 0, i64 4, i1 false) // CHECK-DAG: [[TMP13:%.+]] = bitcast float* [[B]] to i8* // CHECK-DAG: store i8* [[TMP13]], i8** [[TMP12:%[^,]+]], // CHECK-DAG: [[TMP12]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[TMP13:%.+]] = bitcast float* [[B]] to i8* // CHECK-DAG: store i8* [[TMP13]], i8** [[TMP12:%[^,]+]], // CHECK-DAG: [[TMP12]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 1 // CHECK-DAG: [[GEPB]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64 // CHECK-DAG: [[TMP14:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 2 // CHECK-DAG: store i64 4, i64* [[TMP14]], // CHECK-DAG: [[TMP15:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 3 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[BINIT:.+]] to i8*), i8** [[TMP15]], // CHECK-DAG: [[TMP16:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 4 // CHECK-DAG: store i8* null, i8** [[TMP16]], // CHECK-DAG: [[TMP17:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 5 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[BCOMB:.+]] to i8*), i8** [[TMP17]], // CHECK-DAG: [[TMP18:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 6 // CHECK-DAG: [[TMP19:%.+]] = bitcast i32* [[TMP18]] to i8* // CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP19]], i8 0, i64 4, i1 false) // CHECK-DAG: [[TMP21:%.+]] = bitcast i32* [[ARGC_ADDR]] to i8* // CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]], // CHECK-DAG: [[TMP20]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[TMP21:%.+]] = bitcast i32* [[ARGC_ADDR]] to i8* // CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]], // CHECK-DAG: [[TMP20]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 1 // CHECK-DAG: [[GEPARGC]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64 // CHECK-DAG: [[TMP22:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 2 // CHECK-DAG: store i64 4, i64* [[TMP22]], // CHECK-DAG: [[TMP23:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 3 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ARGCINIT:.+]] to i8*), i8** [[TMP23]], // CHECK-DAG: [[TMP24:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 4 // CHECK-DAG: store i8* null, i8** [[TMP24]], // CHECK-DAG: [[TMP25:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 5 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ARGCCOMB:.+]] to i8*), i8** [[TMP25]], // CHECK-DAG: [[TMP26:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 6 // CHECK-DAG: [[TMP27:%.+]] = bitcast i32* [[TMP26]] to i8* // CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP27]], i8 0, i64 4, i1 false) // CHECK-DAG: [[TMP28:%.+]] = bitcast [3 x [[T1]]]* [[RD_IN1]] to i8* // CHECK-DAG: [[TMP29:%.+]] = call i8* @__kmpc_taskred_init(i32 [[GTID]], i32 3, i8* [[TMP28]]) // DEBUG-DAG: call void @llvm.dbg.declare(metadata i8** [[TD1]], // CHECK-DAG: store i8* [[TMP29]], i8** [[TD1]], // CHECK-DAG: call void @__kmpc_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]]) // CHECK-DAG: [[TMP31:%.+]] = bitcast [5 x %struct.S]* [[C]] to i8* // CHECK-DAG: store i8* [[TMP31]], i8** [[TMP30:%[^,]+]], // CHECK-DAG: [[TMP30]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[TMP31:%.+]] = bitcast [5 x %struct.S]* [[C]] to i8* // CHECK-DAG: store i8* [[TMP31]], i8** [[TMP30:%[^,]+]], // CHECK-DAG: [[TMP30]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 1 // CHECK-DAG: [[GEPC]] = getelementptr inbounds [2 x [[T2]]], [2 x [[T2]]]* [[RD_IN2]], i64 0, i64 // CHECK-DAG: [[TMP32:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 2 // CHECK-DAG: store i64 20, i64* [[TMP32]], // CHECK-DAG: [[TMP33:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 3 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[CINIT:.+]] to i8*), i8** [[TMP33]], // CHECK-DAG: [[TMP34:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 4 // CHECK-DAG: store i8* bitcast (void (i8*)* @[[CFINI:.+]] to i8*), i8** [[TMP34]], // CHECK-DAG: [[TMP35:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 5 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[CCOMB:.+]] to i8*), i8** [[TMP35]], // CHECK-DAG: [[TMP36:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 6 // CHECK-DAG: [[TMP37:%.+]] = bitcast i32* [[TMP36]] to i8* // CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP37]], i8 0, i64 4, i1 false) // CHECK-DAG: [[TMP39:%.+]] = bitcast i16* [[VLA]] to i8* // CHECK-DAG: store i8* [[TMP39]], i8** [[TMP38:%[^,]+]], // CHECK-DAG: [[TMP38]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[TMP39:%.+]] = bitcast i16* [[VLA]] to i8* // CHECK-DAG: store i8* [[TMP39]], i8** [[TMP38:%[^,]+]], // CHECK-DAG: [[TMP38]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 1 // CHECK-DAG: [[GEPVLA]] = getelementptr inbounds [2 x [[T2]]], [2 x [[T2]]]* [[RD_IN2]], i64 0, i64 // CHECK-DAG: [[TMP40:%.+]] = mul nuw i64 [[VLA_SIZE]], 2 // CHECK-DAG: [[TMP41:%.+]] = udiv exact i64 [[TMP40]], ptrtoint (i16* getelementptr (i16, i16* null, i32 1) to i64) // CHECK-DAG: [[TMP42:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 2 // CHECK-DAG: store i64 [[TMP40]], i64* [[TMP42]], // CHECK-DAG: [[TMP43:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 3 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[VLAINIT:.+]] to i8*), i8** [[TMP43]], // CHECK-DAG: [[TMP44:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 4 // CHECK-DAG: store i8* null, i8** [[TMP44]], // CHECK-DAG: [[TMP45:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 5 // CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[VLACOMB:.+]] to i8*), i8** [[TMP45]], // CHECK-DAG: [[TMP46:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 6 // CHECK-DAG: store i32 1, i32* [[TMP46]], // CHECK: [[TMP47:%.+]] = bitcast [2 x [[T2]]]* [[RD_IN2]] to i8* // CHECK: [[TMP48:%.+]] = call i8* @__kmpc_taskred_init(i32 [[GTID]], i32 2, i8* [[TMP47]]) // CHECK: store i8* [[TMP48]], i8** [[TD2]], // CHECK: call void @__kmpc_end_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]]) // CHECK: call void @__kmpc_end_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]]) // CHECK-DAG: define internal void @[[AINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}}) // CHECK-DAG: store i32 0, i32* % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[ACOMB]](i8* noundef %0, i8* noundef %1) // CHECK-DAG: add nsw i32 % // CHECK-DAG: store i32 % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[BINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}}) // CHECK-DAG: store float 0.000000e+00, float* % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[BCOMB]](i8* noundef %0, i8* noundef %1) // CHECK-DAG: fadd float % // CHECK-DAG: store float % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[ARGCINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}}) // CHECK-DAG: store i32 0, i32* % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[ARGCCOMB]](i8* noundef %0, i8* noundef %1) // CHECK-DAG: add nsw i32 % // CHECK-DAG: store i32 % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[CINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}}) // CHECK-DAG: phi %struct.S* [ // CHECK-DAG: call {{.+}}(%struct.S* {{.+}}) // CHECK-DAG: br i1 % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[CFINI]](i8* noundef %0) // CHECK-DAG: phi %struct.S* [ // CHECK-DAG: call {{.+}}(%struct.S* {{.+}}) // CHECK-DAG: br i1 % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[CCOMB]](i8* noundef %0, i8* noundef %1) // CHECK-DAG: phi %struct.S* [ // CHECK-DAG: phi %struct.S* [ // CHECK-DAG: call {{.+}}(%struct.S* {{.+}}, %struct.S* {{.+}}, %struct.S* {{.+}}) // CHECK-DAG: call {{.+}}(%struct.S* {{.+}}, %struct.S* {{.+}}) // CHECK-DAG: call {{.+}}(%struct.S* {{.+}}) // CHECK-DAG: br i1 % // CHECK-DAG: ret void // CHECK_DAG: } // CHECK-DAG: define internal void @[[VLAINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}}) // CHECK-DAG: call i32 @__kmpc_global_thread_num(%struct.ident_t* {{[^,]+}}) // CHECK-DAG: call i8* @__kmpc_threadprivate_cached(%struct.ident_t* // CHECK-DAG: phi i16* [ // CHECK-DAG: store i16 0, i16* % // CHECK-DAG: br i1 % // CHECK-DAG: ret void // CHECK-DAG: } // CHECK-DAG: define internal void @[[VLACOMB]](i8* noundef %0, i8* noundef %1) // CHECK-DAG: call i32 @__kmpc_global_thread_num(%struct.ident_t* {{[^,]+}}) // CHECK-DAG: call i8* @__kmpc_threadprivate_cached(%struct.ident_t* // CHECK-DAG: phi i16* [ // CHECK-DAG: phi i16* [ // CHECK-DAG: sext i16 %{{.+}} to i32 // CHECK-DAG: add nsw i32 % // CHECK-DAG: trunc i32 %{{.+}} to i16 // CHECK-DAG: store i16 % // CHECK_DAG: br i1 % // CHECK-DAG: ret void // CHECK-DAG: } #endif // DEBUG-LABEL: distinct !DICompileUnit // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[AINIT]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ACOMB]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[BINIT]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[BCOMB]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ARGCINIT]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ARGCCOMB]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CINIT]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CFINI]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CCOMB]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[VLAINIT]]", // DEBUG-DAG: distinct !DISubprogram(linkageName: "[[VLACOMB]]",
56.576923
193
0.581033
ornata
ca295e08afd4609bcc6a6effd632ed99c3f59b55
20,490
cpp
C++
samples/luxcoreui/uimenu.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
samples/luxcoreui/uimenu.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
samples/luxcoreui/uimenu.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2017 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 <imgui.h> #include <boost/filesystem.hpp> #include <boost/algorithm/string/predicate.hpp> #include <nfd.h> #include "luxcoreapp.h" using namespace std; using namespace luxrays; using namespace luxcore; //------------------------------------------------------------------------------ // MenuRendering //------------------------------------------------------------------------------ #if !defined(LUXRAYS_DISABLE_OPENCL) static void KernelCacheFillProgressHandler(const size_t step, const size_t count) { LA_LOG("KernelCache FillProgressHandler Step: " << step << "/" << count); } #endif void LuxCoreApp::MenuRendering() { if (ImGui::MenuItem("Load")) { nfdchar_t *fileFileName = NULL; nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &fileFileName); if (result == NFD_OKAY) { LoadRenderConfig(fileFileName); free(fileFileName); } } if (session && ImGui::MenuItem("Export")) { nfdchar_t *outPath = NULL; nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outPath); if (result == NFD_OKAY) { LA_LOG("Export current scene to directory: " << outPath); boost::filesystem::path dir(outPath); boost::filesystem::create_directories(dir); // Save the current render engine const string renderEngine = config->GetProperty("renderengine.type").Get<string>(); // Set the render engine to FILESAVER RenderConfigParse(Properties() << Property("renderengine.type")("FILESAVER") << Property("filesaver.directory")(outPath) << Property("filesaver.renderengine.type")(renderEngine)); // Restore the render engine setting RenderConfigParse(Properties() << Property("renderengine.type")(renderEngine)); } } ImGui::Separator(); // Simplified save/resume rendering method: uses predefined names const string saveResumeName = "current"; if (session && ImGui::MenuItem("Save rendering (simplified)")) { // Pause the current rendering session->Pause(); // Save the film session->GetFilm().SaveFilm(saveResumeName + ".flm"); // Save the render state RenderState *renderState = session->GetRenderState(); renderState->Save(saveResumeName + ".rst"); delete renderState; // Resume the current rendering session->Resume(); } if (ImGui::MenuItem("Resume rendering (simplified)")) { // Select the scene nfdchar_t *sceneFileName = NULL; nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName); if (result == NFD_OKAY) { // Load the start film Film *startFilm = Film::Create(saveResumeName + ".flm"); // Load the start render state RenderState *startRenderState = RenderState::Create(saveResumeName + ".rst"); LoadRenderConfig(sceneFileName, startRenderState, startFilm); free(sceneFileName); } } // Normal saving rendering method: requires to select multiple file names if (session && ImGui::MenuItem("Save rendering")) { nfdchar_t *outName = NULL; nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outName); if (result == NFD_OKAY) { // Pause the current rendering session->Pause(); // Save the film session->GetFilm().SaveFilm(string(outName) + ".flm"); // Save the render state RenderState *renderState = session->GetRenderState(); renderState->Save(string(outName) + ".rst"); delete renderState; // Resume the current rendering session->Resume(); } } if (ImGui::MenuItem("Resume rendering")) { // Select the scene nfdchar_t *sceneFileName = NULL; nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName); if (result == NFD_OKAY) { // Select the film nfdchar_t *filmFileName = NULL; result = NFD_OpenDialog("flm", NULL, &filmFileName); if (result == NFD_OKAY) { // Select the render state nfdchar_t *renderStateFileName = NULL; result = NFD_OpenDialog("rst", NULL, &renderStateFileName); if (result == NFD_OKAY) { // Load the start film Film *startFilm = Film::Create(filmFileName); // Load the start render state RenderState *startRenderState = RenderState::Create(renderStateFileName); LoadRenderConfig(sceneFileName, startRenderState, startFilm); free(renderStateFileName); } free(filmFileName); } free(sceneFileName); } // Film *startFilm = new Film("aa.flm"); // RenderState *startRenderState = new RenderState("aa.rst"); // LoadRenderConfig("scenes/luxball/luxball-hdr.cfg", startRenderState, startFilm); } ImGui::Separator(); if (session) { if (session->IsInPause()) { if (ImGui::MenuItem("Resume")) session->Resume(); } else { if (ImGui::MenuItem("Pause")) session->Pause(); } if (ImGui::MenuItem("Cancel")) DeleteRendering(); if (session && ImGui::MenuItem("Restart", "Space bar")) { // Restart rendering session->Stop(); session->Start(); } ImGui::Separator(); } #if !defined(LUXRAYS_DISABLE_OPENCL) if (ImGui::MenuItem("Fill kernel cache")) { if (session) { // Stop any current rendering DeleteRendering(); } Properties props; /*props << Property("opencl.devices.select")("010") << Property("opencl.code.alwaysenabled")( "MATTE MIRROR GLASS ARCHGLASS MATTETRANSLUCENT GLOSSY2 " "METAL2 ROUGHGLASS ROUGHMATTE ROUGHMATTETRANSLUCENT " "GLOSSYTRANSLUCENT " "GLOSSY2_ABSORPTION GLOSSY2_MULTIBOUNCE " "HOMOGENEOUS_VOL CLEAR_VOL " "IMAGEMAPS_BYTE_FORMAT IMAGEMAPS_HALF_FORMAT " "IMAGEMAPS_1xCHANNELS IMAGEMAPS_3xCHANNELS " "HAS_BUMPMAPS " "INFINITE TRIANGLELIGHT") << Property("kernelcachefill.renderengine.types")("PATHOCL") << Property("kernelcachefill.sampler.types")("SOBOL") << Property("kernelcachefill.camera.types")("perspective") << Property("kernelcachefill.light.types")("infinite", "trianglelight") << Property("kernelcachefill.texture.types")("checkerboard2d", "checkerboard3d");*/ KernelCacheFill(props, KernelCacheFillProgressHandler); } ImGui::Separator(); #endif if (ImGui::MenuItem("Quit", "ESC")) glfwSetWindowShouldClose(window, GL_TRUE); } //------------------------------------------------------------------------------ // MenuEngine //------------------------------------------------------------------------------ void LuxCoreApp::MenuEngine() { const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>(); if (ImGui::MenuItem("PATHOCL", "1", (currentEngineType == "PATHOCL"))) { SetRenderingEngineType("PATHOCL"); CloseAllRenderConfigEditors(); } if (ImGui::MenuItem("LIGHTCPU", "2", (currentEngineType == "LIGHTCPU"))) { SetRenderingEngineType("LIGHTCPU"); CloseAllRenderConfigEditors(); } if (ImGui::MenuItem("PATHCPU", "3", (currentEngineType == "PATHCPU"))) { SetRenderingEngineType("PATHCPU"); CloseAllRenderConfigEditors(); } if (ImGui::MenuItem("BIDIRCPU", "4", (currentEngineType == "BIDIRCPU"))) { SetRenderingEngineType("BIDIRCPU"); CloseAllRenderConfigEditors(); } if (ImGui::MenuItem("BIDIRVMCPU", "5", (currentEngineType == "BIDIRVMCPU"))) { SetRenderingEngineType("BIDIRVMCPU"); CloseAllRenderConfigEditors(); } #if !defined(LUXRAYS_DISABLE_OPENCL) if (ImGui::MenuItem("RTPATHOCL", "6", (currentEngineType == "RTPATHOCL"))) { SetRenderingEngineType("RTPATHOCL"); CloseAllRenderConfigEditors(); } #endif if (ImGui::MenuItem("TILEPATHCPU", "7", (currentEngineType == "TILEPATHCPU"))) { SetRenderingEngineType("TILEPATHCPU"); CloseAllRenderConfigEditors(); } #if !defined(LUXRAYS_DISABLE_OPENCL) if (ImGui::MenuItem("TILEPATHOCL", "8", (currentEngineType == "TILEPATHOCL"))) { SetRenderingEngineType("TILEPATHOCL"); CloseAllRenderConfigEditors(); } #endif if (ImGui::MenuItem("RTPATHCPU", "9", (currentEngineType == "RTPATHCPU"))) { SetRenderingEngineType("RTPATHCPU"); CloseAllRenderConfigEditors(); } } //------------------------------------------------------------------------------ // MenuSampler //------------------------------------------------------------------------------ void LuxCoreApp::MenuSampler() { const string currentSamplerType = config->ToProperties().Get("sampler.type").Get<string>(); if (ImGui::MenuItem("RANDOM", NULL, (currentSamplerType == "RANDOM"))) { samplerWindow.Close(); RenderConfigParse(Properties() << Property("sampler.type")("RANDOM")); } if (ImGui::MenuItem("SOBOL", NULL, (currentSamplerType == "SOBOL"))) { samplerWindow.Close(); RenderConfigParse(Properties() << Property("sampler.type")("SOBOL")); } if (ImGui::MenuItem("METROPOLIS", NULL, (currentSamplerType == "METROPOLIS"))) { samplerWindow.Close(); RenderConfigParse(Properties() << Property("sampler.type")("METROPOLIS")); } } //------------------------------------------------------------------------------ // MenuTiles //------------------------------------------------------------------------------ void LuxCoreApp::MenuTiles() { bool showPending = config->GetProperties().Get(Property("screen.tiles.pending.show")(true)).Get<bool>(); if (ImGui::MenuItem("Show pending", NULL, showPending)) RenderConfigParse(Properties() << Property("screen.tiles.pending.show")(!showPending)); bool showConverged = config->GetProperties().Get(Property("screen.tiles.converged.show")(false)).Get<bool>(); if (ImGui::MenuItem("Show converged", NULL, showConverged)) RenderConfigParse(Properties() << Property("screen.tiles.converged.show")(!showConverged)); bool showNotConverged = config->GetProperties().Get(Property("screen.tiles.notconverged.show")(false)).Get<bool>(); if (ImGui::MenuItem("Show not converged", NULL, showNotConverged)) RenderConfigParse(Properties() << Property("screen.tiles.notconverged.show")(!showNotConverged)); ImGui::Separator(); bool showPassCount = config->GetProperties().Get(Property("screen.tiles.passcount.show")(false)).Get<bool>(); if (ImGui::MenuItem("Show pass count", NULL, showPassCount)) RenderConfigParse(Properties() << Property("screen.tiles.passcount.show")(!showPassCount)); bool showError = config->GetProperties().Get(Property("screen.tiles.error.show")(false)).Get<bool>(); if (ImGui::MenuItem("Show error", NULL, showError)) RenderConfigParse(Properties() << Property("screen.tiles.error.show")(!showError)); } //------------------------------------------------------------------------------ // MenuFilm //------------------------------------------------------------------------------ void LuxCoreApp::MenuFilm() { if (ImGui::BeginMenu("Set resolution")) { if (ImGui::MenuItem("320x240")) SetFilmResolution(320, 240); if (ImGui::MenuItem("640x480")) SetFilmResolution(640, 480); if (ImGui::MenuItem("800x600")) SetFilmResolution(800, 600); if (ImGui::MenuItem("1024x768")) SetFilmResolution(1024, 768); if (ImGui::MenuItem("1280x720")) SetFilmResolution(1280, 720); if (ImGui::MenuItem("1920x1080")) SetFilmResolution(1920, 1080); ImGui::Separator(); if (ImGui::MenuItem("Use window resolution")) { int currentFrameBufferWidth, currentFrameBufferHeight; glfwGetFramebufferSize(window, &currentFrameBufferWidth, &currentFrameBufferHeight); SetFilmResolution(currentFrameBufferWidth, currentFrameBufferHeight); } ImGui::Separator(); ImGui::TextUnformatted("Width x Height"); ImGui::PushItemWidth(100); ImGui::InputInt("##width", &menuFilmWidth); ImGui::PopItemWidth(); ImGui::SameLine(); ImGui::TextUnformatted("x"); ImGui::SameLine(); ImGui::PushItemWidth(100); ImGui::InputInt("##height", &menuFilmHeight); ImGui::PopItemWidth(); ImGui::SameLine(); if (ImGui::Button("Apply")) SetFilmResolution(menuFilmWidth, menuFilmHeight); ImGui::EndMenu(); } ImGui::Separator(); if (session && ImGui::MenuItem("Save outputs")) session->GetFilm().SaveOutputs(); if (session && ImGui::MenuItem("Save film")) session->GetFilm().SaveFilm("film.flm"); } //------------------------------------------------------------------------------ // MenuImagePipeline //------------------------------------------------------------------------------ void LuxCoreApp::MenuImagePipeline() { const unsigned int imagePipelineCount = session->GetFilm().GetChannelCount(Film::CHANNEL_IMAGEPIPELINE); for (unsigned int i = 0; i < imagePipelineCount; ++i) { if (ImGui::MenuItem(string("Pipeline #" + ToString(i)).c_str(), NULL, (i == imagePipelineIndex))) imagePipelineIndex = i; } if (imagePipelineIndex > imagePipelineCount) imagePipelineIndex = 0; } //------------------------------------------------------------------------------ // MenuScreen //------------------------------------------------------------------------------ void LuxCoreApp::MenuScreen() { if (ImGui::BeginMenu("Interpolation mode")) { if (ImGui::MenuItem("Nearest", NULL, (renderFrameBufferTexMinFilter == GL_NEAREST))) { renderFrameBufferTexMinFilter = GL_NEAREST; renderFrameBufferTexMagFilter = GL_NEAREST; } if (ImGui::MenuItem("Linear", NULL, (renderFrameBufferTexMinFilter == GL_LINEAR))) { renderFrameBufferTexMinFilter = GL_LINEAR; renderFrameBufferTexMagFilter = GL_LINEAR; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Refresh interval")) { if (ImGui::MenuItem("5ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(5))); if (ImGui::MenuItem("10ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(10))); if (ImGui::MenuItem("20ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(20))); if (ImGui::MenuItem("50ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(50))); if (ImGui::MenuItem("100ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(100))); if (ImGui::MenuItem("500ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(500))); if (ImGui::MenuItem("1000ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(1000))); if (ImGui::MenuItem("2000ms")) config->Parse(Properties().Set(Property("screen.refresh.interval")(2000))); ImGui::EndMenu(); } if (ImGui::MenuItem("Decrease refresh interval","n")) DecScreenRefreshInterval(); if (ImGui::MenuItem("Increase refresh interval","m")) IncScreenRefreshInterval(); if (ImGui::BeginMenu("UI font scale")) { ImGuiIO &io = ImGui::GetIO(); if (ImGui::MenuItem("1.0", NULL, (io.FontGlobalScale == 1.f))) io.FontGlobalScale = 1.f; if (ImGui::MenuItem("1.25", NULL, (io.FontGlobalScale == 1.25f))) io.FontGlobalScale = 1.25f; if (ImGui::MenuItem("1.5", NULL, (io.FontGlobalScale == 1.5f))) io.FontGlobalScale = 1.5f; if (ImGui::MenuItem("1.75", NULL, (io.FontGlobalScale == 1.75f))) io.FontGlobalScale = 1.75f; if (ImGui::MenuItem("2.0", NULL, (io.FontGlobalScale == 2.f))) io.FontGlobalScale = 2.f; ImGui::EndMenu(); } } //------------------------------------------------------------------------------ // MenuTool //------------------------------------------------------------------------------ void LuxCoreApp::MenuTool() { if (ImGui::MenuItem("Camera edit", NULL, (currentTool == TOOL_CAMERA_EDIT))) { currentTool = TOOL_CAMERA_EDIT; RenderConfigParse(Properties() << Property("screen.tool.type")("CAMERA_EDIT")); } if (ImGui::MenuItem("Object selection", NULL, (currentTool == TOOL_OBJECT_SELECTION))) { currentTool = TOOL_OBJECT_SELECTION; Properties props; props << Property("screen.tool.type")("OBJECT_SELECTION"); // Check if the session a OBJECT_ID AOV enabled if(!session->GetFilm().HasOutput(Film::OUTPUT_OBJECT_ID)) { // Enable OBJECT_ID AOV props << Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.type")("OBJECT_ID") << Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.filename")("dummy.png"); } RenderConfigParse(props); } if (ImGui::MenuItem("Image view", NULL, (currentTool == TOOL_IMAGE_VIEW))) { currentTool = TOOL_IMAGE_VIEW; RenderConfigParse(Properties() << Property("screen.tool.type")("IMAGE_VIEW")); } } //------------------------------------------------------------------------------ // MenuWindow //------------------------------------------------------------------------------ void LuxCoreApp::MenuWindow() { if (session) { const string currentRenderEngineType = config->ToProperties().Get("renderengine.type").Get<string>(); if (ImGui::MenuItem("Render Engine editor", NULL, renderEngineWindow.IsOpen())) renderEngineWindow.Toggle(); if (ImGui::MenuItem("Sampler editor", NULL, samplerWindow.IsOpen(), !boost::starts_with(currentRenderEngineType, "TILE") && !boost::starts_with(currentRenderEngineType, "RT"))) samplerWindow.Toggle(); if (ImGui::MenuItem("Pixel Filter editor", NULL, pixelFilterWindow.IsOpen())) pixelFilterWindow.Toggle(); if (ImGui::MenuItem("OpenCL Device editor", NULL, oclDeviceWindow.IsOpen(), boost::ends_with(currentRenderEngineType, "OCL"))) oclDeviceWindow.Toggle(); if (ImGui::MenuItem("Light Strategy editor", NULL, lightStrategyWindow.IsOpen())) lightStrategyWindow.Toggle(); if (ImGui::MenuItem("Accelerator editor", NULL, acceleratorWindow.IsOpen())) acceleratorWindow.Toggle(); if (ImGui::MenuItem("Epsilon editor", NULL, epsilonWindow.IsOpen())) epsilonWindow.Toggle(); ImGui::Separator(); if (ImGui::MenuItem("Film Radiance Groups editor", NULL, filmRadianceGroupsWindow.IsOpen())) filmRadianceGroupsWindow.Toggle(); if (ImGui::MenuItem("Film Outputs editor", NULL, filmOutputsWindow.IsOpen())) filmOutputsWindow.Toggle(); if (ImGui::MenuItem("Film Channels window", NULL, filmChannelsWindow.IsOpen())) filmChannelsWindow.Toggle(); ImGui::Separator(); if (session && ImGui::MenuItem("Statistics", "j", statsWindow.IsOpen())) statsWindow.Toggle(); } if (ImGui::MenuItem("Log console", NULL, logWindow.IsOpen())) logWindow.Toggle(); if (ImGui::MenuItem("Help", NULL, helpWindow.IsOpen())) helpWindow.Toggle(); } //------------------------------------------------------------------------------ // MainMenuBar //------------------------------------------------------------------------------ void LuxCoreApp::MainMenuBar() { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("Rendering")) { MenuRendering(); ImGui::EndMenu(); } if (session) { const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>(); if (ImGui::BeginMenu("Engine")) { MenuEngine(); ImGui::EndMenu(); } if ((!boost::starts_with(currentEngineType, "TILE")) && (!boost::starts_with(currentEngineType, "RT")) && ImGui::BeginMenu("Sampler")) { MenuSampler(); ImGui::EndMenu(); } if (boost::starts_with(currentEngineType, "TILE") && ImGui::BeginMenu("Tiles")) { MenuTiles(); ImGui::EndMenu(); } if (ImGui::BeginMenu("Film")) { MenuFilm(); ImGui::EndMenu(); } if (ImGui::BeginMenu("Image")) { MenuImagePipeline(); ImGui::EndMenu(); } if (ImGui::BeginMenu("Screen")) { MenuScreen(); ImGui::EndMenu(); } if (ImGui::BeginMenu("Tool")) { MenuTool(); ImGui::EndMenu(); } } if (ImGui::BeginMenu("Window")) { MenuWindow(); ImGui::EndMenu(); } menuBarHeight = ImGui::GetWindowHeight(); ImGui::EndMainMenuBar(); } }
34.436975
116
0.621523
LuxRender
ca2a341497fe45225d9ffdab7a85dc569d2c9fb1
26,189
cpp
C++
src/Layers/xrRender/ParticleEffect.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
2
2020-05-17T10:02:18.000Z
2020-08-08T21:10:36.000Z
src/Layers/xrRender/ParticleEffect.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
null
null
null
src/Layers/xrRender/ParticleEffect.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
null
null
null
#include "stdafx.h" #pragma hdrstop #include "ParticleEffect.h" #ifndef _EDITOR #include <xmmintrin.h> #include "../../xrCPU_Pipe/ttapi.h" #pragma comment(lib,"xrCPU_Pipe.lib") #endif using namespace PAPI; using namespace PS; const u32 PS::uDT_STEP = 33; const float PS::fDT_STEP = float(uDT_STEP)/1000.f; static void ApplyTexgen( const Fmatrix &mVP ) { Fmatrix mTexgen; #if defined(USE_DX10) || defined(USE_DX11) Fmatrix mTexelAdjust = { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f }; #else // USE_DX10 float _w = float(RDEVICE.dwWidth); float _h = float(RDEVICE.dwHeight); float o_w = (.5f / _w); float o_h = (.5f / _h); Fmatrix mTexelAdjust = { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f + o_w, 0.5f + o_h, 0.0f, 1.0f }; #endif // USE_DX10 mTexgen.mul(mTexelAdjust,mVP); RCache.set_c( "mVPTexgen", mTexgen ); } void PS::OnEffectParticleBirth(void* owner, u32 , PAPI::Particle& m, u32 ) { CParticleEffect* PE = static_cast<CParticleEffect*>(owner); VERIFY(PE); CPEDef* PED = PE->GetDefinition(); if (PED){ if (PED->m_Flags.is(CPEDef::dfRandomFrame)) m.frame = (u16)iFloor(Random.randI(PED->m_Frame.m_iFrameCount)*255.f); if (PED->m_Flags.is(CPEDef::dfAnimated)&&PED->m_Flags.is(CPEDef::dfRandomPlayback)&&Random.randI(2)) m.flags.set(Particle::ANIMATE_CCW,TRUE); } } void PS::OnEffectParticleDead(void* , u32 , PAPI::Particle& , u32 ) { // CPEDef* PE = static_cast<CPEDef*>(owner); } //------------------------------------------------------------------------------ // class CParticleEffect //------------------------------------------------------------------------------ CParticleEffect::CParticleEffect() { m_HandleEffect = ParticleManager()->CreateEffect(1); VERIFY(m_HandleEffect>=0); m_HandleActionList = ParticleManager()->CreateActionList(); VERIFY(m_HandleActionList>=0); m_RT_Flags.zero (); m_Def = 0; m_fElapsedLimit = 0.f; m_MemDT = 0; m_InitialPosition.set (0,0,0); m_DestroyCallback = 0; m_CollisionCallback = 0; m_XFORM.identity (); } CParticleEffect::~CParticleEffect() { // Log ("--- destroy PE"); OnDeviceDestroy (); ParticleManager()->DestroyEffect (m_HandleEffect); ParticleManager()->DestroyActionList (m_HandleActionList); } void CParticleEffect::Play() { m_RT_Flags.set (flRT_DefferedStop,FALSE); m_RT_Flags.set (flRT_Playing,TRUE); ParticleManager()->PlayEffect(m_HandleEffect,m_HandleActionList); } void CParticleEffect::Stop(BOOL bDefferedStop) { ParticleManager()->StopEffect(m_HandleEffect,m_HandleActionList,bDefferedStop); if (bDefferedStop){ m_RT_Flags.set (flRT_DefferedStop,TRUE); }else{ m_RT_Flags.set (flRT_Playing,FALSE); } } void CParticleEffect::RefreshShader() { OnDeviceDestroy(); OnDeviceCreate(); } void CParticleEffect::UpdateParent(const Fmatrix& m, const Fvector& velocity, BOOL bXFORM) { m_RT_Flags.set (flRT_XFORM, bXFORM); if (bXFORM) m_XFORM.set (m); else{ m_InitialPosition = m.c; ParticleManager()->Transform(m_HandleActionList,m,velocity); } } void CParticleEffect::OnFrame(u32 frame_dt) { if (m_Def && m_RT_Flags.is(flRT_Playing)){ m_MemDT += frame_dt; int StepCount = 0; if (m_MemDT>=uDT_STEP) { // allow maximum of three steps (99ms) to avoid slowdown after loading // it will really skip updates at less than 10fps, which is unplayable StepCount = m_MemDT/uDT_STEP; m_MemDT = m_MemDT%uDT_STEP; clamp (StepCount,0,3); } for (;StepCount; StepCount--) { if (m_Def->m_Flags.is(CPEDef::dfTimeLimit)){ if (!m_RT_Flags.is(flRT_DefferedStop)){ m_fElapsedLimit -= fDT_STEP; if (m_fElapsedLimit<0.f){ m_fElapsedLimit = m_Def->m_fTimeLimit; Stop (true); break; } } } ParticleManager()->Update(m_HandleEffect,m_HandleActionList,fDT_STEP); PAPI::Particle* particles; u32 p_cnt; ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt); // our actions if (m_Def->m_Flags.is(CPEDef::dfFramed|CPEDef::dfAnimated)) m_Def->ExecuteAnimate (particles,p_cnt,fDT_STEP); if (m_Def->m_Flags.is(CPEDef::dfCollision)) m_Def->ExecuteCollision (particles,p_cnt,fDT_STEP,this,m_CollisionCallback); //-move action if (p_cnt) { vis.box.invalidate (); float p_size = 0.f; for(u32 i = 0; i < p_cnt; i++){ Particle &m = particles[i]; vis.box.modify((Fvector&)m.pos); if (m.size.x>p_size) p_size = m.size.x; if (m.size.y>p_size) p_size = m.size.y; if (m.size.z>p_size) p_size = m.size.z; } vis.box.grow (p_size); vis.box.getsphere (vis.sphere.P,vis.sphere.R); } if (m_RT_Flags.is(flRT_DefferedStop)&&(0==p_cnt)){ m_RT_Flags.set (flRT_Playing|flRT_DefferedStop,FALSE); break; } } } else { vis.box.set (m_InitialPosition,m_InitialPosition); vis.box.grow (EPS_L); vis.box.getsphere (vis.sphere.P,vis.sphere.R); } } BOOL CParticleEffect::Compile(CPEDef* def) { m_Def = def; if (m_Def){ // refresh shader RefreshShader (); // append actions IReader F (m_Def->m_Actions.pointer(),m_Def->m_Actions.size()); ParticleManager()->LoadActions (m_HandleActionList,F); ParticleManager()->SetMaxParticles (m_HandleEffect,m_Def->m_MaxParticles); ParticleManager()->SetCallback (m_HandleEffect,OnEffectParticleBirth,OnEffectParticleDead,this,0); // time limit if (m_Def->m_Flags.is(CPEDef::dfTimeLimit)) m_fElapsedLimit = m_Def->m_fTimeLimit; } if (def) shader = def->m_CachedShader; return TRUE; } void CParticleEffect::SetBirthDeadCB(PAPI::OnBirthParticleCB bc, PAPI::OnDeadParticleCB dc, void* owner, u32 p) { ParticleManager()->SetCallback (m_HandleEffect,bc,dc,owner,p); } u32 CParticleEffect::ParticlesCount() { return ParticleManager()->GetParticlesCount(m_HandleEffect); } //------------------------------------------------------------------------------ // Render //------------------------------------------------------------------------------ void CParticleEffect::Copy(dxRender_Visual* ) { FATAL ("Can't duplicate particle system - NOT IMPLEMENTED"); } void CParticleEffect::OnDeviceCreate() { if (m_Def){ if (m_Def->m_Flags.is(CPEDef::dfSprite)){ geom.create (FVF::F_LIT, RCache.Vertex.Buffer(), RCache.QuadIB); if (m_Def) shader = m_Def->m_CachedShader; } } } void CParticleEffect::OnDeviceDestroy() { if (m_Def){ if (m_Def->m_Flags.is(CPEDef::dfSprite)){ geom.destroy (); shader.destroy (); } } } #ifndef _EDITOR //---------------------------------------------------- IC void FillSprite_fpu (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle) { float sa = _sin(angle); float ca = _cos(angle); Fvector Vr, Vt; Vr.x = T.x*r1*sa+R.x*r1*ca; Vr.y = T.y*r1*sa+R.y*r1*ca; Vr.z = T.z*r1*sa+R.z*r1*ca; Vt.x = T.x*r2*ca-R.x*r2*sa; Vt.y = T.y*r2*ca-R.y*r2*sa; Vt.z = T.z*r2*ca-R.z*r2*sa; Fvector a,b,c,d; a.sub (Vt,Vr); b.add (Vt,Vr); c.invert (a); d.invert (b); pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++; pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++; pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++; pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++; } __forceinline void fsincos( const float angle , float &sine , float &cosine ) { __asm { fld DWORD PTR [angle] fsincos mov eax , DWORD PTR [cosine] fstp DWORD PTR [eax] mov eax , DWORD PTR [sine] fstp DWORD PTR [eax] } } IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa ) { #ifdef _GPA_ENABLED TAL_SCOPED_TASK_NAMED( "FillSprite()" ); #endif // _GPA_ENABLED __m128 Vr, Vt, _T , _R , _pos , _zz , _sa , _ca , a , b , c , d; _sa = _mm_set1_ps( sina ); _ca = _mm_set1_ps( cosa ); _T = _mm_load_ss( (float*) &T.x ); _T = _mm_loadh_pi( _T , (__m64*) &T.y ); _R = _mm_load_ss( (float*) &R.x ); _R = _mm_loadh_pi( _R , (__m64*) &R.y ); _pos = _mm_load_ss( (float*) &pos.x ); _pos = _mm_loadh_pi( _pos , (__m64*) &pos.y ); _zz = _mm_setzero_ps(); Vr = _mm_mul_ps( _mm_set1_ps( r1 ) , _mm_add_ps( _mm_mul_ps( _T , _sa ) , _mm_mul_ps( _R , _ca ) ) ); Vt = _mm_mul_ps( _mm_set1_ps( r2 ) , _mm_sub_ps( _mm_mul_ps( _T , _ca ) , _mm_mul_ps( _R , _sa ) ) ); a = _mm_sub_ps( Vt , Vr ); b = _mm_add_ps( Vt , Vr ); c = _mm_sub_ps( _zz , a ); d = _mm_sub_ps( _zz , b ); a = _mm_add_ps( a , _pos ); d = _mm_add_ps( d , _pos ); b = _mm_add_ps( b , _pos ); c = _mm_add_ps( c , _pos ); _mm_store_ss( (float*) &pv->p.x , d ); _mm_storeh_pi( (__m64*) &pv->p.y , d ); pv->color = clr; pv->t.set( lt.x , rb.y ); pv++; _mm_store_ss( (float*) &pv->p.x , a ); _mm_storeh_pi( (__m64*) &pv->p.y , a ); pv->color = clr; pv->t.set( lt.x , lt.y ); pv++; _mm_store_ss( (float*) &pv->p.x , c ); _mm_storeh_pi( (__m64*) &pv->p.y , c ); pv->color = clr; pv->t.set( rb.x , rb.y ); pv++; _mm_store_ss( (float*) &pv->p.x , b ); _mm_storeh_pi( (__m64*) &pv->p.y , b ); pv->color = clr; pv->t.set( rb.x , lt.y ); pv++; } IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa ) { #ifdef _GPA_ENABLED TAL_SCOPED_TASK_NAMED( "FillSpriteTransform()" ); #endif // _GPA_ENABLED const Fvector& T = dir; Fvector R; // R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe(); __m128 _t , _t1 , _t2 , _r , _r1 , _r2 ; // crossproduct _t = _mm_load_ss( (float*) &T.x ); _t = _mm_loadh_pi( _t , (__m64*) &T.y ); _r = _mm_load_ss( (float*) &RDEVICE.vCameraDirection.x ); _r = _mm_loadh_pi( _r , (__m64*) &RDEVICE.vCameraDirection.y ); _t1 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) ); _t2 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) ); _r1 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) ); _r2 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) ); _t1 = _mm_mul_ps( _t1 , _r1 ); _t2 = _mm_mul_ps( _t2 , _r2 ); _t1 = _mm_sub_ps( _t1 , _t2 ); // z | y | 0 | x // normalize_safe _t2 = _mm_mul_ps( _t1 , _t1 ); // zz | yy | 00 | xx _r1 = _mm_movehl_ps( _t2 , _t2 ); // zz | yy | zz | yy _t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy _r1 = _mm_shuffle_ps( _r1 , _r1 , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // zz | zz | zz | zz _t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy + zz _r1 = _mm_set_ss( std::numeric_limits<float>::min() ); if ( _mm_comigt_ss( _t2 , _r1 ) ) { _t2 = _mm_rsqrt_ss( _t2 ); _t2 = _mm_shuffle_ps( _t2 , _t2 , _MM_SHUFFLE( 0 , 0 , 0 , 0 ) ); _t1 = _mm_mul_ps( _t1 , _t2 ); } _mm_store_ss( (float*) &R.x , _t1 ); _mm_storeh_pi( (__m64*) &R.y , _t1 ); FillSprite( pv , T , R , pos , lt , rb , r1 , r2 , clr , sina , cosa ); } extern ENGINE_API float psHUD_FOV; struct PRS_PARAMS { FVF::LIT* pv; u32 p_from; u32 p_to; PAPI::Particle* particles; CParticleEffect* pPE; }; __forceinline void magnitude_sse( Fvector &vec , float &res ) { __m128 tv,tu; tv = _mm_load_ss( (float*) &vec.x ); // tv = 0 | 0 | 0 | x tv = _mm_loadh_pi( tv , (__m64*) &vec.y ); // tv = z | y | 0 | x tv = _mm_mul_ps( tv , tv ); // tv = zz | yy | 0 | xx tu = _mm_movehl_ps( tv , tv ); // tu = zz | yy | zz | yy tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy tu = _mm_shuffle_ps( tu , tu , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // tu = zz | zz | zz | zz tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy + zz tv = _mm_sqrt_ss( tv ); // tv = zz | yy | 0 | sqrt( xx + yy + zz ) _mm_store_ss( (float*) &res , tv ); } void ParticleRenderStream( LPVOID lpvParams ) { #ifdef _GPA_ENABLED TAL_SCOPED_TASK_NAMED( "ParticleRenderStream()" ); TAL_ID rtID = TAL_MakeID( 1 , Core.dwFrame , 0); TAL_AddRelationThis(TAL_RELATION_IS_CHILD_OF, rtID); #endif // _GPA_ENABLED float sina = 0.0f , cosa = 0.0f; DWORD angle = 0xFFFFFFFF; PRS_PARAMS* pParams = (PRS_PARAMS *) lpvParams; FVF::LIT* pv = pParams->pv; u32 p_from = pParams->p_from; u32 p_to = pParams->p_to; PAPI::Particle* particles = pParams->particles; CParticleEffect &pPE = *pParams->pPE; for(u32 i = p_from; i < p_to; i++){ PAPI::Particle &m = particles[i]; Fvector2 lt,rb; lt.set (0.f,0.f); rb.set (1.f,1.f); _mm_prefetch( (char*) &particles[i + 1] , _MM_HINT_NTA ); if ( angle != *((DWORD*)&m.rot.x) ) { angle = *((DWORD*)&m.rot.x); __asm { fld DWORD PTR [angle] fsincos fstp DWORD PTR [cosa] fstp DWORD PTR [sina] } } _mm_prefetch( 64 + (char*) &particles[i + 1] , _MM_HINT_NTA ); if (pPE.m_Def->m_Flags.is(CPEDef::dfFramed)) pPE.m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb); float r_x = m.size.x*0.5f; float r_y = m.size.y*0.5f; float speed; BOOL speed_calculated = FALSE; if (pPE.m_Def->m_Flags.is(CPEDef::dfVelocityScale)){ magnitude_sse( m.vel , speed ); speed_calculated = TRUE; r_x += speed*pPE.m_Def->m_VelocityScale.x; r_y += speed*pPE.m_Def->m_VelocityScale.y; } if (pPE.m_Def->m_Flags.is(CPEDef::dfAlignToPath)){ if ( ! speed_calculated ) magnitude_sse( m.vel , speed ); if ((speed<EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfWorldAlign)){ Fmatrix M; M.setXYZ (pPE.m_Def->m_APDefaultRotation); if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){ Fvector p; pPE.m_XFORM.transform_tiny(p,m.pos); M.mulA_43 (pPE.m_XFORM); FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa); }else{ FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa); } }else if ((speed>=EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfFaceAlign)){ Fmatrix M; M.identity(); M.k.div (m.vel,speed); M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1); M.i.crossproduct (M.j,M.k); M.i.normalize (); M.j.crossproduct (M.k,M.i); M.j.normalize (); if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){ Fvector p; pPE.m_XFORM.transform_tiny(p,m.pos); M.mulA_43 (pPE.m_XFORM); FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa); }else{ FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa); } }else{ Fvector dir; if (speed>=EPS_S) dir.div (m.vel,speed); else dir.setHP(-pPE.m_Def->m_APDefaultRotation.y,-pPE.m_Def->m_APDefaultRotation.x); if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){ Fvector p,d; pPE.m_XFORM.transform_tiny (p,m.pos); pPE.m_XFORM.transform_dir (d,dir); FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,sina,cosa); }else{ FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,sina,cosa); } } }else{ if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){ Fvector p; pPE.m_XFORM.transform_tiny (p,m.pos); FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,sina,cosa); }else{ FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa); } } } } void CParticleEffect::Render(float ) { #ifdef _GPA_ENABLED TAL_SCOPED_TASK_NAMED( "CParticleEffect::Render()" ); #endif // _GPA_ENABLED u32 dwOffset,dwCount; // Get a pointer to the particles in gp memory PAPI::Particle* particles; u32 p_cnt; ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt); if(p_cnt>0){ if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){ FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset); FVF::LIT* pv = pv_start; u32 nWorkers = ttapi_GetWorkersCount(); if ( p_cnt < nWorkers * 20 ) nWorkers = 1; PRS_PARAMS* prsParams = (PRS_PARAMS*) _alloca( sizeof(PRS_PARAMS) * nWorkers ); // Give ~1% more for the last worker // to minimize wait in final spin u32 nSlice = p_cnt / 128; u32 nStep = ( ( p_cnt - nSlice ) / nWorkers ); //u32 nStep = ( p_cnt / nWorkers ); //Msg( "Rnd: %u" , nStep ); for ( u32 i = 0 ; i < nWorkers ; ++i ) { prsParams[i].pv = pv + i*nStep*4; prsParams[i].p_from = i * nStep; prsParams[i].p_to = ( i == ( nWorkers - 1 ) ) ? p_cnt : ( prsParams[i].p_from + nStep ); prsParams[i].particles = particles; prsParams[i].pPE = this; ttapi_AddWorker( ParticleRenderStream , (LPVOID) &prsParams[i] ); } ttapi_RunAllWorkers(); dwCount = p_cnt<<2; RCache.Vertex.Unlock(dwCount,geom->vb_stride); if (dwCount) { #ifndef _EDITOR Fmatrix Pold = Device.mProject; Fmatrix FTold = Device.mFullTransform; if(GetHudMode()) { RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV), Device.fASPECT, VIEWPORT_NEAR, g_pGamePersistent->Environment().CurrentEnv->far_plane); Device.mFullTransform.mul (Device.mProject, Device.mView); RCache.set_xform_project (Device.mProject); RImplementation.rmNear (); ApplyTexgen(Device.mFullTransform); } #endif RCache.set_xform_world (Fidentity); RCache.set_Geometry (geom); RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE); RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2); RCache.set_CullMode (CULL_CCW ); #ifndef _EDITOR if(GetHudMode()) { RImplementation.rmNormal (); Device.mProject = Pold; Device.mFullTransform = FTold; RCache.set_xform_project (Device.mProject); ApplyTexgen(Device.mFullTransform); } #endif } } } } #else //---------------------------------------------------- IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle) { float sa = _sin(angle); float ca = _cos(angle); Fvector Vr, Vt; Vr.x = T.x*r1*sa+R.x*r1*ca; Vr.y = T.y*r1*sa+R.y*r1*ca; Vr.z = T.z*r1*sa+R.z*r1*ca; Vt.x = T.x*r2*ca-R.x*r2*sa; Vt.y = T.y*r2*ca-R.y*r2*sa; Vt.z = T.z*r2*ca-R.z*r2*sa; Fvector a,b,c,d; a.sub (Vt,Vr); b.add (Vt,Vr); c.invert (a); d.invert (b); pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++; pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++; pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++; pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++; } IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle) { float sa = _sin(angle); float ca = _cos(angle); const Fvector& T = dir; Fvector R; R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe(); Fvector Vr, Vt; Vr.x = T.x*r1*sa+R.x*r1*ca; Vr.y = T.y*r1*sa+R.y*r1*ca; Vr.z = T.z*r1*sa+R.z*r1*ca; Vt.x = T.x*r2*ca-R.x*r2*sa; Vt.y = T.y*r2*ca-R.y*r2*sa; Vt.z = T.z*r2*ca-R.z*r2*sa; Fvector a,b,c,d; a.sub (Vt,Vr); b.add (Vt,Vr); c.invert (a); d.invert (b); pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++; pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++; pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++; pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++; } extern ENGINE_API float psHUD_FOV; void CParticleEffect::Render(float ) { u32 dwOffset,dwCount; // Get a pointer to the particles in gp memory PAPI::Particle* particles; u32 p_cnt; ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt); if(p_cnt>0){ if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){ FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset); FVF::LIT* pv = pv_start; for(u32 i = 0; i < p_cnt; i++){ PAPI::Particle &m = particles[i]; Fvector2 lt,rb; lt.set (0.f,0.f); rb.set (1.f,1.f); if (m_Def->m_Flags.is(CPEDef::dfFramed)) m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb); float r_x = m.size.x*0.5f; float r_y = m.size.y*0.5f; if (m_Def->m_Flags.is(CPEDef::dfVelocityScale)){ float speed = m.vel.magnitude(); r_x += speed*m_Def->m_VelocityScale.x; r_y += speed*m_Def->m_VelocityScale.y; } if (m_Def->m_Flags.is(CPEDef::dfAlignToPath)){ float speed = m.vel.magnitude(); if ((speed<EPS_S)&&m_Def->m_Flags.is(CPEDef::dfWorldAlign)){ Fmatrix M; M.setXYZ (m_Def->m_APDefaultRotation); if (m_RT_Flags.is(flRT_XFORM)){ Fvector p; m_XFORM.transform_tiny(p,m.pos); M.mulA_43 (m_XFORM); FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x); }else{ FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x); } }else if ((speed>=EPS_S)&&m_Def->m_Flags.is(CPEDef::dfFaceAlign)){ Fmatrix M; M.identity(); M.k.div (m.vel,speed); M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1); M.i.crossproduct (M.j,M.k); M.i.normalize (); M.j.crossproduct (M.k,M.i); M.j.normalize (); if (m_RT_Flags.is(flRT_XFORM)){ Fvector p; m_XFORM.transform_tiny(p,m.pos); M.mulA_43 (m_XFORM); FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x); }else{ FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x); } }else{ Fvector dir; if (speed>=EPS_S) dir.div (m.vel,speed); else dir.setHP(-m_Def->m_APDefaultRotation.y,-m_Def->m_APDefaultRotation.x); if (m_RT_Flags.is(flRT_XFORM)){ Fvector p,d; m_XFORM.transform_tiny (p,m.pos); m_XFORM.transform_dir (d,dir); FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,m.rot.x); }else{ FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,m.rot.x); } } }else{ if (m_RT_Flags.is(flRT_XFORM)){ Fvector p; m_XFORM.transform_tiny (p,m.pos); FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,m.rot.x); }else{ FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x); } } } dwCount = u32(pv-pv_start); RCache.Vertex.Unlock(dwCount,geom->vb_stride); if (dwCount) { #ifndef _EDITOR Fmatrix Pold = Device.mProject; Fmatrix FTold = Device.mFullTransform; if(GetHudMode()) { RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV), Device.fASPECT, VIEWPORT_NEAR, g_pGamePersistent->Environment().CurrentEnv->far_plane); Device.mFullTransform.mul (Device.mProject, Device.mView); RCache.set_xform_project (Device.mProject); RImplementation.rmNear (); ApplyTexgen(Device.mFullTransform); } #endif RCache.set_xform_world (Fidentity); RCache.set_Geometry (geom); RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE); RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2); RCache.set_CullMode (CULL_CCW ); #ifndef _EDITOR if(GetHudMode()) { RImplementation.rmNormal (); Device.mProject = Pold; Device.mFullTransform = FTold; RCache.set_xform_project (Device.mProject); ApplyTexgen(Device.mFullTransform); } #endif } } } } #endif // _EDITOR
33.277001
186
0.559013
Samsuper12
ca2ec8ce288fab5a0da6054bf551a98fc716ea5c
3,349
cpp
C++
Gems/Blast/Code/Source/Components/BlastFamilyComponentNotificationBusHandler.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
1
2021-07-19T23:54:05.000Z
2021-07-19T23:54:05.000Z
Gems/Blast/Code/Source/Components/BlastFamilyComponentNotificationBusHandler.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Blast/Code/Source/Components/BlastFamilyComponentNotificationBusHandler.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "StdAfx.h" #include <Components/BlastFamilyComponentNotificationBusHandler.h> namespace Blast { BlastFamilyComponentNotificationBusHandler::BlastFamilyComponentNotificationBusHandler() { m_events.resize(static_cast<int>(Function::Count)); SetEvent(&BlastFamilyComponentNotificationBusHandler::OnActorCreatedDummy, "On Actor Created"); SetEvent(&BlastFamilyComponentNotificationBusHandler::OnActorDestroyedDummy, "On Actor Destroyed"); } void BlastFamilyComponentNotificationBusHandler::Reflect(AZ::ReflectContext* context) { if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { behaviorContext->EBus<BlastFamilyComponentNotificationBus>("BlastFamilyComponentNotificationBus") ->Attribute(AZ::Script::Attributes::Module, "destruction") ->Attribute(AZ::Script::Attributes::Category, "Blast") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Handler<BlastFamilyComponentNotificationBusHandler>(); } } void BlastFamilyComponentNotificationBusHandler::Disconnect() { BusDisconnect(); } bool BlastFamilyComponentNotificationBusHandler::Connect(AZ::BehaviorValueParameter* id) { return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::Connect(this, id); } bool BlastFamilyComponentNotificationBusHandler::IsConnected() { return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::IsConnected(this); } bool BlastFamilyComponentNotificationBusHandler::IsConnectedId(AZ::BehaviorValueParameter* id) { return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::IsConnectedId(this, id); } int BlastFamilyComponentNotificationBusHandler::GetFunctionIndex(const char* functionName) const { if (strcmp(functionName, "On Actor Created") == 0) { return static_cast<int>(Function::OnActorCreated); } if (strcmp(functionName, "On Actor Destroyed") == 0) { return static_cast<int>(Function::OnActorDestroyed); } return -1; } void BlastFamilyComponentNotificationBusHandler::OnActorCreatedDummy([[maybe_unused]] BlastActorData blastActor) { // This is never invoked, and only used for type deduction when calling SetEvent } void BlastFamilyComponentNotificationBusHandler::OnActorDestroyedDummy([[maybe_unused]] BlastActorData blastActor) { // This is never invoked, and only used for type deduction when calling SetEvent } void BlastFamilyComponentNotificationBusHandler::OnActorCreated(const BlastActor& blastActor) { Call(static_cast<int>(Function::OnActorCreated), BlastActorData(blastActor)); } void BlastFamilyComponentNotificationBusHandler::OnActorDestroyed(const BlastActor& blastActor) { Call(static_cast<int>(Function::OnActorDestroyed), BlastActorData(blastActor)); } } // namespace Blast
39.4
118
0.724694
Schneidex69
ca2edbd855f22ff164a345a4f5558a5ebf336c32
375
cpp
C++
cpp-eindopdracht/creditsview.cpp
TvanBronswijk/cpp-eindopdracht
657febe944cd856da44c3cc6cb6d1822c1fbf740
[ "MIT" ]
null
null
null
cpp-eindopdracht/creditsview.cpp
TvanBronswijk/cpp-eindopdracht
657febe944cd856da44c3cc6cb6d1822c1fbf740
[ "MIT" ]
null
null
null
cpp-eindopdracht/creditsview.cpp
TvanBronswijk/cpp-eindopdracht
657febe944cd856da44c3cc6cb6d1822c1fbf740
[ "MIT" ]
null
null
null
#include "creditsview.h" #include "gamecontext.h" CreditsView::CreditsView(GameContext* context) : View(context) { } std::ostream & CreditsView::display() { return std::cout << "This game was created by Tobi van Bronswijk and Rick van Berlo." << std::endl << "Thanks for playing!" << std::endl; } bool CreditsView::handle_input(char c) { back(); return true; }
17.045455
70
0.685333
TvanBronswijk
ca31ec481bbb8c4a5201999ae7d67f5783ec3c4f
3,385
cc
C++
src/lib/dhcpsrv/testutils/config_result_check.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
2
2021-06-29T09:56:34.000Z
2021-06-29T09:56:39.000Z
src/lib/dhcpsrv/testutils/config_result_check.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
src/lib/dhcpsrv/testutils/config_result_check.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2014-2017 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <cc/command_interpreter.h> #include <dhcpsrv/testutils/config_result_check.h> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/constants.hpp> #include <boost/algorithm/string/split.hpp> #include <string> namespace isc { namespace dhcp { namespace test { using namespace isc; using namespace isc::data; bool errorContainsPosition(ElementPtr error_element, const std::string& file_name) { if (error_element->contains(isc::config::CONTROL_RESULT)) { ElementPtr result = error_element->get(isc::config::CONTROL_RESULT); ElementPtr text = error_element->get(isc::config::CONTROL_TEXT); if (!result || (result->getType() != Element::integer) || !text || (text->getType() != Element::string)) { return (false); } // Get the error message in the textual format. std::string error_string = text->stringValue(); // The position of the data element causing an error has the following // format: <filename>:<linenum>:<pos>. The <filename> has been specified // by a caller, so let's first check if this file name is present in the // error message. size_t pos = error_string.find(file_name); // If the file name is present, check that it is followed by the line // number and position within the line. if (pos != std::string::npos) { // Split the string starting at the beginning of the <filename>. It // should return a vector of strings. std::string sub = error_string.substr(pos); std::vector<std::string> split_pos; boost::split(split_pos, sub, boost::is_any_of(":"), boost::algorithm::token_compress_off); // There should be at least three elements: <filename>, <linenum> // and <pos>. There can be even more, because one error string may // contain more positions of data elements for multiple // configuration nesting levels. We want at least one position. if ((split_pos.size() >= 3) && (split_pos[0] == file_name) && (!split_pos[1].empty()) && !(split_pos[2].empty())) { // Make sure that the line number comprises only digits. for (int i = 0; i < split_pos[1].size(); ++i) { if (!isdigit(split_pos[1][i])) { return (false); } } // Go over digits of the position within the line. int i = 0; while (isdigit(split_pos[2][i])) { ++i; } // Make sure that there has been at least one digit and that the // position is followed by the paren. if ((i == 0) || (split_pos[2][i] != ')')) { return (false); } // All checks passed. return (true); } } } return (false); } } } }
37.611111
80
0.570162
telekom
ca33067d758bb649588693b6048e4b820f51f274
201
hpp
C++
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2019-04-09T13:03:11.000Z
2021-01-27T04:58:29.000Z
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
2
2017-02-06T03:48:45.000Z
2020-08-31T01:30:10.000Z
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2020-06-28T08:19:53.000Z
2020-06-28T16:30:19.000Z
#pragma once #include "KEngine/Interfaces/ISystem.hpp" namespace pf { /// <summary> /// /// </summary> class EventFeedbackSystem : public ke::ISystem { public: }; }
12.5625
50
0.567164
yxbh